QueryTest.php 139 KB

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