QueryTest.php 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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. * Test selecting rows using the page() method.
  1141. *
  1142. * @return void
  1143. */
  1144. public function testSelectPage() {
  1145. $query = new Query($this->connection);
  1146. $result = $query->select('id')->from('comments')
  1147. ->limit(1)
  1148. ->page(1)->execute();
  1149. $this->assertEquals(0, $query->clause('offset'));
  1150. $this->assertCount(1, $result);
  1151. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1152. $result = $query->page(2)->execute();
  1153. $this->assertEquals(1, $query->clause('offset'));
  1154. $this->assertCount(1, $result);
  1155. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1156. $query = new Query($this->connection);
  1157. $query->select('id')->from('comments')->page(1);
  1158. $this->assertEquals(25, $query->clause('limit'));
  1159. $this->assertEquals(0, $query->clause('offset'));
  1160. $query->select('id')->from('comments')->page(2);
  1161. $this->assertEquals(25, $query->clause('limit'));
  1162. $this->assertEquals(25, $query->clause('offset'));
  1163. }
  1164. /**
  1165. * Tests that Query objects can be included inside the select clause
  1166. * and be used as a normal field, including binding any passed parameter
  1167. *
  1168. * @return void
  1169. */
  1170. public function testSubqueryInSelect() {
  1171. $query = new Query($this->connection);
  1172. $subquery = (new Query($this->connection))
  1173. ->select('name')
  1174. ->from(['b' => 'authors'])
  1175. ->where(['b.id = a.id']);
  1176. $result = $query
  1177. ->select(['id', 'name' => $subquery])
  1178. ->from(['a' => 'comments'])->execute();
  1179. $expected = [
  1180. ['id' => 1, 'name' => 'mariano'],
  1181. ['id' => 2, 'name' => 'nate'],
  1182. ['id' => 3, 'name' => 'larry'],
  1183. ['id' => 4, 'name' => 'garrett'],
  1184. ['id' => 5, 'name' => null],
  1185. ['id' => 6, 'name' => null],
  1186. ];
  1187. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1188. $query = new Query($this->connection);
  1189. $subquery = (new Query($this->connection))
  1190. ->select('name')
  1191. ->from(['b' => 'authors'])
  1192. ->where(['name' => 'mariano'], ['name' => 'string']);
  1193. $result = $query
  1194. ->select(['id', 'name' => $subquery])
  1195. ->from(['a' => 'articles'])->execute();
  1196. $expected = [
  1197. ['id' => 1, 'name' => 'mariano'],
  1198. ['id' => 2, 'name' => 'mariano'],
  1199. ['id' => 3, 'name' => 'mariano'],
  1200. ];
  1201. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1202. }
  1203. /**
  1204. * Tests that Query objects can be included inside the from clause
  1205. * and be used as a normal table, including binding any passed parameter
  1206. *
  1207. * @return void
  1208. */
  1209. public function testSuqueryInFrom() {
  1210. $query = new Query($this->connection);
  1211. $subquery = (new Query($this->connection))
  1212. ->select(['id', 'comment'])
  1213. ->from('comments')
  1214. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1215. $result = $query
  1216. ->select(['say' => 'comment'])
  1217. ->from(['b' => $subquery])
  1218. ->where(['id !=' => 3])
  1219. ->execute();
  1220. $expected = [
  1221. ['say' => 'Second Comment for First Article'],
  1222. ['say' => 'Fourth Comment for First Article'],
  1223. ['say' => 'First Comment for Second Article'],
  1224. ['say' => 'Second Comment for Second Article'],
  1225. ];
  1226. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1227. }
  1228. /**
  1229. * Tests that Query objects can be included inside the where clause
  1230. * and be used as a normal condition, including binding any passed parameter
  1231. *
  1232. * @return void
  1233. */
  1234. public function testSubqueryInWhere() {
  1235. $query = new Query($this->connection);
  1236. $subquery = (new Query($this->connection))
  1237. ->select(['id'])
  1238. ->from('authors')
  1239. ->where(['id' => 1]);
  1240. $result = $query
  1241. ->select(['name'])
  1242. ->from(['authors'])
  1243. ->where(['id !=' => $subquery])
  1244. ->execute();
  1245. $expected = [
  1246. ['name' => 'nate'],
  1247. ['name' => 'larry'],
  1248. ['name' => 'garrett'],
  1249. ];
  1250. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1251. $query = new Query($this->connection);
  1252. $subquery = (new Query($this->connection))
  1253. ->select(['id'])
  1254. ->from('comments')
  1255. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1256. $result = $query
  1257. ->select(['name'])
  1258. ->from(['authors'])
  1259. ->where(['id not in' => $subquery])
  1260. ->execute();
  1261. $expected = [
  1262. ['name' => 'mariano'],
  1263. ];
  1264. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1265. }
  1266. /**
  1267. * Tests that it is possible to use a subquery in a join clause
  1268. *
  1269. * @return void
  1270. */
  1271. public function testSubqueyInJoin() {
  1272. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1273. $query = new Query($this->connection);
  1274. $result = $query
  1275. ->select(['title', 'name'])
  1276. ->from('articles')
  1277. ->join(['b' => $subquery])
  1278. ->execute();
  1279. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1280. $subquery->where(['id' => 1]);
  1281. $result = $query->execute();
  1282. $this->assertCount(3, $result);
  1283. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1284. $result = $query->execute();
  1285. $this->assertCount(1, $result);
  1286. }
  1287. /**
  1288. * Tests that it is possible to one or multiple UNION statements in a query
  1289. *
  1290. * @return void
  1291. */
  1292. public function testUnion() {
  1293. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1294. $query = new Query($this->connection);
  1295. $result = $query->select(['id', 'comment'])
  1296. ->from(['c' => 'comments'])
  1297. ->union($union)
  1298. ->execute();
  1299. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1300. $rows = $result->fetchAll();
  1301. $union->select(['foo' => 'id', 'bar' => 'title']);
  1302. $union = (new Query($this->connection))
  1303. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1304. ->from(['b' => 'authors'])
  1305. ->where(['id ' => 1])
  1306. ->order(['id' => 'desc']);
  1307. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1308. $result = $query->execute();
  1309. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1310. $this->assertNotEquals($rows, $result->fetchAll());
  1311. $union = (new Query($this->connection))
  1312. ->select(['id', 'title'])
  1313. ->from(['c' => 'articles']);
  1314. $query->select(['id', 'comment'], true)->union($union, true);
  1315. $result = $query->execute();
  1316. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1317. $this->assertEquals($rows, $result->fetchAll());
  1318. }
  1319. /**
  1320. * Tests that UNION ALL can be built by setting the second param of union() to true
  1321. *
  1322. * @return void
  1323. */
  1324. public function testUnionAll() {
  1325. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1326. $query = new Query($this->connection);
  1327. $result = $query->select(['id', 'comment'])
  1328. ->from(['c' => 'comments'])
  1329. ->union($union)
  1330. ->execute();
  1331. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1332. $rows = $result->fetchAll();
  1333. $union->select(['foo' => 'id', 'bar' => 'title']);
  1334. $union = (new Query($this->connection))
  1335. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1336. ->from(['b' => 'authors'])
  1337. ->where(['id ' => 1])
  1338. ->order(['id' => 'desc']);
  1339. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1340. $result = $query->execute();
  1341. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1342. $this->assertNotEquals($rows, $result->fetchAll());
  1343. }
  1344. /**
  1345. * Tests stacking decorators for results and resetting the list of decorators
  1346. *
  1347. * @return void
  1348. */
  1349. public function testDecorateResults() {
  1350. $query = new Query($this->connection);
  1351. $result = $query
  1352. ->select(['id', 'title'])
  1353. ->from('articles')
  1354. ->order(['id' => 'ASC'])
  1355. ->decorateResults(function($row) {
  1356. $row['modified_id'] = $row['id'] + 1;
  1357. return $row;
  1358. })
  1359. ->execute();
  1360. while ($row = $result->fetch('assoc')) {
  1361. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1362. }
  1363. $result = $query->decorateResults(function($row) {
  1364. $row['modified_id']--;
  1365. return $row;
  1366. })->execute();
  1367. while ($row = $result->fetch('assoc')) {
  1368. $this->assertEquals($row['id'], $row['modified_id']);
  1369. }
  1370. $result = $query
  1371. ->decorateResults(function($row) {
  1372. $row['foo'] = 'bar';
  1373. return $row;
  1374. }, true)
  1375. ->execute();
  1376. while ($row = $result->fetch('assoc')) {
  1377. $this->assertEquals('bar', $row['foo']);
  1378. $this->assertArrayNotHasKey('modified_id', $row);
  1379. }
  1380. $results = $query->decorateResults(null, true)->execute();
  1381. while ($row = $result->fetch('assoc')) {
  1382. $this->assertArrayNotHasKey('foo', $row);
  1383. $this->assertArrayNotHasKey('modified_id', $row);
  1384. }
  1385. }
  1386. /**
  1387. * Test a basic delete using from()
  1388. *
  1389. * @return void
  1390. */
  1391. public function testDeleteWithFrom() {
  1392. $query = new Query($this->connection);
  1393. $query->delete()
  1394. ->from('authors')
  1395. ->where('1 = 1');
  1396. $result = $query->sql();
  1397. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1398. $result = $query->execute();
  1399. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1400. $this->assertCount(self::AUTHOR_COUNT, $result);
  1401. }
  1402. /**
  1403. * Test a basic delete with no from() call.
  1404. *
  1405. * @return void
  1406. */
  1407. public function testDeleteNoFrom() {
  1408. $query = new Query($this->connection);
  1409. $query->delete('authors')
  1410. ->where('1 = 1');
  1411. $result = $query->sql();
  1412. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1413. $result = $query->execute();
  1414. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1415. $this->assertCount(self::AUTHOR_COUNT, $result);
  1416. }
  1417. /**
  1418. * Test setting select() & delete() modes.
  1419. *
  1420. * @return void
  1421. */
  1422. public function testSelectAndDeleteOnSameQuery() {
  1423. $query = new Query($this->connection);
  1424. $result = $query->select()
  1425. ->delete('authors')
  1426. ->where('1 = 1');
  1427. $result = $query->sql();
  1428. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1429. $this->assertContains(' WHERE 1 = 1', $result);
  1430. }
  1431. /**
  1432. * Test a simple update.
  1433. *
  1434. * @return void
  1435. */
  1436. public function testUpdateSimple() {
  1437. $query = new Query($this->connection);
  1438. $query->update('authors')
  1439. ->set('name', 'mark')
  1440. ->where(['id' => 1]);
  1441. $result = $query->sql();
  1442. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1443. $result = $query->execute();
  1444. $this->assertCount(1, $result);
  1445. }
  1446. /**
  1447. * Test update with multiple fields.
  1448. *
  1449. * @return void
  1450. */
  1451. public function testUpdateMultipleFields() {
  1452. $query = new Query($this->connection);
  1453. $query->update('articles')
  1454. ->set('title', 'mark', 'string')
  1455. ->set('body', 'some text', 'string')
  1456. ->where(['id' => 1]);
  1457. $result = $query->sql();
  1458. $this->assertQuotedQuery(
  1459. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1460. $result,
  1461. true
  1462. );
  1463. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1464. $result = $query->execute();
  1465. $this->assertCount(1, $result);
  1466. }
  1467. /**
  1468. * Test updating multiple fields with an array.
  1469. *
  1470. * @return void
  1471. */
  1472. public function testUpdateMultipleFieldsArray() {
  1473. $query = new Query($this->connection);
  1474. $query->update('articles')
  1475. ->set([
  1476. 'title' => 'mark',
  1477. 'body' => 'some text'
  1478. ], ['title' => 'string', 'body' => 'string'])
  1479. ->where(['id' => 1]);
  1480. $result = $query->sql();
  1481. $this->assertQuotedQuery(
  1482. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1483. $result,
  1484. true
  1485. );
  1486. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1487. $result = $query->execute();
  1488. $this->assertCount(1, $result);
  1489. }
  1490. /**
  1491. * Test updates with an expression.
  1492. *
  1493. * @return void
  1494. */
  1495. public function testUpdateWithExpression() {
  1496. $query = new Query($this->connection);
  1497. $expr = $query->newExpr();
  1498. $expr->add('title = author_id');
  1499. $query->update('articles')
  1500. ->set($expr)
  1501. ->where(['id' => 1]);
  1502. $result = $query->sql();
  1503. $this->assertQuotedQuery(
  1504. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  1505. $result,
  1506. true
  1507. );
  1508. $result = $query->execute();
  1509. $this->assertCount(1, $result);
  1510. }
  1511. /**
  1512. * You cannot call values() before insert() it causes all sorts of pain.
  1513. *
  1514. * @expectedException Cake\Error\Exception
  1515. * @return void
  1516. */
  1517. public function testInsertValuesBeforeInsertFailure() {
  1518. $query = new Query($this->connection);
  1519. $query->select('*')->values([
  1520. 'id' => 1,
  1521. 'title' => 'mark',
  1522. 'body' => 'test insert'
  1523. ]);
  1524. }
  1525. /**
  1526. * Test inserting a single row.
  1527. *
  1528. * @return void
  1529. */
  1530. public function testInsertSimple() {
  1531. $query = new Query($this->connection);
  1532. $query->insert(['title', 'body'])
  1533. ->into('articles')
  1534. ->values([
  1535. 'title' => 'mark',
  1536. 'body' => 'test insert'
  1537. ]);
  1538. $result = $query->sql();
  1539. $this->assertQuotedQuery(
  1540. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1541. 'VALUES \(\?, \?\)',
  1542. $result,
  1543. true
  1544. );
  1545. $result = $query->execute();
  1546. $this->assertCount(1, $result, '1 row should be inserted');
  1547. $expected = [
  1548. [
  1549. 'id' => 4,
  1550. 'author_id' => null,
  1551. 'title' => 'mark',
  1552. 'body' => 'test insert',
  1553. 'published' => 'N',
  1554. ]
  1555. ];
  1556. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  1557. }
  1558. /**
  1559. * Test an insert when not all the listed fields are provided.
  1560. * Columns should be matched up where possible.
  1561. *
  1562. * @return void
  1563. */
  1564. public function testInsertSparseRow() {
  1565. $query = new Query($this->connection);
  1566. $query->insert(['title', 'body'])
  1567. ->into('articles')
  1568. ->values([
  1569. 'title' => 'mark',
  1570. ]);
  1571. $result = $query->sql();
  1572. $this->assertQuotedQuery(
  1573. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1574. 'VALUES \(\?, \?\)',
  1575. $result,
  1576. true
  1577. );
  1578. $result = $query->execute();
  1579. $this->assertCount(1, $result, '1 row should be inserted');
  1580. $expected = [
  1581. [
  1582. 'id' => 4,
  1583. 'author_id' => null,
  1584. 'title' => 'mark',
  1585. 'body' => null,
  1586. 'published' => 'N',
  1587. ]
  1588. ];
  1589. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  1590. }
  1591. /**
  1592. * Test inserting multiple rows with sparse data.
  1593. *
  1594. * @return void
  1595. */
  1596. public function testInsertMultipleRowsSparse() {
  1597. $query = new Query($this->connection);
  1598. $query->insert(['title', 'body'])
  1599. ->into('articles')
  1600. ->values([
  1601. 'body' => 'test insert'
  1602. ])
  1603. ->values([
  1604. 'title' => 'jose',
  1605. ]);
  1606. $result = $query->execute();
  1607. $this->assertCount(2, $result, '2 rows should be inserted');
  1608. $expected = [
  1609. [
  1610. 'id' => 4,
  1611. 'author_id' => null,
  1612. 'title' => null,
  1613. 'body' => 'test insert',
  1614. 'published' => 'N',
  1615. ],
  1616. [
  1617. 'id' => 5,
  1618. 'author_id' => null,
  1619. 'title' => 'jose',
  1620. 'body' => null,
  1621. 'published' => 'N',
  1622. ],
  1623. ];
  1624. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  1625. }
  1626. /**
  1627. * Test that INSERT INTO ... SELECT works.
  1628. *
  1629. * @return void
  1630. */
  1631. public function testInsertFromSelect() {
  1632. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  1633. ->from('authors')
  1634. ->where(['id' => 1]);
  1635. $query = new Query($this->connection);
  1636. $query->insert(
  1637. ['title', 'body', 'author_id'],
  1638. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  1639. )
  1640. ->into('articles')
  1641. ->values($select);
  1642. $result = $query->sql();
  1643. $this->assertQuotedQuery(
  1644. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) SELECT',
  1645. $result,
  1646. true
  1647. );
  1648. $this->assertQuotedQuery(
  1649. 'SELECT <name>, \'some text\', 99 FROM <authors>', $result, true);
  1650. $result = $query->execute();
  1651. $this->assertCount(1, $result);
  1652. $result = (new Query($this->connection))->select('*')
  1653. ->from('articles')
  1654. ->where(['author_id' => 99])
  1655. ->execute();
  1656. $this->assertCount(1, $result);
  1657. $expected = [
  1658. 'id' => 4,
  1659. 'title' => 'mariano',
  1660. 'body' => 'some text',
  1661. 'author_id' => 99,
  1662. 'published' => 'N',
  1663. ];
  1664. $this->assertEquals($expected, $result->fetch('assoc'));
  1665. }
  1666. /**
  1667. * Test that an exception is raised when mixing query + array types.
  1668. *
  1669. * @expectedException Cake\Error\Exception
  1670. */
  1671. public function testInsertFailureMixingTypesArrayFirst() {
  1672. $query = new Query($this->connection);
  1673. $query->insert(['name'])
  1674. ->into('articles')
  1675. ->values(['name' => 'mark'])
  1676. ->values(new Query($this->connection));
  1677. }
  1678. /**
  1679. * Test that an exception is raised when mixing query + array types.
  1680. *
  1681. * @expectedException Cake\Error\Exception
  1682. */
  1683. public function testInsertFailureMixingTypesQueryFirst() {
  1684. $query = new Query($this->connection);
  1685. $query->insert(['name'])
  1686. ->into('articles')
  1687. ->values(new Query($this->connection))
  1688. ->values(['name' => 'mark']);
  1689. }
  1690. /**
  1691. * Tests that functions are correctly transformed and their parameters are bound
  1692. *
  1693. * @group FunctionExpression
  1694. * @return void
  1695. */
  1696. public function testSQLFunctions() {
  1697. $query = new Query($this->connection);
  1698. $result = $query->select(
  1699. function($q) {
  1700. return ['total' => $q->func()->count('*')];
  1701. }
  1702. )
  1703. ->from('articles')
  1704. ->execute();
  1705. $expected = [['total' => 3]];
  1706. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1707. $query = new Query($this->connection);
  1708. $result = $query->select([
  1709. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  1710. ])
  1711. ->from('articles')
  1712. ->order(['c' => 'ASC'])
  1713. ->execute();
  1714. $expected = [
  1715. ['c' => 'First Article is appended'],
  1716. ['c' => 'Second Article is appended'],
  1717. ['c' => 'Third Article is appended']
  1718. ];
  1719. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1720. $query = new Query($this->connection);
  1721. $result = $query
  1722. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  1723. ->execute();
  1724. $this->assertEquals([['d' => '3.0']], $result->fetchAll('assoc'));
  1725. $query = new Query($this->connection);
  1726. $result = $query
  1727. ->select(['d' => $query->func()->now('date')])
  1728. ->execute();
  1729. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  1730. $query = new Query($this->connection);
  1731. $result = $query
  1732. ->select(['d' => $query->func()->now('time')])
  1733. ->execute();
  1734. $this->assertWithinMargin(
  1735. date('U'),
  1736. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1737. 1
  1738. );
  1739. $query = new Query($this->connection);
  1740. $result = $query
  1741. ->select(['d' => $query->func()->now()])
  1742. ->execute();
  1743. $this->assertWithinMargin(
  1744. date('U'),
  1745. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1746. 1
  1747. );
  1748. }
  1749. /**
  1750. * Tests that default types are passed to functions accepting a $types param
  1751. *
  1752. * @return void
  1753. */
  1754. public function testDefaultTypes() {
  1755. $query = new Query($this->connection);
  1756. $this->assertEquals([], $query->defaultTypes());
  1757. $types = ['id' => 'integer', 'created' => 'datetime'];
  1758. $this->assertSame($query, $query->defaultTypes($types));
  1759. $this->assertSame($types, $query->defaultTypes());
  1760. $results = $query->select(['id', 'comment'])
  1761. ->from('comments')
  1762. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  1763. ->execute();
  1764. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  1765. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1766. // Now test default can be overridden
  1767. $types = ['created' => 'date'];
  1768. $results = $query
  1769. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  1770. ->execute();
  1771. $this->assertCount(6, $results, 'All 6 rows should match.');
  1772. }
  1773. /**
  1774. * Tests parameter binding
  1775. *
  1776. * @return void
  1777. */
  1778. public function testBind() {
  1779. $query = new Query($this->connection);
  1780. $results = $query->select(['id', 'comment'])
  1781. ->from('comments')
  1782. ->where(['created BETWEEN :foo AND :bar'])
  1783. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  1784. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  1785. ->execute();
  1786. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  1787. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1788. $query = new Query($this->connection);
  1789. $results = $query->select(['id', 'comment'])
  1790. ->from('comments')
  1791. ->where(['created BETWEEN :foo AND :bar'])
  1792. ->bind(':foo', '2007-03-18 10:50:00')
  1793. ->bind(':bar', '2007-03-18 10:52:00')
  1794. ->execute();
  1795. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1796. }
  1797. /**
  1798. * Test that epilog() will actually append a string to a select query
  1799. *
  1800. * @return void
  1801. */
  1802. public function testAppendSelect() {
  1803. $query = new Query($this->connection);
  1804. $sql = $query
  1805. ->select(['id', 'title'])
  1806. ->from('articles')
  1807. ->where(['id' => 1])
  1808. ->epilog('FOR UPDATE')
  1809. ->sql();
  1810. $this->assertContains('SELECT', $sql);
  1811. $this->assertContains('FROM', $sql);
  1812. $this->assertContains('WHERE', $sql);
  1813. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  1814. }
  1815. /**
  1816. * Test that epilog() will actually append a string to an insert query
  1817. *
  1818. * @return void
  1819. */
  1820. public function testAppendInsert() {
  1821. $query = new Query($this->connection);
  1822. $sql = $query
  1823. ->insert(['id', 'title'])
  1824. ->into('articles')
  1825. ->values([1, 'a title'])
  1826. ->epilog('RETURNING id')
  1827. ->sql();
  1828. $this->assertContains('INSERT', $sql);
  1829. $this->assertContains('INTO', $sql);
  1830. $this->assertContains('VALUES', $sql);
  1831. $this->assertEquals(' RETURNING id', substr($sql, -13));
  1832. }
  1833. /**
  1834. * Test that epilog() will actually append a string to an update query
  1835. *
  1836. * @return void
  1837. */
  1838. public function testAppendUpdate() {
  1839. $query = new Query($this->connection);
  1840. $sql = $query
  1841. ->update('articles')
  1842. ->set(['title' => 'foo'])
  1843. ->where(['id' => 1])
  1844. ->epilog('RETURNING id')
  1845. ->sql();
  1846. $this->assertContains('UPDATE', $sql);
  1847. $this->assertContains('SET', $sql);
  1848. $this->assertContains('WHERE', $sql);
  1849. $this->assertEquals(' RETURNING id', substr($sql, -13));
  1850. }
  1851. /**
  1852. * Test that epilog() will actually append a string to a delete query
  1853. *
  1854. * @return void
  1855. */
  1856. public function testAppendDelete() {
  1857. $query = new Query($this->connection);
  1858. $sql = $query
  1859. ->delete('articles')
  1860. ->where(['id' => 1])
  1861. ->epilog('RETURNING id')
  1862. ->sql();
  1863. $this->assertContains('DELETE FROM', $sql);
  1864. $this->assertContains('WHERE', $sql);
  1865. $this->assertEquals(' RETURNING id', substr($sql, -13));
  1866. }
  1867. /**
  1868. * Tests automatic identifier quoting in the select clause
  1869. *
  1870. * @return void
  1871. */
  1872. public function testQuotingSelectFieldsAndAlias() {
  1873. $this->connection->driver()->autoQuoting(true);
  1874. $query = new Query($this->connection);
  1875. $sql = $query->select(['something'])->sql();
  1876. $this->assertQuotedQuery('SELECT <something>$', $sql);
  1877. $query = new Query($this->connection);
  1878. $sql = $query->select(['foo' => 'something'])->sql();
  1879. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  1880. $query = new Query($this->connection);
  1881. $sql = $query->select(['foo' => 1])->sql();
  1882. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  1883. $query = new Query($this->connection);
  1884. $sql = $query->select(['foo' => '1 + 1'])->sql();
  1885. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  1886. $query = new Query($this->connection);
  1887. $sql = $query->select(['foo' => $query->newExpr()->add('1 + 1')])->sql();
  1888. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  1889. $query = new Query($this->connection);
  1890. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  1891. $this->assertQuotedQuery('<bar>', $sql);
  1892. }
  1893. /**
  1894. * Tests automatic identifier quoting in the from clause
  1895. *
  1896. * @return void
  1897. */
  1898. public function testQuotingFromAndAlias() {
  1899. $this->connection->driver()->autoQuoting(true);
  1900. $query = new Query($this->connection);
  1901. $sql = $query->select('*')->from(['something'])->sql();
  1902. $this->assertQuotedQuery('FROM <something>', $sql);
  1903. $query = new Query($this->connection);
  1904. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  1905. $this->assertQuotedQuery('FROM <something> AS <foo>$', $sql);
  1906. $query = new Query($this->connection);
  1907. $sql = $query->select('*')->from(['foo' => $query->newExpr()->add('bar')])->sql();
  1908. $this->assertQuotedQuery('FROM \(bar\) AS <foo>$', $sql);
  1909. }
  1910. /**
  1911. * Tests automatic identifier quoting for DISTINCT ON
  1912. *
  1913. * @return void
  1914. */
  1915. public function testQuotingDistinctOn() {
  1916. $this->connection->driver()->autoQuoting(true);
  1917. $query = new Query($this->connection);
  1918. $sql = $query->select('*')->distinct(['something'])->sql();
  1919. $this->assertQuotedQuery('<something>', $sql);
  1920. }
  1921. /**
  1922. * Tests automatic identifier quoting in the join clause
  1923. *
  1924. * @return void
  1925. */
  1926. public function testQuotingJoinsAndAlias() {
  1927. $this->connection->driver()->autoQuoting(true);
  1928. $query = new Query($this->connection);
  1929. $sql = $query->select('*')->join(['something'])->sql();
  1930. $this->assertQuotedQuery('JOIN <something>', $sql);
  1931. $query = new Query($this->connection);
  1932. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  1933. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  1934. $query = new Query($this->connection);
  1935. $sql = $query->select('*')->join(['foo' => $query->newExpr()->add('bar')])->sql();
  1936. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  1937. }
  1938. /**
  1939. * Tests automatic identifier quoting in the group by clause
  1940. *
  1941. * @return void
  1942. */
  1943. public function testQuotingGroupBy() {
  1944. $this->connection->driver()->autoQuoting(true);
  1945. $query = new Query($this->connection);
  1946. $sql = $query->select('*')->group(['something'])->sql();
  1947. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  1948. $query = new Query($this->connection);
  1949. $sql = $query->select('*')->group([$query->newExpr()->add('bar')])->sql();
  1950. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  1951. $query = new Query($this->connection);
  1952. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  1953. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  1954. }
  1955. /**
  1956. * Tests automatic identifier quoting strings inside conditions expressions
  1957. *
  1958. * @return void
  1959. */
  1960. public function testQuotingExpressions() {
  1961. $this->connection->driver()->autoQuoting(true);
  1962. $query = new Query($this->connection);
  1963. $sql = $query->select('*')
  1964. ->where(['something' => 'value'])
  1965. ->sql();
  1966. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  1967. $query = new Query($this->connection);
  1968. $sql = $query->select('*')
  1969. ->where([
  1970. 'something' => 'value',
  1971. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  1972. ])
  1973. ->sql();
  1974. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  1975. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  1976. }
  1977. /**
  1978. * Tests that insert query parts get quoted automatically
  1979. *
  1980. * @return void
  1981. */
  1982. public function testQuotingInsert() {
  1983. $this->connection->driver()->autoQuoting(true);
  1984. $query = new Query($this->connection);
  1985. $sql = $query->insert(['bar', 'baz'])
  1986. ->into('foo')
  1987. ->where(['something' => 'value'])
  1988. ->sql();
  1989. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  1990. $query = new Query($this->connection);
  1991. $sql = $query->insert([$query->newExpr()->add('bar')])
  1992. ->into('foo')
  1993. ->where(['something' => 'value'])
  1994. ->sql();
  1995. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  1996. }
  1997. /**
  1998. * Assertion for comparing a table's contents with what is in it.
  1999. *
  2000. * @param string $table
  2001. * @param integer $count
  2002. * @param array $rows
  2003. * @return void
  2004. */
  2005. public function assertTable($table, $count, $rows, $conditions = []) {
  2006. $result = (new Query($this->connection))->select('*')
  2007. ->from($table)
  2008. ->where($conditions)
  2009. ->execute();
  2010. $this->assertCount($count, $result, 'Row count is incorrect');
  2011. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2012. }
  2013. /**
  2014. * Assertion for comparing a regex pattern against a query having its indentifiers
  2015. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2016. * parameter is set to true, it will alter the pattern to both accept quoted and
  2017. * unquoted queries
  2018. *
  2019. * @param string $pattern
  2020. * @param string $query the result to compare against
  2021. * @param boolean $optional
  2022. * @return void
  2023. */
  2024. public function assertQuotedQuery($pattern, $query, $optional = false) {
  2025. if ($optional) {
  2026. $optional = '?';
  2027. }
  2028. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2029. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2030. $this->assertRegExp('#' . $pattern . '#', $query);
  2031. }
  2032. }