QueryTest.php 72 KB

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