QueryTest.php 129 KB

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