SelectQueryTest.php 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286
  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\Test\TestCase\Database\QueryAssertsTrait;
  37. use Cake\TestSuite\TestCase;
  38. use DateTime;
  39. use DateTimeImmutable;
  40. use InvalidArgumentException;
  41. use ReflectionProperty;
  42. use stdClass;
  43. use TestApp\Database\Type\BarType;
  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'])->order(['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)->order(['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. ->order(['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. ->order(['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. ->order(['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. ->order(['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. ->order(['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. ->order(['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. ->order(['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. $result = $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. $result = $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. ->order(['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. ->order(['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. ->order(['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 order() 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. ->order(['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->order(['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->order(['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->order(['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->order(['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. ->order([$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. ->order($expression, true)
  1592. ->order(['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. /**
  1601. * Test that order() being a string works.
  1602. */
  1603. public function testSelectOrderByString(): void
  1604. {
  1605. $query = new SelectQuery($this->connection);
  1606. $query->select(['id'])
  1607. ->from('articles')
  1608. ->order('id asc');
  1609. $result = $query->execute();
  1610. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1611. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1612. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1613. $result->closeCursor();
  1614. }
  1615. /**
  1616. * Test exception for order() with an associative array which contains extra values.
  1617. */
  1618. public function testSelectOrderByAssociativeArrayContainingExtraExpressions(): void
  1619. {
  1620. $this->expectException(InvalidArgumentException::class);
  1621. $this->expectExceptionMessage(
  1622. 'Passing extra expressions by associative array (`\'id\' => \'desc -- Comment\'`) ' .
  1623. 'is not allowed to avoid potential SQL injection. ' .
  1624. 'Use QueryExpression or numeric array instead.'
  1625. );
  1626. $query = new SelectQuery($this->connection);
  1627. $query->select(['id'])
  1628. ->from('articles')
  1629. ->order([
  1630. 'id' => 'desc -- Comment',
  1631. ]);
  1632. }
  1633. /**
  1634. * Tests that order() works with closures.
  1635. */
  1636. public function testSelectOrderByClosure(): void
  1637. {
  1638. $query = new SelectQuery($this->connection);
  1639. $query
  1640. ->select('*')
  1641. ->from('articles')
  1642. ->order(function ($exp, $q) use ($query) {
  1643. $this->assertInstanceOf(QueryExpression::class, $exp);
  1644. $this->assertSame($query, $q);
  1645. return ['id' => 'ASC'];
  1646. });
  1647. $this->assertQuotedQuery(
  1648. 'SELECT \* FROM <articles> ORDER BY <id> ASC',
  1649. $query->sql(),
  1650. !$this->autoQuote
  1651. );
  1652. $query = new SelectQuery($this->connection);
  1653. $query
  1654. ->select('*')
  1655. ->from('articles')
  1656. ->order(function ($exp) {
  1657. return [$exp->add(['id % 2 = 0']), 'title' => 'ASC'];
  1658. });
  1659. $this->assertQuotedQuery(
  1660. 'SELECT \* FROM <articles> ORDER BY id % 2 = 0, <title> ASC',
  1661. $query->sql(),
  1662. !$this->autoQuote
  1663. );
  1664. $query = new SelectQuery($this->connection);
  1665. $query
  1666. ->select('*')
  1667. ->from('articles')
  1668. ->order(function ($exp) {
  1669. return $exp->add('a + b');
  1670. });
  1671. $this->assertQuotedQuery(
  1672. 'SELECT \* FROM <articles> ORDER BY a \+ b',
  1673. $query->sql(),
  1674. !$this->autoQuote
  1675. );
  1676. $query = new SelectQuery($this->connection);
  1677. $query
  1678. ->select('*')
  1679. ->from('articles')
  1680. ->order(function ($exp, $q) {
  1681. return $q->func()->sum('a');
  1682. });
  1683. $this->assertQuotedQuery(
  1684. 'SELECT \* FROM <articles> ORDER BY SUM\(a\)',
  1685. $query->sql(),
  1686. !$this->autoQuote
  1687. );
  1688. }
  1689. /**
  1690. * Test orderAsc() and its input types.
  1691. */
  1692. public function testSelectOrderAsc(): void
  1693. {
  1694. $query = new SelectQuery($this->connection);
  1695. $query->select(['id'])
  1696. ->from('articles')
  1697. ->orderAsc('id');
  1698. $sql = $query->sql();
  1699. $result = $query->execute()->fetchAll('assoc');
  1700. $expected = [
  1701. ['id' => 1],
  1702. ['id' => 2],
  1703. ['id' => 3],
  1704. ];
  1705. $this->assertEquals($expected, $result);
  1706. $this->assertQuotedQuery(
  1707. 'SELECT <id> FROM <articles> ORDER BY <id> ASC',
  1708. $sql,
  1709. !$this->autoQuote
  1710. );
  1711. $query = new SelectQuery($this->connection);
  1712. $query->select(['id'])
  1713. ->from('articles')
  1714. ->orderAsc($query->func()->concat(['id' => 'identifier', '3']));
  1715. $result = $query->execute()->fetchAll('assoc');
  1716. $expected = [
  1717. ['id' => 1],
  1718. ['id' => 2],
  1719. ['id' => 3],
  1720. ];
  1721. $this->assertEquals($expected, $result);
  1722. $query = new SelectQuery($this->connection);
  1723. $query->select(['id'])
  1724. ->from('articles')
  1725. ->orderAsc(function (QueryExpression $exp, Query $query) {
  1726. return $exp
  1727. ->case()
  1728. ->when(['author_id' => 1])
  1729. ->then(1)
  1730. ->else($query->identifier('id'));
  1731. })
  1732. ->orderAsc('id');
  1733. $sql = $query->sql();
  1734. $result = $query->execute()->fetchAll('assoc');
  1735. $expected = [
  1736. ['id' => 1],
  1737. ['id' => 3],
  1738. ['id' => 2],
  1739. ];
  1740. $this->assertEquals($expected, $result);
  1741. $this->assertQuotedQuery(
  1742. 'SELECT <id> FROM <articles> ORDER BY CASE WHEN <author_id> = :c0 THEN :c1 ELSE <id> END ASC, <id> ASC',
  1743. $sql,
  1744. !$this->autoQuote
  1745. );
  1746. }
  1747. /**
  1748. * Test orderDesc() and its input types.
  1749. */
  1750. public function testSelectOrderDesc(): void
  1751. {
  1752. $query = new SelectQuery($this->connection);
  1753. $query->select(['id'])
  1754. ->from('articles')
  1755. ->orderDesc('id');
  1756. $sql = $query->sql();
  1757. $result = $query->execute()->fetchAll('assoc');
  1758. $expected = [
  1759. ['id' => 3],
  1760. ['id' => 2],
  1761. ['id' => 1],
  1762. ];
  1763. $this->assertEquals($expected, $result);
  1764. $this->assertQuotedQuery(
  1765. 'SELECT <id> FROM <articles> ORDER BY <id> DESC',
  1766. $sql,
  1767. !$this->autoQuote
  1768. );
  1769. $query = new SelectQuery($this->connection);
  1770. $query->select(['id'])
  1771. ->from('articles')
  1772. ->orderDesc($query->func()->concat(['id' => 'identifier', '3']));
  1773. $result = $query->execute()->fetchAll('assoc');
  1774. $expected = [
  1775. ['id' => 3],
  1776. ['id' => 2],
  1777. ['id' => 1],
  1778. ];
  1779. $this->assertEquals($expected, $result);
  1780. $query = new SelectQuery($this->connection);
  1781. $query->select(['id'])
  1782. ->from('articles')
  1783. ->orderDesc(function (QueryExpression $exp, Query $query) {
  1784. return $exp
  1785. ->case()
  1786. ->when(['author_id' => 1])
  1787. ->then(1)
  1788. ->else($query->identifier('id'));
  1789. })
  1790. ->orderDesc('id');
  1791. $sql = $query->sql();
  1792. $result = $query->execute()->fetchAll('assoc');
  1793. $expected = [
  1794. ['id' => 2],
  1795. ['id' => 3],
  1796. ['id' => 1],
  1797. ];
  1798. $this->assertEquals($expected, $result);
  1799. $this->assertQuotedQuery(
  1800. 'SELECT <id> FROM <articles> ORDER BY CASE WHEN <author_id> = :c0 THEN :c1 ELSE <id> END DESC, <id> DESC',
  1801. $sql,
  1802. !$this->autoQuote
  1803. );
  1804. }
  1805. /**
  1806. * Tests that group by fields can be passed similar to select fields
  1807. * and that it sends the correct query to the database
  1808. */
  1809. public function testSelectGroup(): void
  1810. {
  1811. $query = new SelectQuery($this->connection);
  1812. $result = $query
  1813. ->select(['total' => 'count(author_id)', 'author_id'])
  1814. ->from('articles')
  1815. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1816. ->group('author_id')
  1817. ->order(['total' => 'desc'])
  1818. ->execute();
  1819. $expected = [['total' => 2, 'author_id' => 1], ['total' => '1', 'author_id' => 3]];
  1820. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1821. $result = $query->select(['total' => 'count(title)', 'name'], true)
  1822. ->group(['name'], true)
  1823. ->order(['total' => 'asc'])
  1824. ->execute();
  1825. $expected = [['total' => 1, 'name' => 'larry'], ['total' => 2, 'name' => 'mariano']];
  1826. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1827. $result = $query->select(['articles.id'])
  1828. ->group(['articles.id'])
  1829. ->execute();
  1830. $this->assertCount(3, $result->fetchAll());
  1831. }
  1832. /**
  1833. * Tests that it is possible to select distinct rows
  1834. */
  1835. public function testSelectDistinct(): void
  1836. {
  1837. $query = new SelectQuery($this->connection);
  1838. $result = $query
  1839. ->select(['author_id'])
  1840. ->from(['a' => 'articles'])
  1841. ->execute();
  1842. $this->assertCount(3, $result->fetchAll());
  1843. $result = $query->distinct()->execute();
  1844. $this->assertCount(2, $result->fetchAll());
  1845. $result = $query->select(['id'])->distinct(false)->execute();
  1846. $this->assertCount(3, $result->fetchAll());
  1847. }
  1848. /**
  1849. * Tests distinct on a specific column reduces rows based on that column.
  1850. */
  1851. public function testSelectDistinctON(): void
  1852. {
  1853. $query = new SelectQuery($this->connection);
  1854. $result = $query
  1855. ->select(['author_id'])
  1856. ->distinct(['author_id'])
  1857. ->from(['a' => 'articles'])
  1858. ->order(['author_id' => 'ASC'])
  1859. ->execute();
  1860. $results = $result->fetchAll('assoc');
  1861. $this->assertCount(2, $results);
  1862. $this->assertEquals(
  1863. [3, 1],
  1864. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1865. );
  1866. $query = new SelectQuery($this->connection);
  1867. $result = $query
  1868. ->select(['author_id'])
  1869. ->distinct('author_id')
  1870. ->from(['a' => 'articles'])
  1871. ->order(['author_id' => 'ASC'])
  1872. ->execute();
  1873. $results = $result->fetchAll('assoc');
  1874. $this->assertCount(2, $results);
  1875. $this->assertEquals(
  1876. [3, 1],
  1877. collection($results)->sortBy('author_id')->extract('author_id')->toList()
  1878. );
  1879. }
  1880. /**
  1881. * Test use of modifiers in the query
  1882. *
  1883. * Testing the generated SQL since the modifiers are usually different per driver
  1884. */
  1885. public function testSelectModifiers(): void
  1886. {
  1887. $query = new SelectQuery($this->connection);
  1888. $result = $query
  1889. ->select(['city', 'state', 'country'])
  1890. ->from(['addresses'])
  1891. ->modifier('DISTINCTROW');
  1892. $this->assertQuotedQuery(
  1893. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1894. $result->sql(),
  1895. !$this->autoQuote
  1896. );
  1897. $query = new SelectQuery($this->connection);
  1898. $result = $query
  1899. ->select(['city', 'state', 'country'])
  1900. ->from(['addresses'])
  1901. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1902. $this->assertQuotedQuery(
  1903. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1904. $result->sql(),
  1905. !$this->autoQuote
  1906. );
  1907. $query = new SelectQuery($this->connection);
  1908. $result = $query
  1909. ->select(['city', 'state', 'country'])
  1910. ->from(['addresses'])
  1911. ->modifier('DISTINCTROW')
  1912. ->modifier('SQL_NO_CACHE');
  1913. $this->assertQuotedQuery(
  1914. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1915. $result->sql(),
  1916. true
  1917. );
  1918. $query = new SelectQuery($this->connection);
  1919. $result = $query
  1920. ->select(['city', 'state', 'country'])
  1921. ->from(['addresses'])
  1922. ->modifier(['TOP 10']);
  1923. $this->assertQuotedQuery(
  1924. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1925. $result->sql(),
  1926. !$this->autoQuote
  1927. );
  1928. $query = new SelectQuery($this->connection);
  1929. $result = $query
  1930. ->select(['city', 'state', 'country'])
  1931. ->from(['addresses'])
  1932. ->modifier($query->newExpr('EXPRESSION'));
  1933. $this->assertQuotedQuery(
  1934. 'SELECT EXPRESSION <city>, <state>, <country> FROM <addresses>',
  1935. $result->sql(),
  1936. !$this->autoQuote
  1937. );
  1938. }
  1939. /**
  1940. * Tests that having() behaves pretty much the same as the where() method
  1941. */
  1942. public function testSelectHaving(): void
  1943. {
  1944. $query = new SelectQuery($this->connection);
  1945. $result = $query
  1946. ->select(['total' => 'count(author_id)', 'author_id'])
  1947. ->from('articles')
  1948. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1949. ->group('author_id')
  1950. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1951. ->execute();
  1952. $expected = [['total' => 1, 'author_id' => 3]];
  1953. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1954. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1955. ->execute();
  1956. $expected = [['total' => 2, 'author_id' => 1]];
  1957. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1958. $result = $query->having(function ($e) {
  1959. return $e->add('count(author_id) = 1 + 1');
  1960. }, [], true)
  1961. ->execute();
  1962. $expected = [['total' => 2, 'author_id' => 1]];
  1963. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1964. }
  1965. /**
  1966. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1967. * in the having clause
  1968. */
  1969. public function testSelectAndHaving(): void
  1970. {
  1971. $query = new SelectQuery($this->connection);
  1972. $result = $query
  1973. ->select(['total' => 'count(author_id)', 'author_id'])
  1974. ->from('articles')
  1975. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1976. ->group('author_id')
  1977. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1978. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1979. ->execute();
  1980. $this->assertCount(0, $result->fetchAll());
  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. ->group('author_id')
  1987. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1988. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1989. ->execute();
  1990. $expected = [['total' => 2, 'author_id' => 1]];
  1991. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1992. $query = new SelectQuery($this->connection);
  1993. $result = $query
  1994. ->select(['total' => 'count(author_id)', 'author_id'])
  1995. ->from('articles')
  1996. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => $query->newExpr()->equalFields('author_id', 'a.id')])
  1997. ->group('author_id')
  1998. ->andHaving(function ($e) {
  1999. return $e->add('count(author_id) = 2 - 1');
  2000. })
  2001. ->execute();
  2002. $expected = [['total' => 1, 'author_id' => 3]];
  2003. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2004. }
  2005. /**
  2006. * Test having casing with string expressions
  2007. */
  2008. public function testHavingAliasCasingStringExpression(): void
  2009. {
  2010. $this->skipIf($this->autoQuote, 'Does not work when autoquoting is enabled.');
  2011. $query = new SelectQuery($this->connection);
  2012. $query
  2013. ->select(['id'])
  2014. ->from(['Authors' => 'authors'])
  2015. ->where([
  2016. 'FUNC( Authors.id) =' => 1,
  2017. 'FUNC( Authors.id) IS NOT' => null,
  2018. ])
  2019. ->having(['COUNT(DISTINCT Authors.id) =' => 1]);
  2020. $this->assertSame(
  2021. 'SELECT id FROM authors Authors WHERE ' .
  2022. '(FUNC( Authors.id) = :c0 AND (FUNC( Authors.id)) IS NOT NULL) ' .
  2023. 'HAVING COUNT(DISTINCT Authors.id) = :c1',
  2024. trim($query->sql())
  2025. );
  2026. }
  2027. /**
  2028. * Tests selecting rows using a limit clause
  2029. */
  2030. public function testSelectLimit(): void
  2031. {
  2032. $query = new SelectQuery($this->connection);
  2033. $result = $query->select('id')->from('articles')->limit(1)->execute();
  2034. $this->assertCount(1, $result->fetchAll());
  2035. $query = new SelectQuery($this->connection);
  2036. $result = $query->select('id')->from('articles')->limit(2)->execute();
  2037. $this->assertCount(2, $result->fetchAll());
  2038. }
  2039. /**
  2040. * Tests selecting rows combining a limit and offset clause
  2041. */
  2042. public function testSelectOffset(): void
  2043. {
  2044. $query = new SelectQuery($this->connection);
  2045. $result = $query->select('id')->from('comments')
  2046. ->limit(1)
  2047. ->offset(0)
  2048. ->order(['id' => 'ASC'])
  2049. ->execute();
  2050. $rows = $result->fetchAll('assoc');
  2051. $this->assertCount(1, $rows);
  2052. $this->assertEquals(['id' => 1], $rows[0]);
  2053. $query = new SelectQuery($this->connection);
  2054. $result = $query->select('id')->from('comments')
  2055. ->limit(1)
  2056. ->offset(1)
  2057. ->execute();
  2058. $rows = $result->fetchAll('assoc');
  2059. $this->assertCount(1, $rows);
  2060. $this->assertEquals(['id' => 2], $rows[0]);
  2061. $query = new SelectQuery($this->connection);
  2062. $result = $query->select('id')->from('comments')
  2063. ->limit(1)
  2064. ->offset(2)
  2065. ->execute();
  2066. $rows = $result->fetchAll('assoc');
  2067. $this->assertCount(1, $rows);
  2068. $this->assertEquals(['id' => 3], $rows[0]);
  2069. $query = new SelectQuery($this->connection);
  2070. $result = $query->select('id')->from('articles')
  2071. ->order(['id' => 'DESC'])
  2072. ->limit(1)
  2073. ->offset(0)
  2074. ->execute();
  2075. $rows = $result->fetchAll('assoc');
  2076. $this->assertCount(1, $rows);
  2077. $this->assertEquals(['id' => 3], $rows[0]);
  2078. $result = $query->limit(2)->offset(1)->execute();
  2079. $rows = $result->fetchAll('assoc');
  2080. $this->assertCount(2, $rows);
  2081. $this->assertEquals(['id' => 2], $rows[0]);
  2082. $this->assertEquals(['id' => 1], $rows[1]);
  2083. $query = new SelectQuery($this->connection);
  2084. $query->select('id')->from('comments')
  2085. ->limit(1)
  2086. ->offset(1)
  2087. ->execute()
  2088. ->closeCursor();
  2089. $reflect = new ReflectionProperty($query, '_dirty');
  2090. $this->assertFalse($reflect->getValue($query));
  2091. $query->offset(2);
  2092. $this->assertTrue($reflect->getValue($query));
  2093. }
  2094. /**
  2095. * Test Pages number.
  2096. */
  2097. public function testPageShouldStartAtOne(): void
  2098. {
  2099. $this->expectException(InvalidArgumentException::class);
  2100. $this->expectExceptionMessage('Pages must start at 1.');
  2101. $query = new SelectQuery($this->connection);
  2102. $query->from('comments')->page(0);
  2103. }
  2104. /**
  2105. * Test selecting rows using the page() method.
  2106. */
  2107. public function testSelectPage(): void
  2108. {
  2109. $query = new SelectQuery($this->connection);
  2110. $result = $query->select('id')->from('comments')
  2111. ->limit(1)
  2112. ->page(1)
  2113. ->execute();
  2114. $rows = $result->fetchAll('assoc');
  2115. $this->assertCount(1, $rows);
  2116. $this->assertEquals(['id' => 1], $rows[0]);
  2117. $query = new SelectQuery($this->connection);
  2118. $result = $query->select('id')->from('comments')
  2119. ->limit(1)
  2120. ->page(2)
  2121. ->order(['id' => 'asc'])
  2122. ->execute();
  2123. $rows = $result->fetchAll('assoc');
  2124. $this->assertCount(1, $rows);
  2125. $this->assertEquals(['id' => 2], $rows[0]);
  2126. $query = new SelectQuery($this->connection);
  2127. $query->select('id')->from('comments')->page(3, 10);
  2128. $this->assertEquals(10, $query->clause('limit'));
  2129. $this->assertEquals(20, $query->clause('offset'));
  2130. $query = new SelectQuery($this->connection);
  2131. $query->select('id')->from('comments')->page(1);
  2132. $this->assertEquals(25, $query->clause('limit'));
  2133. $this->assertEquals(0, $query->clause('offset'));
  2134. $query->select('id')->from('comments')->page(2);
  2135. $this->assertEquals(25, $query->clause('limit'));
  2136. $this->assertEquals(25, $query->clause('offset'));
  2137. }
  2138. /**
  2139. * Test selecting rows using the page() method and ordering the results
  2140. * by a calculated column.
  2141. */
  2142. public function testSelectPageWithOrder(): void
  2143. {
  2144. $query = new SelectQuery($this->connection);
  2145. $result = $query
  2146. ->select([
  2147. 'id',
  2148. 'ids_added' => $query->newExpr()->add('(user_id + article_id)'),
  2149. ])
  2150. ->from('comments')
  2151. ->order(['ids_added' => 'asc'])
  2152. ->limit(2)
  2153. ->page(3)
  2154. ->execute();
  2155. $this->assertEquals(
  2156. [
  2157. ['id' => '6', 'ids_added' => '4'],
  2158. ['id' => '2', 'ids_added' => '5'],
  2159. ],
  2160. $result->fetchAll('assoc')
  2161. );
  2162. }
  2163. /**
  2164. * Tests that Query objects can be included inside the select clause
  2165. * and be used as a normal field, including binding any passed parameter
  2166. */
  2167. public function testSubqueryInSelect(): void
  2168. {
  2169. $query = new SelectQuery($this->connection);
  2170. $subquery = (new SelectQuery($this->connection))
  2171. ->select('name')
  2172. ->from(['b' => 'authors'])
  2173. ->where([$query->newExpr()->equalFields('b.id', 'a.id')]);
  2174. $result = $query
  2175. ->select(['id', 'name' => $subquery])
  2176. ->from(['a' => 'comments'])->execute();
  2177. $expected = [
  2178. ['id' => 1, 'name' => 'mariano'],
  2179. ['id' => 2, 'name' => 'nate'],
  2180. ['id' => 3, 'name' => 'larry'],
  2181. ['id' => 4, 'name' => 'garrett'],
  2182. ['id' => 5, 'name' => null],
  2183. ['id' => 6, 'name' => null],
  2184. ];
  2185. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2186. $query = new SelectQuery($this->connection);
  2187. $subquery = (new SelectQuery($this->connection))
  2188. ->select('name')
  2189. ->from(['b' => 'authors'])
  2190. ->where(['name' => 'mariano'], ['name' => 'string']);
  2191. $result = $query
  2192. ->select(['id', 'name' => $subquery])
  2193. ->from(['a' => 'articles'])->execute();
  2194. $expected = [
  2195. ['id' => 1, 'name' => 'mariano'],
  2196. ['id' => 2, 'name' => 'mariano'],
  2197. ['id' => 3, 'name' => 'mariano'],
  2198. ];
  2199. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2200. }
  2201. /**
  2202. * Tests that Query objects can be included inside the from clause
  2203. * and be used as a normal table, including binding any passed parameter
  2204. */
  2205. public function testSuqueryInFrom(): void
  2206. {
  2207. $query = new SelectQuery($this->connection);
  2208. $subquery = (new SelectQuery($this->connection))
  2209. ->select(['id', 'comment'])
  2210. ->from('comments')
  2211. ->where(['created >' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  2212. $result = $query
  2213. ->select(['say' => 'comment'])
  2214. ->from(['b' => $subquery])
  2215. ->where(['id !=' => 3])
  2216. ->execute();
  2217. $expected = [
  2218. ['say' => 'Second Comment for First Article'],
  2219. ['say' => 'Fourth Comment for First Article'],
  2220. ['say' => 'First Comment for Second Article'],
  2221. ['say' => 'Second Comment for Second Article'],
  2222. ];
  2223. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2224. }
  2225. /**
  2226. * Tests that Query objects can be included inside the where clause
  2227. * and be used as a normal condition, including binding any passed parameter
  2228. */
  2229. public function testSubqueryInWhere(): void
  2230. {
  2231. $query = new SelectQuery($this->connection);
  2232. $subquery = (new SelectQuery($this->connection))
  2233. ->select(['id'])
  2234. ->from('authors')
  2235. ->where(['id' => 1]);
  2236. $result = $query
  2237. ->select(['name'])
  2238. ->from(['authors'])
  2239. ->where(['id !=' => $subquery])
  2240. ->execute();
  2241. $expected = [
  2242. ['name' => 'nate'],
  2243. ['name' => 'larry'],
  2244. ['name' => 'garrett'],
  2245. ];
  2246. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2247. $result->closeCursor();
  2248. $query = new SelectQuery($this->connection);
  2249. $subquery = (new SelectQuery($this->connection))
  2250. ->select(['id'])
  2251. ->from('comments')
  2252. ->where(['created >' => new DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  2253. $result = $query
  2254. ->select(['name'])
  2255. ->from(['authors'])
  2256. ->where(['id not in' => $subquery])
  2257. ->execute();
  2258. $expected = [
  2259. ['name' => 'mariano'],
  2260. ];
  2261. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2262. $result->closeCursor();
  2263. }
  2264. /**
  2265. * Tests that Query objects can be included inside the where clause
  2266. * and be used as a EXISTS and NOT EXISTS conditions
  2267. */
  2268. public function testSubqueryExistsWhere(): void
  2269. {
  2270. $query = new SelectQuery($this->connection);
  2271. $subQuery = (new SelectQuery($this->connection))
  2272. ->select(['id'])
  2273. ->from('articles')
  2274. ->where(function ($exp) {
  2275. return $exp->equalFields('authors.id', 'articles.author_id');
  2276. });
  2277. $result = $query
  2278. ->select(['id'])
  2279. ->from('authors')
  2280. ->where(function ($exp) use ($subQuery) {
  2281. return $exp->exists($subQuery);
  2282. })
  2283. ->execute();
  2284. $rows = $result->fetchAll('assoc');
  2285. $this->assertCount(2, $rows);
  2286. $this->assertEquals(['id' => 1], $rows[0]);
  2287. $this->assertEquals(['id' => 3], $rows[1]);
  2288. $query = new SelectQuery($this->connection);
  2289. $subQuery = (new SelectQuery($this->connection))
  2290. ->select(['id'])
  2291. ->from('articles')
  2292. ->where(function ($exp) {
  2293. return $exp->equalFields('authors.id', 'articles.author_id');
  2294. });
  2295. $result = $query
  2296. ->select(['id'])
  2297. ->from('authors')
  2298. ->where(function ($exp) use ($subQuery) {
  2299. return $exp->notExists($subQuery);
  2300. })
  2301. ->execute();
  2302. $rows = $result->fetchAll('assoc');
  2303. $this->assertCount(2, $rows);
  2304. $this->assertEquals(['id' => 2], $rows[0]);
  2305. $this->assertEquals(['id' => 4], $rows[1]);
  2306. }
  2307. /**
  2308. * Tests that it is possible to use a subquery in a join clause
  2309. */
  2310. public function testSubqueryInJoin(): void
  2311. {
  2312. $subquery = (new SelectQuery($this->connection))->select('*')->from('authors');
  2313. $query = new SelectQuery($this->connection);
  2314. $result = $query
  2315. ->select(['title', 'name'])
  2316. ->from('articles')
  2317. ->join(['b' => $subquery])
  2318. ->execute();
  2319. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result->fetchAll(), 'Cross join causes multiplication');
  2320. $result->closeCursor();
  2321. $subquery->where(['id' => 1]);
  2322. $result = $query->execute();
  2323. $this->assertCount(3, $result->fetchAll());
  2324. $result->closeCursor();
  2325. $query->join(['b' => ['table' => $subquery, 'conditions' => [$query->newExpr()->equalFields('b.id', 'articles.id')]]], [], true);
  2326. $result = $query->execute();
  2327. $this->assertCount(1, $result->fetchAll());
  2328. $result->closeCursor();
  2329. }
  2330. /**
  2331. * Tests that it is possible to one or multiple UNION statements in a query
  2332. */
  2333. public function testUnion(): void
  2334. {
  2335. $union = (new SelectQuery($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  2336. $query = new SelectQuery($this->connection);
  2337. $result = $query->select(['id', 'comment'])
  2338. ->from(['c' => 'comments'])
  2339. ->union($union)
  2340. ->execute();
  2341. $rows = $result->fetchAll();
  2342. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $rows);
  2343. $result->closeCursor();
  2344. $union->select(['foo' => 'id', 'bar' => 'title']);
  2345. $union = (new SelectQuery($this->connection))
  2346. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  2347. ->from(['b' => 'authors'])
  2348. ->where(['id ' => 1])
  2349. ->order(['id' => 'desc']);
  2350. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  2351. $result = $query->execute();
  2352. $rows2 = $result->fetchAll();
  2353. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $rows2);
  2354. $this->assertNotEquals($rows, $rows2);
  2355. $result->closeCursor();
  2356. $union = (new SelectQuery($this->connection))
  2357. ->select(['id', 'title'])
  2358. ->from(['c' => 'articles']);
  2359. $query->select(['id', 'comment'], true)->union($union, true);
  2360. $result = $query->execute();
  2361. $rows3 = $result->fetchAll();
  2362. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $rows3);
  2363. $this->assertEquals($rows, $rows3);
  2364. $result->closeCursor();
  2365. }
  2366. /**
  2367. * Tests that it is possible to run unions with order statements
  2368. */
  2369. public function testUnionOrderBy(): void
  2370. {
  2371. $this->skipIf(
  2372. ($this->connection->getDriver() instanceof Sqlite ||
  2373. $this->connection->getDriver() instanceof Sqlserver),
  2374. 'Driver does not support ORDER BY in UNIONed queries.'
  2375. );
  2376. $union = (new SelectQuery($this->connection))
  2377. ->select(['id', 'title'])
  2378. ->from(['a' => 'articles'])
  2379. ->order(['a.id' => 'asc']);
  2380. $query = new SelectQuery($this->connection);
  2381. $result = $query->select(['id', 'comment'])
  2382. ->from(['c' => 'comments'])
  2383. ->order(['c.id' => 'asc'])
  2384. ->union($union)
  2385. ->execute();
  2386. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result->fetchAll());
  2387. }
  2388. /**
  2389. * Tests that UNION ALL can be built by setting the second param of union() to true
  2390. */
  2391. public function testUnionAll(): void
  2392. {
  2393. $union = (new SelectQuery($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  2394. $query = new SelectQuery($this->connection);
  2395. $result = $query->select(['id', 'comment'])
  2396. ->from(['c' => 'comments'])
  2397. ->union($union)
  2398. ->execute();
  2399. $rows = $result->fetchAll('assoc');
  2400. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $rows);
  2401. $result->closeCursor();
  2402. $union->select(['foo' => 'id', 'bar' => 'title']);
  2403. $union = (new SelectQuery($this->connection))
  2404. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  2405. ->from(['b' => 'authors'])
  2406. ->where(['id ' => 1])
  2407. ->order(['id' => 'desc']);
  2408. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  2409. $result = $query->execute();
  2410. $rows2 = $result->fetchAll();
  2411. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $rows2);
  2412. $this->assertNotEquals($rows, $rows2);
  2413. $result->closeCursor();
  2414. }
  2415. /**
  2416. * Tests stacking decorators for results and resetting the list of decorators
  2417. */
  2418. public function testDecorateResults(): void
  2419. {
  2420. $query = new SelectQuery($this->connection);
  2421. $result = $query
  2422. ->select(['id', 'title'])
  2423. ->from('articles')
  2424. ->order(['id' => 'ASC'])
  2425. ->decorateResults(function ($row) {
  2426. $row['modified_id'] = $row['id'] + 1;
  2427. return $row;
  2428. })
  2429. ->all();
  2430. foreach ($result as $row) {
  2431. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  2432. }
  2433. $result = $query
  2434. ->decorateResults(function ($row) {
  2435. $row['modified_id']--;
  2436. return $row;
  2437. })
  2438. ->all();
  2439. foreach ($result as $row) {
  2440. $this->assertEquals($row['id'], $row['modified_id']);
  2441. }
  2442. $result = $query
  2443. ->decorateResults(function ($row) {
  2444. $row['foo'] = 'bar';
  2445. return $row;
  2446. }, true)
  2447. ->all();
  2448. foreach ($result as $row) {
  2449. $this->assertSame('bar', $row['foo']);
  2450. $this->assertArrayNotHasKey('modified_id', $row);
  2451. }
  2452. $result = $query->decorateResults(null, true)->all();
  2453. foreach ($result as $row) {
  2454. $this->assertArrayNotHasKey('foo', $row);
  2455. $this->assertArrayNotHasKey('modified_id', $row);
  2456. }
  2457. }
  2458. public function testAll(): void
  2459. {
  2460. $query = new SelectQuery($this->connection);
  2461. $query
  2462. ->select(['id', 'title'])
  2463. ->from('articles')
  2464. ->decorateResults(function ($row) {
  2465. $row['generated'] = 'test';
  2466. return $row;
  2467. })
  2468. ->all();
  2469. $count = 0;
  2470. foreach ($query->all() as $row) {
  2471. ++$count;
  2472. $this->assertArrayHasKey('generated', $row);
  2473. $this->assertSame('test', $row['generated']);
  2474. }
  2475. $this->assertSame(3, $count);
  2476. $this->connection->execute('DELETE FROM articles WHERE author_id = 3')->closeCursor();
  2477. // Verify results are cached when query not marked dirty
  2478. $count = 0;
  2479. foreach ($query->all() as $row) {
  2480. ++$count;
  2481. }
  2482. $this->assertSame(3, $count);
  2483. // Mark query as dirty
  2484. $query->select(['id'], true);
  2485. // Verify query is run again
  2486. $count = 0;
  2487. foreach ($query->all() as $row) {
  2488. ++$count;
  2489. }
  2490. $this->assertSame(2, $count);
  2491. }
  2492. public function testGetIterator(): void
  2493. {
  2494. $query = new SelectQuery($this->connection);
  2495. $query
  2496. ->select(['id', 'title'])
  2497. ->from('articles')
  2498. ->decorateResults(function ($row) {
  2499. $row['generated'] = 'test';
  2500. return $row;
  2501. });
  2502. $count = 0;
  2503. foreach ($query as $row) {
  2504. ++$count;
  2505. $this->assertArrayHasKey('generated', $row);
  2506. $this->assertSame('test', $row['generated']);
  2507. }
  2508. $this->assertSame(3, $count);
  2509. $this->connection->execute('DELETE FROM articles WHERE author_id = 3')->closeCursor();
  2510. // Mark query as dirty
  2511. $query->select(['id'], true);
  2512. // Verify all() is called again
  2513. $count = 0;
  2514. foreach ($query as $row) {
  2515. ++$count;
  2516. $this->assertArrayHasKey('generated', $row);
  2517. $this->assertSame('test', $row['generated']);
  2518. }
  2519. $this->assertSame(2, $count);
  2520. }
  2521. /**
  2522. * Tests that functions are correctly transformed and their parameters are bound
  2523. *
  2524. * @group FunctionExpression
  2525. */
  2526. public function testSQLFunctions(): void
  2527. {
  2528. $query = new SelectQuery($this->connection);
  2529. $result = $query->select(
  2530. function ($q) {
  2531. return ['total' => $q->func()->count('*')];
  2532. }
  2533. )
  2534. ->from('comments')
  2535. ->execute();
  2536. $expected = [['total' => 6]];
  2537. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2538. $query = new SelectQuery($this->connection);
  2539. $result = $query->select([
  2540. 'c' => $query->func()->concat(['comment' => 'literal', ' is appended']),
  2541. ])
  2542. ->from('comments')
  2543. ->order(['c' => 'ASC'])
  2544. ->limit(1)
  2545. ->execute();
  2546. $expected = [
  2547. ['c' => 'First Comment for First Article is appended'],
  2548. ];
  2549. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2550. $query = new SelectQuery($this->connection);
  2551. $result = $query
  2552. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2553. ->execute()
  2554. ->fetchAll('assoc');
  2555. $this->assertEquals(3, abs((int)$result[0]['d']));
  2556. $query = new SelectQuery($this->connection);
  2557. $result = $query
  2558. ->select(['d' => $query->func()->now('date')])
  2559. ->execute();
  2560. $result = $result->fetchAll('assoc');
  2561. $this->assertEquals([['d' => date('Y-m-d')]], $result);
  2562. $query = new SelectQuery($this->connection);
  2563. $result = $query
  2564. ->select(['d' => $query->func()->now('time')])
  2565. ->execute();
  2566. $this->assertWithinRange(
  2567. date('U'),
  2568. (new DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2569. 10
  2570. );
  2571. $query = new SelectQuery($this->connection);
  2572. $result = $query
  2573. ->select(['d' => $query->func()->now()])
  2574. ->execute();
  2575. $this->assertWithinRange(
  2576. date('U'),
  2577. (new DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2578. 10
  2579. );
  2580. $query = new SelectQuery($this->connection);
  2581. $result = $query
  2582. ->select([
  2583. 'd' => $query->func()->datePart('day', 'created'),
  2584. 'm' => $query->func()->datePart('month', 'created'),
  2585. 'y' => $query->func()->datePart('year', 'created'),
  2586. 'de' => $query->func()->extract('day', 'created'),
  2587. 'me' => $query->func()->extract('month', 'created'),
  2588. 'ye' => $query->func()->extract('year', 'created'),
  2589. 'wd' => $query->func()->weekday('created'),
  2590. 'dow' => $query->func()->dayOfWeek('created'),
  2591. 'addDays' => $query->func()->dateAdd('created', 2, 'day'),
  2592. 'substractYears' => $query->func()->dateAdd('created', -2, 'year'),
  2593. ])
  2594. ->from('comments')
  2595. ->where(['created' => '2007-03-18 10:45:23'])
  2596. ->execute()
  2597. ->fetchAll('assoc');
  2598. $result[0]['addDays'] = substr($result[0]['addDays'], 0, 10);
  2599. $result[0]['substractYears'] = substr($result[0]['substractYears'], 0, 10);
  2600. $expected = [
  2601. 'd' => 18,
  2602. 'm' => 3,
  2603. 'y' => 2007,
  2604. 'de' => 18,
  2605. 'me' => 3,
  2606. 'ye' => 2007,
  2607. 'wd' => 1, // Sunday
  2608. 'dow' => 1,
  2609. 'addDays' => '2007-03-20',
  2610. 'substractYears' => '2005-03-18',
  2611. ];
  2612. $driver = $this->connection->getDriver();
  2613. if ($driver instanceof Sqlite) {
  2614. $expected = [
  2615. 'd' => '18',
  2616. 'm' => '03',
  2617. 'y' => '2007',
  2618. 'de' => '18',
  2619. 'me' => '03',
  2620. 'ye' => '2007',
  2621. ] + $expected;
  2622. } elseif ($driver instanceof Postgres || $driver instanceof Sqlserver) {
  2623. $expected = array_map(function ($value) {
  2624. return (string)$value;
  2625. }, $expected);
  2626. }
  2627. $this->assertSame($expected, $result[0]);
  2628. }
  2629. /**
  2630. * Tests that the values in tuple comparison expression are being bound correctly,
  2631. * specifically for dialects that translate tuple comparisons.
  2632. *
  2633. * @see \Cake\Database\Driver\TupleComparisonTranslatorTrait::_transformTupleComparison()
  2634. * @see \Cake\Database\Driver\Sqlite::_expressionTranslators()
  2635. * @see \Cake\Database\Driver\Sqlserver::_expressionTranslators()
  2636. */
  2637. public function testTupleComparisonValuesAreBeingBoundCorrectly(): void
  2638. {
  2639. $this->skipIf(
  2640. $this->connection->getDriver() instanceof Sqlserver,
  2641. 'This test fails sporadically in SQLServer'
  2642. );
  2643. $query = (new SelectQuery($this->connection))
  2644. ->select('*')
  2645. ->from('profiles')
  2646. ->where(
  2647. new TupleComparison(
  2648. ['id', 'user_id'],
  2649. [[1, 1]],
  2650. ['integer', 'integer'],
  2651. 'IN'
  2652. )
  2653. );
  2654. $result = $query->all()[0];
  2655. $bindings = array_values($query->getValueBinder()->bindings());
  2656. $this->assertCount(2, $bindings);
  2657. $this->assertSame(1, $bindings[0]['value']);
  2658. $this->assertSame('integer', $bindings[0]['type']);
  2659. $this->assertSame(1, $bindings[1]['value']);
  2660. $this->assertSame('integer', $bindings[1]['type']);
  2661. $this->assertSame(1, $result['id']);
  2662. $this->assertSame(1, $result['user_id']);
  2663. }
  2664. /**
  2665. * Tests that the values in tuple comparison expressions are being bound as expected
  2666. * when types are omitted, specifically for dialects that translate tuple comparisons.
  2667. *
  2668. * @see \Cake\Database\Driver\TupleComparisonTranslatorTrait::_transformTupleComparison()
  2669. * @see \Cake\Database\Driver\Sqlite::_expressionTranslators()
  2670. * @see \Cake\Database\Driver\Sqlserver::_expressionTranslators()
  2671. */
  2672. public function testTupleComparisonTypesCanBeOmitted(): void
  2673. {
  2674. $this->skipIf(
  2675. $this->connection->getDriver() instanceof Sqlserver,
  2676. 'This test fails sporadically in SQLServer'
  2677. );
  2678. $query = (new SelectQuery($this->connection))
  2679. ->select('*')
  2680. ->from('profiles')
  2681. ->where(
  2682. new TupleComparison(
  2683. ['id', 'user_id'],
  2684. [[1, 1]],
  2685. [],
  2686. 'IN'
  2687. )
  2688. );
  2689. $result = $query->all()[0];
  2690. $bindings = array_values($query->getValueBinder()->bindings());
  2691. $this->assertCount(2, $bindings);
  2692. $this->assertSame(1, $bindings[0]['value']);
  2693. $this->assertNull($bindings[0]['type']);
  2694. $this->assertSame(1, $bindings[1]['value']);
  2695. $this->assertNull($bindings[1]['type']);
  2696. $this->assertSame(1, $result['id']);
  2697. $this->assertSame(1, $result['user_id']);
  2698. }
  2699. /**
  2700. * Tests that default types are passed to functions accepting a $types param
  2701. */
  2702. public function testDefaultTypes(): void
  2703. {
  2704. $query = new SelectQuery($this->connection);
  2705. $this->assertEquals([], $query->getDefaultTypes());
  2706. $types = ['id' => 'integer', 'created' => 'datetime'];
  2707. $this->assertSame($query, $query->setDefaultTypes($types));
  2708. $this->assertSame($types, $query->getDefaultTypes());
  2709. $results = $query->select(['id', 'comment'])
  2710. ->from('comments')
  2711. ->where(['created >=' => new DateTime('2007-03-18 10:55:00')])
  2712. ->execute();
  2713. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2714. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2715. // Now test default can be overridden
  2716. $types = ['created' => 'date'];
  2717. $results = $query
  2718. ->where(['created >=' => new DateTime('2007-03-18 10:50:00')], $types, true)
  2719. ->execute();
  2720. $this->assertCount(6, $results->fetchAll(), 'All 6 rows should match.');
  2721. }
  2722. /**
  2723. * Tests parameter binding
  2724. */
  2725. public function testBind(): void
  2726. {
  2727. $query = new SelectQuery($this->connection);
  2728. $results = $query->select(['id', 'comment'])
  2729. ->from('comments')
  2730. ->where(['created BETWEEN :foo AND :bar'])
  2731. ->bind(':foo', new DateTime('2007-03-18 10:50:00'), 'datetime')
  2732. ->bind(':bar', new DateTime('2007-03-18 10:52:00'), 'datetime')
  2733. ->execute();
  2734. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2735. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2736. $query = new SelectQuery($this->connection);
  2737. $results = $query->select(['id', 'comment'])
  2738. ->from('comments')
  2739. ->where(['created BETWEEN :foo AND :bar'])
  2740. ->bind(':foo', '2007-03-18 10:50:00')
  2741. ->bind(':bar', '2007-03-18 10:52:00')
  2742. ->execute();
  2743. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2744. }
  2745. /**
  2746. * Test that epilog() will actually append a string to a select query
  2747. */
  2748. public function testAppendSelect(): void
  2749. {
  2750. $query = new SelectQuery($this->connection);
  2751. $sql = $query
  2752. ->select(['id', 'title'])
  2753. ->from('articles')
  2754. ->where(['id' => 1])
  2755. ->epilog('FOR UPDATE')
  2756. ->sql();
  2757. $this->assertStringContainsString('SELECT', $sql);
  2758. $this->assertStringContainsString('FROM', $sql);
  2759. $this->assertStringContainsString('WHERE', $sql);
  2760. $this->assertSame(' FOR UPDATE', substr($sql, -11));
  2761. }
  2762. /**
  2763. * Tests automatic identifier quoting in the select clause
  2764. */
  2765. public function testQuotingSelectFieldsAndAlias(): void
  2766. {
  2767. $this->connection->getDriver()->enableAutoQuoting(true);
  2768. $query = new SelectQuery($this->connection);
  2769. $sql = $query->select(['something'])->sql();
  2770. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2771. $query = new SelectQuery($this->connection);
  2772. $sql = $query->select(['foo' => 'something'])->sql();
  2773. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2774. $query = new SelectQuery($this->connection);
  2775. $sql = $query->select(['foo' => 1])->sql();
  2776. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2777. $query = new SelectQuery($this->connection);
  2778. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2779. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2780. $query = new SelectQuery($this->connection);
  2781. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2782. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2783. $query = new SelectQuery($this->connection);
  2784. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2785. $this->assertQuotedQuery('<bar>', $sql);
  2786. }
  2787. /**
  2788. * Tests automatic identifier quoting in the from clause
  2789. */
  2790. public function testQuotingFromAndAlias(): void
  2791. {
  2792. $this->connection->getDriver()->enableAutoQuoting(true);
  2793. $query = new SelectQuery($this->connection);
  2794. $sql = $query->select('*')->from(['something'])->sql();
  2795. $this->assertQuotedQuery('FROM <something>', $sql);
  2796. $query = new SelectQuery($this->connection);
  2797. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2798. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  2799. $query = new SelectQuery($this->connection);
  2800. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2801. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  2802. }
  2803. /**
  2804. * Tests automatic identifier quoting for DISTINCT ON
  2805. */
  2806. public function testQuotingDistinctOn(): void
  2807. {
  2808. $this->connection->getDriver()->enableAutoQuoting(true);
  2809. $query = new SelectQuery($this->connection);
  2810. $sql = $query->select('*')->distinct(['something'])->sql();
  2811. $this->assertQuotedQuery('<something>', $sql);
  2812. }
  2813. /**
  2814. * Tests automatic identifier quoting in the join clause
  2815. */
  2816. public function testQuotingJoinsAndAlias(): void
  2817. {
  2818. $this->connection->getDriver()->enableAutoQuoting(true);
  2819. $query = new SelectQuery($this->connection);
  2820. $sql = $query->select('*')->join(['something'])->sql();
  2821. $this->assertQuotedQuery('JOIN <something>', $sql);
  2822. $query = new SelectQuery($this->connection);
  2823. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2824. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2825. $query = new SelectQuery($this->connection);
  2826. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2827. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2828. $query = new SelectQuery($this->connection);
  2829. $sql = $query->select('*')->join([
  2830. 'alias' => 'orders',
  2831. 'table' => 'Order',
  2832. 'conditions' => ['1 = 1'],
  2833. ])->sql();
  2834. $this->assertQuotedQuery('JOIN <Order> <orders> ON 1 = 1', $sql);
  2835. }
  2836. /**
  2837. * Tests automatic identifier quoting in the group by clause
  2838. */
  2839. public function testQuotingGroupBy(): void
  2840. {
  2841. $this->connection->getDriver()->enableAutoQuoting(true);
  2842. $query = new SelectQuery($this->connection);
  2843. $sql = $query->select('*')->group(['something'])->sql();
  2844. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2845. $query = new SelectQuery($this->connection);
  2846. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2847. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2848. $query = new SelectQuery($this->connection);
  2849. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2850. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2851. }
  2852. /**
  2853. * Tests automatic identifier quoting strings inside conditions expressions
  2854. */
  2855. public function testQuotingExpressions(): void
  2856. {
  2857. $this->connection->getDriver()->enableAutoQuoting(true);
  2858. $query = new SelectQuery($this->connection);
  2859. $sql = $query->select('*')
  2860. ->where(['something' => 'value'])
  2861. ->sql();
  2862. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2863. $query = new SelectQuery($this->connection);
  2864. $sql = $query->select('*')
  2865. ->where([
  2866. 'something' => 'value',
  2867. 'OR' => ['foo' => 'bar', 'baz' => 'cake'],
  2868. ])
  2869. ->sql();
  2870. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2871. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2872. }
  2873. /**
  2874. * Tests converting a query to a string
  2875. */
  2876. public function testToString(): void
  2877. {
  2878. $query = new SelectQuery($this->connection);
  2879. $query
  2880. ->select(['title'])
  2881. ->from('articles');
  2882. $result = (string)$query;
  2883. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, !$this->autoQuote);
  2884. }
  2885. /**
  2886. * Tests __debugInfo
  2887. */
  2888. public function testDebugInfo(): void
  2889. {
  2890. $query = (new SelectQuery($this->connection))->select('*')
  2891. ->from('articles')
  2892. ->setDefaultTypes(['id' => 'integer'])
  2893. ->where(['id' => '1']);
  2894. $expected = [
  2895. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2896. 'sql' => $query->sql(),
  2897. 'params' => [
  2898. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0'],
  2899. ],
  2900. 'defaultTypes' => ['id' => 'integer'],
  2901. 'decorators' => 0,
  2902. 'executed' => false,
  2903. ];
  2904. $result = $query->__debugInfo();
  2905. $this->assertEquals($expected, $result);
  2906. $query->execute();
  2907. $expected = [
  2908. '(help)' => 'This is a Query object, to get the results execute or iterate it.',
  2909. 'sql' => $query->sql(),
  2910. 'params' => [
  2911. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0'],
  2912. ],
  2913. 'defaultTypes' => ['id' => 'integer'],
  2914. 'decorators' => 0,
  2915. 'executed' => true,
  2916. ];
  2917. $result = $query->__debugInfo();
  2918. $this->assertEquals($expected, $result);
  2919. }
  2920. /**
  2921. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2922. */
  2923. public function testIsNullWithExpressions(): void
  2924. {
  2925. $query = new SelectQuery($this->connection);
  2926. $subquery = (new SelectQuery($this->connection))
  2927. ->select(['id'])
  2928. ->from('authors')
  2929. ->where(['id' => 1]);
  2930. $result = $query
  2931. ->select(['name'])
  2932. ->from(['authors'])
  2933. ->where(function ($exp) use ($subquery) {
  2934. return $exp->isNotNull($subquery);
  2935. })
  2936. ->execute();
  2937. $this->assertNotEmpty($result->fetchAll('assoc'));
  2938. $result = (new SelectQuery($this->connection))
  2939. ->select(['name'])
  2940. ->from(['authors'])
  2941. ->where(function ($exp) use ($subquery) {
  2942. return $exp->isNull($subquery);
  2943. })
  2944. ->execute();
  2945. $this->assertEmpty($result->fetchAll('assoc'));
  2946. }
  2947. /**
  2948. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2949. * when using autoQuoting
  2950. */
  2951. public function testIsNullAutoQuoting(): void
  2952. {
  2953. $this->connection->getDriver()->enableAutoQuoting(true);
  2954. $query = new SelectQuery($this->connection);
  2955. $query->select('*')->from('things')->where(function ($exp) {
  2956. return $exp->isNull('field');
  2957. });
  2958. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2959. $query = new SelectQuery($this->connection);
  2960. $query->select('*')->from('things')->where(function ($exp) {
  2961. return $exp->isNotNull('field');
  2962. });
  2963. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2964. }
  2965. /**
  2966. * Tests that using the IS operator will automatically translate to the best
  2967. * possible operator depending on the passed value
  2968. */
  2969. public function testDirectIsNull(): void
  2970. {
  2971. $sql = (new SelectQuery($this->connection))
  2972. ->select(['name'])
  2973. ->from(['authors'])
  2974. ->where(['name IS' => null])
  2975. ->sql();
  2976. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, !$this->autoQuote);
  2977. $result = (new SelectQuery($this->connection))
  2978. ->select(['name'])
  2979. ->from(['authors'])
  2980. ->where(['name IS' => 'larry'])
  2981. ->execute();
  2982. $rows = $result->fetchAll('assoc');
  2983. $this->assertCount(1, $rows);
  2984. $this->assertEquals(['name' => 'larry'], $rows[0]);
  2985. }
  2986. /**
  2987. * Tests that using the wrong NULL operator will throw meaningful exception instead of
  2988. * cloaking as always-empty result set.
  2989. */
  2990. public function testIsNullInvalid(): void
  2991. {
  2992. $this->expectException(InvalidArgumentException::class);
  2993. $this->expectExceptionMessage('Expression `name` is missing operator (IS, IS NOT) with `null` value.');
  2994. (new SelectQuery($this->connection))
  2995. ->select(['name'])
  2996. ->from(['authors'])
  2997. ->where(['name' => null])
  2998. ->sql();
  2999. }
  3000. /**
  3001. * Tests that using the wrong NULL operator will throw meaningful exception instead of
  3002. * cloaking as always-empty result set.
  3003. */
  3004. public function testIsNotNullInvalid(): void
  3005. {
  3006. $this->expectException(InvalidArgumentException::class);
  3007. (new SelectQuery($this->connection))
  3008. ->select(['name'])
  3009. ->from(['authors'])
  3010. ->where(['name !=' => null])
  3011. ->sql();
  3012. }
  3013. /**
  3014. * Tests that using the IS NOT operator will automatically translate to the best
  3015. * possible operator depending on the passed value
  3016. */
  3017. public function testDirectIsNotNull(): void
  3018. {
  3019. $sql = (new SelectQuery($this->connection))
  3020. ->select(['name'])
  3021. ->from(['authors'])
  3022. ->where(['name IS NOT' => null])
  3023. ->sql();
  3024. $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, !$this->autoQuote);
  3025. $results = (new SelectQuery($this->connection))
  3026. ->select(['name'])
  3027. ->from(['authors'])
  3028. ->where(['name IS NOT' => 'larry'])
  3029. ->execute()
  3030. ->fetchAll('assoc');
  3031. $this->assertCount(3, $results);
  3032. $this->assertNotEquals(['name' => 'larry'], $results[0]);
  3033. }
  3034. public function testCloneWithExpression(): void
  3035. {
  3036. $query = new SelectQuery($this->connection);
  3037. $query
  3038. ->with(
  3039. new CommonTableExpression(
  3040. 'cte',
  3041. new SelectQuery($this->connection)
  3042. )
  3043. )
  3044. ->with(function (CommonTableExpression $cte, Query $query) {
  3045. return $cte
  3046. ->name('cte2')
  3047. ->query($query);
  3048. });
  3049. $clause = $query->clause('with');
  3050. $clauseClone = (clone $query)->clause('with');
  3051. $this->assertIsArray($clause);
  3052. foreach ($clause as $key => $value) {
  3053. $this->assertEquals($value, $clauseClone[$key]);
  3054. $this->assertNotSame($value, $clauseClone[$key]);
  3055. }
  3056. }
  3057. public function testCloneSelectExpression(): void
  3058. {
  3059. $query = new SelectQuery($this->connection);
  3060. $query
  3061. ->select($query->newExpr('select'))
  3062. ->select(['alias' => $query->newExpr('select')]);
  3063. $clause = $query->clause('select');
  3064. $clauseClone = (clone $query)->clause('select');
  3065. $this->assertIsArray($clause);
  3066. foreach ($clause as $key => $value) {
  3067. $this->assertEquals($value, $clauseClone[$key]);
  3068. $this->assertNotSame($value, $clauseClone[$key]);
  3069. }
  3070. }
  3071. public function testCloneDistinctExpression(): void
  3072. {
  3073. $query = new SelectQuery($this->connection);
  3074. $query->distinct($query->newExpr('distinct'));
  3075. $clause = $query->clause('distinct');
  3076. $clauseClone = (clone $query)->clause('distinct');
  3077. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3078. $this->assertEquals($clause, $clauseClone);
  3079. $this->assertNotSame($clause, $clauseClone);
  3080. }
  3081. public function testCloneModifierExpression(): void
  3082. {
  3083. $query = new SelectQuery($this->connection);
  3084. $query->modifier($query->newExpr('modifier'));
  3085. $clause = $query->clause('modifier');
  3086. $clauseClone = (clone $query)->clause('modifier');
  3087. $this->assertIsArray($clause);
  3088. foreach ($clause as $key => $value) {
  3089. $this->assertEquals($value, $clauseClone[$key]);
  3090. $this->assertNotSame($value, $clauseClone[$key]);
  3091. }
  3092. }
  3093. public function testCloneFromExpression(): void
  3094. {
  3095. $query = new SelectQuery($this->connection);
  3096. $query->from(['alias' => new SelectQuery($this->connection)]);
  3097. $clause = $query->clause('from');
  3098. $clauseClone = (clone $query)->clause('from');
  3099. $this->assertIsArray($clause);
  3100. foreach ($clause as $key => $value) {
  3101. $this->assertEquals($value, $clauseClone[$key]);
  3102. $this->assertNotSame($value, $clauseClone[$key]);
  3103. }
  3104. }
  3105. public function testCloneJoinExpression(): void
  3106. {
  3107. $query = new SelectQuery($this->connection);
  3108. $query
  3109. ->innerJoin(
  3110. ['alias_inner' => new SelectQuery($this->connection)],
  3111. ['alias_inner.fk = parent.pk']
  3112. )
  3113. ->leftJoin(
  3114. ['alias_left' => new SelectQuery($this->connection)],
  3115. ['alias_left.fk = parent.pk']
  3116. )
  3117. ->rightJoin(
  3118. ['alias_right' => new SelectQuery($this->connection)],
  3119. ['alias_right.fk = parent.pk']
  3120. );
  3121. $clause = $query->clause('join');
  3122. $clauseClone = (clone $query)->clause('join');
  3123. $this->assertIsArray($clause);
  3124. foreach ($clause as $key => $value) {
  3125. $this->assertEquals($value['table'], $clauseClone[$key]['table']);
  3126. $this->assertNotSame($value['table'], $clauseClone[$key]['table']);
  3127. $this->assertEquals($value['conditions'], $clauseClone[$key]['conditions']);
  3128. $this->assertNotSame($value['conditions'], $clauseClone[$key]['conditions']);
  3129. }
  3130. }
  3131. public function testCloneWhereExpression(): void
  3132. {
  3133. $query = new SelectQuery($this->connection);
  3134. $query
  3135. ->where($query->newExpr('where'))
  3136. ->where(['field' => $query->newExpr('where')]);
  3137. $clause = $query->clause('where');
  3138. $clauseClone = (clone $query)->clause('where');
  3139. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3140. $this->assertEquals($clause, $clauseClone);
  3141. $this->assertNotSame($clause, $clauseClone);
  3142. }
  3143. public function testCloneGroupExpression(): void
  3144. {
  3145. $query = new SelectQuery($this->connection);
  3146. $query->group($query->newExpr('group'));
  3147. $clause = $query->clause('group');
  3148. $clauseClone = (clone $query)->clause('group');
  3149. $this->assertIsArray($clause);
  3150. foreach ($clause as $key => $value) {
  3151. $this->assertEquals($value, $clauseClone[$key]);
  3152. $this->assertNotSame($value, $clauseClone[$key]);
  3153. }
  3154. }
  3155. public function testCloneHavingExpression(): void
  3156. {
  3157. $query = new SelectQuery($this->connection);
  3158. $query->having($query->newExpr('having'));
  3159. $clause = $query->clause('having');
  3160. $clauseClone = (clone $query)->clause('having');
  3161. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3162. $this->assertEquals($clause, $clauseClone);
  3163. $this->assertNotSame($clause, $clauseClone);
  3164. }
  3165. public function testCloneWindowExpression(): void
  3166. {
  3167. $query = new SelectQuery($this->connection);
  3168. $query
  3169. ->window('window1', new WindowExpression())
  3170. ->window('window2', function (WindowExpression $window) {
  3171. return $window;
  3172. });
  3173. $clause = $query->clause('window');
  3174. $clauseClone = (clone $query)->clause('window');
  3175. $this->assertIsArray($clause);
  3176. foreach ($clause as $key => $value) {
  3177. $this->assertEquals($value['name'], $clauseClone[$key]['name']);
  3178. $this->assertNotSame($value['name'], $clauseClone[$key]['name']);
  3179. $this->assertEquals($value['window'], $clauseClone[$key]['window']);
  3180. $this->assertNotSame($value['window'], $clauseClone[$key]['window']);
  3181. }
  3182. }
  3183. public function testCloneOrderExpression(): void
  3184. {
  3185. $query = new SelectQuery($this->connection);
  3186. $query
  3187. ->order($query->newExpr('order'))
  3188. ->orderAsc($query->newExpr('order_asc'))
  3189. ->orderDesc($query->newExpr('order_desc'));
  3190. $clause = $query->clause('order');
  3191. $clauseClone = (clone $query)->clause('order');
  3192. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3193. $this->assertEquals($clause, $clauseClone);
  3194. $this->assertNotSame($clause, $clauseClone);
  3195. }
  3196. public function testCloneLimitExpression(): void
  3197. {
  3198. $query = new SelectQuery($this->connection);
  3199. $query->limit($query->newExpr('1'));
  3200. $clause = $query->clause('limit');
  3201. $clauseClone = (clone $query)->clause('limit');
  3202. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3203. $this->assertEquals($clause, $clauseClone);
  3204. $this->assertNotSame($clause, $clauseClone);
  3205. }
  3206. public function testCloneOffsetExpression(): void
  3207. {
  3208. $query = new SelectQuery($this->connection);
  3209. $query->offset($query->newExpr('1'));
  3210. $clause = $query->clause('offset');
  3211. $clauseClone = (clone $query)->clause('offset');
  3212. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3213. $this->assertEquals($clause, $clauseClone);
  3214. $this->assertNotSame($clause, $clauseClone);
  3215. }
  3216. public function testCloneUnionExpression(): void
  3217. {
  3218. $query = new SelectQuery($this->connection);
  3219. $query->where(['id' => 1]);
  3220. $query2 = new SelectQuery($this->connection);
  3221. $query2->where(['id' => 2]);
  3222. $query->union($query2);
  3223. $clause = $query->clause('union');
  3224. $clauseClone = (clone $query)->clause('union');
  3225. $this->assertIsArray($clause);
  3226. foreach ($clause as $key => $value) {
  3227. $this->assertEquals($value['query'], $clauseClone[$key]['query']);
  3228. $this->assertNotSame($value['query'], $clauseClone[$key]['query']);
  3229. }
  3230. }
  3231. public function testCloneEpilogExpression(): void
  3232. {
  3233. $query = new SelectQuery($this->connection);
  3234. $query->epilog($query->newExpr('epilog'));
  3235. $clause = $query->clause('epilog');
  3236. $clauseClone = (clone $query)->clause('epilog');
  3237. $this->assertInstanceOf(ExpressionInterface::class, $clause);
  3238. $this->assertEquals($clause, $clauseClone);
  3239. $this->assertNotSame($clause, $clauseClone);
  3240. }
  3241. /**
  3242. * Test that cloning goes deep.
  3243. */
  3244. public function testDeepClone(): void
  3245. {
  3246. $query = new SelectQuery($this->connection);
  3247. $query->select(['id', 'title' => $query->func()->concat(['title' => 'literal', 'test'])])
  3248. ->from('articles')
  3249. ->where(['Articles.id' => 1])
  3250. ->offset(10)
  3251. ->limit(1)
  3252. ->order(['Articles.id' => 'DESC']);
  3253. $dupe = clone $query;
  3254. $this->assertEquals($query->clause('where'), $dupe->clause('where'));
  3255. $this->assertNotSame($query->clause('where'), $dupe->clause('where'));
  3256. $dupe->where(['Articles.title' => 'thinger']);
  3257. $this->assertNotEquals($query->clause('where'), $dupe->clause('where'));
  3258. $this->assertNotSame(
  3259. $query->clause('select')['title'],
  3260. $dupe->clause('select')['title']
  3261. );
  3262. $this->assertEquals($query->clause('order'), $dupe->clause('order'));
  3263. $this->assertNotSame($query->clause('order'), $dupe->clause('order'));
  3264. $query->order(['Articles.title' => 'ASC']);
  3265. $this->assertNotEquals($query->clause('order'), $dupe->clause('order'));
  3266. $this->assertNotSame(
  3267. $query->getSelectTypeMap(),
  3268. $dupe->getSelectTypeMap()
  3269. );
  3270. }
  3271. /**
  3272. * Tests the selectTypeMap method
  3273. */
  3274. public function testSelectTypeMap(): void
  3275. {
  3276. $query = new SelectQuery($this->connection);
  3277. $typeMap = $query->getSelectTypeMap();
  3278. $this->assertInstanceOf(TypeMap::class, $typeMap);
  3279. $another = clone $typeMap;
  3280. $query->setSelectTypeMap($another);
  3281. $this->assertSame($another, $query->getSelectTypeMap());
  3282. }
  3283. /**
  3284. * Tests the automatic type conversion for the fields in the result
  3285. */
  3286. public function testSelectTypeConversion(): void
  3287. {
  3288. TypeFactory::set('custom_datetime', new BarType('custom_datetime'));
  3289. $query = new SelectQuery($this->connection);
  3290. $query
  3291. ->select(['id', 'comment', 'the_date' => 'created', 'updated'])
  3292. ->from('comments')
  3293. ->limit(1)
  3294. ->getSelectTypeMap()
  3295. ->setTypes([
  3296. 'id' => 'integer',
  3297. 'the_date' => 'datetime',
  3298. 'updated' => 'custom_datetime',
  3299. ]);
  3300. $result = $query->execute()->fetchAll('assoc');
  3301. $this->assertIsInt($result[0]['id']);
  3302. $this->assertInstanceOf(DateTimeImmutable::class, $result[0]['the_date']);
  3303. $this->assertInstanceOf(DateTimeImmutable::class, $result[0]['updated']);
  3304. }
  3305. /**
  3306. * Test removeJoin().
  3307. */
  3308. public function testRemoveJoin(): void
  3309. {
  3310. $query = new SelectQuery($this->connection);
  3311. $query->select(['id', 'title'])
  3312. ->from('articles')
  3313. ->join(['authors' => [
  3314. 'type' => 'INNER',
  3315. 'conditions' => ['articles.author_id = authors.id'],
  3316. ]]);
  3317. $this->assertArrayHasKey('authors', $query->clause('join'));
  3318. $this->assertSame($query, $query->removeJoin('authors'));
  3319. $this->assertArrayNotHasKey('authors', $query->clause('join'));
  3320. }
  3321. /**
  3322. * Tests that types in the type map are used in the
  3323. * specific comparison functions when using a callable
  3324. */
  3325. public function testBetweenExpressionAndTypeMap(): void
  3326. {
  3327. $query = new SelectQuery($this->connection);
  3328. $query->select('id')
  3329. ->from('comments')
  3330. ->setDefaultTypes(['created' => 'datetime'])
  3331. ->where(function ($expr) {
  3332. $from = new DateTime('2007-03-18 10:45:00');
  3333. $to = new DateTime('2007-03-18 10:48:00');
  3334. return $expr->between('created', $from, $to);
  3335. });
  3336. $this->assertCount(2, $query->execute()->fetchAll());
  3337. }
  3338. /**
  3339. * Test automatic results casting
  3340. */
  3341. public function testCastResults(): void
  3342. {
  3343. $query = new SelectQuery($this->connection);
  3344. $fields = [
  3345. 'user_id' => 'integer',
  3346. 'is_active' => 'boolean',
  3347. ];
  3348. $typeMap = new TypeMap($fields + ['a' => 'integer']);
  3349. $results = $query
  3350. ->select(array_keys($fields))
  3351. ->select(['a' => 'is_active'])
  3352. ->from('profiles')
  3353. ->setSelectTypeMap($typeMap)
  3354. ->where(['user_id' => 1])
  3355. ->execute()
  3356. ->fetchAll('assoc');
  3357. $this->assertSame([['user_id' => 1, 'is_active' => false, 'a' => 0]], $results);
  3358. }
  3359. /**
  3360. * Test disabling type casting
  3361. */
  3362. public function testCastResultsDisable(): void
  3363. {
  3364. $query = new SelectQuery($this->connection);
  3365. $typeMap = new TypeMap(['a' => 'datetime']);
  3366. $results = $query
  3367. ->select(['a' => 'id'])
  3368. ->from('profiles')
  3369. ->setSelectTypeMap($typeMap)
  3370. ->limit(1)
  3371. ->disableResultsCasting()
  3372. ->execute()
  3373. ->fetchAll('assoc');
  3374. $this->assertEquals([['a' => '1']], $results);
  3375. }
  3376. /**
  3377. * Test obtaining the current results casting mode.
  3378. */
  3379. public function testObtainingResultsCastingMode(): void
  3380. {
  3381. $query = new SelectQuery($this->connection);
  3382. $this->assertTrue($query->isResultsCastingEnabled());
  3383. $query->disableResultsCasting();
  3384. $this->assertFalse($query->isResultsCastingEnabled());
  3385. }
  3386. /**
  3387. * Test that type conversion is only applied once.
  3388. */
  3389. public function testAllNoDuplicateTypeCasting(): void
  3390. {
  3391. $this->skipIf($this->autoQuote, 'Produces bad SQL in postgres with autoQuoting');
  3392. $query = new SelectQuery($this->connection);
  3393. $query
  3394. ->select('1.5 AS a')
  3395. ->setSelectTypeMap(new TypeMap(['a' => 'integer']));
  3396. // Convert to an array and make the query dirty again.
  3397. $result = $query->execute()->fetchAll('assoc');
  3398. $this->assertEquals([['a' => 1]], $result);
  3399. $query->setSelectTypeMap(new TypeMap(['a' => 'float']));
  3400. // Get results a second time.
  3401. $result = $query->execute()->fetchAll('assoc');
  3402. // Had the type casting being remembered from the first time,
  3403. // The value would be a truncated float (1.0)
  3404. $this->assertEquals([['a' => 1.5]], $result);
  3405. }
  3406. /**
  3407. * Test that calling fetchAssoc return an associated array.
  3408. *
  3409. * @throws \Exception
  3410. */
  3411. public function testFetchAssoc(): void
  3412. {
  3413. $query = new SelectQuery($this->connection);
  3414. $fields = [
  3415. 'id' => 'integer',
  3416. 'user_id' => 'integer',
  3417. 'is_active' => 'boolean',
  3418. ];
  3419. $typeMap = new TypeMap($fields);
  3420. $statement = $query
  3421. ->select([
  3422. 'id',
  3423. 'user_id',
  3424. 'is_active',
  3425. ])
  3426. ->from('profiles')
  3427. ->setSelectTypeMap($typeMap)
  3428. ->limit(1)
  3429. ->execute();
  3430. $this->assertSame(['id' => 1, 'user_id' => 1, 'is_active' => false], $statement->fetchAssoc());
  3431. $statement->closeCursor();
  3432. }
  3433. /**
  3434. * Test that calling fetchAssoc return an empty associated array.
  3435. *
  3436. * @throws \Exception
  3437. */
  3438. public function testFetchAssocWithEmptyResult(): void
  3439. {
  3440. $query = new SelectQuery($this->connection);
  3441. $results = $query
  3442. ->select(['id'])
  3443. ->from('profiles')
  3444. ->where(['id' => -1])
  3445. ->execute()
  3446. ->fetchAssoc();
  3447. $this->assertSame([], $results);
  3448. }
  3449. /**
  3450. * Test that calling fetch with with FETCH_TYPE_OBJ return stdClass object.
  3451. *
  3452. * @throws \Exception
  3453. */
  3454. public function testFetchObjects(): void
  3455. {
  3456. $query = new SelectQuery($this->connection);
  3457. $stmt = $query->select([
  3458. 'id',
  3459. 'user_id',
  3460. 'is_active',
  3461. ])
  3462. ->from('profiles')
  3463. ->limit(1)
  3464. ->execute();
  3465. $results = $stmt->fetch('obj');
  3466. $stmt->closeCursor();
  3467. $this->assertInstanceOf(stdClass::class, $results);
  3468. }
  3469. /**
  3470. * Test that fetchColumn() will return the correct value at $position.
  3471. *
  3472. * @throws \Exception
  3473. */
  3474. public function testFetchColumn(): void
  3475. {
  3476. $query = new SelectQuery($this->connection);
  3477. $fields = [
  3478. 'integer',
  3479. 'integer',
  3480. 'boolean',
  3481. ];
  3482. $typeMap = new TypeMap($fields);
  3483. $query
  3484. ->select([
  3485. 'id',
  3486. 'user_id',
  3487. 'is_active',
  3488. ])
  3489. ->from('profiles')
  3490. ->setSelectTypeMap($typeMap)
  3491. ->where(['id' => 2])
  3492. ->limit(1);
  3493. $statement = $query->execute();
  3494. $results = $statement->fetchColumn(0);
  3495. $this->assertSame(2, $results);
  3496. $statement->closeCursor();
  3497. $statement = $query->execute();
  3498. $results = $statement->fetchColumn(1);
  3499. $this->assertSame(2, $results);
  3500. $statement->closeCursor();
  3501. $statement = $query->execute();
  3502. $results = $statement->fetchColumn(2);
  3503. $this->assertSame(false, $results);
  3504. $statement->closeCursor();
  3505. }
  3506. /**
  3507. * Test that fetchColumn() will return false if $position is not set.
  3508. *
  3509. * @throws \Exception
  3510. */
  3511. public function testFetchColumnReturnsFalse(): void
  3512. {
  3513. $query = new SelectQuery($this->connection);
  3514. $fields = [
  3515. 'integer',
  3516. 'integer',
  3517. 'boolean',
  3518. ];
  3519. $typeMap = new TypeMap($fields);
  3520. $query
  3521. ->select([
  3522. 'id',
  3523. 'user_id',
  3524. 'is_active',
  3525. ])
  3526. ->from('profiles')
  3527. ->setSelectTypeMap($typeMap)
  3528. ->where(['id' => 2])
  3529. ->limit(1);
  3530. $statement = $query->execute();
  3531. $results = $statement->fetchColumn(3);
  3532. $this->assertFalse($results);
  3533. $statement->closeCursor();
  3534. }
  3535. /**
  3536. * Tests that query expressions can be used for ordering.
  3537. */
  3538. public function testOrderBySubquery(): void
  3539. {
  3540. $this->autoQuote = true;
  3541. $this->connection->getDriver()->enableAutoQuoting($this->autoQuote);
  3542. $connection = $this->connection;
  3543. $query = new SelectQuery($connection);
  3544. $stmt = $connection->update('articles', ['published' => 'N'], ['id' => 3]);
  3545. $stmt->closeCursor();
  3546. $subquery = new SelectQuery($connection);
  3547. $subquery
  3548. ->select(
  3549. $subquery->newExpr()->case()->when(['a.published' => 'N'])->then(1)->else(0)
  3550. )
  3551. ->from(['a' => 'articles'])
  3552. ->where([
  3553. 'a.id = articles.id',
  3554. ]);
  3555. $query
  3556. ->select(['id'])
  3557. ->from('articles')
  3558. ->orderDesc($subquery)
  3559. ->orderAsc('id')
  3560. ->setSelectTypeMap(new TypeMap([
  3561. 'id' => 'integer',
  3562. ]));
  3563. $this->assertQuotedQuery(
  3564. 'SELECT <id> FROM <articles> ORDER BY \(' .
  3565. 'SELECT \(CASE WHEN <a>\.<published> = \:c0 THEN \:c1 ELSE \:c2 END\) ' .
  3566. 'FROM <articles> <a> ' .
  3567. 'WHERE a\.id = articles\.id' .
  3568. '\) DESC, <id> ASC',
  3569. $query->sql(),
  3570. !$this->autoQuote
  3571. );
  3572. $this->assertEquals(
  3573. [
  3574. [
  3575. 'id' => 3,
  3576. ],
  3577. [
  3578. 'id' => 1,
  3579. ],
  3580. [
  3581. 'id' => 2,
  3582. ],
  3583. ],
  3584. $query->execute()->fetchAll('assoc')
  3585. );
  3586. }
  3587. /**
  3588. * Test that reusing expressions will duplicate bindings and run successfully.
  3589. *
  3590. * This replicates what the SQL Server driver would do for <= SQL Server 2008
  3591. * when ordering on fields that are expressions.
  3592. *
  3593. * @see \Cake\Database\Driver\Sqlserver::_pagingSubquery()
  3594. */
  3595. public function testReusingExpressions(): void
  3596. {
  3597. $connection = $this->connection;
  3598. $query = new SelectQuery($connection);
  3599. $stmt = $connection->update('articles', ['published' => 'N'], ['id' => 3]);
  3600. $stmt->closeCursor();
  3601. $subqueryA = new SelectQuery($connection);
  3602. $subqueryA
  3603. ->select('count(*)')
  3604. ->from(['a' => 'articles'])
  3605. ->where([
  3606. 'a.id = articles.id',
  3607. 'a.published' => 'Y',
  3608. ]);
  3609. $subqueryB = new SelectQuery($connection);
  3610. $subqueryB
  3611. ->select('count(*)')
  3612. ->from(['b' => 'articles'])
  3613. ->where([
  3614. 'b.id = articles.id',
  3615. 'b.published' => 'N',
  3616. ]);
  3617. $query
  3618. ->select([
  3619. 'id',
  3620. 'computedA' => $subqueryA,
  3621. 'computedB' => $subqueryB,
  3622. ])
  3623. ->from('articles')
  3624. ->orderDesc($subqueryB)
  3625. ->orderAsc('id')
  3626. ->setSelectTypeMap(new TypeMap([
  3627. 'id' => 'integer',
  3628. 'computedA' => 'integer',
  3629. 'computedB' => 'integer',
  3630. ]));
  3631. $this->assertQuotedQuery(
  3632. 'SELECT <id>, ' .
  3633. '\(SELECT count\(\*\) FROM <articles> <a> WHERE \(a\.id = articles\.id AND <a>\.<published> = :c0\)\) AS <computedA>, ' .
  3634. '\(SELECT count\(\*\) FROM <articles> <b> WHERE \(b\.id = articles\.id AND <b>\.<published> = :c1\)\) AS <computedB> ' .
  3635. 'FROM <articles> ' .
  3636. 'ORDER BY \(' .
  3637. 'SELECT count\(\*\) FROM <articles> <b> WHERE \(b\.id = articles\.id AND <b>\.<published> = :c2\)' .
  3638. '\) DESC, <id> ASC',
  3639. $query->sql(),
  3640. !$this->autoQuote
  3641. );
  3642. $this->assertSame(
  3643. [
  3644. [
  3645. 'id' => 3,
  3646. 'computedA' => 0,
  3647. 'computedB' => 1,
  3648. ],
  3649. [
  3650. 'id' => 1,
  3651. 'computedA' => 1,
  3652. 'computedB' => 0,
  3653. ],
  3654. [
  3655. 'id' => 2,
  3656. 'computedA' => 1,
  3657. 'computedB' => 0,
  3658. ],
  3659. ],
  3660. $query->execute()->fetchAll('assoc')
  3661. );
  3662. $this->assertSame(
  3663. [
  3664. ':c0' => [
  3665. 'value' => 'Y',
  3666. 'type' => null,
  3667. 'placeholder' => 'c0',
  3668. ],
  3669. ':c1' => [
  3670. 'value' => 'N',
  3671. 'type' => null,
  3672. 'placeholder' => 'c1',
  3673. ],
  3674. ':c2' => [
  3675. 'value' => 'N',
  3676. 'type' => null,
  3677. 'placeholder' => 'c2',
  3678. ],
  3679. ],
  3680. $query->getValueBinder()->bindings()
  3681. );
  3682. }
  3683. /**
  3684. * Tests creating StringExpression.
  3685. */
  3686. public function testStringExpression(): void
  3687. {
  3688. $driver = $this->connection->getDriver();
  3689. $collation = null;
  3690. if ($driver instanceof Mysql) {
  3691. if (version_compare($this->connection->getDriver()->version(), '5.7.0', '<')) {
  3692. $collation = 'utf8_general_ci';
  3693. } else {
  3694. $collation = 'utf8mb4_general_ci';
  3695. }
  3696. } elseif ($driver instanceof Postgres) {
  3697. $collation = 'en_US.utf8';
  3698. } elseif ($driver instanceof Sqlite) {
  3699. $collation = 'BINARY';
  3700. } elseif ($driver instanceof Sqlserver) {
  3701. $collation = 'Latin1_general_CI_AI';
  3702. }
  3703. $query = new SelectQuery($this->connection);
  3704. if ($driver instanceof Postgres) {
  3705. // Older postgres versions throw an error on the parameter type without a cast
  3706. $query->select(['test_string' => $query->func()->cast(new StringExpression('testString', $collation), 'text')]);
  3707. $expected = "SELECT \(CAST\(:c0 COLLATE \"{$collation}\" AS text\)\) AS <test_string>";
  3708. } else {
  3709. $query->select(['test_string' => new StringExpression('testString', $collation)]);
  3710. $expected = "SELECT \(:c0 COLLATE {$collation}\) AS <test_string>";
  3711. }
  3712. $this->assertRegExpSql($expected, $query->sql(new ValueBinder()), !$this->autoQuote);
  3713. $statement = $query->execute();
  3714. $this->assertSame('testString', $statement->fetchColumn(0));
  3715. $statement->closeCursor();
  3716. }
  3717. /**
  3718. * Tests setting identifier collation.
  3719. */
  3720. public function testIdentifierCollation(): void
  3721. {
  3722. $driver = $this->connection->getDriver();
  3723. $collation = null;
  3724. if ($driver instanceof Mysql) {
  3725. if (version_compare($this->connection->getDriver()->version(), '5.7.0', '<')) {
  3726. $collation = 'utf8_general_ci';
  3727. } else {
  3728. $collation = 'utf8mb4_general_ci';
  3729. }
  3730. } elseif ($driver instanceof Postgres) {
  3731. $collation = 'en_US.utf8';
  3732. } elseif ($driver instanceof Sqlite) {
  3733. $collation = 'BINARY';
  3734. } elseif ($driver instanceof Sqlserver) {
  3735. $collation = 'Latin1_general_CI_AI';
  3736. }
  3737. $query = (new SelectQuery($this->connection))
  3738. ->select(['test_string' => new IdentifierExpression('title', $collation)])
  3739. ->from('articles')
  3740. ->where(['id' => 1]);
  3741. if ($driver instanceof Postgres) {
  3742. // Older postgres versions throw an error on the parameter type without a cast
  3743. $expected = "SELECT \(<title> COLLATE \"{$collation}\"\) AS <test_string>";
  3744. } else {
  3745. $expected = "SELECT \(<title> COLLATE {$collation}\) AS <test_string>";
  3746. }
  3747. $this->assertRegExpSql($expected, $query->sql(new ValueBinder()), !$this->autoQuote);
  3748. $statement = $query->execute();
  3749. $this->assertSame('First Article', $statement->fetchColumn(0));
  3750. $statement->closeCursor();
  3751. }
  3752. /**
  3753. * Simple expressions from the point of view of the query expression
  3754. * object are expressions where the field contains one space at most.
  3755. */
  3756. public function testOperatorsInSimpleConditionsAreCaseInsensitive(): void
  3757. {
  3758. $query = (new SelectQuery($this->connection))
  3759. ->select('id')
  3760. ->from('articles')
  3761. ->where(['id in' => [1, 2, 3]]);
  3762. $this->assertQuotedQuery(
  3763. 'SELECT <id> FROM <articles> WHERE <id> IN \(:c0,:c1,:c2\)',
  3764. $query->sql(),
  3765. !$this->autoQuote
  3766. );
  3767. $query = (new SelectQuery($this->connection))
  3768. ->select('id')
  3769. ->from('articles')
  3770. ->where(['id IN' => [1, 2, 3]]);
  3771. $this->assertQuotedQuery(
  3772. 'SELECT <id> FROM <articles> WHERE <id> IN \(:c0,:c1,:c2\)',
  3773. $query->sql(),
  3774. !$this->autoQuote
  3775. );
  3776. }
  3777. /**
  3778. * Complex expressions from the point of view of the query expression
  3779. * object are expressions where the field contains multiple spaces.
  3780. */
  3781. public function testOperatorsInComplexConditionsAreCaseInsensitive(): void
  3782. {
  3783. $this->skipIf($this->autoQuote, 'Does not work when autoquoting is enabled.');
  3784. $query = (new SelectQuery($this->connection))
  3785. ->select('id')
  3786. ->from('profiles')
  3787. ->where(['CONCAT(first_name, " ", last_name) in' => ['foo bar', 'baz 42']]);
  3788. $this->assertSame(
  3789. 'SELECT id FROM profiles WHERE CONCAT\(first_name, " ", last_name\) in \(:c0,:c1\)',
  3790. $query->sql()
  3791. );
  3792. $query = (new SelectQuery($this->connection))
  3793. ->select('id')
  3794. ->from('profiles')
  3795. ->where(['CONCAT(first_name, " ", last_name) IN' => ['foo bar', 'baz 42']]);
  3796. $this->assertSame(
  3797. 'SELECT id FROM profiles WHERE CONCAT\(first_name, " ", last_name\) in \(:c0,:c1\)',
  3798. $query->sql()
  3799. );
  3800. $query = (new SelectQuery($this->connection))
  3801. ->select('id')
  3802. ->from('profiles')
  3803. ->where(['CONCAT(first_name, " ", last_name) not in' => ['foo bar', 'baz 42']]);
  3804. $this->assertSame(
  3805. 'SELECT id FROM profiles WHERE CONCAT\(first_name, " ", last_name\) not in \(:c0,:c1\)',
  3806. $query->sql()
  3807. );
  3808. $query = (new SelectQuery($this->connection))
  3809. ->select('id')
  3810. ->from('profiles')
  3811. ->where(['CONCAT(first_name, " ", last_name) NOT IN' => ['foo bar', 'baz 42']]);
  3812. $this->assertSame(
  3813. 'SELECT id FROM profiles WHERE CONCAT\(first_name, " ", last_name\) not in \(:c0,:c1\)',
  3814. $query->sql()
  3815. );
  3816. }
  3817. }