QueryTest.php 165 KB

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