QueryTest.php 157 KB

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