QueryTest.php 107 KB

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