QueryTest.php 71 KB

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