QueryTest.php 112 KB

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