QueryTest.php 165 KB

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