QueryTest.php 170 KB

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