QueryTest.php 124 KB

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