QueryTest.php 160 KB

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