QueryTest.php 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452
  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. !$this->autoQuote
  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. !$this->autoQuote
  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 where() with callable types.
  1089. *
  1090. * @return void
  1091. */
  1092. public function testWhereCallables()
  1093. {
  1094. $query = new Query($this->connection);
  1095. $query->select(['id'])
  1096. ->from('articles')
  1097. ->where([
  1098. 'id' => '\Cake\Error\Debugger::dump',
  1099. 'title' => ['\Cake\Error\Debugger', 'dump'],
  1100. 'author_id' => function ($exp) {
  1101. return 1;
  1102. }
  1103. ]);
  1104. $this->assertQuotedQuery(
  1105. 'SELECT <id> FROM <articles> WHERE \(<id> = :c0 AND <title> = :c1 AND <author_id> = :c2\)',
  1106. $query->sql(),
  1107. !$this->autoQuote
  1108. );
  1109. }
  1110. /**
  1111. * Tests that empty values don't set where clauses.
  1112. *
  1113. * @return void
  1114. */
  1115. public function testWhereEmptyValues()
  1116. {
  1117. $query = new Query($this->connection);
  1118. $query->from('comments')
  1119. ->where('');
  1120. $this->assertCount(0, $query->clause('where'));
  1121. $query->where([]);
  1122. $this->assertCount(0, $query->clause('where'));
  1123. }
  1124. /**
  1125. * Tests that it is possible to use a between expression
  1126. * in a where condition
  1127. *
  1128. * @return void
  1129. */
  1130. public function testWhereWithBetween()
  1131. {
  1132. $query = new Query($this->connection);
  1133. $result = $query
  1134. ->select(['id'])
  1135. ->from('comments')
  1136. ->where(function ($exp) {
  1137. return $exp->between('id', 5, 6, 'integer');
  1138. })
  1139. ->execute();
  1140. $this->assertCount(2, $result);
  1141. $first = $result->fetch('assoc');
  1142. $this->assertEquals(5, $first['id']);
  1143. $second = $result->fetch('assoc');
  1144. $this->assertEquals(6, $second['id']);
  1145. }
  1146. /**
  1147. * Tests that it is possible to use a between expression
  1148. * in a where condition with a complex data type
  1149. *
  1150. * @return void
  1151. */
  1152. public function testWhereWithBetweenComplex()
  1153. {
  1154. $query = new Query($this->connection);
  1155. $result = $query
  1156. ->select(['id'])
  1157. ->from('comments')
  1158. ->where(function ($exp) {
  1159. $from = new \DateTime('2007-03-18 10:51:00');
  1160. $to = new \DateTime('2007-03-18 10:54:00');
  1161. return $exp->between('created', $from, $to, 'datetime');
  1162. })
  1163. ->execute();
  1164. $this->assertCount(2, $result);
  1165. $first = $result->fetch('assoc');
  1166. $this->assertEquals(4, $first['id']);
  1167. $second = $result->fetch('assoc');
  1168. $this->assertEquals(5, $second['id']);
  1169. }
  1170. /**
  1171. * Tests that it is possible to use an expression object
  1172. * as the field for a between expression
  1173. *
  1174. * @return void
  1175. */
  1176. public function testWhereWithBetweenWithExpressionField()
  1177. {
  1178. $query = new Query($this->connection);
  1179. $result = $query
  1180. ->select(['id'])
  1181. ->from('comments')
  1182. ->where(function ($exp, $q) {
  1183. $field = $q->newExpr('COALESCE(id, 1)');
  1184. return $exp->between($field, 5, 6, 'integer');
  1185. })
  1186. ->execute();
  1187. $this->assertCount(2, $result);
  1188. $first = $result->fetch('assoc');
  1189. $this->assertEquals(5, $first['id']);
  1190. $second = $result->fetch('assoc');
  1191. $this->assertEquals(6, $second['id']);
  1192. }
  1193. /**
  1194. * Tests nesting query expressions both using arrays and closures
  1195. *
  1196. * @return void
  1197. */
  1198. public function testSelectExpressionComposition()
  1199. {
  1200. $query = new Query($this->connection);
  1201. $result = $query
  1202. ->select(['id'])
  1203. ->from('comments')
  1204. ->where(function ($exp) {
  1205. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  1206. return $exp->add($and);
  1207. })
  1208. ->execute();
  1209. $this->assertCount(1, $result);
  1210. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1211. $query = new Query($this->connection);
  1212. $result = $query
  1213. ->select(['id'])
  1214. ->from('comments')
  1215. ->where(function ($exp) {
  1216. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  1217. return $exp->add($and);
  1218. })
  1219. ->execute();
  1220. $this->assertCount(0, $result);
  1221. $query = new Query($this->connection);
  1222. $result = $query
  1223. ->select(['id'])
  1224. ->from('comments')
  1225. ->where(function ($exp) {
  1226. $and = $exp->and_(function ($and) {
  1227. return $and->eq('id', 1)->gt('id', 0);
  1228. });
  1229. return $exp->add($and);
  1230. })
  1231. ->execute();
  1232. $this->assertCount(1, $result);
  1233. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1234. $query = new Query($this->connection);
  1235. $result = $query
  1236. ->select(['id'])
  1237. ->from('comments')
  1238. ->where(function ($exp) {
  1239. $or = $exp->or_(['id' => 1]);
  1240. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  1241. return $or->add($and);
  1242. })
  1243. ->execute();
  1244. $this->assertCount(2, $result);
  1245. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1246. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1247. $query = new Query($this->connection);
  1248. $result = $query
  1249. ->select(['id'])
  1250. ->from('comments')
  1251. ->where(function ($exp) {
  1252. $or = $exp->or_(function ($or) {
  1253. return $or->eq('id', 1)->eq('id', 2);
  1254. });
  1255. return $or;
  1256. })
  1257. ->execute();
  1258. $this->assertCount(2, $result);
  1259. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1260. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1261. }
  1262. /**
  1263. * Tests that conditions can be nested with an unary operator using the array notation
  1264. * and the not() method
  1265. *
  1266. * @return void
  1267. */
  1268. public function testSelectWhereNot()
  1269. {
  1270. $query = new Query($this->connection);
  1271. $result = $query
  1272. ->select(['id'])
  1273. ->from('comments')
  1274. ->where(function ($exp) {
  1275. return $exp->not(
  1276. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  1277. );
  1278. })
  1279. ->execute();
  1280. $this->assertCount(5, $result);
  1281. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1282. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1283. $query = new Query($this->connection);
  1284. $result = $query
  1285. ->select(['id'])
  1286. ->from('comments')
  1287. ->where(function ($exp) {
  1288. return $exp->not(
  1289. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  1290. );
  1291. })
  1292. ->execute();
  1293. $this->assertCount(6, $result);
  1294. $query = new Query($this->connection);
  1295. $result = $query
  1296. ->select(['id'])
  1297. ->from('articles')
  1298. ->where([
  1299. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  1300. ])
  1301. ->execute();
  1302. $this->assertCount(2, $result);
  1303. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1304. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1305. }
  1306. /**
  1307. * Tests order() method both with simple fields and expressions
  1308. *
  1309. * @return void
  1310. */
  1311. public function testSelectOrderBy()
  1312. {
  1313. $query = new Query($this->connection);
  1314. $result = $query
  1315. ->select(['id'])
  1316. ->from('articles')
  1317. ->order(['id' => 'desc'])
  1318. ->execute();
  1319. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1320. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1321. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1322. $result = $query->order(['id' => 'asc'])->execute();
  1323. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1324. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1325. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1326. $result = $query->order(['title' => 'asc'])->execute();
  1327. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1328. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1329. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1330. $result = $query->order(['title' => 'asc'], true)->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. $result = $query->order(['title' => 'asc', 'published' => 'asc'], true)
  1335. ->execute();
  1336. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1337. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1338. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1339. $expression = $query->newExpr(['(id + :offset) % 2']);
  1340. $result = $query
  1341. ->order([$expression, 'id' => 'desc'], true)
  1342. ->bind(':offset', 1, null)
  1343. ->execute();
  1344. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1345. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1346. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1347. $result = $query
  1348. ->order($expression, true)
  1349. ->order(['id' => 'asc'])
  1350. ->bind(':offset', 1, null)
  1351. ->execute();
  1352. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1353. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1354. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1355. }
  1356. /**
  1357. * Test that order() being a string works.
  1358. *
  1359. * @return void
  1360. */
  1361. public function testSelectOrderByString()
  1362. {
  1363. $query = new Query($this->connection);
  1364. $query->select(['id'])
  1365. ->from('articles')
  1366. ->order('id asc');
  1367. $result = $query->execute();
  1368. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1369. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1370. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1371. }
  1372. /**
  1373. * Test orderAsc() and its input types.
  1374. *
  1375. * @return void
  1376. */
  1377. public function testSelectOrderAsc()
  1378. {
  1379. $query = new Query($this->connection);
  1380. $query->select(['id'])
  1381. ->from('articles')
  1382. ->orderAsc('id');
  1383. $sql = $query->sql();
  1384. $result = $query->execute()->fetchAll('assoc');
  1385. $expected = [
  1386. ['id' => 1],
  1387. ['id' => 2],
  1388. ['id' => 3],
  1389. ];
  1390. $this->assertEquals($expected, $result);
  1391. $this->assertQuotedQuery(
  1392. 'SELECT <id> FROM <articles> ORDER BY <id> ASC',
  1393. $sql,
  1394. !$this->autoQuote
  1395. );
  1396. $query = new Query($this->connection);
  1397. $query->select(['id'])
  1398. ->from('articles')
  1399. ->orderAsc($query->func()->concat(['id' => 'literal', '3']));
  1400. $result = $query->execute()->fetchAll('assoc');
  1401. $expected = [
  1402. ['id' => 1],
  1403. ['id' => 2],
  1404. ['id' => 3],
  1405. ];
  1406. $this->assertEquals($expected, $result);
  1407. }
  1408. /**
  1409. * Test orderDesc() and its input types.
  1410. *
  1411. * @return void
  1412. */
  1413. public function testSelectOrderDesc()
  1414. {
  1415. $query = new Query($this->connection);
  1416. $query->select(['id'])
  1417. ->from('articles')
  1418. ->orderDesc('id');
  1419. $sql = $query->sql();
  1420. $result = $query->execute()->fetchAll('assoc');
  1421. $expected = [
  1422. ['id' => 3],
  1423. ['id' => 2],
  1424. ['id' => 1],
  1425. ];
  1426. $this->assertEquals($expected, $result);
  1427. $this->assertQuotedQuery(
  1428. 'SELECT <id> FROM <articles> ORDER BY <id> DESC',
  1429. $sql,
  1430. !$this->autoQuote
  1431. );
  1432. $query = new Query($this->connection);
  1433. $query->select(['id'])
  1434. ->from('articles')
  1435. ->orderDesc($query->func()->concat(['id' => 'literal', '3']));
  1436. $result = $query->execute()->fetchAll('assoc');
  1437. $expected = [
  1438. ['id' => 3],
  1439. ['id' => 2],
  1440. ['id' => 1],
  1441. ];
  1442. $this->assertEquals($expected, $result);
  1443. }
  1444. /**
  1445. * Tests that group by fields can be passed similar to select fields
  1446. * and that it sends the correct query to the database
  1447. *
  1448. * @return void
  1449. */
  1450. public function testSelectGroup()
  1451. {
  1452. $query = new Query($this->connection);
  1453. $result = $query
  1454. ->select(['total' => 'count(author_id)', 'author_id'])
  1455. ->from('articles')
  1456. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1457. ->group('author_id')
  1458. ->execute();
  1459. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1460. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1461. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1462. ->group(['name'], true)
  1463. ->order(['total' => 'asc'])
  1464. ->execute();
  1465. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1466. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1467. $result = $query->select(['articles.id'])
  1468. ->group(['articles.id'])
  1469. ->execute();
  1470. $this->assertCount(3, $result);
  1471. }
  1472. /**
  1473. * Tests that it is possible to select distinct rows
  1474. *
  1475. * @return void
  1476. */
  1477. public function testSelectDistinct()
  1478. {
  1479. $query = new Query($this->connection);
  1480. $result = $query
  1481. ->select(['author_id'])
  1482. ->from(['a' => 'articles'])
  1483. ->execute();
  1484. $this->assertCount(3, $result);
  1485. $result = $query->distinct()->execute();
  1486. $this->assertCount(2, $result);
  1487. $result = $query->select(['id'])->distinct(false)->execute();
  1488. $this->assertCount(3, $result);
  1489. }
  1490. /**
  1491. * Tests that it is possible to select distinct rows, even filtering by one column
  1492. * this is testing that there is a specific implementation for DISTINCT ON
  1493. *
  1494. * @return void
  1495. */
  1496. public function testSelectDistinctON()
  1497. {
  1498. $query = new Query($this->connection);
  1499. $result = $query
  1500. ->select(['id', 'author_id'])
  1501. ->distinct(['author_id'])
  1502. ->from(['a' => 'articles'])
  1503. ->order(['author_id' => 'ASC'])
  1504. ->execute();
  1505. $this->assertCount(2, $result);
  1506. $results = $result->fetchAll('assoc');
  1507. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1508. $this->assertEquals(
  1509. [3, 1],
  1510. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1511. );
  1512. $query = new Query($this->connection);
  1513. $result = $query
  1514. ->select(['id', 'author_id'])
  1515. ->distinct('author_id')
  1516. ->from(['a' => 'articles'])
  1517. ->order(['author_id' => 'ASC'])
  1518. ->execute();
  1519. $this->assertCount(2, $result);
  1520. $results = $result->fetchAll('assoc');
  1521. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1522. $this->assertEquals(
  1523. [3, 1],
  1524. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1525. );
  1526. }
  1527. /**
  1528. * Test use of modifiers in the query
  1529. *
  1530. * Testing the generated SQL since the modifiers are usually different per driver
  1531. *
  1532. * @return void
  1533. */
  1534. public function testSelectModifiers()
  1535. {
  1536. $query = new Query($this->connection);
  1537. $result = $query
  1538. ->select(['city', 'state', 'country'])
  1539. ->from(['addresses'])
  1540. ->modifier('DISTINCTROW');
  1541. $this->assertQuotedQuery(
  1542. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1543. $result->sql(),
  1544. !$this->autoQuote
  1545. );
  1546. $query = new Query($this->connection);
  1547. $result = $query
  1548. ->select(['city', 'state', 'country'])
  1549. ->from(['addresses'])
  1550. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1551. $this->assertQuotedQuery(
  1552. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1553. $result->sql(),
  1554. !$this->autoQuote
  1555. );
  1556. $query = new Query($this->connection);
  1557. $result = $query
  1558. ->select(['city', 'state', 'country'])
  1559. ->from(['addresses'])
  1560. ->modifier('DISTINCTROW')
  1561. ->modifier('SQL_NO_CACHE');
  1562. $this->assertQuotedQuery(
  1563. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1564. $result->sql(),
  1565. true
  1566. );
  1567. $query = new Query($this->connection);
  1568. $result = $query
  1569. ->select(['city', 'state', 'country'])
  1570. ->from(['addresses'])
  1571. ->modifier(['TOP 10']);
  1572. $this->assertQuotedQuery(
  1573. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1574. $result->sql(),
  1575. !$this->autoQuote
  1576. );
  1577. }
  1578. /**
  1579. * Tests that having() behaves pretty much the same as the where() method
  1580. *
  1581. * @return void
  1582. */
  1583. public function testSelectHaving()
  1584. {
  1585. $query = new Query($this->connection);
  1586. $result = $query
  1587. ->select(['total' => 'count(author_id)', 'author_id'])
  1588. ->from('articles')
  1589. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1590. ->group('author_id')
  1591. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1592. ->execute();
  1593. $expected = [['total' => 1, 'author_id' => 3]];
  1594. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1595. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1596. ->execute();
  1597. $expected = [['total' => 2, 'author_id' => 1]];
  1598. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1599. $result = $query->having(function ($e) {
  1600. return $e->add('count(author_id) = 1 + 1');
  1601. }, [], true)
  1602. ->execute();
  1603. $expected = [['total' => 2, 'author_id' => 1]];
  1604. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1605. }
  1606. /**
  1607. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1608. * in the having clause
  1609. *
  1610. * @return void
  1611. */
  1612. public function testSelectOrHaving()
  1613. {
  1614. $query = new Query($this->connection);
  1615. $result = $query
  1616. ->select(['total' => 'count(author_id)', 'author_id'])
  1617. ->from('articles')
  1618. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1619. ->group('author_id')
  1620. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1621. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1622. ->execute();
  1623. $expected = [['total' => 1, 'author_id' => 3]];
  1624. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1625. $query = new Query($this->connection);
  1626. $result = $query
  1627. ->select(['total' => 'count(author_id)', 'author_id'])
  1628. ->from('articles')
  1629. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1630. ->group('author_id')
  1631. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1632. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1633. ->execute();
  1634. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1635. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1636. $query = new Query($this->connection);
  1637. $result = $query
  1638. ->select(['total' => 'count(author_id)', 'author_id'])
  1639. ->from('articles')
  1640. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1641. ->group('author_id')
  1642. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1643. ->orHaving(function ($e) {
  1644. return $e->add('count(author_id) = 1 + 1');
  1645. })
  1646. ->execute();
  1647. $expected = [['total' => 2, 'author_id' => 1]];
  1648. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1649. }
  1650. /**
  1651. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1652. * in the having clause
  1653. *
  1654. * @return void
  1655. */
  1656. public function testSelectAndHaving()
  1657. {
  1658. $query = new Query($this->connection);
  1659. $result = $query
  1660. ->select(['total' => 'count(author_id)', 'author_id'])
  1661. ->from('articles')
  1662. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1663. ->group('author_id')
  1664. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1665. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1666. ->execute();
  1667. $this->assertCount(0, $result);
  1668. $query = new Query($this->connection);
  1669. $result = $query
  1670. ->select(['total' => 'count(author_id)', 'author_id'])
  1671. ->from('articles')
  1672. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1673. ->group('author_id')
  1674. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1675. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1676. ->execute();
  1677. $expected = [['total' => 2, 'author_id' => 1]];
  1678. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1679. $query = new Query($this->connection);
  1680. $result = $query
  1681. ->select(['total' => 'count(author_id)', 'author_id'])
  1682. ->from('articles')
  1683. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1684. ->group('author_id')
  1685. ->andHaving(function ($e) {
  1686. return $e->add('count(author_id) = 2 - 1');
  1687. })
  1688. ->execute();
  1689. $expected = [['total' => 1, 'author_id' => 3]];
  1690. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1691. }
  1692. /**
  1693. * Tests selecting rows using a limit clause
  1694. *
  1695. * @return void
  1696. */
  1697. public function testSelectLimit()
  1698. {
  1699. $query = new Query($this->connection);
  1700. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1701. $this->assertCount(1, $result);
  1702. $query = new Query($this->connection);
  1703. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1704. $this->assertCount(2, $result);
  1705. }
  1706. /**
  1707. * Tests selecting rows combining a limit and offset clause
  1708. *
  1709. * @return void
  1710. */
  1711. public function testSelectOffset()
  1712. {
  1713. $query = new Query($this->connection);
  1714. $result = $query->select('id')->from('comments')
  1715. ->limit(1)
  1716. ->offset(0)
  1717. ->order(['id' => 'ASC'])
  1718. ->execute();
  1719. $this->assertCount(1, $result);
  1720. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1721. $query = new Query($this->connection);
  1722. $result = $query->select('id')->from('comments')
  1723. ->limit(1)
  1724. ->offset(1)
  1725. ->execute();
  1726. $this->assertCount(1, $result);
  1727. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1728. $query = new Query($this->connection);
  1729. $result = $query->select('id')->from('comments')
  1730. ->limit(1)
  1731. ->offset(2)
  1732. ->execute();
  1733. $this->assertCount(1, $result);
  1734. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1735. $query = new Query($this->connection);
  1736. $result = $query->select('id')->from('articles')
  1737. ->order(['id' => 'DESC'])
  1738. ->limit(1)
  1739. ->offset(0)
  1740. ->execute();
  1741. $this->assertCount(1, $result);
  1742. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1743. $result = $query->limit(2)->offset(1)->execute();
  1744. $this->assertCount(2, $result);
  1745. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1746. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1747. }
  1748. /**
  1749. * Test selecting rows using the page() method.
  1750. *
  1751. * @return void
  1752. */
  1753. public function testSelectPage()
  1754. {
  1755. $query = new Query($this->connection);
  1756. $result = $query->select('id')->from('comments')
  1757. ->limit(1)
  1758. ->page(1)
  1759. ->execute();
  1760. $this->assertCount(1, $result);
  1761. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1762. $query = new Query($this->connection);
  1763. $result = $query->select('id')->from('comments')
  1764. ->limit(1)
  1765. ->page(2)
  1766. ->order(['id' => 'asc'])
  1767. ->execute();
  1768. $this->assertCount(1, $result);
  1769. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1770. $query = new Query($this->connection);
  1771. $query->select('id')->from('comments')->page(3, 10);
  1772. $this->assertEquals(10, $query->clause('limit'));
  1773. $this->assertEquals(20, $query->clause('offset'));
  1774. $query = new Query($this->connection);
  1775. $query->select('id')->from('comments')->page(1);
  1776. $this->assertEquals(25, $query->clause('limit'));
  1777. $this->assertEquals(0, $query->clause('offset'));
  1778. $query->select('id')->from('comments')->page(2);
  1779. $this->assertEquals(25, $query->clause('limit'));
  1780. $this->assertEquals(25, $query->clause('offset'));
  1781. }
  1782. /**
  1783. * Tests that Query objects can be included inside the select clause
  1784. * and be used as a normal field, including binding any passed parameter
  1785. *
  1786. * @return void
  1787. */
  1788. public function testSubqueryInSelect()
  1789. {
  1790. $query = new Query($this->connection);
  1791. $subquery = (new Query($this->connection))
  1792. ->select('name')
  1793. ->from(['b' => 'authors'])
  1794. ->where(['b.id = a.id']);
  1795. $result = $query
  1796. ->select(['id', 'name' => $subquery])
  1797. ->from(['a' => 'comments'])->execute();
  1798. $expected = [
  1799. ['id' => 1, 'name' => 'mariano'],
  1800. ['id' => 2, 'name' => 'nate'],
  1801. ['id' => 3, 'name' => 'larry'],
  1802. ['id' => 4, 'name' => 'garrett'],
  1803. ['id' => 5, 'name' => null],
  1804. ['id' => 6, 'name' => null],
  1805. ];
  1806. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1807. $query = new Query($this->connection);
  1808. $subquery = (new Query($this->connection))
  1809. ->select('name')
  1810. ->from(['b' => 'authors'])
  1811. ->where(['name' => 'mariano'], ['name' => 'string']);
  1812. $result = $query
  1813. ->select(['id', 'name' => $subquery])
  1814. ->from(['a' => 'articles'])->execute();
  1815. $expected = [
  1816. ['id' => 1, 'name' => 'mariano'],
  1817. ['id' => 2, 'name' => 'mariano'],
  1818. ['id' => 3, 'name' => 'mariano'],
  1819. ];
  1820. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1821. }
  1822. /**
  1823. * Tests that Query objects can be included inside the from clause
  1824. * and be used as a normal table, including binding any passed parameter
  1825. *
  1826. * @return void
  1827. */
  1828. public function testSuqueryInFrom()
  1829. {
  1830. $query = new Query($this->connection);
  1831. $subquery = (new Query($this->connection))
  1832. ->select(['id', 'comment'])
  1833. ->from('comments')
  1834. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1835. $result = $query
  1836. ->select(['say' => 'comment'])
  1837. ->from(['b' => $subquery])
  1838. ->where(['id !=' => 3])
  1839. ->execute();
  1840. $expected = [
  1841. ['say' => 'Second Comment for First Article'],
  1842. ['say' => 'Fourth Comment for First Article'],
  1843. ['say' => 'First Comment for Second Article'],
  1844. ['say' => 'Second Comment for Second Article'],
  1845. ];
  1846. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1847. }
  1848. /**
  1849. * Tests that Query objects can be included inside the where clause
  1850. * and be used as a normal condition, including binding any passed parameter
  1851. *
  1852. * @return void
  1853. */
  1854. public function testSubqueryInWhere()
  1855. {
  1856. $query = new Query($this->connection);
  1857. $subquery = (new Query($this->connection))
  1858. ->select(['id'])
  1859. ->from('authors')
  1860. ->where(['id' => 1]);
  1861. $result = $query
  1862. ->select(['name'])
  1863. ->from(['authors'])
  1864. ->where(['id !=' => $subquery])
  1865. ->execute();
  1866. $expected = [
  1867. ['name' => 'nate'],
  1868. ['name' => 'larry'],
  1869. ['name' => 'garrett'],
  1870. ];
  1871. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1872. $query = new Query($this->connection);
  1873. $subquery = (new Query($this->connection))
  1874. ->select(['id'])
  1875. ->from('comments')
  1876. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1877. $result = $query
  1878. ->select(['name'])
  1879. ->from(['authors'])
  1880. ->where(['id not in' => $subquery])
  1881. ->execute();
  1882. $expected = [
  1883. ['name' => 'mariano'],
  1884. ];
  1885. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1886. }
  1887. /**
  1888. * Tests that it is possible to use a subquery in a join clause
  1889. *
  1890. * @return void
  1891. */
  1892. public function testSubqueyInJoin()
  1893. {
  1894. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1895. $query = new Query($this->connection);
  1896. $result = $query
  1897. ->select(['title', 'name'])
  1898. ->from('articles')
  1899. ->join(['b' => $subquery])
  1900. ->execute();
  1901. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1902. $subquery->where(['id' => 1]);
  1903. $result = $query->execute();
  1904. $this->assertCount(3, $result);
  1905. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1906. $result = $query->execute();
  1907. $this->assertCount(1, $result);
  1908. }
  1909. /**
  1910. * Tests that it is possible to one or multiple UNION statements in a query
  1911. *
  1912. * @return void
  1913. */
  1914. public function testUnion()
  1915. {
  1916. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1917. $query = new Query($this->connection);
  1918. $result = $query->select(['id', 'comment'])
  1919. ->from(['c' => 'comments'])
  1920. ->union($union)
  1921. ->execute();
  1922. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1923. $rows = $result->fetchAll();
  1924. $union->select(['foo' => 'id', 'bar' => 'title']);
  1925. $union = (new Query($this->connection))
  1926. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1927. ->from(['b' => 'authors'])
  1928. ->where(['id ' => 1])
  1929. ->order(['id' => 'desc']);
  1930. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1931. $result = $query->execute();
  1932. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1933. $this->assertNotEquals($rows, $result->fetchAll());
  1934. $union = (new Query($this->connection))
  1935. ->select(['id', 'title'])
  1936. ->from(['c' => 'articles']);
  1937. $query->select(['id', 'comment'], true)->union($union, true);
  1938. $result = $query->execute();
  1939. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1940. $this->assertEquals($rows, $result->fetchAll());
  1941. }
  1942. /**
  1943. * Tests that it is possible to run unions with order statements
  1944. *
  1945. * @return void
  1946. */
  1947. public function testUnionOrderBy()
  1948. {
  1949. $this->skipIf(
  1950. ($this->connection->driver() instanceof \Cake\Database\Driver\Sqlite ||
  1951. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver),
  1952. 'Driver does not support ORDER BY in UNIONed queries.'
  1953. );
  1954. $union = (new Query($this->connection))
  1955. ->select(['id', 'title'])
  1956. ->from(['a' => 'articles'])
  1957. ->order(['a.id' => 'asc']);
  1958. $query = new Query($this->connection);
  1959. $result = $query->select(['id', 'comment'])
  1960. ->from(['c' => 'comments'])
  1961. ->order(['c.id' => 'asc'])
  1962. ->union($union)
  1963. ->execute();
  1964. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1965. $rows = $result->fetchAll();
  1966. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1967. }
  1968. /**
  1969. * Tests that UNION ALL can be built by setting the second param of union() to true
  1970. *
  1971. * @return void
  1972. */
  1973. public function testUnionAll()
  1974. {
  1975. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1976. $query = new Query($this->connection);
  1977. $result = $query->select(['id', 'comment'])
  1978. ->from(['c' => 'comments'])
  1979. ->union($union)
  1980. ->execute();
  1981. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1982. $rows = $result->fetchAll();
  1983. $union->select(['foo' => 'id', 'bar' => 'title']);
  1984. $union = (new Query($this->connection))
  1985. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1986. ->from(['b' => 'authors'])
  1987. ->where(['id ' => 1])
  1988. ->order(['id' => 'desc']);
  1989. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1990. $result = $query->execute();
  1991. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1992. $this->assertNotEquals($rows, $result->fetchAll());
  1993. }
  1994. /**
  1995. * Tests stacking decorators for results and resetting the list of decorators
  1996. *
  1997. * @return void
  1998. */
  1999. public function testDecorateResults()
  2000. {
  2001. $query = new Query($this->connection);
  2002. $result = $query
  2003. ->select(['id', 'title'])
  2004. ->from('articles')
  2005. ->order(['id' => 'ASC'])
  2006. ->decorateResults(function ($row) {
  2007. $row['modified_id'] = $row['id'] + 1;
  2008. return $row;
  2009. })
  2010. ->execute();
  2011. while ($row = $result->fetch('assoc')) {
  2012. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  2013. }
  2014. $result = $query->decorateResults(function ($row) {
  2015. $row['modified_id']--;
  2016. return $row;
  2017. })->execute();
  2018. while ($row = $result->fetch('assoc')) {
  2019. $this->assertEquals($row['id'], $row['modified_id']);
  2020. }
  2021. $result = $query
  2022. ->decorateResults(function ($row) {
  2023. $row['foo'] = 'bar';
  2024. return $row;
  2025. }, true)
  2026. ->execute();
  2027. while ($row = $result->fetch('assoc')) {
  2028. $this->assertEquals('bar', $row['foo']);
  2029. $this->assertArrayNotHasKey('modified_id', $row);
  2030. }
  2031. $results = $query->decorateResults(null, true)->execute();
  2032. while ($row = $result->fetch('assoc')) {
  2033. $this->assertArrayNotHasKey('foo', $row);
  2034. $this->assertArrayNotHasKey('modified_id', $row);
  2035. }
  2036. }
  2037. /**
  2038. * Test a basic delete using from()
  2039. *
  2040. * @return void
  2041. */
  2042. public function testDeleteWithFrom()
  2043. {
  2044. $query = new Query($this->connection);
  2045. $query->delete()
  2046. ->from('authors')
  2047. ->where('1 = 1');
  2048. $result = $query->sql();
  2049. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2050. $result = $query->execute();
  2051. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2052. $this->assertCount(self::AUTHOR_COUNT, $result);
  2053. }
  2054. /**
  2055. * Test delete with from and alias.
  2056. *
  2057. * @return void
  2058. */
  2059. public function testDeleteWithAliasedFrom()
  2060. {
  2061. $query = new Query($this->connection);
  2062. $query->delete()
  2063. ->from(['a ' => 'authors'])
  2064. ->where(['a.id !=' => 99]);
  2065. $result = $query->sql();
  2066. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, !$this->autoQuote);
  2067. $result = $query->execute();
  2068. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2069. $this->assertCount(self::AUTHOR_COUNT, $result);
  2070. }
  2071. /**
  2072. * Test a basic delete with no from() call.
  2073. *
  2074. * @return void
  2075. */
  2076. public function testDeleteNoFrom()
  2077. {
  2078. $query = new Query($this->connection);
  2079. $query->delete('authors')
  2080. ->where('1 = 1');
  2081. $result = $query->sql();
  2082. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2083. $result = $query->execute();
  2084. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2085. $this->assertCount(self::AUTHOR_COUNT, $result);
  2086. }
  2087. /**
  2088. * Test setting select() & delete() modes.
  2089. *
  2090. * @return void
  2091. */
  2092. public function testSelectAndDeleteOnSameQuery()
  2093. {
  2094. $query = new Query($this->connection);
  2095. $result = $query->select()
  2096. ->delete('authors')
  2097. ->where('1 = 1');
  2098. $result = $query->sql();
  2099. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2100. $this->assertContains(' WHERE 1 = 1', $result);
  2101. }
  2102. /**
  2103. * Test a simple update.
  2104. *
  2105. * @return void
  2106. */
  2107. public function testUpdateSimple()
  2108. {
  2109. $query = new Query($this->connection);
  2110. $query->update('authors')
  2111. ->set('name', 'mark')
  2112. ->where(['id' => 1]);
  2113. $result = $query->sql();
  2114. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, !$this->autoQuote);
  2115. $result = $query->execute();
  2116. $this->assertCount(1, $result);
  2117. }
  2118. /**
  2119. * Test update with multiple fields.
  2120. *
  2121. * @return void
  2122. */
  2123. public function testUpdateMultipleFields()
  2124. {
  2125. $query = new Query($this->connection);
  2126. $query->update('articles')
  2127. ->set('title', 'mark', 'string')
  2128. ->set('body', 'some text', 'string')
  2129. ->where(['id' => 1]);
  2130. $result = $query->sql();
  2131. $this->assertQuotedQuery(
  2132. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2133. $result,
  2134. !$this->autoQuote
  2135. );
  2136. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2137. $result = $query->execute();
  2138. $this->assertCount(1, $result);
  2139. }
  2140. /**
  2141. * Test updating multiple fields with an array.
  2142. *
  2143. * @return void
  2144. */
  2145. public function testUpdateMultipleFieldsArray()
  2146. {
  2147. $query = new Query($this->connection);
  2148. $query->update('articles')
  2149. ->set([
  2150. 'title' => 'mark',
  2151. 'body' => 'some text'
  2152. ], ['title' => 'string', 'body' => 'string'])
  2153. ->where(['id' => 1]);
  2154. $result = $query->sql();
  2155. $this->assertQuotedQuery(
  2156. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2157. $result,
  2158. !$this->autoQuote
  2159. );
  2160. $this->assertQuotedQuery('WHERE <id> = :', $result, !$this->autoQuote);
  2161. $result = $query->execute();
  2162. $this->assertCount(1, $result);
  2163. }
  2164. /**
  2165. * Test updates with an expression.
  2166. *
  2167. * @return void
  2168. */
  2169. public function testUpdateWithExpression()
  2170. {
  2171. $query = new Query($this->connection);
  2172. $expr = $query->newExpr('title = author_id');
  2173. $query->update('articles')
  2174. ->set($expr)
  2175. ->where(['id' => 1]);
  2176. $result = $query->sql();
  2177. $this->assertQuotedQuery(
  2178. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  2179. $result,
  2180. !$this->autoQuote
  2181. );
  2182. $result = $query->execute();
  2183. $this->assertCount(1, $result);
  2184. }
  2185. /**
  2186. * Test update with array fields and types.
  2187. *
  2188. * @return void
  2189. */
  2190. public function testUpdateArrayFields()
  2191. {
  2192. $query = new Query($this->connection);
  2193. $date = new \DateTime;
  2194. $query->update('comments')
  2195. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  2196. ->where(['id' => 1]);
  2197. $result = $query->sql();
  2198. $this->assertQuotedQuery(
  2199. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2200. $result,
  2201. !$this->autoQuote
  2202. );
  2203. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2204. $result = $query->execute();
  2205. $this->assertCount(1, $result);
  2206. $query = new Query($this->connection);
  2207. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  2208. $result = $result->fetchAll('assoc')[0]['created'];
  2209. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  2210. }
  2211. /**
  2212. * You cannot call values() before insert() it causes all sorts of pain.
  2213. *
  2214. * @expectedException \Cake\Database\Exception
  2215. * @return void
  2216. */
  2217. public function testInsertValuesBeforeInsertFailure()
  2218. {
  2219. $query = new Query($this->connection);
  2220. $query->select('*')->values([
  2221. 'id' => 1,
  2222. 'title' => 'mark',
  2223. 'body' => 'test insert'
  2224. ]);
  2225. }
  2226. /**
  2227. * Inserting nothing should not generate an error.
  2228. *
  2229. * @expectedException \RuntimeException
  2230. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  2231. * @return void
  2232. */
  2233. public function testInsertNothing()
  2234. {
  2235. $query = new Query($this->connection);
  2236. $query->insert([]);
  2237. }
  2238. /**
  2239. * Test inserting a single row.
  2240. *
  2241. * @return void
  2242. */
  2243. public function testInsertSimple()
  2244. {
  2245. $query = new Query($this->connection);
  2246. $query->insert(['title', 'body'])
  2247. ->into('articles')
  2248. ->values([
  2249. 'title' => 'mark',
  2250. 'body' => 'test insert'
  2251. ]);
  2252. $result = $query->sql();
  2253. $this->assertQuotedQuery(
  2254. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2255. 'VALUES \(:c0, :c1\)',
  2256. $result,
  2257. !$this->autoQuote
  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, '1 row should be inserted');
  2264. }
  2265. $expected = [
  2266. [
  2267. 'id' => 4,
  2268. 'author_id' => null,
  2269. 'title' => 'mark',
  2270. 'body' => 'test insert',
  2271. 'published' => 'N',
  2272. ]
  2273. ];
  2274. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2275. }
  2276. /**
  2277. * Test an insert when not all the listed fields are provided.
  2278. * Columns should be matched up where possible.
  2279. *
  2280. * @return void
  2281. */
  2282. public function testInsertSparseRow()
  2283. {
  2284. $query = new Query($this->connection);
  2285. $query->insert(['title', 'body'])
  2286. ->into('articles')
  2287. ->values([
  2288. 'title' => 'mark',
  2289. ]);
  2290. $result = $query->sql();
  2291. $this->assertQuotedQuery(
  2292. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2293. 'VALUES \(:c0, :c1\)',
  2294. $result,
  2295. !$this->autoQuote
  2296. );
  2297. $result = $query->execute();
  2298. $result->closeCursor();
  2299. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2300. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2301. $this->assertCount(1, $result, '1 row should be inserted');
  2302. }
  2303. $expected = [
  2304. [
  2305. 'id' => 4,
  2306. 'author_id' => null,
  2307. 'title' => 'mark',
  2308. 'body' => null,
  2309. 'published' => 'N',
  2310. ]
  2311. ];
  2312. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  2313. }
  2314. /**
  2315. * Test inserting multiple rows with sparse data.
  2316. *
  2317. * @return void
  2318. */
  2319. public function testInsertMultipleRowsSparse()
  2320. {
  2321. $query = new Query($this->connection);
  2322. $query->insert(['title', 'body'])
  2323. ->into('articles')
  2324. ->values([
  2325. 'body' => 'test insert'
  2326. ])
  2327. ->values([
  2328. 'title' => 'jose',
  2329. ]);
  2330. $result = $query->execute();
  2331. $result->closeCursor();
  2332. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2333. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2334. $this->assertCount(2, $result, '2 rows should be inserted');
  2335. }
  2336. $expected = [
  2337. [
  2338. 'id' => 4,
  2339. 'author_id' => null,
  2340. 'title' => null,
  2341. 'body' => 'test insert',
  2342. 'published' => 'N',
  2343. ],
  2344. [
  2345. 'id' => 5,
  2346. 'author_id' => null,
  2347. 'title' => 'jose',
  2348. 'body' => null,
  2349. 'published' => 'N',
  2350. ],
  2351. ];
  2352. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2353. }
  2354. /**
  2355. * Test that INSERT INTO ... SELECT works.
  2356. *
  2357. * @return void
  2358. */
  2359. public function testInsertFromSelect()
  2360. {
  2361. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2362. ->from('authors')
  2363. ->where(['id' => 1]);
  2364. $query = new Query($this->connection);
  2365. $query->insert(
  2366. ['title', 'body', 'author_id'],
  2367. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2368. )
  2369. ->into('articles')
  2370. ->values($select);
  2371. $result = $query->sql();
  2372. $this->assertQuotedQuery(
  2373. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
  2374. $result,
  2375. !$this->autoQuote
  2376. );
  2377. $this->assertQuotedQuery(
  2378. 'SELECT <name>, \'some text\', 99 FROM <authors>',
  2379. $result,
  2380. !$this->autoQuote
  2381. );
  2382. $result = $query->execute();
  2383. $result->closeCursor();
  2384. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2385. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2386. $this->assertCount(1, $result);
  2387. }
  2388. $result = (new Query($this->connection))->select('*')
  2389. ->from('articles')
  2390. ->where(['author_id' => 99])
  2391. ->execute();
  2392. $this->assertCount(1, $result);
  2393. $expected = [
  2394. 'id' => 4,
  2395. 'title' => 'mariano',
  2396. 'body' => 'some text',
  2397. 'author_id' => 99,
  2398. 'published' => 'N',
  2399. ];
  2400. $this->assertEquals($expected, $result->fetch('assoc'));
  2401. }
  2402. /**
  2403. * Test that an exception is raised when mixing query + array types.
  2404. *
  2405. * @expectedException \Cake\Database\Exception
  2406. */
  2407. public function testInsertFailureMixingTypesArrayFirst()
  2408. {
  2409. $query = new Query($this->connection);
  2410. $query->insert(['name'])
  2411. ->into('articles')
  2412. ->values(['name' => 'mark'])
  2413. ->values(new Query($this->connection));
  2414. }
  2415. /**
  2416. * Test that an exception is raised when mixing query + array types.
  2417. *
  2418. * @expectedException \Cake\Database\Exception
  2419. */
  2420. public function testInsertFailureMixingTypesQueryFirst()
  2421. {
  2422. $query = new Query($this->connection);
  2423. $query->insert(['name'])
  2424. ->into('articles')
  2425. ->values(new Query($this->connection))
  2426. ->values(['name' => 'mark']);
  2427. }
  2428. /**
  2429. * Test that insert can use expression objects as values.
  2430. *
  2431. * @return void
  2432. */
  2433. public function testInsertExpressionValues()
  2434. {
  2435. $query = new Query($this->connection);
  2436. $query->insert(['title', 'author_id'])
  2437. ->into('articles')
  2438. ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
  2439. $result = $query->execute();
  2440. $result->closeCursor();
  2441. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2442. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2443. $this->assertCount(1, $result);
  2444. }
  2445. $result = (new Query($this->connection))->select('*')
  2446. ->from('articles')
  2447. ->where(['author_id' => 99])
  2448. ->execute();
  2449. $this->assertCount(1, $result);
  2450. $expected = [
  2451. 'id' => 4,
  2452. 'title' => 'jose',
  2453. 'body' => null,
  2454. 'author_id' => '99',
  2455. 'published' => 'N',
  2456. ];
  2457. $this->assertEquals($expected, $result->fetch('assoc'));
  2458. $subquery = new Query($this->connection);
  2459. $subquery->select(['name'])
  2460. ->from('authors')
  2461. ->where(['id' => 1]);
  2462. $query = new Query($this->connection);
  2463. $query->insert(['title', 'author_id'])
  2464. ->into('articles')
  2465. ->values(['title' => $subquery, 'author_id' => 100]);
  2466. $result = $query->execute();
  2467. $result->closeCursor();
  2468. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2469. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2470. $this->assertCount(1, $result);
  2471. }
  2472. $result = (new Query($this->connection))->select('*')
  2473. ->from('articles')
  2474. ->where(['author_id' => 100])
  2475. ->execute();
  2476. $this->assertCount(1, $result);
  2477. $expected = [
  2478. 'id' => 5,
  2479. 'title' => 'mariano',
  2480. 'body' => null,
  2481. 'author_id' => '100',
  2482. 'published' => 'N',
  2483. ];
  2484. $this->assertEquals($expected, $result->fetch('assoc'));
  2485. }
  2486. /**
  2487. * Tests that functions are correctly transformed and their parameters are bound
  2488. *
  2489. * @group FunctionExpression
  2490. * @return void
  2491. */
  2492. public function testSQLFunctions()
  2493. {
  2494. $query = new Query($this->connection);
  2495. $result = $query->select(
  2496. function ($q) {
  2497. return ['total' => $q->func()->count('*')];
  2498. }
  2499. )
  2500. ->from('articles')
  2501. ->execute();
  2502. $expected = [['total' => 3]];
  2503. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2504. $query = new Query($this->connection);
  2505. $result = $query->select([
  2506. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  2507. ])
  2508. ->from('articles')
  2509. ->order(['c' => 'ASC'])
  2510. ->execute();
  2511. $expected = [
  2512. ['c' => 'First Article is appended'],
  2513. ['c' => 'Second Article is appended'],
  2514. ['c' => 'Third Article is appended']
  2515. ];
  2516. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2517. $query = new Query($this->connection);
  2518. $result = $query
  2519. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2520. ->execute()
  2521. ->fetchAll('assoc');
  2522. $this->assertEquals(3, abs($result[0]['d']));
  2523. $query = new Query($this->connection);
  2524. $result = $query
  2525. ->select(['d' => $query->func()->now('date')])
  2526. ->execute();
  2527. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2528. $query = new Query($this->connection);
  2529. $result = $query
  2530. ->select(['d' => $query->func()->now('time')])
  2531. ->execute();
  2532. $this->assertWithinRange(
  2533. date('U'),
  2534. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2535. 1
  2536. );
  2537. $query = new Query($this->connection);
  2538. $result = $query
  2539. ->select(['d' => $query->func()->now()])
  2540. ->execute();
  2541. $this->assertWithinRange(
  2542. date('U'),
  2543. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2544. 1
  2545. );
  2546. $query = new Query($this->connection);
  2547. $result = $query
  2548. ->select([
  2549. 'd' => $query->func()->datePart('day', 'created'),
  2550. 'm' => $query->func()->datePart('month', 'created'),
  2551. 'y' => $query->func()->datePart('year', 'created'),
  2552. 'de' => $query->func()->extract('day', 'created'),
  2553. 'me' => $query->func()->extract('month', 'created'),
  2554. 'ye' => $query->func()->extract('year', 'created'),
  2555. 'wd' => $query->func()->weekday('created'),
  2556. 'dow' => $query->func()->dayOfWeek('created'),
  2557. 'addDays' => $query->func()->dateAdd('created', 2, 'day'),
  2558. 'substractYears' => $query->func()->dateAdd('created', -2, 'year')
  2559. ])
  2560. ->from('comments')
  2561. ->where(['created' => '2007-03-18 10:45:23'])
  2562. ->execute()
  2563. ->fetchAll('assoc');
  2564. $result[0]['m'] = ltrim($result[0]['m'], '0');
  2565. $result[0]['me'] = ltrim($result[0]['me'], '0');
  2566. $result[0]['addDays'] = substr($result[0]['addDays'], 0, 10);
  2567. $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 10);
  2568. $expected = [
  2569. 'd' => '18',
  2570. 'm' => '3',
  2571. 'y' => '2007',
  2572. 'de' => '18',
  2573. 'me' => '3',
  2574. 'ye' => '2007',
  2575. 'wd' => '1', // Sunday
  2576. 'dow' => '1',
  2577. 'addDays' => '2007-03-20',
  2578. 'substractYears' => '2005-03-18'
  2579. ];
  2580. $this->assertEquals($expected, $result[0]);
  2581. }
  2582. /**
  2583. * Tests that default types are passed to functions accepting a $types param
  2584. *
  2585. * @return void
  2586. */
  2587. public function testDefaultTypes()
  2588. {
  2589. $query = new Query($this->connection);
  2590. $this->assertEquals([], $query->defaultTypes());
  2591. $types = ['id' => 'integer', 'created' => 'datetime'];
  2592. $this->assertSame($query, $query->defaultTypes($types));
  2593. $this->assertSame($types, $query->defaultTypes());
  2594. $results = $query->select(['id', 'comment'])
  2595. ->from('comments')
  2596. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2597. ->execute();
  2598. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2599. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2600. // Now test default can be overridden
  2601. $types = ['created' => 'date'];
  2602. $results = $query
  2603. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2604. ->execute();
  2605. $this->assertCount(6, $results, 'All 6 rows should match.');
  2606. }
  2607. /**
  2608. * Tests parameter binding
  2609. *
  2610. * @return void
  2611. */
  2612. public function testBind()
  2613. {
  2614. $query = new Query($this->connection);
  2615. $results = $query->select(['id', 'comment'])
  2616. ->from('comments')
  2617. ->where(['created BETWEEN :foo AND :bar'])
  2618. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2619. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2620. ->execute();
  2621. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2622. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2623. $query = new Query($this->connection);
  2624. $results = $query->select(['id', 'comment'])
  2625. ->from('comments')
  2626. ->where(['created BETWEEN :foo AND :bar'])
  2627. ->bind(':foo', '2007-03-18 10:50:00')
  2628. ->bind(':bar', '2007-03-18 10:52:00')
  2629. ->execute();
  2630. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2631. }
  2632. /**
  2633. * Test that epilog() will actually append a string to a select query
  2634. *
  2635. * @return void
  2636. */
  2637. public function testAppendSelect()
  2638. {
  2639. $query = new Query($this->connection);
  2640. $sql = $query
  2641. ->select(['id', 'title'])
  2642. ->from('articles')
  2643. ->where(['id' => 1])
  2644. ->epilog('FOR UPDATE')
  2645. ->sql();
  2646. $this->assertContains('SELECT', $sql);
  2647. $this->assertContains('FROM', $sql);
  2648. $this->assertContains('WHERE', $sql);
  2649. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2650. }
  2651. /**
  2652. * Test that epilog() will actually append a string to an insert query
  2653. *
  2654. * @return void
  2655. */
  2656. public function testAppendInsert()
  2657. {
  2658. $query = new Query($this->connection);
  2659. $sql = $query
  2660. ->insert(['id', 'title'])
  2661. ->into('articles')
  2662. ->values([1, 'a title'])
  2663. ->epilog('RETURNING id')
  2664. ->sql();
  2665. $this->assertContains('INSERT', $sql);
  2666. $this->assertContains('INTO', $sql);
  2667. $this->assertContains('VALUES', $sql);
  2668. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2669. }
  2670. /**
  2671. * Test that epilog() will actually append a string to an update query
  2672. *
  2673. * @return void
  2674. */
  2675. public function testAppendUpdate()
  2676. {
  2677. $query = new Query($this->connection);
  2678. $sql = $query
  2679. ->update('articles')
  2680. ->set(['title' => 'foo'])
  2681. ->where(['id' => 1])
  2682. ->epilog('RETURNING id')
  2683. ->sql();
  2684. $this->assertContains('UPDATE', $sql);
  2685. $this->assertContains('SET', $sql);
  2686. $this->assertContains('WHERE', $sql);
  2687. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2688. }
  2689. /**
  2690. * Test that epilog() will actually append a string to a delete query
  2691. *
  2692. * @return void
  2693. */
  2694. public function testAppendDelete()
  2695. {
  2696. $query = new Query($this->connection);
  2697. $sql = $query
  2698. ->delete('articles')
  2699. ->where(['id' => 1])
  2700. ->epilog('RETURNING id')
  2701. ->sql();
  2702. $this->assertContains('DELETE FROM', $sql);
  2703. $this->assertContains('WHERE', $sql);
  2704. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2705. }
  2706. /**
  2707. * Tests automatic identifier quoting in the select clause
  2708. *
  2709. * @return void
  2710. */
  2711. public function testQuotingSelectFieldsAndAlias()
  2712. {
  2713. $this->connection->driver()->autoQuoting(true);
  2714. $query = new Query($this->connection);
  2715. $sql = $query->select(['something'])->sql();
  2716. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2717. $query = new Query($this->connection);
  2718. $sql = $query->select(['foo' => 'something'])->sql();
  2719. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2720. $query = new Query($this->connection);
  2721. $sql = $query->select(['foo' => 1])->sql();
  2722. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2723. $query = new Query($this->connection);
  2724. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2725. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2726. $query = new Query($this->connection);
  2727. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2728. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2729. $query = new Query($this->connection);
  2730. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2731. $this->assertQuotedQuery('<bar>', $sql);
  2732. }
  2733. /**
  2734. * Tests automatic identifier quoting in the from clause
  2735. *
  2736. * @return void
  2737. */
  2738. public function testQuotingFromAndAlias()
  2739. {
  2740. $this->connection->driver()->autoQuoting(true);
  2741. $query = new Query($this->connection);
  2742. $sql = $query->select('*')->from(['something'])->sql();
  2743. $this->assertQuotedQuery('FROM <something>', $sql);
  2744. $query = new Query($this->connection);
  2745. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2746. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  2747. $query = new Query($this->connection);
  2748. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2749. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  2750. }
  2751. /**
  2752. * Tests automatic identifier quoting for DISTINCT ON
  2753. *
  2754. * @return void
  2755. */
  2756. public function testQuotingDistinctOn()
  2757. {
  2758. $this->connection->driver()->autoQuoting(true);
  2759. $query = new Query($this->connection);
  2760. $sql = $query->select('*')->distinct(['something'])->sql();
  2761. $this->assertQuotedQuery('<something>', $sql);
  2762. }
  2763. /**
  2764. * Tests automatic identifier quoting in the join clause
  2765. *
  2766. * @return void
  2767. */
  2768. public function testQuotingJoinsAndAlias()
  2769. {
  2770. $this->connection->driver()->autoQuoting(true);
  2771. $query = new Query($this->connection);
  2772. $sql = $query->select('*')->join(['something'])->sql();
  2773. $this->assertQuotedQuery('JOIN <something>', $sql);
  2774. $query = new Query($this->connection);
  2775. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2776. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2777. $query = new Query($this->connection);
  2778. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2779. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2780. }
  2781. /**
  2782. * Tests automatic identifier quoting in the group by clause
  2783. *
  2784. * @return void
  2785. */
  2786. public function testQuotingGroupBy()
  2787. {
  2788. $this->connection->driver()->autoQuoting(true);
  2789. $query = new Query($this->connection);
  2790. $sql = $query->select('*')->group(['something'])->sql();
  2791. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2792. $query = new Query($this->connection);
  2793. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2794. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2795. $query = new Query($this->connection);
  2796. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2797. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2798. }
  2799. /**
  2800. * Tests automatic identifier quoting strings inside conditions expressions
  2801. *
  2802. * @return void
  2803. */
  2804. public function testQuotingExpressions()
  2805. {
  2806. $this->connection->driver()->autoQuoting(true);
  2807. $query = new Query($this->connection);
  2808. $sql = $query->select('*')
  2809. ->where(['something' => 'value'])
  2810. ->sql();
  2811. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2812. $query = new Query($this->connection);
  2813. $sql = $query->select('*')
  2814. ->where([
  2815. 'something' => 'value',
  2816. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2817. ])
  2818. ->sql();
  2819. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2820. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2821. }
  2822. /**
  2823. * Tests that insert query parts get quoted automatically
  2824. *
  2825. * @return void
  2826. */
  2827. public function testQuotingInsert()
  2828. {
  2829. $this->connection->driver()->autoQuoting(true);
  2830. $query = new Query($this->connection);
  2831. $sql = $query->insert(['bar', 'baz'])
  2832. ->into('foo')
  2833. ->where(['something' => 'value'])
  2834. ->sql();
  2835. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2836. $query = new Query($this->connection);
  2837. $sql = $query->insert([$query->newExpr('bar')])
  2838. ->into('foo')
  2839. ->where(['something' => 'value'])
  2840. ->sql();
  2841. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2842. }
  2843. /**
  2844. * Tests converting a query to a string
  2845. *
  2846. * @return void
  2847. */
  2848. public function testToString()
  2849. {
  2850. $query = new Query($this->connection);
  2851. $query
  2852. ->select(['title'])
  2853. ->from('articles');
  2854. $result = (string)$query;
  2855. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, !$this->autoQuote);
  2856. }
  2857. /**
  2858. * Tests __debugInfo
  2859. *
  2860. * @return void
  2861. */
  2862. public function testDebugInfo()
  2863. {
  2864. $query = (new Query($this->connection))->select('*')
  2865. ->from('articles')
  2866. ->defaultTypes(['id' => 'integer'])
  2867. ->where(['id' => '1']);
  2868. $expected = [
  2869. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2870. 'sql' => $query->sql(),
  2871. 'params' => [
  2872. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2873. ],
  2874. 'defaultTypes' => ['id' => 'integer'],
  2875. 'decorators' => 0,
  2876. 'executed' => false
  2877. ];
  2878. $result = $query->__debugInfo();
  2879. $this->assertEquals($expected, $result);
  2880. $query->execute();
  2881. $expected = [
  2882. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2883. 'sql' => $query->sql(),
  2884. 'params' => [
  2885. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2886. ],
  2887. 'defaultTypes' => ['id' => 'integer'],
  2888. 'decorators' => 0,
  2889. 'executed' => true
  2890. ];
  2891. $result = $query->__debugInfo();
  2892. $this->assertEquals($expected, $result);
  2893. }
  2894. /**
  2895. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2896. *
  2897. * @return void
  2898. */
  2899. public function testIsNullWithExpressions()
  2900. {
  2901. $query = new Query($this->connection);
  2902. $subquery = (new Query($this->connection))
  2903. ->select(['id'])
  2904. ->from('authors')
  2905. ->where(['id' => 1]);
  2906. $result = $query
  2907. ->select(['name'])
  2908. ->from(['authors'])
  2909. ->where(function ($exp) use ($subquery) {
  2910. return $exp->isNotNull($subquery);
  2911. })
  2912. ->execute();
  2913. $this->assertNotEmpty($result->fetchAll('assoc'));
  2914. $result = (new Query($this->connection))
  2915. ->select(['name'])
  2916. ->from(['authors'])
  2917. ->where(function ($exp) use ($subquery) {
  2918. return $exp->isNull($subquery);
  2919. })
  2920. ->execute();
  2921. $this->assertEmpty($result->fetchAll('assoc'));
  2922. }
  2923. /**
  2924. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2925. * when using autoQuoting
  2926. *
  2927. * @return void
  2928. */
  2929. public function testIsNullAutoQuoting()
  2930. {
  2931. $this->connection->driver()->autoQuoting(true);
  2932. $query = new Query($this->connection);
  2933. $query->select('*')->from('things')->where(function ($exp) {
  2934. return $exp->isNull('field');
  2935. });
  2936. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2937. $query = new Query($this->connection);
  2938. $query->select('*')->from('things')->where(function ($exp) {
  2939. return $exp->isNotNull('field');
  2940. });
  2941. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2942. }
  2943. /**
  2944. * Tests that using the IS operator will automatically translate to the best
  2945. * possible operator depending on the passed value
  2946. *
  2947. * @return void
  2948. */
  2949. public function testDirectIsNull()
  2950. {
  2951. $sql = (new Query($this->connection))
  2952. ->select(['name'])
  2953. ->from(['authors'])
  2954. ->where(['name IS' => null])
  2955. ->sql();
  2956. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, !$this->autoQuote);
  2957. $results = (new Query($this->connection))
  2958. ->select(['name'])
  2959. ->from(['authors'])
  2960. ->where(['name IS' => 'larry'])
  2961. ->execute();
  2962. $this->assertCount(1, $results);
  2963. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  2964. }
  2965. /**
  2966. * Tests that using the IS NOT operator will automatically translate to the best
  2967. * possible operator depending on the passed value
  2968. *
  2969. * @return void
  2970. */
  2971. public function testDirectIsNotNull()
  2972. {
  2973. $sql = (new Query($this->connection))
  2974. ->select(['name'])
  2975. ->from(['authors'])
  2976. ->where(['name IS NOT' => null])
  2977. ->sql();
  2978. $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, !$this->autoQuote);
  2979. $results = (new Query($this->connection))
  2980. ->select(['name'])
  2981. ->from(['authors'])
  2982. ->where(['name IS NOT' => 'larry'])
  2983. ->execute();
  2984. $this->assertCount(3, $results);
  2985. $this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
  2986. }
  2987. /**
  2988. * Tests that case statements work correctly for various use-cases.
  2989. *
  2990. * @return void
  2991. */
  2992. public function testSqlCaseStatement()
  2993. {
  2994. $query = new Query($this->connection);
  2995. $publishedCase = $query
  2996. ->newExpr()
  2997. ->addCase(
  2998. $query
  2999. ->newExpr()
  3000. ->add(['published' => 'Y']),
  3001. 1,
  3002. 'integer'
  3003. );
  3004. $notPublishedCase = $query
  3005. ->newExpr()
  3006. ->addCase(
  3007. $query
  3008. ->newExpr()
  3009. ->add(['published' => 'N']),
  3010. 1,
  3011. 'integer'
  3012. );
  3013. //Postgres requires the case statement to be cast to a integer
  3014. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  3015. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  3016. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  3017. }
  3018. $results = $query
  3019. ->select([
  3020. 'published' => $query->func()->sum($publishedCase),
  3021. 'not_published' => $query->func()->sum($notPublishedCase)
  3022. ])
  3023. ->from(['comments'])
  3024. ->execute()
  3025. ->fetchAll('assoc');
  3026. $this->assertEquals(5, $results[0]['published']);
  3027. $this->assertEquals(1, $results[0]['not_published']);
  3028. $query = new Query($this->connection);
  3029. $query
  3030. ->insert(['article_id', 'user_id', 'comment', 'published'])
  3031. ->into('comments')
  3032. ->values([
  3033. 'article_id' => 2,
  3034. 'user_id' => 1,
  3035. 'comment' => 'In limbo',
  3036. 'published' => 'L'
  3037. ])
  3038. ->execute()
  3039. ->closeCursor();
  3040. $query = new Query($this->connection);
  3041. $conditions = [
  3042. $query
  3043. ->newExpr()
  3044. ->add(['published' => 'Y']),
  3045. $query
  3046. ->newExpr()
  3047. ->add(['published' => 'N'])
  3048. ];
  3049. $values = [
  3050. 'Published',
  3051. 'Not published',
  3052. 'None'
  3053. ];
  3054. $results = $query
  3055. ->select([
  3056. 'id',
  3057. 'comment',
  3058. 'status' => $query->newExpr()->addCase($conditions, $values)
  3059. ])
  3060. ->from(['comments'])
  3061. ->execute()
  3062. ->fetchAll('assoc');
  3063. $this->assertEquals('Published', $results[2]['status']);
  3064. $this->assertEquals('Not published', $results[3]['status']);
  3065. $this->assertEquals('None', $results[6]['status']);
  3066. }
  3067. /**
  3068. * Shows that bufferResults(false) will prevent client-side results buffering
  3069. *
  3070. * @return void
  3071. */
  3072. public function testUnbufferedQuery()
  3073. {
  3074. $query = new Query($this->connection);
  3075. $result = $query->select(['body', 'author_id'])
  3076. ->from('articles')
  3077. ->bufferResults(false)
  3078. ->execute();
  3079. if (!method_exists($result, 'bufferResults')) {
  3080. $result->closeCursor();
  3081. $this->skipIf(true, 'This driver does not support unbuffered queries');
  3082. }
  3083. $this->assertCount(0, $result);
  3084. $list = $result->fetchAll('assoc');
  3085. $this->assertCount(3, $list);
  3086. $result->closeCursor();
  3087. $query = new Query($this->connection);
  3088. $result = $query->select(['body', 'author_id'])
  3089. ->from('articles')
  3090. ->execute();
  3091. $this->assertCount(3, $result);
  3092. $list = $result->fetchAll('assoc');
  3093. $this->assertCount(3, $list);
  3094. $result->closeCursor();
  3095. }
  3096. /**
  3097. * Assertion for comparing a table's contents with what is in it.
  3098. *
  3099. * @param string $table
  3100. * @param int $count
  3101. * @param array $rows
  3102. * @param array $conditions
  3103. * @return void
  3104. */
  3105. public function assertTable($table, $count, $rows, $conditions = [])
  3106. {
  3107. $result = (new Query($this->connection))->select('*')
  3108. ->from($table)
  3109. ->where($conditions)
  3110. ->execute();
  3111. $this->assertCount($count, $result, 'Row count is incorrect');
  3112. $this->assertEquals($rows, $result->fetchAll('assoc'));
  3113. }
  3114. /**
  3115. * Assertion for comparing a regex pattern against a query having its identifiers
  3116. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  3117. * parameter is set to true, it will alter the pattern to both accept quoted and
  3118. * unquoted queries
  3119. *
  3120. * @param string $pattern
  3121. * @param string $query the result to compare against
  3122. * @param bool $optional
  3123. * @return void
  3124. */
  3125. public function assertQuotedQuery($pattern, $query, $optional = false)
  3126. {
  3127. if ($optional) {
  3128. $optional = '?';
  3129. }
  3130. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  3131. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  3132. $this->assertRegExp('#' . $pattern . '#', $query);
  3133. }
  3134. }