QueryTest.php 111 KB

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