QueryTest.php 159 KB

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