QueryTest.php 151 KB

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