QueryTest.php 157 KB

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