QueryTest.php 119 KB

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