QueryTest.php 120 KB

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