QueryTest.php 163 KB

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