QueryTest.php 147 KB

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