QueryTest.php 151 KB

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