QueryTest.php 122 KB

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