QueryTest.php 106 KB

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