QueryTest.php 173 KB

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