QueryTest.php 119 KB

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