SelectQueryTest.php 147 KB

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