QueryTest.php 181 KB

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