QueryTest.php 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232
  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. $this->skipIf(
  1352. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver,
  1353. 'Not implemented yet in SqlServer'
  1354. );
  1355. $query = new Query($this->connection);
  1356. $result = $query
  1357. ->select(['id', 'author_id'])
  1358. ->distinct(['author_id'])
  1359. ->from(['a' => 'articles'])
  1360. ->execute();
  1361. $this->assertCount(2, $result);
  1362. }
  1363. /**
  1364. * Test use of modifiers in the query
  1365. *
  1366. * Testing the generated SQL since the modifiers are usually different per driver
  1367. *
  1368. * @return void
  1369. */
  1370. public function testSelectModifiers()
  1371. {
  1372. $query = new Query($this->connection);
  1373. $result = $query
  1374. ->select(['city', 'state', 'country'])
  1375. ->from(['addresses'])
  1376. ->modifier('DISTINCTROW');
  1377. $this->assertQuotedQuery(
  1378. 'SELECT DISTINCTROW <city>, <state>, <country> FROM <addresses>',
  1379. $result->sql(),
  1380. true
  1381. );
  1382. $query = new Query($this->connection);
  1383. $result = $query
  1384. ->select(['city', 'state', 'country'])
  1385. ->from(['addresses'])
  1386. ->modifier(['DISTINCTROW', 'SQL_NO_CACHE']);
  1387. $this->assertQuotedQuery(
  1388. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1389. $result->sql(),
  1390. true
  1391. );
  1392. $query = new Query($this->connection);
  1393. $result = $query
  1394. ->select(['city', 'state', 'country'])
  1395. ->from(['addresses'])
  1396. ->modifier('DISTINCTROW')
  1397. ->modifier('SQL_NO_CACHE');
  1398. $this->assertQuotedQuery(
  1399. 'SELECT DISTINCTROW SQL_NO_CACHE <city>, <state>, <country> FROM <addresses>',
  1400. $result->sql(),
  1401. true
  1402. );
  1403. $query = new Query($this->connection);
  1404. $result = $query
  1405. ->select(['city', 'state', 'country'])
  1406. ->from(['addresses'])
  1407. ->modifier(['TOP 10']);
  1408. $this->assertQuotedQuery(
  1409. 'SELECT TOP 10 <city>, <state>, <country> FROM <addresses>',
  1410. $result->sql(),
  1411. true
  1412. );
  1413. }
  1414. /**
  1415. * Tests that having() behaves pretty much the same as the where() method
  1416. *
  1417. * @return void
  1418. */
  1419. public function testSelectHaving()
  1420. {
  1421. $query = new Query($this->connection);
  1422. $result = $query
  1423. ->select(['total' => 'count(author_id)', 'author_id'])
  1424. ->from('articles')
  1425. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1426. ->group('author_id')
  1427. ->having(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1428. ->execute();
  1429. $expected = [['total' => 1, 'author_id' => 3]];
  1430. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1431. $result = $query->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'], true)
  1432. ->execute();
  1433. $expected = [['total' => 2, 'author_id' => 1]];
  1434. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1435. $result = $query->having(function ($e) {
  1436. return $e->add('count(author_id) = 1 + 1');
  1437. }, [], true)
  1438. ->execute();
  1439. $expected = [['total' => 2, 'author_id' => 1]];
  1440. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1441. }
  1442. /**
  1443. * Tests that Query::orHaving() can be used to concatenate conditions with OR
  1444. * in the having clause
  1445. *
  1446. * @return void
  1447. */
  1448. public function testSelectOrHaving()
  1449. {
  1450. $query = new Query($this->connection);
  1451. $result = $query
  1452. ->select(['total' => 'count(author_id)', 'author_id'])
  1453. ->from('articles')
  1454. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1455. ->group('author_id')
  1456. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1457. ->orHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1458. ->execute();
  1459. $expected = [['total' => 1, 'author_id' => 3]];
  1460. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1461. $query = new Query($this->connection);
  1462. $result = $query
  1463. ->select(['total' => 'count(author_id)', 'author_id'])
  1464. ->from('articles')
  1465. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1466. ->group('author_id')
  1467. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1468. ->orHaving(['count(author_id) <=' => 2], ['count(author_id)' => 'integer'])
  1469. ->execute();
  1470. $expected = [['total' => 2, 'author_id' => 1], ['total' => 1, 'author_id' => 3]];
  1471. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1472. $query = new Query($this->connection);
  1473. $result = $query
  1474. ->select(['total' => 'count(author_id)', 'author_id'])
  1475. ->from('articles')
  1476. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1477. ->group('author_id')
  1478. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1479. ->orHaving(function ($e) {
  1480. return $e->add('count(author_id) = 1 + 1');
  1481. })
  1482. ->execute();
  1483. $expected = [['total' => 2, 'author_id' => 1]];
  1484. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1485. }
  1486. /**
  1487. * Tests that Query::andHaving() can be used to concatenate conditions with AND
  1488. * in the having clause
  1489. *
  1490. * @return void
  1491. */
  1492. public function testSelectAndHaving()
  1493. {
  1494. $query = new Query($this->connection);
  1495. $result = $query
  1496. ->select(['total' => 'count(author_id)', 'author_id'])
  1497. ->from('articles')
  1498. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1499. ->group('author_id')
  1500. ->having(['count(author_id) >' => 2], ['count(author_id)' => 'integer'])
  1501. ->andHaving(['count(author_id) <' => 2], ['count(author_id)' => 'integer'])
  1502. ->execute();
  1503. $this->assertCount(0, $result);
  1504. $query = new Query($this->connection);
  1505. $result = $query
  1506. ->select(['total' => 'count(author_id)', 'author_id'])
  1507. ->from('articles')
  1508. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1509. ->group('author_id')
  1510. ->having(['count(author_id)' => 2], ['count(author_id)' => 'integer'])
  1511. ->andHaving(['count(author_id) >' => 1], ['count(author_id)' => 'integer'])
  1512. ->execute();
  1513. $expected = [['total' => 2, 'author_id' => 1]];
  1514. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1515. $query = new Query($this->connection);
  1516. $result = $query
  1517. ->select(['total' => 'count(author_id)', 'author_id'])
  1518. ->from('articles')
  1519. ->join(['table' => 'authors', 'alias' => 'a', 'conditions' => 'author_id = a.id'])
  1520. ->group('author_id')
  1521. ->andHaving(function ($e) {
  1522. return $e->add('count(author_id) = 2 - 1');
  1523. })
  1524. ->execute();
  1525. $expected = [['total' => 1, 'author_id' => 3]];
  1526. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1527. }
  1528. /**
  1529. * Tests selecting rows using a limit clause
  1530. *
  1531. * @return void
  1532. */
  1533. public function testSelectLimit()
  1534. {
  1535. $query = new Query($this->connection);
  1536. $result = $query->select('id')->from('articles')->limit(1)->execute();
  1537. $this->assertCount(1, $result);
  1538. $query = new Query($this->connection);
  1539. $result = $query->select('id')->from('articles')->limit(2)->execute();
  1540. $this->assertCount(2, $result);
  1541. }
  1542. /**
  1543. * Tests selecting rows combining a limit and offset clause
  1544. *
  1545. * @return void
  1546. */
  1547. public function testSelectOffset()
  1548. {
  1549. $query = new Query($this->connection);
  1550. $result = $query->select('id')->from('comments')
  1551. ->limit(1)
  1552. ->offset(0)
  1553. ->order(['id' => 'ASC'])
  1554. ->execute();
  1555. $this->assertCount(1, $result);
  1556. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1557. $query = new Query($this->connection);
  1558. $result = $query->select('id')->from('comments')
  1559. ->limit(1)
  1560. ->offset(1)
  1561. ->execute();
  1562. $this->assertCount(1, $result);
  1563. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1564. $query = new Query($this->connection);
  1565. $result = $query->select('id')->from('comments')
  1566. ->limit(1)
  1567. ->offset(2)
  1568. ->execute();
  1569. $this->assertCount(1, $result);
  1570. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1571. $query = new Query($this->connection);
  1572. $result = $query->select('id')->from('articles')
  1573. ->order(['id' => 'DESC'])
  1574. ->limit(1)
  1575. ->offset(0)
  1576. ->execute();
  1577. $this->assertCount(1, $result);
  1578. $this->assertEquals(['id' => 3], $result->fetch('assoc'));
  1579. $result = $query->limit(2)->offset(1)->execute();
  1580. $this->assertCount(2, $result);
  1581. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1582. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1583. }
  1584. /**
  1585. * Test selecting rows using the page() method.
  1586. *
  1587. * @return void
  1588. */
  1589. public function testSelectPage()
  1590. {
  1591. $query = new Query($this->connection);
  1592. $result = $query->select('id')->from('comments')
  1593. ->limit(1)
  1594. ->page(1)
  1595. ->execute();
  1596. $this->assertCount(1, $result);
  1597. $this->assertEquals(['id' => 1], $result->fetch('assoc'));
  1598. $query = new Query($this->connection);
  1599. $result = $query->select('id')->from('comments')
  1600. ->limit(1)
  1601. ->page(2)
  1602. ->order(['id' => 'asc'])
  1603. ->execute();
  1604. $this->assertCount(1, $result);
  1605. $this->assertEquals(['id' => 2], $result->fetch('assoc'));
  1606. $query = new Query($this->connection);
  1607. $query->select('id')->from('comments')->page(3, 10);
  1608. $this->assertEquals(10, $query->clause('limit'));
  1609. $this->assertEquals(20, $query->clause('offset'));
  1610. $query = new Query($this->connection);
  1611. $query->select('id')->from('comments')->page(1);
  1612. $this->assertEquals(25, $query->clause('limit'));
  1613. $this->assertEquals(0, $query->clause('offset'));
  1614. $query->select('id')->from('comments')->page(2);
  1615. $this->assertEquals(25, $query->clause('limit'));
  1616. $this->assertEquals(25, $query->clause('offset'));
  1617. }
  1618. /**
  1619. * Tests that Query objects can be included inside the select clause
  1620. * and be used as a normal field, including binding any passed parameter
  1621. *
  1622. * @return void
  1623. */
  1624. public function testSubqueryInSelect()
  1625. {
  1626. $query = new Query($this->connection);
  1627. $subquery = (new Query($this->connection))
  1628. ->select('name')
  1629. ->from(['b' => 'authors'])
  1630. ->where(['b.id = a.id']);
  1631. $result = $query
  1632. ->select(['id', 'name' => $subquery])
  1633. ->from(['a' => 'comments'])->execute();
  1634. $expected = [
  1635. ['id' => 1, 'name' => 'mariano'],
  1636. ['id' => 2, 'name' => 'nate'],
  1637. ['id' => 3, 'name' => 'larry'],
  1638. ['id' => 4, 'name' => 'garrett'],
  1639. ['id' => 5, 'name' => null],
  1640. ['id' => 6, 'name' => null],
  1641. ];
  1642. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1643. $query = new Query($this->connection);
  1644. $subquery = (new Query($this->connection))
  1645. ->select('name')
  1646. ->from(['b' => 'authors'])
  1647. ->where(['name' => 'mariano'], ['name' => 'string']);
  1648. $result = $query
  1649. ->select(['id', 'name' => $subquery])
  1650. ->from(['a' => 'articles'])->execute();
  1651. $expected = [
  1652. ['id' => 1, 'name' => 'mariano'],
  1653. ['id' => 2, 'name' => 'mariano'],
  1654. ['id' => 3, 'name' => 'mariano'],
  1655. ];
  1656. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1657. }
  1658. /**
  1659. * Tests that Query objects can be included inside the from clause
  1660. * and be used as a normal table, including binding any passed parameter
  1661. *
  1662. * @return void
  1663. */
  1664. public function testSuqueryInFrom()
  1665. {
  1666. $query = new Query($this->connection);
  1667. $subquery = (new Query($this->connection))
  1668. ->select(['id', 'comment'])
  1669. ->from('comments')
  1670. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1671. $result = $query
  1672. ->select(['say' => 'comment'])
  1673. ->from(['b' => $subquery])
  1674. ->where(['id !=' => 3])
  1675. ->execute();
  1676. $expected = [
  1677. ['say' => 'Second Comment for First Article'],
  1678. ['say' => 'Fourth Comment for First Article'],
  1679. ['say' => 'First Comment for Second Article'],
  1680. ['say' => 'Second Comment for Second Article'],
  1681. ];
  1682. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1683. }
  1684. /**
  1685. * Tests that Query objects can be included inside the where clause
  1686. * and be used as a normal condition, including binding any passed parameter
  1687. *
  1688. * @return void
  1689. */
  1690. public function testSubqueryInWhere()
  1691. {
  1692. $query = new Query($this->connection);
  1693. $subquery = (new Query($this->connection))
  1694. ->select(['id'])
  1695. ->from('authors')
  1696. ->where(['id' => 1]);
  1697. $result = $query
  1698. ->select(['name'])
  1699. ->from(['authors'])
  1700. ->where(['id !=' => $subquery])
  1701. ->execute();
  1702. $expected = [
  1703. ['name' => 'nate'],
  1704. ['name' => 'larry'],
  1705. ['name' => 'garrett'],
  1706. ];
  1707. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1708. $query = new Query($this->connection);
  1709. $subquery = (new Query($this->connection))
  1710. ->select(['id'])
  1711. ->from('comments')
  1712. ->where(['created >' => new \DateTime('2007-03-18 10:45:23')], ['created' => 'datetime']);
  1713. $result = $query
  1714. ->select(['name'])
  1715. ->from(['authors'])
  1716. ->where(['id not in' => $subquery])
  1717. ->execute();
  1718. $expected = [
  1719. ['name' => 'mariano'],
  1720. ];
  1721. $this->assertEquals($expected, $result->fetchAll('assoc'));
  1722. }
  1723. /**
  1724. * Tests that it is possible to use a subquery in a join clause
  1725. *
  1726. * @return void
  1727. */
  1728. public function testSubqueyInJoin()
  1729. {
  1730. $subquery = (new Query($this->connection))->select('*')->from('authors');
  1731. $query = new Query($this->connection);
  1732. $result = $query
  1733. ->select(['title', 'name'])
  1734. ->from('articles')
  1735. ->join(['b' => $subquery])
  1736. ->execute();
  1737. $this->assertCount(self::ARTICLE_COUNT * self::AUTHOR_COUNT, $result, 'Cross join causes multiplication');
  1738. $subquery->where(['id' => 1]);
  1739. $result = $query->execute();
  1740. $this->assertCount(3, $result);
  1741. $query->join(['b' => ['table' => $subquery, 'conditions' => ['b.id = articles.id']]], [], true);
  1742. $result = $query->execute();
  1743. $this->assertCount(1, $result);
  1744. }
  1745. /**
  1746. * Tests that it is possible to one or multiple UNION statements in a query
  1747. *
  1748. * @return void
  1749. */
  1750. public function testUnion()
  1751. {
  1752. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1753. $query = new Query($this->connection);
  1754. $result = $query->select(['id', 'comment'])
  1755. ->from(['c' => 'comments'])
  1756. ->union($union)
  1757. ->execute();
  1758. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1759. $rows = $result->fetchAll();
  1760. $union->select(['foo' => 'id', 'bar' => 'title']);
  1761. $union = (new Query($this->connection))
  1762. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1763. ->from(['b' => 'authors'])
  1764. ->where(['id ' => 1])
  1765. ->order(['id' => 'desc']);
  1766. $query->select(['foo' => 'id', 'bar' => 'comment'])->union($union);
  1767. $result = $query->execute();
  1768. $this->assertCount(self::COMMENT_COUNT + self::AUTHOR_COUNT, $result);
  1769. $this->assertNotEquals($rows, $result->fetchAll());
  1770. $union = (new Query($this->connection))
  1771. ->select(['id', 'title'])
  1772. ->from(['c' => 'articles']);
  1773. $query->select(['id', 'comment'], true)->union($union, true);
  1774. $result = $query->execute();
  1775. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1776. $this->assertEquals($rows, $result->fetchAll());
  1777. }
  1778. /**
  1779. * Tests that it is possible to run unions with order statements
  1780. *
  1781. * @return void
  1782. */
  1783. public function testUnionOrderBy()
  1784. {
  1785. $this->skipIf(
  1786. $this->connection->driver() instanceof \Cake\Database\Driver\Sqlite,
  1787. 'SQLite does not support ORDER BY in UNIONed queries.'
  1788. );
  1789. $union = (new Query($this->connection))
  1790. ->select(['id', 'title'])
  1791. ->from(['a' => 'articles'])
  1792. ->order(['a.id' => 'asc']);
  1793. $query = new Query($this->connection);
  1794. $result = $query->select(['id', 'comment'])
  1795. ->from(['c' => 'comments'])
  1796. ->order(['c.id' => 'asc'])
  1797. ->union($union)
  1798. ->execute();
  1799. $this->assertCount(self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1800. }
  1801. /**
  1802. * Tests that UNION ALL can be built by setting the second param of union() to true
  1803. *
  1804. * @return void
  1805. */
  1806. public function testUnionAll()
  1807. {
  1808. $union = (new Query($this->connection))->select(['id', 'title'])->from(['a' => 'articles']);
  1809. $query = new Query($this->connection);
  1810. $result = $query->select(['id', 'comment'])
  1811. ->from(['c' => 'comments'])
  1812. ->union($union)
  1813. ->execute();
  1814. $this->assertCount(self::ARTICLE_COUNT + self::COMMENT_COUNT, $result);
  1815. $rows = $result->fetchAll();
  1816. $union->select(['foo' => 'id', 'bar' => 'title']);
  1817. $union = (new Query($this->connection))
  1818. ->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
  1819. ->from(['b' => 'authors'])
  1820. ->where(['id ' => 1])
  1821. ->order(['id' => 'desc']);
  1822. $query->select(['foo' => 'id', 'bar' => 'comment'])->unionAll($union);
  1823. $result = $query->execute();
  1824. $this->assertCount(1 + self::COMMENT_COUNT + self::ARTICLE_COUNT, $result);
  1825. $this->assertNotEquals($rows, $result->fetchAll());
  1826. }
  1827. /**
  1828. * Tests stacking decorators for results and resetting the list of decorators
  1829. *
  1830. * @return void
  1831. */
  1832. public function testDecorateResults()
  1833. {
  1834. $query = new Query($this->connection);
  1835. $result = $query
  1836. ->select(['id', 'title'])
  1837. ->from('articles')
  1838. ->order(['id' => 'ASC'])
  1839. ->decorateResults(function ($row) {
  1840. $row['modified_id'] = $row['id'] + 1;
  1841. return $row;
  1842. })
  1843. ->execute();
  1844. while ($row = $result->fetch('assoc')) {
  1845. $this->assertEquals($row['id'] + 1, $row['modified_id']);
  1846. }
  1847. $result = $query->decorateResults(function ($row) {
  1848. $row['modified_id']--;
  1849. return $row;
  1850. })->execute();
  1851. while ($row = $result->fetch('assoc')) {
  1852. $this->assertEquals($row['id'], $row['modified_id']);
  1853. }
  1854. $result = $query
  1855. ->decorateResults(function ($row) {
  1856. $row['foo'] = 'bar';
  1857. return $row;
  1858. }, true)
  1859. ->execute();
  1860. while ($row = $result->fetch('assoc')) {
  1861. $this->assertEquals('bar', $row['foo']);
  1862. $this->assertArrayNotHasKey('modified_id', $row);
  1863. }
  1864. $results = $query->decorateResults(null, true)->execute();
  1865. while ($row = $result->fetch('assoc')) {
  1866. $this->assertArrayNotHasKey('foo', $row);
  1867. $this->assertArrayNotHasKey('modified_id', $row);
  1868. }
  1869. }
  1870. /**
  1871. * Test a basic delete using from()
  1872. *
  1873. * @return void
  1874. */
  1875. public function testDeleteWithFrom()
  1876. {
  1877. $query = new Query($this->connection);
  1878. $query->delete()
  1879. ->from('authors')
  1880. ->where('1 = 1');
  1881. $result = $query->sql();
  1882. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1883. $result = $query->execute();
  1884. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1885. $this->assertCount(self::AUTHOR_COUNT, $result);
  1886. }
  1887. /**
  1888. * Test delete with from and alias.
  1889. *
  1890. * @return void
  1891. */
  1892. public function testDeleteWithAliasedFrom()
  1893. {
  1894. $query = new Query($this->connection);
  1895. $query->delete()
  1896. ->from(['a ' => 'authors'])
  1897. ->where(['a.id !=' => 99]);
  1898. $result = $query->sql();
  1899. $this->assertQuotedQuery('DELETE FROM <authors> WHERE <id> != :c0', $result, true);
  1900. $result = $query->execute();
  1901. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1902. $this->assertCount(self::AUTHOR_COUNT, $result);
  1903. }
  1904. /**
  1905. * Test a basic delete with no from() call.
  1906. *
  1907. * @return void
  1908. */
  1909. public function testDeleteNoFrom()
  1910. {
  1911. $query = new Query($this->connection);
  1912. $query->delete('authors')
  1913. ->where('1 = 1');
  1914. $result = $query->sql();
  1915. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1916. $result = $query->execute();
  1917. $this->assertInstanceOf('Cake\Database\StatementInterface', $result);
  1918. $this->assertCount(self::AUTHOR_COUNT, $result);
  1919. }
  1920. /**
  1921. * Test setting select() & delete() modes.
  1922. *
  1923. * @return void
  1924. */
  1925. public function testSelectAndDeleteOnSameQuery()
  1926. {
  1927. $query = new Query($this->connection);
  1928. $result = $query->select()
  1929. ->delete('authors')
  1930. ->where('1 = 1');
  1931. $result = $query->sql();
  1932. $this->assertQuotedQuery('DELETE FROM <authors>', $result, true);
  1933. $this->assertContains(' WHERE 1 = 1', $result);
  1934. }
  1935. /**
  1936. * Test a simple update.
  1937. *
  1938. * @return void
  1939. */
  1940. public function testUpdateSimple()
  1941. {
  1942. $query = new Query($this->connection);
  1943. $query->update('authors')
  1944. ->set('name', 'mark')
  1945. ->where(['id' => 1]);
  1946. $result = $query->sql();
  1947. $this->assertQuotedQuery('UPDATE <authors> SET <name> = :', $result, true);
  1948. $result = $query->execute();
  1949. $this->assertCount(1, $result);
  1950. }
  1951. /**
  1952. * Test update with multiple fields.
  1953. *
  1954. * @return void
  1955. */
  1956. public function testUpdateMultipleFields()
  1957. {
  1958. $query = new Query($this->connection);
  1959. $query->update('articles')
  1960. ->set('title', 'mark', 'string')
  1961. ->set('body', 'some text', 'string')
  1962. ->where(['id' => 1]);
  1963. $result = $query->sql();
  1964. $this->assertQuotedQuery(
  1965. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1966. $result,
  1967. true
  1968. );
  1969. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  1970. $result = $query->execute();
  1971. $this->assertCount(1, $result);
  1972. }
  1973. /**
  1974. * Test updating multiple fields with an array.
  1975. *
  1976. * @return void
  1977. */
  1978. public function testUpdateMultipleFieldsArray()
  1979. {
  1980. $query = new Query($this->connection);
  1981. $query->update('articles')
  1982. ->set([
  1983. 'title' => 'mark',
  1984. 'body' => 'some text'
  1985. ], ['title' => 'string', 'body' => 'string'])
  1986. ->where(['id' => 1]);
  1987. $result = $query->sql();
  1988. $this->assertQuotedQuery(
  1989. 'UPDATE <articles> SET <title> = :c0 , <body> = :c1',
  1990. $result,
  1991. true
  1992. );
  1993. $this->assertQuotedQuery('WHERE <id> = :', $result, true);
  1994. $result = $query->execute();
  1995. $this->assertCount(1, $result);
  1996. }
  1997. /**
  1998. * Test updates with an expression.
  1999. *
  2000. * @return void
  2001. */
  2002. public function testUpdateWithExpression()
  2003. {
  2004. $query = new Query($this->connection);
  2005. $expr = $query->newExpr('title = author_id');
  2006. $query->update('articles')
  2007. ->set($expr)
  2008. ->where(['id' => 1]);
  2009. $result = $query->sql();
  2010. $this->assertQuotedQuery(
  2011. 'UPDATE <articles> SET title = author_id WHERE <id> = :',
  2012. $result,
  2013. true
  2014. );
  2015. $result = $query->execute();
  2016. $this->assertCount(1, $result);
  2017. }
  2018. /**
  2019. * Test update with array fields and types.
  2020. *
  2021. * @return void
  2022. */
  2023. public function testUpdateArrayFields()
  2024. {
  2025. $query = new Query($this->connection);
  2026. $date = new \DateTime;
  2027. $query->update('comments')
  2028. ->set(['comment' => 'mark', 'created' => $date], ['created' => 'date'])
  2029. ->where(['id' => 1]);
  2030. $result = $query->sql();
  2031. $this->assertQuotedQuery(
  2032. 'UPDATE <comments> SET <comment> = :c0 , <created> = :c1',
  2033. $result,
  2034. true
  2035. );
  2036. $this->assertQuotedQuery(' WHERE <id> = :c2$', $result, true);
  2037. $result = $query->execute();
  2038. $this->assertCount(1, $result);
  2039. $query = new Query($this->connection);
  2040. $result = $query->select('created')->from('comments')->where(['id' => 1])->execute();
  2041. $result = $result->fetchAll('assoc')[0]['created'];
  2042. $this->assertStringStartsWith($date->format('Y-m-d'), $result);
  2043. }
  2044. /**
  2045. * You cannot call values() before insert() it causes all sorts of pain.
  2046. *
  2047. * @expectedException \Cake\Database\Exception
  2048. * @return void
  2049. */
  2050. public function testInsertValuesBeforeInsertFailure()
  2051. {
  2052. $query = new Query($this->connection);
  2053. $query->select('*')->values([
  2054. 'id' => 1,
  2055. 'title' => 'mark',
  2056. 'body' => 'test insert'
  2057. ]);
  2058. }
  2059. /**
  2060. * Inserting nothing should not generate an error.
  2061. *
  2062. * @expectedException \RuntimeException
  2063. * @expectedExceptionMessage At least 1 column is required to perform an insert.
  2064. * @return void
  2065. */
  2066. public function testInsertNothing()
  2067. {
  2068. $query = new Query($this->connection);
  2069. $query->insert([]);
  2070. }
  2071. /**
  2072. * Test inserting a single row.
  2073. *
  2074. * @return void
  2075. */
  2076. public function testInsertSimple()
  2077. {
  2078. $query = new Query($this->connection);
  2079. $query->insert(['title', 'body'])
  2080. ->into('articles')
  2081. ->values([
  2082. 'title' => 'mark',
  2083. 'body' => 'test insert'
  2084. ]);
  2085. $result = $query->sql();
  2086. $this->assertQuotedQuery(
  2087. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2088. 'VALUES \(:c0, :c1\)',
  2089. $result,
  2090. true
  2091. );
  2092. $result = $query->execute();
  2093. $result->closeCursor();
  2094. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2095. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2096. $this->assertCount(1, $result, '1 row should be inserted');
  2097. }
  2098. $expected = [
  2099. [
  2100. 'id' => 4,
  2101. 'author_id' => null,
  2102. 'title' => 'mark',
  2103. 'body' => 'test insert',
  2104. 'published' => 'N',
  2105. ]
  2106. ];
  2107. $this->assertTable('articles', 1, $expected, ['id >=' => 4]);
  2108. }
  2109. /**
  2110. * Test an insert when not all the listed fields are provided.
  2111. * Columns should be matched up where possible.
  2112. *
  2113. * @return void
  2114. */
  2115. public function testInsertSparseRow()
  2116. {
  2117. $query = new Query($this->connection);
  2118. $query->insert(['title', 'body'])
  2119. ->into('articles')
  2120. ->values([
  2121. 'title' => 'mark',
  2122. ]);
  2123. $result = $query->sql();
  2124. $this->assertQuotedQuery(
  2125. 'INSERT INTO <articles> \(<title>, <body>\) (OUTPUT INSERTED\.\* )?' .
  2126. 'VALUES \(:c0, :c1\)',
  2127. $result,
  2128. true
  2129. );
  2130. $result = $query->execute();
  2131. $result->closeCursor();
  2132. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2133. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2134. $this->assertCount(1, $result, '1 row should be inserted');
  2135. }
  2136. $expected = [
  2137. [
  2138. 'id' => 4,
  2139. 'author_id' => null,
  2140. 'title' => 'mark',
  2141. 'body' => null,
  2142. 'published' => 'N',
  2143. ]
  2144. ];
  2145. $this->assertTable('articles', 1, $expected, ['id >= 4']);
  2146. }
  2147. /**
  2148. * Test inserting multiple rows with sparse data.
  2149. *
  2150. * @return void
  2151. */
  2152. public function testInsertMultipleRowsSparse()
  2153. {
  2154. $query = new Query($this->connection);
  2155. $query->insert(['title', 'body'])
  2156. ->into('articles')
  2157. ->values([
  2158. 'body' => 'test insert'
  2159. ])
  2160. ->values([
  2161. 'title' => 'jose',
  2162. ]);
  2163. $result = $query->execute();
  2164. $result->closeCursor();
  2165. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2166. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2167. $this->assertCount(2, $result, '2 rows should be inserted');
  2168. }
  2169. $expected = [
  2170. [
  2171. 'id' => 4,
  2172. 'author_id' => null,
  2173. 'title' => null,
  2174. 'body' => 'test insert',
  2175. 'published' => 'N',
  2176. ],
  2177. [
  2178. 'id' => 5,
  2179. 'author_id' => null,
  2180. 'title' => 'jose',
  2181. 'body' => null,
  2182. 'published' => 'N',
  2183. ],
  2184. ];
  2185. $this->assertTable('articles', 2, $expected, ['id >=' => 4]);
  2186. }
  2187. /**
  2188. * Test that INSERT INTO ... SELECT works.
  2189. *
  2190. * @return void
  2191. */
  2192. public function testInsertFromSelect()
  2193. {
  2194. $select = (new Query($this->connection))->select(['name', "'some text'", 99])
  2195. ->from('authors')
  2196. ->where(['id' => 1]);
  2197. $query = new Query($this->connection);
  2198. $query->insert(
  2199. ['title', 'body', 'author_id'],
  2200. ['title' => 'string', 'body' => 'string', 'author_id' => 'integer']
  2201. )
  2202. ->into('articles')
  2203. ->values($select);
  2204. $result = $query->sql();
  2205. $this->assertQuotedQuery(
  2206. 'INSERT INTO <articles> \(<title>, <body>, <author_id>\) (OUTPUT INSERTED\.\* )?SELECT',
  2207. $result,
  2208. true
  2209. );
  2210. $this->assertQuotedQuery(
  2211. 'SELECT <name>, \'some text\', 99 FROM <authors>',
  2212. $result,
  2213. true
  2214. );
  2215. $result = $query->execute();
  2216. $result->closeCursor();
  2217. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2218. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2219. $this->assertCount(1, $result);
  2220. }
  2221. $result = (new Query($this->connection))->select('*')
  2222. ->from('articles')
  2223. ->where(['author_id' => 99])
  2224. ->execute();
  2225. $this->assertCount(1, $result);
  2226. $expected = [
  2227. 'id' => 4,
  2228. 'title' => 'mariano',
  2229. 'body' => 'some text',
  2230. 'author_id' => 99,
  2231. 'published' => 'N',
  2232. ];
  2233. $this->assertEquals($expected, $result->fetch('assoc'));
  2234. }
  2235. /**
  2236. * Test that an exception is raised when mixing query + array types.
  2237. *
  2238. * @expectedException \Cake\Database\Exception
  2239. */
  2240. public function testInsertFailureMixingTypesArrayFirst()
  2241. {
  2242. $query = new Query($this->connection);
  2243. $query->insert(['name'])
  2244. ->into('articles')
  2245. ->values(['name' => 'mark'])
  2246. ->values(new Query($this->connection));
  2247. }
  2248. /**
  2249. * Test that an exception is raised when mixing query + array types.
  2250. *
  2251. * @expectedException \Cake\Database\Exception
  2252. */
  2253. public function testInsertFailureMixingTypesQueryFirst()
  2254. {
  2255. $query = new Query($this->connection);
  2256. $query->insert(['name'])
  2257. ->into('articles')
  2258. ->values(new Query($this->connection))
  2259. ->values(['name' => 'mark']);
  2260. }
  2261. /**
  2262. * Test that insert can use expression objects as values.
  2263. *
  2264. * @return void
  2265. */
  2266. public function testInsertExpressionValues()
  2267. {
  2268. $query = new Query($this->connection);
  2269. $query->insert(['title', 'author_id'])
  2270. ->into('articles')
  2271. ->values(['title' => $query->newExpr("SELECT 'jose'"), 'author_id' => 99]);
  2272. $result = $query->execute();
  2273. $result->closeCursor();
  2274. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2275. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2276. $this->assertCount(1, $result);
  2277. }
  2278. $result = (new Query($this->connection))->select('*')
  2279. ->from('articles')
  2280. ->where(['author_id' => 99])
  2281. ->execute();
  2282. $this->assertCount(1, $result);
  2283. $expected = [
  2284. 'id' => 4,
  2285. 'title' => 'jose',
  2286. 'body' => null,
  2287. 'author_id' => '99',
  2288. 'published' => 'N',
  2289. ];
  2290. $this->assertEquals($expected, $result->fetch('assoc'));
  2291. $subquery = new Query($this->connection);
  2292. $subquery->select(['name'])
  2293. ->from('authors')
  2294. ->where(['id' => 1]);
  2295. $query = new Query($this->connection);
  2296. $query->insert(['title', 'author_id'])
  2297. ->into('articles')
  2298. ->values(['title' => $subquery, 'author_id' => 100]);
  2299. $result = $query->execute();
  2300. $result->closeCursor();
  2301. //PDO_SQLSRV returns -1 for successful inserts when using INSERT ... OUTPUT
  2302. if (!$this->connection->driver() instanceof \Cake\Database\Driver\Sqlserver) {
  2303. $this->assertCount(1, $result);
  2304. }
  2305. $result = (new Query($this->connection))->select('*')
  2306. ->from('articles')
  2307. ->where(['author_id' => 100])
  2308. ->execute();
  2309. $this->assertCount(1, $result);
  2310. $expected = [
  2311. 'id' => 5,
  2312. 'title' => 'mariano',
  2313. 'body' => null,
  2314. 'author_id' => '100',
  2315. 'published' => 'N',
  2316. ];
  2317. $this->assertEquals($expected, $result->fetch('assoc'));
  2318. }
  2319. /**
  2320. * Tests that functions are correctly transformed and their parameters are bound
  2321. *
  2322. * @group FunctionExpression
  2323. * @return void
  2324. */
  2325. public function testSQLFunctions()
  2326. {
  2327. $query = new Query($this->connection);
  2328. $result = $query->select(
  2329. function ($q) {
  2330. return ['total' => $q->func()->count('*')];
  2331. }
  2332. )
  2333. ->from('articles')
  2334. ->execute();
  2335. $expected = [['total' => 3]];
  2336. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2337. $query = new Query($this->connection);
  2338. $result = $query->select([
  2339. 'c' => $query->func()->concat(['title' => 'literal', ' is appended'])
  2340. ])
  2341. ->from('articles')
  2342. ->order(['c' => 'ASC'])
  2343. ->execute();
  2344. $expected = [
  2345. ['c' => 'First Article is appended'],
  2346. ['c' => 'Second Article is appended'],
  2347. ['c' => 'Third Article is appended']
  2348. ];
  2349. $this->assertEquals($expected, $result->fetchAll('assoc'));
  2350. $query = new Query($this->connection);
  2351. $result = $query
  2352. ->select(['d' => $query->func()->dateDiff(['2012-01-05', '2012-01-02'])])
  2353. ->execute()
  2354. ->fetchAll('assoc');
  2355. $this->assertEquals(3, abs($result[0]['d']));
  2356. $query = new Query($this->connection);
  2357. $result = $query
  2358. ->select(['d' => $query->func()->now('date')])
  2359. ->execute();
  2360. $this->assertEquals([['d' => date('Y-m-d')]], $result->fetchAll('assoc'));
  2361. $query = new Query($this->connection);
  2362. $result = $query
  2363. ->select(['d' => $query->func()->now('time')])
  2364. ->execute();
  2365. $this->assertWithinRange(
  2366. date('U'),
  2367. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2368. 1
  2369. );
  2370. $query = new Query($this->connection);
  2371. $result = $query
  2372. ->select(['d' => $query->func()->now()])
  2373. ->execute();
  2374. $this->assertWithinRange(
  2375. date('U'),
  2376. (new \DateTime($result->fetchAll('assoc')[0]['d']))->format('U'),
  2377. 1
  2378. );
  2379. }
  2380. /**
  2381. * Tests that default types are passed to functions accepting a $types param
  2382. *
  2383. * @return void
  2384. */
  2385. public function testDefaultTypes()
  2386. {
  2387. $query = new Query($this->connection);
  2388. $this->assertEquals([], $query->defaultTypes());
  2389. $types = ['id' => 'integer', 'created' => 'datetime'];
  2390. $this->assertSame($query, $query->defaultTypes($types));
  2391. $this->assertSame($types, $query->defaultTypes());
  2392. $results = $query->select(['id', 'comment'])
  2393. ->from('comments')
  2394. ->where(['created >=' => new \DateTime('2007-03-18 10:55:00')])
  2395. ->execute();
  2396. $expected = [['id' => '6', 'comment' => 'Second Comment for Second Article']];
  2397. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2398. // Now test default can be overridden
  2399. $types = ['created' => 'date'];
  2400. $results = $query
  2401. ->where(['created >=' => new \DateTime('2007-03-18 10:50:00')], $types, true)
  2402. ->execute();
  2403. $this->assertCount(6, $results, 'All 6 rows should match.');
  2404. }
  2405. /**
  2406. * Tests parameter binding
  2407. *
  2408. * @return void
  2409. */
  2410. public function testBind()
  2411. {
  2412. $query = new Query($this->connection);
  2413. $results = $query->select(['id', 'comment'])
  2414. ->from('comments')
  2415. ->where(['created BETWEEN :foo AND :bar'])
  2416. ->bind(':foo', new \DateTime('2007-03-18 10:50:00'), 'datetime')
  2417. ->bind(':bar', new \DateTime('2007-03-18 10:52:00'), 'datetime')
  2418. ->execute();
  2419. $expected = [['id' => '4', 'comment' => 'Fourth Comment for First Article']];
  2420. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2421. $query = new Query($this->connection);
  2422. $results = $query->select(['id', 'comment'])
  2423. ->from('comments')
  2424. ->where(['created BETWEEN :foo AND :bar'])
  2425. ->bind(':foo', '2007-03-18 10:50:00')
  2426. ->bind(':bar', '2007-03-18 10:52:00')
  2427. ->execute();
  2428. $this->assertEquals($expected, $results->fetchAll('assoc'));
  2429. }
  2430. /**
  2431. * Test that epilog() will actually append a string to a select query
  2432. *
  2433. * @return void
  2434. */
  2435. public function testAppendSelect()
  2436. {
  2437. $query = new Query($this->connection);
  2438. $sql = $query
  2439. ->select(['id', 'title'])
  2440. ->from('articles')
  2441. ->where(['id' => 1])
  2442. ->epilog('FOR UPDATE')
  2443. ->sql();
  2444. $this->assertContains('SELECT', $sql);
  2445. $this->assertContains('FROM', $sql);
  2446. $this->assertContains('WHERE', $sql);
  2447. $this->assertEquals(' FOR UPDATE', substr($sql, -11));
  2448. }
  2449. /**
  2450. * Test that epilog() will actually append a string to an insert query
  2451. *
  2452. * @return void
  2453. */
  2454. public function testAppendInsert()
  2455. {
  2456. $query = new Query($this->connection);
  2457. $sql = $query
  2458. ->insert(['id', 'title'])
  2459. ->into('articles')
  2460. ->values([1, 'a title'])
  2461. ->epilog('RETURNING id')
  2462. ->sql();
  2463. $this->assertContains('INSERT', $sql);
  2464. $this->assertContains('INTO', $sql);
  2465. $this->assertContains('VALUES', $sql);
  2466. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2467. }
  2468. /**
  2469. * Test that epilog() will actually append a string to an update query
  2470. *
  2471. * @return void
  2472. */
  2473. public function testAppendUpdate()
  2474. {
  2475. $query = new Query($this->connection);
  2476. $sql = $query
  2477. ->update('articles')
  2478. ->set(['title' => 'foo'])
  2479. ->where(['id' => 1])
  2480. ->epilog('RETURNING id')
  2481. ->sql();
  2482. $this->assertContains('UPDATE', $sql);
  2483. $this->assertContains('SET', $sql);
  2484. $this->assertContains('WHERE', $sql);
  2485. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2486. }
  2487. /**
  2488. * Test that epilog() will actually append a string to a delete query
  2489. *
  2490. * @return void
  2491. */
  2492. public function testAppendDelete()
  2493. {
  2494. $query = new Query($this->connection);
  2495. $sql = $query
  2496. ->delete('articles')
  2497. ->where(['id' => 1])
  2498. ->epilog('RETURNING id')
  2499. ->sql();
  2500. $this->assertContains('DELETE FROM', $sql);
  2501. $this->assertContains('WHERE', $sql);
  2502. $this->assertEquals(' RETURNING id', substr($sql, -13));
  2503. }
  2504. /**
  2505. * Tests automatic identifier quoting in the select clause
  2506. *
  2507. * @return void
  2508. */
  2509. public function testQuotingSelectFieldsAndAlias()
  2510. {
  2511. $this->connection->driver()->autoQuoting(true);
  2512. $query = new Query($this->connection);
  2513. $sql = $query->select(['something'])->sql();
  2514. $this->assertQuotedQuery('SELECT <something>$', $sql);
  2515. $query = new Query($this->connection);
  2516. $sql = $query->select(['foo' => 'something'])->sql();
  2517. $this->assertQuotedQuery('SELECT <something> AS <foo>$', $sql);
  2518. $query = new Query($this->connection);
  2519. $sql = $query->select(['foo' => 1])->sql();
  2520. $this->assertQuotedQuery('SELECT 1 AS <foo>$', $sql);
  2521. $query = new Query($this->connection);
  2522. $sql = $query->select(['foo' => '1 + 1'])->sql();
  2523. $this->assertQuotedQuery('SELECT <1 \+ 1> AS <foo>$', $sql);
  2524. $query = new Query($this->connection);
  2525. $sql = $query->select(['foo' => $query->newExpr('1 + 1')])->sql();
  2526. $this->assertQuotedQuery('SELECT \(1 \+ 1\) AS <foo>$', $sql);
  2527. $query = new Query($this->connection);
  2528. $sql = $query->select(['foo' => new IdentifierExpression('bar')])->sql();
  2529. $this->assertQuotedQuery('<bar>', $sql);
  2530. }
  2531. /**
  2532. * Tests automatic identifier quoting in the from clause
  2533. *
  2534. * @return void
  2535. */
  2536. public function testQuotingFromAndAlias()
  2537. {
  2538. $this->connection->driver()->autoQuoting(true);
  2539. $query = new Query($this->connection);
  2540. $sql = $query->select('*')->from(['something'])->sql();
  2541. $this->assertQuotedQuery('FROM <something>', $sql);
  2542. $query = new Query($this->connection);
  2543. $sql = $query->select('*')->from(['foo' => 'something'])->sql();
  2544. $this->assertQuotedQuery('FROM <something> <foo>$', $sql);
  2545. $query = new Query($this->connection);
  2546. $sql = $query->select('*')->from(['foo' => $query->newExpr('bar')])->sql();
  2547. $this->assertQuotedQuery('FROM \(bar\) <foo>$', $sql);
  2548. }
  2549. /**
  2550. * Tests automatic identifier quoting for DISTINCT ON
  2551. *
  2552. * @return void
  2553. */
  2554. public function testQuotingDistinctOn()
  2555. {
  2556. $this->connection->driver()->autoQuoting(true);
  2557. $query = new Query($this->connection);
  2558. $sql = $query->select('*')->distinct(['something'])->sql();
  2559. $this->assertQuotedQuery('<something>', $sql);
  2560. }
  2561. /**
  2562. * Tests automatic identifier quoting in the join clause
  2563. *
  2564. * @return void
  2565. */
  2566. public function testQuotingJoinsAndAlias()
  2567. {
  2568. $this->connection->driver()->autoQuoting(true);
  2569. $query = new Query($this->connection);
  2570. $sql = $query->select('*')->join(['something'])->sql();
  2571. $this->assertQuotedQuery('JOIN <something>', $sql);
  2572. $query = new Query($this->connection);
  2573. $sql = $query->select('*')->join(['foo' => 'something'])->sql();
  2574. $this->assertQuotedQuery('JOIN <something> <foo>', $sql);
  2575. $query = new Query($this->connection);
  2576. $sql = $query->select('*')->join(['foo' => $query->newExpr('bar')])->sql();
  2577. $this->assertQuotedQuery('JOIN \(bar\) <foo>', $sql);
  2578. }
  2579. /**
  2580. * Tests automatic identifier quoting in the group by clause
  2581. *
  2582. * @return void
  2583. */
  2584. public function testQuotingGroupBy()
  2585. {
  2586. $this->connection->driver()->autoQuoting(true);
  2587. $query = new Query($this->connection);
  2588. $sql = $query->select('*')->group(['something'])->sql();
  2589. $this->assertQuotedQuery('GROUP BY <something>', $sql);
  2590. $query = new Query($this->connection);
  2591. $sql = $query->select('*')->group([$query->newExpr('bar')])->sql();
  2592. $this->assertQuotedQuery('GROUP BY \(bar\)', $sql);
  2593. $query = new Query($this->connection);
  2594. $sql = $query->select('*')->group([new IdentifierExpression('bar')])->sql();
  2595. $this->assertQuotedQuery('GROUP BY \(<bar>\)', $sql);
  2596. }
  2597. /**
  2598. * Tests automatic identifier quoting strings inside conditions expressions
  2599. *
  2600. * @return void
  2601. */
  2602. public function testQuotingExpressions()
  2603. {
  2604. $this->connection->driver()->autoQuoting(true);
  2605. $query = new Query($this->connection);
  2606. $sql = $query->select('*')
  2607. ->where(['something' => 'value'])
  2608. ->sql();
  2609. $this->assertQuotedQuery('WHERE <something> = :c0', $sql);
  2610. $query = new Query($this->connection);
  2611. $sql = $query->select('*')
  2612. ->where([
  2613. 'something' => 'value',
  2614. 'OR' => ['foo' => 'bar', 'baz' => 'cake']
  2615. ])
  2616. ->sql();
  2617. $this->assertQuotedQuery('<something> = :c0 AND', $sql);
  2618. $this->assertQuotedQuery('\(<foo> = :c1 OR <baz> = :c2\)', $sql);
  2619. }
  2620. /**
  2621. * Tests that insert query parts get quoted automatically
  2622. *
  2623. * @return void
  2624. */
  2625. public function testQuotingInsert()
  2626. {
  2627. $this->connection->driver()->autoQuoting(true);
  2628. $query = new Query($this->connection);
  2629. $sql = $query->insert(['bar', 'baz'])
  2630. ->into('foo')
  2631. ->where(['something' => 'value'])
  2632. ->sql();
  2633. $this->assertQuotedQuery('INSERT INTO <foo> \(<bar>, <baz>\)', $sql);
  2634. $query = new Query($this->connection);
  2635. $sql = $query->insert([$query->newExpr('bar')])
  2636. ->into('foo')
  2637. ->where(['something' => 'value'])
  2638. ->sql();
  2639. $this->assertQuotedQuery('INSERT INTO <foo> \(\(bar\)\)', $sql);
  2640. }
  2641. /**
  2642. * Tests converting a query to a string
  2643. *
  2644. * @return void
  2645. */
  2646. public function testToString()
  2647. {
  2648. $query = new Query($this->connection);
  2649. $query
  2650. ->select(['title'])
  2651. ->from('articles');
  2652. $result = (string)$query;
  2653. $this->assertQuotedQuery('SELECT <title> FROM <articles>', $result, true);
  2654. }
  2655. /**
  2656. * Tests __debugInfo
  2657. *
  2658. * @return void
  2659. */
  2660. public function testDebugInfo()
  2661. {
  2662. $query = (new Query($this->connection))->select('*')
  2663. ->from('articles')
  2664. ->defaultTypes(['id' => 'integer'])
  2665. ->where(['id' => '1']);
  2666. $expected = [
  2667. 'sql' => $query->sql(),
  2668. 'params' => [
  2669. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2670. ],
  2671. 'defaultTypes' => ['id' => 'integer'],
  2672. 'decorators' => 0,
  2673. 'executed' => false
  2674. ];
  2675. $result = $query->__debugInfo();
  2676. $this->assertEquals($expected, $result);
  2677. $query->execute();
  2678. $expected = [
  2679. 'sql' => $query->sql(),
  2680. 'params' => [
  2681. ':c0' => ['value' => '1', 'type' => 'integer', 'placeholder' => 'c0']
  2682. ],
  2683. 'defaultTypes' => ['id' => 'integer'],
  2684. 'decorators' => 0,
  2685. 'executed' => true
  2686. ];
  2687. $result = $query->__debugInfo();
  2688. $this->assertEquals($expected, $result);
  2689. }
  2690. /**
  2691. * Tests that it is possible to pass ExpressionInterface to isNull and isNotNull
  2692. *
  2693. * @return void
  2694. */
  2695. public function testIsNullWithExpressions()
  2696. {
  2697. $query = new Query($this->connection);
  2698. $subquery = (new Query($this->connection))
  2699. ->select(['id'])
  2700. ->from('authors')
  2701. ->where(['id' => 1]);
  2702. $result = $query
  2703. ->select(['name'])
  2704. ->from(['authors'])
  2705. ->where(function ($exp) use ($subquery) {
  2706. return $exp->isNotNull($subquery);
  2707. })
  2708. ->execute();
  2709. $this->assertNotEmpty($result->fetchAll('assoc'));
  2710. $result = (new Query($this->connection))
  2711. ->select(['name'])
  2712. ->from(['authors'])
  2713. ->where(function ($exp) use ($subquery) {
  2714. return $exp->isNull($subquery);
  2715. })
  2716. ->execute();
  2717. $this->assertEmpty($result->fetchAll('assoc'));
  2718. }
  2719. /**
  2720. * Tests that strings passed to isNull and isNotNull will be treated as identifiers
  2721. * when using autoQuoting
  2722. *
  2723. * @return void
  2724. */
  2725. public function testIsNullAutoQuoting()
  2726. {
  2727. $this->connection->driver()->autoQuoting(true);
  2728. $query = new Query($this->connection);
  2729. $query->select('*')->from('things')->where(function ($exp) {
  2730. return $exp->isNull('field');
  2731. });
  2732. $this->assertQuotedQuery('WHERE \(<field>\) IS NULL', $query->sql());
  2733. $query = new Query($this->connection);
  2734. $query->select('*')->from('things')->where(function ($exp) {
  2735. return $exp->isNotNull('field');
  2736. });
  2737. $this->assertQuotedQuery('WHERE \(<field>\) IS NOT NULL', $query->sql());
  2738. }
  2739. /**
  2740. * Tests that using the IS operator will automatically translate to the best
  2741. * possible operator depending on the passed value
  2742. *
  2743. * @return void
  2744. */
  2745. public function testDirectIsNull()
  2746. {
  2747. $sql = (new Query($this->connection))
  2748. ->select(['name'])
  2749. ->from(['authors'])
  2750. ->where(['name IS' => null])
  2751. ->sql();
  2752. $this->assertQuotedQuery('WHERE \(<name>\) IS NULL', $sql, true);
  2753. $results = (new Query($this->connection))
  2754. ->select(['name'])
  2755. ->from(['authors'])
  2756. ->where(['name IS' => 'larry'])
  2757. ->execute();
  2758. $this->assertCount(1, $results);
  2759. $this->assertEquals(['name' => 'larry'], $results->fetch('assoc'));
  2760. }
  2761. /**
  2762. * Tests that using the IS NOT operator will automatically translate to the best
  2763. * possible operator depending on the passed value
  2764. *
  2765. * @return void
  2766. */
  2767. public function testDirectIsNotNull()
  2768. {
  2769. $sql = (new Query($this->connection))
  2770. ->select(['name'])
  2771. ->from(['authors'])
  2772. ->where(['name IS NOT' => null])
  2773. ->sql();
  2774. $this->assertQuotedQuery('WHERE \(<name>\) IS NOT NULL', $sql, true);
  2775. $results = (new Query($this->connection))
  2776. ->select(['name'])
  2777. ->from(['authors'])
  2778. ->where(['name IS NOT' => 'larry'])
  2779. ->execute();
  2780. $this->assertCount(3, $results);
  2781. $this->assertNotEquals(['name' => 'larry'], $results->fetch('assoc'));
  2782. }
  2783. /**
  2784. * Tests that case statements work correctly for various use-cases.
  2785. *
  2786. * @return void
  2787. */
  2788. public function testSqlCaseStatement()
  2789. {
  2790. $query = new Query($this->connection);
  2791. $publishedCase = $query
  2792. ->newExpr()
  2793. ->addCase(
  2794. $query
  2795. ->newExpr()
  2796. ->add(['published' => 'Y']),
  2797. 1,
  2798. 'integer'
  2799. );
  2800. $notPublishedCase = $query
  2801. ->newExpr()
  2802. ->addCase(
  2803. $query
  2804. ->newExpr()
  2805. ->add(['published' => 'N']),
  2806. 1,
  2807. 'integer'
  2808. );
  2809. //Postgres requires the case statement to be cast to a integer
  2810. if ($this->connection->driver() instanceof \Cake\Database\Driver\Postgres) {
  2811. $publishedCase = $query->func()->cast([$publishedCase, 'integer' => 'literal'])->type(' AS ');
  2812. $notPublishedCase = $query->func()->cast([$notPublishedCase, 'integer' => 'literal'])->type(' AS ');
  2813. }
  2814. $results = $query
  2815. ->select([
  2816. 'published' => $query->func()->sum($publishedCase),
  2817. 'not_published' => $query->func()->sum($notPublishedCase)
  2818. ])
  2819. ->from(['comments'])
  2820. ->execute()
  2821. ->fetchAll('assoc');
  2822. $this->assertEquals(5, $results[0]['published']);
  2823. $this->assertEquals(1, $results[0]['not_published']);
  2824. $query = new Query($this->connection);
  2825. $query
  2826. ->insert(['article_id', 'user_id', 'comment', 'published'])
  2827. ->into('comments')
  2828. ->values([
  2829. 'article_id' => 2,
  2830. 'user_id' => 1,
  2831. 'comment' => 'In limbo',
  2832. 'published' => 'L'
  2833. ])
  2834. ->execute()
  2835. ->closeCursor();
  2836. $query = new Query($this->connection);
  2837. $conditions = [
  2838. $query
  2839. ->newExpr()
  2840. ->add(['published' => 'Y']),
  2841. $query
  2842. ->newExpr()
  2843. ->add(['published' => 'N'])
  2844. ];
  2845. $values = [
  2846. 'Published',
  2847. 'Not published',
  2848. 'None'
  2849. ];
  2850. $results = $query
  2851. ->select([
  2852. 'id',
  2853. 'comment',
  2854. 'status' => $query->newExpr()->addCase($conditions, $values)
  2855. ])
  2856. ->from(['comments'])
  2857. ->execute()
  2858. ->fetchAll('assoc');
  2859. $this->assertEquals('Published', $results[2]['status']);
  2860. $this->assertEquals('Not published', $results[3]['status']);
  2861. $this->assertEquals('None', $results[6]['status']);
  2862. }
  2863. /**
  2864. * Shows that bufferResults(false) will prevent client-side results buffering
  2865. *
  2866. * @return void
  2867. */
  2868. public function testUnbufferedQuery()
  2869. {
  2870. $query = new Query($this->connection);
  2871. $result = $query->select(['body', 'author_id'])
  2872. ->from('articles')
  2873. ->bufferResults(false)
  2874. ->execute();
  2875. if (!method_exists($result, 'bufferResults')) {
  2876. $result->closeCursor();
  2877. $this->skipIf(true, 'This driver does not support unbuffered queries');
  2878. }
  2879. $this->assertCount(0, $result);
  2880. $list = $result->fetchAll('assoc');
  2881. $this->assertCount(3, $list);
  2882. $result->closeCursor();
  2883. $query = new Query($this->connection);
  2884. $result = $query->select(['body', 'author_id'])
  2885. ->from('articles')
  2886. ->execute();
  2887. $this->assertCount(3, $result);
  2888. $list = $result->fetchAll('assoc');
  2889. $this->assertCount(3, $list);
  2890. $result->closeCursor();
  2891. }
  2892. /**
  2893. * Assertion for comparing a table's contents with what is in it.
  2894. *
  2895. * @param string $table
  2896. * @param int $count
  2897. * @param array $rows
  2898. * @param array $conditions
  2899. * @return void
  2900. */
  2901. public function assertTable($table, $count, $rows, $conditions = [])
  2902. {
  2903. $result = (new Query($this->connection))->select('*')
  2904. ->from($table)
  2905. ->where($conditions)
  2906. ->execute();
  2907. $this->assertCount($count, $result, 'Row count is incorrect');
  2908. $this->assertEquals($rows, $result->fetchAll('assoc'));
  2909. }
  2910. /**
  2911. * Assertion for comparing a regex pattern against a query having its identifiers
  2912. * quoted. It accepts queries quoted with the characters `<` and `>`. If the third
  2913. * parameter is set to true, it will alter the pattern to both accept quoted and
  2914. * unquoted queries
  2915. *
  2916. * @param string $pattern
  2917. * @param string $query the result to compare against
  2918. * @param bool $optional
  2919. * @return void
  2920. */
  2921. public function assertQuotedQuery($pattern, $query, $optional = false)
  2922. {
  2923. if ($optional) {
  2924. $optional = '?';
  2925. }
  2926. $pattern = str_replace('<', '[`"\[]' . $optional, $pattern);
  2927. $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
  2928. $this->assertRegExp('#' . $pattern . '#', $query);
  2929. }
  2930. }