QueryTest.php 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712
  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\Database\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * Tests Query class
  24. *
  25. */
  26. class QueryTest extends TestCase
  27. {
  28. public $fixtures = ['core.articles', 'core.authors', 'core.comments'];
  29. const ARTICLE_COUNT = 3;
  30. const AUTHOR_COUNT = 4;
  31. const COMMENT_COUNT = 6;
  32. public function setUp()
  33. {
  34. parent::setUp();
  35. $this->connection = ConnectionManager::get('test');
  36. $this->autoQuote = $this->connection->driver()->autoQuoting();
  37. }
  38. public function tearDown()
  39. {
  40. parent::tearDown();
  41. $this->connection->driver()->autoQuoting($this->autoQuote);
  42. unset($this->connection);
  43. }
  44. /**
  45. * Queries need a default type to prevent fatal errors
  46. * when an uninitialized query has its sql() method called.
  47. *
  48. * @return void
  49. */
  50. public function testDefaultType()
  51. {
  52. $query = new Query($this->connection);
  53. $this->assertEquals('', $query->sql());
  54. $this->assertEquals('select', $query->type());
  55. }
  56. /**
  57. * Tests that it is possible to obtain expression results from a query
  58. *
  59. * @return void
  60. */
  61. public function testSelectFieldsOnly()
  62. {
  63. $this->connection->driver()->autoQuoting(false);
  64. $query = new Query($this->connection);
  65. $result = $query->select('1 + 1')->execute();
  66. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  67. $this->assertEquals([2], $result->fetch());
  68. //This new field should be appended
  69. $result = $query->select(['1 + 3'])->execute();
  70. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  71. $this->assertEquals([2, 4], $result->fetch());
  72. //This should now overwrite all previous fields
  73. $result = $query->select(['1 + 2', '1 + 5'], true)->execute();
  74. $this->assertEquals([3, 6], $result->fetch());
  75. }
  76. /**
  77. * Tests that it is possible to pass a closure as fields in select()
  78. *
  79. * @return void
  80. */
  81. public function testSelectClosure()
  82. {
  83. $this->connection->driver()->autoQuoting(false);
  84. $query = new Query($this->connection);
  85. $result = $query->select(function ($q) use ($query) {
  86. $this->assertSame($query, $q);
  87. return ['1 + 2', '1 + 5'];
  88. })->execute();
  89. $this->assertEquals([3, 6], $result->fetch());
  90. }
  91. /**
  92. * Tests it is possible to select fields from tables with no conditions
  93. *
  94. * @return void
  95. */
  96. public function testSelectFieldsFromTable()
  97. {
  98. $query = new Query($this->connection);
  99. $result = $query->select(['body', 'author_id'])->from('articles')->execute();
  100. $this->assertEquals(['body' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
  101. $this->assertEquals(['body' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
  102. //Append more tables to next execution
  103. $result = $query->select('name')->from(['authors'])->order(['name' => 'desc', 'articles.id' => 'asc'])->execute();
  104. $this->assertEquals(['body' => 'First Article Body', 'author_id' => 1, 'name' => 'nate'], $result->fetch('assoc'));
  105. $this->assertEquals(['body' => 'Second Article Body', 'author_id' => 3, 'name' => 'nate'], $result->fetch('assoc'));
  106. $this->assertEquals(['body' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'], $result->fetch('assoc'));
  107. // Overwrite tables and only fetch from authors
  108. $result = $query->select('name', true)->from('authors', true)->order(['name' => 'desc'], true)->execute();
  109. $this->assertEquals(['nate'], $result->fetch());
  110. $this->assertEquals(['mariano'], $result->fetch());
  111. $this->assertCount(4, $result);
  112. }
  113. /**
  114. * Tests it is possible to select aliased fields
  115. *
  116. * @return void
  117. */
  118. public function testSelectAliasedFieldsFromTable()
  119. {
  120. $query = new Query($this->connection);
  121. $result = $query->select(['text' => 'comment', 'article_id'])->from('comments')->execute();
  122. $this->assertEquals(['text' => 'First Comment for First Article', 'article_id' => 1], $result->fetch('assoc'));
  123. $this->assertEquals(['text' => 'Second Comment for First Article', 'article_id' => 1], $result->fetch('assoc'));
  124. $query = new Query($this->connection);
  125. $result = $query->select(['text' => 'comment', 'article' => 'article_id'])->from('comments')->execute();
  126. $this->assertEquals(['text' => 'First Comment for First Article', 'article' => 1], $result->fetch('assoc'));
  127. $this->assertEquals(['text' => 'Second Comment for First Article', 'article' => 1], $result->fetch('assoc'));
  128. $query = new Query($this->connection);
  129. $query->select(['text' => 'comment'])->select(['article_id', 'foo' => 'comment']);
  130. $result = $query->from('comments')->execute();
  131. $this->assertEquals(
  132. ['foo' => 'First Comment for First Article', 'text' => 'First Comment for First Article', 'article_id' => 1],
  133. $result->fetch('assoc')
  134. );
  135. $query = new Query($this->connection);
  136. $exp = $query->newExpr('1 + 1');
  137. $comp = $query->newExpr(['article_id +' => 2]);
  138. $result = $query->select(['text' => 'comment', 'two' => $exp, 'three' => $comp])
  139. ->from('comments')->execute();
  140. $this->assertEquals(['text' => 'First Comment for First Article', 'two' => 2, 'three' => 3], $result->fetch('assoc'));
  141. }
  142. /**
  143. * Tests that tables can also be aliased and referenced in the select clause using such alias
  144. *
  145. * @return void
  146. */
  147. public function testSelectAliasedTables()
  148. {
  149. $query = new Query($this->connection);
  150. $result = $query->select(['text' => 'a.body', 'a.author_id'])
  151. ->from(['a' => 'articles'])->execute();
  152. $this->assertEquals(['text' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
  153. $this->assertEquals(['text' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
  154. $result = $query->select(['name' => 'b.name'])->from(['b' => 'authors'])
  155. ->order(['text' => 'desc', 'name' => 'desc'])
  156. ->execute();
  157. $this->assertEquals(
  158. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'],
  159. $result->fetch('assoc')
  160. );
  161. $this->assertEquals(
  162. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'mariano'],
  163. $result->fetch('assoc')
  164. );
  165. }
  166. /**
  167. * Tests it is possible to add joins to a select query
  168. *
  169. * @return void
  170. */
  171. public function testSelectWithJoins()
  172. {
  173. $query = new Query($this->connection);
  174. $result = $query
  175. ->select(['title', 'name'])
  176. ->from('articles')
  177. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  178. ->order(['title' => 'asc'])
  179. ->execute();
  180. $this->assertCount(3, $result);
  181. $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
  182. $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
  183. $result = $query->join('authors', [], true)->execute();
  184. $this->assertCount(12, $result, 'Cross join results in 12 records');
  185. $result = $query->join([
  186. ['table' => 'authors', 'type' => 'INNER', 'conditions' => $query->newExpr()->equalFields('author_id', 'authors.id')]
  187. ], [], true)->execute();
  188. $this->assertCount(3, $result);
  189. $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
  190. $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
  191. }
  192. /**
  193. * Tests it is possible to add joins to a select query using array or expression as conditions
  194. *
  195. * @return void
  196. */
  197. public function testSelectWithJoinsConditions()
  198. {
  199. $query = new Query($this->connection);
  200. $result = $query
  201. ->select(['title', 'name'])
  202. ->from('articles')
  203. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => [$query->newExpr()->equalFields('author_id ', 'a.id')]])
  204. ->order(['title' => 'asc'])
  205. ->execute();
  206. $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
  207. $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
  208. $query = new Query($this->connection);
  209. $conditions = $query->newExpr()->equalFields('author_id', 'a.id');
  210. $result = $query
  211. ->select(['title', 'name'])
  212. ->from('articles')
  213. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $conditions])
  214. ->order(['title' => 'asc'])
  215. ->execute();
  216. $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
  217. $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
  218. $query = new Query($this->connection);
  219. $time = new \DateTime('2007-03-18 10:50:00');
  220. $types = ['created' => 'datetime'];
  221. $result = $query
  222. ->select(['title', 'comment' => 'c.comment'])
  223. ->from('articles')
  224. ->join(['table' => 'comments', 'alias' => 'c', 'conditions' => ['created <=' => $time]], $types)
  225. ->execute();
  226. $this->assertEquals(['title' => 'First Article', 'comment' => 'First Comment for First Article'], $result->fetch('assoc'));
  227. }
  228. /**
  229. * Tests that joins can be aliased using array keys
  230. *
  231. * @return void
  232. */
  233. public function testSelectAliasedJoins()
  234. {
  235. $query = new Query($this->connection);
  236. $result = $query
  237. ->select(['title', 'name'])
  238. ->from('articles')
  239. ->join(['a' => 'authors'])
  240. ->order(['name' => 'desc', 'articles.id' => 'asc'])
  241. ->execute();
  242. $this->assertEquals(['title' => 'First Article', 'name' => 'nate'], $result->fetch('assoc'));
  243. $this->assertEquals(['title' => 'Second Article', 'name' => 'nate'], $result->fetch('assoc'));
  244. $query = new Query($this->connection);
  245. $conditions = $query->newExpr('author_id = a.id');
  246. $result = $query
  247. ->select(['title', 'name'])
  248. ->from('articles')
  249. ->join(['a' => ['table' => 'authors', 'conditions' => $conditions]])
  250. ->order(['title' => 'asc'])
  251. ->execute();
  252. $this->assertEquals(['title' => 'First Article', 'name' => 'mariano'], $result->fetch('assoc'));
  253. $this->assertEquals(['title' => 'Second Article', 'name' => 'larry'], $result->fetch('assoc'));
  254. $query = new Query($this->connection);
  255. $time = new \DateTime('2007-03-18 10:45:23');
  256. $types = ['created' => 'datetime'];
  257. $result = $query
  258. ->select(['title', 'name' => 'c.comment'])
  259. ->from('articles')
  260. ->join(['c' => ['table' => 'comments', 'conditions' => ['created' => $time]]], $types)
  261. ->execute();
  262. $this->assertEquals(['title' => 'First Article', 'name' => 'First Comment for First Article'], $result->fetch('assoc'));
  263. }
  264. /**
  265. * Tests the leftJoin method
  266. *
  267. * @return void
  268. */
  269. public function testSelectLeftJoin()
  270. {
  271. $query = new Query($this->connection);
  272. $time = new \DateTime('2007-03-18 10:45:23');
  273. $types = ['created' => 'datetime'];
  274. $result = $query
  275. ->select(['title', 'name' => 'c.comment'])
  276. ->from('articles')
  277. ->leftJoin(['c' => 'comments'], ['created <' => $time], $types)
  278. ->execute();
  279. $this->assertEquals(['title' => 'First Article', 'name' => null], $result->fetch('assoc'));
  280. $query = new Query($this->connection);
  281. $result = $query
  282. ->select(['title', 'name' => 'c.comment'])
  283. ->from('articles')
  284. ->leftJoin(['c' => 'comments'], ['created >' => $time], $types)
  285. ->execute();
  286. $this->assertEquals(
  287. ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
  288. $result->fetch('assoc')
  289. );
  290. }
  291. /**
  292. * Tests the innerJoin method
  293. *
  294. * @return void
  295. */
  296. public function testSelectInnerJoin()
  297. {
  298. $query = new Query($this->connection);
  299. $time = new \DateTime('2007-03-18 10:45:23');
  300. $types = ['created' => 'datetime'];
  301. $result = $query
  302. ->select(['title', 'name' => 'c.comment'])
  303. ->from('articles')
  304. ->innerJoin(['c' => 'comments'], ['created <' => $time], $types)
  305. ->execute();
  306. $this->assertCount(0, $result->fetchAll());
  307. }
  308. /**
  309. * Tests the rightJoin method
  310. *
  311. * @return void
  312. */
  313. public function testSelectRightJoin()
  314. {
  315. $this->skipIf(
  316. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlite,
  317. 'SQLite does not support RIGHT joins'
  318. );
  319. $query = new Query($this->connection);
  320. $time = new \DateTime('2007-03-18 10:45:23');
  321. $types = ['created' => 'datetime'];
  322. $result = $query
  323. ->select(['title', 'name' => 'c.comment'])
  324. ->from('articles')
  325. ->rightJoin(['c' => 'comments'], ['created <' => $time], $types)
  326. ->execute();
  327. $this->assertCount(6, $result);
  328. $this->assertEquals(
  329. ['title' => null, 'name' => 'First Comment for First Article'],
  330. $result->fetch('assoc')
  331. );
  332. }
  333. /**
  334. * Tests that it is possible to pass a callable as conditions for a join
  335. *
  336. * @return void
  337. */
  338. public function testSelectJoinWithCallback()
  339. {
  340. $query = new Query($this->connection);
  341. $types = ['created' => 'datetime'];
  342. $result = $query
  343. ->select(['title', 'name' => 'c.comment'])
  344. ->from('articles')
  345. ->innerJoin(['c' => 'comments'], function ($exp, $q) use ($query, $types) {
  346. $this->assertSame($q, $query);
  347. $exp->add(['created <' => new \DateTime('2007-03-18 10:45:23')], $types);
  348. return $exp;
  349. })
  350. ->execute();
  351. $this->assertCount(0, $result->fetchAll());
  352. $query = new Query($this->connection);
  353. $types = ['created' => 'datetime'];
  354. $result = $query
  355. ->select(['title', 'name' => 'comments.comment'])
  356. ->from('articles')
  357. ->innerJoin('comments', function ($exp, $q) use ($query, $types) {
  358. $this->assertSame($q, $query);
  359. $exp->add(['created >' => new \DateTime('2007-03-18 10:45:23')], $types);
  360. return $exp;
  361. })
  362. ->execute();
  363. $this->assertEquals(
  364. ['title' => 'First Article', 'name' => 'Second Comment for First Article'],
  365. $result->fetch('assoc')
  366. );
  367. }
  368. /**
  369. * Tests it is possible to filter a query by using simple AND joined conditions
  370. *
  371. * @return void
  372. */
  373. public function testSelectSimpleWhere()
  374. {
  375. $query = new Query($this->connection);
  376. $result = $query
  377. ->select(['title'])
  378. ->from('articles')
  379. ->where(['id' => 1, 'title' => 'First Article'])
  380. ->execute();
  381. $this->assertCount(1, $result);
  382. $result->closeCursor();
  383. $query = new Query($this->connection);
  384. $result = $query
  385. ->select(['title'])
  386. ->from('articles')
  387. ->where(['id' => 100], ['id' => 'integer'])
  388. ->execute();
  389. $this->assertCount(0, $result);
  390. $result->closeCursor();
  391. }
  392. /**
  393. * Tests using where conditions with operators and scalar values works
  394. *
  395. * @return void
  396. */
  397. public function testSelectWhereOperators()
  398. {
  399. $query = new Query($this->connection);
  400. $result = $query
  401. ->select(['comment'])
  402. ->from('comments')
  403. ->where(['id >' => 4])
  404. ->execute();
  405. $this->assertCount(2, $result);
  406. $this->assertEquals(['comment' => 'First Comment for Second Article'], $result->fetch('assoc'));
  407. $result->closeCursor();
  408. $query = new Query($this->connection);
  409. $result = $query
  410. ->select(['title'])
  411. ->from('articles')
  412. ->where(['id <' => 2])
  413. ->execute();
  414. $this->assertCount(1, $result);
  415. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  416. $result->closeCursor();
  417. $query = new Query($this->connection);
  418. $result = $query
  419. ->select(['title'])
  420. ->from('articles')
  421. ->where(['id <=' => 2])
  422. ->execute();
  423. $this->assertCount(2, $result);
  424. $result->closeCursor();
  425. $query = new Query($this->connection);
  426. $result = $query
  427. ->select(['title'])
  428. ->from('articles')
  429. ->where(['id >=' => 1])
  430. ->execute();
  431. $this->assertCount(3, $result);
  432. $result->closeCursor();
  433. $query = new Query($this->connection);
  434. $result = $query
  435. ->select(['title'])
  436. ->from('articles')
  437. ->where(['id <=' => 1])
  438. ->execute();
  439. $this->assertCount(1, $result);
  440. $result->closeCursor();
  441. $query = new Query($this->connection);
  442. $result = $query
  443. ->select(['title'])
  444. ->from('articles')
  445. ->where(['id !=' => 2])
  446. ->execute();
  447. $this->assertCount(2, $result);
  448. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  449. $result->closeCursor();
  450. $query = new Query($this->connection);
  451. $result = $query
  452. ->select(['title'])
  453. ->from('articles')
  454. ->where(['title LIKE' => 'First Article'])
  455. ->execute();
  456. $this->assertCount(1, $result);
  457. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  458. $result->closeCursor();
  459. $query = new Query($this->connection);
  460. $result = $query
  461. ->select(['title'])
  462. ->from('articles')
  463. ->where(['title like' => '%Article%'])
  464. ->execute();
  465. $this->assertCount(3, $result);
  466. $result->closeCursor();
  467. $query = new Query($this->connection);
  468. $result = $query
  469. ->select(['title'])
  470. ->from('articles')
  471. ->where(['title not like' => '%Article%'])
  472. ->execute();
  473. $this->assertCount(0, $result);
  474. $result->closeCursor();
  475. }
  476. /**
  477. * Test that unary expressions in selects are built correctly.
  478. *
  479. * @return void
  480. */
  481. public function testSelectWhereUnary()
  482. {
  483. $query = new Query($this->connection);
  484. $result = $query
  485. ->select(['id'])
  486. ->from('articles')
  487. ->where([
  488. 'title is not' => null,
  489. 'user_id is' => null
  490. ])
  491. ->sql();
  492. $this->assertQuotedQuery(
  493. 'SELECT <id> FROM <articles> WHERE \(\(<title>\) IS NOT NULL AND \(<user_id>\) IS NULL\)',
  494. $result,
  495. !$this->autoQuote
  496. );
  497. }
  498. /**
  499. * Tests selecting with conditions and specifying types for those
  500. *
  501. * @return void
  502. */
  503. public function testSelectWhereTypes()
  504. {
  505. $query = new Query($this->connection);
  506. $result = $query
  507. ->select(['id'])
  508. ->from('comments')
  509. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  510. ->execute();
  511. $this->assertCount(1, $result);
  512. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  513. $query = new Query($this->connection);
  514. $result = $query
  515. ->select(['id'])
  516. ->from('comments')
  517. ->where(['created >' => new \DateTime('2007-03-18 10:46:00')], ['created' => 'datetime'])
  518. ->execute();
  519. $this->assertCount(5, $result);
  520. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  521. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  522. $query = new Query($this->connection);
  523. $result = $query
  524. ->select(['id'])
  525. ->from('comments')
  526. ->where(
  527. [
  528. 'created >' => new \DateTime('2007-03-18 10:40:00'),
  529. 'created <' => new \DateTime('2007-03-18 10:46:00')
  530. ],
  531. ['created' => 'datetime']
  532. )
  533. ->execute();
  534. $this->assertCount(1, $result);
  535. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  536. $query = new Query($this->connection);
  537. $result = $query
  538. ->select(['id'])
  539. ->from('comments')
  540. ->where(
  541. [
  542. 'id' => '3something-crazy',
  543. 'created <' => new \DateTime('2013-01-01 12:00')
  544. ],
  545. ['created' => 'datetime', 'id' => 'integer']
  546. )
  547. ->execute();
  548. $this->assertCount(1, $result);
  549. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  550. $query = new Query($this->connection);
  551. $result = $query
  552. ->select(['id'])
  553. ->from('comments')
  554. ->where(
  555. [
  556. 'id' => '1something-crazy',
  557. 'created <' => new \DateTime('2013-01-01 12:00')
  558. ],
  559. ['created' => 'datetime', 'id' => 'float']
  560. )
  561. ->execute();
  562. $this->assertCount(1, $result);
  563. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  564. }
  565. /**
  566. * Tests that passing an array type to any where condition will replace
  567. * the passed array accordingly as a proper IN condition
  568. *
  569. * @return void
  570. */
  571. public function testSelectWhereArrayType()
  572. {
  573. $query = new Query($this->connection);
  574. $result = $query
  575. ->select(['id'])
  576. ->from('comments')
  577. ->where(['id' => ['1', '3']], ['id' => 'integer[]'])
  578. ->execute();
  579. $this->assertCount(2, $result);
  580. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  581. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  582. }
  583. /**
  584. * Tests that passing an empty array type to any where condition will not
  585. * result in a SQL error, but an internal exception
  586. *
  587. * @expectedException Cake\Database\Exception
  588. * @expectedExceptionMessage Impossible to generate condition with empty list of values for field
  589. * @return void
  590. */
  591. public function testSelectWhereArrayTypeEmpty()
  592. {
  593. $query = new Query($this->connection);
  594. $result = $query
  595. ->select(['id'])
  596. ->from('comments')
  597. ->where(['id' => []], ['id' => 'integer[]'])
  598. ->execute();
  599. }
  600. /**
  601. * Tests exception message for impossible condition when using an expression
  602. * @expectedException Cake\Database\Exception
  603. * @expectedExceptionMessage with empty list of values for field (SELECT 1)
  604. * @return void
  605. */
  606. public function testSelectWhereArrayTypeEmptyWithExpression()
  607. {
  608. $query = new Query($this->connection);
  609. $result = $query
  610. ->select(['id'])
  611. ->from('comments')
  612. ->where(function ($exp, $q) {
  613. return $exp->in($q->newExpr('SELECT 1'), []);
  614. })
  615. ->execute();
  616. }
  617. /**
  618. * Tests that Query::orWhere() can be used to concatenate conditions with OR
  619. *
  620. * @return void
  621. */
  622. public function testSelectOrWhere()
  623. {
  624. $query = new Query($this->connection);
  625. $result = $query
  626. ->select(['id'])
  627. ->from('comments')
  628. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  629. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  630. ->execute();
  631. $this->assertCount(2, $result);
  632. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  633. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  634. }
  635. /**
  636. * Tests that Query::andWhere() can be used to concatenate conditions with AND
  637. *
  638. * @return void
  639. */
  640. public function testSelectAndWhere()
  641. {
  642. $query = new Query($this->connection);
  643. $result = $query
  644. ->select(['id'])
  645. ->from('comments')
  646. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  647. ->andWhere(['id' => 1])
  648. ->execute();
  649. $this->assertCount(1, $result);
  650. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  651. $query = new Query($this->connection);
  652. $result = $query
  653. ->select(['id'])
  654. ->from('comments')
  655. ->where(['created' => new \DateTime('2007-03-18 10:50:55')], ['created' => 'datetime'])
  656. ->andWhere(['id' => 2])
  657. ->execute();
  658. $this->assertCount(0, $result);
  659. }
  660. /**
  661. * Tests that combining Query::andWhere() and Query::orWhere() produces
  662. * correct conditions nesting
  663. *
  664. * @return void
  665. */
  666. public function testSelectExpressionNesting()
  667. {
  668. $query = new Query($this->connection);
  669. $result = $query
  670. ->select(['id'])
  671. ->from('comments')
  672. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  673. ->orWhere(['id' => 2])
  674. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  675. ->execute();
  676. $this->assertCount(2, $result);
  677. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  678. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  679. $query = new Query($this->connection);
  680. $result = $query
  681. ->select(['id'])
  682. ->from('comments')
  683. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  684. ->orWhere(['id' => 2])
  685. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  686. ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
  687. ->execute();
  688. $this->assertCount(3, $result);
  689. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  690. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  691. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  692. }
  693. /**
  694. * Tests that Query::orWhere() can be used without calling where() before
  695. *
  696. * @return void
  697. */
  698. public function testSelectOrWhereNoPreviousCondition()
  699. {
  700. $query = new Query($this->connection);
  701. $result = $query
  702. ->select(['id'])
  703. ->from('comments')
  704. ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  705. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  706. ->execute();
  707. $this->assertCount(2, $result);
  708. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  709. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  710. }
  711. /**
  712. * Tests that Query::andWhere() can be used without calling where() before
  713. *
  714. * @return void
  715. */
  716. public function testSelectAndWhereNoPreviousCondition()
  717. {
  718. $query = new Query($this->connection);
  719. $result = $query
  720. ->select(['id'])
  721. ->from('comments')
  722. ->andWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  723. ->andWhere(['id' => 1])
  724. ->execute();
  725. $this->assertCount(1, $result);
  726. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  727. }
  728. /**
  729. * Tests that it is possible to pass a closure to where() to build a set of
  730. * conditions and return the expression to be used
  731. *
  732. * @return void
  733. */
  734. public function testSelectWhereUsingClosure()
  735. {
  736. $query = new Query($this->connection);
  737. $result = $query
  738. ->select(['id'])
  739. ->from('comments')
  740. ->where(function ($exp) {
  741. return $exp->eq('id', 1);
  742. })
  743. ->execute();
  744. $this->assertCount(1, $result);
  745. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  746. $query = new Query($this->connection);
  747. $result = $query
  748. ->select(['id'])
  749. ->from('comments')
  750. ->where(function ($exp) {
  751. return $exp
  752. ->eq('id', 1)
  753. ->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  754. })
  755. ->execute();
  756. $this->assertCount(1, $result);
  757. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  758. $query = new Query($this->connection);
  759. $result = $query
  760. ->select(['id'])
  761. ->from('comments')
  762. ->where(function ($exp) {
  763. return $exp
  764. ->eq('id', 1)
  765. ->eq('created', new \DateTime('2021-12-30 15:00'), 'datetime');
  766. })
  767. ->execute();
  768. $this->assertCount(0, $result);
  769. }
  770. /**
  771. * Tests generating tuples in the values side containing closure expressions
  772. *
  773. * @return void
  774. */
  775. public function testTupleWithClosureExpression()
  776. {
  777. $query = new Query($this->connection);
  778. $query->select(['id'])
  779. ->from('comments')
  780. ->where([
  781. 'OR' => [
  782. 'id' => 1,
  783. function ($exp) {
  784. return $exp->eq('id', 2);
  785. }
  786. ]
  787. ]);
  788. $result = $query->sql();
  789. $this->assertQuotedQuery(
  790. 'SELECT <id> FROM <comments> WHERE \(<id> = :c0 OR <id> = :c1\)',
  791. $result,
  792. !$this->autoQuote
  793. );
  794. }
  795. /**
  796. * Tests that it is possible to pass a closure to andWhere() to build a set of
  797. * conditions and return the expression to be used
  798. *
  799. * @return void
  800. */
  801. public function testSelectAndWhereUsingClosure()
  802. {
  803. $query = new Query($this->connection);
  804. $result = $query
  805. ->select(['id'])
  806. ->from('comments')
  807. ->where(['id' => '1'])
  808. ->andWhere(function ($exp) {
  809. return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  810. })
  811. ->execute();
  812. $this->assertCount(1, $result);
  813. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  814. $query = new Query($this->connection);
  815. $result = $query
  816. ->select(['id'])
  817. ->from('comments')
  818. ->where(['id' => '1'])
  819. ->andWhere(function ($exp) {
  820. return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime');
  821. })
  822. ->execute();
  823. $this->assertCount(0, $result);
  824. }
  825. /**
  826. * Tests that it is possible to pass a closure to orWhere() to build a set of
  827. * conditions and return the expression to be used
  828. *
  829. * @return void
  830. */
  831. public function testSelectOrWhereUsingClosure()
  832. {
  833. $query = new Query($this->connection);
  834. $result = $query
  835. ->select(['id'])
  836. ->from('comments')
  837. ->where(['id' => '1'])
  838. ->orWhere(function ($exp) {
  839. return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
  840. })
  841. ->execute();
  842. $this->assertCount(2, $result);
  843. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  844. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  845. $query = new Query($this->connection);
  846. $result = $query
  847. ->select(['id'])
  848. ->from('comments')
  849. ->where(['id' => '1'])
  850. ->orWhere(function ($exp) {
  851. return $exp
  852. ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
  853. ->eq('id', 3);
  854. })
  855. ->execute();
  856. $this->assertCount(1, $result);
  857. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  858. }
  859. /**
  860. * Tests that expression objects can be used as the field in a comparison
  861. * and the values will be bound correctly to the query
  862. *
  863. * @return void
  864. */
  865. public function testSelectWhereUsingExpressionInField()
  866. {
  867. $query = new Query($this->connection);
  868. $result = $query
  869. ->select(['id'])
  870. ->from('comments')
  871. ->where(function ($exp) {
  872. $field = clone $exp;
  873. $field->add('SELECT min(id) FROM comments');
  874. return $exp
  875. ->eq($field, 100, 'integer');
  876. })
  877. ->execute();
  878. $this->assertCount(0, $result);
  879. }
  880. /**
  881. * Tests using where conditions with operator methods
  882. *
  883. * @return void
  884. */
  885. public function testSelectWhereOperatorMethods()
  886. {
  887. $query = new Query($this->connection);
  888. $result = $query
  889. ->select(['title'])
  890. ->from('articles')
  891. ->where(function ($exp) {
  892. return $exp->gt('id', 1);
  893. })
  894. ->execute();
  895. $this->assertCount(2, $result);
  896. $this->assertEquals(['title' => 'Second Article'], $result->fetch('assoc'));
  897. $query = new Query($this->connection);
  898. $result = $query->select(['title'])
  899. ->from('articles')
  900. ->where(function ($exp) {
  901. return $exp->lt('id', 2);
  902. })
  903. ->execute();
  904. $this->assertCount(1, $result);
  905. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  906. $query = new Query($this->connection);
  907. $result = $query->select(['title'])
  908. ->from('articles')
  909. ->where(function ($exp) {
  910. return $exp->lte('id', 2);
  911. })
  912. ->execute();
  913. $this->assertCount(2, $result);
  914. $query = new Query($this->connection);
  915. $result = $query
  916. ->select(['title'])
  917. ->from('articles')
  918. ->where(function ($exp) {
  919. return $exp->gte('id', 1);
  920. })
  921. ->execute();
  922. $this->assertCount(3, $result);
  923. $query = new Query($this->connection);
  924. $result = $query
  925. ->select(['title'])
  926. ->from('articles')
  927. ->where(function ($exp) {
  928. return $exp->lte('id', 1);
  929. })
  930. ->execute();
  931. $this->assertCount(1, $result);
  932. $query = new Query($this->connection);
  933. $result = $query
  934. ->select(['title'])
  935. ->from('articles')
  936. ->where(function ($exp) {
  937. return $exp->notEq('id', 2);
  938. })
  939. ->execute();
  940. $this->assertCount(2, $result);
  941. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  942. $query = new Query($this->connection);
  943. $result = $query
  944. ->select(['title'])
  945. ->from('articles')
  946. ->where(function ($exp) {
  947. return $exp->like('title', 'First Article');
  948. })
  949. ->execute();
  950. $this->assertCount(1, $result);
  951. $this->assertEquals(['title' => 'First Article'], $result->fetch('assoc'));
  952. $query = new Query($this->connection);
  953. $result = $query
  954. ->select(['title'])
  955. ->from('articles')
  956. ->where(function ($exp) {
  957. return $exp->like('title', '%Article%');
  958. })
  959. ->execute();
  960. $this->assertCount(3, $result);
  961. $query = new Query($this->connection);
  962. $result = $query
  963. ->select(['title'])
  964. ->from('articles')
  965. ->where(function ($exp) {
  966. return $exp->notLike('title', '%Article%');
  967. })
  968. ->execute();
  969. $this->assertCount(0, $result);
  970. $query = new Query($this->connection);
  971. $result = $query
  972. ->select(['id'])
  973. ->from('comments')
  974. ->where(function ($exp) {
  975. return $exp->isNull('published');
  976. })
  977. ->execute();
  978. $this->assertCount(0, $result);
  979. $query = new Query($this->connection);
  980. $result = $query
  981. ->select(['id'])
  982. ->from('comments')
  983. ->where(function ($exp) {
  984. return $exp->isNotNull('published');
  985. })
  986. ->execute();
  987. $this->assertCount(6, $result);
  988. $query = new Query($this->connection);
  989. $result = $query
  990. ->select(['id'])
  991. ->from('comments')
  992. ->where(function ($exp) {
  993. return $exp->in('published', ['Y', 'N']);
  994. })
  995. ->execute();
  996. $this->assertCount(6, $result);
  997. $query = new Query($this->connection);
  998. $result = $query
  999. ->select(['id'])
  1000. ->from('comments')
  1001. ->where(function ($exp) {
  1002. return $exp->in(
  1003. 'created',
  1004. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  1005. 'datetime'
  1006. );
  1007. })
  1008. ->execute();
  1009. $this->assertCount(2, $result);
  1010. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1011. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1012. $query = new Query($this->connection);
  1013. $result = $query
  1014. ->select(['id'])
  1015. ->from('comments')
  1016. ->where(function ($exp) {
  1017. return $exp->notIn(
  1018. 'created',
  1019. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  1020. 'datetime'
  1021. );
  1022. })
  1023. ->execute();
  1024. $this->assertCount(4, $result);
  1025. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1026. }
  1027. /**
  1028. * Tests that calling "in" and "notIn" will cast the passed values to an array
  1029. *
  1030. * @return void
  1031. */
  1032. public function testInValueCast()
  1033. {
  1034. $query = new Query($this->connection);
  1035. $result = $query
  1036. ->select(['id'])
  1037. ->from('comments')
  1038. ->where(function ($exp) {
  1039. return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
  1040. })
  1041. ->execute();
  1042. $this->assertCount(1, $result);
  1043. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1044. $query = new Query($this->connection);
  1045. $result = $query
  1046. ->select(['id'])
  1047. ->from('comments')
  1048. ->where(function ($exp) {
  1049. return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
  1050. })
  1051. ->execute();
  1052. $this->assertCount(5, $result);
  1053. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1054. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1055. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  1056. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1057. $result->closeCursor();
  1058. $query = new Query($this->connection);
  1059. $result = $query
  1060. ->select(['id'])
  1061. ->from('comments')
  1062. ->where(function ($exp, $q) {
  1063. return $exp->in(
  1064. 'created',
  1065. $q->newExpr("'2007-03-18 10:45:23'"),
  1066. 'datetime'
  1067. );
  1068. })
  1069. ->execute();
  1070. $this->assertCount(1, $result);
  1071. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1072. $result->closeCursor();
  1073. $query = new Query($this->connection);
  1074. $result = $query
  1075. ->select(['id'])
  1076. ->from('comments')
  1077. ->where(function ($exp, $q) {
  1078. return $exp->notIn(
  1079. 'created',
  1080. $q->newExpr("'2007-03-18 10:45:23'"),
  1081. 'datetime'
  1082. );
  1083. })
  1084. ->execute();
  1085. $this->assertCount(5, $result);
  1086. $result->closeCursor();
  1087. }
  1088. /**
  1089. * Tests that calling "in" and "notIn" will cast the passed values to an array
  1090. *
  1091. * @return void
  1092. */
  1093. public function testInValueCast2()
  1094. {
  1095. $query = new Query($this->connection);
  1096. $result = $query
  1097. ->select(['id'])
  1098. ->from('comments')
  1099. ->where(['created IN' => '2007-03-18 10:45:23'])
  1100. ->execute();
  1101. $this->assertCount(1, $result);
  1102. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1103. $result->closeCursor();
  1104. $query = new Query($this->connection);
  1105. $result = $query
  1106. ->select(['id'])
  1107. ->from('comments')
  1108. ->where(['created NOT IN' => '2007-03-18 10:45:23'])
  1109. ->execute();
  1110. $this->assertCount(5, $result);
  1111. $result->closeCursor();
  1112. }
  1113. /**
  1114. * Tests where() with callable types.
  1115. *
  1116. * @return void
  1117. */
  1118. public function testWhereCallables()
  1119. {
  1120. $query = new Query($this->connection);
  1121. $query->select(['id'])
  1122. ->from('articles')
  1123. ->where([
  1124. 'id' => '\Cake\Error\Debugger::dump',
  1125. 'title' => ['\Cake\Error\Debugger', 'dump'],
  1126. 'author_id' => function ($exp) {
  1127. return 1;
  1128. }
  1129. ]);
  1130. $this->assertQuotedQuery(
  1131. 'SELECT <id> FROM <articles> WHERE \(<id> = :c0 AND <title> = :c1 AND <author_id> = :c2\)',
  1132. $query->sql(),
  1133. !$this->autoQuote
  1134. );
  1135. }
  1136. /**
  1137. * Tests that empty values don't set where clauses.
  1138. *
  1139. * @return void
  1140. */
  1141. public function testWhereEmptyValues()
  1142. {
  1143. $query = new Query($this->connection);
  1144. $query->from('comments')
  1145. ->where('');
  1146. $this->assertCount(0, $query->clause('where'));
  1147. $query->where([]);
  1148. $this->assertCount(0, $query->clause('where'));
  1149. }
  1150. /**
  1151. * Tests that it is possible to use a between expression
  1152. * in a where condition
  1153. *
  1154. * @return void
  1155. */
  1156. public function testWhereWithBetween()
  1157. {
  1158. $query = new Query($this->connection);
  1159. $result = $query
  1160. ->select(['id'])
  1161. ->from('comments')
  1162. ->where(function ($exp) {
  1163. return $exp->between('id', 5, 6, 'integer');
  1164. })
  1165. ->execute();
  1166. $this->assertCount(2, $result);
  1167. $first = $result->fetch('assoc');
  1168. $this->assertEquals(5, $first['id']);
  1169. $second = $result->fetch('assoc');
  1170. $this->assertEquals(6, $second['id']);
  1171. $result->closeCursor();
  1172. }
  1173. /**
  1174. * Tests that it is possible to use a between expression
  1175. * in a where condition with a complex data type
  1176. *
  1177. * @return void
  1178. */
  1179. public function testWhereWithBetweenComplex()
  1180. {
  1181. $query = new Query($this->connection);
  1182. $result = $query
  1183. ->select(['id'])
  1184. ->from('comments')
  1185. ->where(function ($exp) {
  1186. $from = new \DateTime('2007-03-18 10:51:00');
  1187. $to = new \DateTime('2007-03-18 10:54:00');
  1188. return $exp->between('created', $from, $to, 'datetime');
  1189. })
  1190. ->execute();
  1191. $this->assertCount(2, $result);
  1192. $first = $result->fetch('assoc');
  1193. $this->assertEquals(4, $first['id']);
  1194. $second = $result->fetch('assoc');
  1195. $this->assertEquals(5, $second['id']);
  1196. $result->closeCursor();
  1197. }
  1198. /**
  1199. * Tests that it is possible to use an expression object
  1200. * as the field for a between expression
  1201. *
  1202. * @return void
  1203. */
  1204. public function testWhereWithBetweenWithExpressionField()
  1205. {
  1206. $query = new Query($this->connection);
  1207. $result = $query
  1208. ->select(['id'])
  1209. ->from('comments')
  1210. ->where(function ($exp, $q) {
  1211. $field = $q->func()->coalesce([new IdentifierExpression('id'), 1 => 'literal']);
  1212. return $exp->between($field, 5, 6, 'integer');
  1213. })
  1214. ->execute();
  1215. $this->assertCount(2, $result);
  1216. $first = $result->fetch('assoc');
  1217. $this->assertEquals(5, $first['id']);
  1218. $second = $result->fetch('assoc');
  1219. $this->assertEquals(6, $second['id']);
  1220. $result->closeCursor();
  1221. }
  1222. /**
  1223. * Tests that it is possible to use an expression object
  1224. * as any of the parts of the between expression
  1225. *
  1226. * @return void
  1227. */
  1228. public function testWhereWithBetweenWithExpressionParts()
  1229. {
  1230. $query = new Query($this->connection);
  1231. $result = $query
  1232. ->select(['id'])
  1233. ->from('comments')
  1234. ->where(function ($exp, $q) {
  1235. $from = $q->newExpr("'2007-03-18 10:51:00'");
  1236. $to = $q->newExpr("'2007-03-18 10:54:00'");
  1237. return $exp->between('created', $from, $to);
  1238. })
  1239. ->execute();
  1240. $this->assertCount(2, $result);
  1241. $first = $result->fetch('assoc');
  1242. $this->assertEquals(4, $first['id']);
  1243. $second = $result->fetch('assoc');
  1244. $this->assertEquals(5, $second['id']);
  1245. }
  1246. /**
  1247. * Tests nesting query expressions both using arrays and closures
  1248. *
  1249. * @return void
  1250. */
  1251. public function testSelectExpressionComposition()
  1252. {
  1253. $query = new Query($this->connection);
  1254. $result = $query
  1255. ->select(['id'])
  1256. ->from('comments')
  1257. ->where(function ($exp) {
  1258. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  1259. return $exp->add($and);
  1260. })
  1261. ->execute();
  1262. $this->assertCount(1, $result);
  1263. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1264. $query = new Query($this->connection);
  1265. $result = $query
  1266. ->select(['id'])
  1267. ->from('comments')
  1268. ->where(function ($exp) {
  1269. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  1270. return $exp->add($and);
  1271. })
  1272. ->execute();
  1273. $this->assertCount(0, $result);
  1274. $query = new Query($this->connection);
  1275. $result = $query
  1276. ->select(['id'])
  1277. ->from('comments')
  1278. ->where(function ($exp) {
  1279. $and = $exp->and_(function ($and) {
  1280. return $and->eq('id', 1)->gt('id', 0);
  1281. });
  1282. return $exp->add($and);
  1283. })
  1284. ->execute();
  1285. $this->assertCount(1, $result);
  1286. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1287. $query = new Query($this->connection);
  1288. $result = $query
  1289. ->select(['id'])
  1290. ->from('comments')
  1291. ->where(function ($exp) {
  1292. $or = $exp->or_(['id' => 1]);
  1293. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  1294. return $or->add($and);
  1295. })
  1296. ->execute();
  1297. $this->assertCount(2, $result);
  1298. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1299. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1300. $query = new Query($this->connection);
  1301. $result = $query
  1302. ->select(['id'])
  1303. ->from('comments')
  1304. ->where(function ($exp) {
  1305. $or = $exp->or_(function ($or) {
  1306. return $or->eq('id', 1)->eq('id', 2);
  1307. });
  1308. return $or;
  1309. })
  1310. ->execute();
  1311. $this->assertCount(2, $result);
  1312. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1313. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1314. }
  1315. /**
  1316. * Tests that conditions can be nested with an unary operator using the array notation
  1317. * and the not() method
  1318. *
  1319. * @return void
  1320. */
  1321. public function testSelectWhereNot()
  1322. {
  1323. $query = new Query($this->connection);
  1324. $result = $query
  1325. ->select(['id'])
  1326. ->from('comments')
  1327. ->where(function ($exp) {
  1328. return $exp->not(
  1329. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  1330. );
  1331. })
  1332. ->execute();
  1333. $this->assertCount(5, $result);
  1334. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1335. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1336. $query = new Query($this->connection);
  1337. $result = $query
  1338. ->select(['id'])
  1339. ->from('comments')
  1340. ->where(function ($exp) {
  1341. return $exp->not(
  1342. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  1343. );
  1344. })
  1345. ->execute();
  1346. $this->assertCount(6, $result);
  1347. $query = new Query($this->connection);
  1348. $result = $query
  1349. ->select(['id'])
  1350. ->from('articles')
  1351. ->where([
  1352. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  1353. ])
  1354. ->execute();
  1355. $this->assertCount(2, $result);
  1356. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1357. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1358. }
  1359. /**
  1360. * Tests order() method both with simple fields and expressions
  1361. *
  1362. * @return void
  1363. */
  1364. public function testSelectOrderBy()
  1365. {
  1366. $query = new Query($this->connection);
  1367. $result = $query
  1368. ->select(['id'])
  1369. ->from('articles')
  1370. ->order(['id' => 'desc'])
  1371. ->execute();
  1372. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1373. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1374. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1375. $result = $query->order(['id' => 'asc'])->execute();
  1376. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1377. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1378. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1379. $result = $query->order(['title' => 'asc'])->execute();
  1380. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1381. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1382. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1383. $result = $query->order(['title' => 'asc'], true)->execute();
  1384. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1385. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1386. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1387. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1388. ->execute();
  1389. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1390. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1391. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1392. $expression = $query->newExpr(['(id + :offset) % 2']);
  1393. $result = $query
  1394. ->order([$expression, 'id' => 'desc'], true)
  1395. ->bind(':offset', 1, null)
  1396. ->execute();
  1397. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1398. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1399. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1400. $result = $query
  1401. ->order($expression, true)
  1402. ->order(['id' => 'asc'])
  1403. ->bind(':offset', 1, null)
  1404. ->execute();
  1405. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1406. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1407. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1408. }
  1409. /**
  1410. * Test that order() being a string works.
  1411. *
  1412. * @return void
  1413. */
  1414. public function testSelectOrderByString()
  1415. {
  1416. $query = new Query($this->connection);
  1417. $query->select(['id'])
  1418. ->from('articles')
  1419. ->order('id asc');
  1420. $result = $query->execute();
  1421. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1422. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1423. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1424. }
  1425. /**
  1426. * Test orderAsc() and its input types.
  1427. *
  1428. * @return void
  1429. */
  1430. public function testSelectOrderAsc()
  1431. {
  1432. $query = new Query($this->connection);
  1433. $query->select(['id'])
  1434. ->from('articles')
  1435. ->orderAsc('id');
  1436. $sql = $query->sql();
  1437. $result = $query->execute()->fetchAll('assoc');
  1438. $expected = [
  1439. ['id' => 1],
  1440. ['id' => 2],
  1441. ['id' => 3],
  1442. ];
  1443. $this->assertEquals($expected, $result);
  1444. $this->assertQuotedQuery(
  1445. 'SELECT <id> FROM <articles> ORDER BY <id> ASC',
  1446. $sql,
  1447. !$this->autoQuote
  1448. );
  1449. $query = new Query($this->connection);
  1450. $query->select(['id'])
  1451. ->from('articles')
  1452. ->orderAsc($query->func()->concat(['id' => 'identifier', '3']));
  1453. $result = $query->execute()->fetchAll('assoc');
  1454. $expected = [
  1455. ['id' => 1],
  1456. ['id' => 2],
  1457. ['id' => 3],
  1458. ];
  1459. $this->assertEquals($expected, $result);
  1460. }
  1461. /**
  1462. * Test orderDesc() and its input types.
  1463. *
  1464. * @return void
  1465. */
  1466. public function testSelectOrderDesc()
  1467. {
  1468. $query = new Query($this->connection);
  1469. $query->select(['id'])
  1470. ->from('articles')
  1471. ->orderDesc('id');
  1472. $sql = $query->sql();
  1473. $result = $query->execute()->fetchAll('assoc');
  1474. $expected = [
  1475. ['id' => 3],
  1476. ['id' => 2],
  1477. ['id' => 1],
  1478. ];
  1479. $this->assertEquals($expected, $result);
  1480. $this->assertQuotedQuery(
  1481. 'SELECT <id> FROM <articles> ORDER BY <id> DESC',
  1482. $sql,
  1483. !$this->autoQuote
  1484. );
  1485. $query = new Query($this->connection);
  1486. $query->select(['id'])
  1487. ->from('articles')
  1488. ->orderDesc($query->func()->concat(['id' => 'identifier', '3']));
  1489. $result = $query->execute()->fetchAll('assoc');
  1490. $expected = [
  1491. ['id' => 3],
  1492. ['id' => 2],
  1493. ['id' => 1],
  1494. ];
  1495. $this->assertEquals($expected, $result);
  1496. }
  1497. /**
  1498. * Tests that group by fields can be passed similar to select fields
  1499. * and that it sends the correct query to the database
  1500. *
  1501. * @return void
  1502. */
  1503. public function testSelectGroup()
  1504. {
  1505. $query = new Query($this->connection);
  1506. $result = $query
  1507. ->select(['total' => 'count(author_id)', 'author_id'])
  1508. ->from('articles')
  1509. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1510. ->group('author_id')
  1511. ->execute();
  1512. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1513. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1514. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1515. ->group(['name'], true)
  1516. ->order(['total' => 'asc'])
  1517. ->execute();
  1518. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1519. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1520. $result = $query->select(['articles.id'])
  1521. ->group(['articles.id'])
  1522. ->execute();
  1523. $this->assertCount(3, $result);
  1524. }
  1525. /**
  1526. * Tests that it is possible to select distinct rows
  1527. *
  1528. * @return void
  1529. */
  1530. public function testSelectDistinct()
  1531. {
  1532. $query = new Query($this->connection);
  1533. $result = $query
  1534. ->select(['author_id'])
  1535. ->from(['a' => 'articles'])
  1536. ->execute();
  1537. $this->assertCount(3, $result);
  1538. $result = $query->distinct()->execute();
  1539. $this->assertCount(2, $result);
  1540. $result = $query->select(['id'])->distinct(false)->execute();
  1541. $this->assertCount(3, $result);
  1542. }
  1543. /**
  1544. * Tests that it is possible to select distinct rows, even filtering by one column
  1545. * this is testing that there is a specific implementation for DISTINCT ON
  1546. *
  1547. * @return void
  1548. */
  1549. public function testSelectDistinctON()
  1550. {
  1551. $query = new Query($this->connection);
  1552. $result = $query
  1553. ->select(['id', 'author_id'])
  1554. ->distinct(['author_id'])
  1555. ->from(['a' => 'articles'])
  1556. ->order(['author_id' => 'ASC'])
  1557. ->execute();
  1558. $this->assertCount(2, $result);
  1559. $results = $result->fetchAll('assoc');
  1560. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1561. $this->assertEquals(
  1562. [3, 1],
  1563. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1564. );
  1565. $query = new Query($this->connection);
  1566. $result = $query
  1567. ->select(['id', 'author_id'])
  1568. ->distinct('author_id')
  1569. ->from(['a' => 'articles'])
  1570. ->order(['author_id' => 'ASC'])
  1571. ->execute();
  1572. $this->assertCount(2, $result);
  1573. $results = $result->fetchAll('assoc');
  1574. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1575. $this->assertEquals(
  1576. [3, 1],
  1577. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1578. );
  1579. }
  1580. /**
  1581. * Test use of modifiers in the query
  1582. *
  1583. * Testing the generated SQL since the modifiers are usually different per driver
  1584. *
  1585. * @return void
  1586. */
  1587. public function testSelectModifiers()
  1588. {
  1589. $query = new Query($this->connection);
  1590. $result = $query
  1591. ->select(['city', 'state', 'country'])
  1592. ->from(['addresses'])
  1593. ->modifier('DISTINCTROW');
  1594. $this->assertQuotedQuery(
  1595. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1596. $result->sql(),
  1597. !$this->autoQuote
  1598. );
  1599. $query = new Query($this->connection);
  1600. $result = $query
  1601. ->select(['city', 'state', 'country'])
  1602. ->from(['addresses'])
  1603. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1604. $this->assertQuotedQuery(
  1605. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1606. $result->sql(),
  1607. !$this->autoQuote
  1608. );
  1609. $query = new Query($this->connection);
  1610. $result = $query
  1611. ->select(['city', 'state', 'country'])
  1612. ->from(['addresses'])
  1613. ->modifier('DISTINCTROW')
  1614. ->modifier('SQL_NO_CACHE');
  1615. $this->assertQuotedQuery(
  1616. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1617. $result->sql(),
  1618. true
  1619. );
  1620. $query = new Query($this->connection);
  1621. $result = $query
  1622. ->select(['city', 'state', 'country'])
  1623. ->from(['addresses'])
  1624. ->modifier(['TOP 10']);
  1625. $this->assertQuotedQuery(
  1626. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1627. $result->sql(),
  1628. !$this->autoQuote
  1629. );
  1630. }
  1631. /**
  1632. * Tests that having() behaves pretty much the same as the where() method
  1633. *
  1634. * @return void
  1635. */
  1636. public function testSelectHaving()
  1637. {
  1638. $query = new Query($this->connection);
  1639. $result = $query
  1640. ->select(['total' => 'count(author_id)', 'author_id'])
  1641. ->from('articles')
  1642. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1643. ->group('author_id')
  1644. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1645. ->execute();
  1646. $expected = [['total' => 1, 'author_id' => 3]];
  1647. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1648. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1649. ->execute();
  1650. $expected = [['total' => 2, 'author_id' => 1]];
  1651. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1652. $result = $query->having(function ($e) {
  1653. return $e->add('count(author_id) = 1 + 1');
  1654. }, [], true)
  1655. ->execute();
  1656. $expected = [['total' => 2, 'author_id' => 1]];
  1657. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1658. }
  1659. /**
  1660. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1661. * in the having clause
  1662. *
  1663. * @return void
  1664. */
  1665. public function testSelectOrHaving()
  1666. {
  1667. $query = new Query($this->connection);
  1668. $result = $query
  1669. ->select(['total' => 'count(author_id)', 'author_id'])
  1670. ->from('articles')
  1671. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1672. ->group('author_id')
  1673. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1674. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1675. ->execute();
  1676. $expected = [['total' => 1, 'author_id' => 3]];
  1677. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1678. $query = new Query($this->connection);
  1679. $result = $query
  1680. ->select(['total' => 'count(author_id)', 'author_id'])
  1681. ->from('articles')
  1682. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1683. ->group('author_id')
  1684. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1685. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1686. ->execute();
  1687. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1688. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1689. $query = new Query($this->connection);
  1690. $result = $query
  1691. ->select(['total' => 'count(author_id)', 'author_id'])
  1692. ->from('articles')
  1693. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1694. ->group('author_id')
  1695. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1696. ->orHaving(function ($e) {
  1697. return $e->add('count(author_id) = 1 + 1');
  1698. })
  1699. ->execute();
  1700. $expected = [['total' => 2, 'author_id' => 1]];
  1701. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1702. }
  1703. /**
  1704. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1705. * in the having clause
  1706. *
  1707. * @return void
  1708. */
  1709. public function testSelectAndHaving()
  1710. {
  1711. $query = new Query($this->connection);
  1712. $result = $query
  1713. ->select(['total' => 'count(author_id)', 'author_id'])
  1714. ->from('articles')
  1715. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1716. ->group('author_id')
  1717. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1718. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1719. ->execute();
  1720. $this->assertCount(0, $result);
  1721. $query = new Query($this->connection);
  1722. $result = $query
  1723. ->select(['total' => 'count(author_id)', 'author_id'])
  1724. ->from('articles')
  1725. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1726. ->group('author_id')
  1727. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1728. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1729. ->execute();
  1730. $expected = [['total' => 2, 'author_id' => 1]];
  1731. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1732. $query = new Query($this->connection);
  1733. $result = $query
  1734. ->select(['total' => 'count(author_id)', 'author_id'])
  1735. ->from('articles')
  1736. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1737. ->group('author_id')
  1738. ->andHaving(function ($e) {
  1739. return $e->add('count(author_id) = 2 - 1');
  1740. })
  1741. ->execute();
  1742. $expected = [['total' => 1, 'author_id' => 3]];
  1743. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1744. }
  1745. /**
  1746. * Tests selecting rows using a limit clause
  1747. *
  1748. * @return void
  1749. */
  1750. public function testSelectLimit()
  1751. {
  1752. $query = new Query($this->connection);
  1753. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1754. $this->assertCount(1, $result);
  1755. $query = new Query($this->connection);
  1756. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1757. $this->assertCount(2, $result);
  1758. }
  1759. /**
  1760. * Tests selecting rows combining a limit and offset clause
  1761. *
  1762. * @return void
  1763. */
  1764. public function testSelectOffset()
  1765. {
  1766. $query = new Query($this->connection);
  1767. $result = $query->select('id')->from('comments')
  1768. ->limit(1)
  1769. ->offset(0)
  1770. ->order(['id' => 'ASC'])
  1771. ->execute();
  1772. $this->assertCount(1, $result);
  1773. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1774. $query = new Query($this->connection);
  1775. $result = $query->select('id')->from('comments')
  1776. ->limit(1)
  1777. ->offset(1)
  1778. ->execute();
  1779. $this->assertCount(1, $result);
  1780. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1781. $query = new Query($this->connection);
  1782. $result = $query->select('id')->from('comments')
  1783. ->limit(1)
  1784. ->offset(2)
  1785. ->execute();
  1786. $this->assertCount(1, $result);
  1787. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1788. $query = new Query($this->connection);
  1789. $result = $query->select('id')->from('articles')
  1790. ->order(['id' => 'DESC'])
  1791. ->limit(1)
  1792. ->offset(0)
  1793. ->execute();
  1794. $this->assertCount(1, $result);
  1795. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1796. $result = $query->limit(2)->offset(1)->execute();
  1797. $this->assertCount(2, $result);
  1798. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1799. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1800. $query = new Query($this->connection);
  1801. $query->select('id')->from('comments')
  1802. ->limit(1)
  1803. ->offset(1)
  1804. ->execute();
  1805. $dirty = $this->readAttribute($query, '_dirty');
  1806. $this->assertFalse($dirty);
  1807. $query->offset(2);
  1808. $dirty = $this->readAttribute($query, '_dirty');
  1809. $this->assertTrue($dirty);
  1810. }
  1811. /**
  1812. * Test selecting rows using the page() method.
  1813. *
  1814. * @return void
  1815. */
  1816. public function testSelectPage()
  1817. {
  1818. $query = new Query($this->connection);
  1819. $result = $query->select('id')->from('comments')
  1820. ->limit(1)
  1821. ->page(1)
  1822. ->execute();
  1823. $this->assertCount(1, $result);
  1824. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1825. $query = new Query($this->connection);
  1826. $result = $query->select('id')->from('comments')
  1827. ->limit(1)
  1828. ->page(2)
  1829. ->order(['id' => 'asc'])
  1830. ->execute();
  1831. $this->assertCount(1, $result);
  1832. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1833. $query = new Query($this->connection);
  1834. $query->select('id')->from('comments')->page(3, 10);
  1835. $this->assertEquals(10, $query->clause('limit'));
  1836. $this->assertEquals(20, $query->clause('offset'));
  1837. $query = new Query($this->connection);
  1838. $query->select('id')->from('comments')->page(1);
  1839. $this->assertEquals(25, $query->clause('limit'));
  1840. $this->assertEquals(0, $query->clause('offset'));
  1841. $query->select('id')->from('comments')->page(2);
  1842. $this->assertEquals(25, $query->clause('limit'));
  1843. $this->assertEquals(25, $query->clause('offset'));
  1844. }
  1845. /**
  1846. * Tests that Query objects can be included inside the select clause
  1847. * and be used as a normal field, including binding any passed parameter
  1848. *
  1849. * @return void
  1850. */
  1851. public function testSubqueryInSelect()
  1852. {
  1853. $query = new Query($this->connection);
  1854. $subquery = (new Query($this->connection))
  1855. ->select('name')
  1856. ->from(['b' => 'authors'])
  1857. ->where([$query->newExpr()->equalFields('b.id', 'a.id')]);
  1858. $result = $query
  1859. ->select(['id', 'name' => $subquery])
  1860. ->from(['a' => 'comments'])->execute();
  1861. $expected = [
  1862. ['id' => 1, 'name' => 'mariano'],
  1863. ['id' => 2, 'name' => 'nate'],
  1864. ['id' => 3, 'name' => 'larry'],
  1865. ['id' => 4, 'name' => 'garrett'],
  1866. ['id' => 5, 'name' => null],
  1867. ['id' => 6, 'name' => null],
  1868. ];
  1869. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1870. $query = new Query($this->connection);
  1871. $subquery = (new Query($this->connection))
  1872. ->select('name')
  1873. ->from(['b' => 'authors'])
  1874. ->where(['name' => 'mariano'], ['name' => 'string']);
  1875. $result = $query
  1876. ->select(['id', 'name' => $subquery])
  1877. ->from(['a' => 'articles'])->execute();
  1878. $expected = [
  1879. ['id' => 1, 'name' => 'mariano'],
  1880. ['id' => 2, 'name' => 'mariano'],
  1881. ['id' => 3, 'name' => 'mariano'],
  1882. ];
  1883. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1884. }
  1885. /**
  1886. * Tests that Query objects can be included inside the from clause
  1887. * and be used as a normal table, including binding any passed parameter
  1888. *
  1889. * @return void
  1890. */
  1891. public function testSuqueryInFrom()
  1892. {
  1893. $query = new Query($this->connection);
  1894. $subquery = (new Query($this->connection))
  1895. ->select(['id', 'comment'])
  1896. ->from('comments')
  1897. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1898. $result = $query
  1899. ->select(['say' => 'comment'])
  1900. ->from(['b' => $subquery])
  1901. ->where(['id !=' => 3])
  1902. ->execute();
  1903. $expected = [
  1904. ['say' => 'Second Comment for First Article'],
  1905. ['say' => 'Fourth Comment for First Article'],
  1906. ['say' => 'First Comment for Second Article'],
  1907. ['say' => 'Second Comment for Second Article'],
  1908. ];
  1909. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1910. }
  1911. /**
  1912. * Tests that Query objects can be included inside the where clause
  1913. * and be used as a normal condition, including binding any passed parameter
  1914. *
  1915. * @return void
  1916. */
  1917. public function testSubqueryInWhere()
  1918. {
  1919. $query = new Query($this->connection);
  1920. $subquery = (new Query($this->connection))
  1921. ->select(['id'])
  1922. ->from('authors')
  1923. ->where(['id' => 1]);
  1924. $result = $query
  1925. ->select(['name'])
  1926. ->from(['authors'])
  1927. ->where(['id !=' => $subquery])
  1928. ->execute();
  1929. $expected = [
  1930. ['name' => 'nate'],
  1931. ['name' => 'larry'],
  1932. ['name' => 'garrett'],
  1933. ];
  1934. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1935. $result->closeCursor();
  1936. $query = new Query($this->connection);
  1937. $subquery = (new Query($this->connection))
  1938. ->select(['id'])
  1939. ->from('comments')
  1940. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1941. $result = $query
  1942. ->select(['name'])
  1943. ->from(['authors'])
  1944. ->where(['id not in' => $subquery])
  1945. ->execute();
  1946. $expected = [
  1947. ['name' => 'mariano'],
  1948. ];
  1949. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1950. $result->closeCursor();
  1951. }
  1952. /**
  1953. * Tests that it is possible to use a subquery in a join clause
  1954. *
  1955. * @return void
  1956. */
  1957. public function testSubqueryInJoin()
  1958. {
  1959. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1960. $query = new Query($this->connection);
  1961. $result = $query
  1962. ->select(['title', 'name'])
  1963. ->from('articles')
  1964. ->join(['b' => $subquery])
  1965. ->execute();
  1966. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1967. $result->closeCursor();
  1968. $subquery->where(['id' => 1]);
  1969. $result = $query->execute();
  1970. $this->assertCount(3, $result);
  1971. $result->closeCursor();
  1972. $query->join(['b' => ['table' => $subquery, 'conditions' => [$query->newExpr()->equalFields('b.id', 'articles.id')]]], [], true);
  1973. $result = $query->execute();
  1974. $this->assertCount(1, $result);
  1975. $result->closeCursor();
  1976. }
  1977. /**
  1978. * Tests that it is possible to one or multiple UNION statements in a query
  1979. *
  1980. * @return void
  1981. */
  1982. public function testUnion()
  1983. {
  1984. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1985. $query = new Query($this->connection);
  1986. $result = $query->select(['id', 'comment'])
  1987. ->from(['c' => 'comments'])
  1988. ->union($union)
  1989. ->execute();
  1990. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1991. $rows = $result->fetchAll();
  1992. $result->closeCursor();
  1993. $union->select(['foo' => 'id', 'bar' => 'title']);
  1994. $union = (new Query($this->connection))
  1995. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1996. ->from(['b' => 'authors'])
  1997. ->where(['id ' => 1])
  1998. ->order(['id' => 'desc']);
  1999. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  2000. $result = $query->execute();
  2001. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  2002. $this->assertNotEquals($rows, $result->fetchAll());
  2003. $result->closeCursor();
  2004. $union = (new Query($this->connection))
  2005. ->select(['id', 'title'])
  2006. ->from(['c' => 'articles']);
  2007. $query->select(['id', 'comment'], true)->union($union, true);
  2008. $result = $query->execute();
  2009. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2010. $this->assertEquals($rows, $result->fetchAll());
  2011. $result->closeCursor();
  2012. }
  2013. /**
  2014. * Tests that it is possible to run unions with order statements
  2015. *
  2016. * @return void
  2017. */
  2018. public function testUnionOrderBy()
  2019. {
  2020. $this->skipIf(
  2021. ($this->connection->driver() instanceof \Cake\Database\Driver\Sqlite ||
  2022. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver),
  2023. 'Driver does not support ORDER BY in UNIONed queries.'
  2024. );
  2025. $union = (new Query($this->connection))
  2026. ->select(['id', 'title'])
  2027. ->from(['a' => 'articles'])
  2028. ->order(['a.id' => 'asc']);
  2029. $query = new Query($this->connection);
  2030. $result = $query->select(['id', 'comment'])
  2031. ->from(['c' => 'comments'])
  2032. ->order(['c.id' => 'asc'])
  2033. ->union($union)
  2034. ->execute();
  2035. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2036. $rows = $result->fetchAll();
  2037. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2038. }
  2039. /**
  2040. * Tests that UNION ALL can be built by setting the second param of union() to true
  2041. *
  2042. * @return void
  2043. */
  2044. public function testUnionAll()
  2045. {
  2046. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  2047. $query = new Query($this->connection);
  2048. $result = $query->select(['id', 'comment'])
  2049. ->from(['c' => 'comments'])
  2050. ->union($union)
  2051. ->execute();
  2052. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  2053. $rows = $result->fetchAll();
  2054. $result->closeCursor();
  2055. $union->select(['foo' => 'id', 'bar' => 'title']);
  2056. $union = (new Query($this->connection))
  2057. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  2058. ->from(['b' => 'authors'])
  2059. ->where(['id ' => 1])
  2060. ->order(['id' => 'desc']);
  2061. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  2062. $result = $query->execute();
  2063. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2064. $this->assertNotEquals($rows, $result->fetchAll());
  2065. $result->closeCursor();
  2066. }
  2067. /**
  2068. * Tests stacking decorators for results and resetting the list of decorators
  2069. *
  2070. * @return void
  2071. */
  2072. public function testDecorateResults()
  2073. {
  2074. $query = new Query($this->connection);
  2075. $result = $query
  2076. ->select(['id', 'title'])
  2077. ->from('articles')
  2078. ->order(['id' => 'ASC'])
  2079. ->decorateResults(function ($row) {
  2080. $row['modified_id'] = $row['id'] + 1;
  2081. return $row;
  2082. })
  2083. ->execute();
  2084. while ($row = $result->fetch('assoc')) {
  2085. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  2086. }
  2087. $result = $query->decorateResults(function ($row) {
  2088. $row['modified_id']--;
  2089. return $row;
  2090. })->execute();
  2091. while ($row = $result->fetch('assoc')) {
  2092. $this->assertEquals($row['id'], $row['modified_id']);
  2093. }
  2094. $result->closeCursor();
  2095. $result = $query
  2096. ->decorateResults(function ($row) {
  2097. $row['foo'] = 'bar';
  2098. return $row;
  2099. }, true)
  2100. ->execute();
  2101. while ($row = $result->fetch('assoc')) {
  2102. $this->assertEquals('bar', $row['foo']);
  2103. $this->assertArrayNotHasKey('modified_id', $row);
  2104. }
  2105. $results = $query->decorateResults(null, true)->execute();
  2106. while ($row = $result->fetch('assoc')) {
  2107. $this->assertArrayNotHasKey('foo', $row);
  2108. $this->assertArrayNotHasKey('modified_id', $row);
  2109. }
  2110. $results->closeCursor();
  2111. }
  2112. /**
  2113. * Test a basic delete using from()
  2114. *
  2115. * @return void
  2116. */
  2117. public function testDeleteWithFrom()
  2118. {
  2119. $query = new Query($this->connection);
  2120. $query->delete()
  2121. ->from('authors')
  2122. ->where('1 = 1');
  2123. $result = $query->sql();
  2124. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2125. $result = $query->execute();
  2126. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2127. $this->assertCount(self::AUTHOR_COUNT, $result);
  2128. $result->closeCursor();
  2129. }
  2130. /**
  2131. * Test delete with from and alias.
  2132. *
  2133. * @return void
  2134. */
  2135. public function testDeleteWithAliasedFrom()
  2136. {
  2137. $query = new Query($this->connection);
  2138. $query->delete()
  2139. ->from(['a ' => 'authors'])
  2140. ->where(['a.id !=' => 99]);
  2141. $result = $query->sql();
  2142. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, !$this->autoQuote);
  2143. $result = $query->execute();
  2144. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2145. $this->assertCount(self::AUTHOR_COUNT, $result);
  2146. $result->closeCursor();
  2147. }
  2148. /**
  2149. * Test a basic delete with no from() call.
  2150. *
  2151. * @return void
  2152. */
  2153. public function testDeleteNoFrom()
  2154. {
  2155. $query = new Query($this->connection);
  2156. $query->delete('authors')
  2157. ->where('1 = 1');
  2158. $result = $query->sql();
  2159. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2160. $result = $query->execute();
  2161. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2162. $this->assertCount(self::AUTHOR_COUNT, $result);
  2163. $result->closeCursor();
  2164. }
  2165. /**
  2166. * Test setting select() & delete() modes.
  2167. *
  2168. * @return void
  2169. */
  2170. public function testSelectAndDeleteOnSameQuery()
  2171. {
  2172. $query = new Query($this->connection);
  2173. $result = $query->select()
  2174. ->delete('authors')
  2175. ->where('1 = 1');
  2176. $result = $query->sql();
  2177. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2178. $this->assertContains(' WHERE 1 = 1', $result);
  2179. }
  2180. /**
  2181. * Test a simple update.
  2182. *
  2183. * @return void
  2184. */
  2185. public function testUpdateSimple()
  2186. {
  2187. $query = new Query($this->connection);
  2188. $query->update('authors')
  2189. ->set('name', 'mark')
  2190. ->where(['id' => 1]);
  2191. $result = $query->sql();
  2192. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, !$this->autoQuote);
  2193. $result = $query->execute();
  2194. $this->assertCount(1, $result);
  2195. $result->closeCursor();
  2196. }
  2197. /**
  2198. * Test update with multiple fields.
  2199. *
  2200. * @return void
  2201. */
  2202. public function testUpdateMultipleFields()
  2203. {
  2204. $query = new Query($this->connection);
  2205. $query->update('articles')
  2206. ->set('title', 'mark', 'string')
  2207. ->set('body', 'some text', 'string')
  2208. ->where(['id' => 1]);
  2209. $result = $query->sql();
  2210. $this->assertQuotedQuery(
  2211. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2212. $result,
  2213. !$this->autoQuote
  2214. );
  2215. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2216. $result = $query->execute();
  2217. $this->assertCount(1, $result);
  2218. $result->closeCursor();
  2219. }
  2220. /**
  2221. * Test updating multiple fields with an array.
  2222. *
  2223. * @return void
  2224. */
  2225. public function testUpdateMultipleFieldsArray()
  2226. {
  2227. $query = new Query($this->connection);
  2228. $query->update('articles')
  2229. ->set([
  2230. 'title' => 'mark',
  2231. 'body' => 'some text'
  2232. ], ['title' => 'string', 'body' => 'string'])
  2233. ->where(['id' => 1]);
  2234. $result = $query->sql();
  2235. $this->assertQuotedQuery(
  2236. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2237. $result,
  2238. !$this->autoQuote
  2239. );
  2240. $this->assertQuotedQuery('WHERE <id> = :', $result, !$this->autoQuote);
  2241. $result = $query->execute();
  2242. $this->assertCount(1, $result);
  2243. $result->closeCursor();
  2244. }
  2245. /**
  2246. * Test updates with an expression.
  2247. *
  2248. * @return void
  2249. */
  2250. public function testUpdateWithExpression()
  2251. {
  2252. $query = new Query($this->connection);
  2253. $expr = $query->newExpr()->equalFields('article_id', 'user_id');
  2254. $query->update('comments')
  2255. ->set($expr)
  2256. ->where(['id' => 1]);
  2257. $result = $query->sql();
  2258. $this->assertQuotedQuery(
  2259. 'UPDATE <comments> SET <article_id> = \(<user_id>\) WHERE <id> = :',
  2260. $result,
  2261. !$this->autoQuote
  2262. );
  2263. $result = $query->execute();
  2264. $this->assertCount(1, $result);
  2265. $result->closeCursor();
  2266. }
  2267. /**
  2268. * Test update with array fields and types.
  2269. *
  2270. * @return void
  2271. */
  2272. public function testUpdateArrayFields()
  2273. {
  2274. $query = new Query($this->connection);
  2275. $date = new \DateTime;
  2276. $query->update('comments')
  2277. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  2278. ->where(['id' => 1]);
  2279. $result = $query->sql();
  2280. $this->assertQuotedQuery(
  2281. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2282. $result,
  2283. !$this->autoQuote
  2284. );
  2285. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2286. $result = $query->execute();
  2287. $this->assertCount(1, $result);
  2288. $query = new Query($this->connection);
  2289. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  2290. $result = $result->fetchAll('assoc')[0]['created'];
  2291. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  2292. }
  2293. /**
  2294. * Test update with callable in set
  2295. *
  2296. * @return void
  2297. */
  2298. public function testUpdateSetCallable()
  2299. {
  2300. $query = new Query($this->connection);
  2301. $date = new \DateTime;
  2302. $query->update('comments')
  2303. ->set(function ($exp) use ($date) {
  2304. return $exp
  2305. ->eq('comment', 'mark')
  2306. ->eq('created', $date, 'date');
  2307. })
  2308. ->where(['id' => 1]);
  2309. $result = $query->sql();
  2310. $this->assertQuotedQuery(
  2311. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2312. $result,
  2313. !$this->autoQuote
  2314. );
  2315. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2316. $result = $query->execute();
  2317. $this->assertCount(1, $result);
  2318. }
  2319. /**
  2320. * You cannot call values() before insert() it causes all sorts of pain.
  2321. *
  2322. * @expectedException \Cake\Database\Exception
  2323. * @return void
  2324. */
  2325. public function testInsertValuesBeforeInsertFailure()
  2326. {
  2327. $query = new Query($this->connection);
  2328. $query->select('*')->values([
  2329. 'id' => 1,
  2330. 'title' => 'mark',
  2331. 'body' => 'test insert'
  2332. ]);
  2333. }
  2334. /**
  2335. * Inserting nothing should not generate an error.
  2336. *
  2337. * @expectedException \RuntimeException
  2338. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  2339. * @return void
  2340. */
  2341. public function testInsertNothing()
  2342. {
  2343. $query = new Query($this->connection);
  2344. $query->insert([]);
  2345. }
  2346. /**
  2347. * Test inserting a single row.
  2348. *
  2349. * @return void
  2350. */
  2351. public function testInsertSimple()
  2352. {
  2353. $query = new Query($this->connection);
  2354. $query->insert(['title', 'body'])
  2355. ->into('articles')
  2356. ->values([
  2357. 'title' => 'mark',
  2358. 'body' => 'test insert'
  2359. ]);
  2360. $result = $query->sql();
  2361. $this->assertQuotedQuery(
  2362. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2363. 'VALUES \(:c0, :c1\)',
  2364. $result,
  2365. !$this->autoQuote
  2366. );
  2367. $result = $query->execute();
  2368. $result->closeCursor();
  2369. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2370. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2371. $this->assertCount(1, $result, '1 row should be inserted');
  2372. }
  2373. $expected = [
  2374. [
  2375. 'id' => 4,
  2376. 'author_id' => null,
  2377. 'title' => 'mark',
  2378. 'body' => 'test insert',
  2379. 'published' => 'N',
  2380. ]
  2381. ];
  2382. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2383. }
  2384. /**
  2385. * Test an insert when not all the listed fields are provided.
  2386. * Columns should be matched up where possible.
  2387. *
  2388. * @return void
  2389. */
  2390. public function testInsertSparseRow()
  2391. {
  2392. $query = new Query($this->connection);
  2393. $query->insert(['title', 'body'])
  2394. ->into('articles')
  2395. ->values([
  2396. 'title' => 'mark',
  2397. ]);
  2398. $result = $query->sql();
  2399. $this->assertQuotedQuery(
  2400. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2401. 'VALUES \(:c0, :c1\)',
  2402. $result,
  2403. !$this->autoQuote
  2404. );
  2405. $result = $query->execute();
  2406. $result->closeCursor();
  2407. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2408. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2409. $this->assertCount(1, $result, '1 row should be inserted');
  2410. }
  2411. $expected = [
  2412. [
  2413. 'id' => 4,
  2414. 'author_id' => null,
  2415. 'title' => 'mark',
  2416. 'body' => null,
  2417. 'published' => 'N',
  2418. ]
  2419. ];
  2420. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2421. }
  2422. /**
  2423. * Test inserting multiple rows with sparse data.
  2424. *
  2425. * @return void
  2426. */
  2427. public function testInsertMultipleRowsSparse()
  2428. {
  2429. $query = new Query($this->connection);
  2430. $query->insert(['title', 'body'])
  2431. ->into('articles')
  2432. ->values([
  2433. 'body' => 'test insert'
  2434. ])
  2435. ->values([
  2436. 'title' => 'jose',
  2437. ]);
  2438. $result = $query->execute();
  2439. $result->closeCursor();
  2440. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2441. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2442. $this->assertCount(2, $result, '2 rows should be inserted');
  2443. }
  2444. $expected = [
  2445. [
  2446. 'id' => 4,
  2447. 'author_id' => null,
  2448. 'title' => null,
  2449. 'body' => 'test insert',
  2450. 'published' => 'N',
  2451. ],
  2452. [
  2453. 'id' => 5,
  2454. 'author_id' => null,
  2455. 'title' => 'jose',
  2456. 'body' => null,
  2457. 'published' => 'N',
  2458. ],
  2459. ];
  2460. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2461. }
  2462. /**
  2463. * Test that INSERT INTO ... SELECT works.
  2464. *
  2465. * @return void
  2466. */
  2467. public function testInsertFromSelect()
  2468. {
  2469. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2470. ->from('authors')
  2471. ->where(['id' => 1]);
  2472. $query = new Query($this->connection);
  2473. $query->insert(
  2474. ['title', 'body', 'author_id'],
  2475. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2476. )
  2477. ->into('articles')
  2478. ->values($select);
  2479. $result = $query->sql();
  2480. $this->assertQuotedQuery(
  2481. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
  2482. $result,
  2483. !$this->autoQuote
  2484. );
  2485. $this->assertQuotedQuery(
  2486. 'SELECT <name>, \'some text\', 99 FROM <authors>',
  2487. $result,
  2488. !$this->autoQuote
  2489. );
  2490. $result = $query->execute();
  2491. $result->closeCursor();
  2492. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2493. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2494. $this->assertCount(1, $result);
  2495. }
  2496. $result = (new Query($this->connection))->select('*')
  2497. ->from('articles')
  2498. ->where(['author_id' => 99])
  2499. ->execute();
  2500. $this->assertCount(1, $result);
  2501. $expected = [
  2502. 'id' => 4,
  2503. 'title' => 'mariano',
  2504. 'body' => 'some text',
  2505. 'author_id' => 99,
  2506. 'published' => 'N',
  2507. ];
  2508. $this->assertEquals($expected, $result->fetch('assoc'));
  2509. }
  2510. /**
  2511. * Test that an exception is raised when mixing query + array types.
  2512. *
  2513. * @expectedException \Cake\Database\Exception
  2514. */
  2515. public function testInsertFailureMixingTypesArrayFirst()
  2516. {
  2517. $query = new Query($this->connection);
  2518. $query->insert(['name'])
  2519. ->into('articles')
  2520. ->values(['name' => 'mark'])
  2521. ->values(new Query($this->connection));
  2522. }
  2523. /**
  2524. * Test that an exception is raised when mixing query + array types.
  2525. *
  2526. * @expectedException \Cake\Database\Exception
  2527. */
  2528. public function testInsertFailureMixingTypesQueryFirst()
  2529. {
  2530. $query = new Query($this->connection);
  2531. $query->insert(['name'])
  2532. ->into('articles')
  2533. ->values(new Query($this->connection))
  2534. ->values(['name' => 'mark']);
  2535. }
  2536. /**
  2537. * Test that insert can use expression objects as values.
  2538. *
  2539. * @return void
  2540. */
  2541. public function testInsertExpressionValues()
  2542. {
  2543. $query = new Query($this->connection);
  2544. $query->insert(['title', 'author_id'])
  2545. ->into('articles')
  2546. ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
  2547. $result = $query->execute();
  2548. $result->closeCursor();
  2549. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2550. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2551. $this->assertCount(1, $result);
  2552. }
  2553. $result = (new Query($this->connection))->select('*')
  2554. ->from('articles')
  2555. ->where(['author_id' => 99])
  2556. ->execute();
  2557. $this->assertCount(1, $result);
  2558. $expected = [
  2559. 'id' => 4,
  2560. 'title' => 'jose',
  2561. 'body' => null,
  2562. 'author_id' => '99',
  2563. 'published' => 'N',
  2564. ];
  2565. $this->assertEquals($expected, $result->fetch('assoc'));
  2566. $subquery = new Query($this->connection);
  2567. $subquery->select(['name'])
  2568. ->from('authors')
  2569. ->where(['id' => 1]);
  2570. $query = new Query($this->connection);
  2571. $query->insert(['title', 'author_id'])
  2572. ->into('articles')
  2573. ->values(['title' => $subquery, 'author_id' => 100]);
  2574. $result = $query->execute();
  2575. $result->closeCursor();
  2576. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2577. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2578. $this->assertCount(1, $result);
  2579. }
  2580. $result = (new Query($this->connection))->select('*')
  2581. ->from('articles')
  2582. ->where(['author_id' => 100])
  2583. ->execute();
  2584. $this->assertCount(1, $result);
  2585. $expected = [
  2586. 'id' => 5,
  2587. 'title' => 'mariano',
  2588. 'body' => null,
  2589. 'author_id' => '100',
  2590. 'published' => 'N',
  2591. ];
  2592. $this->assertEquals($expected, $result->fetch('assoc'));
  2593. }
  2594. /**
  2595. * Tests that functions are correctly transformed and their parameters are bound
  2596. *
  2597. * @group FunctionExpression
  2598. * @return void
  2599. */
  2600. public function testSQLFunctions()
  2601. {
  2602. $query = new Query($this->connection);
  2603. $result = $query->select(
  2604. function ($q) {
  2605. return ['total' => $q->func()->count('*')];
  2606. }
  2607. )
  2608. ->from('comments')
  2609. ->execute();
  2610. $expected = [['total' => 6]];
  2611. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2612. $query = new Query($this->connection);
  2613. $result = $query->select([
  2614. 'c' => $query->func()->concat(['comment' => 'literal', ' is appended'])
  2615. ])
  2616. ->from('comments')
  2617. ->order(['c' => 'ASC'])
  2618. ->limit(1)
  2619. ->execute();
  2620. $expected = [
  2621. ['c' => 'First Comment for First Article is appended'],
  2622. ];
  2623. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2624. $query = new Query($this->connection);
  2625. $result = $query
  2626. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2627. ->execute()
  2628. ->fetchAll('assoc');
  2629. $this->assertEquals(3, abs($result[0]['d']));
  2630. $query = new Query($this->connection);
  2631. $result = $query
  2632. ->select(['d' => $query->func()->now('date')])
  2633. ->execute();
  2634. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2635. $query = new Query($this->connection);
  2636. $result = $query
  2637. ->select(['d' => $query->func()->now('time')])
  2638. ->execute();
  2639. $this->assertWithinRange(
  2640. date('U'),
  2641. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2642. 1
  2643. );
  2644. $query = new Query($this->connection);
  2645. $result = $query
  2646. ->select(['d' => $query->func()->now()])
  2647. ->execute();
  2648. $this->assertWithinRange(
  2649. date('U'),
  2650. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2651. 1
  2652. );
  2653. $query = new Query($this->connection);
  2654. $result = $query
  2655. ->select([
  2656. 'd' => $query->func()->datePart('day', 'created'),
  2657. 'm' => $query->func()->datePart('month', 'created'),
  2658. 'y' => $query->func()->datePart('year', 'created'),
  2659. 'de' => $query->func()->extract('day', 'created'),
  2660. 'me' => $query->func()->extract('month', 'created'),
  2661. 'ye' => $query->func()->extract('year', 'created'),
  2662. 'wd' => $query->func()->weekday('created'),
  2663. 'dow' => $query->func()->dayOfWeek('created'),
  2664. 'addDays' => $query->func()->dateAdd('created', 2, 'day'),
  2665. 'substractYears' => $query->func()->dateAdd('created', -2, 'year')
  2666. ])
  2667. ->from('comments')
  2668. ->where(['created' => '2007-03-18 10:45:23'])
  2669. ->execute()
  2670. ->fetchAll('assoc');
  2671. $result[0]['m'] = ltrim($result[0]['m'], '0');
  2672. $result[0]['me'] = ltrim($result[0]['me'], '0');
  2673. $result[0]['addDays'] = substr($result[0]['addDays'], 0, 10);
  2674. $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 10);
  2675. $expected = [
  2676. 'd' => '18',
  2677. 'm' => '3',
  2678. 'y' => '2007',
  2679. 'de' => '18',
  2680. 'me' => '3',
  2681. 'ye' => '2007',
  2682. 'wd' => '1', // Sunday
  2683. 'dow' => '1',
  2684. 'addDays' => '2007-03-20',
  2685. 'substractYears' => '2005-03-18'
  2686. ];
  2687. $this->assertEquals($expected, $result[0]);
  2688. }
  2689. /**
  2690. * Tests that default types are passed to functions accepting a $types param
  2691. *
  2692. * @return void
  2693. */
  2694. public function testDefaultTypes()
  2695. {
  2696. $query = new Query($this->connection);
  2697. $this->assertEquals([], $query->defaultTypes());
  2698. $types = ['id' => 'integer', 'created' => 'datetime'];
  2699. $this->assertSame($query, $query->defaultTypes($types));
  2700. $this->assertSame($types, $query->defaultTypes());
  2701. $results = $query->select(['id', 'comment'])
  2702. ->from('comments')
  2703. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2704. ->execute();
  2705. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2706. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2707. // Now test default can be overridden
  2708. $types = ['created' => 'date'];
  2709. $results = $query
  2710. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2711. ->execute();
  2712. $this->assertCount(6, $results, 'All 6 rows should match.');
  2713. }
  2714. /**
  2715. * Tests parameter binding
  2716. *
  2717. * @return void
  2718. */
  2719. public function testBind()
  2720. {
  2721. $query = new Query($this->connection);
  2722. $results = $query->select(['id', 'comment'])
  2723. ->from('comments')
  2724. ->where(['created BETWEEN :foo AND :bar'])
  2725. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2726. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2727. ->execute();
  2728. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2729. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2730. $query = new Query($this->connection);
  2731. $results = $query->select(['id', 'comment'])
  2732. ->from('comments')
  2733. ->where(['created BETWEEN :foo AND :bar'])
  2734. ->bind(':foo', '2007-03-18 10:50:00')
  2735. ->bind(':bar', '2007-03-18 10:52:00')
  2736. ->execute();
  2737. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2738. }
  2739. /**
  2740. * Test that epilog() will actually append a string to a select query
  2741. *
  2742. * @return void
  2743. */
  2744. public function testAppendSelect()
  2745. {
  2746. $query = new Query($this->connection);
  2747. $sql = $query
  2748. ->select(['id', 'title'])
  2749. ->from('articles')
  2750. ->where(['id' => 1])
  2751. ->epilog('FOR UPDATE')
  2752. ->sql();
  2753. $this->assertContains('SELECT', $sql);
  2754. $this->assertContains('FROM', $sql);
  2755. $this->assertContains('WHERE', $sql);
  2756. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2757. }
  2758. /**
  2759. * Test that epilog() will actually append a string to an insert query
  2760. *
  2761. * @return void
  2762. */
  2763. public function testAppendInsert()
  2764. {
  2765. $query = new Query($this->connection);
  2766. $sql = $query
  2767. ->insert(['id', 'title'])
  2768. ->into('articles')
  2769. ->values([1, 'a title'])
  2770. ->epilog('RETURNING id')
  2771. ->sql();
  2772. $this->assertContains('INSERT', $sql);
  2773. $this->assertContains('INTO', $sql);
  2774. $this->assertContains('VALUES', $sql);
  2775. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2776. }
  2777. /**
  2778. * Test that epilog() will actually append a string to an update query
  2779. *
  2780. * @return void
  2781. */
  2782. public function testAppendUpdate()
  2783. {
  2784. $query = new Query($this->connection);
  2785. $sql = $query
  2786. ->update('articles')
  2787. ->set(['title' => 'foo'])
  2788. ->where(['id' => 1])
  2789. ->epilog('RETURNING id')
  2790. ->sql();
  2791. $this->assertContains('UPDATE', $sql);
  2792. $this->assertContains('SET', $sql);
  2793. $this->assertContains('WHERE', $sql);
  2794. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2795. }
  2796. /**
  2797. * Test that epilog() will actually append a string to a delete query
  2798. *
  2799. * @return void
  2800. */
  2801. public function testAppendDelete()
  2802. {
  2803. $query = new Query($this->connection);
  2804. $sql = $query
  2805. ->delete('articles')
  2806. ->where(['id' => 1])
  2807. ->epilog('RETURNING id')
  2808. ->sql();
  2809. $this->assertContains('DELETE FROM', $sql);
  2810. $this->assertContains('WHERE', $sql);
  2811. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2812. }
  2813. /**
  2814. * Tests automatic identifier quoting in the select clause
  2815. *
  2816. * @return void
  2817. */
  2818. public function testQuotingSelectFieldsAndAlias()
  2819. {
  2820. $this->connection->driver()->autoQuoting(true);
  2821. $query = new Query($this->connection);
  2822. $sql = $query->select(['something'])->sql();
  2823. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2824. $query = new Query($this->connection);
  2825. $sql = $query->select(['foo' => 'something'])->sql();
  2826. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2827. $query = new Query($this->connection);
  2828. $sql = $query->select(['foo' => 1])->sql();
  2829. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2830. $query = new Query($this->connection);
  2831. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2832. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2833. $query = new Query($this->connection);
  2834. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2835. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2836. $query = new Query($this->connection);
  2837. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2838. $this->assertQuotedQuery('<bar>', $sql);
  2839. }
  2840. /**
  2841. * Tests automatic identifier quoting in the from clause
  2842. *
  2843. * @return void
  2844. */
  2845. public function testQuotingFromAndAlias()
  2846. {
  2847. $this->connection->driver()->autoQuoting(true);
  2848. $query = new Query($this->connection);
  2849. $sql = $query->select('*')->from(['something'])->sql();
  2850. $this->assertQuotedQuery('FROM <something>', $sql);
  2851. $query = new Query($this->connection);
  2852. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2853. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  2854. $query = new Query($this->connection);
  2855. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2856. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  2857. }
  2858. /**
  2859. * Tests automatic identifier quoting for DISTINCT ON
  2860. *
  2861. * @return void
  2862. */
  2863. public function testQuotingDistinctOn()
  2864. {
  2865. $this->connection->driver()->autoQuoting(true);
  2866. $query = new Query($this->connection);
  2867. $sql = $query->select('*')->distinct(['something'])->sql();
  2868. $this->assertQuotedQuery('<something>', $sql);
  2869. }
  2870. /**
  2871. * Tests automatic identifier quoting in the join clause
  2872. *
  2873. * @return void
  2874. */
  2875. public function testQuotingJoinsAndAlias()
  2876. {
  2877. $this->connection->driver()->autoQuoting(true);
  2878. $query = new Query($this->connection);
  2879. $sql = $query->select('*')->join(['something'])->sql();
  2880. $this->assertQuotedQuery('JOIN <something>', $sql);
  2881. $query = new Query($this->connection);
  2882. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2883. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2884. $query = new Query($this->connection);
  2885. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2886. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2887. }
  2888. /**
  2889. * Tests automatic identifier quoting in the group by clause
  2890. *
  2891. * @return void
  2892. */
  2893. public function testQuotingGroupBy()
  2894. {
  2895. $this->connection->driver()->autoQuoting(true);
  2896. $query = new Query($this->connection);
  2897. $sql = $query->select('*')->group(['something'])->sql();
  2898. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2899. $query = new Query($this->connection);
  2900. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2901. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2902. $query = new Query($this->connection);
  2903. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2904. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2905. }
  2906. /**
  2907. * Tests automatic identifier quoting strings inside conditions expressions
  2908. *
  2909. * @return void
  2910. */
  2911. public function testQuotingExpressions()
  2912. {
  2913. $this->connection->driver()->autoQuoting(true);
  2914. $query = new Query($this->connection);
  2915. $sql = $query->select('*')
  2916. ->where(['something' => 'value'])
  2917. ->sql();
  2918. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2919. $query = new Query($this->connection);
  2920. $sql = $query->select('*')
  2921. ->where([
  2922. 'something' => 'value',
  2923. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2924. ])
  2925. ->sql();
  2926. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2927. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2928. }
  2929. /**
  2930. * Tests that insert query parts get quoted automatically
  2931. *
  2932. * @return void
  2933. */
  2934. public function testQuotingInsert()
  2935. {
  2936. $this->connection->driver()->autoQuoting(true);
  2937. $query = new Query($this->connection);
  2938. $sql = $query->insert(['bar', 'baz'])
  2939. ->into('foo')
  2940. ->where(['something' => 'value'])
  2941. ->sql();
  2942. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2943. $query = new Query($this->connection);
  2944. $sql = $query->insert([$query->newExpr('bar')])
  2945. ->into('foo')
  2946. ->where(['something' => 'value'])
  2947. ->sql();
  2948. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2949. }
  2950. /**
  2951. * Tests converting a query to a string
  2952. *
  2953. * @return void
  2954. */
  2955. public function testToString()
  2956. {
  2957. $query = new Query($this->connection);
  2958. $query
  2959. ->select(['title'])
  2960. ->from('articles');
  2961. $result = (string)$query;
  2962. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, !$this->autoQuote);
  2963. }
  2964. /**
  2965. * Tests __debugInfo
  2966. *
  2967. * @return void
  2968. */
  2969. public function testDebugInfo()
  2970. {
  2971. $query = (new Query($this->connection))->select('*')
  2972. ->from('articles')
  2973. ->defaultTypes(['id' => 'integer'])
  2974. ->where(['id' => '1']);
  2975. $expected = [
  2976. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2977. 'sql' => $query->sql(),
  2978. 'params' => [
  2979. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2980. ],
  2981. 'defaultTypes' => ['id' => 'integer'],
  2982. 'decorators' => 0,
  2983. 'executed' => false
  2984. ];
  2985. $result = $query->__debugInfo();
  2986. $this->assertEquals($expected, $result);
  2987. $query->execute();
  2988. $expected = [
  2989. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2990. 'sql' => $query->sql(),
  2991. 'params' => [
  2992. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2993. ],
  2994. 'defaultTypes' => ['id' => 'integer'],
  2995. 'decorators' => 0,
  2996. 'executed' => true
  2997. ];
  2998. $result = $query->__debugInfo();
  2999. $this->assertEquals($expected, $result);
  3000. }
  3001. /**
  3002. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  3003. *
  3004. * @return void
  3005. */
  3006. public function testIsNullWithExpressions()
  3007. {
  3008. $query = new Query($this->connection);
  3009. $subquery = (new Query($this->connection))
  3010. ->select(['id'])
  3011. ->from('authors')
  3012. ->where(['id' => 1]);
  3013. $result = $query
  3014. ->select(['name'])
  3015. ->from(['authors'])
  3016. ->where(function ($exp) use ($subquery) {
  3017. return $exp->isNotNull($subquery);
  3018. })
  3019. ->execute();
  3020. $this->assertNotEmpty($result->fetchAll('assoc'));
  3021. $result = (new Query($this->connection))
  3022. ->select(['name'])
  3023. ->from(['authors'])
  3024. ->where(function ($exp) use ($subquery) {
  3025. return $exp->isNull($subquery);
  3026. })
  3027. ->execute();
  3028. $this->assertEmpty($result->fetchAll('assoc'));
  3029. }
  3030. /**
  3031. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  3032. * when using autoQuoting
  3033. *
  3034. * @return void
  3035. */
  3036. public function testIsNullAutoQuoting()
  3037. {
  3038. $this->connection->driver()->autoQuoting(true);
  3039. $query = new Query($this->connection);
  3040. $query->select('*')->from('things')->where(function ($exp) {
  3041. return $exp->isNull('field');
  3042. });
  3043. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  3044. $query = new Query($this->connection);
  3045. $query->select('*')->from('things')->where(function ($exp) {
  3046. return $exp->isNotNull('field');
  3047. });
  3048. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  3049. }
  3050. /**
  3051. * Tests that using the IS operator will automatically translate to the best
  3052. * possible operator depending on the passed value
  3053. *
  3054. * @return void
  3055. */
  3056. public function testDirectIsNull()
  3057. {
  3058. $sql = (new Query($this->connection))
  3059. ->select(['name'])
  3060. ->from(['authors'])
  3061. ->where(['name IS' => null])
  3062. ->sql();
  3063. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, !$this->autoQuote);
  3064. $results = (new Query($this->connection))
  3065. ->select(['name'])
  3066. ->from(['authors'])
  3067. ->where(['name IS' => 'larry'])
  3068. ->execute();
  3069. $this->assertCount(1, $results);
  3070. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  3071. }
  3072. /**
  3073. * Tests that using the IS NOT operator will automatically translate to the best
  3074. * possible operator depending on the passed value
  3075. *
  3076. * @return void
  3077. */
  3078. public function testDirectIsNotNull()
  3079. {
  3080. $sql = (new Query($this->connection))
  3081. ->select(['name'])
  3082. ->from(['authors'])
  3083. ->where(['name IS NOT' => null])
  3084. ->sql();
  3085. $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, !$this->autoQuote);
  3086. $results = (new Query($this->connection))
  3087. ->select(['name'])
  3088. ->from(['authors'])
  3089. ->where(['name IS NOT' => 'larry'])
  3090. ->execute();
  3091. $this->assertCount(3, $results);
  3092. $this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
  3093. }
  3094. /**
  3095. * Tests that case statements work correctly for various use-cases.
  3096. *
  3097. * @return void
  3098. */
  3099. public function testSqlCaseStatement()
  3100. {
  3101. $query = new Query($this->connection);
  3102. $publishedCase = $query
  3103. ->newExpr()
  3104. ->addCase(
  3105. $query
  3106. ->newExpr()
  3107. ->add(['published' => 'Y']),
  3108. 1,
  3109. 'integer'
  3110. );
  3111. $notPublishedCase = $query
  3112. ->newExpr()
  3113. ->addCase(
  3114. $query
  3115. ->newExpr()
  3116. ->add(['published' => 'N']),
  3117. 1,
  3118. 'integer'
  3119. );
  3120. //Postgres requires the case statement to be cast to a integer
  3121. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  3122. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  3123. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  3124. }
  3125. $results = $query
  3126. ->select([
  3127. 'published' => $query->func()->sum($publishedCase),
  3128. 'not_published' => $query->func()->sum($notPublishedCase)
  3129. ])
  3130. ->from(['comments'])
  3131. ->execute()
  3132. ->fetchAll('assoc');
  3133. $this->assertEquals(5, $results[0]['published']);
  3134. $this->assertEquals(1, $results[0]['not_published']);
  3135. $query = new Query($this->connection);
  3136. $query
  3137. ->insert(['article_id', 'user_id', 'comment', 'published'])
  3138. ->into('comments')
  3139. ->values([
  3140. 'article_id' => 2,
  3141. 'user_id' => 1,
  3142. 'comment' => 'In limbo',
  3143. 'published' => 'L'
  3144. ])
  3145. ->execute()
  3146. ->closeCursor();
  3147. $query = new Query($this->connection);
  3148. $conditions = [
  3149. $query
  3150. ->newExpr()
  3151. ->add(['published' => 'Y']),
  3152. $query
  3153. ->newExpr()
  3154. ->add(['published' => 'N'])
  3155. ];
  3156. $values = [
  3157. 'Published',
  3158. 'Not published',
  3159. 'None'
  3160. ];
  3161. $results = $query
  3162. ->select([
  3163. 'id',
  3164. 'comment',
  3165. 'status' => $query->newExpr()->addCase($conditions, $values)
  3166. ])
  3167. ->from(['comments'])
  3168. ->execute()
  3169. ->fetchAll('assoc');
  3170. $this->assertEquals('Published', $results[2]['status']);
  3171. $this->assertEquals('Not published', $results[3]['status']);
  3172. $this->assertEquals('None', $results[6]['status']);
  3173. }
  3174. /**
  3175. * Shows that bufferResults(false) will prevent client-side results buffering
  3176. *
  3177. * @return void
  3178. */
  3179. public function testUnbufferedQuery()
  3180. {
  3181. $query = new Query($this->connection);
  3182. $result = $query->select(['body', 'author_id'])
  3183. ->from('articles')
  3184. ->bufferResults(false)
  3185. ->execute();
  3186. if (!method_exists($result, 'bufferResults')) {
  3187. $result->closeCursor();
  3188. $this->markTestSkipped('This driver does not support unbuffered queries');
  3189. }
  3190. $this->assertCount(0, $result, 'Unbuffered queries only have a count when results are fetched');
  3191. $list = $result->fetchAll('assoc');
  3192. $this->assertCount(3, $list);
  3193. $result->closeCursor();
  3194. $query = new Query($this->connection);
  3195. $result = $query->select(['body', 'author_id'])
  3196. ->from('articles')
  3197. ->execute();
  3198. $this->assertCount(3, $result, 'Buffered queries can be counted any time.');
  3199. $list = $result->fetchAll('assoc');
  3200. $this->assertCount(3, $list);
  3201. $result->closeCursor();
  3202. }
  3203. /**
  3204. * Test that cloning goes deep.
  3205. *
  3206. * @return void
  3207. */
  3208. public function testDeepClone()
  3209. {
  3210. $query = new Query($this->connection);
  3211. $query->select(['id', 'title' => $query->func()->concat(['title' => 'literal', 'test'])])
  3212. ->from('articles')
  3213. ->where(['Articles.id' => 1])
  3214. ->offset(10)
  3215. ->limit(1)
  3216. ->order(['Articles.id' => 'DESC']);
  3217. $dupe = clone $query;
  3218. $this->assertEquals($query->clause('where'), $dupe->clause('where'));
  3219. $this->assertNotSame($query->clause('where'), $dupe->clause('where'));
  3220. $dupe->where(['Articles.title' => 'thinger']);
  3221. $this->assertNotEquals($query->clause('where'), $dupe->clause('where'));
  3222. $this->assertNotSame(
  3223. $query->clause('select')['title'],
  3224. $dupe->clause('select')['title']
  3225. );
  3226. $this->assertEquals($query->clause('order'), $dupe->clause('order'));
  3227. $this->assertNotSame($query->clause('order'), $dupe->clause('order'));
  3228. $query->order(['Articles.title' => 'ASC']);
  3229. $this->assertNotEquals($query->clause('order'), $dupe->clause('order'));
  3230. $this->assertNotSame(
  3231. $query->selectTypeMap(),
  3232. $dupe->selectTypeMap()
  3233. );
  3234. }
  3235. /**
  3236. * Tests the selectTypeMap method
  3237. *
  3238. * @return void
  3239. */
  3240. public function testSelectTypeMap()
  3241. {
  3242. $query = new Query($this->connection);
  3243. $typeMap = $query->selectTypeMap();
  3244. $this->assertInstanceOf(TypeMap::class, $typeMap);
  3245. $another = clone $typeMap;
  3246. $query->selectTypeMap($another);
  3247. $this->assertSame($another, $query->selectTypeMap());
  3248. }
  3249. /**
  3250. * Tests the automatic type conversion for the fields in the result
  3251. *
  3252. * @return void
  3253. */
  3254. public function testSelectTypeConversion()
  3255. {
  3256. $query = new Query($this->connection);
  3257. $query
  3258. ->select(['id', 'comment', 'the_date' => 'created'])
  3259. ->from('comments')
  3260. ->limit(1)
  3261. ->selectTypeMap()->types(['id' => 'integer', 'the_date' => 'datetime']);
  3262. $result = $query->execute()->fetchAll('assoc');
  3263. $this->assertInternalType('integer', $result[0]['id']);
  3264. $this->assertInstanceOf('DateTime', $result[0]['the_date']);
  3265. }
  3266. /**
  3267. * Test removeJoin().
  3268. *
  3269. * @return void
  3270. */
  3271. public function testRemoveJoin()
  3272. {
  3273. $query = new Query($this->connection);
  3274. $query->select(['id', 'title'])
  3275. ->from('articles')
  3276. ->join(['authors' => [
  3277. 'type' => 'INNER',
  3278. 'conditions' => ['articles.author_id = authors.id']
  3279. ]]);
  3280. $this->assertArrayHasKey('authors', $query->join());
  3281. $this->assertSame($query, $query->removeJoin('authors'));
  3282. $this->assertArrayNotHasKey('authors', $query->join());
  3283. }
  3284. /**
  3285. * Tests that types in the type map are used in the
  3286. * specific comparison functions when using a callable
  3287. *
  3288. * @return void
  3289. */
  3290. public function testBetweenExpressionAndTypeMap()
  3291. {
  3292. $query = new Query($this->connection);
  3293. $query->select('id')
  3294. ->from('comments')
  3295. ->defaultTypes(['created' => 'datetime'])
  3296. ->where(function ($expr) {
  3297. $from = new \DateTime('2007-03-18 10:45:00');
  3298. $to = new \DateTime('2007-03-18 10:48:00');
  3299. return $expr->between('created', $from, $to);
  3300. });
  3301. $this->assertCount(2, $query->execute()->fetchAll());
  3302. }
  3303. /**
  3304. * Test use of modifiers in a INSERT query
  3305. *
  3306. * Testing the generated SQL since the modifiers are usually different per driver
  3307. *
  3308. * @return void
  3309. */
  3310. public function testInsertModifiers()
  3311. {
  3312. $query = new Query($this->connection);
  3313. $result = $query
  3314. ->insert(['title'])
  3315. ->into('articles')
  3316. ->values(['title' => 'foo'])
  3317. ->modifier('IGNORE');
  3318. $this->assertQuotedQuery(
  3319. 'INSERT IGNORE INTO <articles> \(<title>\) VALUES \(:c0\)',
  3320. $result->sql(),
  3321. !$this->autoQuote
  3322. );
  3323. $query = new Query($this->connection);
  3324. $result = $query
  3325. ->insert(['title'])
  3326. ->into('articles')
  3327. ->values(['title' => 'foo'])
  3328. ->modifier(['IGNORE', 'LOW_PRIORITY']);
  3329. $this->assertQuotedQuery(
  3330. 'INSERT IGNORE LOW_PRIORITY INTO <articles> \(<title>\) VALUES \(:c0\)',
  3331. $result->sql(),
  3332. !$this->autoQuote
  3333. );
  3334. }
  3335. /**
  3336. * Assertion for comparing a table's contents with what is in it.
  3337. *
  3338. * @param string $table
  3339. * @param int $count
  3340. * @param array $rows
  3341. * @param array $conditions
  3342. * @return void
  3343. */
  3344. public function assertTable($table, $count, $rows, $conditions = [])
  3345. {
  3346. $result = (new Query($this->connection))->select('*')
  3347. ->from($table)
  3348. ->where($conditions)
  3349. ->execute();
  3350. $this->assertCount($count, $result, 'Row count is incorrect');
  3351. $this->assertEquals($rows, $result->fetchAll('assoc'));
  3352. $result->closeCursor();
  3353. }
  3354. /**
  3355. * Assertion for comparing a regex pattern against a query having its identifiers
  3356. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  3357. * parameter is set to true, it will alter the pattern to both accept quoted and
  3358. * unquoted queries
  3359. *
  3360. * @param string $pattern
  3361. * @param string $query the result to compare against
  3362. * @param bool $optional
  3363. * @return void
  3364. */
  3365. public function assertQuotedQuery($pattern, $query, $optional = false)
  3366. {
  3367. if ($optional) {
  3368. $optional = '?';
  3369. }
  3370. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  3371. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  3372. $this->assertRegExp('#' . $pattern . '#', $query);
  3373. }
  3374. }