QueryTest.php 168 KB

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