QueryTest.php 119 KB

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