QueryTest.php 147 KB

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