QueryTest.php 145 KB

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