QueryTest.php 130 KB

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