QueryTest.php 145 KB

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