QueryTest.php 158 KB

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