QueryTest.php 108 KB

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