QueryTest.php 163 KB

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