QueryTest.php 75 KB

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