SelectQueryTest.php 146 KB

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