QueryTest.php 112 KB

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