QueryTest.php 121 KB

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