QueryTest.php 157 KB

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