QueryTest.php 136 KB

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