SelectQueryTest.php 146 KB

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