QueryTest.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Database;
  16. use Cake\Core\Configure;
  17. use Cake\Database\Expression\IdentifierExpression;
  18. use Cake\Database\Query;
  19. use Cake\Datasource\ConnectionManager;
  20. use Cake\TestSuite\TestCase;
  21. /**
  22. * Tests Query class
  23. *
  24. */
  25. class QueryTest extends TestCase {
  26. public $fixtures = ['core.article', 'core.author', 'core.comment'];
  27. const ARTICLE_COUNT = 3;
  28. const AUTHOR_COUNT = 4;
  29. const COMMENT_COUNT = 6;
  30. public function setUp() {
  31. parent::setUp();
  32. $this->connection = ConnectionManager::get('test');
  33. $this->autoQuote = $this->connection->driver()->autoQuoting();
  34. }
  35. public function tearDown() {
  36. parent::tearDown();
  37. $this->connection->driver()->autoQuoting($this->autoQuote);
  38. unset($this->connection);
  39. }
  40. /**
  41. * Queries need a default type to prevent fatal errors
  42. * when an uninitialized query has its sql() method called.
  43. *
  44. * @return void
  45. */
  46. public function testDefaultType() {
  47. $query = new Query($this->connection);
  48. $this->assertEquals('', $query->sql());
  49. $this->assertEquals('select', $query->type());
  50. }
  51. /**
  52. * Tests that it is possible to obtain expression results from a query
  53. *
  54. * @return void
  55. */
  56. public function testSelectFieldsOnly() {
  57. $this->connection->driver()->autoQuoting(false);
  58. $query = new Query($this->connection);
  59. $result = $query->select('1 + 1')->execute();
  60. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  61. $this->assertEquals([2], $result->fetch());
  62. //This new field should be appended
  63. $result = $query->select(array('1 + 3'))->execute();
  64. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  65. $this->assertEquals([2, 4], $result->fetch());
  66. //This should now overwrite all previous fields
  67. $result = $query->select(array('1 + 2', '1 + 5'), true)->execute();
  68. $this->assertEquals([3, 6], $result->fetch());
  69. }
  70. /**
  71. * Tests that it is possible to pass a closure as fields in select()
  72. *
  73. * @return void
  74. */
  75. public function testSelectClosure() {
  76. $this->connection->driver()->autoQuoting(false);
  77. $query = new Query($this->connection);
  78. $result = $query->select(function($q) use ($query) {
  79. $this->assertSame($query, $q);
  80. return ['1 + 2', '1 + 5'];
  81. })->execute();
  82. $this->assertEquals([3, 6], $result->fetch());
  83. }
  84. /**
  85. * Tests it is possible to select fields from tables with no conditions
  86. *
  87. * @return void
  88. */
  89. public function testSelectFieldsFromTable() {
  90. $query = new Query($this->connection);
  91. $result = $query->select(array('body', 'author_id'))->from('articles')->execute();
  92. $this->assertEquals(array('body' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  93. $this->assertEquals(array('body' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  94. //Append more tables to next execution
  95. $result = $query->select('name')->from(array('authors'))->order(['name' => 'desc', 'articles.id' => 'asc'])->execute();
  96. $this->assertEquals(array('body' => 'First Article Body', 'author_id' => 1, 'name' => 'nate'), $result->fetch('assoc'));
  97. $this->assertEquals(array('body' => 'Second Article Body', 'author_id' => 3, 'name' => 'nate'), $result->fetch('assoc'));
  98. $this->assertEquals(array('body' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'), $result->fetch('assoc'));
  99. // Overwrite tables and only fetch from authors
  100. $result = $query->select('name', true)->from('authors', true)->order(['name' => 'desc'], true)->execute();
  101. $this->assertEquals(array('nate'), $result->fetch());
  102. $this->assertEquals(array('mariano'), $result->fetch());
  103. $this->assertCount(4, $result);
  104. }
  105. /**
  106. * Tests it is possible to select aliased fields
  107. *
  108. * @return void
  109. */
  110. public function testSelectAliasedFieldsFromTable() {
  111. $query = new Query($this->connection);
  112. $result = $query->select(['text' => 'body', 'author_id'])->from('articles')->execute();
  113. $this->assertEquals(array('text' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  114. $this->assertEquals(array('text' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  115. $query = new Query($this->connection);
  116. $result = $query->select(['text' => 'body', 'author' => 'author_id'])->from('articles')->execute();
  117. $this->assertEquals(array('text' => 'First Article Body', 'author' => 1), $result->fetch('assoc'));
  118. $this->assertEquals(array('text' => 'Second Article Body', 'author' => 3), $result->fetch('assoc'));
  119. $query = new Query($this->connection);
  120. $query->select(['text' => 'body'])->select(['author_id', 'foo' => 'body']);
  121. $result = $query->from('articles')->execute();
  122. $this->assertEquals(array('foo' => 'First Article Body', 'text' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  123. $this->assertEquals(array('foo' => 'Second Article Body', 'text' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  124. $query = new Query($this->connection);
  125. $exp = $query->newExpr('1 + 1');
  126. $comp = $query->newExpr(['author_id +' => 2]);
  127. $result = $query->select(['text' => 'body', 'two' => $exp, 'three' => $comp])
  128. ->from('articles')->execute();
  129. $this->assertEquals(array('text' => 'First Article Body', 'two' => 2, 'three' => 3), $result->fetch('assoc'));
  130. $this->assertEquals(array('text' => 'Second Article Body', 'two' => 2, 'three' => 5), $result->fetch('assoc'));
  131. }
  132. /**
  133. * Tests that tables can also be aliased and referenced in the select clause using such alias
  134. *
  135. * @return void
  136. */
  137. public function testSelectAliasedTables() {
  138. $query = new Query($this->connection);
  139. $result = $query->select(['text' => 'a.body', 'a.author_id'])
  140. ->from(['a' => 'articles'])->execute();
  141. $this->assertEquals(['text' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
  142. $this->assertEquals(['text' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
  143. $result = $query->select(['name' => 'b.name'])->from(['b' => 'authors'])
  144. ->order(['text' => 'desc', 'name' => 'desc'])
  145. ->execute();
  146. $this->assertEquals(
  147. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'],
  148. $result->fetch('assoc')
  149. );
  150. $this->assertEquals(
  151. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'mariano'],
  152. $result->fetch('assoc')
  153. );
  154. }
  155. /**
  156. * Tests it is possible to add joins to a select query
  157. *
  158. * @return void
  159. */
  160. public function testSelectWithJoins() {
  161. $query = new Query($this->connection);
  162. $result = $query
  163. ->select(['title', 'name'])
  164. ->from('articles')
  165. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  166. ->order(['title' => 'asc'])
  167. ->execute();
  168. $this->assertCount(3, $result);
  169. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  170. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  171. $result = $query->join('authors', [], true)->execute();
  172. $this->assertCount(12, $result, 'Cross join results in 12 records');
  173. $result = $query->join([
  174. ['table' => 'authors', 'type' => 'INNER', 'conditions' => 'author_id = authors.id']
  175. ], [], true)->execute();
  176. $this->assertCount(3, $result);
  177. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  178. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  179. }
  180. /**
  181. * Tests it is possible to add joins to a select query using array or expression as conditions
  182. *
  183. * @return void
  184. */
  185. public function testSelectWithJoinsConditions() {
  186. $query = new Query($this->connection);
  187. $result = $query
  188. ->select(['title', 'name'])
  189. ->from('articles')
  190. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => ['author_id = a.id']])
  191. ->order(['title' => 'asc'])
  192. ->execute();
  193. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  194. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  195. $query = new Query($this->connection);
  196. $conditions = $query->newExpr('author_id = a.id');
  197. $result = $query
  198. ->select(['title', 'name'])
  199. ->from('articles')
  200. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $conditions])
  201. ->order(['title' => 'asc'])
  202. ->execute();
  203. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  204. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  205. $query = new Query($this->connection);
  206. $time = new \DateTime('2007-03-18 10:50:00');
  207. $types = ['created' => 'datetime'];
  208. $result = $query
  209. ->select(['title', 'comment' => 'c.comment'])
  210. ->from('articles')
  211. ->join(['table' => 'comments', 'alias' => 'c', 'conditions' => ['created <=' => $time]], $types)
  212. ->execute();
  213. $this->assertEquals(['title' => 'First Article', 'comment' => 'First Comment for First Article'], $result->fetch('assoc'));
  214. }
  215. /**
  216. * Tests that joins can be aliased using array keys
  217. *
  218. * @return void
  219. */
  220. public function testSelectAliasedJoins() {
  221. $query = new Query($this->connection);
  222. $result = $query
  223. ->select(['title', 'name'])
  224. ->from('articles')
  225. ->join(['a' => 'authors'])
  226. ->order(['name' => 'desc', 'articles.id' => 'asc'])
  227. ->execute();
  228. $this->assertEquals(array('title' => 'First Article', 'name' => 'nate'), $result->fetch('assoc'));
  229. $this->assertEquals(array('title' => 'Second Article', 'name' => 'nate'), $result->fetch('assoc'));
  230. $query = new Query($this->connection);
  231. $conditions = $query->newExpr('author_id = a.id');
  232. $result = $query
  233. ->select(['title', 'name'])
  234. ->from('articles')
  235. ->join(['a' => ['table' => 'authors', 'conditions' => $conditions]])
  236. ->order(['title' => 'asc'])
  237. ->execute();
  238. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  239. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  240. $query = new Query($this->connection);
  241. $time = new \DateTime('2007-03-18 10:45:23');
  242. $types = ['created' => 'datetime'];
  243. $result = $query
  244. ->select(['title', 'name' => 'c.comment'])
  245. ->from('articles')
  246. ->join(['c' => ['table' => 'comments', 'conditions' => ['created' => $time]]], $types)
  247. ->execute();
  248. $this->assertEquals(array('title' => 'First Article', 'name' => 'First Comment for First Article'), $result->fetch('assoc'));
  249. }
  250. /**
  251. * Tests the leftJoin method
  252. *
  253. * @return void
  254. */
  255. public function testSelectLeftJoin() {
  256. $query = new Query($this->connection);
  257. $time = new \DateTime('2007-03-18 10:45:23');
  258. $types = ['created' => 'datetime'];
  259. $result = $query
  260. ->select(['title', 'name' => 'c.comment'])
  261. ->from('articles')
  262. ->leftJoin(['c' => 'comments'], ['created <' => $time], $types)
  263. ->execute();
  264. $this->assertEquals(array('title' => 'First Article', 'name' => null), $result->fetch('assoc'));
  265. $query = new Query($this->connection);
  266. $result = $query
  267. ->select(['title', 'name' => 'c.comment'])
  268. ->from('articles')
  269. ->leftJoin(['c' => 'comments'], ['created >' => $time], $types)
  270. ->execute();
  271. $this->assertEquals(
  272. ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
  273. $result->fetch('assoc')
  274. );
  275. }
  276. /**
  277. * Tests the innerJoin method
  278. *
  279. * @return void
  280. */
  281. public function testSelectInnerJoin() {
  282. $query = new Query($this->connection);
  283. $time = new \DateTime('2007-03-18 10:45:23');
  284. $types = ['created' => 'datetime'];
  285. $result = $query
  286. ->select(['title', 'name' => 'c.comment'])
  287. ->from('articles')
  288. ->innerJoin(['c' => 'comments'], ['created <' => $time], $types)
  289. ->execute();
  290. $this->assertCount(0, $result->fetchAll());
  291. $query = new Query($this->connection);
  292. $result = $query
  293. ->select(['title', 'name' => 'c.comment'])
  294. ->from('articles')
  295. ->leftJoin(['c' => 'comments'], ['created >' => $time], $types)
  296. ->execute();
  297. $this->assertEquals(
  298. ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
  299. $result->fetch('assoc')
  300. );
  301. }
  302. /**
  303. * Tests the rightJoin method
  304. *
  305. * @return void
  306. */
  307. public function testSelectRightJoin() {
  308. $this->skipIf(
  309. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlite,
  310. 'SQLite does not support RIGHT joins'
  311. );
  312. $query = new Query($this->connection);
  313. $time = new \DateTime('2007-03-18 10:45:23');
  314. $types = ['created' => 'datetime'];
  315. $result = $query
  316. ->select(['title', 'name' => 'c.comment'])
  317. ->from('articles')
  318. ->rightJoin(['c' => 'comments'], ['created <' => $time], $types)
  319. ->execute();
  320. $this->assertCount(6, $result);
  321. $this->assertEquals(
  322. ['title' => null, 'name' => 'First Comment for First Article'],
  323. $result->fetch('assoc')
  324. );
  325. }
  326. /**
  327. * Tests that it is possible to pass a callable as conditions for a join
  328. *
  329. * @return void
  330. */
  331. public function testSelectJoinWithCallback() {
  332. $query = new Query($this->connection);
  333. $types = ['created' => 'datetime'];
  334. $result = $query
  335. ->select(['title', 'name' => 'c.comment'])
  336. ->from('articles')
  337. ->innerJoin(['c' => 'comments'], function($exp, $q) use ($query, $types) {
  338. $this->assertSame($q, $query);
  339. $exp->add(['created <' => new \DateTime('2007-03-18 10:45:23')], $types);
  340. return $exp;
  341. })
  342. ->execute();
  343. $this->assertCount(0, $result->fetchAll());
  344. $query = new Query($this->connection);
  345. $types = ['created' => 'datetime'];
  346. $result = $query
  347. ->select(['title', 'name' => 'comments.comment'])
  348. ->from('articles')
  349. ->innerJoin('comments', function($exp, $q) use ($query, $types) {
  350. $this->assertSame($q, $query);
  351. $exp->add(['created >' => new \DateTime('2007-03-18 10:45:23')], $types);
  352. return $exp;
  353. })
  354. ->execute();
  355. $this->assertEquals(
  356. ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
  357. $result->fetch('assoc')
  358. );
  359. }
  360. /**
  361. * Tests it is possible to filter a query by using simple AND joined conditions
  362. *
  363. * @return void
  364. */
  365. public function testSelectSimpleWhere() {
  366. $query = new Query($this->connection);
  367. $result = $query
  368. ->select(['title'])
  369. ->from('articles')
  370. ->where(['id' => 1, 'title' => 'First Article'])
  371. ->execute();
  372. $this->assertCount(1, $result);
  373. $query = new Query($this->connection);
  374. $result = $query
  375. ->select(['title'])
  376. ->from('articles')
  377. ->where(['id' => 100], ['id' => 'integer'])
  378. ->execute();
  379. $this->assertCount(0, $result);
  380. }
  381. /**
  382. * Tests using where conditions with operators and scalar values works
  383. *
  384. * @return void
  385. */
  386. public function testSelectWhereOperators() {
  387. $query = new Query($this->connection);
  388. $result = $query
  389. ->select(['title'])
  390. ->from('articles')
  391. ->where(['id >' => 1])
  392. ->execute();
  393. $this->assertCount(2, $result);
  394. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  395. $query = new Query($this->connection);
  396. $result = $query
  397. ->select(['title'])
  398. ->from('articles')
  399. ->where(['id <' => 2])
  400. ->execute();
  401. $this->assertCount(1, $result);
  402. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  403. $query = new Query($this->connection);
  404. $result = $query
  405. ->select(['title'])
  406. ->from('articles')
  407. ->where(['id <=' => 2])
  408. ->execute();
  409. $this->assertCount(2, $result);
  410. $query = new Query($this->connection);
  411. $result = $query
  412. ->select(['title'])
  413. ->from('articles')
  414. ->where(['id >=' => 1])
  415. ->execute();
  416. $this->assertCount(3, $result);
  417. $query = new Query($this->connection);
  418. $result = $query
  419. ->select(['title'])
  420. ->from('articles')
  421. ->where(['id <=' => 1])
  422. ->execute();
  423. $this->assertCount(1, $result);
  424. $query = new Query($this->connection);
  425. $result = $query
  426. ->select(['title'])
  427. ->from('articles')
  428. ->where(['id !=' => 2])
  429. ->execute();
  430. $this->assertCount(2, $result);
  431. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  432. $query = new Query($this->connection);
  433. $result = $query
  434. ->select(['title'])
  435. ->from('articles')
  436. ->where(['title LIKE' => 'First Article'])
  437. ->execute();
  438. $this->assertCount(1, $result);
  439. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  440. $query = new Query($this->connection);
  441. $result = $query
  442. ->select(['title'])
  443. ->from('articles')
  444. ->where(['title like' => '%Article%'])
  445. ->execute();
  446. $this->assertCount(3, $result);
  447. $query = new Query($this->connection);
  448. $result = $query
  449. ->select(['title'])
  450. ->from('articles')
  451. ->where(['title not like' => '%Article%'])
  452. ->execute();
  453. $this->assertCount(0, $result);
  454. }
  455. /**
  456. * Tests selecting with conditions and specifying types for those
  457. *
  458. * @return void
  459. */
  460. public function testSelectWhereTypes() {
  461. $query = new Query($this->connection);
  462. $result = $query
  463. ->select(['id'])
  464. ->from('comments')
  465. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  466. ->execute();
  467. $this->assertCount(1, $result);
  468. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  469. $query = new Query($this->connection);
  470. $result = $query
  471. ->select(['id'])
  472. ->from('comments')
  473. ->where(['created >' => new \DateTime('2007-03-18 10:46:00')], ['created' => 'datetime'])
  474. ->execute();
  475. $this->assertCount(5, $result);
  476. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  477. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  478. $query = new Query($this->connection);
  479. $result = $query
  480. ->select(['id'])
  481. ->from('comments')
  482. ->where(
  483. [
  484. 'created >' => new \DateTime('2007-03-18 10:40:00'),
  485. 'created <' => new \DateTime('2007-03-18 10:46:00')
  486. ],
  487. ['created' => 'datetime']
  488. )
  489. ->execute();
  490. $this->assertCount(1, $result);
  491. $this->assertEquals(array('id' => 1), $result->fetch('assoc'));
  492. $query = new Query($this->connection);
  493. $result = $query
  494. ->select(['id'])
  495. ->from('comments')
  496. ->where(
  497. [
  498. 'id' => '3something-crazy',
  499. 'created <' => new \DateTime('2013-01-01 12:00')
  500. ],
  501. ['created' => 'datetime', 'id' => 'integer']
  502. )
  503. ->execute();
  504. $this->assertCount(1, $result);
  505. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  506. $query = new Query($this->connection);
  507. $result = $query
  508. ->select(['id'])
  509. ->from('comments')
  510. ->where(
  511. [
  512. 'id' => '1something-crazy',
  513. 'created <' => new \DateTime('2013-01-01 12:00')
  514. ],
  515. ['created' => 'datetime', 'id' => 'float']
  516. )
  517. ->execute();
  518. $this->assertCount(1, $result);
  519. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  520. }
  521. /**
  522. * Tests that passing an array type to any where condition will replace
  523. * the passed array accordingly as a proper IN condition
  524. *
  525. * @return void
  526. */
  527. public function testSelectWhereArrayType() {
  528. $query = new Query($this->connection);
  529. $result = $query
  530. ->select(['id'])
  531. ->from('comments')
  532. ->where(['id' => ['1', '3']], ['id' => 'integer[]'])
  533. ->execute();
  534. $this->assertCount(2, $result);
  535. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  536. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  537. }
  538. /**
  539. * Tests that passing an empty array type to any where condition will not
  540. * result in an error, but in an empty result set
  541. *
  542. * @return void
  543. */
  544. public function testSelectWhereArrayTypeEmpty() {
  545. $query = new Query($this->connection);
  546. $result = $query
  547. ->select(['id'])
  548. ->from('comments')
  549. ->where(['id' => []], ['id' => 'integer[]'])
  550. ->execute();
  551. $this->assertCount(0, $result);
  552. }
  553. /**
  554. * Tests that Query::orWhere() can be used to concatenate conditions with OR
  555. *
  556. * @return void
  557. */
  558. public function testSelectOrWhere() {
  559. $query = new Query($this->connection);
  560. $result = $query
  561. ->select(['id'])
  562. ->from('comments')
  563. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  564. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  565. ->execute();
  566. $this->assertCount(2, $result);
  567. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  568. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  569. }
  570. /**
  571. * Tests that Query::andWhere() can be used to concatenate conditions with AND
  572. *
  573. * @return void
  574. */
  575. public function testSelectAndWhere() {
  576. $query = new Query($this->connection);
  577. $result = $query
  578. ->select(['id'])
  579. ->from('comments')
  580. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  581. ->andWhere(['id' => 1])
  582. ->execute();
  583. $this->assertCount(1, $result);
  584. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  585. $query = new Query($this->connection);
  586. $result = $query
  587. ->select(['id'])
  588. ->from('comments')
  589. ->where(['created' => new \DateTime('2007-03-18 10:50:55')], ['created' => 'datetime'])
  590. ->andWhere(['id' => 2])
  591. ->execute();
  592. $this->assertCount(0, $result);
  593. }
  594. /**
  595. * Tests that combining Query::andWhere() and Query::orWhere() produces
  596. * correct conditions nesting
  597. *
  598. * @return void
  599. */
  600. public function testSelectExpressionNesting() {
  601. $query = new Query($this->connection);
  602. $result = $query
  603. ->select(['id'])
  604. ->from('comments')
  605. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  606. ->orWhere(['id' => 2])
  607. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  608. ->execute();
  609. $this->assertCount(2, $result);
  610. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  611. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  612. $query = new Query($this->connection);
  613. $result = $query
  614. ->select(['id'])
  615. ->from('comments')
  616. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  617. ->orWhere(['id' => 2])
  618. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  619. ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
  620. ->execute();
  621. $this->assertCount(3, $result);
  622. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  623. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  624. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  625. }
  626. /**
  627. * Tests that Query::orWhere() can be used without calling where() before
  628. *
  629. * @return void
  630. */
  631. public function testSelectOrWhereNoPreviousCondition() {
  632. $query = new Query($this->connection);
  633. $result = $query
  634. ->select(['id'])
  635. ->from('comments')
  636. ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  637. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  638. ->execute();
  639. $this->assertCount(2, $result);
  640. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  641. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  642. }
  643. /**
  644. * Tests that Query::andWhere() can be used without calling where() before
  645. *
  646. * @return void
  647. */
  648. public function testSelectAndWhereNoPreviousCondition() {
  649. $query = new Query($this->connection);
  650. $result = $query
  651. ->select(['id'])
  652. ->from('comments')
  653. ->andWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  654. ->andWhere(['id' => 1])
  655. ->execute();
  656. $this->assertCount(1, $result);
  657. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  658. }
  659. /**
  660. * Tests that it is possible to pass a closure to where() to build a set of
  661. * conditions and return the expression to be used
  662. *
  663. * @return void
  664. */
  665. public function testSelectWhereUsingClosure() {
  666. $query = new Query($this->connection);
  667. $result = $query
  668. ->select(['id'])
  669. ->from('comments')
  670. ->where(function($exp) {
  671. return $exp->eq('id', 1);
  672. })
  673. ->execute();
  674. $this->assertCount(1, $result);
  675. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  676. $query = new Query($this->connection);
  677. $result = $query
  678. ->select(['id'])
  679. ->from('comments')
  680. ->where(function($exp) {
  681. return $exp
  682. ->eq('id', 1)
  683. ->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  684. })
  685. ->execute();
  686. $this->assertCount(1, $result);
  687. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  688. $query = new Query($this->connection);
  689. $result = $query
  690. ->select(['id'])
  691. ->from('comments')
  692. ->where(function($exp) {
  693. return $exp
  694. ->eq('id', 1)
  695. ->eq('created', new \DateTime('2021-12-30 15:00'), 'datetime');
  696. })
  697. ->execute();
  698. $this->assertCount(0, $result);
  699. }
  700. /**
  701. * Tests generating tuples in the values side containing closure expressions
  702. *
  703. * @return void
  704. */
  705. public function testTupleWithClosureExpression() {
  706. $query = new Query($this->connection);
  707. $query->select(['id'])
  708. ->from('comments')
  709. ->where([
  710. 'OR' => [
  711. 'id' => 1,
  712. function($exp) {
  713. return $exp->eq('id', 2);
  714. }
  715. ]
  716. ]);
  717. $result = $query->sql();
  718. $this->assertQuotedQuery(
  719. 'SELECT <id> FROM <comments> WHERE \(<id> = :c0 OR <id> = :c1\)',
  720. $result,
  721. true
  722. );
  723. }
  724. /**
  725. * Tests that it is possible to pass a closure to andWhere() to build a set of
  726. * conditions and return the expression to be used
  727. *
  728. * @return void
  729. */
  730. public function testSelectAndWhereUsingClosure() {
  731. $query = new Query($this->connection);
  732. $result = $query
  733. ->select(['id'])
  734. ->from('comments')
  735. ->where(['id' => '1'])
  736. ->andWhere(function($exp) {
  737. return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  738. })
  739. ->execute();
  740. $this->assertCount(1, $result);
  741. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  742. $query = new Query($this->connection);
  743. $result = $query
  744. ->select(['id'])
  745. ->from('comments')
  746. ->where(['id' => '1'])
  747. ->andWhere(function($exp) {
  748. return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime');
  749. })
  750. ->execute();
  751. $this->assertCount(0, $result);
  752. }
  753. /**
  754. * Tests that it is possible to pass a closure to orWhere() to build a set of
  755. * conditions and return the expression to be used
  756. *
  757. * @return void
  758. */
  759. public function testSelectOrWhereUsingClosure() {
  760. $query = new Query($this->connection);
  761. $result = $query
  762. ->select(['id'])
  763. ->from('comments')
  764. ->where(['id' => '1'])
  765. ->orWhere(function($exp) {
  766. return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
  767. })
  768. ->execute();
  769. $this->assertCount(2, $result);
  770. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  771. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  772. $query = new Query($this->connection);
  773. $result = $query
  774. ->select(['id'])
  775. ->from('comments')
  776. ->where(['id' => '1'])
  777. ->orWhere(function($exp) {
  778. return $exp
  779. ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
  780. ->eq('id', 3);
  781. })
  782. ->execute();
  783. $this->assertCount(1, $result);
  784. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  785. }
  786. /**
  787. * Tests that expression objects can be used as the field in a comparison
  788. * and the values will be bound correctly to the query
  789. *
  790. * @return void
  791. */
  792. public function testSelectWhereUsingExpressionInField() {
  793. $query = new Query($this->connection);
  794. $result = $query
  795. ->select(['id'])
  796. ->from('comments')
  797. ->where(function($exp) {
  798. $field = clone $exp;
  799. $field->add('SELECT min(id) FROM comments');
  800. return $exp
  801. ->gt($field, 100, 'integer');
  802. });
  803. debug($result->sql());
  804. $rsult = $result->execute();
  805. $this->assertCount(0, $result);
  806. }
  807. /**
  808. * Tests using where conditions with operator methods
  809. *
  810. * @return void
  811. */
  812. public function testSelectWhereOperatorMethods() {
  813. $query = new Query($this->connection);
  814. $result = $query
  815. ->select(['title'])
  816. ->from('articles')
  817. ->where(function($exp) {
  818. return $exp->gt('id', 1);
  819. })
  820. ->execute();
  821. $this->assertCount(2, $result);
  822. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  823. $query = new Query($this->connection);
  824. $result = $query->select(['title'])
  825. ->from('articles')
  826. ->where(function($exp) {
  827. return $exp->lt('id', 2);
  828. })
  829. ->execute();
  830. $this->assertCount(1, $result);
  831. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  832. $query = new Query($this->connection);
  833. $result = $query->select(['title'])
  834. ->from('articles')
  835. ->where(function($exp) {
  836. return $exp->lte('id', 2);
  837. })
  838. ->execute();
  839. $this->assertCount(2, $result);
  840. $query = new Query($this->connection);
  841. $result = $query
  842. ->select(['title'])
  843. ->from('articles')
  844. ->where(function($exp) {
  845. return $exp->gte('id', 1);
  846. })
  847. ->execute();
  848. $this->assertCount(3, $result);
  849. $query = new Query($this->connection);
  850. $result = $query
  851. ->select(['title'])
  852. ->from('articles')
  853. ->where(function($exp) {
  854. return $exp->lte('id', 1);
  855. })
  856. ->execute();
  857. $this->assertCount(1, $result);
  858. $query = new Query($this->connection);
  859. $result = $query
  860. ->select(['title'])
  861. ->from('articles')
  862. ->where(function($exp) {
  863. return $exp->notEq('id', 2);
  864. })
  865. ->execute();
  866. $this->assertCount(2, $result);
  867. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  868. $query = new Query($this->connection);
  869. $result = $query
  870. ->select(['title'])
  871. ->from('articles')
  872. ->where(function($exp) {
  873. return $exp->like('title', 'First Article');
  874. })
  875. ->execute();
  876. $this->assertCount(1, $result);
  877. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  878. $query = new Query($this->connection);
  879. $result = $query
  880. ->select(['title'])
  881. ->from('articles')
  882. ->where(function($exp) {
  883. return $exp->like('title', '%Article%');
  884. })
  885. ->execute();
  886. $this->assertCount(3, $result);
  887. $query = new Query($this->connection);
  888. $result = $query
  889. ->select(['title'])
  890. ->from('articles')
  891. ->where(function($exp) {
  892. return $exp->notLike('title', '%Article%');
  893. })
  894. ->execute();
  895. $this->assertCount(0, $result);
  896. $query = new Query($this->connection);
  897. $result = $query
  898. ->select(['id'])
  899. ->from('comments')
  900. ->where(function($exp) {
  901. return $exp->isNull('published');
  902. })
  903. ->execute();
  904. $this->assertCount(0, $result);
  905. $query = new Query($this->connection);
  906. $result = $query
  907. ->select(['id'])
  908. ->from('comments')
  909. ->where(function($exp) {
  910. return $exp->isNotNull('published');
  911. })
  912. ->execute();
  913. $this->assertCount(6, $result);
  914. $query = new Query($this->connection);
  915. $result = $query
  916. ->select(['id'])
  917. ->from('comments')
  918. ->where(function($exp) {
  919. return $exp->in('published', ['Y', 'N']);
  920. })
  921. ->execute();
  922. $this->assertCount(6, $result);
  923. $query = new Query($this->connection);
  924. $result = $query
  925. ->select(['id'])
  926. ->from('comments')
  927. ->where(function($exp) {
  928. return $exp->in(
  929. 'created',
  930. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  931. 'datetime'
  932. );
  933. })
  934. ->execute();
  935. $this->assertCount(2, $result);
  936. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  937. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  938. $query = new Query($this->connection);
  939. $result = $query
  940. ->select(['id'])
  941. ->from('comments')
  942. ->where(function($exp) {
  943. return $exp->notIn(
  944. 'created',
  945. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  946. 'datetime'
  947. );
  948. })
  949. ->execute();
  950. $this->assertCount(4, $result);
  951. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  952. }
  953. /**
  954. * Tests that calling "in" and "notIn" will cast the passed values to an array
  955. *
  956. * @return void
  957. */
  958. public function testInValueCast() {
  959. $query = new Query($this->connection);
  960. $result = $query
  961. ->select(['id'])
  962. ->from('comments')
  963. ->where(function($exp) {
  964. return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
  965. })
  966. ->execute();
  967. $this->assertCount(1, $result);
  968. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  969. $query = new Query($this->connection);
  970. $result = $query
  971. ->select(['id'])
  972. ->from('comments')
  973. ->where(function($exp) {
  974. return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
  975. })
  976. ->execute();
  977. $this->assertCount(5, $result);
  978. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  979. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  980. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  981. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  982. $query = new Query($this->connection);
  983. $result = $query
  984. ->select(['id'])
  985. ->from('comments')
  986. ->where(function($exp, $q) {
  987. return $exp->in(
  988. 'created',
  989. $q->newExpr("'2007-03-18 10:45:23'"),
  990. 'datetime'
  991. );
  992. })
  993. ->execute();
  994. $this->assertCount(1, $result);
  995. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  996. $query = new Query($this->connection);
  997. $result = $query
  998. ->select(['id'])
  999. ->from('comments')
  1000. ->where(function($exp, $q) {
  1001. return $exp->notIn(
  1002. 'created',
  1003. $q->newExpr("'2007-03-18 10:45:23'"),
  1004. 'datetime'
  1005. );
  1006. })
  1007. ->execute();
  1008. $this->assertCount(5, $result);
  1009. }
  1010. /**
  1011. * Tests that calling "in" and "notIn" will cast the passed values to an array
  1012. *
  1013. * @return void
  1014. */
  1015. public function testInValueCast2() {
  1016. $query = new Query($this->connection);
  1017. $result = $query
  1018. ->select(['id'])
  1019. ->from('comments')
  1020. ->where(['created IN' => '2007-03-18 10:45:23'])
  1021. ->execute();
  1022. $this->assertCount(1, $result);
  1023. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1024. $query = new Query($this->connection);
  1025. $result = $query
  1026. ->select(['id'])
  1027. ->from('comments')
  1028. ->where(['created NOT IN' => '2007-03-18 10:45:23'])
  1029. ->execute();
  1030. $this->assertCount(5, $result);
  1031. }
  1032. /**
  1033. * Tests nesting query expressions both using arrays and closures
  1034. *
  1035. * @return void
  1036. */
  1037. public function testSelectExpressionComposition() {
  1038. $query = new Query($this->connection);
  1039. $result = $query
  1040. ->select(['id'])
  1041. ->from('comments')
  1042. ->where(function($exp) {
  1043. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  1044. return $exp->add($and);
  1045. })
  1046. ->execute();
  1047. $this->assertCount(1, $result);
  1048. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1049. $query = new Query($this->connection);
  1050. $result = $query
  1051. ->select(['id'])
  1052. ->from('comments')
  1053. ->where(function($exp) {
  1054. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  1055. return $exp->add($and);
  1056. })
  1057. ->execute();
  1058. $this->assertCount(0, $result);
  1059. $query = new Query($this->connection);
  1060. $result = $query
  1061. ->select(['id'])
  1062. ->from('comments')
  1063. ->where(function($exp) {
  1064. $and = $exp->and_(function($and) {
  1065. return $and->eq('id', 1)->gt('id', 0);
  1066. });
  1067. return $exp->add($and);
  1068. })
  1069. ->execute();
  1070. $this->assertCount(1, $result);
  1071. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1072. $query = new Query($this->connection);
  1073. $result = $query
  1074. ->select(['id'])
  1075. ->from('comments')
  1076. ->where(function($exp) {
  1077. $or = $exp->or_(['id' => 1]);
  1078. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  1079. return $or->add($and);
  1080. })
  1081. ->execute();
  1082. $this->assertCount(2, $result);
  1083. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1084. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1085. $query = new Query($this->connection);
  1086. $result = $query
  1087. ->select(['id'])
  1088. ->from('comments')
  1089. ->where(function($exp) {
  1090. $or = $exp->or_(function($or) {
  1091. return $or->eq('id', 1)->eq('id', 2);
  1092. });
  1093. return $or;
  1094. })
  1095. ->execute();
  1096. $this->assertCount(2, $result);
  1097. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1098. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1099. }
  1100. /**
  1101. * Tests that conditions can be nested with an unary operator using the array notation
  1102. * and the not() method
  1103. *
  1104. * @return void
  1105. */
  1106. public function testSelectWhereNot() {
  1107. $query = new Query($this->connection);
  1108. $result = $query
  1109. ->select(['id'])
  1110. ->from('comments')
  1111. ->where(function($exp) {
  1112. return $exp->not(
  1113. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  1114. );
  1115. })
  1116. ->execute();
  1117. $this->assertCount(5, $result);
  1118. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1119. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1120. $query = new Query($this->connection);
  1121. $result = $query
  1122. ->select(['id'])
  1123. ->from('comments')
  1124. ->where(function($exp) {
  1125. return $exp->not(
  1126. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  1127. );
  1128. })
  1129. ->execute();
  1130. $this->assertCount(6, $result);
  1131. $query = new Query($this->connection);
  1132. $result = $query
  1133. ->select(['id'])
  1134. ->from('articles')
  1135. ->where([
  1136. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  1137. ])
  1138. ->execute();
  1139. $this->assertCount(2, $result);
  1140. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1141. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1142. }
  1143. /**
  1144. * Tests order() method both with simple fields and expressions
  1145. *
  1146. * @return void
  1147. */
  1148. public function testSelectOrderBy() {
  1149. $query = new Query($this->connection);
  1150. $result = $query
  1151. ->select(['id'])
  1152. ->from('articles')
  1153. ->order(['id' => 'desc'])
  1154. ->execute();
  1155. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1156. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1157. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1158. $result = $query->order(['id' => 'asc'])->execute();
  1159. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1160. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1161. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1162. $result = $query->order(['title' => 'asc'])->execute();
  1163. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1164. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1165. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1166. $result = $query->order(['title' => 'asc'], true)->execute();
  1167. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1168. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1169. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1170. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1171. ->execute();
  1172. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1173. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1174. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1175. $expression = $query->newExpr(['(id + :offset) % 2']);
  1176. $result = $query
  1177. ->order([$expression, 'id' => 'desc'], true)
  1178. ->bind(':offset', 1, null)
  1179. ->execute();
  1180. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1181. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1182. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1183. $result = $query
  1184. ->order($expression, true)
  1185. ->order(['id' => 'asc'])
  1186. ->bind(':offset', 1, null)
  1187. ->execute();
  1188. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1189. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1190. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1191. }
  1192. /**
  1193. * Tests that group by fields can be passed similar to select fields
  1194. * and that it sends the correct query to the database
  1195. *
  1196. * @return void
  1197. */
  1198. public function testSelectGroup() {
  1199. $query = new Query($this->connection);
  1200. $result = $query
  1201. ->select(['total' => 'count(author_id)', 'author_id'])
  1202. ->from('articles')
  1203. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1204. ->group('author_id')
  1205. ->execute();
  1206. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1207. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1208. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1209. ->group(['name'], true)
  1210. ->order(['total' => 'asc'])
  1211. ->execute();
  1212. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1213. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1214. $result = $query->select(['articles.id'])
  1215. ->group(['articles.id'])
  1216. ->execute();
  1217. $this->assertCount(3, $result);
  1218. }
  1219. /**
  1220. * Tests that it is possible to select distinct rows
  1221. *
  1222. * @return void
  1223. */
  1224. public function testSelectDistinct() {
  1225. $query = new Query($this->connection);
  1226. $result = $query
  1227. ->select(['author_id'])
  1228. ->from(['a' => 'articles'])
  1229. ->execute();
  1230. $this->assertCount(3, $result);
  1231. $result = $query->distinct()->execute();
  1232. $this->assertCount(2, $result);
  1233. $result = $query->select(['id'])->distinct(false)->execute();
  1234. $this->assertCount(3, $result);
  1235. }
  1236. /**
  1237. * Tests that it is possible to select distinct rows, even filtering by one column
  1238. * this is testing that there is a specific implementation for DISTINCT ON
  1239. *
  1240. * @return void
  1241. */
  1242. public function testSelectDistinctON() {
  1243. $this->skipIf(
  1244. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  1245. 'Not implemented yet in SqlServer'
  1246. );
  1247. $query = new Query($this->connection);
  1248. $result = $query
  1249. ->select(['id', 'author_id'])
  1250. ->distinct(['author_id'])
  1251. ->from(['a' => 'articles'])
  1252. ->execute();
  1253. $this->assertCount(2, $result);
  1254. }
  1255. /**
  1256. * Test use of modifiers in the query
  1257. *
  1258. * Testing the generated SQL since the modifiers are usually different per driver
  1259. *
  1260. * @return void
  1261. */
  1262. public function testSelectModifiers() {
  1263. $query = new Query($this->connection);
  1264. $result = $query
  1265. ->select(['city', 'state', 'country'])
  1266. ->from(['addresses'])
  1267. ->modifier('DISTINCTROW');
  1268. $this->assertQuotedQuery(
  1269. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1270. $result->sql(),
  1271. true
  1272. );
  1273. $query = new Query($this->connection);
  1274. $result = $query
  1275. ->select(['city', 'state', 'country'])
  1276. ->from(['addresses'])
  1277. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1278. $this->assertQuotedQuery(
  1279. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1280. $result->sql(),
  1281. true
  1282. );
  1283. $query = new Query($this->connection);
  1284. $result = $query
  1285. ->select(['city', 'state', 'country'])
  1286. ->from(['addresses'])
  1287. ->modifier('DISTINCTROW')
  1288. ->modifier('SQL_NO_CACHE');
  1289. $this->assertQuotedQuery(
  1290. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1291. $result->sql(),
  1292. true
  1293. );
  1294. $query = new Query($this->connection);
  1295. $result = $query
  1296. ->select(['city', 'state', 'country'])
  1297. ->from(['addresses'])
  1298. ->modifier(['TOP 10']);
  1299. $this->assertQuotedQuery(
  1300. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1301. $result->sql(),
  1302. true
  1303. );
  1304. }
  1305. /**
  1306. * Tests that having() behaves pretty much the same as the where() method
  1307. *
  1308. * @return void
  1309. */
  1310. public function testSelectHaving() {
  1311. $query = new Query($this->connection);
  1312. $result = $query
  1313. ->select(['total' => 'count(author_id)', 'author_id'])
  1314. ->from('articles')
  1315. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1316. ->group('author_id')
  1317. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1318. ->execute();
  1319. $expected = [['total' => 1, 'author_id' => 3]];
  1320. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1321. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1322. ->execute();
  1323. $expected = [['total' => 2, 'author_id' => 1]];
  1324. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1325. $result = $query->having(function($e) {
  1326. return $e->add('count(author_id) = 1 + 1');
  1327. }, [], true)
  1328. ->execute();
  1329. $expected = [['total' => 2, 'author_id' => 1]];
  1330. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1331. }
  1332. /**
  1333. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1334. * in the having clause
  1335. *
  1336. * @return void
  1337. */
  1338. public function testSelectOrHaving() {
  1339. $query = new Query($this->connection);
  1340. $result = $query
  1341. ->select(['total' => 'count(author_id)', 'author_id'])
  1342. ->from('articles')
  1343. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1344. ->group('author_id')
  1345. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1346. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1347. ->execute();
  1348. $expected = [['total' => 1, 'author_id' => 3]];
  1349. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1350. $query = new Query($this->connection);
  1351. $result = $query
  1352. ->select(['total' => 'count(author_id)', 'author_id'])
  1353. ->from('articles')
  1354. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1355. ->group('author_id')
  1356. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1357. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1358. ->execute();
  1359. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1360. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1361. $query = new Query($this->connection);
  1362. $result = $query
  1363. ->select(['total' => 'count(author_id)', 'author_id'])
  1364. ->from('articles')
  1365. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1366. ->group('author_id')
  1367. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1368. ->orHaving(function($e) {
  1369. return $e->add('count(author_id) = 1 + 1');
  1370. })
  1371. ->execute();
  1372. $expected = [['total' => 2, 'author_id' => 1]];
  1373. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1374. }
  1375. /**
  1376. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1377. * in the having clause
  1378. *
  1379. * @return void
  1380. */
  1381. public function testSelectAndHaving() {
  1382. $query = new Query($this->connection);
  1383. $result = $query
  1384. ->select(['total' => 'count(author_id)', 'author_id'])
  1385. ->from('articles')
  1386. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1387. ->group('author_id')
  1388. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1389. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1390. ->execute();
  1391. $this->assertCount(0, $result);
  1392. $query = new Query($this->connection);
  1393. $result = $query
  1394. ->select(['total' => 'count(author_id)', 'author_id'])
  1395. ->from('articles')
  1396. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1397. ->group('author_id')
  1398. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1399. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1400. ->execute();
  1401. $expected = [['total' => 2, 'author_id' => 1]];
  1402. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1403. $query = new Query($this->connection);
  1404. $result = $query
  1405. ->select(['total' => 'count(author_id)', 'author_id'])
  1406. ->from('articles')
  1407. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1408. ->group('author_id')
  1409. ->andHaving(function($e) {
  1410. return $e->add('count(author_id) = 2 - 1');
  1411. })
  1412. ->execute();
  1413. $expected = [['total' => 1, 'author_id' => 3]];
  1414. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1415. }
  1416. /**
  1417. * Tests selecting rows using a limit clause
  1418. *
  1419. * @return void
  1420. */
  1421. public function testSelectLimit() {
  1422. $query = new Query($this->connection);
  1423. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1424. $this->assertCount(1, $result);
  1425. $query = new Query($this->connection);
  1426. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1427. $this->assertCount(2, $result);
  1428. }
  1429. /**
  1430. * Tests selecting rows combining a limit and offset clause
  1431. *
  1432. * @return void
  1433. */
  1434. public function testSelectOffset() {
  1435. $query = new Query($this->connection);
  1436. $result = $query->select('id')->from('comments')
  1437. ->limit(1)
  1438. ->offset(0)
  1439. ->order(['id' => 'ASC'])
  1440. ->execute();
  1441. $this->assertCount(1, $result);
  1442. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1443. $query = new Query($this->connection);
  1444. $result = $query->select('id')->from('comments')
  1445. ->limit(1)
  1446. ->offset(1)
  1447. ->execute();
  1448. $this->assertCount(1, $result);
  1449. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1450. $query = new Query($this->connection);
  1451. $result = $query->select('id')->from('comments')
  1452. ->limit(1)
  1453. ->offset(2)
  1454. ->execute();
  1455. $this->assertCount(1, $result);
  1456. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1457. $query = new Query($this->connection);
  1458. $result = $query->select('id')->from('articles')
  1459. ->order(['id' => 'DESC'])
  1460. ->limit(1)
  1461. ->offset(0)
  1462. ->execute();
  1463. $this->assertCount(1, $result);
  1464. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1465. $result = $query->limit(2)->offset(1)->execute();
  1466. $this->assertCount(2, $result);
  1467. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1468. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1469. }
  1470. /**
  1471. * Test selecting rows using the page() method.
  1472. *
  1473. * @return void
  1474. */
  1475. public function testSelectPage() {
  1476. $query = new Query($this->connection);
  1477. $result = $query->select('id')->from('comments')
  1478. ->limit(1)
  1479. ->page(1)
  1480. ->execute();
  1481. $this->assertCount(1, $result);
  1482. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1483. $query = new Query($this->connection);
  1484. $result = $query->select('id')->from('comments')
  1485. ->limit(1)
  1486. ->page(2)
  1487. ->execute();
  1488. $this->assertCount(1, $result);
  1489. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1490. $query = new Query($this->connection);
  1491. $query->select('id')->from('comments')->page(1);
  1492. $this->assertEquals(25, $query->clause('limit'));
  1493. $this->assertEquals(0, $query->clause('offset'));
  1494. $query->select('id')->from('comments')->page(2);
  1495. $this->assertEquals(25, $query->clause('limit'));
  1496. $this->assertEquals(25, $query->clause('offset'));
  1497. }
  1498. /**
  1499. * Tests that Query objects can be included inside the select clause
  1500. * and be used as a normal field, including binding any passed parameter
  1501. *
  1502. * @return void
  1503. */
  1504. public function testSubqueryInSelect() {
  1505. $query = new Query($this->connection);
  1506. $subquery = (new Query($this->connection))
  1507. ->select('name')
  1508. ->from(['b' => 'authors'])
  1509. ->where(['b.id = a.id']);
  1510. $result = $query
  1511. ->select(['id', 'name' => $subquery])
  1512. ->from(['a' => 'comments'])->execute();
  1513. $expected = [
  1514. ['id' => 1, 'name' => 'mariano'],
  1515. ['id' => 2, 'name' => 'nate'],
  1516. ['id' => 3, 'name' => 'larry'],
  1517. ['id' => 4, 'name' => 'garrett'],
  1518. ['id' => 5, 'name' => null],
  1519. ['id' => 6, 'name' => null],
  1520. ];
  1521. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1522. $query = new Query($this->connection);
  1523. $subquery = (new Query($this->connection))
  1524. ->select('name')
  1525. ->from(['b' => 'authors'])
  1526. ->where(['name' => 'mariano'], ['name' => 'string']);
  1527. $result = $query
  1528. ->select(['id', 'name' => $subquery])
  1529. ->from(['a' => 'articles'])->execute();
  1530. $expected = [
  1531. ['id' => 1, 'name' => 'mariano'],
  1532. ['id' => 2, 'name' => 'mariano'],
  1533. ['id' => 3, 'name' => 'mariano'],
  1534. ];
  1535. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1536. }
  1537. /**
  1538. * Tests that Query objects can be included inside the from clause
  1539. * and be used as a normal table, including binding any passed parameter
  1540. *
  1541. * @return void
  1542. */
  1543. public function testSuqueryInFrom() {
  1544. $query = new Query($this->connection);
  1545. $subquery = (new Query($this->connection))
  1546. ->select(['id', 'comment'])
  1547. ->from('comments')
  1548. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1549. $result = $query
  1550. ->select(['say' => 'comment'])
  1551. ->from(['b' => $subquery])
  1552. ->where(['id !=' => 3])
  1553. ->execute();
  1554. $expected = [
  1555. ['say' => 'Second Comment for First Article'],
  1556. ['say' => 'Fourth Comment for First Article'],
  1557. ['say' => 'First Comment for Second Article'],
  1558. ['say' => 'Second Comment for Second Article'],
  1559. ];
  1560. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1561. }
  1562. /**
  1563. * Tests that Query objects can be included inside the where clause
  1564. * and be used as a normal condition, including binding any passed parameter
  1565. *
  1566. * @return void
  1567. */
  1568. public function testSubqueryInWhere() {
  1569. $query = new Query($this->connection);
  1570. $subquery = (new Query($this->connection))
  1571. ->select(['id'])
  1572. ->from('authors')
  1573. ->where(['id' => 1]);
  1574. $result = $query
  1575. ->select(['name'])
  1576. ->from(['authors'])
  1577. ->where(['id !=' => $subquery])
  1578. ->execute();
  1579. $expected = [
  1580. ['name' => 'nate'],
  1581. ['name' => 'larry'],
  1582. ['name' => 'garrett'],
  1583. ];
  1584. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1585. $query = new Query($this->connection);
  1586. $subquery = (new Query($this->connection))
  1587. ->select(['id'])
  1588. ->from('comments')
  1589. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1590. $result = $query
  1591. ->select(['name'])
  1592. ->from(['authors'])
  1593. ->where(['id not in' => $subquery])
  1594. ->execute();
  1595. $expected = [
  1596. ['name' => 'mariano'],
  1597. ];
  1598. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1599. }
  1600. /**
  1601. * Tests that it is possible to use a subquery in a join clause
  1602. *
  1603. * @return void
  1604. */
  1605. public function testSubqueyInJoin() {
  1606. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1607. $query = new Query($this->connection);
  1608. $result = $query
  1609. ->select(['title', 'name'])
  1610. ->from('articles')
  1611. ->join(['b' => $subquery])
  1612. ->execute();
  1613. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1614. $subquery->where(['id' => 1]);
  1615. $result = $query->execute();
  1616. $this->assertCount(3, $result);
  1617. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1618. $result = $query->execute();
  1619. $this->assertCount(1, $result);
  1620. }
  1621. /**
  1622. * Tests that it is possible to one or multiple UNION statements in a query
  1623. *
  1624. * @return void
  1625. */
  1626. public function testUnion() {
  1627. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1628. $query = new Query($this->connection);
  1629. $result = $query->select(['id', 'comment'])
  1630. ->from(['c' => 'comments'])
  1631. ->union($union)
  1632. ->execute();
  1633. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1634. $rows = $result->fetchAll();
  1635. $union->select(['foo' => 'id', 'bar' => 'title']);
  1636. $union = (new Query($this->connection))
  1637. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1638. ->from(['b' => 'authors'])
  1639. ->where(['id ' => 1])
  1640. ->order(['id' => 'desc']);
  1641. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1642. $result = $query->execute();
  1643. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1644. $this->assertNotEquals($rows, $result->fetchAll());
  1645. $union = (new Query($this->connection))
  1646. ->select(['id', 'title'])
  1647. ->from(['c' => 'articles']);
  1648. $query->select(['id', 'comment'], true)->union($union, true);
  1649. $result = $query->execute();
  1650. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1651. $this->assertEquals($rows, $result->fetchAll());
  1652. }
  1653. /**
  1654. * Tests that UNION ALL can be built by setting the second param of union() to true
  1655. *
  1656. * @return void
  1657. */
  1658. public function testUnionAll() {
  1659. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1660. $query = new Query($this->connection);
  1661. $result = $query->select(['id', 'comment'])
  1662. ->from(['c' => 'comments'])
  1663. ->union($union)
  1664. ->execute();
  1665. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1666. $rows = $result->fetchAll();
  1667. $union->select(['foo' => 'id', 'bar' => 'title']);
  1668. $union = (new Query($this->connection))
  1669. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1670. ->from(['b' => 'authors'])
  1671. ->where(['id ' => 1])
  1672. ->order(['id' => 'desc']);
  1673. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1674. $result = $query->execute();
  1675. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1676. $this->assertNotEquals($rows, $result->fetchAll());
  1677. }
  1678. /**
  1679. * Tests stacking decorators for results and resetting the list of decorators
  1680. *
  1681. * @return void
  1682. */
  1683. public function testDecorateResults() {
  1684. $query = new Query($this->connection);
  1685. $result = $query
  1686. ->select(['id', 'title'])
  1687. ->from('articles')
  1688. ->order(['id' => 'ASC'])
  1689. ->decorateResults(function($row) {
  1690. $row['modified_id'] = $row['id'] + 1;
  1691. return $row;
  1692. })
  1693. ->execute();
  1694. while ($row = $result->fetch('assoc')) {
  1695. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1696. }
  1697. $result = $query->decorateResults(function($row) {
  1698. $row['modified_id']--;
  1699. return $row;
  1700. })->execute();
  1701. while ($row = $result->fetch('assoc')) {
  1702. $this->assertEquals($row['id'], $row['modified_id']);
  1703. }
  1704. $result = $query
  1705. ->decorateResults(function($row) {
  1706. $row['foo'] = 'bar';
  1707. return $row;
  1708. }, true)
  1709. ->execute();
  1710. while ($row = $result->fetch('assoc')) {
  1711. $this->assertEquals('bar', $row['foo']);
  1712. $this->assertArrayNotHasKey('modified_id', $row);
  1713. }
  1714. $results = $query->decorateResults(null, true)->execute();
  1715. while ($row = $result->fetch('assoc')) {
  1716. $this->assertArrayNotHasKey('foo', $row);
  1717. $this->assertArrayNotHasKey('modified_id', $row);
  1718. }
  1719. }
  1720. /**
  1721. * Test a basic delete using from()
  1722. *
  1723. * @return void
  1724. */
  1725. public function testDeleteWithFrom() {
  1726. $query = new Query($this->connection);
  1727. $query->delete()
  1728. ->from('authors')
  1729. ->where('1 = 1');
  1730. $result = $query->sql();
  1731. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1732. $result = $query->execute();
  1733. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1734. $this->assertCount(self::AUTHOR_COUNT, $result);
  1735. }
  1736. /**
  1737. * Test delete with from and alias.
  1738. *
  1739. * @return void
  1740. */
  1741. public function testDeleteWithAliasedFrom() {
  1742. $query = new Query($this->connection);
  1743. $query->delete()
  1744. ->from(['a ' => 'authors'])
  1745. ->where(['a.id !=' => 99]);
  1746. $result = $query->sql();
  1747. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, true);
  1748. $result = $query->execute();
  1749. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1750. $this->assertCount(self::AUTHOR_COUNT, $result);
  1751. }
  1752. /**
  1753. * Test a basic delete with no from() call.
  1754. *
  1755. * @return void
  1756. */
  1757. public function testDeleteNoFrom() {
  1758. $query = new Query($this->connection);
  1759. $query->delete('authors')
  1760. ->where('1 = 1');
  1761. $result = $query->sql();
  1762. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1763. $result = $query->execute();
  1764. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1765. $this->assertCount(self::AUTHOR_COUNT, $result);
  1766. }
  1767. /**
  1768. * Test setting select() & delete() modes.
  1769. *
  1770. * @return void
  1771. */
  1772. public function testSelectAndDeleteOnSameQuery() {
  1773. $query = new Query($this->connection);
  1774. $result = $query->select()
  1775. ->delete('authors')
  1776. ->where('1 = 1');
  1777. $result = $query->sql();
  1778. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1779. $this->assertContains(' WHERE 1 = 1', $result);
  1780. }
  1781. /**
  1782. * Test a simple update.
  1783. *
  1784. * @return void
  1785. */
  1786. public function testUpdateSimple() {
  1787. $query = new Query($this->connection);
  1788. $query->update('authors')
  1789. ->set('name', 'mark')
  1790. ->where(['id' => 1]);
  1791. $result = $query->sql();
  1792. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1793. $result = $query->execute();
  1794. $this->assertCount(1, $result);
  1795. }
  1796. /**
  1797. * Test update with multiple fields.
  1798. *
  1799. * @return void
  1800. */
  1801. public function testUpdateMultipleFields() {
  1802. $query = new Query($this->connection);
  1803. $query->update('articles')
  1804. ->set('title', 'mark', 'string')
  1805. ->set('body', 'some text', 'string')
  1806. ->where(['id' => 1]);
  1807. $result = $query->sql();
  1808. $this->assertQuotedQuery(
  1809. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1810. $result,
  1811. true
  1812. );
  1813. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1814. $result = $query->execute();
  1815. $this->assertCount(1, $result);
  1816. }
  1817. /**
  1818. * Test updating multiple fields with an array.
  1819. *
  1820. * @return void
  1821. */
  1822. public function testUpdateMultipleFieldsArray() {
  1823. $query = new Query($this->connection);
  1824. $query->update('articles')
  1825. ->set([
  1826. 'title' => 'mark',
  1827. 'body' => 'some text'
  1828. ], ['title' => 'string', 'body' => 'string'])
  1829. ->where(['id' => 1]);
  1830. $result = $query->sql();
  1831. $this->assertQuotedQuery(
  1832. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1833. $result,
  1834. true
  1835. );
  1836. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1837. $result = $query->execute();
  1838. $this->assertCount(1, $result);
  1839. }
  1840. /**
  1841. * Test updates with an expression.
  1842. *
  1843. * @return void
  1844. */
  1845. public function testUpdateWithExpression() {
  1846. $query = new Query($this->connection);
  1847. $expr = $query->newExpr('title = author_id');
  1848. $query->update('articles')
  1849. ->set($expr)
  1850. ->where(['id' => 1]);
  1851. $result = $query->sql();
  1852. $this->assertQuotedQuery(
  1853. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  1854. $result,
  1855. true
  1856. );
  1857. $result = $query->execute();
  1858. $this->assertCount(1, $result);
  1859. }
  1860. /**
  1861. * Test update with array fields and types.
  1862. *
  1863. * @return void
  1864. */
  1865. public function testUpdateArrayFields() {
  1866. $query = new Query($this->connection);
  1867. $date = new \DateTime;
  1868. $query->update('comments')
  1869. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  1870. ->where(['id' => 1]);
  1871. $result = $query->sql();
  1872. $this->assertQuotedQuery(
  1873. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  1874. $result,
  1875. true
  1876. );
  1877. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1878. $result = $query->execute();
  1879. $this->assertCount(1, $result);
  1880. $query = new Query($this->connection);
  1881. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  1882. $result = $result->fetchAll('assoc')[0]['created'];
  1883. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  1884. }
  1885. /**
  1886. * You cannot call values() before insert() it causes all sorts of pain.
  1887. *
  1888. * @expectedException \Cake\Error\Exception
  1889. * @return void
  1890. */
  1891. public function testInsertValuesBeforeInsertFailure() {
  1892. $query = new Query($this->connection);
  1893. $query->select('*')->values([
  1894. 'id' => 1,
  1895. 'title' => 'mark',
  1896. 'body' => 'test insert'
  1897. ]);
  1898. }
  1899. /**
  1900. * Inserting nothing should not generate an error.
  1901. *
  1902. * @expectedException RuntimeException
  1903. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  1904. * @return void
  1905. */
  1906. public function testInsertNothing() {
  1907. $query = new Query($this->connection);
  1908. $query->insert([]);
  1909. }
  1910. /**
  1911. * Test inserting a single row.
  1912. *
  1913. * @return void
  1914. */
  1915. public function testInsertSimple() {
  1916. $query = new Query($this->connection);
  1917. $query->insert(['title', 'body'])
  1918. ->into('articles')
  1919. ->values([
  1920. 'title' => 'mark',
  1921. 'body' => 'test insert'
  1922. ]);
  1923. $result = $query->sql();
  1924. $this->assertQuotedQuery(
  1925. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1926. 'VALUES \(\?, \?\)',
  1927. $result,
  1928. true
  1929. );
  1930. $result = $query->execute();
  1931. $this->assertCount(1, $result, '1 row should be inserted');
  1932. $expected = [
  1933. [
  1934. 'id' => 4,
  1935. 'author_id' => null,
  1936. 'title' => 'mark',
  1937. 'body' => 'test insert',
  1938. 'published' => 'N',
  1939. ]
  1940. ];
  1941. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  1942. }
  1943. /**
  1944. * Test an insert when not all the listed fields are provided.
  1945. * Columns should be matched up where possible.
  1946. *
  1947. * @return void
  1948. */
  1949. public function testInsertSparseRow() {
  1950. $query = new Query($this->connection);
  1951. $query->insert(['title', 'body'])
  1952. ->into('articles')
  1953. ->values([
  1954. 'title' => 'mark',
  1955. ]);
  1956. $result = $query->sql();
  1957. $this->assertQuotedQuery(
  1958. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1959. 'VALUES \(\?, \?\)',
  1960. $result,
  1961. true
  1962. );
  1963. $result = $query->execute();
  1964. $this->assertCount(1, $result, '1 row should be inserted');
  1965. $expected = [
  1966. [
  1967. 'id' => 4,
  1968. 'author_id' => null,
  1969. 'title' => 'mark',
  1970. 'body' => null,
  1971. 'published' => 'N',
  1972. ]
  1973. ];
  1974. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  1975. }
  1976. /**
  1977. * Test inserting multiple rows with sparse data.
  1978. *
  1979. * @return void
  1980. */
  1981. public function testInsertMultipleRowsSparse() {
  1982. $query = new Query($this->connection);
  1983. $query->insert(['title', 'body'])
  1984. ->into('articles')
  1985. ->values([
  1986. 'body' => 'test insert'
  1987. ])
  1988. ->values([
  1989. 'title' => 'jose',
  1990. ]);
  1991. $result = $query->execute();
  1992. $this->assertCount(2, $result, '2 rows should be inserted');
  1993. $expected = [
  1994. [
  1995. 'id' => 4,
  1996. 'author_id' => null,
  1997. 'title' => null,
  1998. 'body' => 'test insert',
  1999. 'published' => 'N',
  2000. ],
  2001. [
  2002. 'id' => 5,
  2003. 'author_id' => null,
  2004. 'title' => 'jose',
  2005. 'body' => null,
  2006. 'published' => 'N',
  2007. ],
  2008. ];
  2009. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2010. }
  2011. /**
  2012. * Test that INSERT INTO ... SELECT works.
  2013. *
  2014. * @return void
  2015. */
  2016. public function testInsertFromSelect() {
  2017. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2018. ->from('authors')
  2019. ->where(['id' => 1]);
  2020. $query = new Query($this->connection);
  2021. $query->insert(
  2022. ['title', 'body', 'author_id'],
  2023. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2024. )
  2025. ->into('articles')
  2026. ->values($select);
  2027. $result = $query->sql();
  2028. $this->assertQuotedQuery(
  2029. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) SELECT',
  2030. $result,
  2031. true
  2032. );
  2033. $this->assertQuotedQuery(
  2034. 'SELECT <name>, \'some text\', 99 FROM <authors>', $result, true);
  2035. $result = $query->execute();
  2036. $this->assertCount(1, $result);
  2037. $result = (new Query($this->connection))->select('*')
  2038. ->from('articles')
  2039. ->where(['author_id' => 99])
  2040. ->execute();
  2041. $this->assertCount(1, $result);
  2042. $expected = [
  2043. 'id' => 4,
  2044. 'title' => 'mariano',
  2045. 'body' => 'some text',
  2046. 'author_id' => 99,
  2047. 'published' => 'N',
  2048. ];
  2049. $this->assertEquals($expected, $result->fetch('assoc'));
  2050. }
  2051. /**
  2052. * Test that an exception is raised when mixing query + array types.
  2053. *
  2054. * @expectedException \Cake\Error\Exception
  2055. */
  2056. public function testInsertFailureMixingTypesArrayFirst() {
  2057. $query = new Query($this->connection);
  2058. $query->insert(['name'])
  2059. ->into('articles')
  2060. ->values(['name' => 'mark'])
  2061. ->values(new Query($this->connection));
  2062. }
  2063. /**
  2064. * Test that an exception is raised when mixing query + array types.
  2065. *
  2066. * @expectedException \Cake\Error\Exception
  2067. */
  2068. public function testInsertFailureMixingTypesQueryFirst() {
  2069. $query = new Query($this->connection);
  2070. $query->insert(['name'])
  2071. ->into('articles')
  2072. ->values(new Query($this->connection))
  2073. ->values(['name' => 'mark']);
  2074. }
  2075. /**
  2076. * Tests that functions are correctly transformed and their parameters are bound
  2077. *
  2078. * @group FunctionExpression
  2079. * @return void
  2080. */
  2081. public function testSQLFunctions() {
  2082. $query = new Query($this->connection);
  2083. $result = $query->select(
  2084. function($q) {
  2085. return ['total' => $q->func()->count('*')];
  2086. }
  2087. )
  2088. ->from('articles')
  2089. ->execute();
  2090. $expected = [['total' => 3]];
  2091. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2092. $query = new Query($this->connection);
  2093. $result = $query->select([
  2094. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  2095. ])
  2096. ->from('articles')
  2097. ->order(['c' => 'ASC'])
  2098. ->execute();
  2099. $expected = [
  2100. ['c' => 'First Article is appended'],
  2101. ['c' => 'Second Article is appended'],
  2102. ['c' => 'Third Article is appended']
  2103. ];
  2104. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2105. $query = new Query($this->connection);
  2106. $result = $query
  2107. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2108. ->execute()
  2109. ->fetchAll('assoc');
  2110. $this->assertEquals(3, abs($result[0]['d']));
  2111. $query = new Query($this->connection);
  2112. $result = $query
  2113. ->select(['d' => $query->func()->now('date')])
  2114. ->execute();
  2115. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2116. $query = new Query($this->connection);
  2117. $result = $query
  2118. ->select(['d' => $query->func()->now('time')])
  2119. ->execute();
  2120. $this->assertWithinRange(
  2121. date('U'),
  2122. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2123. 1
  2124. );
  2125. $query = new Query($this->connection);
  2126. $result = $query
  2127. ->select(['d' => $query->func()->now()])
  2128. ->execute();
  2129. $this->assertWithinRange(
  2130. date('U'),
  2131. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2132. 1
  2133. );
  2134. }
  2135. /**
  2136. * Tests that default types are passed to functions accepting a $types param
  2137. *
  2138. * @return void
  2139. */
  2140. public function testDefaultTypes() {
  2141. $query = new Query($this->connection);
  2142. $this->assertEquals([], $query->defaultTypes());
  2143. $types = ['id' => 'integer', 'created' => 'datetime'];
  2144. $this->assertSame($query, $query->defaultTypes($types));
  2145. $this->assertSame($types, $query->defaultTypes());
  2146. $results = $query->select(['id', 'comment'])
  2147. ->from('comments')
  2148. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2149. ->execute();
  2150. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2151. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2152. // Now test default can be overridden
  2153. $types = ['created' => 'date'];
  2154. $results = $query
  2155. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2156. ->execute();
  2157. $this->assertCount(6, $results, 'All 6 rows should match.');
  2158. }
  2159. /**
  2160. * Tests parameter binding
  2161. *
  2162. * @return void
  2163. */
  2164. public function testBind() {
  2165. $query = new Query($this->connection);
  2166. $results = $query->select(['id', 'comment'])
  2167. ->from('comments')
  2168. ->where(['created BETWEEN :foo AND :bar'])
  2169. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2170. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2171. ->execute();
  2172. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2173. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2174. $query = new Query($this->connection);
  2175. $results = $query->select(['id', 'comment'])
  2176. ->from('comments')
  2177. ->where(['created BETWEEN :foo AND :bar'])
  2178. ->bind(':foo', '2007-03-18 10:50:00')
  2179. ->bind(':bar', '2007-03-18 10:52:00')
  2180. ->execute();
  2181. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2182. }
  2183. /**
  2184. * Test that epilog() will actually append a string to a select query
  2185. *
  2186. * @return void
  2187. */
  2188. public function testAppendSelect() {
  2189. $query = new Query($this->connection);
  2190. $sql = $query
  2191. ->select(['id', 'title'])
  2192. ->from('articles')
  2193. ->where(['id' => 1])
  2194. ->epilog('FOR UPDATE')
  2195. ->sql();
  2196. $this->assertContains('SELECT', $sql);
  2197. $this->assertContains('FROM', $sql);
  2198. $this->assertContains('WHERE', $sql);
  2199. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2200. }
  2201. /**
  2202. * Test that epilog() will actually append a string to an insert query
  2203. *
  2204. * @return void
  2205. */
  2206. public function testAppendInsert() {
  2207. $query = new Query($this->connection);
  2208. $sql = $query
  2209. ->insert(['id', 'title'])
  2210. ->into('articles')
  2211. ->values([1, 'a title'])
  2212. ->epilog('RETURNING id')
  2213. ->sql();
  2214. $this->assertContains('INSERT', $sql);
  2215. $this->assertContains('INTO', $sql);
  2216. $this->assertContains('VALUES', $sql);
  2217. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2218. }
  2219. /**
  2220. * Test that epilog() will actually append a string to an update query
  2221. *
  2222. * @return void
  2223. */
  2224. public function testAppendUpdate() {
  2225. $query = new Query($this->connection);
  2226. $sql = $query
  2227. ->update('articles')
  2228. ->set(['title' => 'foo'])
  2229. ->where(['id' => 1])
  2230. ->epilog('RETURNING id')
  2231. ->sql();
  2232. $this->assertContains('UPDATE', $sql);
  2233. $this->assertContains('SET', $sql);
  2234. $this->assertContains('WHERE', $sql);
  2235. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2236. }
  2237. /**
  2238. * Test that epilog() will actually append a string to a delete query
  2239. *
  2240. * @return void
  2241. */
  2242. public function testAppendDelete() {
  2243. $query = new Query($this->connection);
  2244. $sql = $query
  2245. ->delete('articles')
  2246. ->where(['id' => 1])
  2247. ->epilog('RETURNING id')
  2248. ->sql();
  2249. $this->assertContains('DELETE FROM', $sql);
  2250. $this->assertContains('WHERE', $sql);
  2251. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2252. }
  2253. /**
  2254. * Tests automatic identifier quoting in the select clause
  2255. *
  2256. * @return void
  2257. */
  2258. public function testQuotingSelectFieldsAndAlias() {
  2259. $this->connection->driver()->autoQuoting(true);
  2260. $query = new Query($this->connection);
  2261. $sql = $query->select(['something'])->sql();
  2262. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2263. $query = new Query($this->connection);
  2264. $sql = $query->select(['foo' => 'something'])->sql();
  2265. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2266. $query = new Query($this->connection);
  2267. $sql = $query->select(['foo' => 1])->sql();
  2268. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2269. $query = new Query($this->connection);
  2270. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2271. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2272. $query = new Query($this->connection);
  2273. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2274. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2275. $query = new Query($this->connection);
  2276. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2277. $this->assertQuotedQuery('<bar>', $sql);
  2278. }
  2279. /**
  2280. * Tests automatic identifier quoting in the from clause
  2281. *
  2282. * @return void
  2283. */
  2284. public function testQuotingFromAndAlias() {
  2285. $this->connection->driver()->autoQuoting(true);
  2286. $query = new Query($this->connection);
  2287. $sql = $query->select('*')->from(['something'])->sql();
  2288. $this->assertQuotedQuery('FROM <something>', $sql);
  2289. $query = new Query($this->connection);
  2290. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2291. $this->assertQuotedQuery('FROM <something> AS <foo>$', $sql);
  2292. $query = new Query($this->connection);
  2293. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2294. $this->assertQuotedQuery('FROM \(bar\) AS <foo>$', $sql);
  2295. }
  2296. /**
  2297. * Tests automatic identifier quoting for DISTINCT ON
  2298. *
  2299. * @return void
  2300. */
  2301. public function testQuotingDistinctOn() {
  2302. $this->connection->driver()->autoQuoting(true);
  2303. $query = new Query($this->connection);
  2304. $sql = $query->select('*')->distinct(['something'])->sql();
  2305. $this->assertQuotedQuery('<something>', $sql);
  2306. }
  2307. /**
  2308. * Tests automatic identifier quoting in the join clause
  2309. *
  2310. * @return void
  2311. */
  2312. public function testQuotingJoinsAndAlias() {
  2313. $this->connection->driver()->autoQuoting(true);
  2314. $query = new Query($this->connection);
  2315. $sql = $query->select('*')->join(['something'])->sql();
  2316. $this->assertQuotedQuery('JOIN <something>', $sql);
  2317. $query = new Query($this->connection);
  2318. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2319. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2320. $query = new Query($this->connection);
  2321. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2322. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2323. }
  2324. /**
  2325. * Tests automatic identifier quoting in the group by clause
  2326. *
  2327. * @return void
  2328. */
  2329. public function testQuotingGroupBy() {
  2330. $this->connection->driver()->autoQuoting(true);
  2331. $query = new Query($this->connection);
  2332. $sql = $query->select('*')->group(['something'])->sql();
  2333. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2334. $query = new Query($this->connection);
  2335. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2336. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2337. $query = new Query($this->connection);
  2338. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2339. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2340. }
  2341. /**
  2342. * Tests automatic identifier quoting strings inside conditions expressions
  2343. *
  2344. * @return void
  2345. */
  2346. public function testQuotingExpressions() {
  2347. $this->connection->driver()->autoQuoting(true);
  2348. $query = new Query($this->connection);
  2349. $sql = $query->select('*')
  2350. ->where(['something' => 'value'])
  2351. ->sql();
  2352. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2353. $query = new Query($this->connection);
  2354. $sql = $query->select('*')
  2355. ->where([
  2356. 'something' => 'value',
  2357. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2358. ])
  2359. ->sql();
  2360. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2361. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2362. }
  2363. /**
  2364. * Tests that insert query parts get quoted automatically
  2365. *
  2366. * @return void
  2367. */
  2368. public function testQuotingInsert() {
  2369. $this->connection->driver()->autoQuoting(true);
  2370. $query = new Query($this->connection);
  2371. $sql = $query->insert(['bar', 'baz'])
  2372. ->into('foo')
  2373. ->where(['something' => 'value'])
  2374. ->sql();
  2375. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2376. $query = new Query($this->connection);
  2377. $sql = $query->insert([$query->newExpr('bar')])
  2378. ->into('foo')
  2379. ->where(['something' => 'value'])
  2380. ->sql();
  2381. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2382. }
  2383. /**
  2384. * Tests converting a query to a string
  2385. *
  2386. * @return void
  2387. */
  2388. public function testToString() {
  2389. $query = new Query($this->connection);
  2390. $query
  2391. ->select(['title'])
  2392. ->from('articles');
  2393. $result = (string)$query;
  2394. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, true);
  2395. }
  2396. /**
  2397. * Tests __debugInfo
  2398. *
  2399. * @return void
  2400. */
  2401. public function testDebugInfo() {
  2402. $query = (new Query($this->connection))->select('*')
  2403. ->from('articles')
  2404. ->defaultTypes(['id' => 'integer'])
  2405. ->where(['id' => '1']);
  2406. $expected = [
  2407. 'sql' => $query->sql(),
  2408. 'params' => [
  2409. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2410. ],
  2411. 'defaultTypes' => ['id' => 'integer'],
  2412. 'decorators' => 0,
  2413. 'executed' => false
  2414. ];
  2415. $result = $query->__debugInfo();
  2416. $this->assertEquals($expected, $result);
  2417. $query->execute();
  2418. $expected = [
  2419. 'sql' => $query->sql(),
  2420. 'params' => [
  2421. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2422. ],
  2423. 'defaultTypes' => ['id' => 'integer'],
  2424. 'decorators' => 0,
  2425. 'executed' => true
  2426. ];
  2427. $result = $query->__debugInfo();
  2428. }
  2429. /**
  2430. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2431. *
  2432. * @return void
  2433. */
  2434. public function testIsNullWithExpressions() {
  2435. $query = new Query($this->connection);
  2436. $subquery = (new Query($this->connection))
  2437. ->select(['id'])
  2438. ->from('authors')
  2439. ->where(['id' => 1]);
  2440. $result = $query
  2441. ->select(['name'])
  2442. ->from(['authors'])
  2443. ->where(function($exp) use ($subquery) {
  2444. return $exp->isNotNull($subquery);
  2445. })
  2446. ->execute();
  2447. $this->assertNotEmpty($result->fetchAll('assoc'));
  2448. $result = (new Query($this->connection))
  2449. ->select(['name'])
  2450. ->from(['authors'])
  2451. ->where(function($exp) use ($subquery) {
  2452. return $exp->isNull($subquery);
  2453. })
  2454. ->execute();
  2455. $this->assertEmpty($result->fetchAll('assoc'));
  2456. }
  2457. /**
  2458. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2459. * when using autoQuoting
  2460. *
  2461. * @return void
  2462. */
  2463. public function testIsNullAutoQuoting() {
  2464. $this->connection->driver()->autoQuoting(true);
  2465. $query = new Query($this->connection);
  2466. $query->select('*')->from('things')->where(function($exp) {
  2467. return $exp->isNull('field');
  2468. });
  2469. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2470. $query = new Query($this->connection);
  2471. $query->select('*')->from('things')->where(function($exp) {
  2472. return $exp->isNotNull('field');
  2473. });
  2474. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2475. }
  2476. /**
  2477. * Tests that using the IS operator will automatically translate to the best
  2478. * possible operator depending on the passed value
  2479. *
  2480. * @return void
  2481. */
  2482. public function testDirectIsNull() {
  2483. $sql = (new Query($this->connection))
  2484. ->select(['name'])
  2485. ->from(['authors'])
  2486. ->where(['name IS' => null])
  2487. ->sql();
  2488. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, true);
  2489. $results = (new Query($this->connection))
  2490. ->select(['name'])
  2491. ->from(['authors'])
  2492. ->where(['name IS' => 'larry'])
  2493. ->execute();
  2494. $this->assertCount(1, $results);
  2495. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  2496. }
  2497. /**
  2498. * Tests that case statements work correctly for various use-cases.
  2499. *
  2500. * @return void
  2501. */
  2502. public function testSqlCaseStatement() {
  2503. $query = new Query($this->connection);
  2504. $publishedCase = $query
  2505. ->newExpr()
  2506. ->addCase($query
  2507. ->newExpr()
  2508. ->add(['published' => 'Y']), 1, 'integer'
  2509. );
  2510. $notPublishedCase = $query
  2511. ->newExpr()
  2512. ->addCase($query
  2513. ->newExpr()
  2514. ->add(['published' => 'N']), 1, 'integer'
  2515. );
  2516. //Postgres requires the case statement to be cast to a integer
  2517. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  2518. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  2519. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  2520. }
  2521. $results = $query
  2522. ->select([
  2523. 'published' => $query->func()->sum($publishedCase),
  2524. 'not_published' => $query->func()->sum($notPublishedCase)
  2525. ])
  2526. ->from(['comments'])
  2527. ->execute()
  2528. ->fetchAll('assoc');
  2529. $this->assertEquals(5, $results[0]['published']);
  2530. $this->assertEquals(1, $results[0]['not_published']);
  2531. $query = new Query($this->connection);
  2532. $query
  2533. ->insert(['article_id', 'user_id', 'comment', 'published'])
  2534. ->into('comments')
  2535. ->values([
  2536. 'article_id' => 2,
  2537. 'user_id' => 1,
  2538. 'comment' => 'In limbo',
  2539. 'published' => 'L'
  2540. ])
  2541. ->execute();
  2542. $query = new Query($this->connection);
  2543. $conditions = [
  2544. $query
  2545. ->newExpr()
  2546. ->add(['published' => 'Y']),
  2547. $query
  2548. ->newExpr()
  2549. ->add(['published' => 'N'])
  2550. ];
  2551. $values = [
  2552. 'Published',
  2553. 'Not published',
  2554. 'None'
  2555. ];
  2556. $results = $query
  2557. ->select([
  2558. 'id',
  2559. 'comment',
  2560. 'status' => $query->newExpr()->addCase($conditions, $values)
  2561. ])
  2562. ->from(['comments'])
  2563. ->execute()
  2564. ->fetchAll('assoc');
  2565. $this->assertEquals('Published', $results[2]['status']);
  2566. $this->assertEquals('Not published', $results[3]['status']);
  2567. $this->assertEquals('None', $results[6]['status']);
  2568. }
  2569. /**
  2570. * Assertion for comparing a table's contents with what is in it.
  2571. *
  2572. * @param string $table
  2573. * @param int $count
  2574. * @param array $rows
  2575. * @param array $conditions
  2576. * @return void
  2577. */
  2578. public function assertTable($table, $count, $rows, $conditions = []) {
  2579. $result = (new Query($this->connection))->select('*')
  2580. ->from($table)
  2581. ->where($conditions)
  2582. ->execute();
  2583. $this->assertCount($count, $result, 'Row count is incorrect');
  2584. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2585. }
  2586. /**
  2587. * Assertion for comparing a regex pattern against a query having its indentifiers
  2588. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2589. * parameter is set to true, it will alter the pattern to both accept quoted and
  2590. * unquoted queries
  2591. *
  2592. * @param string $pattern
  2593. * @param string $query the result to compare against
  2594. * @param bool $optional
  2595. * @return void
  2596. */
  2597. public function assertQuotedQuery($pattern, $query, $optional = false) {
  2598. if ($optional) {
  2599. $optional = '?';
  2600. }
  2601. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2602. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2603. $this->assertRegExp('#' . $pattern . '#', $query);
  2604. }
  2605. }