QueryTest.php 176 KB

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