QueryTest.php 78 KB

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