QueryTest.php 149 KB

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