QueryTest.php 118 KB

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