QueryTest.php 65 KB

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