QueryTest.php 118 KB

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