QueryTest.php 125 KB

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