QueryTest.php 159 KB

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