QueryTest.php 181 KB

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