QueryTest.php 153 KB

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