QueryTest.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961
  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.articles', 'core.authors', 'core.comments'];
  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. ->eq($field, 100, 'integer');
  802. })
  803. ->execute();
  804. $this->assertCount(0, $result);
  805. }
  806. /**
  807. * Tests using where conditions with operator methods
  808. *
  809. * @return void
  810. */
  811. public function testSelectWhereOperatorMethods() {
  812. $query = new Query($this->connection);
  813. $result = $query
  814. ->select(['title'])
  815. ->from('articles')
  816. ->where(function ($exp) {
  817. return $exp->gt('id', 1);
  818. })
  819. ->execute();
  820. $this->assertCount(2, $result);
  821. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  822. $query = new Query($this->connection);
  823. $result = $query->select(['title'])
  824. ->from('articles')
  825. ->where(function ($exp) {
  826. return $exp->lt('id', 2);
  827. })
  828. ->execute();
  829. $this->assertCount(1, $result);
  830. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  831. $query = new Query($this->connection);
  832. $result = $query->select(['title'])
  833. ->from('articles')
  834. ->where(function ($exp) {
  835. return $exp->lte('id', 2);
  836. })
  837. ->execute();
  838. $this->assertCount(2, $result);
  839. $query = new Query($this->connection);
  840. $result = $query
  841. ->select(['title'])
  842. ->from('articles')
  843. ->where(function ($exp) {
  844. return $exp->gte('id', 1);
  845. })
  846. ->execute();
  847. $this->assertCount(3, $result);
  848. $query = new Query($this->connection);
  849. $result = $query
  850. ->select(['title'])
  851. ->from('articles')
  852. ->where(function ($exp) {
  853. return $exp->lte('id', 1);
  854. })
  855. ->execute();
  856. $this->assertCount(1, $result);
  857. $query = new Query($this->connection);
  858. $result = $query
  859. ->select(['title'])
  860. ->from('articles')
  861. ->where(function ($exp) {
  862. return $exp->notEq('id', 2);
  863. })
  864. ->execute();
  865. $this->assertCount(2, $result);
  866. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  867. $query = new Query($this->connection);
  868. $result = $query
  869. ->select(['title'])
  870. ->from('articles')
  871. ->where(function ($exp) {
  872. return $exp->like('title', 'First Article');
  873. })
  874. ->execute();
  875. $this->assertCount(1, $result);
  876. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  877. $query = new Query($this->connection);
  878. $result = $query
  879. ->select(['title'])
  880. ->from('articles')
  881. ->where(function ($exp) {
  882. return $exp->like('title', '%Article%');
  883. })
  884. ->execute();
  885. $this->assertCount(3, $result);
  886. $query = new Query($this->connection);
  887. $result = $query
  888. ->select(['title'])
  889. ->from('articles')
  890. ->where(function ($exp) {
  891. return $exp->notLike('title', '%Article%');
  892. })
  893. ->execute();
  894. $this->assertCount(0, $result);
  895. $query = new Query($this->connection);
  896. $result = $query
  897. ->select(['id'])
  898. ->from('comments')
  899. ->where(function ($exp) {
  900. return $exp->isNull('published');
  901. })
  902. ->execute();
  903. $this->assertCount(0, $result);
  904. $query = new Query($this->connection);
  905. $result = $query
  906. ->select(['id'])
  907. ->from('comments')
  908. ->where(function ($exp) {
  909. return $exp->isNotNull('published');
  910. })
  911. ->execute();
  912. $this->assertCount(6, $result);
  913. $query = new Query($this->connection);
  914. $result = $query
  915. ->select(['id'])
  916. ->from('comments')
  917. ->where(function ($exp) {
  918. return $exp->in('published', ['Y', 'N']);
  919. })
  920. ->execute();
  921. $this->assertCount(6, $result);
  922. $query = new Query($this->connection);
  923. $result = $query
  924. ->select(['id'])
  925. ->from('comments')
  926. ->where(function ($exp) {
  927. return $exp->in(
  928. 'created',
  929. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  930. 'datetime'
  931. );
  932. })
  933. ->execute();
  934. $this->assertCount(2, $result);
  935. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  936. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  937. $query = new Query($this->connection);
  938. $result = $query
  939. ->select(['id'])
  940. ->from('comments')
  941. ->where(function ($exp) {
  942. return $exp->notIn(
  943. 'created',
  944. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  945. 'datetime'
  946. );
  947. })
  948. ->execute();
  949. $this->assertCount(4, $result);
  950. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  951. }
  952. /**
  953. * Tests that calling "in" and "notIn" will cast the passed values to an array
  954. *
  955. * @return void
  956. */
  957. public function testInValueCast() {
  958. $query = new Query($this->connection);
  959. $result = $query
  960. ->select(['id'])
  961. ->from('comments')
  962. ->where(function ($exp) {
  963. return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
  964. })
  965. ->execute();
  966. $this->assertCount(1, $result);
  967. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  968. $query = new Query($this->connection);
  969. $result = $query
  970. ->select(['id'])
  971. ->from('comments')
  972. ->where(function ($exp) {
  973. return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
  974. })
  975. ->execute();
  976. $this->assertCount(5, $result);
  977. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  978. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  979. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  980. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  981. $query = new Query($this->connection);
  982. $result = $query
  983. ->select(['id'])
  984. ->from('comments')
  985. ->where(function ($exp, $q) {
  986. return $exp->in(
  987. 'created',
  988. $q->newExpr("'2007-03-18 10:45:23'"),
  989. 'datetime'
  990. );
  991. })
  992. ->execute();
  993. $this->assertCount(1, $result);
  994. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  995. $query = new Query($this->connection);
  996. $result = $query
  997. ->select(['id'])
  998. ->from('comments')
  999. ->where(function ($exp, $q) {
  1000. return $exp->notIn(
  1001. 'created',
  1002. $q->newExpr("'2007-03-18 10:45:23'"),
  1003. 'datetime'
  1004. );
  1005. })
  1006. ->execute();
  1007. $this->assertCount(5, $result);
  1008. }
  1009. /**
  1010. * Tests that calling "in" and "notIn" will cast the passed values to an array
  1011. *
  1012. * @return void
  1013. */
  1014. public function testInValueCast2() {
  1015. $query = new Query($this->connection);
  1016. $result = $query
  1017. ->select(['id'])
  1018. ->from('comments')
  1019. ->where(['created IN' => '2007-03-18 10:45:23'])
  1020. ->execute();
  1021. $this->assertCount(1, $result);
  1022. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1023. $query = new Query($this->connection);
  1024. $result = $query
  1025. ->select(['id'])
  1026. ->from('comments')
  1027. ->where(['created NOT IN' => '2007-03-18 10:45:23'])
  1028. ->execute();
  1029. $this->assertCount(5, $result);
  1030. }
  1031. /**
  1032. * Tests that it is possible to use a between expression
  1033. * in a where condition
  1034. *
  1035. * @return void
  1036. */
  1037. public function testWhereWithBetween() {
  1038. $query = new Query($this->connection);
  1039. $result = $query
  1040. ->select(['id'])
  1041. ->from('comments')
  1042. ->where(function($exp) {
  1043. return $exp->between('id', 5, 6, 'integer');
  1044. })
  1045. ->execute();
  1046. $this->assertCount(2, $result);
  1047. $first = $result->fetch('assoc');
  1048. $this->assertEquals(5, $first['id']);
  1049. $second = $result->fetch('assoc');
  1050. $this->assertEquals(6, $second['id']);
  1051. }
  1052. /**
  1053. * Tests that it is possible to use a between expression
  1054. * in a where condition with a complex data type
  1055. *
  1056. * @return void
  1057. */
  1058. public function testWhereWithBetweenComplex() {
  1059. $query = new Query($this->connection);
  1060. $result = $query
  1061. ->select(['id'])
  1062. ->from('comments')
  1063. ->where(function($exp) {
  1064. $from = new \DateTime('2007-03-18 10:51:00');
  1065. $to = new \DateTime('2007-03-18 10:54:00');
  1066. return $exp->between('created', $from, $to, 'datetime');
  1067. })
  1068. ->execute();
  1069. $this->assertCount(2, $result);
  1070. $first = $result->fetch('assoc');
  1071. $this->assertEquals(4, $first['id']);
  1072. $second = $result->fetch('assoc');
  1073. $this->assertEquals(5, $second['id']);
  1074. }
  1075. /**
  1076. * Tests nesting query expressions both using arrays and closures
  1077. *
  1078. * @return void
  1079. */
  1080. public function testSelectExpressionComposition() {
  1081. $query = new Query($this->connection);
  1082. $result = $query
  1083. ->select(['id'])
  1084. ->from('comments')
  1085. ->where(function ($exp) {
  1086. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  1087. return $exp->add($and);
  1088. })
  1089. ->execute();
  1090. $this->assertCount(1, $result);
  1091. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1092. $query = new Query($this->connection);
  1093. $result = $query
  1094. ->select(['id'])
  1095. ->from('comments')
  1096. ->where(function ($exp) {
  1097. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  1098. return $exp->add($and);
  1099. })
  1100. ->execute();
  1101. $this->assertCount(0, $result);
  1102. $query = new Query($this->connection);
  1103. $result = $query
  1104. ->select(['id'])
  1105. ->from('comments')
  1106. ->where(function ($exp) {
  1107. $and = $exp->and_(function ($and) {
  1108. return $and->eq('id', 1)->gt('id', 0);
  1109. });
  1110. return $exp->add($and);
  1111. })
  1112. ->execute();
  1113. $this->assertCount(1, $result);
  1114. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1115. $query = new Query($this->connection);
  1116. $result = $query
  1117. ->select(['id'])
  1118. ->from('comments')
  1119. ->where(function ($exp) {
  1120. $or = $exp->or_(['id' => 1]);
  1121. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  1122. return $or->add($and);
  1123. })
  1124. ->execute();
  1125. $this->assertCount(2, $result);
  1126. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1127. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1128. $query = new Query($this->connection);
  1129. $result = $query
  1130. ->select(['id'])
  1131. ->from('comments')
  1132. ->where(function ($exp) {
  1133. $or = $exp->or_(function ($or) {
  1134. return $or->eq('id', 1)->eq('id', 2);
  1135. });
  1136. return $or;
  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 that conditions can be nested with an unary operator using the array notation
  1145. * and the not() method
  1146. *
  1147. * @return void
  1148. */
  1149. public function testSelectWhereNot() {
  1150. $query = new Query($this->connection);
  1151. $result = $query
  1152. ->select(['id'])
  1153. ->from('comments')
  1154. ->where(function ($exp) {
  1155. return $exp->not(
  1156. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  1157. );
  1158. })
  1159. ->execute();
  1160. $this->assertCount(5, $result);
  1161. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1162. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1163. $query = new Query($this->connection);
  1164. $result = $query
  1165. ->select(['id'])
  1166. ->from('comments')
  1167. ->where(function ($exp) {
  1168. return $exp->not(
  1169. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  1170. );
  1171. })
  1172. ->execute();
  1173. $this->assertCount(6, $result);
  1174. $query = new Query($this->connection);
  1175. $result = $query
  1176. ->select(['id'])
  1177. ->from('articles')
  1178. ->where([
  1179. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  1180. ])
  1181. ->execute();
  1182. $this->assertCount(2, $result);
  1183. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1184. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1185. }
  1186. /**
  1187. * Tests order() method both with simple fields and expressions
  1188. *
  1189. * @return void
  1190. */
  1191. public function testSelectOrderBy() {
  1192. $query = new Query($this->connection);
  1193. $result = $query
  1194. ->select(['id'])
  1195. ->from('articles')
  1196. ->order(['id' => 'desc'])
  1197. ->execute();
  1198. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1199. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1200. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1201. $result = $query->order(['id' => 'asc'])->execute();
  1202. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1203. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1204. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1205. $result = $query->order(['title' => 'asc'])->execute();
  1206. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1207. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1208. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1209. $result = $query->order(['title' => 'asc'], true)->execute();
  1210. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1211. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1212. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1213. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1214. ->execute();
  1215. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1216. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1217. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1218. $expression = $query->newExpr(['(id + :offset) % 2']);
  1219. $result = $query
  1220. ->order([$expression, 'id' => 'desc'], true)
  1221. ->bind(':offset', 1, null)
  1222. ->execute();
  1223. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1224. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1225. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1226. $result = $query
  1227. ->order($expression, true)
  1228. ->order(['id' => 'asc'])
  1229. ->bind(':offset', 1, null)
  1230. ->execute();
  1231. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1232. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1233. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1234. }
  1235. /**
  1236. * Tests that group by fields can be passed similar to select fields
  1237. * and that it sends the correct query to the database
  1238. *
  1239. * @return void
  1240. */
  1241. public function testSelectGroup() {
  1242. $query = new Query($this->connection);
  1243. $result = $query
  1244. ->select(['total' => 'count(author_id)', 'author_id'])
  1245. ->from('articles')
  1246. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1247. ->group('author_id')
  1248. ->execute();
  1249. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1250. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1251. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1252. ->group(['name'], true)
  1253. ->order(['total' => 'asc'])
  1254. ->execute();
  1255. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1256. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1257. $result = $query->select(['articles.id'])
  1258. ->group(['articles.id'])
  1259. ->execute();
  1260. $this->assertCount(3, $result);
  1261. }
  1262. /**
  1263. * Tests that it is possible to select distinct rows
  1264. *
  1265. * @return void
  1266. */
  1267. public function testSelectDistinct() {
  1268. $query = new Query($this->connection);
  1269. $result = $query
  1270. ->select(['author_id'])
  1271. ->from(['a' => 'articles'])
  1272. ->execute();
  1273. $this->assertCount(3, $result);
  1274. $result = $query->distinct()->execute();
  1275. $this->assertCount(2, $result);
  1276. $result = $query->select(['id'])->distinct(false)->execute();
  1277. $this->assertCount(3, $result);
  1278. }
  1279. /**
  1280. * Tests that it is possible to select distinct rows, even filtering by one column
  1281. * this is testing that there is a specific implementation for DISTINCT ON
  1282. *
  1283. * @return void
  1284. */
  1285. public function testSelectDistinctON() {
  1286. $this->skipIf(
  1287. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  1288. 'Not implemented yet in SqlServer'
  1289. );
  1290. $query = new Query($this->connection);
  1291. $result = $query
  1292. ->select(['id', 'author_id'])
  1293. ->distinct(['author_id'])
  1294. ->from(['a' => 'articles'])
  1295. ->execute();
  1296. $this->assertCount(2, $result);
  1297. }
  1298. /**
  1299. * Test use of modifiers in the query
  1300. *
  1301. * Testing the generated SQL since the modifiers are usually different per driver
  1302. *
  1303. * @return void
  1304. */
  1305. public function testSelectModifiers() {
  1306. $query = new Query($this->connection);
  1307. $result = $query
  1308. ->select(['city', 'state', 'country'])
  1309. ->from(['addresses'])
  1310. ->modifier('DISTINCTROW');
  1311. $this->assertQuotedQuery(
  1312. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1313. $result->sql(),
  1314. true
  1315. );
  1316. $query = new Query($this->connection);
  1317. $result = $query
  1318. ->select(['city', 'state', 'country'])
  1319. ->from(['addresses'])
  1320. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1321. $this->assertQuotedQuery(
  1322. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1323. $result->sql(),
  1324. true
  1325. );
  1326. $query = new Query($this->connection);
  1327. $result = $query
  1328. ->select(['city', 'state', 'country'])
  1329. ->from(['addresses'])
  1330. ->modifier('DISTINCTROW')
  1331. ->modifier('SQL_NO_CACHE');
  1332. $this->assertQuotedQuery(
  1333. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1334. $result->sql(),
  1335. true
  1336. );
  1337. $query = new Query($this->connection);
  1338. $result = $query
  1339. ->select(['city', 'state', 'country'])
  1340. ->from(['addresses'])
  1341. ->modifier(['TOP 10']);
  1342. $this->assertQuotedQuery(
  1343. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1344. $result->sql(),
  1345. true
  1346. );
  1347. }
  1348. /**
  1349. * Tests that having() behaves pretty much the same as the where() method
  1350. *
  1351. * @return void
  1352. */
  1353. public function testSelectHaving() {
  1354. $query = new Query($this->connection);
  1355. $result = $query
  1356. ->select(['total' => 'count(author_id)', 'author_id'])
  1357. ->from('articles')
  1358. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1359. ->group('author_id')
  1360. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1361. ->execute();
  1362. $expected = [['total' => 1, 'author_id' => 3]];
  1363. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1364. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1365. ->execute();
  1366. $expected = [['total' => 2, 'author_id' => 1]];
  1367. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1368. $result = $query->having(function ($e) {
  1369. return $e->add('count(author_id) = 1 + 1');
  1370. }, [], true)
  1371. ->execute();
  1372. $expected = [['total' => 2, 'author_id' => 1]];
  1373. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1374. }
  1375. /**
  1376. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1377. * in the having clause
  1378. *
  1379. * @return void
  1380. */
  1381. public function testSelectOrHaving() {
  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. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1390. ->execute();
  1391. $expected = [['total' => 1, 'author_id' => 3]];
  1392. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1393. $query = new Query($this->connection);
  1394. $result = $query
  1395. ->select(['total' => 'count(author_id)', 'author_id'])
  1396. ->from('articles')
  1397. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1398. ->group('author_id')
  1399. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1400. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1401. ->execute();
  1402. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1403. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1404. $query = new Query($this->connection);
  1405. $result = $query
  1406. ->select(['total' => 'count(author_id)', 'author_id'])
  1407. ->from('articles')
  1408. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1409. ->group('author_id')
  1410. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1411. ->orHaving(function ($e) {
  1412. return $e->add('count(author_id) = 1 + 1');
  1413. })
  1414. ->execute();
  1415. $expected = [['total' => 2, 'author_id' => 1]];
  1416. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1417. }
  1418. /**
  1419. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1420. * in the having clause
  1421. *
  1422. * @return void
  1423. */
  1424. public function testSelectAndHaving() {
  1425. $query = new Query($this->connection);
  1426. $result = $query
  1427. ->select(['total' => 'count(author_id)', 'author_id'])
  1428. ->from('articles')
  1429. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1430. ->group('author_id')
  1431. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1432. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1433. ->execute();
  1434. $this->assertCount(0, $result);
  1435. $query = new Query($this->connection);
  1436. $result = $query
  1437. ->select(['total' => 'count(author_id)', 'author_id'])
  1438. ->from('articles')
  1439. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1440. ->group('author_id')
  1441. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1442. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1443. ->execute();
  1444. $expected = [['total' => 2, 'author_id' => 1]];
  1445. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1446. $query = new Query($this->connection);
  1447. $result = $query
  1448. ->select(['total' => 'count(author_id)', 'author_id'])
  1449. ->from('articles')
  1450. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1451. ->group('author_id')
  1452. ->andHaving(function ($e) {
  1453. return $e->add('count(author_id) = 2 - 1');
  1454. })
  1455. ->execute();
  1456. $expected = [['total' => 1, 'author_id' => 3]];
  1457. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1458. }
  1459. /**
  1460. * Tests selecting rows using a limit clause
  1461. *
  1462. * @return void
  1463. */
  1464. public function testSelectLimit() {
  1465. $query = new Query($this->connection);
  1466. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1467. $this->assertCount(1, $result);
  1468. $query = new Query($this->connection);
  1469. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1470. $this->assertCount(2, $result);
  1471. }
  1472. /**
  1473. * Tests selecting rows combining a limit and offset clause
  1474. *
  1475. * @return void
  1476. */
  1477. public function testSelectOffset() {
  1478. $query = new Query($this->connection);
  1479. $result = $query->select('id')->from('comments')
  1480. ->limit(1)
  1481. ->offset(0)
  1482. ->order(['id' => 'ASC'])
  1483. ->execute();
  1484. $this->assertCount(1, $result);
  1485. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1486. $query = new Query($this->connection);
  1487. $result = $query->select('id')->from('comments')
  1488. ->limit(1)
  1489. ->offset(1)
  1490. ->execute();
  1491. $this->assertCount(1, $result);
  1492. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1493. $query = new Query($this->connection);
  1494. $result = $query->select('id')->from('comments')
  1495. ->limit(1)
  1496. ->offset(2)
  1497. ->execute();
  1498. $this->assertCount(1, $result);
  1499. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1500. $query = new Query($this->connection);
  1501. $result = $query->select('id')->from('articles')
  1502. ->order(['id' => 'DESC'])
  1503. ->limit(1)
  1504. ->offset(0)
  1505. ->execute();
  1506. $this->assertCount(1, $result);
  1507. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1508. $result = $query->limit(2)->offset(1)->execute();
  1509. $this->assertCount(2, $result);
  1510. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1511. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1512. }
  1513. /**
  1514. * Test selecting rows using the page() method.
  1515. *
  1516. * @return void
  1517. */
  1518. public function testSelectPage() {
  1519. $query = new Query($this->connection);
  1520. $result = $query->select('id')->from('comments')
  1521. ->limit(1)
  1522. ->page(1)
  1523. ->execute();
  1524. $this->assertCount(1, $result);
  1525. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1526. $query = new Query($this->connection);
  1527. $result = $query->select('id')->from('comments')
  1528. ->limit(1)
  1529. ->page(2)
  1530. ->order(['id' => 'asc'])
  1531. ->execute();
  1532. $this->assertCount(1, $result);
  1533. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1534. $query = new Query($this->connection);
  1535. $query->select('id')->from('comments')->page(3, 10);
  1536. $this->assertEquals(10, $query->clause('limit'));
  1537. $this->assertEquals(20, $query->clause('offset'));
  1538. $query = new Query($this->connection);
  1539. $query->select('id')->from('comments')->page(1);
  1540. $this->assertEquals(25, $query->clause('limit'));
  1541. $this->assertEquals(0, $query->clause('offset'));
  1542. $query->select('id')->from('comments')->page(2);
  1543. $this->assertEquals(25, $query->clause('limit'));
  1544. $this->assertEquals(25, $query->clause('offset'));
  1545. }
  1546. /**
  1547. * Tests that Query objects can be included inside the select clause
  1548. * and be used as a normal field, including binding any passed parameter
  1549. *
  1550. * @return void
  1551. */
  1552. public function testSubqueryInSelect() {
  1553. $query = new Query($this->connection);
  1554. $subquery = (new Query($this->connection))
  1555. ->select('name')
  1556. ->from(['b' => 'authors'])
  1557. ->where(['b.id = a.id']);
  1558. $result = $query
  1559. ->select(['id', 'name' => $subquery])
  1560. ->from(['a' => 'comments'])->execute();
  1561. $expected = [
  1562. ['id' => 1, 'name' => 'mariano'],
  1563. ['id' => 2, 'name' => 'nate'],
  1564. ['id' => 3, 'name' => 'larry'],
  1565. ['id' => 4, 'name' => 'garrett'],
  1566. ['id' => 5, 'name' => null],
  1567. ['id' => 6, 'name' => null],
  1568. ];
  1569. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1570. $query = new Query($this->connection);
  1571. $subquery = (new Query($this->connection))
  1572. ->select('name')
  1573. ->from(['b' => 'authors'])
  1574. ->where(['name' => 'mariano'], ['name' => 'string']);
  1575. $result = $query
  1576. ->select(['id', 'name' => $subquery])
  1577. ->from(['a' => 'articles'])->execute();
  1578. $expected = [
  1579. ['id' => 1, 'name' => 'mariano'],
  1580. ['id' => 2, 'name' => 'mariano'],
  1581. ['id' => 3, 'name' => 'mariano'],
  1582. ];
  1583. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1584. }
  1585. /**
  1586. * Tests that Query objects can be included inside the from clause
  1587. * and be used as a normal table, including binding any passed parameter
  1588. *
  1589. * @return void
  1590. */
  1591. public function testSuqueryInFrom() {
  1592. $query = new Query($this->connection);
  1593. $subquery = (new Query($this->connection))
  1594. ->select(['id', 'comment'])
  1595. ->from('comments')
  1596. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1597. $result = $query
  1598. ->select(['say' => 'comment'])
  1599. ->from(['b' => $subquery])
  1600. ->where(['id !=' => 3])
  1601. ->execute();
  1602. $expected = [
  1603. ['say' => 'Second Comment for First Article'],
  1604. ['say' => 'Fourth Comment for First Article'],
  1605. ['say' => 'First Comment for Second Article'],
  1606. ['say' => 'Second Comment for Second Article'],
  1607. ];
  1608. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1609. }
  1610. /**
  1611. * Tests that Query objects can be included inside the where clause
  1612. * and be used as a normal condition, including binding any passed parameter
  1613. *
  1614. * @return void
  1615. */
  1616. public function testSubqueryInWhere() {
  1617. $query = new Query($this->connection);
  1618. $subquery = (new Query($this->connection))
  1619. ->select(['id'])
  1620. ->from('authors')
  1621. ->where(['id' => 1]);
  1622. $result = $query
  1623. ->select(['name'])
  1624. ->from(['authors'])
  1625. ->where(['id !=' => $subquery])
  1626. ->execute();
  1627. $expected = [
  1628. ['name' => 'nate'],
  1629. ['name' => 'larry'],
  1630. ['name' => 'garrett'],
  1631. ];
  1632. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1633. $query = new Query($this->connection);
  1634. $subquery = (new Query($this->connection))
  1635. ->select(['id'])
  1636. ->from('comments')
  1637. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1638. $result = $query
  1639. ->select(['name'])
  1640. ->from(['authors'])
  1641. ->where(['id not in' => $subquery])
  1642. ->execute();
  1643. $expected = [
  1644. ['name' => 'mariano'],
  1645. ];
  1646. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1647. }
  1648. /**
  1649. * Tests that it is possible to use a subquery in a join clause
  1650. *
  1651. * @return void
  1652. */
  1653. public function testSubqueyInJoin() {
  1654. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1655. $query = new Query($this->connection);
  1656. $result = $query
  1657. ->select(['title', 'name'])
  1658. ->from('articles')
  1659. ->join(['b' => $subquery])
  1660. ->execute();
  1661. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1662. $subquery->where(['id' => 1]);
  1663. $result = $query->execute();
  1664. $this->assertCount(3, $result);
  1665. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1666. $result = $query->execute();
  1667. $this->assertCount(1, $result);
  1668. }
  1669. /**
  1670. * Tests that it is possible to one or multiple UNION statements in a query
  1671. *
  1672. * @return void
  1673. */
  1674. public function testUnion() {
  1675. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1676. $query = new Query($this->connection);
  1677. $result = $query->select(['id', 'comment'])
  1678. ->from(['c' => 'comments'])
  1679. ->union($union)
  1680. ->execute();
  1681. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1682. $rows = $result->fetchAll();
  1683. $union->select(['foo' => 'id', 'bar' => 'title']);
  1684. $union = (new Query($this->connection))
  1685. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1686. ->from(['b' => 'authors'])
  1687. ->where(['id ' => 1])
  1688. ->order(['id' => 'desc']);
  1689. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1690. $result = $query->execute();
  1691. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1692. $this->assertNotEquals($rows, $result->fetchAll());
  1693. $union = (new Query($this->connection))
  1694. ->select(['id', 'title'])
  1695. ->from(['c' => 'articles']);
  1696. $query->select(['id', 'comment'], true)->union($union, true);
  1697. $result = $query->execute();
  1698. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1699. $this->assertEquals($rows, $result->fetchAll());
  1700. }
  1701. /**
  1702. * Tests that UNION ALL can be built by setting the second param of union() to true
  1703. *
  1704. * @return void
  1705. */
  1706. public function testUnionAll() {
  1707. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1708. $query = new Query($this->connection);
  1709. $result = $query->select(['id', 'comment'])
  1710. ->from(['c' => 'comments'])
  1711. ->union($union)
  1712. ->execute();
  1713. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1714. $rows = $result->fetchAll();
  1715. $union->select(['foo' => 'id', 'bar' => 'title']);
  1716. $union = (new Query($this->connection))
  1717. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1718. ->from(['b' => 'authors'])
  1719. ->where(['id ' => 1])
  1720. ->order(['id' => 'desc']);
  1721. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1722. $result = $query->execute();
  1723. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1724. $this->assertNotEquals($rows, $result->fetchAll());
  1725. }
  1726. /**
  1727. * Tests stacking decorators for results and resetting the list of decorators
  1728. *
  1729. * @return void
  1730. */
  1731. public function testDecorateResults() {
  1732. $query = new Query($this->connection);
  1733. $result = $query
  1734. ->select(['id', 'title'])
  1735. ->from('articles')
  1736. ->order(['id' => 'ASC'])
  1737. ->decorateResults(function ($row) {
  1738. $row['modified_id'] = $row['id'] + 1;
  1739. return $row;
  1740. })
  1741. ->execute();
  1742. while ($row = $result->fetch('assoc')) {
  1743. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1744. }
  1745. $result = $query->decorateResults(function ($row) {
  1746. $row['modified_id']--;
  1747. return $row;
  1748. })->execute();
  1749. while ($row = $result->fetch('assoc')) {
  1750. $this->assertEquals($row['id'], $row['modified_id']);
  1751. }
  1752. $result = $query
  1753. ->decorateResults(function ($row) {
  1754. $row['foo'] = 'bar';
  1755. return $row;
  1756. }, true)
  1757. ->execute();
  1758. while ($row = $result->fetch('assoc')) {
  1759. $this->assertEquals('bar', $row['foo']);
  1760. $this->assertArrayNotHasKey('modified_id', $row);
  1761. }
  1762. $results = $query->decorateResults(null, true)->execute();
  1763. while ($row = $result->fetch('assoc')) {
  1764. $this->assertArrayNotHasKey('foo', $row);
  1765. $this->assertArrayNotHasKey('modified_id', $row);
  1766. }
  1767. }
  1768. /**
  1769. * Test a basic delete using from()
  1770. *
  1771. * @return void
  1772. */
  1773. public function testDeleteWithFrom() {
  1774. $query = new Query($this->connection);
  1775. $query->delete()
  1776. ->from('authors')
  1777. ->where('1 = 1');
  1778. $result = $query->sql();
  1779. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1780. $result = $query->execute();
  1781. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1782. $this->assertCount(self::AUTHOR_COUNT, $result);
  1783. }
  1784. /**
  1785. * Test delete with from and alias.
  1786. *
  1787. * @return void
  1788. */
  1789. public function testDeleteWithAliasedFrom() {
  1790. $query = new Query($this->connection);
  1791. $query->delete()
  1792. ->from(['a ' => 'authors'])
  1793. ->where(['a.id !=' => 99]);
  1794. $result = $query->sql();
  1795. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, true);
  1796. $result = $query->execute();
  1797. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1798. $this->assertCount(self::AUTHOR_COUNT, $result);
  1799. }
  1800. /**
  1801. * Test a basic delete with no from() call.
  1802. *
  1803. * @return void
  1804. */
  1805. public function testDeleteNoFrom() {
  1806. $query = new Query($this->connection);
  1807. $query->delete('authors')
  1808. ->where('1 = 1');
  1809. $result = $query->sql();
  1810. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1811. $result = $query->execute();
  1812. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1813. $this->assertCount(self::AUTHOR_COUNT, $result);
  1814. }
  1815. /**
  1816. * Test setting select() & delete() modes.
  1817. *
  1818. * @return void
  1819. */
  1820. public function testSelectAndDeleteOnSameQuery() {
  1821. $query = new Query($this->connection);
  1822. $result = $query->select()
  1823. ->delete('authors')
  1824. ->where('1 = 1');
  1825. $result = $query->sql();
  1826. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1827. $this->assertContains(' WHERE 1 = 1', $result);
  1828. }
  1829. /**
  1830. * Test a simple update.
  1831. *
  1832. * @return void
  1833. */
  1834. public function testUpdateSimple() {
  1835. $query = new Query($this->connection);
  1836. $query->update('authors')
  1837. ->set('name', 'mark')
  1838. ->where(['id' => 1]);
  1839. $result = $query->sql();
  1840. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1841. $result = $query->execute();
  1842. $this->assertCount(1, $result);
  1843. }
  1844. /**
  1845. * Test update with multiple fields.
  1846. *
  1847. * @return void
  1848. */
  1849. public function testUpdateMultipleFields() {
  1850. $query = new Query($this->connection);
  1851. $query->update('articles')
  1852. ->set('title', 'mark', 'string')
  1853. ->set('body', 'some text', 'string')
  1854. ->where(['id' => 1]);
  1855. $result = $query->sql();
  1856. $this->assertQuotedQuery(
  1857. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1858. $result,
  1859. true
  1860. );
  1861. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1862. $result = $query->execute();
  1863. $this->assertCount(1, $result);
  1864. }
  1865. /**
  1866. * Test updating multiple fields with an array.
  1867. *
  1868. * @return void
  1869. */
  1870. public function testUpdateMultipleFieldsArray() {
  1871. $query = new Query($this->connection);
  1872. $query->update('articles')
  1873. ->set([
  1874. 'title' => 'mark',
  1875. 'body' => 'some text'
  1876. ], ['title' => 'string', 'body' => 'string'])
  1877. ->where(['id' => 1]);
  1878. $result = $query->sql();
  1879. $this->assertQuotedQuery(
  1880. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1881. $result,
  1882. true
  1883. );
  1884. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1885. $result = $query->execute();
  1886. $this->assertCount(1, $result);
  1887. }
  1888. /**
  1889. * Test updates with an expression.
  1890. *
  1891. * @return void
  1892. */
  1893. public function testUpdateWithExpression() {
  1894. $query = new Query($this->connection);
  1895. $expr = $query->newExpr('title = author_id');
  1896. $query->update('articles')
  1897. ->set($expr)
  1898. ->where(['id' => 1]);
  1899. $result = $query->sql();
  1900. $this->assertQuotedQuery(
  1901. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  1902. $result,
  1903. true
  1904. );
  1905. $result = $query->execute();
  1906. $this->assertCount(1, $result);
  1907. }
  1908. /**
  1909. * Test update with array fields and types.
  1910. *
  1911. * @return void
  1912. */
  1913. public function testUpdateArrayFields() {
  1914. $query = new Query($this->connection);
  1915. $date = new \DateTime;
  1916. $query->update('comments')
  1917. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  1918. ->where(['id' => 1]);
  1919. $result = $query->sql();
  1920. $this->assertQuotedQuery(
  1921. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  1922. $result,
  1923. true
  1924. );
  1925. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1926. $result = $query->execute();
  1927. $this->assertCount(1, $result);
  1928. $query = new Query($this->connection);
  1929. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  1930. $result = $result->fetchAll('assoc')[0]['created'];
  1931. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  1932. }
  1933. /**
  1934. * You cannot call values() before insert() it causes all sorts of pain.
  1935. *
  1936. * @expectedException \Cake\Database\Exception
  1937. * @return void
  1938. */
  1939. public function testInsertValuesBeforeInsertFailure() {
  1940. $query = new Query($this->connection);
  1941. $query->select('*')->values([
  1942. 'id' => 1,
  1943. 'title' => 'mark',
  1944. 'body' => 'test insert'
  1945. ]);
  1946. }
  1947. /**
  1948. * Inserting nothing should not generate an error.
  1949. *
  1950. * @expectedException RuntimeException
  1951. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  1952. * @return void
  1953. */
  1954. public function testInsertNothing() {
  1955. $query = new Query($this->connection);
  1956. $query->insert([]);
  1957. }
  1958. /**
  1959. * Test inserting a single row.
  1960. *
  1961. * @return void
  1962. */
  1963. public function testInsertSimple() {
  1964. $query = new Query($this->connection);
  1965. $query->insert(['title', 'body'])
  1966. ->into('articles')
  1967. ->values([
  1968. 'title' => 'mark',
  1969. 'body' => 'test insert'
  1970. ]);
  1971. $result = $query->sql();
  1972. $this->assertQuotedQuery(
  1973. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1974. 'VALUES \(:c0, :c1\)',
  1975. $result,
  1976. true
  1977. );
  1978. $result = $query->execute();
  1979. $this->assertCount(1, $result, '1 row should be inserted');
  1980. $expected = [
  1981. [
  1982. 'id' => 4,
  1983. 'author_id' => null,
  1984. 'title' => 'mark',
  1985. 'body' => 'test insert',
  1986. 'published' => 'N',
  1987. ]
  1988. ];
  1989. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  1990. }
  1991. /**
  1992. * Test an insert when not all the listed fields are provided.
  1993. * Columns should be matched up where possible.
  1994. *
  1995. * @return void
  1996. */
  1997. public function testInsertSparseRow() {
  1998. $query = new Query($this->connection);
  1999. $query->insert(['title', 'body'])
  2000. ->into('articles')
  2001. ->values([
  2002. 'title' => 'mark',
  2003. ]);
  2004. $result = $query->sql();
  2005. $this->assertQuotedQuery(
  2006. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  2007. 'VALUES \(:c0, :c1\)',
  2008. $result,
  2009. true
  2010. );
  2011. $result = $query->execute();
  2012. $this->assertCount(1, $result, '1 row should be inserted');
  2013. $expected = [
  2014. [
  2015. 'id' => 4,
  2016. 'author_id' => null,
  2017. 'title' => 'mark',
  2018. 'body' => null,
  2019. 'published' => 'N',
  2020. ]
  2021. ];
  2022. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  2023. }
  2024. /**
  2025. * Test inserting multiple rows with sparse data.
  2026. *
  2027. * @return void
  2028. */
  2029. public function testInsertMultipleRowsSparse() {
  2030. $query = new Query($this->connection);
  2031. $query->insert(['title', 'body'])
  2032. ->into('articles')
  2033. ->values([
  2034. 'body' => 'test insert'
  2035. ])
  2036. ->values([
  2037. 'title' => 'jose',
  2038. ]);
  2039. $result = $query->execute();
  2040. $this->assertCount(2, $result, '2 rows should be inserted');
  2041. $expected = [
  2042. [
  2043. 'id' => 4,
  2044. 'author_id' => null,
  2045. 'title' => null,
  2046. 'body' => 'test insert',
  2047. 'published' => 'N',
  2048. ],
  2049. [
  2050. 'id' => 5,
  2051. 'author_id' => null,
  2052. 'title' => 'jose',
  2053. 'body' => null,
  2054. 'published' => 'N',
  2055. ],
  2056. ];
  2057. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2058. }
  2059. /**
  2060. * Test that INSERT INTO ... SELECT works.
  2061. *
  2062. * @return void
  2063. */
  2064. public function testInsertFromSelect() {
  2065. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2066. ->from('authors')
  2067. ->where(['id' => 1]);
  2068. $query = new Query($this->connection);
  2069. $query->insert(
  2070. ['title', 'body', 'author_id'],
  2071. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2072. )
  2073. ->into('articles')
  2074. ->values($select);
  2075. $result = $query->sql();
  2076. $this->assertQuotedQuery(
  2077. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) SELECT',
  2078. $result,
  2079. true
  2080. );
  2081. $this->assertQuotedQuery(
  2082. 'SELECT <name>, \'some text\', 99 FROM <authors>', $result, true);
  2083. $result = $query->execute();
  2084. $this->assertCount(1, $result);
  2085. $result = (new Query($this->connection))->select('*')
  2086. ->from('articles')
  2087. ->where(['author_id' => 99])
  2088. ->execute();
  2089. $this->assertCount(1, $result);
  2090. $expected = [
  2091. 'id' => 4,
  2092. 'title' => 'mariano',
  2093. 'body' => 'some text',
  2094. 'author_id' => 99,
  2095. 'published' => 'N',
  2096. ];
  2097. $this->assertEquals($expected, $result->fetch('assoc'));
  2098. }
  2099. /**
  2100. * Test that an exception is raised when mixing query + array types.
  2101. *
  2102. * @expectedException \Cake\Database\Exception
  2103. */
  2104. public function testInsertFailureMixingTypesArrayFirst() {
  2105. $query = new Query($this->connection);
  2106. $query->insert(['name'])
  2107. ->into('articles')
  2108. ->values(['name' => 'mark'])
  2109. ->values(new Query($this->connection));
  2110. }
  2111. /**
  2112. * Test that an exception is raised when mixing query + array types.
  2113. *
  2114. * @expectedException \Cake\Database\Exception
  2115. */
  2116. public function testInsertFailureMixingTypesQueryFirst() {
  2117. $query = new Query($this->connection);
  2118. $query->insert(['name'])
  2119. ->into('articles')
  2120. ->values(new Query($this->connection))
  2121. ->values(['name' => 'mark']);
  2122. }
  2123. /**
  2124. * Test that insert can use expression objects as values.
  2125. *
  2126. * @return void
  2127. */
  2128. public function testInsertExpressionValues() {
  2129. $query = new Query($this->connection);
  2130. $query->insert(['title'])
  2131. ->into('articles')
  2132. ->values(['title' => $query->newExpr("SELECT 'jose'")]);
  2133. $result = $query->execute();
  2134. $this->assertCount(1, $result);
  2135. $subquery = new Query($this->connection);
  2136. $subquery->select(['name'])
  2137. ->from('authors')
  2138. ->where(['id' => 1]);
  2139. $query = new Query($this->connection);
  2140. $query->insert(['title'])
  2141. ->into('articles')
  2142. ->values(['title' => $subquery]);
  2143. $result = $query->execute();
  2144. $this->assertCount(1, $result);
  2145. }
  2146. /**
  2147. * Tests that functions are correctly transformed and their parameters are bound
  2148. *
  2149. * @group FunctionExpression
  2150. * @return void
  2151. */
  2152. public function testSQLFunctions() {
  2153. $query = new Query($this->connection);
  2154. $result = $query->select(
  2155. function ($q) {
  2156. return ['total' => $q->func()->count('*')];
  2157. }
  2158. )
  2159. ->from('articles')
  2160. ->execute();
  2161. $expected = [['total' => 3]];
  2162. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2163. $query = new Query($this->connection);
  2164. $result = $query->select([
  2165. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  2166. ])
  2167. ->from('articles')
  2168. ->order(['c' => 'ASC'])
  2169. ->execute();
  2170. $expected = [
  2171. ['c' => 'First Article is appended'],
  2172. ['c' => 'Second Article is appended'],
  2173. ['c' => 'Third Article is appended']
  2174. ];
  2175. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2176. $query = new Query($this->connection);
  2177. $result = $query
  2178. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2179. ->execute()
  2180. ->fetchAll('assoc');
  2181. $this->assertEquals(3, abs($result[0]['d']));
  2182. $query = new Query($this->connection);
  2183. $result = $query
  2184. ->select(['d' => $query->func()->now('date')])
  2185. ->execute();
  2186. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2187. $query = new Query($this->connection);
  2188. $result = $query
  2189. ->select(['d' => $query->func()->now('time')])
  2190. ->execute();
  2191. $this->assertWithinRange(
  2192. date('U'),
  2193. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2194. 1
  2195. );
  2196. $query = new Query($this->connection);
  2197. $result = $query
  2198. ->select(['d' => $query->func()->now()])
  2199. ->execute();
  2200. $this->assertWithinRange(
  2201. date('U'),
  2202. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2203. 1
  2204. );
  2205. }
  2206. /**
  2207. * Tests that default types are passed to functions accepting a $types param
  2208. *
  2209. * @return void
  2210. */
  2211. public function testDefaultTypes() {
  2212. $query = new Query($this->connection);
  2213. $this->assertEquals([], $query->defaultTypes());
  2214. $types = ['id' => 'integer', 'created' => 'datetime'];
  2215. $this->assertSame($query, $query->defaultTypes($types));
  2216. $this->assertSame($types, $query->defaultTypes());
  2217. $results = $query->select(['id', 'comment'])
  2218. ->from('comments')
  2219. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2220. ->execute();
  2221. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2222. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2223. // Now test default can be overridden
  2224. $types = ['created' => 'date'];
  2225. $results = $query
  2226. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2227. ->execute();
  2228. $this->assertCount(6, $results, 'All 6 rows should match.');
  2229. }
  2230. /**
  2231. * Tests parameter binding
  2232. *
  2233. * @return void
  2234. */
  2235. public function testBind() {
  2236. $query = new Query($this->connection);
  2237. $results = $query->select(['id', 'comment'])
  2238. ->from('comments')
  2239. ->where(['created BETWEEN :foo AND :bar'])
  2240. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2241. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2242. ->execute();
  2243. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2244. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2245. $query = new Query($this->connection);
  2246. $results = $query->select(['id', 'comment'])
  2247. ->from('comments')
  2248. ->where(['created BETWEEN :foo AND :bar'])
  2249. ->bind(':foo', '2007-03-18 10:50:00')
  2250. ->bind(':bar', '2007-03-18 10:52:00')
  2251. ->execute();
  2252. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2253. }
  2254. /**
  2255. * Test that epilog() will actually append a string to a select query
  2256. *
  2257. * @return void
  2258. */
  2259. public function testAppendSelect() {
  2260. $query = new Query($this->connection);
  2261. $sql = $query
  2262. ->select(['id', 'title'])
  2263. ->from('articles')
  2264. ->where(['id' => 1])
  2265. ->epilog('FOR UPDATE')
  2266. ->sql();
  2267. $this->assertContains('SELECT', $sql);
  2268. $this->assertContains('FROM', $sql);
  2269. $this->assertContains('WHERE', $sql);
  2270. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2271. }
  2272. /**
  2273. * Test that epilog() will actually append a string to an insert query
  2274. *
  2275. * @return void
  2276. */
  2277. public function testAppendInsert() {
  2278. $query = new Query($this->connection);
  2279. $sql = $query
  2280. ->insert(['id', 'title'])
  2281. ->into('articles')
  2282. ->values([1, 'a title'])
  2283. ->epilog('RETURNING id')
  2284. ->sql();
  2285. $this->assertContains('INSERT', $sql);
  2286. $this->assertContains('INTO', $sql);
  2287. $this->assertContains('VALUES', $sql);
  2288. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2289. }
  2290. /**
  2291. * Test that epilog() will actually append a string to an update query
  2292. *
  2293. * @return void
  2294. */
  2295. public function testAppendUpdate() {
  2296. $query = new Query($this->connection);
  2297. $sql = $query
  2298. ->update('articles')
  2299. ->set(['title' => 'foo'])
  2300. ->where(['id' => 1])
  2301. ->epilog('RETURNING id')
  2302. ->sql();
  2303. $this->assertContains('UPDATE', $sql);
  2304. $this->assertContains('SET', $sql);
  2305. $this->assertContains('WHERE', $sql);
  2306. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2307. }
  2308. /**
  2309. * Test that epilog() will actually append a string to a delete query
  2310. *
  2311. * @return void
  2312. */
  2313. public function testAppendDelete() {
  2314. $query = new Query($this->connection);
  2315. $sql = $query
  2316. ->delete('articles')
  2317. ->where(['id' => 1])
  2318. ->epilog('RETURNING id')
  2319. ->sql();
  2320. $this->assertContains('DELETE FROM', $sql);
  2321. $this->assertContains('WHERE', $sql);
  2322. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2323. }
  2324. /**
  2325. * Tests automatic identifier quoting in the select clause
  2326. *
  2327. * @return void
  2328. */
  2329. public function testQuotingSelectFieldsAndAlias() {
  2330. $this->connection->driver()->autoQuoting(true);
  2331. $query = new Query($this->connection);
  2332. $sql = $query->select(['something'])->sql();
  2333. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2334. $query = new Query($this->connection);
  2335. $sql = $query->select(['foo' => 'something'])->sql();
  2336. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2337. $query = new Query($this->connection);
  2338. $sql = $query->select(['foo' => 1])->sql();
  2339. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2340. $query = new Query($this->connection);
  2341. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2342. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2343. $query = new Query($this->connection);
  2344. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2345. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2346. $query = new Query($this->connection);
  2347. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2348. $this->assertQuotedQuery('<bar>', $sql);
  2349. }
  2350. /**
  2351. * Tests automatic identifier quoting in the from clause
  2352. *
  2353. * @return void
  2354. */
  2355. public function testQuotingFromAndAlias() {
  2356. $this->connection->driver()->autoQuoting(true);
  2357. $query = new Query($this->connection);
  2358. $sql = $query->select('*')->from(['something'])->sql();
  2359. $this->assertQuotedQuery('FROM <something>', $sql);
  2360. $query = new Query($this->connection);
  2361. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2362. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  2363. $query = new Query($this->connection);
  2364. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2365. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  2366. }
  2367. /**
  2368. * Tests automatic identifier quoting for DISTINCT ON
  2369. *
  2370. * @return void
  2371. */
  2372. public function testQuotingDistinctOn() {
  2373. $this->connection->driver()->autoQuoting(true);
  2374. $query = new Query($this->connection);
  2375. $sql = $query->select('*')->distinct(['something'])->sql();
  2376. $this->assertQuotedQuery('<something>', $sql);
  2377. }
  2378. /**
  2379. * Tests automatic identifier quoting in the join clause
  2380. *
  2381. * @return void
  2382. */
  2383. public function testQuotingJoinsAndAlias() {
  2384. $this->connection->driver()->autoQuoting(true);
  2385. $query = new Query($this->connection);
  2386. $sql = $query->select('*')->join(['something'])->sql();
  2387. $this->assertQuotedQuery('JOIN <something>', $sql);
  2388. $query = new Query($this->connection);
  2389. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2390. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2391. $query = new Query($this->connection);
  2392. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2393. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2394. }
  2395. /**
  2396. * Tests automatic identifier quoting in the group by clause
  2397. *
  2398. * @return void
  2399. */
  2400. public function testQuotingGroupBy() {
  2401. $this->connection->driver()->autoQuoting(true);
  2402. $query = new Query($this->connection);
  2403. $sql = $query->select('*')->group(['something'])->sql();
  2404. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2405. $query = new Query($this->connection);
  2406. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2407. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2408. $query = new Query($this->connection);
  2409. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2410. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2411. }
  2412. /**
  2413. * Tests automatic identifier quoting strings inside conditions expressions
  2414. *
  2415. * @return void
  2416. */
  2417. public function testQuotingExpressions() {
  2418. $this->connection->driver()->autoQuoting(true);
  2419. $query = new Query($this->connection);
  2420. $sql = $query->select('*')
  2421. ->where(['something' => 'value'])
  2422. ->sql();
  2423. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2424. $query = new Query($this->connection);
  2425. $sql = $query->select('*')
  2426. ->where([
  2427. 'something' => 'value',
  2428. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2429. ])
  2430. ->sql();
  2431. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2432. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2433. }
  2434. /**
  2435. * Tests that insert query parts get quoted automatically
  2436. *
  2437. * @return void
  2438. */
  2439. public function testQuotingInsert() {
  2440. $this->connection->driver()->autoQuoting(true);
  2441. $query = new Query($this->connection);
  2442. $sql = $query->insert(['bar', 'baz'])
  2443. ->into('foo')
  2444. ->where(['something' => 'value'])
  2445. ->sql();
  2446. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2447. $query = new Query($this->connection);
  2448. $sql = $query->insert([$query->newExpr('bar')])
  2449. ->into('foo')
  2450. ->where(['something' => 'value'])
  2451. ->sql();
  2452. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2453. }
  2454. /**
  2455. * Tests converting a query to a string
  2456. *
  2457. * @return void
  2458. */
  2459. public function testToString() {
  2460. $query = new Query($this->connection);
  2461. $query
  2462. ->select(['title'])
  2463. ->from('articles');
  2464. $result = (string)$query;
  2465. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, true);
  2466. }
  2467. /**
  2468. * Tests __debugInfo
  2469. *
  2470. * @return void
  2471. */
  2472. public function testDebugInfo() {
  2473. $query = (new Query($this->connection))->select('*')
  2474. ->from('articles')
  2475. ->defaultTypes(['id' => 'integer'])
  2476. ->where(['id' => '1']);
  2477. $expected = [
  2478. 'sql' => $query->sql(),
  2479. 'params' => [
  2480. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2481. ],
  2482. 'defaultTypes' => ['id' => 'integer'],
  2483. 'decorators' => 0,
  2484. 'executed' => false
  2485. ];
  2486. $result = $query->__debugInfo();
  2487. $this->assertEquals($expected, $result);
  2488. $query->execute();
  2489. $expected = [
  2490. 'sql' => $query->sql(),
  2491. 'params' => [
  2492. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2493. ],
  2494. 'defaultTypes' => ['id' => 'integer'],
  2495. 'decorators' => 0,
  2496. 'executed' => true
  2497. ];
  2498. $result = $query->__debugInfo();
  2499. $this->assertEquals($expected, $result);
  2500. }
  2501. /**
  2502. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2503. *
  2504. * @return void
  2505. */
  2506. public function testIsNullWithExpressions() {
  2507. $query = new Query($this->connection);
  2508. $subquery = (new Query($this->connection))
  2509. ->select(['id'])
  2510. ->from('authors')
  2511. ->where(['id' => 1]);
  2512. $result = $query
  2513. ->select(['name'])
  2514. ->from(['authors'])
  2515. ->where(function ($exp) use ($subquery) {
  2516. return $exp->isNotNull($subquery);
  2517. })
  2518. ->execute();
  2519. $this->assertNotEmpty($result->fetchAll('assoc'));
  2520. $result = (new Query($this->connection))
  2521. ->select(['name'])
  2522. ->from(['authors'])
  2523. ->where(function ($exp) use ($subquery) {
  2524. return $exp->isNull($subquery);
  2525. })
  2526. ->execute();
  2527. $this->assertEmpty($result->fetchAll('assoc'));
  2528. }
  2529. /**
  2530. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2531. * when using autoQuoting
  2532. *
  2533. * @return void
  2534. */
  2535. public function testIsNullAutoQuoting() {
  2536. $this->connection->driver()->autoQuoting(true);
  2537. $query = new Query($this->connection);
  2538. $query->select('*')->from('things')->where(function ($exp) {
  2539. return $exp->isNull('field');
  2540. });
  2541. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2542. $query = new Query($this->connection);
  2543. $query->select('*')->from('things')->where(function ($exp) {
  2544. return $exp->isNotNull('field');
  2545. });
  2546. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2547. }
  2548. /**
  2549. * Tests that using the IS operator will automatically translate to the best
  2550. * possible operator depending on the passed value
  2551. *
  2552. * @return void
  2553. */
  2554. public function testDirectIsNull() {
  2555. $sql = (new Query($this->connection))
  2556. ->select(['name'])
  2557. ->from(['authors'])
  2558. ->where(['name IS' => null])
  2559. ->sql();
  2560. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, true);
  2561. $results = (new Query($this->connection))
  2562. ->select(['name'])
  2563. ->from(['authors'])
  2564. ->where(['name IS' => 'larry'])
  2565. ->execute();
  2566. $this->assertCount(1, $results);
  2567. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  2568. }
  2569. /**
  2570. * Tests that case statements work correctly for various use-cases.
  2571. *
  2572. * @return void
  2573. */
  2574. public function testSqlCaseStatement() {
  2575. $query = new Query($this->connection);
  2576. $publishedCase = $query
  2577. ->newExpr()
  2578. ->addCase($query
  2579. ->newExpr()
  2580. ->add(['published' => 'Y']), 1, 'integer'
  2581. );
  2582. $notPublishedCase = $query
  2583. ->newExpr()
  2584. ->addCase($query
  2585. ->newExpr()
  2586. ->add(['published' => 'N']), 1, 'integer'
  2587. );
  2588. //Postgres requires the case statement to be cast to a integer
  2589. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  2590. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  2591. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  2592. }
  2593. $results = $query
  2594. ->select([
  2595. 'published' => $query->func()->sum($publishedCase),
  2596. 'not_published' => $query->func()->sum($notPublishedCase)
  2597. ])
  2598. ->from(['comments'])
  2599. ->execute()
  2600. ->fetchAll('assoc');
  2601. $this->assertEquals(5, $results[0]['published']);
  2602. $this->assertEquals(1, $results[0]['not_published']);
  2603. $query = new Query($this->connection);
  2604. $query
  2605. ->insert(['article_id', 'user_id', 'comment', 'published'])
  2606. ->into('comments')
  2607. ->values([
  2608. 'article_id' => 2,
  2609. 'user_id' => 1,
  2610. 'comment' => 'In limbo',
  2611. 'published' => 'L'
  2612. ])
  2613. ->execute();
  2614. $query = new Query($this->connection);
  2615. $conditions = [
  2616. $query
  2617. ->newExpr()
  2618. ->add(['published' => 'Y']),
  2619. $query
  2620. ->newExpr()
  2621. ->add(['published' => 'N'])
  2622. ];
  2623. $values = [
  2624. 'Published',
  2625. 'Not published',
  2626. 'None'
  2627. ];
  2628. $results = $query
  2629. ->select([
  2630. 'id',
  2631. 'comment',
  2632. 'status' => $query->newExpr()->addCase($conditions, $values)
  2633. ])
  2634. ->from(['comments'])
  2635. ->execute()
  2636. ->fetchAll('assoc');
  2637. $this->assertEquals('Published', $results[2]['status']);
  2638. $this->assertEquals('Not published', $results[3]['status']);
  2639. $this->assertEquals('None', $results[6]['status']);
  2640. }
  2641. /**
  2642. * Assertion for comparing a table's contents with what is in it.
  2643. *
  2644. * @param string $table
  2645. * @param int $count
  2646. * @param array $rows
  2647. * @param array $conditions
  2648. * @return void
  2649. */
  2650. public function assertTable($table, $count, $rows, $conditions = []) {
  2651. $result = (new Query($this->connection))->select('*')
  2652. ->from($table)
  2653. ->where($conditions)
  2654. ->execute();
  2655. $this->assertCount($count, $result, 'Row count is incorrect');
  2656. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2657. }
  2658. /**
  2659. * Assertion for comparing a regex pattern against a query having its identifiers
  2660. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2661. * parameter is set to true, it will alter the pattern to both accept quoted and
  2662. * unquoted queries
  2663. *
  2664. * @param string $pattern
  2665. * @param string $query the result to compare against
  2666. * @param bool $optional
  2667. * @return void
  2668. */
  2669. public function assertQuotedQuery($pattern, $query, $optional = false) {
  2670. if ($optional) {
  2671. $optional = '?';
  2672. }
  2673. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2674. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2675. $this->assertRegExp('#' . $pattern . '#', $query);
  2676. }
  2677. }