QueryTest.php 66 KB

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