QueryTest.php 85 KB

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