QueryTest.php 129 KB

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