QueryTest.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  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. public $fixtures = ['core.article', 'core.author', 'core.comment'];
  27. const ARTICLE_COUNT = 3;
  28. const AUTHOR_COUNT = 4;
  29. const COMMENT_COUNT = 6;
  30. public function setUp() {
  31. parent::setUp();
  32. $this->connection = ConnectionManager::get('test');
  33. $this->autoQuote = $this->connection->driver()->autoQuoting();
  34. }
  35. public function tearDown() {
  36. parent::tearDown();
  37. $this->connection->driver()->autoQuoting($this->autoQuote);
  38. unset($this->connection);
  39. }
  40. /**
  41. * Queries need a default type to prevent fatal errors
  42. * when an uninitialized query has its sql() method called.
  43. *
  44. * @return void
  45. */
  46. public function testDefaultType() {
  47. $query = new Query($this->connection);
  48. $this->assertEquals('', $query->sql());
  49. $this->assertEquals('select', $query->type());
  50. }
  51. /**
  52. * Tests that it is possible to obtain expression results from a query
  53. *
  54. * @return void
  55. */
  56. public function testSelectFieldsOnly() {
  57. $this->connection->driver()->autoQuoting(false);
  58. $query = new Query($this->connection);
  59. $result = $query->select('1 + 1')->execute();
  60. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  61. $this->assertEquals([2], $result->fetch());
  62. //This new field should be appended
  63. $result = $query->select(array('1 + 3'))->execute();
  64. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  65. $this->assertEquals([2, 4], $result->fetch());
  66. //This should now overwrite all previous fields
  67. $result = $query->select(array('1 + 2', '1 + 5'), true)->execute();
  68. $this->assertEquals([3, 6], $result->fetch());
  69. }
  70. /**
  71. * Tests that it is possible to pass a closure as fields in select()
  72. *
  73. * @return void
  74. */
  75. public function testSelectClosure() {
  76. $this->connection->driver()->autoQuoting(false);
  77. $query = new Query($this->connection);
  78. $result = $query->select(function($q) use ($query) {
  79. $this->assertSame($query, $q);
  80. return ['1 + 2', '1 + 5'];
  81. })->execute();
  82. $this->assertEquals([3, 6], $result->fetch());
  83. }
  84. /**
  85. * Tests it is possible to select fields from tables with no conditions
  86. *
  87. * @return void
  88. */
  89. public function testSelectFieldsFromTable() {
  90. $query = new Query($this->connection);
  91. $result = $query->select(array('body', 'author_id'))->from('articles')->execute();
  92. $this->assertEquals(array('body' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  93. $this->assertEquals(array('body' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  94. //Append more tables to next execution
  95. $result = $query->select('name')->from(array('authors'))->order(['name' => 'desc', 'articles.id' => 'asc'])->execute();
  96. $this->assertEquals(array('body' => 'First Article Body', 'author_id' => 1, 'name' => 'nate'), $result->fetch('assoc'));
  97. $this->assertEquals(array('body' => 'Second Article Body', 'author_id' => 3, 'name' => 'nate'), $result->fetch('assoc'));
  98. $this->assertEquals(array('body' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'), $result->fetch('assoc'));
  99. // Overwrite tables and only fetch from authors
  100. $result = $query->select('name', true)->from('authors', true)->order(['name' => 'desc'], true)->execute();
  101. $this->assertEquals(array('nate'), $result->fetch());
  102. $this->assertEquals(array('mariano'), $result->fetch());
  103. $this->assertCount(4, $result);
  104. }
  105. /**
  106. * Tests it is possible to select aliased fields
  107. *
  108. * @return void
  109. */
  110. public function testSelectAliasedFieldsFromTable() {
  111. $query = new Query($this->connection);
  112. $result = $query->select(['text' => 'body', 'author_id'])->from('articles')->execute();
  113. $this->assertEquals(array('text' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  114. $this->assertEquals(array('text' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  115. $query = new Query($this->connection);
  116. $result = $query->select(['text' => 'body', 'author' => 'author_id'])->from('articles')->execute();
  117. $this->assertEquals(array('text' => 'First Article Body', 'author' => 1), $result->fetch('assoc'));
  118. $this->assertEquals(array('text' => 'Second Article Body', 'author' => 3), $result->fetch('assoc'));
  119. $query = new Query($this->connection);
  120. $query->select(['text' => 'body'])->select(['author_id', 'foo' => 'body']);
  121. $result = $query->from('articles')->execute();
  122. $this->assertEquals(array('foo' => 'First Article Body', 'text' => 'First Article Body', 'author_id' => 1), $result->fetch('assoc'));
  123. $this->assertEquals(array('foo' => 'Second Article Body', 'text' => 'Second Article Body', 'author_id' => 3), $result->fetch('assoc'));
  124. $query = new Query($this->connection);
  125. $exp = $query->newExpr()->add('1 + 1');
  126. $comp = $query->newExpr()->add(['author_id +' => 2]);
  127. $result = $query->select(['text' => 'body', 'two' => $exp, 'three' => $comp])
  128. ->from('articles')->execute();
  129. $this->assertEquals(array('text' => 'First Article Body', 'two' => 2, 'three' => 3), $result->fetch('assoc'));
  130. $this->assertEquals(array('text' => 'Second Article Body', 'two' => 2, 'three' => 5), $result->fetch('assoc'));
  131. }
  132. /**
  133. * Tests that tables can also be aliased and referenced in the select clause using such alias
  134. *
  135. * @return void
  136. */
  137. public function testSelectAliasedTables() {
  138. $query = new Query($this->connection);
  139. $result = $query->select(['text' => 'a.body', 'a.author_id'])
  140. ->from(['a' => 'articles'])->execute();
  141. $this->assertEquals(['text' => 'First Article Body', 'author_id' => 1], $result->fetch('assoc'));
  142. $this->assertEquals(['text' => 'Second Article Body', 'author_id' => 3], $result->fetch('assoc'));
  143. $result = $query->select(['name' => 'b.name'])->from(['b' => 'authors'])
  144. ->order(['text' => 'desc', 'name' => 'desc'])
  145. ->execute();
  146. $this->assertEquals(
  147. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'nate'],
  148. $result->fetch('assoc')
  149. );
  150. $this->assertEquals(
  151. ['text' => 'Third Article Body', 'author_id' => 1, 'name' => 'mariano'],
  152. $result->fetch('assoc')
  153. );
  154. }
  155. /**
  156. * Tests it is possible to add joins to a select query
  157. *
  158. * @return void
  159. */
  160. public function testSelectWithJoins() {
  161. $query = new Query($this->connection);
  162. $result = $query
  163. ->select(['title', 'name'])
  164. ->from('articles')
  165. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  166. ->order(['title' => 'asc'])
  167. ->execute();
  168. $this->assertCount(3, $result);
  169. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  170. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  171. $result = $query->join('authors', [], true)->execute();
  172. $this->assertCount(12, $result, 'Cross join results in 12 records');
  173. $result = $query->join([
  174. ['table' => 'authors', 'type' => 'INNER', 'conditions' => 'author_id = authors.id']
  175. ], [], true)->execute();
  176. $this->assertCount(3, $result);
  177. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  178. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  179. }
  180. /**
  181. * Tests it is possible to add joins to a select query using array or expression as conditions
  182. *
  183. * @return void
  184. */
  185. public function testSelectWithJoinsConditions() {
  186. $query = new Query($this->connection);
  187. $result = $query
  188. ->select(['title', 'name'])
  189. ->from('articles')
  190. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => ['author_id = a.id']])
  191. ->order(['title' => 'asc'])
  192. ->execute();
  193. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  194. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  195. $query = new Query($this->connection);
  196. $conditions = $query->newExpr()->add('author_id = a.id');
  197. $result = $query
  198. ->select(['title', 'name'])
  199. ->from('articles')
  200. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $conditions])
  201. ->order(['title' => 'asc'])
  202. ->execute();
  203. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  204. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  205. $query = new Query($this->connection);
  206. $time = new \DateTime('2007-03-18 10:50:00');
  207. $types = ['created' => 'datetime'];
  208. $result = $query
  209. ->select(['title', 'comment' => 'c.comment'])
  210. ->from('articles')
  211. ->join(['table' => 'comments', 'alias' => 'c', 'conditions' => ['created <=' => $time]], $types)
  212. ->execute();
  213. $this->assertEquals(['title' => 'First Article', 'comment' => 'First Comment for First Article'], $result->fetch('assoc'));
  214. }
  215. /**
  216. * Tests that joins can be aliased using array keys
  217. *
  218. * @return void
  219. */
  220. public function testSelectAliasedJoins() {
  221. $query = new Query($this->connection);
  222. $result = $query
  223. ->select(['title', 'name'])
  224. ->from('articles')
  225. ->join(['a' => 'authors'])
  226. ->order(['name' => 'desc', 'articles.id' => 'asc'])
  227. ->execute();
  228. $this->assertEquals(array('title' => 'First Article', 'name' => 'nate'), $result->fetch('assoc'));
  229. $this->assertEquals(array('title' => 'Second Article', 'name' => 'nate'), $result->fetch('assoc'));
  230. $query = new Query($this->connection);
  231. $conditions = $query->newExpr()->add('author_id = a.id');
  232. $result = $query
  233. ->select(['title', 'name'])
  234. ->from('articles')
  235. ->join(['a' => ['table' => 'authors', 'conditions' => $conditions]])
  236. ->order(['title' => 'asc'])
  237. ->execute();
  238. $this->assertEquals(array('title' => 'First Article', 'name' => 'mariano'), $result->fetch('assoc'));
  239. $this->assertEquals(array('title' => 'Second Article', 'name' => 'larry'), $result->fetch('assoc'));
  240. $query = new Query($this->connection);
  241. $time = new \DateTime('2007-03-18 10:45:23');
  242. $types = ['created' => 'datetime'];
  243. $result = $query
  244. ->select(['title', 'name' => 'c.comment'])
  245. ->from('articles')
  246. ->join(['c' => ['table' => 'comments', 'conditions' => ['created' => $time]]], $types)
  247. ->execute();
  248. $this->assertEquals(array('title' => 'First Article', 'name' => 'First Comment for First Article'), $result->fetch('assoc'));
  249. }
  250. /**
  251. * Tests it is possible to filter a query by using simple AND joined conditions
  252. *
  253. * @return void
  254. */
  255. public function testSelectSimpleWhere() {
  256. $query = new Query($this->connection);
  257. $result = $query
  258. ->select(['title'])
  259. ->from('articles')
  260. ->where(['id' => 1, 'title' => 'First Article'])
  261. ->execute();
  262. $this->assertCount(1, $result);
  263. $query = new Query($this->connection);
  264. $result = $query
  265. ->select(['title'])
  266. ->from('articles')
  267. ->where(['id' => 100], ['id' => 'integer'])
  268. ->execute();
  269. $this->assertCount(0, $result);
  270. }
  271. /**
  272. * Tests using where conditions with operators and scalar values works
  273. *
  274. * @return void
  275. */
  276. public function testSelectWhereOperators() {
  277. $query = new Query($this->connection);
  278. $result = $query
  279. ->select(['title'])
  280. ->from('articles')
  281. ->where(['id >' => 1])
  282. ->execute();
  283. $this->assertCount(2, $result);
  284. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  285. $query = new Query($this->connection);
  286. $result = $query
  287. ->select(['title'])
  288. ->from('articles')
  289. ->where(['id <' => 2])
  290. ->execute();
  291. $this->assertCount(1, $result);
  292. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  293. $query = new Query($this->connection);
  294. $result = $query
  295. ->select(['title'])
  296. ->from('articles')
  297. ->where(['id <=' => 2])
  298. ->execute();
  299. $this->assertCount(2, $result);
  300. $query = new Query($this->connection);
  301. $result = $query
  302. ->select(['title'])
  303. ->from('articles')
  304. ->where(['id >=' => 1])
  305. ->execute();
  306. $this->assertCount(3, $result);
  307. $query = new Query($this->connection);
  308. $result = $query
  309. ->select(['title'])
  310. ->from('articles')
  311. ->where(['id <=' => 1])
  312. ->execute();
  313. $this->assertCount(1, $result);
  314. $query = new Query($this->connection);
  315. $result = $query
  316. ->select(['title'])
  317. ->from('articles')
  318. ->where(['id !=' => 2])
  319. ->execute();
  320. $this->assertCount(2, $result);
  321. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  322. $query = new Query($this->connection);
  323. $result = $query
  324. ->select(['title'])
  325. ->from('articles')
  326. ->where(['title LIKE' => 'First Article'])
  327. ->execute();
  328. $this->assertCount(1, $result);
  329. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  330. $query = new Query($this->connection);
  331. $result = $query
  332. ->select(['title'])
  333. ->from('articles')
  334. ->where(['title like' => '%Article%'])
  335. ->execute();
  336. $this->assertCount(3, $result);
  337. $query = new Query($this->connection);
  338. $result = $query
  339. ->select(['title'])
  340. ->from('articles')
  341. ->where(['title not like' => '%Article%'])
  342. ->execute();
  343. $this->assertCount(0, $result);
  344. }
  345. /**
  346. * Tests selecting with conditions and specifying types for those
  347. *
  348. * @return void
  349. **/
  350. public function testSelectWhereTypes() {
  351. $query = new Query($this->connection);
  352. $result = $query
  353. ->select(['id'])
  354. ->from('comments')
  355. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  356. ->execute();
  357. $this->assertCount(1, $result);
  358. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  359. $query = new Query($this->connection);
  360. $result = $query
  361. ->select(['id'])
  362. ->from('comments')
  363. ->where(['created >' => new \DateTime('2007-03-18 10:46:00')], ['created' => 'datetime'])
  364. ->execute();
  365. $this->assertCount(5, $result);
  366. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  367. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  368. $query = new Query($this->connection);
  369. $result = $query
  370. ->select(['id'])
  371. ->from('comments')
  372. ->where(
  373. [
  374. 'created >' => new \DateTime('2007-03-18 10:40:00'),
  375. 'created <' => new \DateTime('2007-03-18 10:46:00')
  376. ],
  377. ['created' => 'datetime']
  378. )
  379. ->execute();
  380. $this->assertCount(1, $result);
  381. $this->assertEquals(array('id' => 1), $result->fetch('assoc'));
  382. $query = new Query($this->connection);
  383. $result = $query
  384. ->select(['id'])
  385. ->from('comments')
  386. ->where(
  387. [
  388. 'id' => '3something-crazy',
  389. 'created <' => new \DateTime('2013-01-01 12:00')
  390. ],
  391. ['created' => 'datetime', 'id' => 'integer']
  392. )
  393. ->execute();
  394. $this->assertCount(1, $result);
  395. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  396. $query = new Query($this->connection);
  397. $result = $query
  398. ->select(['id'])
  399. ->from('comments')
  400. ->where(
  401. [
  402. 'id' => '1something-crazy',
  403. 'created <' => new \DateTime('2013-01-01 12:00')
  404. ],
  405. ['created' => 'datetime', 'id' => 'float']
  406. )
  407. ->execute();
  408. $this->assertCount(1, $result);
  409. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  410. }
  411. /**
  412. * Tests that passing an array type to any where condition will replace
  413. * the passed array accordingly as a proper IN condition
  414. *
  415. * @return void
  416. */
  417. public function testSelectWhereArrayType() {
  418. $query = new Query($this->connection);
  419. $result = $query
  420. ->select(['id'])
  421. ->from('comments')
  422. ->where(['id' => ['1', '3']], ['id' => 'integer[]'])
  423. ->execute();
  424. $this->assertCount(2, $result);
  425. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  426. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  427. }
  428. /**
  429. * Tests that Query::orWhere() can be used to concatenate conditions with OR
  430. *
  431. * @return void
  432. **/
  433. public function testSelectOrWhere() {
  434. $query = new Query($this->connection);
  435. $result = $query
  436. ->select(['id'])
  437. ->from('comments')
  438. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  439. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  440. ->execute();
  441. $this->assertCount(2, $result);
  442. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  443. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  444. }
  445. /**
  446. * Tests that Query::andWhere() can be used to concatenate conditions with AND
  447. *
  448. * @return void
  449. **/
  450. public function testSelectAndWhere() {
  451. $query = new Query($this->connection);
  452. $result = $query
  453. ->select(['id'])
  454. ->from('comments')
  455. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  456. ->andWhere(['id' => 1])
  457. ->execute();
  458. $this->assertCount(1, $result);
  459. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  460. $query = new Query($this->connection);
  461. $result = $query
  462. ->select(['id'])
  463. ->from('comments')
  464. ->where(['created' => new \DateTime('2007-03-18 10:50:55')], ['created' => 'datetime'])
  465. ->andWhere(['id' => 2])
  466. ->execute();
  467. $this->assertCount(0, $result);
  468. }
  469. /**
  470. * Tests that combining Query::andWhere() and Query::orWhere() produces
  471. * correct conditions nesting
  472. *
  473. * @return void
  474. **/
  475. public function testSelectExpressionNesting() {
  476. $query = new Query($this->connection);
  477. $result = $query
  478. ->select(['id'])
  479. ->from('comments')
  480. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  481. ->orWhere(['id' => 2])
  482. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  483. ->execute();
  484. $this->assertCount(2, $result);
  485. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  486. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  487. $query = new Query($this->connection);
  488. $result = $query
  489. ->select(['id'])
  490. ->from('comments')
  491. ->where(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  492. ->orWhere(['id' => 2])
  493. ->andWhere(['created >=' => new \DateTime('2007-03-18 10:40:00')], ['created' => 'datetime'])
  494. ->orWhere(['created' => new \DateTime('2007-03-18 10:49:23')], ['created' => 'datetime'])
  495. ->execute();
  496. $this->assertCount(3, $result);
  497. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  498. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  499. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  500. }
  501. /**
  502. * Tests that Query::orWhere() can be used without calling where() before
  503. *
  504. * @return void
  505. **/
  506. public function testSelectOrWhereNoPreviousCondition() {
  507. $query = new Query($this->connection);
  508. $result = $query
  509. ->select(['id'])
  510. ->from('comments')
  511. ->orWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  512. ->orWhere(['created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  513. ->execute();
  514. $this->assertCount(2, $result);
  515. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  516. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  517. }
  518. /**
  519. * Tests that Query::andWhere() can be used without calling where() before
  520. *
  521. * @return void
  522. **/
  523. public function testSelectAndWhereNoPreviousCondition() {
  524. $query = new Query($this->connection);
  525. $result = $query
  526. ->select(['id'])
  527. ->from('comments')
  528. ->andWhere(['created' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime'])
  529. ->andWhere(['id' => 1])
  530. ->execute();
  531. $this->assertCount(1, $result);
  532. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  533. }
  534. /**
  535. * Tests that it is possible to pass a closure to where() to build a set of
  536. * conditions and return the expression to be used
  537. *
  538. * @return void
  539. */
  540. public function testSelectWhereUsingClosure() {
  541. $query = new Query($this->connection);
  542. $result = $query
  543. ->select(['id'])
  544. ->from('comments')
  545. ->where(function($exp) {
  546. return $exp->eq('id', 1);
  547. })
  548. ->execute();
  549. $this->assertCount(1, $result);
  550. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  551. $query = new Query($this->connection);
  552. $result = $query
  553. ->select(['id'])
  554. ->from('comments')
  555. ->where(function($exp) {
  556. return $exp
  557. ->eq('id', 1)
  558. ->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  559. })
  560. ->execute();
  561. $this->assertCount(1, $result);
  562. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  563. $query = new Query($this->connection);
  564. $result = $query
  565. ->select(['id'])
  566. ->from('comments')
  567. ->where(function($exp) {
  568. return $exp
  569. ->eq('id', 1)
  570. ->eq('created', new \DateTime('2021-12-30 15:00'), 'datetime');
  571. })
  572. ->execute();
  573. $this->assertCount(0, $result);
  574. }
  575. /**
  576. * Tests that it is possible to pass a closure to andWhere() to build a set of
  577. * conditions and return the expression to be used
  578. *
  579. * @return void
  580. */
  581. public function testSelectAndWhereUsingClosure() {
  582. $query = new Query($this->connection);
  583. $result = $query
  584. ->select(['id'])
  585. ->from('comments')
  586. ->where(['id' => '1'])
  587. ->andWhere(function($exp) {
  588. return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  589. })
  590. ->execute();
  591. $this->assertCount(1, $result);
  592. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  593. $query = new Query($this->connection);
  594. $result = $query
  595. ->select(['id'])
  596. ->from('comments')
  597. ->where(['id' => '1'])
  598. ->andWhere(function($exp) {
  599. return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime');
  600. })
  601. ->execute();
  602. $this->assertCount(0, $result);
  603. }
  604. /**
  605. * Tests that it is possible to pass a closure to orWhere() to build a set of
  606. * conditions and return the expression to be used
  607. *
  608. * @return void
  609. */
  610. public function testSelectOrWhereUsingClosure() {
  611. $query = new Query($this->connection);
  612. $result = $query
  613. ->select(['id'])
  614. ->from('comments')
  615. ->where(['id' => '1'])
  616. ->orWhere(function($exp) {
  617. return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
  618. })
  619. ->execute();
  620. $this->assertCount(2, $result);
  621. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  622. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  623. $query = new Query($this->connection);
  624. $result = $query
  625. ->select(['id'])
  626. ->from('comments')
  627. ->where(['id' => '1'])
  628. ->orWhere(function($exp) {
  629. return $exp
  630. ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
  631. ->eq('id', 3);
  632. })
  633. ->execute();
  634. $this->assertCount(1, $result);
  635. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  636. }
  637. /**
  638. * Tests using where conditions with operator methods
  639. *
  640. * @return void
  641. */
  642. public function testSelectWhereOperatorMethods() {
  643. $query = new Query($this->connection);
  644. $result = $query
  645. ->select(['title'])
  646. ->from('articles')
  647. ->where(function($exp) {
  648. return $exp->gt('id', 1);
  649. })
  650. ->execute();
  651. $this->assertCount(2, $result);
  652. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  653. $query = new Query($this->connection);
  654. $result = $query->select(['title'])
  655. ->from('articles')
  656. ->where(function($exp) {
  657. return $exp->lt('id', 2);
  658. })
  659. ->execute();
  660. $this->assertCount(1, $result);
  661. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  662. $query = new Query($this->connection);
  663. $result = $query->select(['title'])
  664. ->from('articles')
  665. ->where(function($exp) {
  666. return $exp->lte('id', 2);
  667. })
  668. ->execute();
  669. $this->assertCount(2, $result);
  670. $query = new Query($this->connection);
  671. $result = $query
  672. ->select(['title'])
  673. ->from('articles')
  674. ->where(function($exp) {
  675. return $exp->gte('id', 1);
  676. })
  677. ->execute();
  678. $this->assertCount(3, $result);
  679. $query = new Query($this->connection);
  680. $result = $query
  681. ->select(['title'])
  682. ->from('articles')
  683. ->where(function($exp) {
  684. return $exp->lte('id', 1);
  685. })
  686. ->execute();
  687. $this->assertCount(1, $result);
  688. $query = new Query($this->connection);
  689. $result = $query
  690. ->select(['title'])
  691. ->from('articles')
  692. ->where(function($exp) {
  693. return $exp->notEq('id', 2);
  694. })
  695. ->execute();
  696. $this->assertCount(2, $result);
  697. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  698. $query = new Query($this->connection);
  699. $result = $query
  700. ->select(['title'])
  701. ->from('articles')
  702. ->where(function($exp) {
  703. return $exp->like('title', 'First Article');
  704. })
  705. ->execute();
  706. $this->assertCount(1, $result);
  707. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  708. $query = new Query($this->connection);
  709. $result = $query
  710. ->select(['title'])
  711. ->from('articles')
  712. ->where(function($exp) {
  713. return $exp->like('title', '%Article%');
  714. })
  715. ->execute();
  716. $this->assertCount(3, $result);
  717. $query = new Query($this->connection);
  718. $result = $query
  719. ->select(['title'])
  720. ->from('articles')
  721. ->where(function($exp) {
  722. return $exp->notLike('title', '%Article%');
  723. })
  724. ->execute();
  725. $this->assertCount(0, $result);
  726. $query = new Query($this->connection);
  727. $result = $query
  728. ->select(['id'])
  729. ->from('comments')
  730. ->where(function($exp) {
  731. return $exp->isNull('published');
  732. })
  733. ->execute();
  734. $this->assertCount(0, $result);
  735. $query = new Query($this->connection);
  736. $result = $query
  737. ->select(['id'])
  738. ->from('comments')
  739. ->where(function($exp) {
  740. return $exp->isNotNull('published');
  741. })
  742. ->execute();
  743. $this->assertCount(6, $result);
  744. $query = new Query($this->connection);
  745. $result = $query
  746. ->select(['id'])
  747. ->from('comments')
  748. ->where(function($exp) {
  749. return $exp->in('published', ['Y', 'N']);
  750. })
  751. ->execute();
  752. $this->assertCount(6, $result);
  753. $query = new Query($this->connection);
  754. $result = $query
  755. ->select(['id'])
  756. ->from('comments')
  757. ->where(function($exp) {
  758. return $exp->in(
  759. 'created',
  760. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  761. 'datetime'
  762. );
  763. })
  764. ->execute();
  765. $this->assertCount(2, $result);
  766. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  767. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  768. $query = new Query($this->connection);
  769. $result = $query
  770. ->select(['id'])
  771. ->from('comments')
  772. ->where(function($exp) {
  773. return $exp->notIn(
  774. 'created',
  775. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  776. 'datetime'
  777. );
  778. })
  779. ->execute();
  780. $this->assertCount(4, $result);
  781. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  782. }
  783. /**
  784. * Tests that calling "in" and "notIn" will cast the passed values to an array
  785. *
  786. * @return void
  787. */
  788. public function testInValueCast() {
  789. $query = new Query($this->connection);
  790. $result = $query
  791. ->select(['id'])
  792. ->from('comments')
  793. ->where(function($exp) {
  794. return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
  795. })
  796. ->execute();
  797. $this->assertCount(1, $result);
  798. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  799. $query = new Query($this->connection);
  800. $result = $query
  801. ->select(['id'])
  802. ->from('comments')
  803. ->where(function($exp) {
  804. return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
  805. })
  806. ->execute();
  807. $this->assertCount(5, $result);
  808. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  809. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  810. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  811. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  812. $query = new Query($this->connection);
  813. $result = $query
  814. ->select(['id'])
  815. ->from('comments')
  816. ->where(function($exp, $q) {
  817. return $exp->in(
  818. 'created',
  819. $q->newExpr()->add("'2007-03-18 10:45:23'"),
  820. 'datetime'
  821. );
  822. })
  823. ->execute();
  824. $this->assertCount(1, $result);
  825. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  826. $query = new Query($this->connection);
  827. $result = $query
  828. ->select(['id'])
  829. ->from('comments')
  830. ->where(function($exp, $q) {
  831. return $exp->notIn(
  832. 'created',
  833. $q->newExpr()->add("'2007-03-18 10:45:23'"),
  834. 'datetime'
  835. );
  836. })
  837. ->execute();
  838. $this->assertCount(5, $result);
  839. }
  840. /**
  841. * Tests that calling "in" and "notIn" will cast the passed values to an array
  842. *
  843. * @return void
  844. */
  845. public function testInValueCast2() {
  846. $query = new Query($this->connection);
  847. $result = $query
  848. ->select(['id'])
  849. ->from('comments')
  850. ->where(['created IN' => '2007-03-18 10:45:23'])
  851. ->execute();
  852. $this->assertCount(1, $result);
  853. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  854. $query = new Query($this->connection);
  855. $result = $query
  856. ->select(['id'])
  857. ->from('comments')
  858. ->where(['created NOT IN' => '2007-03-18 10:45:23'])
  859. ->execute();
  860. $this->assertCount(5, $result);
  861. }
  862. /**
  863. * Tests nesting query expressions both using arrays and closures
  864. *
  865. * @return void
  866. **/
  867. public function testSelectExpressionComposition() {
  868. $query = new Query($this->connection);
  869. $result = $query
  870. ->select(['id'])
  871. ->from('comments')
  872. ->where(function($exp) {
  873. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  874. return $exp->add($and);
  875. })
  876. ->execute();
  877. $this->assertCount(1, $result);
  878. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  879. $query = new Query($this->connection);
  880. $result = $query
  881. ->select(['id'])
  882. ->from('comments')
  883. ->where(function($exp) {
  884. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  885. return $exp->add($and);
  886. })
  887. ->execute();
  888. $this->assertCount(0, $result);
  889. $query = new Query($this->connection);
  890. $result = $query
  891. ->select(['id'])
  892. ->from('comments')
  893. ->where(function($exp) {
  894. $and = $exp->and_(function($and) {
  895. return $and->eq('id', 1)->gt('id', 0);
  896. });
  897. return $exp->add($and);
  898. })
  899. ->execute();
  900. $this->assertCount(1, $result);
  901. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  902. $query = new Query($this->connection);
  903. $result = $query
  904. ->select(['id'])
  905. ->from('comments')
  906. ->where(function($exp) {
  907. $or = $exp->or_(['id' => 1]);
  908. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  909. return $or->add($and);
  910. })
  911. ->execute();
  912. $this->assertCount(2, $result);
  913. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  914. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  915. $query = new Query($this->connection);
  916. $result = $query
  917. ->select(['id'])
  918. ->from('comments')
  919. ->where(function($exp) {
  920. $or = $exp->or_(function($or) {
  921. return $or->eq('id', 1)->eq('id', 2);
  922. });
  923. return $or;
  924. })
  925. ->execute();
  926. $this->assertCount(2, $result);
  927. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  928. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  929. }
  930. /**
  931. * Tests that conditions can be nested with an unary operator using the array notation
  932. * and the not() method
  933. *
  934. * @return void
  935. **/
  936. public function testSelectWhereNot() {
  937. $query = new Query($this->connection);
  938. $result = $query
  939. ->select(['id'])
  940. ->from('comments')
  941. ->where(function($exp) {
  942. return $exp->not(
  943. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  944. );
  945. })
  946. ->execute();
  947. $this->assertCount(5, $result);
  948. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  949. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  950. $query = new Query($this->connection);
  951. $result = $query
  952. ->select(['id'])
  953. ->from('comments')
  954. ->where(function($exp) {
  955. return $exp->not(
  956. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  957. );
  958. })
  959. ->execute();
  960. $this->assertCount(6, $result);
  961. $query = new Query($this->connection);
  962. $result = $query
  963. ->select(['id'])
  964. ->from('articles')
  965. ->where([
  966. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  967. ])
  968. ->execute();
  969. $this->assertCount(2, $result);
  970. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  971. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  972. }
  973. /**
  974. * Tests order() method both with simple fields and expressions
  975. *
  976. * @return void
  977. **/
  978. public function testSelectOrderBy() {
  979. $query = new Query($this->connection);
  980. $result = $query
  981. ->select(['id'])
  982. ->from('articles')
  983. ->order(['id' => 'desc'])
  984. ->execute();
  985. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  986. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  987. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  988. $result = $query->order(['id' => 'asc'])->execute();
  989. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  990. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  991. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  992. $result = $query->order(['title' => 'asc'])->execute();
  993. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  994. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  995. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  996. $result = $query->order(['title' => 'asc'], true)->execute();
  997. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  998. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  999. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1000. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1001. ->execute();
  1002. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1003. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1004. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1005. $expression = $query->newExpr()
  1006. ->add(['(id + :offset) % 2']);
  1007. $result = $query
  1008. ->order([$expression, 'id' => 'desc'], true)
  1009. ->bind(':offset', 1, null)
  1010. ->execute();
  1011. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1012. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1013. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1014. $result = $query
  1015. ->order($expression, true)
  1016. ->order(['id' => 'asc'])
  1017. ->bind(':offset', 1, null)
  1018. ->execute();
  1019. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1020. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1021. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1022. }
  1023. /**
  1024. * Tests that group by fields can be passed similar to select fields
  1025. * and that it sends the correct query to the database
  1026. *
  1027. * @return void
  1028. **/
  1029. public function testSelectGroup() {
  1030. $query = new Query($this->connection);
  1031. $result = $query
  1032. ->select(['total' => 'count(author_id)', 'author_id'])
  1033. ->from('articles')
  1034. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1035. ->group('author_id')
  1036. ->execute();
  1037. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1038. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1039. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1040. ->group(['name'], true)
  1041. ->order(['total' => 'asc'])
  1042. ->execute();
  1043. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1044. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1045. $result = $query->select(['articles.id'])
  1046. ->group(['articles.id'])
  1047. ->execute();
  1048. $this->assertCount(3, $result);
  1049. }
  1050. /**
  1051. * Tests that it is possible to select distinct rows
  1052. *
  1053. * @return void
  1054. */
  1055. public function testSelectDistinct() {
  1056. $query = new Query($this->connection);
  1057. $result = $query
  1058. ->select(['author_id'])
  1059. ->from(['a' => 'articles'])
  1060. ->execute();
  1061. $this->assertCount(3, $result);
  1062. $result = $query->distinct()->execute();
  1063. $this->assertCount(2, $result);
  1064. $result = $query->select(['id'])->distinct(false)->execute();
  1065. $this->assertCount(3, $result);
  1066. }
  1067. /**
  1068. * Tests that it is possible to select distinct rows, even filtering by one column
  1069. * this is testing that there is an specific implementation for DISTINCT ON
  1070. *
  1071. * @return void
  1072. */
  1073. public function testSelectDistinctON() {
  1074. $this->skipIf(
  1075. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  1076. 'Not implemented yet in SqlServer'
  1077. );
  1078. $query = new Query($this->connection);
  1079. $result = $query
  1080. ->select(['id', 'author_id'])
  1081. ->distinct(['author_id'])
  1082. ->from(['a' => 'articles'])
  1083. ->execute();
  1084. $this->assertCount(2, $result);
  1085. }
  1086. /**
  1087. * Test use of modifiers in the query
  1088. *
  1089. * Testing the generated SQL since the modifiers are usually different per driver
  1090. *
  1091. * @return void
  1092. */
  1093. public function testSelectModifiers() {
  1094. $query = new Query($this->connection);
  1095. $result = $query
  1096. ->select(['city', 'state', 'country'])
  1097. ->from(['addresses'])
  1098. ->modifier('DISTINCTROW');
  1099. $this->assertQuotedQuery(
  1100. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1101. $result->sql(),
  1102. true
  1103. );
  1104. $query = new Query($this->connection);
  1105. $result = $query
  1106. ->select(['city', 'state', 'country'])
  1107. ->from(['addresses'])
  1108. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1109. $this->assertQuotedQuery(
  1110. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1111. $result->sql(),
  1112. true
  1113. );
  1114. $query = new Query($this->connection);
  1115. $result = $query
  1116. ->select(['city', 'state', 'country'])
  1117. ->from(['addresses'])
  1118. ->modifier('DISTINCTROW')
  1119. ->modifier('SQL_NO_CACHE');
  1120. $this->assertQuotedQuery(
  1121. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1122. $result->sql(),
  1123. true
  1124. );
  1125. $query = new Query($this->connection);
  1126. $result = $query
  1127. ->select(['city', 'state', 'country'])
  1128. ->from(['addresses'])
  1129. ->modifier(['TOP 10']);
  1130. $this->assertQuotedQuery(
  1131. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1132. $result->sql(),
  1133. true
  1134. );
  1135. }
  1136. /**
  1137. * Tests that having() behaves pretty much the same as the where() method
  1138. *
  1139. * @return void
  1140. */
  1141. public function testSelectHaving() {
  1142. $query = new Query($this->connection);
  1143. $result = $query
  1144. ->select(['total' => 'count(author_id)', 'author_id'])
  1145. ->from('articles')
  1146. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1147. ->group('author_id')
  1148. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1149. ->execute();
  1150. $expected = [['total' => 1, 'author_id' => 3]];
  1151. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1152. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1153. ->execute();
  1154. $expected = [['total' => 2, 'author_id' => 1]];
  1155. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1156. $result = $query->having(function($e) {
  1157. return $e->add('count(author_id) = 1 + 1');
  1158. }, [], true)
  1159. ->execute();
  1160. $expected = [['total' => 2, 'author_id' => 1]];
  1161. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1162. }
  1163. /**
  1164. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1165. * in the having clause
  1166. *
  1167. * @return void
  1168. */
  1169. public function testSelectOrHaving() {
  1170. $query = new Query($this->connection);
  1171. $result = $query
  1172. ->select(['total' => 'count(author_id)', 'author_id'])
  1173. ->from('articles')
  1174. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1175. ->group('author_id')
  1176. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1177. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1178. ->execute();
  1179. $expected = [['total' => 1, 'author_id' => 3]];
  1180. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1181. $query = new Query($this->connection);
  1182. $result = $query
  1183. ->select(['total' => 'count(author_id)', 'author_id'])
  1184. ->from('articles')
  1185. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1186. ->group('author_id')
  1187. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1188. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1189. ->execute();
  1190. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1191. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1192. $query = new Query($this->connection);
  1193. $result = $query
  1194. ->select(['total' => 'count(author_id)', 'author_id'])
  1195. ->from('articles')
  1196. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1197. ->group('author_id')
  1198. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1199. ->orHaving(function($e) {
  1200. return $e->add('count(author_id) = 1 + 1');
  1201. })
  1202. ->execute();
  1203. $expected = [['total' => 2, 'author_id' => 1]];
  1204. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1205. }
  1206. /**
  1207. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1208. * in the having clause
  1209. *
  1210. * @return void
  1211. */
  1212. public function testSelectAndHaving() {
  1213. $query = new Query($this->connection);
  1214. $result = $query
  1215. ->select(['total' => 'count(author_id)', 'author_id'])
  1216. ->from('articles')
  1217. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1218. ->group('author_id')
  1219. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1220. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1221. ->execute();
  1222. $this->assertCount(0, $result);
  1223. $query = new Query($this->connection);
  1224. $result = $query
  1225. ->select(['total' => 'count(author_id)', 'author_id'])
  1226. ->from('articles')
  1227. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1228. ->group('author_id')
  1229. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1230. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1231. ->execute();
  1232. $expected = [['total' => 2, 'author_id' => 1]];
  1233. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1234. $query = new Query($this->connection);
  1235. $result = $query
  1236. ->select(['total' => 'count(author_id)', 'author_id'])
  1237. ->from('articles')
  1238. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1239. ->group('author_id')
  1240. ->andHaving(function($e) {
  1241. return $e->add('count(author_id) = 2 - 1');
  1242. })
  1243. ->execute();
  1244. $expected = [['total' => 1, 'author_id' => 3]];
  1245. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1246. }
  1247. /**
  1248. * Tests selecting rows using a limit clause
  1249. *
  1250. * @return void
  1251. */
  1252. public function testSelectLimit() {
  1253. $query = new Query($this->connection);
  1254. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1255. $this->assertCount(1, $result);
  1256. $query = new Query($this->connection);
  1257. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1258. $this->assertCount(2, $result);
  1259. }
  1260. /**
  1261. * Tests selecting rows combining a limit and offset clause
  1262. *
  1263. * @return void
  1264. */
  1265. public function testSelectOffset() {
  1266. $query = new Query($this->connection);
  1267. $result = $query->select('id')->from('comments')
  1268. ->limit(1)
  1269. ->offset(0)
  1270. ->order(['id' => 'ASC'])
  1271. ->execute();
  1272. $this->assertCount(1, $result);
  1273. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1274. $query = new Query($this->connection);
  1275. $result = $query->select('id')->from('comments')
  1276. ->limit(1)
  1277. ->offset(1)
  1278. ->execute();
  1279. $this->assertCount(1, $result);
  1280. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1281. $query = new Query($this->connection);
  1282. $result = $query->select('id')->from('comments')
  1283. ->limit(1)
  1284. ->offset(2)
  1285. ->execute();
  1286. $this->assertCount(1, $result);
  1287. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1288. $query = new Query($this->connection);
  1289. $result = $query->select('id')->from('articles')
  1290. ->order(['id' => 'DESC'])
  1291. ->limit(1)
  1292. ->offset(0)
  1293. ->execute();
  1294. $this->assertCount(1, $result);
  1295. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1296. $result = $query->limit(2)->offset(1)->execute();
  1297. $this->assertCount(2, $result);
  1298. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1299. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1300. }
  1301. /**
  1302. * Test selecting rows using the page() method.
  1303. *
  1304. * @return void
  1305. */
  1306. public function testSelectPage() {
  1307. $query = new Query($this->connection);
  1308. $result = $query->select('id')->from('comments')
  1309. ->limit(1)
  1310. ->page(1)
  1311. ->execute();
  1312. $this->assertCount(1, $result);
  1313. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1314. $query = new Query($this->connection);
  1315. $result = $query->select('id')->from('comments')
  1316. ->limit(1)
  1317. ->page(2)
  1318. ->execute();
  1319. $this->assertCount(1, $result);
  1320. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1321. $query = new Query($this->connection);
  1322. $query->select('id')->from('comments')->page(1);
  1323. $this->assertEquals(25, $query->clause('limit'));
  1324. $this->assertEquals(0, $query->clause('offset'));
  1325. $query->select('id')->from('comments')->page(2);
  1326. $this->assertEquals(25, $query->clause('limit'));
  1327. $this->assertEquals(25, $query->clause('offset'));
  1328. }
  1329. /**
  1330. * Tests that Query objects can be included inside the select clause
  1331. * and be used as a normal field, including binding any passed parameter
  1332. *
  1333. * @return void
  1334. */
  1335. public function testSubqueryInSelect() {
  1336. $query = new Query($this->connection);
  1337. $subquery = (new Query($this->connection))
  1338. ->select('name')
  1339. ->from(['b' => 'authors'])
  1340. ->where(['b.id = a.id']);
  1341. $result = $query
  1342. ->select(['id', 'name' => $subquery])
  1343. ->from(['a' => 'comments'])->execute();
  1344. $expected = [
  1345. ['id' => 1, 'name' => 'mariano'],
  1346. ['id' => 2, 'name' => 'nate'],
  1347. ['id' => 3, 'name' => 'larry'],
  1348. ['id' => 4, 'name' => 'garrett'],
  1349. ['id' => 5, 'name' => null],
  1350. ['id' => 6, 'name' => null],
  1351. ];
  1352. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1353. $query = new Query($this->connection);
  1354. $subquery = (new Query($this->connection))
  1355. ->select('name')
  1356. ->from(['b' => 'authors'])
  1357. ->where(['name' => 'mariano'], ['name' => 'string']);
  1358. $result = $query
  1359. ->select(['id', 'name' => $subquery])
  1360. ->from(['a' => 'articles'])->execute();
  1361. $expected = [
  1362. ['id' => 1, 'name' => 'mariano'],
  1363. ['id' => 2, 'name' => 'mariano'],
  1364. ['id' => 3, 'name' => 'mariano'],
  1365. ];
  1366. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1367. }
  1368. /**
  1369. * Tests that Query objects can be included inside the from clause
  1370. * and be used as a normal table, including binding any passed parameter
  1371. *
  1372. * @return void
  1373. */
  1374. public function testSuqueryInFrom() {
  1375. $query = new Query($this->connection);
  1376. $subquery = (new Query($this->connection))
  1377. ->select(['id', 'comment'])
  1378. ->from('comments')
  1379. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1380. $result = $query
  1381. ->select(['say' => 'comment'])
  1382. ->from(['b' => $subquery])
  1383. ->where(['id !=' => 3])
  1384. ->execute();
  1385. $expected = [
  1386. ['say' => 'Second Comment for First Article'],
  1387. ['say' => 'Fourth Comment for First Article'],
  1388. ['say' => 'First Comment for Second Article'],
  1389. ['say' => 'Second Comment for Second Article'],
  1390. ];
  1391. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1392. }
  1393. /**
  1394. * Tests that Query objects can be included inside the where clause
  1395. * and be used as a normal condition, including binding any passed parameter
  1396. *
  1397. * @return void
  1398. */
  1399. public function testSubqueryInWhere() {
  1400. $query = new Query($this->connection);
  1401. $subquery = (new Query($this->connection))
  1402. ->select(['id'])
  1403. ->from('authors')
  1404. ->where(['id' => 1]);
  1405. $result = $query
  1406. ->select(['name'])
  1407. ->from(['authors'])
  1408. ->where(['id !=' => $subquery])
  1409. ->execute();
  1410. $expected = [
  1411. ['name' => 'nate'],
  1412. ['name' => 'larry'],
  1413. ['name' => 'garrett'],
  1414. ];
  1415. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1416. $query = new Query($this->connection);
  1417. $subquery = (new Query($this->connection))
  1418. ->select(['id'])
  1419. ->from('comments')
  1420. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1421. $result = $query
  1422. ->select(['name'])
  1423. ->from(['authors'])
  1424. ->where(['id not in' => $subquery])
  1425. ->execute();
  1426. $expected = [
  1427. ['name' => 'mariano'],
  1428. ];
  1429. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1430. }
  1431. /**
  1432. * Tests that it is possible to use a subquery in a join clause
  1433. *
  1434. * @return void
  1435. */
  1436. public function testSubqueyInJoin() {
  1437. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1438. $query = new Query($this->connection);
  1439. $result = $query
  1440. ->select(['title', 'name'])
  1441. ->from('articles')
  1442. ->join(['b' => $subquery])
  1443. ->execute();
  1444. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1445. $subquery->where(['id' => 1]);
  1446. $result = $query->execute();
  1447. $this->assertCount(3, $result);
  1448. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1449. $result = $query->execute();
  1450. $this->assertCount(1, $result);
  1451. }
  1452. /**
  1453. * Tests that it is possible to one or multiple UNION statements in a query
  1454. *
  1455. * @return void
  1456. */
  1457. public function testUnion() {
  1458. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1459. $query = new Query($this->connection);
  1460. $result = $query->select(['id', 'comment'])
  1461. ->from(['c' => 'comments'])
  1462. ->union($union)
  1463. ->execute();
  1464. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1465. $rows = $result->fetchAll();
  1466. $union->select(['foo' => 'id', 'bar' => 'title']);
  1467. $union = (new Query($this->connection))
  1468. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1469. ->from(['b' => 'authors'])
  1470. ->where(['id ' => 1])
  1471. ->order(['id' => 'desc']);
  1472. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1473. $result = $query->execute();
  1474. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1475. $this->assertNotEquals($rows, $result->fetchAll());
  1476. $union = (new Query($this->connection))
  1477. ->select(['id', 'title'])
  1478. ->from(['c' => 'articles']);
  1479. $query->select(['id', 'comment'], true)->union($union, true);
  1480. $result = $query->execute();
  1481. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1482. $this->assertEquals($rows, $result->fetchAll());
  1483. }
  1484. /**
  1485. * Tests that UNION ALL can be built by setting the second param of union() to true
  1486. *
  1487. * @return void
  1488. */
  1489. public function testUnionAll() {
  1490. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1491. $query = new Query($this->connection);
  1492. $result = $query->select(['id', 'comment'])
  1493. ->from(['c' => 'comments'])
  1494. ->union($union)
  1495. ->execute();
  1496. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1497. $rows = $result->fetchAll();
  1498. $union->select(['foo' => 'id', 'bar' => 'title']);
  1499. $union = (new Query($this->connection))
  1500. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1501. ->from(['b' => 'authors'])
  1502. ->where(['id ' => 1])
  1503. ->order(['id' => 'desc']);
  1504. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1505. $result = $query->execute();
  1506. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1507. $this->assertNotEquals($rows, $result->fetchAll());
  1508. }
  1509. /**
  1510. * Tests stacking decorators for results and resetting the list of decorators
  1511. *
  1512. * @return void
  1513. */
  1514. public function testDecorateResults() {
  1515. $query = new Query($this->connection);
  1516. $result = $query
  1517. ->select(['id', 'title'])
  1518. ->from('articles')
  1519. ->order(['id' => 'ASC'])
  1520. ->decorateResults(function($row) {
  1521. $row['modified_id'] = $row['id'] + 1;
  1522. return $row;
  1523. })
  1524. ->execute();
  1525. while ($row = $result->fetch('assoc')) {
  1526. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1527. }
  1528. $result = $query->decorateResults(function($row) {
  1529. $row['modified_id']--;
  1530. return $row;
  1531. })->execute();
  1532. while ($row = $result->fetch('assoc')) {
  1533. $this->assertEquals($row['id'], $row['modified_id']);
  1534. }
  1535. $result = $query
  1536. ->decorateResults(function($row) {
  1537. $row['foo'] = 'bar';
  1538. return $row;
  1539. }, true)
  1540. ->execute();
  1541. while ($row = $result->fetch('assoc')) {
  1542. $this->assertEquals('bar', $row['foo']);
  1543. $this->assertArrayNotHasKey('modified_id', $row);
  1544. }
  1545. $results = $query->decorateResults(null, true)->execute();
  1546. while ($row = $result->fetch('assoc')) {
  1547. $this->assertArrayNotHasKey('foo', $row);
  1548. $this->assertArrayNotHasKey('modified_id', $row);
  1549. }
  1550. }
  1551. /**
  1552. * Test a basic delete using from()
  1553. *
  1554. * @return void
  1555. */
  1556. public function testDeleteWithFrom() {
  1557. $query = new Query($this->connection);
  1558. $query->delete()
  1559. ->from('authors')
  1560. ->where('1 = 1');
  1561. $result = $query->sql();
  1562. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1563. $result = $query->execute();
  1564. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1565. $this->assertCount(self::AUTHOR_COUNT, $result);
  1566. }
  1567. /**
  1568. * Test a basic delete with no from() call.
  1569. *
  1570. * @return void
  1571. */
  1572. public function testDeleteNoFrom() {
  1573. $query = new Query($this->connection);
  1574. $query->delete('authors')
  1575. ->where('1 = 1');
  1576. $result = $query->sql();
  1577. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1578. $result = $query->execute();
  1579. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1580. $this->assertCount(self::AUTHOR_COUNT, $result);
  1581. }
  1582. /**
  1583. * Test setting select() & delete() modes.
  1584. *
  1585. * @return void
  1586. */
  1587. public function testSelectAndDeleteOnSameQuery() {
  1588. $query = new Query($this->connection);
  1589. $result = $query->select()
  1590. ->delete('authors')
  1591. ->where('1 = 1');
  1592. $result = $query->sql();
  1593. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1594. $this->assertContains(' WHERE 1 = 1', $result);
  1595. }
  1596. /**
  1597. * Test a simple update.
  1598. *
  1599. * @return void
  1600. */
  1601. public function testUpdateSimple() {
  1602. $query = new Query($this->connection);
  1603. $query->update('authors')
  1604. ->set('name', 'mark')
  1605. ->where(['id' => 1]);
  1606. $result = $query->sql();
  1607. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1608. $result = $query->execute();
  1609. $this->assertCount(1, $result);
  1610. }
  1611. /**
  1612. * Test update with multiple fields.
  1613. *
  1614. * @return void
  1615. */
  1616. public function testUpdateMultipleFields() {
  1617. $query = new Query($this->connection);
  1618. $query->update('articles')
  1619. ->set('title', 'mark', 'string')
  1620. ->set('body', 'some text', 'string')
  1621. ->where(['id' => 1]);
  1622. $result = $query->sql();
  1623. $this->assertQuotedQuery(
  1624. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1625. $result,
  1626. true
  1627. );
  1628. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1629. $result = $query->execute();
  1630. $this->assertCount(1, $result);
  1631. }
  1632. /**
  1633. * Test updating multiple fields with an array.
  1634. *
  1635. * @return void
  1636. */
  1637. public function testUpdateMultipleFieldsArray() {
  1638. $query = new Query($this->connection);
  1639. $query->update('articles')
  1640. ->set([
  1641. 'title' => 'mark',
  1642. 'body' => 'some text'
  1643. ], ['title' => 'string', 'body' => 'string'])
  1644. ->where(['id' => 1]);
  1645. $result = $query->sql();
  1646. $this->assertQuotedQuery(
  1647. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1648. $result,
  1649. true
  1650. );
  1651. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1652. $result = $query->execute();
  1653. $this->assertCount(1, $result);
  1654. }
  1655. /**
  1656. * Test updates with an expression.
  1657. *
  1658. * @return void
  1659. */
  1660. public function testUpdateWithExpression() {
  1661. $query = new Query($this->connection);
  1662. $expr = $query->newExpr();
  1663. $expr->add('title = author_id');
  1664. $query->update('articles')
  1665. ->set($expr)
  1666. ->where(['id' => 1]);
  1667. $result = $query->sql();
  1668. $this->assertQuotedQuery(
  1669. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  1670. $result,
  1671. true
  1672. );
  1673. $result = $query->execute();
  1674. $this->assertCount(1, $result);
  1675. }
  1676. /**
  1677. * Test update with array fields and types.
  1678. *
  1679. * @return void
  1680. */
  1681. public function testUpdateArrayFields() {
  1682. $query = new Query($this->connection);
  1683. $date = new \DateTime;
  1684. $query->update('comments')
  1685. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  1686. ->where(['id' => 1]);
  1687. $result = $query->sql();
  1688. $this->assertQuotedQuery(
  1689. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  1690. $result,
  1691. true
  1692. );
  1693. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1694. $result = $query->execute();
  1695. $this->assertCount(1, $result);
  1696. $query = new Query($this->connection);
  1697. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  1698. $result = $result->fetchAll('assoc')[0]['created'];
  1699. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  1700. }
  1701. /**
  1702. * You cannot call values() before insert() it causes all sorts of pain.
  1703. *
  1704. * @expectedException \Cake\Error\Exception
  1705. * @return void
  1706. */
  1707. public function testInsertValuesBeforeInsertFailure() {
  1708. $query = new Query($this->connection);
  1709. $query->select('*')->values([
  1710. 'id' => 1,
  1711. 'title' => 'mark',
  1712. 'body' => 'test insert'
  1713. ]);
  1714. }
  1715. /**
  1716. * Inserting nothing should not generate an error.
  1717. *
  1718. * @expectedException RuntimeException
  1719. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  1720. * @return void
  1721. */
  1722. public function testInsertNothing() {
  1723. $query = new Query($this->connection);
  1724. $query->insert([]);
  1725. }
  1726. /**
  1727. * Test inserting a single row.
  1728. *
  1729. * @return void
  1730. */
  1731. public function testInsertSimple() {
  1732. $query = new Query($this->connection);
  1733. $query->insert(['title', 'body'])
  1734. ->into('articles')
  1735. ->values([
  1736. 'title' => 'mark',
  1737. 'body' => 'test insert'
  1738. ]);
  1739. $result = $query->sql();
  1740. $this->assertQuotedQuery(
  1741. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1742. 'VALUES \(\?, \?\)',
  1743. $result,
  1744. true
  1745. );
  1746. $result = $query->execute();
  1747. $this->assertCount(1, $result, '1 row should be inserted');
  1748. $expected = [
  1749. [
  1750. 'id' => 4,
  1751. 'author_id' => null,
  1752. 'title' => 'mark',
  1753. 'body' => 'test insert',
  1754. 'published' => 'N',
  1755. ]
  1756. ];
  1757. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  1758. }
  1759. /**
  1760. * Test an insert when not all the listed fields are provided.
  1761. * Columns should be matched up where possible.
  1762. *
  1763. * @return void
  1764. */
  1765. public function testInsertSparseRow() {
  1766. $query = new Query($this->connection);
  1767. $query->insert(['title', 'body'])
  1768. ->into('articles')
  1769. ->values([
  1770. 'title' => 'mark',
  1771. ]);
  1772. $result = $query->sql();
  1773. $this->assertQuotedQuery(
  1774. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1775. 'VALUES \(\?, \?\)',
  1776. $result,
  1777. true
  1778. );
  1779. $result = $query->execute();
  1780. $this->assertCount(1, $result, '1 row should be inserted');
  1781. $expected = [
  1782. [
  1783. 'id' => 4,
  1784. 'author_id' => null,
  1785. 'title' => 'mark',
  1786. 'body' => null,
  1787. 'published' => 'N',
  1788. ]
  1789. ];
  1790. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  1791. }
  1792. /**
  1793. * Test inserting multiple rows with sparse data.
  1794. *
  1795. * @return void
  1796. */
  1797. public function testInsertMultipleRowsSparse() {
  1798. $query = new Query($this->connection);
  1799. $query->insert(['title', 'body'])
  1800. ->into('articles')
  1801. ->values([
  1802. 'body' => 'test insert'
  1803. ])
  1804. ->values([
  1805. 'title' => 'jose',
  1806. ]);
  1807. $result = $query->execute();
  1808. $this->assertCount(2, $result, '2 rows should be inserted');
  1809. $expected = [
  1810. [
  1811. 'id' => 4,
  1812. 'author_id' => null,
  1813. 'title' => null,
  1814. 'body' => 'test insert',
  1815. 'published' => 'N',
  1816. ],
  1817. [
  1818. 'id' => 5,
  1819. 'author_id' => null,
  1820. 'title' => 'jose',
  1821. 'body' => null,
  1822. 'published' => 'N',
  1823. ],
  1824. ];
  1825. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  1826. }
  1827. /**
  1828. * Test that INSERT INTO ... SELECT works.
  1829. *
  1830. * @return void
  1831. */
  1832. public function testInsertFromSelect() {
  1833. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  1834. ->from('authors')
  1835. ->where(['id' => 1]);
  1836. $query = new Query($this->connection);
  1837. $query->insert(
  1838. ['title', 'body', 'author_id'],
  1839. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  1840. )
  1841. ->into('articles')
  1842. ->values($select);
  1843. $result = $query->sql();
  1844. $this->assertQuotedQuery(
  1845. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) SELECT',
  1846. $result,
  1847. true
  1848. );
  1849. $this->assertQuotedQuery(
  1850. 'SELECT <name>, \'some text\', 99 FROM <authors>', $result, true);
  1851. $result = $query->execute();
  1852. $this->assertCount(1, $result);
  1853. $result = (new Query($this->connection))->select('*')
  1854. ->from('articles')
  1855. ->where(['author_id' => 99])
  1856. ->execute();
  1857. $this->assertCount(1, $result);
  1858. $expected = [
  1859. 'id' => 4,
  1860. 'title' => 'mariano',
  1861. 'body' => 'some text',
  1862. 'author_id' => 99,
  1863. 'published' => 'N',
  1864. ];
  1865. $this->assertEquals($expected, $result->fetch('assoc'));
  1866. }
  1867. /**
  1868. * Test that an exception is raised when mixing query + array types.
  1869. *
  1870. * @expectedException \Cake\Error\Exception
  1871. */
  1872. public function testInsertFailureMixingTypesArrayFirst() {
  1873. $query = new Query($this->connection);
  1874. $query->insert(['name'])
  1875. ->into('articles')
  1876. ->values(['name' => 'mark'])
  1877. ->values(new Query($this->connection));
  1878. }
  1879. /**
  1880. * Test that an exception is raised when mixing query + array types.
  1881. *
  1882. * @expectedException \Cake\Error\Exception
  1883. */
  1884. public function testInsertFailureMixingTypesQueryFirst() {
  1885. $query = new Query($this->connection);
  1886. $query->insert(['name'])
  1887. ->into('articles')
  1888. ->values(new Query($this->connection))
  1889. ->values(['name' => 'mark']);
  1890. }
  1891. /**
  1892. * Tests that functions are correctly transformed and their parameters are bound
  1893. *
  1894. * @group FunctionExpression
  1895. * @return void
  1896. */
  1897. public function testSQLFunctions() {
  1898. $query = new Query($this->connection);
  1899. $result = $query->select(
  1900. function($q) {
  1901. return ['total' => $q->func()->count('*')];
  1902. }
  1903. )
  1904. ->from('articles')
  1905. ->execute();
  1906. $expected = [['total' => 3]];
  1907. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1908. $query = new Query($this->connection);
  1909. $result = $query->select([
  1910. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  1911. ])
  1912. ->from('articles')
  1913. ->order(['c' => 'ASC'])
  1914. ->execute();
  1915. $expected = [
  1916. ['c' => 'First Article is appended'],
  1917. ['c' => 'Second Article is appended'],
  1918. ['c' => 'Third Article is appended']
  1919. ];
  1920. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1921. $query = new Query($this->connection);
  1922. $result = $query
  1923. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  1924. ->execute()
  1925. ->fetchAll('assoc');
  1926. $this->assertEquals(3, abs($result[0]['d']));
  1927. $query = new Query($this->connection);
  1928. $result = $query
  1929. ->select(['d' => $query->func()->now('date')])
  1930. ->execute();
  1931. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  1932. $query = new Query($this->connection);
  1933. $result = $query
  1934. ->select(['d' => $query->func()->now('time')])
  1935. ->execute();
  1936. $this->assertWithinMargin(
  1937. date('U'),
  1938. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1939. 1
  1940. );
  1941. $query = new Query($this->connection);
  1942. $result = $query
  1943. ->select(['d' => $query->func()->now()])
  1944. ->execute();
  1945. $this->assertWithinMargin(
  1946. date('U'),
  1947. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1948. 1
  1949. );
  1950. }
  1951. /**
  1952. * Tests that default types are passed to functions accepting a $types param
  1953. *
  1954. * @return void
  1955. */
  1956. public function testDefaultTypes() {
  1957. $query = new Query($this->connection);
  1958. $this->assertEquals([], $query->defaultTypes());
  1959. $types = ['id' => 'integer', 'created' => 'datetime'];
  1960. $this->assertSame($query, $query->defaultTypes($types));
  1961. $this->assertSame($types, $query->defaultTypes());
  1962. $results = $query->select(['id', 'comment'])
  1963. ->from('comments')
  1964. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  1965. ->execute();
  1966. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  1967. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1968. // Now test default can be overridden
  1969. $types = ['created' => 'date'];
  1970. $results = $query
  1971. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  1972. ->execute();
  1973. $this->assertCount(6, $results, 'All 6 rows should match.');
  1974. }
  1975. /**
  1976. * Tests parameter binding
  1977. *
  1978. * @return void
  1979. */
  1980. public function testBind() {
  1981. $query = new Query($this->connection);
  1982. $results = $query->select(['id', 'comment'])
  1983. ->from('comments')
  1984. ->where(['created BETWEEN :foo AND :bar'])
  1985. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  1986. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  1987. ->execute();
  1988. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  1989. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1990. $query = new Query($this->connection);
  1991. $results = $query->select(['id', 'comment'])
  1992. ->from('comments')
  1993. ->where(['created BETWEEN :foo AND :bar'])
  1994. ->bind(':foo', '2007-03-18 10:50:00')
  1995. ->bind(':bar', '2007-03-18 10:52:00')
  1996. ->execute();
  1997. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1998. }
  1999. /**
  2000. * Test that epilog() will actually append a string to a select query
  2001. *
  2002. * @return void
  2003. */
  2004. public function testAppendSelect() {
  2005. $query = new Query($this->connection);
  2006. $sql = $query
  2007. ->select(['id', 'title'])
  2008. ->from('articles')
  2009. ->where(['id' => 1])
  2010. ->epilog('FOR UPDATE')
  2011. ->sql();
  2012. $this->assertContains('SELECT', $sql);
  2013. $this->assertContains('FROM', $sql);
  2014. $this->assertContains('WHERE', $sql);
  2015. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2016. }
  2017. /**
  2018. * Test that epilog() will actually append a string to an insert query
  2019. *
  2020. * @return void
  2021. */
  2022. public function testAppendInsert() {
  2023. $query = new Query($this->connection);
  2024. $sql = $query
  2025. ->insert(['id', 'title'])
  2026. ->into('articles')
  2027. ->values([1, 'a title'])
  2028. ->epilog('RETURNING id')
  2029. ->sql();
  2030. $this->assertContains('INSERT', $sql);
  2031. $this->assertContains('INTO', $sql);
  2032. $this->assertContains('VALUES', $sql);
  2033. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2034. }
  2035. /**
  2036. * Test that epilog() will actually append a string to an update query
  2037. *
  2038. * @return void
  2039. */
  2040. public function testAppendUpdate() {
  2041. $query = new Query($this->connection);
  2042. $sql = $query
  2043. ->update('articles')
  2044. ->set(['title' => 'foo'])
  2045. ->where(['id' => 1])
  2046. ->epilog('RETURNING id')
  2047. ->sql();
  2048. $this->assertContains('UPDATE', $sql);
  2049. $this->assertContains('SET', $sql);
  2050. $this->assertContains('WHERE', $sql);
  2051. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2052. }
  2053. /**
  2054. * Test that epilog() will actually append a string to a delete query
  2055. *
  2056. * @return void
  2057. */
  2058. public function testAppendDelete() {
  2059. $query = new Query($this->connection);
  2060. $sql = $query
  2061. ->delete('articles')
  2062. ->where(['id' => 1])
  2063. ->epilog('RETURNING id')
  2064. ->sql();
  2065. $this->assertContains('DELETE FROM', $sql);
  2066. $this->assertContains('WHERE', $sql);
  2067. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2068. }
  2069. /**
  2070. * Tests automatic identifier quoting in the select clause
  2071. *
  2072. * @return void
  2073. */
  2074. public function testQuotingSelectFieldsAndAlias() {
  2075. $this->connection->driver()->autoQuoting(true);
  2076. $query = new Query($this->connection);
  2077. $sql = $query->select(['something'])->sql();
  2078. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2079. $query = new Query($this->connection);
  2080. $sql = $query->select(['foo' => 'something'])->sql();
  2081. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2082. $query = new Query($this->connection);
  2083. $sql = $query->select(['foo' => 1])->sql();
  2084. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2085. $query = new Query($this->connection);
  2086. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2087. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2088. $query = new Query($this->connection);
  2089. $sql = $query->select(['foo' => $query->newExpr()->add('1 + 1')])->sql();
  2090. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2091. $query = new Query($this->connection);
  2092. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2093. $this->assertQuotedQuery('<bar>', $sql);
  2094. }
  2095. /**
  2096. * Tests automatic identifier quoting in the from clause
  2097. *
  2098. * @return void
  2099. */
  2100. public function testQuotingFromAndAlias() {
  2101. $this->connection->driver()->autoQuoting(true);
  2102. $query = new Query($this->connection);
  2103. $sql = $query->select('*')->from(['something'])->sql();
  2104. $this->assertQuotedQuery('FROM <something>', $sql);
  2105. $query = new Query($this->connection);
  2106. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2107. $this->assertQuotedQuery('FROM <something> AS <foo>$', $sql);
  2108. $query = new Query($this->connection);
  2109. $sql = $query->select('*')->from(['foo' => $query->newExpr()->add('bar')])->sql();
  2110. $this->assertQuotedQuery('FROM \(bar\) AS <foo>$', $sql);
  2111. }
  2112. /**
  2113. * Tests automatic identifier quoting for DISTINCT ON
  2114. *
  2115. * @return void
  2116. */
  2117. public function testQuotingDistinctOn() {
  2118. $this->connection->driver()->autoQuoting(true);
  2119. $query = new Query($this->connection);
  2120. $sql = $query->select('*')->distinct(['something'])->sql();
  2121. $this->assertQuotedQuery('<something>', $sql);
  2122. }
  2123. /**
  2124. * Tests automatic identifier quoting in the join clause
  2125. *
  2126. * @return void
  2127. */
  2128. public function testQuotingJoinsAndAlias() {
  2129. $this->connection->driver()->autoQuoting(true);
  2130. $query = new Query($this->connection);
  2131. $sql = $query->select('*')->join(['something'])->sql();
  2132. $this->assertQuotedQuery('JOIN <something>', $sql);
  2133. $query = new Query($this->connection);
  2134. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2135. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2136. $query = new Query($this->connection);
  2137. $sql = $query->select('*')->join(['foo' => $query->newExpr()->add('bar')])->sql();
  2138. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2139. }
  2140. /**
  2141. * Tests automatic identifier quoting in the group by clause
  2142. *
  2143. * @return void
  2144. */
  2145. public function testQuotingGroupBy() {
  2146. $this->connection->driver()->autoQuoting(true);
  2147. $query = new Query($this->connection);
  2148. $sql = $query->select('*')->group(['something'])->sql();
  2149. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2150. $query = new Query($this->connection);
  2151. $sql = $query->select('*')->group([$query->newExpr()->add('bar')])->sql();
  2152. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2153. $query = new Query($this->connection);
  2154. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2155. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2156. }
  2157. /**
  2158. * Tests automatic identifier quoting strings inside conditions expressions
  2159. *
  2160. * @return void
  2161. */
  2162. public function testQuotingExpressions() {
  2163. $this->connection->driver()->autoQuoting(true);
  2164. $query = new Query($this->connection);
  2165. $sql = $query->select('*')
  2166. ->where(['something' => 'value'])
  2167. ->sql();
  2168. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2169. $query = new Query($this->connection);
  2170. $sql = $query->select('*')
  2171. ->where([
  2172. 'something' => 'value',
  2173. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2174. ])
  2175. ->sql();
  2176. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2177. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2178. }
  2179. /**
  2180. * Tests that insert query parts get quoted automatically
  2181. *
  2182. * @return void
  2183. */
  2184. public function testQuotingInsert() {
  2185. $this->connection->driver()->autoQuoting(true);
  2186. $query = new Query($this->connection);
  2187. $sql = $query->insert(['bar', 'baz'])
  2188. ->into('foo')
  2189. ->where(['something' => 'value'])
  2190. ->sql();
  2191. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2192. $query = new Query($this->connection);
  2193. $sql = $query->insert([$query->newExpr()->add('bar')])
  2194. ->into('foo')
  2195. ->where(['something' => 'value'])
  2196. ->sql();
  2197. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2198. }
  2199. /**
  2200. * Tests converting a query to a string
  2201. *
  2202. * @return void
  2203. */
  2204. public function testToString() {
  2205. $query = new Query($this->connection);
  2206. $query
  2207. ->select(['title'])
  2208. ->from('articles');
  2209. $result = (string)$query;
  2210. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, true);
  2211. }
  2212. /**
  2213. * Tests __debugInfo
  2214. *
  2215. * @return void
  2216. */
  2217. public function testDebugInfo() {
  2218. $query = (new Query($this->connection))->select('*')
  2219. ->from('articles')
  2220. ->defaultTypes(['id' => 'integer'])
  2221. ->where(['id' => '1']);
  2222. $expected = [
  2223. 'sql' => $query->sql(),
  2224. 'params' => [
  2225. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2226. ],
  2227. 'defaultTypes' => ['id' => 'integer'],
  2228. 'decorators' => 0,
  2229. 'executed' => false
  2230. ];
  2231. $result = $query->__debugInfo();
  2232. $this->assertEquals($expected, $result);
  2233. $query->execute();
  2234. $expected = [
  2235. 'sql' => $query->sql(),
  2236. 'params' => [
  2237. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2238. ],
  2239. 'defaultTypes' => ['id' => 'integer'],
  2240. 'decorators' => 0,
  2241. 'executed' => true
  2242. ];
  2243. $result = $query->__debugInfo();
  2244. }
  2245. /**
  2246. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2247. *
  2248. * @return void
  2249. */
  2250. public function testIsNullWithExpressions() {
  2251. $query = new Query($this->connection);
  2252. $subquery = (new Query($this->connection))
  2253. ->select(['id'])
  2254. ->from('authors')
  2255. ->where(['id' => 1]);
  2256. $result = $query
  2257. ->select(['name'])
  2258. ->from(['authors'])
  2259. ->where(function($exp) use ($subquery) {
  2260. return $exp->isNotNull($subquery);
  2261. })
  2262. ->execute();
  2263. $this->assertNotEmpty($result->fetchAll('assoc'));
  2264. $result = (new Query($this->connection))
  2265. ->select(['name'])
  2266. ->from(['authors'])
  2267. ->where(function($exp) use ($subquery) {
  2268. return $exp->isNull($subquery);
  2269. })
  2270. ->execute();
  2271. $this->assertEmpty($result->fetchAll('assoc'));
  2272. }
  2273. /**
  2274. * Assertion for comparing a table's contents with what is in it.
  2275. *
  2276. * @param string $table
  2277. * @param int $count
  2278. * @param array $rows
  2279. * @param array $conditions
  2280. * @return void
  2281. */
  2282. public function assertTable($table, $count, $rows, $conditions = []) {
  2283. $result = (new Query($this->connection))->select('*')
  2284. ->from($table)
  2285. ->where($conditions)
  2286. ->execute();
  2287. $this->assertCount($count, $result, 'Row count is incorrect');
  2288. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2289. }
  2290. /**
  2291. * Assertion for comparing a regex pattern against a query having its indentifiers
  2292. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2293. * parameter is set to true, it will alter the pattern to both accept quoted and
  2294. * unquoted queries
  2295. *
  2296. * @param string $pattern
  2297. * @param string $query the result to compare against
  2298. * @param bool $optional
  2299. * @return void
  2300. */
  2301. public function assertQuotedQuery($pattern, $query, $optional = false) {
  2302. if ($optional) {
  2303. $optional = '?';
  2304. }
  2305. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2306. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2307. $this->assertRegExp('#' . $pattern . '#', $query);
  2308. }
  2309. }