QueryTest.php 79 KB

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