QueryTest.php 167 KB

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