QueryTest.php 156 KB

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