QueryTest.php 131 KB

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