QueryTest.php 158 KB

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