QueryTest.php 173 KB

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