QueryTest.php 173 KB

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