QueryTest.php 72 KB

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