QueryTest.php 165 KB

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