QueryTest.php 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601
  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('1 + 1');
  126. $comp = $query->newExpr(['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('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('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 generating tuples in the values side containing closure expressions
  577. *
  578. * @return void
  579. */
  580. public function testTupleWithClosureExpression() {
  581. $query = new Query($this->connection);
  582. $query->select(['id'])
  583. ->from('comments')
  584. ->where([
  585. 'OR' => [
  586. 'id' => 1,
  587. function($exp) {
  588. return $exp->eq('id', 2);
  589. }
  590. ]
  591. ]);
  592. $result = $query->sql();
  593. $this->assertQuotedQuery(
  594. 'SELECT <id> FROM <comments> WHERE \(<id> = :c0 OR <id> = :c1\)',
  595. $result,
  596. true
  597. );
  598. }
  599. /**
  600. * Tests that it is possible to pass a closure to andWhere() to build a set of
  601. * conditions and return the expression to be used
  602. *
  603. * @return void
  604. */
  605. public function testSelectAndWhereUsingClosure() {
  606. $query = new Query($this->connection);
  607. $result = $query
  608. ->select(['id'])
  609. ->from('comments')
  610. ->where(['id' => '1'])
  611. ->andWhere(function($exp) {
  612. return $exp->eq('created', new \DateTime('2007-03-18 10:45:23'), 'datetime');
  613. })
  614. ->execute();
  615. $this->assertCount(1, $result);
  616. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  617. $query = new Query($this->connection);
  618. $result = $query
  619. ->select(['id'])
  620. ->from('comments')
  621. ->where(['id' => '1'])
  622. ->andWhere(function($exp) {
  623. return $exp->eq('created', new \DateTime('2022-12-21 12:00'), 'datetime');
  624. })
  625. ->execute();
  626. $this->assertCount(0, $result);
  627. }
  628. /**
  629. * Tests that it is possible to pass a closure to orWhere() to build a set of
  630. * conditions and return the expression to be used
  631. *
  632. * @return void
  633. */
  634. public function testSelectOrWhereUsingClosure() {
  635. $query = new Query($this->connection);
  636. $result = $query
  637. ->select(['id'])
  638. ->from('comments')
  639. ->where(['id' => '1'])
  640. ->orWhere(function($exp) {
  641. return $exp->eq('created', new \DateTime('2007-03-18 10:47:23'), 'datetime');
  642. })
  643. ->execute();
  644. $this->assertCount(2, $result);
  645. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  646. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  647. $query = new Query($this->connection);
  648. $result = $query
  649. ->select(['id'])
  650. ->from('comments')
  651. ->where(['id' => '1'])
  652. ->orWhere(function($exp) {
  653. return $exp
  654. ->eq('created', new \DateTime('2012-12-22 12:00'), 'datetime')
  655. ->eq('id', 3);
  656. })
  657. ->execute();
  658. $this->assertCount(1, $result);
  659. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  660. }
  661. /**
  662. * Tests using where conditions with operator methods
  663. *
  664. * @return void
  665. */
  666. public function testSelectWhereOperatorMethods() {
  667. $query = new Query($this->connection);
  668. $result = $query
  669. ->select(['title'])
  670. ->from('articles')
  671. ->where(function($exp) {
  672. return $exp->gt('id', 1);
  673. })
  674. ->execute();
  675. $this->assertCount(2, $result);
  676. $this->assertEquals(array('title' => 'Second Article'), $result->fetch('assoc'));
  677. $query = new Query($this->connection);
  678. $result = $query->select(['title'])
  679. ->from('articles')
  680. ->where(function($exp) {
  681. return $exp->lt('id', 2);
  682. })
  683. ->execute();
  684. $this->assertCount(1, $result);
  685. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  686. $query = new Query($this->connection);
  687. $result = $query->select(['title'])
  688. ->from('articles')
  689. ->where(function($exp) {
  690. return $exp->lte('id', 2);
  691. })
  692. ->execute();
  693. $this->assertCount(2, $result);
  694. $query = new Query($this->connection);
  695. $result = $query
  696. ->select(['title'])
  697. ->from('articles')
  698. ->where(function($exp) {
  699. return $exp->gte('id', 1);
  700. })
  701. ->execute();
  702. $this->assertCount(3, $result);
  703. $query = new Query($this->connection);
  704. $result = $query
  705. ->select(['title'])
  706. ->from('articles')
  707. ->where(function($exp) {
  708. return $exp->lte('id', 1);
  709. })
  710. ->execute();
  711. $this->assertCount(1, $result);
  712. $query = new Query($this->connection);
  713. $result = $query
  714. ->select(['title'])
  715. ->from('articles')
  716. ->where(function($exp) {
  717. return $exp->notEq('id', 2);
  718. })
  719. ->execute();
  720. $this->assertCount(2, $result);
  721. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  722. $query = new Query($this->connection);
  723. $result = $query
  724. ->select(['title'])
  725. ->from('articles')
  726. ->where(function($exp) {
  727. return $exp->like('title', 'First Article');
  728. })
  729. ->execute();
  730. $this->assertCount(1, $result);
  731. $this->assertEquals(array('title' => 'First Article'), $result->fetch('assoc'));
  732. $query = new Query($this->connection);
  733. $result = $query
  734. ->select(['title'])
  735. ->from('articles')
  736. ->where(function($exp) {
  737. return $exp->like('title', '%Article%');
  738. })
  739. ->execute();
  740. $this->assertCount(3, $result);
  741. $query = new Query($this->connection);
  742. $result = $query
  743. ->select(['title'])
  744. ->from('articles')
  745. ->where(function($exp) {
  746. return $exp->notLike('title', '%Article%');
  747. })
  748. ->execute();
  749. $this->assertCount(0, $result);
  750. $query = new Query($this->connection);
  751. $result = $query
  752. ->select(['id'])
  753. ->from('comments')
  754. ->where(function($exp) {
  755. return $exp->isNull('published');
  756. })
  757. ->execute();
  758. $this->assertCount(0, $result);
  759. $query = new Query($this->connection);
  760. $result = $query
  761. ->select(['id'])
  762. ->from('comments')
  763. ->where(function($exp) {
  764. return $exp->isNotNull('published');
  765. })
  766. ->execute();
  767. $this->assertCount(6, $result);
  768. $query = new Query($this->connection);
  769. $result = $query
  770. ->select(['id'])
  771. ->from('comments')
  772. ->where(function($exp) {
  773. return $exp->in('published', ['Y', 'N']);
  774. })
  775. ->execute();
  776. $this->assertCount(6, $result);
  777. $query = new Query($this->connection);
  778. $result = $query
  779. ->select(['id'])
  780. ->from('comments')
  781. ->where(function($exp) {
  782. return $exp->in(
  783. 'created',
  784. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  785. 'datetime'
  786. );
  787. })
  788. ->execute();
  789. $this->assertCount(2, $result);
  790. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  791. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  792. $query = new Query($this->connection);
  793. $result = $query
  794. ->select(['id'])
  795. ->from('comments')
  796. ->where(function($exp) {
  797. return $exp->notIn(
  798. 'created',
  799. [new \DateTime('2007-03-18 10:45:23'), new \DateTime('2007-03-18 10:47:23')],
  800. 'datetime'
  801. );
  802. })
  803. ->execute();
  804. $this->assertCount(4, $result);
  805. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  806. }
  807. /**
  808. * Tests that calling "in" and "notIn" will cast the passed values to an array
  809. *
  810. * @return void
  811. */
  812. public function testInValueCast() {
  813. $query = new Query($this->connection);
  814. $result = $query
  815. ->select(['id'])
  816. ->from('comments')
  817. ->where(function($exp) {
  818. return $exp->in('created', '2007-03-18 10:45:23', 'datetime');
  819. })
  820. ->execute();
  821. $this->assertCount(1, $result);
  822. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  823. $query = new Query($this->connection);
  824. $result = $query
  825. ->select(['id'])
  826. ->from('comments')
  827. ->where(function($exp) {
  828. return $exp->notIn('created', '2007-03-18 10:45:23', 'datetime');
  829. })
  830. ->execute();
  831. $this->assertCount(5, $result);
  832. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  833. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  834. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  835. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  836. $query = new Query($this->connection);
  837. $result = $query
  838. ->select(['id'])
  839. ->from('comments')
  840. ->where(function($exp, $q) {
  841. return $exp->in(
  842. 'created',
  843. $q->newExpr("'2007-03-18 10:45:23'"),
  844. 'datetime'
  845. );
  846. })
  847. ->execute();
  848. $this->assertCount(1, $result);
  849. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  850. $query = new Query($this->connection);
  851. $result = $query
  852. ->select(['id'])
  853. ->from('comments')
  854. ->where(function($exp, $q) {
  855. return $exp->notIn(
  856. 'created',
  857. $q->newExpr("'2007-03-18 10:45:23'"),
  858. 'datetime'
  859. );
  860. })
  861. ->execute();
  862. $this->assertCount(5, $result);
  863. }
  864. /**
  865. * Tests that calling "in" and "notIn" will cast the passed values to an array
  866. *
  867. * @return void
  868. */
  869. public function testInValueCast2() {
  870. $query = new Query($this->connection);
  871. $result = $query
  872. ->select(['id'])
  873. ->from('comments')
  874. ->where(['created IN' => '2007-03-18 10:45:23'])
  875. ->execute();
  876. $this->assertCount(1, $result);
  877. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  878. $query = new Query($this->connection);
  879. $result = $query
  880. ->select(['id'])
  881. ->from('comments')
  882. ->where(['created NOT IN' => '2007-03-18 10:45:23'])
  883. ->execute();
  884. $this->assertCount(5, $result);
  885. }
  886. /**
  887. * Tests nesting query expressions both using arrays and closures
  888. *
  889. * @return void
  890. */
  891. public function testSelectExpressionComposition() {
  892. $query = new Query($this->connection);
  893. $result = $query
  894. ->select(['id'])
  895. ->from('comments')
  896. ->where(function($exp) {
  897. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  898. return $exp->add($and);
  899. })
  900. ->execute();
  901. $this->assertCount(1, $result);
  902. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  903. $query = new Query($this->connection);
  904. $result = $query
  905. ->select(['id'])
  906. ->from('comments')
  907. ->where(function($exp) {
  908. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  909. return $exp->add($and);
  910. })
  911. ->execute();
  912. $this->assertCount(0, $result);
  913. $query = new Query($this->connection);
  914. $result = $query
  915. ->select(['id'])
  916. ->from('comments')
  917. ->where(function($exp) {
  918. $and = $exp->and_(function($and) {
  919. return $and->eq('id', 1)->gt('id', 0);
  920. });
  921. return $exp->add($and);
  922. })
  923. ->execute();
  924. $this->assertCount(1, $result);
  925. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  926. $query = new Query($this->connection);
  927. $result = $query
  928. ->select(['id'])
  929. ->from('comments')
  930. ->where(function($exp) {
  931. $or = $exp->or_(['id' => 1]);
  932. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  933. return $or->add($and);
  934. })
  935. ->execute();
  936. $this->assertCount(2, $result);
  937. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  938. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  939. $query = new Query($this->connection);
  940. $result = $query
  941. ->select(['id'])
  942. ->from('comments')
  943. ->where(function($exp) {
  944. $or = $exp->or_(function($or) {
  945. return $or->eq('id', 1)->eq('id', 2);
  946. });
  947. return $or;
  948. })
  949. ->execute();
  950. $this->assertCount(2, $result);
  951. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  952. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  953. }
  954. /**
  955. * Tests that conditions can be nested with an unary operator using the array notation
  956. * and the not() method
  957. *
  958. * @return void
  959. */
  960. public function testSelectWhereNot() {
  961. $query = new Query($this->connection);
  962. $result = $query
  963. ->select(['id'])
  964. ->from('comments')
  965. ->where(function($exp) {
  966. return $exp->not(
  967. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  968. );
  969. })
  970. ->execute();
  971. $this->assertCount(5, $result);
  972. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  973. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  974. $query = new Query($this->connection);
  975. $result = $query
  976. ->select(['id'])
  977. ->from('comments')
  978. ->where(function($exp) {
  979. return $exp->not(
  980. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  981. );
  982. })
  983. ->execute();
  984. $this->assertCount(6, $result);
  985. $query = new Query($this->connection);
  986. $result = $query
  987. ->select(['id'])
  988. ->from('articles')
  989. ->where([
  990. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  991. ])
  992. ->execute();
  993. $this->assertCount(2, $result);
  994. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  995. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  996. }
  997. /**
  998. * Tests order() method both with simple fields and expressions
  999. *
  1000. * @return void
  1001. */
  1002. public function testSelectOrderBy() {
  1003. $query = new Query($this->connection);
  1004. $result = $query
  1005. ->select(['id'])
  1006. ->from('articles')
  1007. ->order(['id' => 'desc'])
  1008. ->execute();
  1009. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1010. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1011. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1012. $result = $query->order(['id' => 'asc'])->execute();
  1013. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1014. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1015. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1016. $result = $query->order(['title' => 'asc'])->execute();
  1017. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1018. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1019. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1020. $result = $query->order(['title' => 'asc'], true)->execute();
  1021. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1022. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1023. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1024. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1025. ->execute();
  1026. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1027. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1028. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1029. $expression = $query->newExpr(['(id + :offset) % 2']);
  1030. $result = $query
  1031. ->order([$expression, 'id' => 'desc'], true)
  1032. ->bind(':offset', 1, null)
  1033. ->execute();
  1034. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1035. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1036. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1037. $result = $query
  1038. ->order($expression, true)
  1039. ->order(['id' => 'asc'])
  1040. ->bind(':offset', 1, null)
  1041. ->execute();
  1042. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1043. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1044. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1045. }
  1046. /**
  1047. * Tests that group by fields can be passed similar to select fields
  1048. * and that it sends the correct query to the database
  1049. *
  1050. * @return void
  1051. */
  1052. public function testSelectGroup() {
  1053. $query = new Query($this->connection);
  1054. $result = $query
  1055. ->select(['total' => 'count(author_id)', 'author_id'])
  1056. ->from('articles')
  1057. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1058. ->group('author_id')
  1059. ->execute();
  1060. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1061. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1062. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1063. ->group(['name'], true)
  1064. ->order(['total' => 'asc'])
  1065. ->execute();
  1066. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1067. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1068. $result = $query->select(['articles.id'])
  1069. ->group(['articles.id'])
  1070. ->execute();
  1071. $this->assertCount(3, $result);
  1072. }
  1073. /**
  1074. * Tests that it is possible to select distinct rows
  1075. *
  1076. * @return void
  1077. */
  1078. public function testSelectDistinct() {
  1079. $query = new Query($this->connection);
  1080. $result = $query
  1081. ->select(['author_id'])
  1082. ->from(['a' => 'articles'])
  1083. ->execute();
  1084. $this->assertCount(3, $result);
  1085. $result = $query->distinct()->execute();
  1086. $this->assertCount(2, $result);
  1087. $result = $query->select(['id'])->distinct(false)->execute();
  1088. $this->assertCount(3, $result);
  1089. }
  1090. /**
  1091. * Tests that it is possible to select distinct rows, even filtering by one column
  1092. * this is testing that there is an specific implementation for DISTINCT ON
  1093. *
  1094. * @return void
  1095. */
  1096. public function testSelectDistinctON() {
  1097. $this->skipIf(
  1098. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  1099. 'Not implemented yet in SqlServer'
  1100. );
  1101. $query = new Query($this->connection);
  1102. $result = $query
  1103. ->select(['id', 'author_id'])
  1104. ->distinct(['author_id'])
  1105. ->from(['a' => 'articles'])
  1106. ->execute();
  1107. $this->assertCount(2, $result);
  1108. }
  1109. /**
  1110. * Test use of modifiers in the query
  1111. *
  1112. * Testing the generated SQL since the modifiers are usually different per driver
  1113. *
  1114. * @return void
  1115. */
  1116. public function testSelectModifiers() {
  1117. $query = new Query($this->connection);
  1118. $result = $query
  1119. ->select(['city', 'state', 'country'])
  1120. ->from(['addresses'])
  1121. ->modifier('DISTINCTROW');
  1122. $this->assertQuotedQuery(
  1123. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1124. $result->sql(),
  1125. true
  1126. );
  1127. $query = new Query($this->connection);
  1128. $result = $query
  1129. ->select(['city', 'state', 'country'])
  1130. ->from(['addresses'])
  1131. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1132. $this->assertQuotedQuery(
  1133. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1134. $result->sql(),
  1135. true
  1136. );
  1137. $query = new Query($this->connection);
  1138. $result = $query
  1139. ->select(['city', 'state', 'country'])
  1140. ->from(['addresses'])
  1141. ->modifier('DISTINCTROW')
  1142. ->modifier('SQL_NO_CACHE');
  1143. $this->assertQuotedQuery(
  1144. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1145. $result->sql(),
  1146. true
  1147. );
  1148. $query = new Query($this->connection);
  1149. $result = $query
  1150. ->select(['city', 'state', 'country'])
  1151. ->from(['addresses'])
  1152. ->modifier(['TOP 10']);
  1153. $this->assertQuotedQuery(
  1154. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1155. $result->sql(),
  1156. true
  1157. );
  1158. }
  1159. /**
  1160. * Tests that having() behaves pretty much the same as the where() method
  1161. *
  1162. * @return void
  1163. */
  1164. public function testSelectHaving() {
  1165. $query = new Query($this->connection);
  1166. $result = $query
  1167. ->select(['total' => 'count(author_id)', 'author_id'])
  1168. ->from('articles')
  1169. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1170. ->group('author_id')
  1171. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1172. ->execute();
  1173. $expected = [['total' => 1, 'author_id' => 3]];
  1174. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1175. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1176. ->execute();
  1177. $expected = [['total' => 2, 'author_id' => 1]];
  1178. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1179. $result = $query->having(function($e) {
  1180. return $e->add('count(author_id) = 1 + 1');
  1181. }, [], true)
  1182. ->execute();
  1183. $expected = [['total' => 2, 'author_id' => 1]];
  1184. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1185. }
  1186. /**
  1187. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1188. * in the having clause
  1189. *
  1190. * @return void
  1191. */
  1192. public function testSelectOrHaving() {
  1193. $query = new Query($this->connection);
  1194. $result = $query
  1195. ->select(['total' => 'count(author_id)', 'author_id'])
  1196. ->from('articles')
  1197. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1198. ->group('author_id')
  1199. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1200. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1201. ->execute();
  1202. $expected = [['total' => 1, 'author_id' => 3]];
  1203. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1204. $query = new Query($this->connection);
  1205. $result = $query
  1206. ->select(['total' => 'count(author_id)', 'author_id'])
  1207. ->from('articles')
  1208. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1209. ->group('author_id')
  1210. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1211. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1212. ->execute();
  1213. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1214. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1215. $query = new Query($this->connection);
  1216. $result = $query
  1217. ->select(['total' => 'count(author_id)', 'author_id'])
  1218. ->from('articles')
  1219. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1220. ->group('author_id')
  1221. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1222. ->orHaving(function($e) {
  1223. return $e->add('count(author_id) = 1 + 1');
  1224. })
  1225. ->execute();
  1226. $expected = [['total' => 2, 'author_id' => 1]];
  1227. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1228. }
  1229. /**
  1230. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1231. * in the having clause
  1232. *
  1233. * @return void
  1234. */
  1235. public function testSelectAndHaving() {
  1236. $query = new Query($this->connection);
  1237. $result = $query
  1238. ->select(['total' => 'count(author_id)', 'author_id'])
  1239. ->from('articles')
  1240. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1241. ->group('author_id')
  1242. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1243. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1244. ->execute();
  1245. $this->assertCount(0, $result);
  1246. $query = new Query($this->connection);
  1247. $result = $query
  1248. ->select(['total' => 'count(author_id)', 'author_id'])
  1249. ->from('articles')
  1250. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1251. ->group('author_id')
  1252. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1253. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1254. ->execute();
  1255. $expected = [['total' => 2, 'author_id' => 1]];
  1256. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1257. $query = new Query($this->connection);
  1258. $result = $query
  1259. ->select(['total' => 'count(author_id)', 'author_id'])
  1260. ->from('articles')
  1261. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1262. ->group('author_id')
  1263. ->andHaving(function($e) {
  1264. return $e->add('count(author_id) = 2 - 1');
  1265. })
  1266. ->execute();
  1267. $expected = [['total' => 1, 'author_id' => 3]];
  1268. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1269. }
  1270. /**
  1271. * Tests selecting rows using a limit clause
  1272. *
  1273. * @return void
  1274. */
  1275. public function testSelectLimit() {
  1276. $query = new Query($this->connection);
  1277. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1278. $this->assertCount(1, $result);
  1279. $query = new Query($this->connection);
  1280. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1281. $this->assertCount(2, $result);
  1282. }
  1283. /**
  1284. * Tests selecting rows combining a limit and offset clause
  1285. *
  1286. * @return void
  1287. */
  1288. public function testSelectOffset() {
  1289. $query = new Query($this->connection);
  1290. $result = $query->select('id')->from('comments')
  1291. ->limit(1)
  1292. ->offset(0)
  1293. ->order(['id' => 'ASC'])
  1294. ->execute();
  1295. $this->assertCount(1, $result);
  1296. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1297. $query = new Query($this->connection);
  1298. $result = $query->select('id')->from('comments')
  1299. ->limit(1)
  1300. ->offset(1)
  1301. ->execute();
  1302. $this->assertCount(1, $result);
  1303. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1304. $query = new Query($this->connection);
  1305. $result = $query->select('id')->from('comments')
  1306. ->limit(1)
  1307. ->offset(2)
  1308. ->execute();
  1309. $this->assertCount(1, $result);
  1310. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1311. $query = new Query($this->connection);
  1312. $result = $query->select('id')->from('articles')
  1313. ->order(['id' => 'DESC'])
  1314. ->limit(1)
  1315. ->offset(0)
  1316. ->execute();
  1317. $this->assertCount(1, $result);
  1318. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1319. $result = $query->limit(2)->offset(1)->execute();
  1320. $this->assertCount(2, $result);
  1321. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1322. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1323. }
  1324. /**
  1325. * Test selecting rows using the page() method.
  1326. *
  1327. * @return void
  1328. */
  1329. public function testSelectPage() {
  1330. $query = new Query($this->connection);
  1331. $result = $query->select('id')->from('comments')
  1332. ->limit(1)
  1333. ->page(1)
  1334. ->execute();
  1335. $this->assertCount(1, $result);
  1336. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1337. $query = new Query($this->connection);
  1338. $result = $query->select('id')->from('comments')
  1339. ->limit(1)
  1340. ->page(2)
  1341. ->execute();
  1342. $this->assertCount(1, $result);
  1343. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1344. $query = new Query($this->connection);
  1345. $query->select('id')->from('comments')->page(1);
  1346. $this->assertEquals(25, $query->clause('limit'));
  1347. $this->assertEquals(0, $query->clause('offset'));
  1348. $query->select('id')->from('comments')->page(2);
  1349. $this->assertEquals(25, $query->clause('limit'));
  1350. $this->assertEquals(25, $query->clause('offset'));
  1351. }
  1352. /**
  1353. * Tests that Query objects can be included inside the select clause
  1354. * and be used as a normal field, including binding any passed parameter
  1355. *
  1356. * @return void
  1357. */
  1358. public function testSubqueryInSelect() {
  1359. $query = new Query($this->connection);
  1360. $subquery = (new Query($this->connection))
  1361. ->select('name')
  1362. ->from(['b' => 'authors'])
  1363. ->where(['b.id = a.id']);
  1364. $result = $query
  1365. ->select(['id', 'name' => $subquery])
  1366. ->from(['a' => 'comments'])->execute();
  1367. $expected = [
  1368. ['id' => 1, 'name' => 'mariano'],
  1369. ['id' => 2, 'name' => 'nate'],
  1370. ['id' => 3, 'name' => 'larry'],
  1371. ['id' => 4, 'name' => 'garrett'],
  1372. ['id' => 5, 'name' => null],
  1373. ['id' => 6, 'name' => null],
  1374. ];
  1375. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1376. $query = new Query($this->connection);
  1377. $subquery = (new Query($this->connection))
  1378. ->select('name')
  1379. ->from(['b' => 'authors'])
  1380. ->where(['name' => 'mariano'], ['name' => 'string']);
  1381. $result = $query
  1382. ->select(['id', 'name' => $subquery])
  1383. ->from(['a' => 'articles'])->execute();
  1384. $expected = [
  1385. ['id' => 1, 'name' => 'mariano'],
  1386. ['id' => 2, 'name' => 'mariano'],
  1387. ['id' => 3, 'name' => 'mariano'],
  1388. ];
  1389. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1390. }
  1391. /**
  1392. * Tests that Query objects can be included inside the from clause
  1393. * and be used as a normal table, including binding any passed parameter
  1394. *
  1395. * @return void
  1396. */
  1397. public function testSuqueryInFrom() {
  1398. $query = new Query($this->connection);
  1399. $subquery = (new Query($this->connection))
  1400. ->select(['id', 'comment'])
  1401. ->from('comments')
  1402. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1403. $result = $query
  1404. ->select(['say' => 'comment'])
  1405. ->from(['b' => $subquery])
  1406. ->where(['id !=' => 3])
  1407. ->execute();
  1408. $expected = [
  1409. ['say' => 'Second Comment for First Article'],
  1410. ['say' => 'Fourth Comment for First Article'],
  1411. ['say' => 'First Comment for Second Article'],
  1412. ['say' => 'Second Comment for Second Article'],
  1413. ];
  1414. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1415. }
  1416. /**
  1417. * Tests that Query objects can be included inside the where clause
  1418. * and be used as a normal condition, including binding any passed parameter
  1419. *
  1420. * @return void
  1421. */
  1422. public function testSubqueryInWhere() {
  1423. $query = new Query($this->connection);
  1424. $subquery = (new Query($this->connection))
  1425. ->select(['id'])
  1426. ->from('authors')
  1427. ->where(['id' => 1]);
  1428. $result = $query
  1429. ->select(['name'])
  1430. ->from(['authors'])
  1431. ->where(['id !=' => $subquery])
  1432. ->execute();
  1433. $expected = [
  1434. ['name' => 'nate'],
  1435. ['name' => 'larry'],
  1436. ['name' => 'garrett'],
  1437. ];
  1438. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1439. $query = new Query($this->connection);
  1440. $subquery = (new Query($this->connection))
  1441. ->select(['id'])
  1442. ->from('comments')
  1443. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1444. $result = $query
  1445. ->select(['name'])
  1446. ->from(['authors'])
  1447. ->where(['id not in' => $subquery])
  1448. ->execute();
  1449. $expected = [
  1450. ['name' => 'mariano'],
  1451. ];
  1452. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1453. }
  1454. /**
  1455. * Tests that it is possible to use a subquery in a join clause
  1456. *
  1457. * @return void
  1458. */
  1459. public function testSubqueyInJoin() {
  1460. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1461. $query = new Query($this->connection);
  1462. $result = $query
  1463. ->select(['title', 'name'])
  1464. ->from('articles')
  1465. ->join(['b' => $subquery])
  1466. ->execute();
  1467. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1468. $subquery->where(['id' => 1]);
  1469. $result = $query->execute();
  1470. $this->assertCount(3, $result);
  1471. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1472. $result = $query->execute();
  1473. $this->assertCount(1, $result);
  1474. }
  1475. /**
  1476. * Tests that it is possible to one or multiple UNION statements in a query
  1477. *
  1478. * @return void
  1479. */
  1480. public function testUnion() {
  1481. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1482. $query = new Query($this->connection);
  1483. $result = $query->select(['id', 'comment'])
  1484. ->from(['c' => 'comments'])
  1485. ->union($union)
  1486. ->execute();
  1487. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1488. $rows = $result->fetchAll();
  1489. $union->select(['foo' => 'id', 'bar' => 'title']);
  1490. $union = (new Query($this->connection))
  1491. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1492. ->from(['b' => 'authors'])
  1493. ->where(['id ' => 1])
  1494. ->order(['id' => 'desc']);
  1495. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1496. $result = $query->execute();
  1497. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1498. $this->assertNotEquals($rows, $result->fetchAll());
  1499. $union = (new Query($this->connection))
  1500. ->select(['id', 'title'])
  1501. ->from(['c' => 'articles']);
  1502. $query->select(['id', 'comment'], true)->union($union, true);
  1503. $result = $query->execute();
  1504. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1505. $this->assertEquals($rows, $result->fetchAll());
  1506. }
  1507. /**
  1508. * Tests that UNION ALL can be built by setting the second param of union() to true
  1509. *
  1510. * @return void
  1511. */
  1512. public function testUnionAll() {
  1513. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1514. $query = new Query($this->connection);
  1515. $result = $query->select(['id', 'comment'])
  1516. ->from(['c' => 'comments'])
  1517. ->union($union)
  1518. ->execute();
  1519. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1520. $rows = $result->fetchAll();
  1521. $union->select(['foo' => 'id', 'bar' => 'title']);
  1522. $union = (new Query($this->connection))
  1523. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1524. ->from(['b' => 'authors'])
  1525. ->where(['id ' => 1])
  1526. ->order(['id' => 'desc']);
  1527. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1528. $result = $query->execute();
  1529. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1530. $this->assertNotEquals($rows, $result->fetchAll());
  1531. }
  1532. /**
  1533. * Tests stacking decorators for results and resetting the list of decorators
  1534. *
  1535. * @return void
  1536. */
  1537. public function testDecorateResults() {
  1538. $query = new Query($this->connection);
  1539. $result = $query
  1540. ->select(['id', 'title'])
  1541. ->from('articles')
  1542. ->order(['id' => 'ASC'])
  1543. ->decorateResults(function($row) {
  1544. $row['modified_id'] = $row['id'] + 1;
  1545. return $row;
  1546. })
  1547. ->execute();
  1548. while ($row = $result->fetch('assoc')) {
  1549. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1550. }
  1551. $result = $query->decorateResults(function($row) {
  1552. $row['modified_id']--;
  1553. return $row;
  1554. })->execute();
  1555. while ($row = $result->fetch('assoc')) {
  1556. $this->assertEquals($row['id'], $row['modified_id']);
  1557. }
  1558. $result = $query
  1559. ->decorateResults(function($row) {
  1560. $row['foo'] = 'bar';
  1561. return $row;
  1562. }, true)
  1563. ->execute();
  1564. while ($row = $result->fetch('assoc')) {
  1565. $this->assertEquals('bar', $row['foo']);
  1566. $this->assertArrayNotHasKey('modified_id', $row);
  1567. }
  1568. $results = $query->decorateResults(null, true)->execute();
  1569. while ($row = $result->fetch('assoc')) {
  1570. $this->assertArrayNotHasKey('foo', $row);
  1571. $this->assertArrayNotHasKey('modified_id', $row);
  1572. }
  1573. }
  1574. /**
  1575. * Test a basic delete using from()
  1576. *
  1577. * @return void
  1578. */
  1579. public function testDeleteWithFrom() {
  1580. $query = new Query($this->connection);
  1581. $query->delete()
  1582. ->from('authors')
  1583. ->where('1 = 1');
  1584. $result = $query->sql();
  1585. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1586. $result = $query->execute();
  1587. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1588. $this->assertCount(self::AUTHOR_COUNT, $result);
  1589. }
  1590. /**
  1591. * Test a basic delete with no from() call.
  1592. *
  1593. * @return void
  1594. */
  1595. public function testDeleteNoFrom() {
  1596. $query = new Query($this->connection);
  1597. $query->delete('authors')
  1598. ->where('1 = 1');
  1599. $result = $query->sql();
  1600. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1601. $result = $query->execute();
  1602. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1603. $this->assertCount(self::AUTHOR_COUNT, $result);
  1604. }
  1605. /**
  1606. * Test setting select() & delete() modes.
  1607. *
  1608. * @return void
  1609. */
  1610. public function testSelectAndDeleteOnSameQuery() {
  1611. $query = new Query($this->connection);
  1612. $result = $query->select()
  1613. ->delete('authors')
  1614. ->where('1 = 1');
  1615. $result = $query->sql();
  1616. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1617. $this->assertContains(' WHERE 1 = 1', $result);
  1618. }
  1619. /**
  1620. * Test a simple update.
  1621. *
  1622. * @return void
  1623. */
  1624. public function testUpdateSimple() {
  1625. $query = new Query($this->connection);
  1626. $query->update('authors')
  1627. ->set('name', 'mark')
  1628. ->where(['id' => 1]);
  1629. $result = $query->sql();
  1630. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1631. $result = $query->execute();
  1632. $this->assertCount(1, $result);
  1633. }
  1634. /**
  1635. * Test update with multiple fields.
  1636. *
  1637. * @return void
  1638. */
  1639. public function testUpdateMultipleFields() {
  1640. $query = new Query($this->connection);
  1641. $query->update('articles')
  1642. ->set('title', 'mark', 'string')
  1643. ->set('body', 'some text', '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> = :c2$', $result, true);
  1652. $result = $query->execute();
  1653. $this->assertCount(1, $result);
  1654. }
  1655. /**
  1656. * Test updating multiple fields with an array.
  1657. *
  1658. * @return void
  1659. */
  1660. public function testUpdateMultipleFieldsArray() {
  1661. $query = new Query($this->connection);
  1662. $query->update('articles')
  1663. ->set([
  1664. 'title' => 'mark',
  1665. 'body' => 'some text'
  1666. ], ['title' => 'string', 'body' => 'string'])
  1667. ->where(['id' => 1]);
  1668. $result = $query->sql();
  1669. $this->assertQuotedQuery(
  1670. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1671. $result,
  1672. true
  1673. );
  1674. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1675. $result = $query->execute();
  1676. $this->assertCount(1, $result);
  1677. }
  1678. /**
  1679. * Test updates with an expression.
  1680. *
  1681. * @return void
  1682. */
  1683. public function testUpdateWithExpression() {
  1684. $query = new Query($this->connection);
  1685. $expr = $query->newExpr('title = author_id');
  1686. $query->update('articles')
  1687. ->set($expr)
  1688. ->where(['id' => 1]);
  1689. $result = $query->sql();
  1690. $this->assertQuotedQuery(
  1691. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  1692. $result,
  1693. true
  1694. );
  1695. $result = $query->execute();
  1696. $this->assertCount(1, $result);
  1697. }
  1698. /**
  1699. * Test update with array fields and types.
  1700. *
  1701. * @return void
  1702. */
  1703. public function testUpdateArrayFields() {
  1704. $query = new Query($this->connection);
  1705. $date = new \DateTime;
  1706. $query->update('comments')
  1707. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  1708. ->where(['id' => 1]);
  1709. $result = $query->sql();
  1710. $this->assertQuotedQuery(
  1711. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  1712. $result,
  1713. true
  1714. );
  1715. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1716. $result = $query->execute();
  1717. $this->assertCount(1, $result);
  1718. $query = new Query($this->connection);
  1719. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  1720. $result = $result->fetchAll('assoc')[0]['created'];
  1721. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  1722. }
  1723. /**
  1724. * You cannot call values() before insert() it causes all sorts of pain.
  1725. *
  1726. * @expectedException \Cake\Error\Exception
  1727. * @return void
  1728. */
  1729. public function testInsertValuesBeforeInsertFailure() {
  1730. $query = new Query($this->connection);
  1731. $query->select('*')->values([
  1732. 'id' => 1,
  1733. 'title' => 'mark',
  1734. 'body' => 'test insert'
  1735. ]);
  1736. }
  1737. /**
  1738. * Inserting nothing should not generate an error.
  1739. *
  1740. * @expectedException RuntimeException
  1741. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  1742. * @return void
  1743. */
  1744. public function testInsertNothing() {
  1745. $query = new Query($this->connection);
  1746. $query->insert([]);
  1747. }
  1748. /**
  1749. * Test inserting a single row.
  1750. *
  1751. * @return void
  1752. */
  1753. public function testInsertSimple() {
  1754. $query = new Query($this->connection);
  1755. $query->insert(['title', 'body'])
  1756. ->into('articles')
  1757. ->values([
  1758. 'title' => 'mark',
  1759. 'body' => 'test insert'
  1760. ]);
  1761. $result = $query->sql();
  1762. $this->assertQuotedQuery(
  1763. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1764. 'VALUES \(\?, \?\)',
  1765. $result,
  1766. true
  1767. );
  1768. $result = $query->execute();
  1769. $this->assertCount(1, $result, '1 row should be inserted');
  1770. $expected = [
  1771. [
  1772. 'id' => 4,
  1773. 'author_id' => null,
  1774. 'title' => 'mark',
  1775. 'body' => 'test insert',
  1776. 'published' => 'N',
  1777. ]
  1778. ];
  1779. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  1780. }
  1781. /**
  1782. * Test an insert when not all the listed fields are provided.
  1783. * Columns should be matched up where possible.
  1784. *
  1785. * @return void
  1786. */
  1787. public function testInsertSparseRow() {
  1788. $query = new Query($this->connection);
  1789. $query->insert(['title', 'body'])
  1790. ->into('articles')
  1791. ->values([
  1792. 'title' => 'mark',
  1793. ]);
  1794. $result = $query->sql();
  1795. $this->assertQuotedQuery(
  1796. 'INSERT INTO <articles> \(<title>, <body>\) ' .
  1797. 'VALUES \(\?, \?\)',
  1798. $result,
  1799. true
  1800. );
  1801. $result = $query->execute();
  1802. $this->assertCount(1, $result, '1 row should be inserted');
  1803. $expected = [
  1804. [
  1805. 'id' => 4,
  1806. 'author_id' => null,
  1807. 'title' => 'mark',
  1808. 'body' => null,
  1809. 'published' => 'N',
  1810. ]
  1811. ];
  1812. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  1813. }
  1814. /**
  1815. * Test inserting multiple rows with sparse data.
  1816. *
  1817. * @return void
  1818. */
  1819. public function testInsertMultipleRowsSparse() {
  1820. $query = new Query($this->connection);
  1821. $query->insert(['title', 'body'])
  1822. ->into('articles')
  1823. ->values([
  1824. 'body' => 'test insert'
  1825. ])
  1826. ->values([
  1827. 'title' => 'jose',
  1828. ]);
  1829. $result = $query->execute();
  1830. $this->assertCount(2, $result, '2 rows should be inserted');
  1831. $expected = [
  1832. [
  1833. 'id' => 4,
  1834. 'author_id' => null,
  1835. 'title' => null,
  1836. 'body' => 'test insert',
  1837. 'published' => 'N',
  1838. ],
  1839. [
  1840. 'id' => 5,
  1841. 'author_id' => null,
  1842. 'title' => 'jose',
  1843. 'body' => null,
  1844. 'published' => 'N',
  1845. ],
  1846. ];
  1847. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  1848. }
  1849. /**
  1850. * Test that INSERT INTO ... SELECT works.
  1851. *
  1852. * @return void
  1853. */
  1854. public function testInsertFromSelect() {
  1855. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  1856. ->from('authors')
  1857. ->where(['id' => 1]);
  1858. $query = new Query($this->connection);
  1859. $query->insert(
  1860. ['title', 'body', 'author_id'],
  1861. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  1862. )
  1863. ->into('articles')
  1864. ->values($select);
  1865. $result = $query->sql();
  1866. $this->assertQuotedQuery(
  1867. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) SELECT',
  1868. $result,
  1869. true
  1870. );
  1871. $this->assertQuotedQuery(
  1872. 'SELECT <name>, \'some text\', 99 FROM <authors>', $result, true);
  1873. $result = $query->execute();
  1874. $this->assertCount(1, $result);
  1875. $result = (new Query($this->connection))->select('*')
  1876. ->from('articles')
  1877. ->where(['author_id' => 99])
  1878. ->execute();
  1879. $this->assertCount(1, $result);
  1880. $expected = [
  1881. 'id' => 4,
  1882. 'title' => 'mariano',
  1883. 'body' => 'some text',
  1884. 'author_id' => 99,
  1885. 'published' => 'N',
  1886. ];
  1887. $this->assertEquals($expected, $result->fetch('assoc'));
  1888. }
  1889. /**
  1890. * Test that an exception is raised when mixing query + array types.
  1891. *
  1892. * @expectedException \Cake\Error\Exception
  1893. */
  1894. public function testInsertFailureMixingTypesArrayFirst() {
  1895. $query = new Query($this->connection);
  1896. $query->insert(['name'])
  1897. ->into('articles')
  1898. ->values(['name' => 'mark'])
  1899. ->values(new Query($this->connection));
  1900. }
  1901. /**
  1902. * Test that an exception is raised when mixing query + array types.
  1903. *
  1904. * @expectedException \Cake\Error\Exception
  1905. */
  1906. public function testInsertFailureMixingTypesQueryFirst() {
  1907. $query = new Query($this->connection);
  1908. $query->insert(['name'])
  1909. ->into('articles')
  1910. ->values(new Query($this->connection))
  1911. ->values(['name' => 'mark']);
  1912. }
  1913. /**
  1914. * Tests that functions are correctly transformed and their parameters are bound
  1915. *
  1916. * @group FunctionExpression
  1917. * @return void
  1918. */
  1919. public function testSQLFunctions() {
  1920. $query = new Query($this->connection);
  1921. $result = $query->select(
  1922. function($q) {
  1923. return ['total' => $q->func()->count('*')];
  1924. }
  1925. )
  1926. ->from('articles')
  1927. ->execute();
  1928. $expected = [['total' => 3]];
  1929. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1930. $query = new Query($this->connection);
  1931. $result = $query->select([
  1932. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  1933. ])
  1934. ->from('articles')
  1935. ->order(['c' => 'ASC'])
  1936. ->execute();
  1937. $expected = [
  1938. ['c' => 'First Article is appended'],
  1939. ['c' => 'Second Article is appended'],
  1940. ['c' => 'Third Article is appended']
  1941. ];
  1942. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1943. $query = new Query($this->connection);
  1944. $result = $query
  1945. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  1946. ->execute()
  1947. ->fetchAll('assoc');
  1948. $this->assertEquals(3, abs($result[0]['d']));
  1949. $query = new Query($this->connection);
  1950. $result = $query
  1951. ->select(['d' => $query->func()->now('date')])
  1952. ->execute();
  1953. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  1954. $query = new Query($this->connection);
  1955. $result = $query
  1956. ->select(['d' => $query->func()->now('time')])
  1957. ->execute();
  1958. $this->assertWithinMargin(
  1959. date('U'),
  1960. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1961. 1
  1962. );
  1963. $query = new Query($this->connection);
  1964. $result = $query
  1965. ->select(['d' => $query->func()->now()])
  1966. ->execute();
  1967. $this->assertWithinMargin(
  1968. date('U'),
  1969. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  1970. 1
  1971. );
  1972. }
  1973. /**
  1974. * Tests that default types are passed to functions accepting a $types param
  1975. *
  1976. * @return void
  1977. */
  1978. public function testDefaultTypes() {
  1979. $query = new Query($this->connection);
  1980. $this->assertEquals([], $query->defaultTypes());
  1981. $types = ['id' => 'integer', 'created' => 'datetime'];
  1982. $this->assertSame($query, $query->defaultTypes($types));
  1983. $this->assertSame($types, $query->defaultTypes());
  1984. $results = $query->select(['id', 'comment'])
  1985. ->from('comments')
  1986. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  1987. ->execute();
  1988. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  1989. $this->assertEquals($expected, $results->fetchAll('assoc'));
  1990. // Now test default can be overridden
  1991. $types = ['created' => 'date'];
  1992. $results = $query
  1993. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  1994. ->execute();
  1995. $this->assertCount(6, $results, 'All 6 rows should match.');
  1996. }
  1997. /**
  1998. * Tests parameter binding
  1999. *
  2000. * @return void
  2001. */
  2002. public function testBind() {
  2003. $query = new Query($this->connection);
  2004. $results = $query->select(['id', 'comment'])
  2005. ->from('comments')
  2006. ->where(['created BETWEEN :foo AND :bar'])
  2007. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2008. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2009. ->execute();
  2010. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2011. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2012. $query = new Query($this->connection);
  2013. $results = $query->select(['id', 'comment'])
  2014. ->from('comments')
  2015. ->where(['created BETWEEN :foo AND :bar'])
  2016. ->bind(':foo', '2007-03-18 10:50:00')
  2017. ->bind(':bar', '2007-03-18 10:52:00')
  2018. ->execute();
  2019. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2020. }
  2021. /**
  2022. * Test that epilog() will actually append a string to a select query
  2023. *
  2024. * @return void
  2025. */
  2026. public function testAppendSelect() {
  2027. $query = new Query($this->connection);
  2028. $sql = $query
  2029. ->select(['id', 'title'])
  2030. ->from('articles')
  2031. ->where(['id' => 1])
  2032. ->epilog('FOR UPDATE')
  2033. ->sql();
  2034. $this->assertContains('SELECT', $sql);
  2035. $this->assertContains('FROM', $sql);
  2036. $this->assertContains('WHERE', $sql);
  2037. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2038. }
  2039. /**
  2040. * Test that epilog() will actually append a string to an insert query
  2041. *
  2042. * @return void
  2043. */
  2044. public function testAppendInsert() {
  2045. $query = new Query($this->connection);
  2046. $sql = $query
  2047. ->insert(['id', 'title'])
  2048. ->into('articles')
  2049. ->values([1, 'a title'])
  2050. ->epilog('RETURNING id')
  2051. ->sql();
  2052. $this->assertContains('INSERT', $sql);
  2053. $this->assertContains('INTO', $sql);
  2054. $this->assertContains('VALUES', $sql);
  2055. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2056. }
  2057. /**
  2058. * Test that epilog() will actually append a string to an update query
  2059. *
  2060. * @return void
  2061. */
  2062. public function testAppendUpdate() {
  2063. $query = new Query($this->connection);
  2064. $sql = $query
  2065. ->update('articles')
  2066. ->set(['title' => 'foo'])
  2067. ->where(['id' => 1])
  2068. ->epilog('RETURNING id')
  2069. ->sql();
  2070. $this->assertContains('UPDATE', $sql);
  2071. $this->assertContains('SET', $sql);
  2072. $this->assertContains('WHERE', $sql);
  2073. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2074. }
  2075. /**
  2076. * Test that epilog() will actually append a string to a delete query
  2077. *
  2078. * @return void
  2079. */
  2080. public function testAppendDelete() {
  2081. $query = new Query($this->connection);
  2082. $sql = $query
  2083. ->delete('articles')
  2084. ->where(['id' => 1])
  2085. ->epilog('RETURNING id')
  2086. ->sql();
  2087. $this->assertContains('DELETE FROM', $sql);
  2088. $this->assertContains('WHERE', $sql);
  2089. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2090. }
  2091. /**
  2092. * Tests automatic identifier quoting in the select clause
  2093. *
  2094. * @return void
  2095. */
  2096. public function testQuotingSelectFieldsAndAlias() {
  2097. $this->connection->driver()->autoQuoting(true);
  2098. $query = new Query($this->connection);
  2099. $sql = $query->select(['something'])->sql();
  2100. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2101. $query = new Query($this->connection);
  2102. $sql = $query->select(['foo' => 'something'])->sql();
  2103. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2104. $query = new Query($this->connection);
  2105. $sql = $query->select(['foo' => 1])->sql();
  2106. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2107. $query = new Query($this->connection);
  2108. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2109. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2110. $query = new Query($this->connection);
  2111. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2112. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2113. $query = new Query($this->connection);
  2114. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2115. $this->assertQuotedQuery('<bar>', $sql);
  2116. }
  2117. /**
  2118. * Tests automatic identifier quoting in the from clause
  2119. *
  2120. * @return void
  2121. */
  2122. public function testQuotingFromAndAlias() {
  2123. $this->connection->driver()->autoQuoting(true);
  2124. $query = new Query($this->connection);
  2125. $sql = $query->select('*')->from(['something'])->sql();
  2126. $this->assertQuotedQuery('FROM <something>', $sql);
  2127. $query = new Query($this->connection);
  2128. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2129. $this->assertQuotedQuery('FROM <something> AS <foo>$', $sql);
  2130. $query = new Query($this->connection);
  2131. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2132. $this->assertQuotedQuery('FROM \(bar\) AS <foo>$', $sql);
  2133. }
  2134. /**
  2135. * Tests automatic identifier quoting for DISTINCT ON
  2136. *
  2137. * @return void
  2138. */
  2139. public function testQuotingDistinctOn() {
  2140. $this->connection->driver()->autoQuoting(true);
  2141. $query = new Query($this->connection);
  2142. $sql = $query->select('*')->distinct(['something'])->sql();
  2143. $this->assertQuotedQuery('<something>', $sql);
  2144. }
  2145. /**
  2146. * Tests automatic identifier quoting in the join clause
  2147. *
  2148. * @return void
  2149. */
  2150. public function testQuotingJoinsAndAlias() {
  2151. $this->connection->driver()->autoQuoting(true);
  2152. $query = new Query($this->connection);
  2153. $sql = $query->select('*')->join(['something'])->sql();
  2154. $this->assertQuotedQuery('JOIN <something>', $sql);
  2155. $query = new Query($this->connection);
  2156. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2157. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2158. $query = new Query($this->connection);
  2159. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2160. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2161. }
  2162. /**
  2163. * Tests automatic identifier quoting in the group by clause
  2164. *
  2165. * @return void
  2166. */
  2167. public function testQuotingGroupBy() {
  2168. $this->connection->driver()->autoQuoting(true);
  2169. $query = new Query($this->connection);
  2170. $sql = $query->select('*')->group(['something'])->sql();
  2171. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2172. $query = new Query($this->connection);
  2173. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2174. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2175. $query = new Query($this->connection);
  2176. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2177. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2178. }
  2179. /**
  2180. * Tests automatic identifier quoting strings inside conditions expressions
  2181. *
  2182. * @return void
  2183. */
  2184. public function testQuotingExpressions() {
  2185. $this->connection->driver()->autoQuoting(true);
  2186. $query = new Query($this->connection);
  2187. $sql = $query->select('*')
  2188. ->where(['something' => 'value'])
  2189. ->sql();
  2190. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2191. $query = new Query($this->connection);
  2192. $sql = $query->select('*')
  2193. ->where([
  2194. 'something' => 'value',
  2195. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2196. ])
  2197. ->sql();
  2198. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2199. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2200. }
  2201. /**
  2202. * Tests that insert query parts get quoted automatically
  2203. *
  2204. * @return void
  2205. */
  2206. public function testQuotingInsert() {
  2207. $this->connection->driver()->autoQuoting(true);
  2208. $query = new Query($this->connection);
  2209. $sql = $query->insert(['bar', 'baz'])
  2210. ->into('foo')
  2211. ->where(['something' => 'value'])
  2212. ->sql();
  2213. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2214. $query = new Query($this->connection);
  2215. $sql = $query->insert([$query->newExpr('bar')])
  2216. ->into('foo')
  2217. ->where(['something' => 'value'])
  2218. ->sql();
  2219. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2220. }
  2221. /**
  2222. * Tests converting a query to a string
  2223. *
  2224. * @return void
  2225. */
  2226. public function testToString() {
  2227. $query = new Query($this->connection);
  2228. $query
  2229. ->select(['title'])
  2230. ->from('articles');
  2231. $result = (string)$query;
  2232. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, true);
  2233. }
  2234. /**
  2235. * Tests __debugInfo
  2236. *
  2237. * @return void
  2238. */
  2239. public function testDebugInfo() {
  2240. $query = (new Query($this->connection))->select('*')
  2241. ->from('articles')
  2242. ->defaultTypes(['id' => 'integer'])
  2243. ->where(['id' => '1']);
  2244. $expected = [
  2245. 'sql' => $query->sql(),
  2246. 'params' => [
  2247. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2248. ],
  2249. 'defaultTypes' => ['id' => 'integer'],
  2250. 'decorators' => 0,
  2251. 'executed' => false
  2252. ];
  2253. $result = $query->__debugInfo();
  2254. $this->assertEquals($expected, $result);
  2255. $query->execute();
  2256. $expected = [
  2257. 'sql' => $query->sql(),
  2258. 'params' => [
  2259. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2260. ],
  2261. 'defaultTypes' => ['id' => 'integer'],
  2262. 'decorators' => 0,
  2263. 'executed' => true
  2264. ];
  2265. $result = $query->__debugInfo();
  2266. }
  2267. /**
  2268. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2269. *
  2270. * @return void
  2271. */
  2272. public function testIsNullWithExpressions() {
  2273. $query = new Query($this->connection);
  2274. $subquery = (new Query($this->connection))
  2275. ->select(['id'])
  2276. ->from('authors')
  2277. ->where(['id' => 1]);
  2278. $result = $query
  2279. ->select(['name'])
  2280. ->from(['authors'])
  2281. ->where(function($exp) use ($subquery) {
  2282. return $exp->isNotNull($subquery);
  2283. })
  2284. ->execute();
  2285. $this->assertNotEmpty($result->fetchAll('assoc'));
  2286. $result = (new Query($this->connection))
  2287. ->select(['name'])
  2288. ->from(['authors'])
  2289. ->where(function($exp) use ($subquery) {
  2290. return $exp->isNull($subquery);
  2291. })
  2292. ->execute();
  2293. $this->assertEmpty($result->fetchAll('assoc'));
  2294. }
  2295. /**
  2296. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2297. * when using autoQuoting
  2298. *
  2299. * @return void
  2300. */
  2301. public function testIsNullAutoQuoting() {
  2302. $this->connection->driver()->autoQuoting(true);
  2303. $query = new Query($this->connection);
  2304. $query->select('*')->from('things')->where(function($exp) {
  2305. return $exp->isNull('field');
  2306. });
  2307. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2308. $query = new Query($this->connection);
  2309. $query->select('*')->from('things')->where(function($exp) {
  2310. return $exp->isNotNull('field');
  2311. });
  2312. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2313. }
  2314. /**
  2315. * Assertion for comparing a table's contents with what is in it.
  2316. *
  2317. * @param string $table
  2318. * @param int $count
  2319. * @param array $rows
  2320. * @param array $conditions
  2321. * @return void
  2322. */
  2323. public function assertTable($table, $count, $rows, $conditions = []) {
  2324. $result = (new Query($this->connection))->select('*')
  2325. ->from($table)
  2326. ->where($conditions)
  2327. ->execute();
  2328. $this->assertCount($count, $result, 'Row count is incorrect');
  2329. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2330. }
  2331. /**
  2332. * Assertion for comparing a regex pattern against a query having its indentifiers
  2333. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2334. * parameter is set to true, it will alter the pattern to both accept quoted and
  2335. * unquoted queries
  2336. *
  2337. * @param string $pattern
  2338. * @param string $query the result to compare against
  2339. * @param bool $optional
  2340. * @return void
  2341. */
  2342. public function assertQuotedQuery($pattern, $query, $optional = false) {
  2343. if ($optional) {
  2344. $optional = '?';
  2345. }
  2346. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2347. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2348. $this->assertRegExp('#' . $pattern . '#', $query);
  2349. }
  2350. }