QueryTest.php 144 KB

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