QueryTest.php 131 KB

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