QueryTest.php 135 KB

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