QueryTest.php 108 KB

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