QueryTest.php 121 KB

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