QueryTest.php 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118
  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\TypeMap;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\TestSuite\TestCase;
  22. /**
  23. * Tests Query class
  24. *
  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' => 'float']
  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');
  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 where() with callable types.
  1274. *
  1275. * @return void
  1276. */
  1277. public function testWhereCallables()
  1278. {
  1279. $query = new Query($this->connection);
  1280. $query->select(['id'])
  1281. ->from('articles')
  1282. ->where([
  1283. 'id' => '\Cake\Error\Debugger::dump',
  1284. 'title' => ['\Cake\Error\Debugger', 'dump'],
  1285. 'author_id' => function ($exp) {
  1286. return 1;
  1287. }
  1288. ]);
  1289. $this->assertQuotedQuery(
  1290. 'SELECT <id> FROM <articles> WHERE \(<id> = :c0 AND <title> = :c1 AND <author_id> = :c2\)',
  1291. $query->sql(),
  1292. !$this->autoQuote
  1293. );
  1294. }
  1295. /**
  1296. * Tests that empty values don't set where clauses.
  1297. *
  1298. * @return void
  1299. */
  1300. public function testWhereEmptyValues()
  1301. {
  1302. $query = new Query($this->connection);
  1303. $query->from('comments')
  1304. ->where('');
  1305. $this->assertCount(0, $query->clause('where'));
  1306. $query->where([]);
  1307. $this->assertCount(0, $query->clause('where'));
  1308. }
  1309. /**
  1310. * Tests that it is possible to use a between expression
  1311. * in a where condition
  1312. *
  1313. * @return void
  1314. */
  1315. public function testWhereWithBetween()
  1316. {
  1317. $this->loadFixtures('Comments');
  1318. $query = new Query($this->connection);
  1319. $result = $query
  1320. ->select(['id'])
  1321. ->from('comments')
  1322. ->where(function ($exp) {
  1323. return $exp->between('id', 5, 6, 'integer');
  1324. })
  1325. ->execute();
  1326. $this->assertCount(2, $result);
  1327. $first = $result->fetch('assoc');
  1328. $this->assertEquals(5, $first['id']);
  1329. $second = $result->fetch('assoc');
  1330. $this->assertEquals(6, $second['id']);
  1331. $result->closeCursor();
  1332. }
  1333. /**
  1334. * Tests that it is possible to use a between expression
  1335. * in a where condition with a complex data type
  1336. *
  1337. * @return void
  1338. */
  1339. public function testWhereWithBetweenComplex()
  1340. {
  1341. $this->loadFixtures('Comments');
  1342. $query = new Query($this->connection);
  1343. $result = $query
  1344. ->select(['id'])
  1345. ->from('comments')
  1346. ->where(function ($exp) {
  1347. $from = new \DateTime('2007-03-18 10:51:00');
  1348. $to = new \DateTime('2007-03-18 10:54:00');
  1349. return $exp->between('created', $from, $to, 'datetime');
  1350. })
  1351. ->execute();
  1352. $this->assertCount(2, $result);
  1353. $first = $result->fetch('assoc');
  1354. $this->assertEquals(4, $first['id']);
  1355. $second = $result->fetch('assoc');
  1356. $this->assertEquals(5, $second['id']);
  1357. $result->closeCursor();
  1358. }
  1359. /**
  1360. * Tests that it is possible to use an expression object
  1361. * as the field for a between expression
  1362. *
  1363. * @return void
  1364. */
  1365. public function testWhereWithBetweenWithExpressionField()
  1366. {
  1367. $this->loadFixtures('Comments');
  1368. $query = new Query($this->connection);
  1369. $result = $query
  1370. ->select(['id'])
  1371. ->from('comments')
  1372. ->where(function ($exp, $q) {
  1373. $field = $q->func()->coalesce([new IdentifierExpression('id'), 1 => 'literal']);
  1374. return $exp->between($field, 5, 6, 'integer');
  1375. })
  1376. ->execute();
  1377. $this->assertCount(2, $result);
  1378. $first = $result->fetch('assoc');
  1379. $this->assertEquals(5, $first['id']);
  1380. $second = $result->fetch('assoc');
  1381. $this->assertEquals(6, $second['id']);
  1382. $result->closeCursor();
  1383. }
  1384. /**
  1385. * Tests that it is possible to use an expression object
  1386. * as any of the parts of the between expression
  1387. *
  1388. * @return void
  1389. */
  1390. public function testWhereWithBetweenWithExpressionParts()
  1391. {
  1392. $this->loadFixtures('Comments');
  1393. $query = new Query($this->connection);
  1394. $result = $query
  1395. ->select(['id'])
  1396. ->from('comments')
  1397. ->where(function ($exp, $q) {
  1398. $from = $q->newExpr("'2007-03-18 10:51:00'");
  1399. $to = $q->newExpr("'2007-03-18 10:54:00'");
  1400. return $exp->between('created', $from, $to);
  1401. })
  1402. ->execute();
  1403. $this->assertCount(2, $result);
  1404. $first = $result->fetch('assoc');
  1405. $this->assertEquals(4, $first['id']);
  1406. $second = $result->fetch('assoc');
  1407. $this->assertEquals(5, $second['id']);
  1408. $result->closeCursor();
  1409. }
  1410. /**
  1411. * Tests nesting query expressions both using arrays and closures
  1412. *
  1413. * @return void
  1414. */
  1415. public function testSelectExpressionComposition()
  1416. {
  1417. $this->loadFixtures('Comments');
  1418. $query = new Query($this->connection);
  1419. $result = $query
  1420. ->select(['id'])
  1421. ->from('comments')
  1422. ->where(function ($exp) {
  1423. $and = $exp->and_(['id' => 2, 'id >' => 1]);
  1424. return $exp->add($and);
  1425. })
  1426. ->execute();
  1427. $this->assertCount(1, $result);
  1428. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1429. $result->closeCursor();
  1430. $query = new Query($this->connection);
  1431. $result = $query
  1432. ->select(['id'])
  1433. ->from('comments')
  1434. ->where(function ($exp) {
  1435. $and = $exp->and_(['id' => 2, 'id <' => 2]);
  1436. return $exp->add($and);
  1437. })
  1438. ->execute();
  1439. $this->assertCount(0, $result);
  1440. $result->closeCursor();
  1441. $query = new Query($this->connection);
  1442. $result = $query
  1443. ->select(['id'])
  1444. ->from('comments')
  1445. ->where(function ($exp) {
  1446. $and = $exp->and_(function ($and) {
  1447. return $and->eq('id', 1)->gt('id', 0);
  1448. });
  1449. return $exp->add($and);
  1450. })
  1451. ->execute();
  1452. $this->assertCount(1, $result);
  1453. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1454. $result->closeCursor();
  1455. $query = new Query($this->connection);
  1456. $result = $query
  1457. ->select(['id'])
  1458. ->from('comments')
  1459. ->where(function ($exp) {
  1460. $or = $exp->or_(['id' => 1]);
  1461. $and = $exp->and_(['id >' => 2, 'id <' => 4]);
  1462. return $or->add($and);
  1463. })
  1464. ->execute();
  1465. $this->assertCount(2, $result);
  1466. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1467. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1468. $result->closeCursor();
  1469. $query = new Query($this->connection);
  1470. $result = $query
  1471. ->select(['id'])
  1472. ->from('comments')
  1473. ->where(function ($exp) {
  1474. $or = $exp->or_(function ($or) {
  1475. return $or->eq('id', 1)->eq('id', 2);
  1476. });
  1477. return $or;
  1478. })
  1479. ->execute();
  1480. $this->assertCount(2, $result);
  1481. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1482. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1483. $result->closeCursor();
  1484. }
  1485. /**
  1486. * Tests that conditions can be nested with an unary operator using the array notation
  1487. * and the not() method
  1488. *
  1489. * @return void
  1490. */
  1491. public function testSelectWhereNot()
  1492. {
  1493. $this->loadFixtures('Articles', 'Comments');
  1494. $query = new Query($this->connection);
  1495. $result = $query
  1496. ->select(['id'])
  1497. ->from('comments')
  1498. ->where(function ($exp) {
  1499. return $exp->not(
  1500. $exp->and_(['id' => 2, 'created' => new \DateTime('2007-03-18 10:47:23')], ['created' => 'datetime'])
  1501. );
  1502. })
  1503. ->execute();
  1504. $this->assertCount(5, $result);
  1505. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1506. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1507. $result->closeCursor();
  1508. $query = new Query($this->connection);
  1509. $result = $query
  1510. ->select(['id'])
  1511. ->from('comments')
  1512. ->where(function ($exp) {
  1513. return $exp->not(
  1514. $exp->and_(['id' => 2, 'created' => new \DateTime('2012-12-21 12:00')], ['created' => 'datetime'])
  1515. );
  1516. })
  1517. ->execute();
  1518. $this->assertCount(6, $result);
  1519. $result->closeCursor();
  1520. }
  1521. /**
  1522. * Tests that conditions can be nested with an unary operator using the array notation
  1523. * and the not() method
  1524. *
  1525. * @return void
  1526. */
  1527. public function testSelectWhereNot2()
  1528. {
  1529. $this->loadFixtures('Articles');
  1530. $query = new Query($this->connection);
  1531. $result = $query
  1532. ->select(['id'])
  1533. ->from('articles')
  1534. ->where([
  1535. 'not' => ['or' => ['id' => 1, 'id >' => 2], 'id' => 3]
  1536. ])
  1537. ->execute();
  1538. $this->assertCount(2, $result);
  1539. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1540. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1541. $result->closeCursor();
  1542. }
  1543. /**
  1544. * Tests order() method both with simple fields and expressions
  1545. *
  1546. * @return void
  1547. */
  1548. public function testSelectOrderBy()
  1549. {
  1550. $this->loadFixtures('Comments');
  1551. $query = new Query($this->connection);
  1552. $result = $query
  1553. ->select(['id'])
  1554. ->from('comments')
  1555. ->order(['id' => 'desc'])
  1556. ->execute();
  1557. $this->assertEquals(['id' => 6], $result->fetch('assoc'));
  1558. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1559. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  1560. $result->closeCursor();
  1561. $result = $query->order(['id' => 'asc'])->execute();
  1562. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1563. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1564. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1565. $result->closeCursor();
  1566. $result = $query->order(['comment' => 'asc'])->execute();
  1567. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1568. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1569. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1570. $result->closeCursor();
  1571. $result = $query->order(['comment' => 'asc'], true)->execute();
  1572. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1573. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1574. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  1575. $result->closeCursor();
  1576. $result = $query->order(['user_id' => 'asc', 'created' => 'desc'], true)
  1577. ->execute();
  1578. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1579. $this->assertEquals(['id' => 4], $result->fetch('assoc'));
  1580. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1581. $result->closeCursor();
  1582. $expression = $query->newExpr(['(id + :offset) % 2']);
  1583. $result = $query
  1584. ->order([$expression, 'id' => 'desc'], true)
  1585. ->bind(':offset', 1, null)
  1586. ->execute();
  1587. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1588. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1589. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1590. $result->closeCursor();
  1591. $result = $query
  1592. ->order($expression, true)
  1593. ->order(['id' => 'asc'])
  1594. ->bind(':offset', 1, null)
  1595. ->execute();
  1596. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1597. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1598. $this->assertEquals(['id' => 5], $result->fetch('assoc'));
  1599. $result->closeCursor();
  1600. }
  1601. /**
  1602. * Test that order() being a string works.
  1603. *
  1604. * @return void
  1605. */
  1606. public function testSelectOrderByString()
  1607. {
  1608. $this->loadFixtures('Articles');
  1609. $query = new Query($this->connection);
  1610. $query->select(['id'])
  1611. ->from('articles')
  1612. ->order('id asc');
  1613. $result = $query->execute();
  1614. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1615. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1616. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1617. $result->closeCursor();
  1618. }
  1619. /**
  1620. * Test orderAsc() and its input types.
  1621. *
  1622. * @return void
  1623. */
  1624. public function testSelectOrderAsc()
  1625. {
  1626. $this->loadFixtures('Articles');
  1627. $query = new Query($this->connection);
  1628. $query->select(['id'])
  1629. ->from('articles')
  1630. ->orderAsc('id');
  1631. $sql = $query->sql();
  1632. $result = $query->execute()->fetchAll('assoc');
  1633. $expected = [
  1634. ['id' => 1],
  1635. ['id' => 2],
  1636. ['id' => 3],
  1637. ];
  1638. $this->assertEquals($expected, $result);
  1639. $this->assertQuotedQuery(
  1640. 'SELECT <id> FROM <articles> ORDER BY <id> ASC',
  1641. $sql,
  1642. !$this->autoQuote
  1643. );
  1644. $query = new Query($this->connection);
  1645. $query->select(['id'])
  1646. ->from('articles')
  1647. ->orderAsc($query->func()->concat(['id' => 'identifier', '3']));
  1648. $result = $query->execute()->fetchAll('assoc');
  1649. $expected = [
  1650. ['id' => 1],
  1651. ['id' => 2],
  1652. ['id' => 3],
  1653. ];
  1654. $this->assertEquals($expected, $result);
  1655. }
  1656. /**
  1657. * Test orderDesc() and its input types.
  1658. *
  1659. * @return void
  1660. */
  1661. public function testSelectOrderDesc()
  1662. {
  1663. $this->loadFixtures('Articles');
  1664. $query = new Query($this->connection);
  1665. $query->select(['id'])
  1666. ->from('articles')
  1667. ->orderDesc('id');
  1668. $sql = $query->sql();
  1669. $result = $query->execute()->fetchAll('assoc');
  1670. $expected = [
  1671. ['id' => 3],
  1672. ['id' => 2],
  1673. ['id' => 1],
  1674. ];
  1675. $this->assertEquals($expected, $result);
  1676. $this->assertQuotedQuery(
  1677. 'SELECT <id> FROM <articles> ORDER BY <id> DESC',
  1678. $sql,
  1679. !$this->autoQuote
  1680. );
  1681. $query = new Query($this->connection);
  1682. $query->select(['id'])
  1683. ->from('articles')
  1684. ->orderDesc($query->func()->concat(['id' => 'identifier', '3']));
  1685. $result = $query->execute()->fetchAll('assoc');
  1686. $expected = [
  1687. ['id' => 3],
  1688. ['id' => 2],
  1689. ['id' => 1],
  1690. ];
  1691. $this->assertEquals($expected, $result);
  1692. }
  1693. /**
  1694. * Tests that group by fields can be passed similar to select fields
  1695. * and that it sends the correct query to the database
  1696. *
  1697. * @return void
  1698. */
  1699. public function testSelectGroup()
  1700. {
  1701. $this->loadFixtures('Authors', 'Articles');
  1702. $query = new Query($this->connection);
  1703. $result = $query
  1704. ->select(['total' => 'count(author_id)', 'author_id'])
  1705. ->from('articles')
  1706. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1707. ->group('author_id')
  1708. ->execute();
  1709. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1710. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1711. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1712. ->group(['name'], true)
  1713. ->order(['total' => 'asc'])
  1714. ->execute();
  1715. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1716. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1717. $result = $query->select(['articles.id'])
  1718. ->group(['articles.id'])
  1719. ->execute();
  1720. $this->assertCount(3, $result);
  1721. }
  1722. /**
  1723. * Tests that it is possible to select distinct rows
  1724. *
  1725. * @return void
  1726. */
  1727. public function testSelectDistinct()
  1728. {
  1729. $this->loadFixtures('Authors', 'Articles');
  1730. $query = new Query($this->connection);
  1731. $result = $query
  1732. ->select(['author_id'])
  1733. ->from(['a' => 'articles'])
  1734. ->execute();
  1735. $this->assertCount(3, $result);
  1736. $result = $query->distinct()->execute();
  1737. $this->assertCount(2, $result);
  1738. $result = $query->select(['id'])->distinct(false)->execute();
  1739. $this->assertCount(3, $result);
  1740. }
  1741. /**
  1742. * Tests that it is possible to select distinct rows, even filtering by one column
  1743. * this is testing that there is a specific implementation for DISTINCT ON
  1744. *
  1745. * @return void
  1746. */
  1747. public function testSelectDistinctON()
  1748. {
  1749. $this->loadFixtures('Authors', 'Articles');
  1750. $query = new Query($this->connection);
  1751. $result = $query
  1752. ->select(['id', 'author_id'])
  1753. ->distinct(['author_id'])
  1754. ->from(['a' => 'articles'])
  1755. ->order(['author_id' => 'ASC'])
  1756. ->execute();
  1757. $this->assertCount(2, $result);
  1758. $results = $result->fetchAll('assoc');
  1759. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1760. $this->assertEquals(
  1761. [3, 1],
  1762. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1763. );
  1764. $query = new Query($this->connection);
  1765. $result = $query
  1766. ->select(['id', 'author_id'])
  1767. ->distinct('author_id')
  1768. ->from(['a' => 'articles'])
  1769. ->order(['author_id' => 'ASC'])
  1770. ->execute();
  1771. $this->assertCount(2, $result);
  1772. $results = $result->fetchAll('assoc');
  1773. $this->assertEquals(['id', 'author_id'], array_keys($results[0]));
  1774. $this->assertEquals(
  1775. [3, 1],
  1776. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1777. );
  1778. }
  1779. /**
  1780. * Test use of modifiers in the query
  1781. *
  1782. * Testing the generated SQL since the modifiers are usually different per driver
  1783. *
  1784. * @return void
  1785. */
  1786. public function testSelectModifiers()
  1787. {
  1788. $query = new Query($this->connection);
  1789. $result = $query
  1790. ->select(['city', 'state', 'country'])
  1791. ->from(['addresses'])
  1792. ->modifier('DISTINCTROW');
  1793. $this->assertQuotedQuery(
  1794. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1795. $result->sql(),
  1796. !$this->autoQuote
  1797. );
  1798. $query = new Query($this->connection);
  1799. $result = $query
  1800. ->select(['city', 'state', 'country'])
  1801. ->from(['addresses'])
  1802. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1803. $this->assertQuotedQuery(
  1804. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1805. $result->sql(),
  1806. !$this->autoQuote
  1807. );
  1808. $query = new Query($this->connection);
  1809. $result = $query
  1810. ->select(['city', 'state', 'country'])
  1811. ->from(['addresses'])
  1812. ->modifier('DISTINCTROW')
  1813. ->modifier('SQL_NO_CACHE');
  1814. $this->assertQuotedQuery(
  1815. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1816. $result->sql(),
  1817. true
  1818. );
  1819. $query = new Query($this->connection);
  1820. $result = $query
  1821. ->select(['city', 'state', 'country'])
  1822. ->from(['addresses'])
  1823. ->modifier(['TOP 10']);
  1824. $this->assertQuotedQuery(
  1825. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1826. $result->sql(),
  1827. !$this->autoQuote
  1828. );
  1829. }
  1830. /**
  1831. * Tests that having() behaves pretty much the same as the where() method
  1832. *
  1833. * @return void
  1834. */
  1835. public function testSelectHaving()
  1836. {
  1837. $this->loadFixtures('Authors', 'Articles');
  1838. $query = new Query($this->connection);
  1839. $result = $query
  1840. ->select(['total' => 'count(author_id)', 'author_id'])
  1841. ->from('articles')
  1842. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1843. ->group('author_id')
  1844. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1845. ->execute();
  1846. $expected = [['total' => 1, 'author_id' => 3]];
  1847. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1848. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1849. ->execute();
  1850. $expected = [['total' => 2, 'author_id' => 1]];
  1851. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1852. $result = $query->having(function ($e) {
  1853. return $e->add('count(author_id) = 1 + 1');
  1854. }, [], true)
  1855. ->execute();
  1856. $expected = [['total' => 2, 'author_id' => 1]];
  1857. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1858. }
  1859. /**
  1860. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1861. * in the having clause
  1862. *
  1863. * @return void
  1864. */
  1865. public function testSelectOrHaving()
  1866. {
  1867. $this->loadFixtures('Authors', 'Articles');
  1868. $query = new Query($this->connection);
  1869. $result = $query
  1870. ->select(['total' => 'count(author_id)', 'author_id'])
  1871. ->from('articles')
  1872. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1873. ->group('author_id')
  1874. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1875. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1876. ->execute();
  1877. $expected = [['total' => 1, 'author_id' => 3]];
  1878. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1879. $query = new Query($this->connection);
  1880. $result = $query
  1881. ->select(['total' => 'count(author_id)', 'author_id'])
  1882. ->from('articles')
  1883. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1884. ->group('author_id')
  1885. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1886. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1887. ->execute();
  1888. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1889. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1890. $query = new Query($this->connection);
  1891. $result = $query
  1892. ->select(['total' => 'count(author_id)', 'author_id'])
  1893. ->from('articles')
  1894. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1895. ->group('author_id')
  1896. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1897. ->orHaving(function ($e) {
  1898. return $e->add('count(author_id) = 1 + 1');
  1899. })
  1900. ->execute();
  1901. $expected = [['total' => 2, 'author_id' => 1]];
  1902. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1903. }
  1904. /**
  1905. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1906. * in the having clause
  1907. *
  1908. * @return void
  1909. */
  1910. public function testSelectAndHaving()
  1911. {
  1912. $this->loadFixtures('Authors', 'Articles');
  1913. $query = new Query($this->connection);
  1914. $result = $query
  1915. ->select(['total' => 'count(author_id)', 'author_id'])
  1916. ->from('articles')
  1917. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1918. ->group('author_id')
  1919. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1920. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1921. ->execute();
  1922. $this->assertCount(0, $result);
  1923. $query = new Query($this->connection);
  1924. $result = $query
  1925. ->select(['total' => 'count(author_id)', 'author_id'])
  1926. ->from('articles')
  1927. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1928. ->group('author_id')
  1929. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1930. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1931. ->execute();
  1932. $expected = [['total' => 2, 'author_id' => 1]];
  1933. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1934. $query = new Query($this->connection);
  1935. $result = $query
  1936. ->select(['total' => 'count(author_id)', 'author_id'])
  1937. ->from('articles')
  1938. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1939. ->group('author_id')
  1940. ->andHaving(function ($e) {
  1941. return $e->add('count(author_id) = 2 - 1');
  1942. })
  1943. ->execute();
  1944. $expected = [['total' => 1, 'author_id' => 3]];
  1945. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1946. }
  1947. /**
  1948. * Tests selecting rows using a limit clause
  1949. *
  1950. * @return void
  1951. */
  1952. public function testSelectLimit()
  1953. {
  1954. $this->loadFixtures('Articles');
  1955. $query = new Query($this->connection);
  1956. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1957. $this->assertCount(1, $result);
  1958. $query = new Query($this->connection);
  1959. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1960. $this->assertCount(2, $result);
  1961. }
  1962. /**
  1963. * Tests selecting rows combining a limit and offset clause
  1964. *
  1965. * @return void
  1966. */
  1967. public function testSelectOffset()
  1968. {
  1969. $this->loadFixtures('Articles', 'Comments');
  1970. $query = new Query($this->connection);
  1971. $result = $query->select('id')->from('comments')
  1972. ->limit(1)
  1973. ->offset(0)
  1974. ->order(['id' => 'ASC'])
  1975. ->execute();
  1976. $this->assertCount(1, $result);
  1977. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1978. $query = new Query($this->connection);
  1979. $result = $query->select('id')->from('comments')
  1980. ->limit(1)
  1981. ->offset(1)
  1982. ->execute();
  1983. $this->assertCount(1, $result);
  1984. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1985. $query = new Query($this->connection);
  1986. $result = $query->select('id')->from('comments')
  1987. ->limit(1)
  1988. ->offset(2)
  1989. ->execute();
  1990. $this->assertCount(1, $result);
  1991. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1992. $query = new Query($this->connection);
  1993. $result = $query->select('id')->from('articles')
  1994. ->order(['id' => 'DESC'])
  1995. ->limit(1)
  1996. ->offset(0)
  1997. ->execute();
  1998. $this->assertCount(1, $result);
  1999. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  2000. $result = $query->limit(2)->offset(1)->execute();
  2001. $this->assertCount(2, $result);
  2002. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  2003. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  2004. $query = new Query($this->connection);
  2005. $query->select('id')->from('comments')
  2006. ->limit(1)
  2007. ->offset(1)
  2008. ->execute();
  2009. $dirty = $this->readAttribute($query, '_dirty');
  2010. $this->assertFalse($dirty);
  2011. $query->offset(2);
  2012. $dirty = $this->readAttribute($query, '_dirty');
  2013. $this->assertTrue($dirty);
  2014. }
  2015. /**
  2016. * Test selecting rows using the page() method.
  2017. *
  2018. * @return void
  2019. */
  2020. public function testSelectPage()
  2021. {
  2022. $this->loadFixtures('Comments');
  2023. $query = new Query($this->connection);
  2024. $result = $query->select('id')->from('comments')
  2025. ->limit(1)
  2026. ->page(1)
  2027. ->execute();
  2028. $this->assertCount(1, $result);
  2029. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  2030. $query = new Query($this->connection);
  2031. $result = $query->select('id')->from('comments')
  2032. ->limit(1)
  2033. ->page(2)
  2034. ->order(['id' => 'asc'])
  2035. ->execute();
  2036. $this->assertCount(1, $result);
  2037. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  2038. $query = new Query($this->connection);
  2039. $query->select('id')->from('comments')->page(3, 10);
  2040. $this->assertEquals(10, $query->clause('limit'));
  2041. $this->assertEquals(20, $query->clause('offset'));
  2042. $query = new Query($this->connection);
  2043. $query->select('id')->from('comments')->page(1);
  2044. $this->assertEquals(25, $query->clause('limit'));
  2045. $this->assertEquals(0, $query->clause('offset'));
  2046. $query->select('id')->from('comments')->page(2);
  2047. $this->assertEquals(25, $query->clause('limit'));
  2048. $this->assertEquals(25, $query->clause('offset'));
  2049. }
  2050. /**
  2051. * Tests that Query objects can be included inside the select clause
  2052. * and be used as a normal field, including binding any passed parameter
  2053. *
  2054. * @return void
  2055. */
  2056. public function testSubqueryInSelect()
  2057. {
  2058. $this->loadFixtures('Authors', 'Articles', 'Comments');
  2059. $query = new Query($this->connection);
  2060. $subquery = (new Query($this->connection))
  2061. ->select('name')
  2062. ->from(['b' => 'authors'])
  2063. ->where([$query->newExpr()->equalFields('b.id', 'a.id')]);
  2064. $result = $query
  2065. ->select(['id', 'name' => $subquery])
  2066. ->from(['a' => 'comments'])->execute();
  2067. $expected = [
  2068. ['id' => 1, 'name' => 'mariano'],
  2069. ['id' => 2, 'name' => 'nate'],
  2070. ['id' => 3, 'name' => 'larry'],
  2071. ['id' => 4, 'name' => 'garrett'],
  2072. ['id' => 5, 'name' => null],
  2073. ['id' => 6, 'name' => null],
  2074. ];
  2075. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2076. $query = new Query($this->connection);
  2077. $subquery = (new Query($this->connection))
  2078. ->select('name')
  2079. ->from(['b' => 'authors'])
  2080. ->where(['name' => 'mariano'], ['name' => 'string']);
  2081. $result = $query
  2082. ->select(['id', 'name' => $subquery])
  2083. ->from(['a' => 'articles'])->execute();
  2084. $expected = [
  2085. ['id' => 1, 'name' => 'mariano'],
  2086. ['id' => 2, 'name' => 'mariano'],
  2087. ['id' => 3, 'name' => 'mariano'],
  2088. ];
  2089. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2090. }
  2091. /**
  2092. * Tests that Query objects can be included inside the from clause
  2093. * and be used as a normal table, including binding any passed parameter
  2094. *
  2095. * @return void
  2096. */
  2097. public function testSuqueryInFrom()
  2098. {
  2099. $this->loadFixtures('Comments');
  2100. $query = new Query($this->connection);
  2101. $subquery = (new Query($this->connection))
  2102. ->select(['id', 'comment'])
  2103. ->from('comments')
  2104. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  2105. $result = $query
  2106. ->select(['say' => 'comment'])
  2107. ->from(['b' => $subquery])
  2108. ->where(['id !=' => 3])
  2109. ->execute();
  2110. $expected = [
  2111. ['say' => 'Second Comment for First Article'],
  2112. ['say' => 'Fourth Comment for First Article'],
  2113. ['say' => 'First Comment for Second Article'],
  2114. ['say' => 'Second Comment for Second Article'],
  2115. ];
  2116. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2117. }
  2118. /**
  2119. * Tests that Query objects can be included inside the where clause
  2120. * and be used as a normal condition, including binding any passed parameter
  2121. *
  2122. * @return void
  2123. */
  2124. public function testSubqueryInWhere()
  2125. {
  2126. $this->loadFixtures('Authors', 'Comments');
  2127. $query = new Query($this->connection);
  2128. $subquery = (new Query($this->connection))
  2129. ->select(['id'])
  2130. ->from('authors')
  2131. ->where(['id' => 1]);
  2132. $result = $query
  2133. ->select(['name'])
  2134. ->from(['authors'])
  2135. ->where(['id !=' => $subquery])
  2136. ->execute();
  2137. $expected = [
  2138. ['name' => 'nate'],
  2139. ['name' => 'larry'],
  2140. ['name' => 'garrett'],
  2141. ];
  2142. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2143. $result->closeCursor();
  2144. $query = new Query($this->connection);
  2145. $subquery = (new Query($this->connection))
  2146. ->select(['id'])
  2147. ->from('comments')
  2148. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  2149. $result = $query
  2150. ->select(['name'])
  2151. ->from(['authors'])
  2152. ->where(['id not in' => $subquery])
  2153. ->execute();
  2154. $expected = [
  2155. ['name' => 'mariano'],
  2156. ];
  2157. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2158. $result->closeCursor();
  2159. }
  2160. /**
  2161. * Tests that it is possible to use a subquery in a join clause
  2162. *
  2163. * @return void
  2164. */
  2165. public function testSubqueryInJoin()
  2166. {
  2167. $this->loadFixtures('Authors', 'Articles');
  2168. $subquery = (new Query($this->connection))->select('*')->from('authors');
  2169. $query = new Query($this->connection);
  2170. $result = $query
  2171. ->select(['title', 'name'])
  2172. ->from('articles')
  2173. ->join(['b' => $subquery])
  2174. ->execute();
  2175. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  2176. $result->closeCursor();
  2177. $subquery->where(['id' => 1]);
  2178. $result = $query->execute();
  2179. $this->assertCount(3, $result);
  2180. $result->closeCursor();
  2181. $query->join(['b' => ['table' => $subquery, 'conditions' => [$query->newExpr()->equalFields('b.id', 'articles.id')]]], [], true);
  2182. $result = $query->execute();
  2183. $this->assertCount(1, $result);
  2184. $result->closeCursor();
  2185. }
  2186. /**
  2187. * Tests that it is possible to one or multiple UNION statements in a query
  2188. *
  2189. * @return void
  2190. */
  2191. public function testUnion()
  2192. {
  2193. $this->loadFixtures('Authors', 'Articles', 'Comments');
  2194. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  2195. $query = new Query($this->connection);
  2196. $result = $query->select(['id', 'comment'])
  2197. ->from(['c' => 'comments'])
  2198. ->union($union)
  2199. ->execute();
  2200. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2201. $rows = $result->fetchAll();
  2202. $result->closeCursor();
  2203. $union->select(['foo' => 'id', 'bar' => 'title']);
  2204. $union = (new Query($this->connection))
  2205. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  2206. ->from(['b' => 'authors'])
  2207. ->where(['id ' => 1])
  2208. ->order(['id' => 'desc']);
  2209. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  2210. $result = $query->execute();
  2211. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  2212. $this->assertNotEquals($rows, $result->fetchAll());
  2213. $result->closeCursor();
  2214. $union = (new Query($this->connection))
  2215. ->select(['id', 'title'])
  2216. ->from(['c' => 'articles']);
  2217. $query->select(['id', 'comment'], true)->union($union, true);
  2218. $result = $query->execute();
  2219. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2220. $this->assertEquals($rows, $result->fetchAll());
  2221. $result->closeCursor();
  2222. }
  2223. /**
  2224. * Tests that it is possible to run unions with order statements
  2225. *
  2226. * @return void
  2227. */
  2228. public function testUnionOrderBy()
  2229. {
  2230. $this->loadFixtures('Articles', 'Comments');
  2231. $this->skipIf(
  2232. ($this->connection->driver() instanceof \Cake\Database\Driver\Sqlite ||
  2233. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver),
  2234. 'Driver does not support ORDER BY in UNIONed queries.'
  2235. );
  2236. $union = (new Query($this->connection))
  2237. ->select(['id', 'title'])
  2238. ->from(['a' => 'articles'])
  2239. ->order(['a.id' => 'asc']);
  2240. $query = new Query($this->connection);
  2241. $result = $query->select(['id', 'comment'])
  2242. ->from(['c' => 'comments'])
  2243. ->order(['c.id' => 'asc'])
  2244. ->union($union)
  2245. ->execute();
  2246. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2247. $rows = $result->fetchAll();
  2248. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2249. }
  2250. /**
  2251. * Tests that UNION ALL can be built by setting the second param of union() to true
  2252. *
  2253. * @return void
  2254. */
  2255. public function testUnionAll()
  2256. {
  2257. $this->loadFixtures('Authors', 'Articles', 'Comments');
  2258. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  2259. $query = new Query($this->connection);
  2260. $result = $query->select(['id', 'comment'])
  2261. ->from(['c' => 'comments'])
  2262. ->union($union)
  2263. ->execute();
  2264. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  2265. $rows = $result->fetchAll();
  2266. $result->closeCursor();
  2267. $union->select(['foo' => 'id', 'bar' => 'title']);
  2268. $union = (new Query($this->connection))
  2269. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  2270. ->from(['b' => 'authors'])
  2271. ->where(['id ' => 1])
  2272. ->order(['id' => 'desc']);
  2273. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  2274. $result = $query->execute();
  2275. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  2276. $this->assertNotEquals($rows, $result->fetchAll());
  2277. $result->closeCursor();
  2278. }
  2279. /**
  2280. * Tests stacking decorators for results and resetting the list of decorators
  2281. *
  2282. * @return void
  2283. */
  2284. public function testDecorateResults()
  2285. {
  2286. $this->loadFixtures('Articles');
  2287. $query = new Query($this->connection);
  2288. $result = $query
  2289. ->select(['id', 'title'])
  2290. ->from('articles')
  2291. ->order(['id' => 'ASC'])
  2292. ->decorateResults(function ($row) {
  2293. $row['modified_id'] = $row['id'] + 1;
  2294. return $row;
  2295. })
  2296. ->execute();
  2297. while ($row = $result->fetch('assoc')) {
  2298. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  2299. }
  2300. $result = $query->decorateResults(function ($row) {
  2301. $row['modified_id']--;
  2302. return $row;
  2303. })->execute();
  2304. while ($row = $result->fetch('assoc')) {
  2305. $this->assertEquals($row['id'], $row['modified_id']);
  2306. }
  2307. $result->closeCursor();
  2308. $result = $query
  2309. ->decorateResults(function ($row) {
  2310. $row['foo'] = 'bar';
  2311. return $row;
  2312. }, true)
  2313. ->execute();
  2314. while ($row = $result->fetch('assoc')) {
  2315. $this->assertEquals('bar', $row['foo']);
  2316. $this->assertArrayNotHasKey('modified_id', $row);
  2317. }
  2318. $results = $query->decorateResults(null, true)->execute();
  2319. while ($row = $result->fetch('assoc')) {
  2320. $this->assertArrayNotHasKey('foo', $row);
  2321. $this->assertArrayNotHasKey('modified_id', $row);
  2322. }
  2323. $results->closeCursor();
  2324. }
  2325. /**
  2326. * Test a basic delete using from()
  2327. *
  2328. * @return void
  2329. */
  2330. public function testDeleteWithFrom()
  2331. {
  2332. $this->loadFixtures('Authors');
  2333. $query = new Query($this->connection);
  2334. $query->delete()
  2335. ->from('authors')
  2336. ->where('1 = 1');
  2337. $result = $query->sql();
  2338. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2339. $result = $query->execute();
  2340. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2341. $this->assertCount(self::AUTHOR_COUNT, $result);
  2342. $result->closeCursor();
  2343. }
  2344. /**
  2345. * Test delete with from and alias.
  2346. *
  2347. * @return void
  2348. */
  2349. public function testDeleteWithAliasedFrom()
  2350. {
  2351. $this->loadFixtures('Authors');
  2352. $query = new Query($this->connection);
  2353. $query->delete()
  2354. ->from(['a ' => 'authors'])
  2355. ->where(['a.id !=' => 99]);
  2356. $result = $query->sql();
  2357. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, !$this->autoQuote);
  2358. $result = $query->execute();
  2359. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2360. $this->assertCount(self::AUTHOR_COUNT, $result);
  2361. $result->closeCursor();
  2362. }
  2363. /**
  2364. * Test a basic delete with no from() call.
  2365. *
  2366. * @return void
  2367. */
  2368. public function testDeleteNoFrom()
  2369. {
  2370. $this->loadFixtures('Authors');
  2371. $query = new Query($this->connection);
  2372. $query->delete('authors')
  2373. ->where('1 = 1');
  2374. $result = $query->sql();
  2375. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2376. $result = $query->execute();
  2377. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  2378. $this->assertCount(self::AUTHOR_COUNT, $result);
  2379. $result->closeCursor();
  2380. }
  2381. /**
  2382. * Test setting select() & delete() modes.
  2383. *
  2384. * @return void
  2385. */
  2386. public function testSelectAndDeleteOnSameQuery()
  2387. {
  2388. $this->loadFixtures('Authors');
  2389. $query = new Query($this->connection);
  2390. $result = $query->select()
  2391. ->delete('authors')
  2392. ->where('1 = 1');
  2393. $result = $query->sql();
  2394. $this->assertQuotedQuery('DELETE FROM <authors>', $result, !$this->autoQuote);
  2395. $this->assertContains(' WHERE 1 = 1', $result);
  2396. }
  2397. /**
  2398. * Test a simple update.
  2399. *
  2400. * @return void
  2401. */
  2402. public function testUpdateSimple()
  2403. {
  2404. $this->loadFixtures('Authors');
  2405. $query = new Query($this->connection);
  2406. $query->update('authors')
  2407. ->set('name', 'mark')
  2408. ->where(['id' => 1]);
  2409. $result = $query->sql();
  2410. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, !$this->autoQuote);
  2411. $result = $query->execute();
  2412. $this->assertCount(1, $result);
  2413. $result->closeCursor();
  2414. }
  2415. /**
  2416. * Test update with multiple fields.
  2417. *
  2418. * @return void
  2419. */
  2420. public function testUpdateMultipleFields()
  2421. {
  2422. $this->loadFixtures('Articles');
  2423. $query = new Query($this->connection);
  2424. $query->update('articles')
  2425. ->set('title', 'mark', 'string')
  2426. ->set('body', 'some text', 'string')
  2427. ->where(['id' => 1]);
  2428. $result = $query->sql();
  2429. $this->assertQuotedQuery(
  2430. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2431. $result,
  2432. !$this->autoQuote
  2433. );
  2434. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2435. $result = $query->execute();
  2436. $this->assertCount(1, $result);
  2437. $result->closeCursor();
  2438. }
  2439. /**
  2440. * Test updating multiple fields with an array.
  2441. *
  2442. * @return void
  2443. */
  2444. public function testUpdateMultipleFieldsArray()
  2445. {
  2446. $this->loadFixtures('Articles');
  2447. $query = new Query($this->connection);
  2448. $query->update('articles')
  2449. ->set([
  2450. 'title' => 'mark',
  2451. 'body' => 'some text'
  2452. ], ['title' => 'string', 'body' => 'string'])
  2453. ->where(['id' => 1]);
  2454. $result = $query->sql();
  2455. $this->assertQuotedQuery(
  2456. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  2457. $result,
  2458. !$this->autoQuote
  2459. );
  2460. $this->assertQuotedQuery('WHERE <id> = :', $result, !$this->autoQuote);
  2461. $result = $query->execute();
  2462. $this->assertCount(1, $result);
  2463. $result->closeCursor();
  2464. }
  2465. /**
  2466. * Test updates with an expression.
  2467. *
  2468. * @return void
  2469. */
  2470. public function testUpdateWithExpression()
  2471. {
  2472. $this->loadFixtures('Comments');
  2473. $query = new Query($this->connection);
  2474. $expr = $query->newExpr()->equalFields('article_id', 'user_id');
  2475. $query->update('comments')
  2476. ->set($expr)
  2477. ->where(['id' => 1]);
  2478. $result = $query->sql();
  2479. $this->assertQuotedQuery(
  2480. 'UPDATE <comments> SET <article_id> = \(<user_id>\) WHERE <id> = :',
  2481. $result,
  2482. !$this->autoQuote
  2483. );
  2484. $result = $query->execute();
  2485. $this->assertCount(1, $result);
  2486. $result->closeCursor();
  2487. }
  2488. /**
  2489. * Test update with array fields and types.
  2490. *
  2491. * @return void
  2492. */
  2493. public function testUpdateArrayFields()
  2494. {
  2495. $this->loadFixtures('Comments');
  2496. $query = new Query($this->connection);
  2497. $date = new \DateTime;
  2498. $query->update('comments')
  2499. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  2500. ->where(['id' => 1]);
  2501. $result = $query->sql();
  2502. $this->assertQuotedQuery(
  2503. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2504. $result,
  2505. !$this->autoQuote
  2506. );
  2507. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2508. $result = $query->execute();
  2509. $this->assertCount(1, $result);
  2510. $query = new Query($this->connection);
  2511. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  2512. $result = $result->fetchAll('assoc')[0]['created'];
  2513. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  2514. }
  2515. /**
  2516. * Test update with callable in set
  2517. *
  2518. * @return void
  2519. */
  2520. public function testUpdateSetCallable()
  2521. {
  2522. $this->loadFixtures('Comments');
  2523. $query = new Query($this->connection);
  2524. $date = new \DateTime;
  2525. $query->update('comments')
  2526. ->set(function ($exp) use ($date) {
  2527. return $exp
  2528. ->eq('comment', 'mark')
  2529. ->eq('created', $date, 'date');
  2530. })
  2531. ->where(['id' => 1]);
  2532. $result = $query->sql();
  2533. $this->assertQuotedQuery(
  2534. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2535. $result,
  2536. !$this->autoQuote
  2537. );
  2538. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, !$this->autoQuote);
  2539. $result = $query->execute();
  2540. $this->assertCount(1, $result);
  2541. }
  2542. /**
  2543. * You cannot call values() before insert() it causes all sorts of pain.
  2544. *
  2545. * @expectedException \Cake\Database\Exception
  2546. * @return void
  2547. */
  2548. public function testInsertValuesBeforeInsertFailure()
  2549. {
  2550. $query = new Query($this->connection);
  2551. $query->select('*')->values([
  2552. 'id' => 1,
  2553. 'title' => 'mark',
  2554. 'body' => 'test insert'
  2555. ]);
  2556. }
  2557. /**
  2558. * Inserting nothing should not generate an error.
  2559. *
  2560. * @expectedException \RuntimeException
  2561. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  2562. * @return void
  2563. */
  2564. public function testInsertNothing()
  2565. {
  2566. $query = new Query($this->connection);
  2567. $query->insert([]);
  2568. }
  2569. /**
  2570. * Test insert overwrites values
  2571. *
  2572. * @return void
  2573. */
  2574. public function testInsertOverwritesValues()
  2575. {
  2576. $this->loadFixtures('Articles');
  2577. $query = new Query($this->connection);
  2578. $query->insert(['title', 'body'])
  2579. ->insert(['title'])
  2580. ->into('articles')
  2581. ->values([
  2582. 'title' => 'mark',
  2583. ]);
  2584. $result = $query->sql();
  2585. $this->assertQuotedQuery(
  2586. 'INSERT INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?' .
  2587. 'VALUES \(:c0\)',
  2588. $result,
  2589. !$this->autoQuote
  2590. );
  2591. }
  2592. /**
  2593. * Test inserting a single row.
  2594. *
  2595. * @return void
  2596. */
  2597. public function testInsertSimple()
  2598. {
  2599. $this->loadFixtures('Articles');
  2600. $query = new Query($this->connection);
  2601. $query->insert(['title', 'body'])
  2602. ->into('articles')
  2603. ->values([
  2604. 'title' => 'mark',
  2605. 'body' => 'test insert'
  2606. ]);
  2607. $result = $query->sql();
  2608. $this->assertQuotedQuery(
  2609. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2610. 'VALUES \(:c0, :c1\)',
  2611. $result,
  2612. !$this->autoQuote
  2613. );
  2614. $result = $query->execute();
  2615. $result->closeCursor();
  2616. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2617. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2618. $this->assertCount(1, $result, '1 row should be inserted');
  2619. }
  2620. $expected = [
  2621. [
  2622. 'id' => 4,
  2623. 'author_id' => null,
  2624. 'title' => 'mark',
  2625. 'body' => 'test insert',
  2626. 'published' => 'N',
  2627. ]
  2628. ];
  2629. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2630. }
  2631. /**
  2632. * Test an insert when not all the listed fields are provided.
  2633. * Columns should be matched up where possible.
  2634. *
  2635. * @return void
  2636. */
  2637. public function testInsertSparseRow()
  2638. {
  2639. $this->loadFixtures('Articles');
  2640. $query = new Query($this->connection);
  2641. $query->insert(['title', 'body'])
  2642. ->into('articles')
  2643. ->values([
  2644. 'title' => 'mark',
  2645. ]);
  2646. $result = $query->sql();
  2647. $this->assertQuotedQuery(
  2648. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2649. 'VALUES \(:c0, :c1\)',
  2650. $result,
  2651. !$this->autoQuote
  2652. );
  2653. $result = $query->execute();
  2654. $result->closeCursor();
  2655. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2656. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2657. $this->assertCount(1, $result, '1 row should be inserted');
  2658. }
  2659. $expected = [
  2660. [
  2661. 'id' => 4,
  2662. 'author_id' => null,
  2663. 'title' => 'mark',
  2664. 'body' => null,
  2665. 'published' => 'N',
  2666. ]
  2667. ];
  2668. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2669. }
  2670. /**
  2671. * Test inserting multiple rows with sparse data.
  2672. *
  2673. * @return void
  2674. */
  2675. public function testInsertMultipleRowsSparse()
  2676. {
  2677. $this->loadFixtures('Articles');
  2678. $query = new Query($this->connection);
  2679. $query->insert(['title', 'body'])
  2680. ->into('articles')
  2681. ->values([
  2682. 'body' => 'test insert'
  2683. ])
  2684. ->values([
  2685. 'title' => 'jose',
  2686. ]);
  2687. $result = $query->execute();
  2688. $result->closeCursor();
  2689. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2690. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2691. $this->assertCount(2, $result, '2 rows should be inserted');
  2692. }
  2693. $expected = [
  2694. [
  2695. 'id' => 4,
  2696. 'author_id' => null,
  2697. 'title' => null,
  2698. 'body' => 'test insert',
  2699. 'published' => 'N',
  2700. ],
  2701. [
  2702. 'id' => 5,
  2703. 'author_id' => null,
  2704. 'title' => 'jose',
  2705. 'body' => null,
  2706. 'published' => 'N',
  2707. ],
  2708. ];
  2709. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2710. }
  2711. /**
  2712. * Test that INSERT INTO ... SELECT works.
  2713. *
  2714. * @return void
  2715. */
  2716. public function testInsertFromSelect()
  2717. {
  2718. $this->loadFixtures('Authors', 'Articles');
  2719. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2720. ->from('authors')
  2721. ->where(['id' => 1]);
  2722. $query = new Query($this->connection);
  2723. $query->insert(
  2724. ['title', 'body', 'author_id'],
  2725. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2726. )
  2727. ->into('articles')
  2728. ->values($select);
  2729. $result = $query->sql();
  2730. $this->assertQuotedQuery(
  2731. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
  2732. $result,
  2733. !$this->autoQuote
  2734. );
  2735. $this->assertQuotedQuery(
  2736. 'SELECT <name>, \'some text\', 99 FROM <authors>',
  2737. $result,
  2738. !$this->autoQuote
  2739. );
  2740. $result = $query->execute();
  2741. $result->closeCursor();
  2742. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2743. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2744. $this->assertCount(1, $result);
  2745. }
  2746. $result = (new Query($this->connection))->select('*')
  2747. ->from('articles')
  2748. ->where(['author_id' => 99])
  2749. ->execute();
  2750. $this->assertCount(1, $result);
  2751. $expected = [
  2752. 'id' => 4,
  2753. 'title' => 'mariano',
  2754. 'body' => 'some text',
  2755. 'author_id' => 99,
  2756. 'published' => 'N',
  2757. ];
  2758. $this->assertEquals($expected, $result->fetch('assoc'));
  2759. }
  2760. /**
  2761. * Test that an exception is raised when mixing query + array types.
  2762. *
  2763. * @expectedException \Cake\Database\Exception
  2764. */
  2765. public function testInsertFailureMixingTypesArrayFirst()
  2766. {
  2767. $this->loadFixtures('Articles');
  2768. $query = new Query($this->connection);
  2769. $query->insert(['name'])
  2770. ->into('articles')
  2771. ->values(['name' => 'mark'])
  2772. ->values(new Query($this->connection));
  2773. }
  2774. /**
  2775. * Test that an exception is raised when mixing query + array types.
  2776. *
  2777. * @expectedException \Cake\Database\Exception
  2778. */
  2779. public function testInsertFailureMixingTypesQueryFirst()
  2780. {
  2781. $this->loadFixtures('Articles');
  2782. $query = new Query($this->connection);
  2783. $query->insert(['name'])
  2784. ->into('articles')
  2785. ->values(new Query($this->connection))
  2786. ->values(['name' => 'mark']);
  2787. }
  2788. /**
  2789. * Test that insert can use expression objects as values.
  2790. *
  2791. * @return void
  2792. */
  2793. public function testInsertExpressionValues()
  2794. {
  2795. $this->loadFixtures('Articles', 'Authors');
  2796. $query = new Query($this->connection);
  2797. $query->insert(['title', 'author_id'])
  2798. ->into('articles')
  2799. ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
  2800. $result = $query->execute();
  2801. $result->closeCursor();
  2802. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2803. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2804. $this->assertCount(1, $result);
  2805. }
  2806. $result = (new Query($this->connection))->select('*')
  2807. ->from('articles')
  2808. ->where(['author_id' => 99])
  2809. ->execute();
  2810. $this->assertCount(1, $result);
  2811. $expected = [
  2812. 'id' => 4,
  2813. 'title' => 'jose',
  2814. 'body' => null,
  2815. 'author_id' => '99',
  2816. 'published' => 'N',
  2817. ];
  2818. $this->assertEquals($expected, $result->fetch('assoc'));
  2819. $subquery = new Query($this->connection);
  2820. $subquery->select(['name'])
  2821. ->from('authors')
  2822. ->where(['id' => 1]);
  2823. $query = new Query($this->connection);
  2824. $query->insert(['title', 'author_id'])
  2825. ->into('articles')
  2826. ->values(['title' => $subquery, 'author_id' => 100]);
  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);
  2832. }
  2833. $result = (new Query($this->connection))->select('*')
  2834. ->from('articles')
  2835. ->where(['author_id' => 100])
  2836. ->execute();
  2837. $this->assertCount(1, $result);
  2838. $expected = [
  2839. 'id' => 5,
  2840. 'title' => 'mariano',
  2841. 'body' => null,
  2842. 'author_id' => '100',
  2843. 'published' => 'N',
  2844. ];
  2845. $this->assertEquals($expected, $result->fetch('assoc'));
  2846. }
  2847. /**
  2848. * Tests that functions are correctly transformed and their parameters are bound
  2849. *
  2850. * @group FunctionExpression
  2851. * @return void
  2852. */
  2853. public function testSQLFunctions()
  2854. {
  2855. $this->loadFixtures('Comments');
  2856. $query = new Query($this->connection);
  2857. $result = $query->select(
  2858. function ($q) {
  2859. return ['total' => $q->func()->count('*')];
  2860. }
  2861. )
  2862. ->from('comments')
  2863. ->execute();
  2864. $expected = [['total' => 6]];
  2865. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2866. $query = new Query($this->connection);
  2867. $result = $query->select([
  2868. 'c' => $query->func()->concat(['comment' => 'literal', ' is appended'])
  2869. ])
  2870. ->from('comments')
  2871. ->order(['c' => 'ASC'])
  2872. ->limit(1)
  2873. ->execute();
  2874. $expected = [
  2875. ['c' => 'First Comment for First Article is appended'],
  2876. ];
  2877. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2878. $query = new Query($this->connection);
  2879. $result = $query
  2880. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2881. ->execute()
  2882. ->fetchAll('assoc');
  2883. $this->assertEquals(3, abs($result[0]['d']));
  2884. $query = new Query($this->connection);
  2885. $result = $query
  2886. ->select(['d' => $query->func()->now('date')])
  2887. ->execute();
  2888. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2889. $query = new Query($this->connection);
  2890. $result = $query
  2891. ->select(['d' => $query->func()->now('time')])
  2892. ->execute();
  2893. $this->assertWithinRange(
  2894. date('U'),
  2895. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2896. 1
  2897. );
  2898. $query = new Query($this->connection);
  2899. $result = $query
  2900. ->select(['d' => $query->func()->now()])
  2901. ->execute();
  2902. $this->assertWithinRange(
  2903. date('U'),
  2904. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2905. 1
  2906. );
  2907. $query = new Query($this->connection);
  2908. $result = $query
  2909. ->select([
  2910. 'd' => $query->func()->datePart('day', 'created'),
  2911. 'm' => $query->func()->datePart('month', 'created'),
  2912. 'y' => $query->func()->datePart('year', 'created'),
  2913. 'de' => $query->func()->extract('day', 'created'),
  2914. 'me' => $query->func()->extract('month', 'created'),
  2915. 'ye' => $query->func()->extract('year', 'created'),
  2916. 'wd' => $query->func()->weekday('created'),
  2917. 'dow' => $query->func()->dayOfWeek('created'),
  2918. 'addDays' => $query->func()->dateAdd('created', 2, 'day'),
  2919. 'substractYears' => $query->func()->dateAdd('created', -2, 'year')
  2920. ])
  2921. ->from('comments')
  2922. ->where(['created' => '2007-03-18 10:45:23'])
  2923. ->execute()
  2924. ->fetchAll('assoc');
  2925. $result[0]['m'] = ltrim($result[0]['m'], '0');
  2926. $result[0]['me'] = ltrim($result[0]['me'], '0');
  2927. $result[0]['addDays'] = substr($result[0]['addDays'], 0, 10);
  2928. $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 10);
  2929. $expected = [
  2930. 'd' => '18',
  2931. 'm' => '3',
  2932. 'y' => '2007',
  2933. 'de' => '18',
  2934. 'me' => '3',
  2935. 'ye' => '2007',
  2936. 'wd' => '1', // Sunday
  2937. 'dow' => '1',
  2938. 'addDays' => '2007-03-20',
  2939. 'substractYears' => '2005-03-18'
  2940. ];
  2941. $this->assertEquals($expected, $result[0]);
  2942. }
  2943. /**
  2944. * Tests that default types are passed to functions accepting a $types param
  2945. *
  2946. * @return void
  2947. */
  2948. public function testDefaultTypes()
  2949. {
  2950. $this->loadFixtures('Comments');
  2951. $query = new Query($this->connection);
  2952. $this->assertEquals([], $query->defaultTypes());
  2953. $types = ['id' => 'integer', 'created' => 'datetime'];
  2954. $this->assertSame($query, $query->defaultTypes($types));
  2955. $this->assertSame($types, $query->defaultTypes());
  2956. $results = $query->select(['id', 'comment'])
  2957. ->from('comments')
  2958. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2959. ->execute();
  2960. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2961. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2962. // Now test default can be overridden
  2963. $types = ['created' => 'date'];
  2964. $results = $query
  2965. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2966. ->execute();
  2967. $this->assertCount(6, $results, 'All 6 rows should match.');
  2968. }
  2969. /**
  2970. * Tests parameter binding
  2971. *
  2972. * @return void
  2973. */
  2974. public function testBind()
  2975. {
  2976. $this->loadFixtures('Comments');
  2977. $query = new Query($this->connection);
  2978. $results = $query->select(['id', 'comment'])
  2979. ->from('comments')
  2980. ->where(['created BETWEEN :foo AND :bar'])
  2981. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2982. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2983. ->execute();
  2984. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2985. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2986. $query = new Query($this->connection);
  2987. $results = $query->select(['id', 'comment'])
  2988. ->from('comments')
  2989. ->where(['created BETWEEN :foo AND :bar'])
  2990. ->bind(':foo', '2007-03-18 10:50:00')
  2991. ->bind(':bar', '2007-03-18 10:52:00')
  2992. ->execute();
  2993. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2994. }
  2995. /**
  2996. * Test that epilog() will actually append a string to a select query
  2997. *
  2998. * @return void
  2999. */
  3000. public function testAppendSelect()
  3001. {
  3002. $this->loadFixtures('Articles');
  3003. $query = new Query($this->connection);
  3004. $sql = $query
  3005. ->select(['id', 'title'])
  3006. ->from('articles')
  3007. ->where(['id' => 1])
  3008. ->epilog('FOR UPDATE')
  3009. ->sql();
  3010. $this->assertContains('SELECT', $sql);
  3011. $this->assertContains('FROM', $sql);
  3012. $this->assertContains('WHERE', $sql);
  3013. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  3014. }
  3015. /**
  3016. * Test that epilog() will actually append a string to an insert query
  3017. *
  3018. * @return void
  3019. */
  3020. public function testAppendInsert()
  3021. {
  3022. $query = new Query($this->connection);
  3023. $sql = $query
  3024. ->insert(['id', 'title'])
  3025. ->into('articles')
  3026. ->values([1, 'a title'])
  3027. ->epilog('RETURNING id')
  3028. ->sql();
  3029. $this->assertContains('INSERT', $sql);
  3030. $this->assertContains('INTO', $sql);
  3031. $this->assertContains('VALUES', $sql);
  3032. $this->assertEquals(' RETURNING id', substr($sql, -13));
  3033. }
  3034. /**
  3035. * Test that epilog() will actually append a string to an update query
  3036. *
  3037. * @return void
  3038. */
  3039. public function testAppendUpdate()
  3040. {
  3041. $query = new Query($this->connection);
  3042. $sql = $query
  3043. ->update('articles')
  3044. ->set(['title' => 'foo'])
  3045. ->where(['id' => 1])
  3046. ->epilog('RETURNING id')
  3047. ->sql();
  3048. $this->assertContains('UPDATE', $sql);
  3049. $this->assertContains('SET', $sql);
  3050. $this->assertContains('WHERE', $sql);
  3051. $this->assertEquals(' RETURNING id', substr($sql, -13));
  3052. }
  3053. /**
  3054. * Test that epilog() will actually append a string to a delete query
  3055. *
  3056. * @return void
  3057. */
  3058. public function testAppendDelete()
  3059. {
  3060. $query = new Query($this->connection);
  3061. $sql = $query
  3062. ->delete('articles')
  3063. ->where(['id' => 1])
  3064. ->epilog('RETURNING id')
  3065. ->sql();
  3066. $this->assertContains('DELETE FROM', $sql);
  3067. $this->assertContains('WHERE', $sql);
  3068. $this->assertEquals(' RETURNING id', substr($sql, -13));
  3069. }
  3070. /**
  3071. * Tests automatic identifier quoting in the select clause
  3072. *
  3073. * @return void
  3074. */
  3075. public function testQuotingSelectFieldsAndAlias()
  3076. {
  3077. $this->connection->driver()->autoQuoting(true);
  3078. $query = new Query($this->connection);
  3079. $sql = $query->select(['something'])->sql();
  3080. $this->assertQuotedQuery('SELECT <something>$', $sql);
  3081. $query = new Query($this->connection);
  3082. $sql = $query->select(['foo' => 'something'])->sql();
  3083. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  3084. $query = new Query($this->connection);
  3085. $sql = $query->select(['foo' => 1])->sql();
  3086. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  3087. $query = new Query($this->connection);
  3088. $sql = $query->select(['foo' => '1 + 1'])->sql();
  3089. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  3090. $query = new Query($this->connection);
  3091. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  3092. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  3093. $query = new Query($this->connection);
  3094. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  3095. $this->assertQuotedQuery('<bar>', $sql);
  3096. }
  3097. /**
  3098. * Tests automatic identifier quoting in the from clause
  3099. *
  3100. * @return void
  3101. */
  3102. public function testQuotingFromAndAlias()
  3103. {
  3104. $this->connection->driver()->autoQuoting(true);
  3105. $query = new Query($this->connection);
  3106. $sql = $query->select('*')->from(['something'])->sql();
  3107. $this->assertQuotedQuery('FROM <something>', $sql);
  3108. $query = new Query($this->connection);
  3109. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  3110. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  3111. $query = new Query($this->connection);
  3112. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  3113. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  3114. }
  3115. /**
  3116. * Tests automatic identifier quoting for DISTINCT ON
  3117. *
  3118. * @return void
  3119. */
  3120. public function testQuotingDistinctOn()
  3121. {
  3122. $this->connection->driver()->autoQuoting(true);
  3123. $query = new Query($this->connection);
  3124. $sql = $query->select('*')->distinct(['something'])->sql();
  3125. $this->assertQuotedQuery('<something>', $sql);
  3126. }
  3127. /**
  3128. * Tests automatic identifier quoting in the join clause
  3129. *
  3130. * @return void
  3131. */
  3132. public function testQuotingJoinsAndAlias()
  3133. {
  3134. $this->connection->driver()->autoQuoting(true);
  3135. $query = new Query($this->connection);
  3136. $sql = $query->select('*')->join(['something'])->sql();
  3137. $this->assertQuotedQuery('JOIN <something>', $sql);
  3138. $query = new Query($this->connection);
  3139. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  3140. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  3141. $query = new Query($this->connection);
  3142. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  3143. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  3144. }
  3145. /**
  3146. * Tests automatic identifier quoting in the group by clause
  3147. *
  3148. * @return void
  3149. */
  3150. public function testQuotingGroupBy()
  3151. {
  3152. $this->connection->driver()->autoQuoting(true);
  3153. $query = new Query($this->connection);
  3154. $sql = $query->select('*')->group(['something'])->sql();
  3155. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  3156. $query = new Query($this->connection);
  3157. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  3158. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  3159. $query = new Query($this->connection);
  3160. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  3161. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  3162. }
  3163. /**
  3164. * Tests automatic identifier quoting strings inside conditions expressions
  3165. *
  3166. * @return void
  3167. */
  3168. public function testQuotingExpressions()
  3169. {
  3170. $this->connection->driver()->autoQuoting(true);
  3171. $query = new Query($this->connection);
  3172. $sql = $query->select('*')
  3173. ->where(['something' => 'value'])
  3174. ->sql();
  3175. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  3176. $query = new Query($this->connection);
  3177. $sql = $query->select('*')
  3178. ->where([
  3179. 'something' => 'value',
  3180. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  3181. ])
  3182. ->sql();
  3183. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  3184. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  3185. }
  3186. /**
  3187. * Tests that insert query parts get quoted automatically
  3188. *
  3189. * @return void
  3190. */
  3191. public function testQuotingInsert()
  3192. {
  3193. $this->connection->driver()->autoQuoting(true);
  3194. $query = new Query($this->connection);
  3195. $sql = $query->insert(['bar', 'baz'])
  3196. ->into('foo')
  3197. ->where(['something' => 'value'])
  3198. ->sql();
  3199. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  3200. $query = new Query($this->connection);
  3201. $sql = $query->insert([$query->newExpr('bar')])
  3202. ->into('foo')
  3203. ->where(['something' => 'value'])
  3204. ->sql();
  3205. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  3206. }
  3207. /**
  3208. * Tests converting a query to a string
  3209. *
  3210. * @return void
  3211. */
  3212. public function testToString()
  3213. {
  3214. $query = new Query($this->connection);
  3215. $query
  3216. ->select(['title'])
  3217. ->from('articles');
  3218. $result = (string)$query;
  3219. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, !$this->autoQuote);
  3220. }
  3221. /**
  3222. * Tests __debugInfo
  3223. *
  3224. * @return void
  3225. */
  3226. public function testDebugInfo()
  3227. {
  3228. $query = (new Query($this->connection))->select('*')
  3229. ->from('articles')
  3230. ->defaultTypes(['id' => 'integer'])
  3231. ->where(['id' => '1']);
  3232. $expected = [
  3233. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  3234. 'sql' => $query->sql(),
  3235. 'params' => [
  3236. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  3237. ],
  3238. 'defaultTypes' => ['id' => 'integer'],
  3239. 'decorators' => 0,
  3240. 'executed' => false
  3241. ];
  3242. $result = $query->__debugInfo();
  3243. $this->assertEquals($expected, $result);
  3244. $query->execute();
  3245. $expected = [
  3246. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  3247. 'sql' => $query->sql(),
  3248. 'params' => [
  3249. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  3250. ],
  3251. 'defaultTypes' => ['id' => 'integer'],
  3252. 'decorators' => 0,
  3253. 'executed' => true
  3254. ];
  3255. $result = $query->__debugInfo();
  3256. $this->assertEquals($expected, $result);
  3257. }
  3258. /**
  3259. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  3260. *
  3261. * @return void
  3262. */
  3263. public function testIsNullWithExpressions()
  3264. {
  3265. $this->loadFixtures('Authors');
  3266. $query = new Query($this->connection);
  3267. $subquery = (new Query($this->connection))
  3268. ->select(['id'])
  3269. ->from('authors')
  3270. ->where(['id' => 1]);
  3271. $result = $query
  3272. ->select(['name'])
  3273. ->from(['authors'])
  3274. ->where(function ($exp) use ($subquery) {
  3275. return $exp->isNotNull($subquery);
  3276. })
  3277. ->execute();
  3278. $this->assertNotEmpty($result->fetchAll('assoc'));
  3279. $result = (new Query($this->connection))
  3280. ->select(['name'])
  3281. ->from(['authors'])
  3282. ->where(function ($exp) use ($subquery) {
  3283. return $exp->isNull($subquery);
  3284. })
  3285. ->execute();
  3286. $this->assertEmpty($result->fetchAll('assoc'));
  3287. }
  3288. /**
  3289. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  3290. * when using autoQuoting
  3291. *
  3292. * @return void
  3293. */
  3294. public function testIsNullAutoQuoting()
  3295. {
  3296. $this->connection->driver()->autoQuoting(true);
  3297. $query = new Query($this->connection);
  3298. $query->select('*')->from('things')->where(function ($exp) {
  3299. return $exp->isNull('field');
  3300. });
  3301. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  3302. $query = new Query($this->connection);
  3303. $query->select('*')->from('things')->where(function ($exp) {
  3304. return $exp->isNotNull('field');
  3305. });
  3306. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  3307. }
  3308. /**
  3309. * Tests that using the IS operator will automatically translate to the best
  3310. * possible operator depending on the passed value
  3311. *
  3312. * @return void
  3313. */
  3314. public function testDirectIsNull()
  3315. {
  3316. $this->loadFixtures('Authors');
  3317. $sql = (new Query($this->connection))
  3318. ->select(['name'])
  3319. ->from(['authors'])
  3320. ->where(['name IS' => null])
  3321. ->sql();
  3322. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, !$this->autoQuote);
  3323. $results = (new Query($this->connection))
  3324. ->select(['name'])
  3325. ->from(['authors'])
  3326. ->where(['name IS' => 'larry'])
  3327. ->execute();
  3328. $this->assertCount(1, $results);
  3329. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  3330. }
  3331. /**
  3332. * Tests that using the IS NOT operator will automatically translate to the best
  3333. * possible operator depending on the passed value
  3334. *
  3335. * @return void
  3336. */
  3337. public function testDirectIsNotNull()
  3338. {
  3339. $this->loadFixtures('Authors');
  3340. $sql = (new Query($this->connection))
  3341. ->select(['name'])
  3342. ->from(['authors'])
  3343. ->where(['name IS NOT' => null])
  3344. ->sql();
  3345. $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, !$this->autoQuote);
  3346. $results = (new Query($this->connection))
  3347. ->select(['name'])
  3348. ->from(['authors'])
  3349. ->where(['name IS NOT' => 'larry'])
  3350. ->execute();
  3351. $this->assertCount(3, $results);
  3352. $this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
  3353. }
  3354. /**
  3355. * Tests that case statements work correctly for various use-cases.
  3356. *
  3357. * @return void
  3358. */
  3359. public function testSqlCaseStatement()
  3360. {
  3361. $this->loadFixtures('Comments');
  3362. $query = new Query($this->connection);
  3363. $publishedCase = $query
  3364. ->newExpr()
  3365. ->addCase(
  3366. $query
  3367. ->newExpr()
  3368. ->add(['published' => 'Y']),
  3369. 1,
  3370. 'integer'
  3371. );
  3372. $notPublishedCase = $query
  3373. ->newExpr()
  3374. ->addCase(
  3375. $query
  3376. ->newExpr()
  3377. ->add(['published' => 'N']),
  3378. 1,
  3379. 'integer'
  3380. );
  3381. //Postgres requires the case statement to be cast to a integer
  3382. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  3383. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  3384. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  3385. }
  3386. $results = $query
  3387. ->select([
  3388. 'published' => $query->func()->sum($publishedCase),
  3389. 'not_published' => $query->func()->sum($notPublishedCase)
  3390. ])
  3391. ->from(['comments'])
  3392. ->execute()
  3393. ->fetchAll('assoc');
  3394. $this->assertEquals(5, $results[0]['published']);
  3395. $this->assertEquals(1, $results[0]['not_published']);
  3396. $query = new Query($this->connection);
  3397. $query
  3398. ->insert(['article_id', 'user_id', 'comment', 'published'])
  3399. ->into('comments')
  3400. ->values([
  3401. 'article_id' => 2,
  3402. 'user_id' => 1,
  3403. 'comment' => 'In limbo',
  3404. 'published' => 'L'
  3405. ])
  3406. ->execute()
  3407. ->closeCursor();
  3408. $query = new Query($this->connection);
  3409. $conditions = [
  3410. $query
  3411. ->newExpr()
  3412. ->add(['published' => 'Y']),
  3413. $query
  3414. ->newExpr()
  3415. ->add(['published' => 'N'])
  3416. ];
  3417. $values = [
  3418. 'Published',
  3419. 'Not published',
  3420. 'None'
  3421. ];
  3422. $results = $query
  3423. ->select([
  3424. 'id',
  3425. 'comment',
  3426. 'status' => $query->newExpr()->addCase($conditions, $values)
  3427. ])
  3428. ->from(['comments'])
  3429. ->execute()
  3430. ->fetchAll('assoc');
  3431. $this->assertEquals('Published', $results[2]['status']);
  3432. $this->assertEquals('Not published', $results[3]['status']);
  3433. $this->assertEquals('None', $results[6]['status']);
  3434. }
  3435. /**
  3436. * Shows that bufferResults(false) will prevent client-side results buffering
  3437. *
  3438. * @return void
  3439. */
  3440. public function testUnbufferedQuery()
  3441. {
  3442. $this->loadFixtures('Articles');
  3443. $query = new Query($this->connection);
  3444. $result = $query->select(['body', 'author_id'])
  3445. ->from('articles')
  3446. ->bufferResults(false)
  3447. ->execute();
  3448. if (!method_exists($result, 'bufferResults')) {
  3449. $result->closeCursor();
  3450. $this->markTestSkipped('This driver does not support unbuffered queries');
  3451. }
  3452. $this->assertCount(0, $result, 'Unbuffered queries only have a count when results are fetched');
  3453. $list = $result->fetchAll('assoc');
  3454. $this->assertCount(3, $list);
  3455. $result->closeCursor();
  3456. $query = new Query($this->connection);
  3457. $result = $query->select(['body', 'author_id'])
  3458. ->from('articles')
  3459. ->execute();
  3460. $this->assertCount(3, $result, 'Buffered queries can be counted any time.');
  3461. $list = $result->fetchAll('assoc');
  3462. $this->assertCount(3, $list);
  3463. $result->closeCursor();
  3464. }
  3465. /**
  3466. * Test that cloning goes deep.
  3467. *
  3468. * @return void
  3469. */
  3470. public function testDeepClone()
  3471. {
  3472. $this->loadFixtures('Articles');
  3473. $query = new Query($this->connection);
  3474. $query->select(['id', 'title' => $query->func()->concat(['title' => 'literal', 'test'])])
  3475. ->from('articles')
  3476. ->where(['Articles.id' => 1])
  3477. ->offset(10)
  3478. ->limit(1)
  3479. ->order(['Articles.id' => 'DESC']);
  3480. $dupe = clone $query;
  3481. $this->assertEquals($query->clause('where'), $dupe->clause('where'));
  3482. $this->assertNotSame($query->clause('where'), $dupe->clause('where'));
  3483. $dupe->where(['Articles.title' => 'thinger']);
  3484. $this->assertNotEquals($query->clause('where'), $dupe->clause('where'));
  3485. $this->assertNotSame(
  3486. $query->clause('select')['title'],
  3487. $dupe->clause('select')['title']
  3488. );
  3489. $this->assertEquals($query->clause('order'), $dupe->clause('order'));
  3490. $this->assertNotSame($query->clause('order'), $dupe->clause('order'));
  3491. $query->order(['Articles.title' => 'ASC']);
  3492. $this->assertNotEquals($query->clause('order'), $dupe->clause('order'));
  3493. $this->assertNotSame(
  3494. $query->selectTypeMap(),
  3495. $dupe->selectTypeMap()
  3496. );
  3497. }
  3498. /**
  3499. * Tests the selectTypeMap method
  3500. *
  3501. * @return void
  3502. */
  3503. public function testSelectTypeMap()
  3504. {
  3505. $query = new Query($this->connection);
  3506. $typeMap = $query->selectTypeMap();
  3507. $this->assertInstanceOf(TypeMap::class, $typeMap);
  3508. $another = clone $typeMap;
  3509. $query->selectTypeMap($another);
  3510. $this->assertSame($another, $query->selectTypeMap());
  3511. }
  3512. /**
  3513. * Tests the automatic type conversion for the fields in the result
  3514. *
  3515. * @return void
  3516. */
  3517. public function testSelectTypeConversion()
  3518. {
  3519. $this->loadFixtures('Comments');
  3520. $query = new Query($this->connection);
  3521. $query
  3522. ->select(['id', 'comment', 'the_date' => 'created'])
  3523. ->from('comments')
  3524. ->limit(1)
  3525. ->selectTypeMap()->types(['id' => 'integer', 'the_date' => 'datetime']);
  3526. $result = $query->execute()->fetchAll('assoc');
  3527. $this->assertInternalType('integer', $result[0]['id']);
  3528. $this->assertInstanceOf('DateTime', $result[0]['the_date']);
  3529. }
  3530. /**
  3531. * Tests that the json type can save and get data symetrically
  3532. *
  3533. * @return void
  3534. */
  3535. public function testSymetricJsonType()
  3536. {
  3537. $query = new Query($this->connection);
  3538. $insert = $query
  3539. ->insert(['comment', 'article_id', 'user_id'], ['comment' => 'json'])
  3540. ->into('comments')
  3541. ->values([
  3542. 'comment' => ['a' => 'b', 'c' => true],
  3543. 'article_id' => 1,
  3544. 'user_id' => 1
  3545. ])
  3546. ->execute();
  3547. $id = $insert->lastInsertId('comments', 'id');
  3548. $insert->closeCursor();
  3549. $query = new Query($this->connection);
  3550. $query
  3551. ->select(['comment'])
  3552. ->from('comments')
  3553. ->where(['id' => $id])
  3554. ->selectTypeMap()->types(['comment' => 'json']);
  3555. $result = $query->execute();
  3556. $comment = $result->fetchAll('assoc')[0]['comment'];
  3557. $result->closeCursor();
  3558. $this->assertSame(['a' => 'b', 'c' => true], $comment);
  3559. }
  3560. /**
  3561. * Test removeJoin().
  3562. *
  3563. * @return void
  3564. */
  3565. public function testRemoveJoin()
  3566. {
  3567. $this->loadFixtures('Articles');
  3568. $query = new Query($this->connection);
  3569. $query->select(['id', 'title'])
  3570. ->from('articles')
  3571. ->join(['authors' => [
  3572. 'type' => 'INNER',
  3573. 'conditions' => ['articles.author_id = authors.id']
  3574. ]]);
  3575. $this->assertArrayHasKey('authors', $query->join());
  3576. $this->assertSame($query, $query->removeJoin('authors'));
  3577. $this->assertArrayNotHasKey('authors', $query->join());
  3578. }
  3579. /**
  3580. * Tests that types in the type map are used in the
  3581. * specific comparison functions when using a callable
  3582. *
  3583. * @return void
  3584. */
  3585. public function testBetweenExpressionAndTypeMap()
  3586. {
  3587. $this->loadFixtures('Comments');
  3588. $query = new Query($this->connection);
  3589. $query->select('id')
  3590. ->from('comments')
  3591. ->defaultTypes(['created' => 'datetime'])
  3592. ->where(function ($expr) {
  3593. $from = new \DateTime('2007-03-18 10:45:00');
  3594. $to = new \DateTime('2007-03-18 10:48:00');
  3595. return $expr->between('created', $from, $to);
  3596. });
  3597. $this->assertCount(2, $query->execute()->fetchAll());
  3598. }
  3599. /**
  3600. * Test use of modifiers in a INSERT query
  3601. *
  3602. * Testing the generated SQL since the modifiers are usually different per driver
  3603. *
  3604. * @return void
  3605. */
  3606. public function testInsertModifiers()
  3607. {
  3608. $query = new Query($this->connection);
  3609. $result = $query
  3610. ->insert(['title'])
  3611. ->into('articles')
  3612. ->values(['title' => 'foo'])
  3613. ->modifier('IGNORE');
  3614. $this->assertQuotedQuery(
  3615. 'INSERT IGNORE INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
  3616. $result->sql(),
  3617. !$this->autoQuote
  3618. );
  3619. $query = new Query($this->connection);
  3620. $result = $query
  3621. ->insert(['title'])
  3622. ->into('articles')
  3623. ->values(['title' => 'foo'])
  3624. ->modifier(['IGNORE', 'LOW_PRIORITY']);
  3625. $this->assertQuotedQuery(
  3626. 'INSERT IGNORE LOW_PRIORITY INTO <articles> \(<title>\) (OUTPUT INSERTED\.\* )?',
  3627. $result->sql(),
  3628. !$this->autoQuote
  3629. );
  3630. }
  3631. /**
  3632. * Test use of modifiers in a UPDATE query
  3633. *
  3634. * Testing the generated SQL since the modifiers are usually different per driver
  3635. *
  3636. * @return void
  3637. */
  3638. public function testUpdateModifiers()
  3639. {
  3640. $query = new Query($this->connection);
  3641. $result = $query
  3642. ->update('authors')
  3643. ->set('name', 'mark')
  3644. ->modifier('TOP 10 PERCENT');
  3645. $this->assertQuotedQuery(
  3646. 'UPDATE TOP 10 PERCENT <authors> SET <name> = :c0',
  3647. $result->sql(),
  3648. !$this->autoQuote
  3649. );
  3650. $query = new Query($this->connection);
  3651. $result = $query
  3652. ->update('authors')
  3653. ->set('name', 'mark')
  3654. ->modifier(['TOP 10 PERCENT', 'FOO']);
  3655. $this->assertQuotedQuery(
  3656. 'UPDATE TOP 10 PERCENT FOO <authors> SET <name> = :c0',
  3657. $result->sql(),
  3658. !$this->autoQuote
  3659. );
  3660. $query = new Query($this->connection);
  3661. $result = $query
  3662. ->update('authors')
  3663. ->set('name', 'mark')
  3664. ->modifier([$query->newExpr('TOP 10 PERCENT')]);
  3665. $this->assertQuotedQuery(
  3666. 'UPDATE TOP 10 PERCENT <authors> SET <name> = :c0',
  3667. $result->sql(),
  3668. !$this->autoQuote
  3669. );
  3670. }
  3671. /**
  3672. * Test use of modifiers in a DELETE query
  3673. *
  3674. * Testing the generated SQL since the modifiers are usually different per driver
  3675. *
  3676. * @return void
  3677. */
  3678. public function testDeleteModifiers()
  3679. {
  3680. $query = new Query($this->connection);
  3681. $result = $query->delete()
  3682. ->from('authors')
  3683. ->where('1 = 1')
  3684. ->modifier('IGNORE');
  3685. $this->assertQuotedQuery(
  3686. 'DELETE IGNORE FROM <authors> WHERE 1 = 1',
  3687. $result->sql(),
  3688. !$this->autoQuote
  3689. );
  3690. $query = new Query($this->connection);
  3691. $result = $query->delete()
  3692. ->from('authors')
  3693. ->where('1 = 1')
  3694. ->modifier(['IGNORE', 'QUICK']);
  3695. $this->assertQuotedQuery(
  3696. 'DELETE IGNORE QUICK FROM <authors> WHERE 1 = 1',
  3697. $result->sql(),
  3698. !$this->autoQuote
  3699. );
  3700. }
  3701. /**
  3702. * Tests that fetch returns an anonymous object when the string 'obj'
  3703. * is passed as an argument
  3704. *
  3705. * @return void
  3706. */
  3707. public function testSelectWithObjFetchType()
  3708. {
  3709. $this->loadFixtures('Comments');
  3710. $query = new Query($this->connection);
  3711. $result = $query
  3712. ->select(['id'])
  3713. ->from('comments')
  3714. ->where(['id' => '1'])
  3715. ->execute();
  3716. $obj = (object)['id' => 1];
  3717. $this->assertEquals($obj, $result->fetch('obj'));
  3718. $query = new Query($this->connection);
  3719. $result = $query
  3720. ->select(['id'])
  3721. ->from('comments')
  3722. ->where(['id' => '1'])
  3723. ->execute();
  3724. $rows = $result->fetchAll('obj');
  3725. $this->assertEquals($obj, $rows[0]);
  3726. }
  3727. /**
  3728. * Assertion for comparing a table's contents with what is in it.
  3729. *
  3730. * @param string $table
  3731. * @param int $count
  3732. * @param array $rows
  3733. * @param array $conditions
  3734. * @return void
  3735. */
  3736. public function assertTable($table, $count, $rows, $conditions = [])
  3737. {
  3738. $result = (new Query($this->connection))->select('*')
  3739. ->from($table)
  3740. ->where($conditions)
  3741. ->execute();
  3742. $this->assertCount($count, $result, 'Row count is incorrect');
  3743. $this->assertEquals($rows, $result->fetchAll('assoc'));
  3744. $result->closeCursor();
  3745. }
  3746. /**
  3747. * Assertion for comparing a regex pattern against a query having its identifiers
  3748. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  3749. * parameter is set to true, it will alter the pattern to both accept quoted and
  3750. * unquoted queries
  3751. *
  3752. * @param string $pattern
  3753. * @param string $query the result to compare against
  3754. * @param bool $optional
  3755. * @return void
  3756. */
  3757. public function assertQuotedQuery($pattern, $query, $optional = false)
  3758. {
  3759. if ($optional) {
  3760. $optional = '?';
  3761. }
  3762. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  3763. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  3764. $this->assertRegExp('#' . $pattern . '#', $query);
  3765. }
  3766. }