QueryTest.php 109 KB

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