QueryTest.php 157 KB

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