QueryTest.php 156 KB

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