QueryTest.php 173 KB

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