QueryTest.php 117 KB

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