QueryTest.php 148 KB

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