QueryTest.php 110 KB

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