QueryTest.php 148 KB

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