QueryTest.php 119 KB

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