QueryTest.php 144 KB

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