QueryTest.php 165 KB

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