QueryTest.php 154 KB

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