QueryTest.php 154 KB

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