MDB2.php 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id$
  47. //
  48. /**
  49. * @package MDB2
  50. * @category Database
  51. * @author Lukas Smith <smith@pooteeweet.org>
  52. */
  53. require_once 'PEAR.php';
  54. // {{{ Error constants
  55. /**
  56. * The method mapErrorCode in each MDB2_dbtype implementation maps
  57. * native error codes to one of these.
  58. *
  59. * If you add an error code here, make sure you also add a textual
  60. * version of it in MDB2::errorMessage().
  61. */
  62. define('MDB2_OK', true);
  63. define('MDB2_ERROR', -1);
  64. define('MDB2_ERROR_SYNTAX', -2);
  65. define('MDB2_ERROR_CONSTRAINT', -3);
  66. define('MDB2_ERROR_NOT_FOUND', -4);
  67. define('MDB2_ERROR_ALREADY_EXISTS', -5);
  68. define('MDB2_ERROR_UNSUPPORTED', -6);
  69. define('MDB2_ERROR_MISMATCH', -7);
  70. define('MDB2_ERROR_INVALID', -8);
  71. define('MDB2_ERROR_NOT_CAPABLE', -9);
  72. define('MDB2_ERROR_TRUNCATED', -10);
  73. define('MDB2_ERROR_INVALID_NUMBER', -11);
  74. define('MDB2_ERROR_INVALID_DATE', -12);
  75. define('MDB2_ERROR_DIVZERO', -13);
  76. define('MDB2_ERROR_NODBSELECTED', -14);
  77. define('MDB2_ERROR_CANNOT_CREATE', -15);
  78. define('MDB2_ERROR_CANNOT_DELETE', -16);
  79. define('MDB2_ERROR_CANNOT_DROP', -17);
  80. define('MDB2_ERROR_NOSUCHTABLE', -18);
  81. define('MDB2_ERROR_NOSUCHFIELD', -19);
  82. define('MDB2_ERROR_NEED_MORE_DATA', -20);
  83. define('MDB2_ERROR_NOT_LOCKED', -21);
  84. define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
  85. define('MDB2_ERROR_INVALID_DSN', -23);
  86. define('MDB2_ERROR_CONNECT_FAILED', -24);
  87. define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
  88. define('MDB2_ERROR_NOSUCHDB', -26);
  89. define('MDB2_ERROR_ACCESS_VIOLATION', -27);
  90. define('MDB2_ERROR_CANNOT_REPLACE', -28);
  91. define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
  92. define('MDB2_ERROR_DEADLOCK', -30);
  93. define('MDB2_ERROR_CANNOT_ALTER', -31);
  94. define('MDB2_ERROR_MANAGER', -32);
  95. define('MDB2_ERROR_MANAGER_PARSE', -33);
  96. define('MDB2_ERROR_LOADMODULE', -34);
  97. define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
  98. define('MDB2_ERROR_NO_PERMISSION', -36);
  99. define('MDB2_ERROR_DISCONNECT_FAILED', -37);
  100. // }}}
  101. // {{{ Verbose constants
  102. /**
  103. * These are just helper constants to more verbosely express parameters to prepare()
  104. */
  105. define('MDB2_PREPARE_MANIP', false);
  106. define('MDB2_PREPARE_RESULT', null);
  107. // }}}
  108. // {{{ Fetchmode constants
  109. /**
  110. * This is a special constant that tells MDB2 the user hasn't specified
  111. * any particular get mode, so the default should be used.
  112. */
  113. define('MDB2_FETCHMODE_DEFAULT', 0);
  114. /**
  115. * Column data indexed by numbers, ordered from 0 and up
  116. */
  117. define('MDB2_FETCHMODE_ORDERED', 1);
  118. /**
  119. * Column data indexed by column names
  120. */
  121. define('MDB2_FETCHMODE_ASSOC', 2);
  122. /**
  123. * Column data as object properties
  124. */
  125. define('MDB2_FETCHMODE_OBJECT', 3);
  126. /**
  127. * For multi-dimensional results: normally the first level of arrays
  128. * is the row number, and the second level indexed by column number or name.
  129. * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
  130. * is the column name, and the second level the row number.
  131. */
  132. define('MDB2_FETCHMODE_FLIPPED', 4);
  133. // }}}
  134. // {{{ Portability mode constants
  135. /**
  136. * Portability: turn off all portability features.
  137. * @see MDB2_Driver_Common::setOption()
  138. */
  139. define('MDB2_PORTABILITY_NONE', 0);
  140. /**
  141. * Portability: convert names of tables and fields to case defined in the
  142. * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
  143. * @see MDB2_Driver_Common::setOption()
  144. */
  145. define('MDB2_PORTABILITY_FIX_CASE', 1);
  146. /**
  147. * Portability: right trim the data output by query*() and fetch*().
  148. * @see MDB2_Driver_Common::setOption()
  149. */
  150. define('MDB2_PORTABILITY_RTRIM', 2);
  151. /**
  152. * Portability: force reporting the number of rows deleted.
  153. * @see MDB2_Driver_Common::setOption()
  154. */
  155. define('MDB2_PORTABILITY_DELETE_COUNT', 4);
  156. /**
  157. * Portability: not needed in MDB2 (just left here for compatibility to DB)
  158. * @see MDB2_Driver_Common::setOption()
  159. */
  160. define('MDB2_PORTABILITY_NUMROWS', 8);
  161. /**
  162. * Portability: makes certain error messages in certain drivers compatible
  163. * with those from other DBMS's.
  164. *
  165. * + mysql, mysqli: change unique/primary key constraints
  166. * MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
  167. *
  168. * + odbc(access): MS's ODBC driver reports 'no such field' as code
  169. * 07001, which means 'too few parameters.' When this option is on
  170. * that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
  171. *
  172. * @see MDB2_Driver_Common::setOption()
  173. */
  174. define('MDB2_PORTABILITY_ERRORS', 16);
  175. /**
  176. * Portability: convert empty values to null strings in data output by
  177. * query*() and fetch*().
  178. * @see MDB2_Driver_Common::setOption()
  179. */
  180. define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
  181. /**
  182. * Portability: removes database/table qualifiers from associative indexes
  183. * @see MDB2_Driver_Common::setOption()
  184. */
  185. define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
  186. /**
  187. * Portability: turn on all portability features.
  188. * @see MDB2_Driver_Common::setOption()
  189. */
  190. define('MDB2_PORTABILITY_ALL', 127);
  191. // }}}
  192. // {{{ Globals for class instance tracking
  193. /**
  194. * These are global variables that are used to track the various class instances
  195. */
  196. $GLOBALS['_MDB2_databases'] = array();
  197. $GLOBALS['_MDB2_dsninfo_default'] = array(
  198. 'phptype' => false,
  199. 'dbsyntax' => false,
  200. 'username' => false,
  201. 'password' => false,
  202. 'protocol' => false,
  203. 'hostspec' => false,
  204. 'port' => false,
  205. 'socket' => false,
  206. 'database' => false,
  207. 'mode' => false,
  208. );
  209. // }}}
  210. // {{{ class MDB2
  211. /**
  212. * The main 'MDB2' class is simply a container class with some static
  213. * methods for creating DB objects as well as some utility functions
  214. * common to all parts of DB.
  215. *
  216. * The object model of MDB2 is as follows (indentation means inheritance):
  217. *
  218. * MDB2 The main MDB2 class. This is simply a utility class
  219. * with some 'static' methods for creating MDB2 objects as
  220. * well as common utility functions for other MDB2 classes.
  221. *
  222. * MDB2_Driver_Common The base for each MDB2 implementation. Provides default
  223. * | implementations (in OO lingo virtual methods) for
  224. * | the actual DB implementations as well as a bunch of
  225. * | query utility functions.
  226. * |
  227. * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
  228. * When calling MDB2::factory or MDB2::connect for MySQL
  229. * connections, the object returned is an instance of this
  230. * class.
  231. * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
  232. * When calling MDB2::factory or MDB2::connect for PostGreSQL
  233. * connections, the object returned is an instance of this
  234. * class.
  235. *
  236. * @package MDB2
  237. * @category Database
  238. * @author Lukas Smith <smith@pooteeweet.org>
  239. */
  240. class MDB2
  241. {
  242. // {{{ function setOptions($db, $options)
  243. /**
  244. * set option array in an exiting database object
  245. *
  246. * @param MDB2_Driver_Common MDB2 object
  247. * @param array An associative array of option names and their values.
  248. *
  249. * @return mixed MDB2_OK or a PEAR Error object
  250. *
  251. * @access public
  252. */
  253. static function setOptions($db, $options)
  254. {
  255. if (is_array($options)) {
  256. foreach ($options as $option => $value) {
  257. $test = $db->setOption($option, $value);
  258. if (MDB2::isError($test)) {
  259. return $test;
  260. }
  261. }
  262. }
  263. return MDB2_OK;
  264. }
  265. // }}}
  266. // {{{ function classExists($classname)
  267. /**
  268. * Checks if a class exists without triggering __autoload
  269. *
  270. * @param string classname
  271. *
  272. * @return bool true success and false on error
  273. * @static
  274. * @access public
  275. */
  276. static function classExists($classname)
  277. {
  278. return class_exists($classname, false);
  279. }
  280. // }}}
  281. // {{{ function loadClass($class_name, $debug)
  282. /**
  283. * Loads a PEAR class.
  284. *
  285. * @param string classname to load
  286. * @param bool if errors should be suppressed
  287. *
  288. * @return mixed true success or PEAR_Error on failure
  289. *
  290. * @access public
  291. */
  292. static function loadClass($class_name, $debug)
  293. {
  294. if (!MDB2::classExists($class_name)) {
  295. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  296. if ($debug) {
  297. $include = include_once($file_name);
  298. } else {
  299. $include = @include_once($file_name);
  300. }
  301. if (!$include) {
  302. if (!MDB2::fileExists($file_name)) {
  303. $msg = "unable to find package '$class_name' file '$file_name'";
  304. } else {
  305. $msg = "unable to load class '$class_name' from file '$file_name'";
  306. }
  307. $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
  308. return $err;
  309. }
  310. if (!MDB2::classExists($class_name)) {
  311. $msg = "unable to load class '$class_name' from file '$file_name'";
  312. $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
  313. return $err;
  314. }
  315. }
  316. return MDB2_OK;
  317. }
  318. // }}}
  319. // {{{ function factory($dsn, $options = false)
  320. /**
  321. * Create a new MDB2 object for the specified database type
  322. *
  323. * @param mixed 'data source name', see the MDB2::parseDSN
  324. * method for a description of the dsn format.
  325. * Can also be specified as an array of the
  326. * format returned by MDB2::parseDSN.
  327. * @param array An associative array of option names and
  328. * their values.
  329. *
  330. * @return mixed a newly created MDB2 object, or false on error
  331. *
  332. * @access public
  333. */
  334. static function factory($dsn, $options = false)
  335. {
  336. $dsninfo = MDB2::parseDSN($dsn);
  337. if (empty($dsninfo['phptype'])) {
  338. $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
  339. null, null, 'no RDBMS driver specified');
  340. return $err;
  341. }
  342. $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
  343. $debug = (!empty($options['debug']));
  344. $err = MDB2::loadClass($class_name, $debug);
  345. if (MDB2::isError($err)) {
  346. return $err;
  347. }
  348. $db = new $class_name();
  349. $db->setDSN($dsninfo);
  350. $err = MDB2::setOptions($db, $options);
  351. if (MDB2::isError($err)) {
  352. return $err;
  353. }
  354. return $db;
  355. }
  356. // }}}
  357. // {{{ function connect($dsn, $options = false)
  358. /**
  359. * Create a new MDB2_Driver_* connection object and connect to the specified
  360. * database
  361. *
  362. * @param mixed $dsn 'data source name', see the MDB2::parseDSN
  363. * method for a description of the dsn format.
  364. * Can also be specified as an array of the
  365. * format returned by MDB2::parseDSN.
  366. * @param array $options An associative array of option names and
  367. * their values.
  368. *
  369. * @return mixed a newly created MDB2 connection object, or a MDB2
  370. * error object on error
  371. *
  372. * @access public
  373. * @see MDB2::parseDSN
  374. */
  375. static function connect($dsn, $options = false)
  376. {
  377. $db = MDB2::factory($dsn, $options);
  378. if (MDB2::isError($db)) {
  379. return $db;
  380. }
  381. $err = $db->connect();
  382. if (MDB2::isError($err)) {
  383. $dsn = $db->getDSN('string', 'xxx');
  384. $db->disconnect();
  385. $err->addUserInfo($dsn);
  386. return $err;
  387. }
  388. return $db;
  389. }
  390. // }}}
  391. // {{{ function singleton($dsn = null, $options = false)
  392. /**
  393. * Returns a MDB2 connection with the requested DSN.
  394. * A new MDB2 connection object is only created if no object with the
  395. * requested DSN exists yet.
  396. *
  397. * @param mixed 'data source name', see the MDB2::parseDSN
  398. * method for a description of the dsn format.
  399. * Can also be specified as an array of the
  400. * format returned by MDB2::parseDSN.
  401. * @param array An associative array of option names and
  402. * their values.
  403. *
  404. * @return mixed a newly created MDB2 connection object, or a MDB2
  405. * error object on error
  406. *
  407. * @access public
  408. * @see MDB2::parseDSN
  409. */
  410. static function singleton($dsn = null, $options = false)
  411. {
  412. if ($dsn) {
  413. $dsninfo = MDB2::parseDSN($dsn);
  414. $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
  415. $keys = array_keys($GLOBALS['_MDB2_databases']);
  416. for ($i=0, $j=count($keys); $i<$j; ++$i) {
  417. if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
  418. $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
  419. if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
  420. MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
  421. return $GLOBALS['_MDB2_databases'][$keys[$i]];
  422. }
  423. }
  424. }
  425. } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
  426. return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
  427. }
  428. $db = MDB2::factory($dsn, $options);
  429. return $db;
  430. }
  431. // }}}
  432. // {{{ function areEquals()
  433. /**
  434. * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
  435. * so use this method instead.
  436. * @see http://pear.php.net/bugs/bug.php?id=11790
  437. *
  438. * @param array $arr1
  439. * @param array $arr2
  440. * @return boolean
  441. */
  442. static function areEquals($arr1, $arr2)
  443. {
  444. if (count($arr1) != count($arr2)) {
  445. return false;
  446. }
  447. foreach (array_keys($arr1) as $k) {
  448. if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
  449. return false;
  450. }
  451. }
  452. return true;
  453. }
  454. // }}}
  455. // {{{ function loadFile($file)
  456. /**
  457. * load a file (like 'Date')
  458. *
  459. * @param string $file name of the file in the MDB2 directory (without '.php')
  460. *
  461. * @return string name of the file that was included
  462. *
  463. * @access public
  464. */
  465. static function loadFile($file)
  466. {
  467. $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
  468. if (!MDB2::fileExists($file_name)) {
  469. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  470. 'unable to find: '.$file_name);
  471. }
  472. if (!include_once($file_name)) {
  473. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  474. 'unable to load driver class: '.$file_name);
  475. }
  476. return $file_name;
  477. }
  478. // }}}
  479. // {{{ function apiVersion()
  480. /**
  481. * Return the MDB2 API version
  482. *
  483. * @return string the MDB2 API version number
  484. *
  485. * @access public
  486. */
  487. function apiVersion()
  488. {
  489. return '@package_version@';
  490. }
  491. // }}}
  492. // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  493. /**
  494. * This method is used to communicate an error and invoke error
  495. * callbacks etc. Basically a wrapper for PEAR::raiseError
  496. * without the message string.
  497. *
  498. * @param mixed int error code
  499. *
  500. * @param int error mode, see PEAR_Error docs
  501. *
  502. * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
  503. * error level (E_USER_NOTICE etc). If error mode is
  504. * PEAR_ERROR_CALLBACK, this is the callback function,
  505. * either as a function name, or as an array of an
  506. * object and method name. For other error modes this
  507. * parameter is ignored.
  508. *
  509. * @param string Extra debug information. Defaults to the last
  510. * query and native error code.
  511. *
  512. * @return PEAR_Error instance of a PEAR Error object
  513. *
  514. * @access private
  515. * @see PEAR_Error
  516. */
  517. public static function &raiseError($code = null,
  518. $mode = null,
  519. $options = null,
  520. $userinfo = null,
  521. $dummy1 = null,
  522. $dummy2 = null,
  523. $dummy3 = false)
  524. {
  525. $pear = new PEAR;
  526. $err = $pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
  527. return $err;
  528. }
  529. // }}}
  530. // {{{ function isError($data, $code = null)
  531. /**
  532. * Tell whether a value is a MDB2 error.
  533. *
  534. * @param mixed the value to test
  535. * @param int if is an error object, return true
  536. * only if $code is a string and
  537. * $db->getMessage() == $code or
  538. * $code is an integer and $db->getCode() == $code
  539. *
  540. * @return bool true if parameter is an error
  541. *
  542. * @access public
  543. */
  544. static function isError($data, $code = null)
  545. {
  546. if ($data instanceof MDB2_Error) {
  547. if (null === $code) {
  548. return true;
  549. }
  550. if (is_string($code)) {
  551. return $data->getMessage() === $code;
  552. }
  553. return in_array($data->getCode(), (array)$code);
  554. }
  555. return false;
  556. }
  557. // }}}
  558. // {{{ function isConnection($value)
  559. /**
  560. * Tell whether a value is a MDB2 connection
  561. *
  562. * @param mixed value to test
  563. *
  564. * @return bool whether $value is a MDB2 connection
  565. * @access public
  566. */
  567. static function isConnection($value)
  568. {
  569. return ($value instanceof MDB2_Driver_Common);
  570. }
  571. // }}}
  572. // {{{ function isResult($value)
  573. /**
  574. * Tell whether a value is a MDB2 result
  575. *
  576. * @param mixed $value value to test
  577. *
  578. * @return bool whether $value is a MDB2 result
  579. *
  580. * @access public
  581. */
  582. function isResult($value)
  583. {
  584. return ($value instanceof MDB2_Result);
  585. }
  586. // }}}
  587. // {{{ function isResultCommon($value)
  588. /**
  589. * Tell whether a value is a MDB2 result implementing the common interface
  590. *
  591. * @param mixed $value value to test
  592. *
  593. * @return bool whether $value is a MDB2 result implementing the common interface
  594. *
  595. * @access public
  596. */
  597. static function isResultCommon($value)
  598. {
  599. return ($value instanceof MDB2_Result_Common);
  600. }
  601. // }}}
  602. // {{{ function isStatement($value)
  603. /**
  604. * Tell whether a value is a MDB2 statement interface
  605. *
  606. * @param mixed value to test
  607. *
  608. * @return bool whether $value is a MDB2 statement interface
  609. *
  610. * @access public
  611. */
  612. function isStatement($value)
  613. {
  614. return ($value instanceof MDB2_Statement_Common);
  615. }
  616. // }}}
  617. // {{{ function errorMessage($value = null)
  618. /**
  619. * Return a textual error message for a MDB2 error code
  620. *
  621. * @param int|array integer error code,
  622. null to get the current error code-message map,
  623. or an array with a new error code-message map
  624. *
  625. * @return string error message, or false if the error code was
  626. * not recognized
  627. *
  628. * @access public
  629. */
  630. static function errorMessage($value = null)
  631. {
  632. static $errorMessages;
  633. if (is_array($value)) {
  634. $errorMessages = $value;
  635. return MDB2_OK;
  636. }
  637. if (!isset($errorMessages)) {
  638. $errorMessages = array(
  639. MDB2_OK => 'no error',
  640. MDB2_ERROR => 'unknown error',
  641. MDB2_ERROR_ALREADY_EXISTS => 'already exists',
  642. MDB2_ERROR_CANNOT_CREATE => 'can not create',
  643. MDB2_ERROR_CANNOT_ALTER => 'can not alter',
  644. MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
  645. MDB2_ERROR_CANNOT_DELETE => 'can not delete',
  646. MDB2_ERROR_CANNOT_DROP => 'can not drop',
  647. MDB2_ERROR_CONSTRAINT => 'constraint violation',
  648. MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
  649. MDB2_ERROR_DIVZERO => 'division by zero',
  650. MDB2_ERROR_INVALID => 'invalid',
  651. MDB2_ERROR_INVALID_DATE => 'invalid date or time',
  652. MDB2_ERROR_INVALID_NUMBER => 'invalid number',
  653. MDB2_ERROR_MISMATCH => 'mismatch',
  654. MDB2_ERROR_NODBSELECTED => 'no database selected',
  655. MDB2_ERROR_NOSUCHFIELD => 'no such field',
  656. MDB2_ERROR_NOSUCHTABLE => 'no such table',
  657. MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
  658. MDB2_ERROR_NOT_FOUND => 'not found',
  659. MDB2_ERROR_NOT_LOCKED => 'not locked',
  660. MDB2_ERROR_SYNTAX => 'syntax error',
  661. MDB2_ERROR_UNSUPPORTED => 'not supported',
  662. MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  663. MDB2_ERROR_INVALID_DSN => 'invalid DSN',
  664. MDB2_ERROR_CONNECT_FAILED => 'connect failed',
  665. MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
  666. MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  667. MDB2_ERROR_NOSUCHDB => 'no such database',
  668. MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
  669. MDB2_ERROR_LOADMODULE => 'error while including on demand module',
  670. MDB2_ERROR_TRUNCATED => 'truncated',
  671. MDB2_ERROR_DEADLOCK => 'deadlock detected',
  672. MDB2_ERROR_NO_PERMISSION => 'no permission',
  673. MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed',
  674. );
  675. }
  676. if (null === $value) {
  677. return $errorMessages;
  678. }
  679. if (MDB2::isError($value)) {
  680. $value = $value->getCode();
  681. }
  682. return isset($errorMessages[$value]) ?
  683. $errorMessages[$value] : $errorMessages[MDB2_ERROR];
  684. }
  685. // }}}
  686. // {{{ function parseDSN($dsn)
  687. /**
  688. * Parse a data source name.
  689. *
  690. * Additional keys can be added by appending a URI query string to the
  691. * end of the DSN.
  692. *
  693. * The format of the supplied DSN is in its fullest form:
  694. * <code>
  695. * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
  696. * </code>
  697. *
  698. * Most variations are allowed:
  699. * <code>
  700. * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
  701. * phptype://username:password@hostspec/database_name
  702. * phptype://username:password@hostspec
  703. * phptype://username@hostspec
  704. * phptype://hostspec/database
  705. * phptype://hostspec
  706. * phptype(dbsyntax)
  707. * phptype
  708. * </code>
  709. *
  710. * @param string Data Source Name to be parsed
  711. *
  712. * @return array an associative array with the following keys:
  713. * + phptype: Database backend used in PHP (mysql, odbc etc.)
  714. * + dbsyntax: Database used with regards to SQL syntax etc.
  715. * + protocol: Communication protocol to use (tcp, unix etc.)
  716. * + hostspec: Host specification (hostname[:port])
  717. * + database: Database to use on the DBMS server
  718. * + username: User name for login
  719. * + password: Password for login
  720. *
  721. * @access public
  722. * @author Tomas V.V.Cox <cox@idecnet.com>
  723. */
  724. static function parseDSN($dsn)
  725. {
  726. $parsed = $GLOBALS['_MDB2_dsninfo_default'];
  727. if (is_array($dsn)) {
  728. $dsn = array_merge($parsed, $dsn);
  729. if (!$dsn['dbsyntax']) {
  730. $dsn['dbsyntax'] = $dsn['phptype'];
  731. }
  732. return $dsn;
  733. }
  734. // Find phptype and dbsyntax
  735. if (($pos = strpos($dsn, '://')) !== false) {
  736. $str = substr($dsn, 0, $pos);
  737. $dsn = substr($dsn, $pos + 3);
  738. } else {
  739. $str = $dsn;
  740. $dsn = null;
  741. }
  742. // Get phptype and dbsyntax
  743. // $str => phptype(dbsyntax)
  744. if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  745. $parsed['phptype'] = $arr[1];
  746. $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
  747. } else {
  748. $parsed['phptype'] = $str;
  749. $parsed['dbsyntax'] = $str;
  750. }
  751. if (!count($dsn)) {
  752. return $parsed;
  753. }
  754. // Get (if found): username and password
  755. // $dsn => username:password@protocol+hostspec/database
  756. if (($at = strrpos($dsn,'@')) !== false) {
  757. $str = substr($dsn, 0, $at);
  758. $dsn = substr($dsn, $at + 1);
  759. if (($pos = strpos($str, ':')) !== false) {
  760. $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  761. $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  762. } else {
  763. $parsed['username'] = rawurldecode($str);
  764. }
  765. }
  766. // Find protocol and hostspec
  767. // $dsn => proto(proto_opts)/database
  768. if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  769. $proto = $match[1];
  770. $proto_opts = $match[2] ? $match[2] : false;
  771. $dsn = $match[3];
  772. // $dsn => protocol+hostspec/database (old format)
  773. } else {
  774. if (strpos($dsn, '+') !== false) {
  775. list($proto, $dsn) = explode('+', $dsn, 2);
  776. }
  777. if ( strpos($dsn, '//') === 0
  778. && strpos($dsn, '/', 2) !== false
  779. && $parsed['phptype'] == 'oci8'
  780. ) {
  781. //oracle's "Easy Connect" syntax:
  782. //"username/password@[//]host[:port][/service_name]"
  783. //e.g. "scott/tiger@//mymachine:1521/oracle"
  784. $proto_opts = $dsn;
  785. $pos = strrpos($proto_opts, '/');
  786. $dsn = substr($proto_opts, $pos + 1);
  787. $proto_opts = substr($proto_opts, 0, $pos);
  788. } elseif (strpos($dsn, '/') !== false) {
  789. list($proto_opts, $dsn) = explode('/', $dsn, 2);
  790. } else {
  791. $proto_opts = $dsn;
  792. $dsn = null;
  793. }
  794. }
  795. // process the different protocol options
  796. $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  797. $proto_opts = rawurldecode($proto_opts);
  798. if (strpos($proto_opts, ':') !== false) {
  799. list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
  800. }
  801. if ($parsed['protocol'] == 'tcp') {
  802. $parsed['hostspec'] = $proto_opts;
  803. } elseif ($parsed['protocol'] == 'unix') {
  804. $parsed['socket'] = $proto_opts;
  805. }
  806. // Get dabase if any
  807. // $dsn => database
  808. if ($dsn) {
  809. // /database
  810. if (($pos = strpos($dsn, '?')) === false) {
  811. $parsed['database'] = rawurldecode($dsn);
  812. // /database?param1=value1&param2=value2
  813. } else {
  814. $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
  815. $dsn = substr($dsn, $pos + 1);
  816. if (strpos($dsn, '&') !== false) {
  817. $opts = explode('&', $dsn);
  818. } else { // database?param1=value1
  819. $opts = array($dsn);
  820. }
  821. foreach ($opts as $opt) {
  822. list($key, $value) = explode('=', $opt);
  823. if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
  824. // don't allow params overwrite
  825. $parsed[$key] = rawurldecode($value);
  826. }
  827. }
  828. }
  829. }
  830. return $parsed;
  831. }
  832. // }}}
  833. // {{{ function fileExists($file)
  834. /**
  835. * Checks if a file exists in the include path
  836. *
  837. * @param string filename
  838. *
  839. * @return bool true success and false on error
  840. *
  841. * @access public
  842. */
  843. static function fileExists($file)
  844. {
  845. // safe_mode does notwork with is_readable()
  846. if (!@ini_get('safe_mode')) {
  847. $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
  848. foreach ($dirs as $dir) {
  849. if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
  850. return true;
  851. }
  852. }
  853. } else {
  854. $fp = @fopen($file, 'r', true);
  855. if (is_resource($fp)) {
  856. @fclose($fp);
  857. return true;
  858. }
  859. }
  860. return false;
  861. }
  862. // }}}
  863. }
  864. // }}}
  865. // {{{ class MDB2_Error extends PEAR_Error
  866. /**
  867. * MDB2_Error implements a class for reporting portable database error
  868. * messages.
  869. *
  870. * @package MDB2
  871. * @category Database
  872. * @author Stig Bakken <ssb@fast.no>
  873. */
  874. class MDB2_Error extends PEAR_Error
  875. {
  876. // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
  877. /**
  878. * MDB2_Error constructor.
  879. *
  880. * @param mixed MDB2 error code, or string with error message.
  881. * @param int what 'error mode' to operate in
  882. * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER
  883. * @param mixed additional debug info, such as the last query
  884. */
  885. function __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
  886. $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
  887. {
  888. if (null === $code) {
  889. $code = MDB2_ERROR;
  890. }
  891. $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
  892. $mode, $level, $debuginfo);
  893. }
  894. // }}}
  895. }
  896. // }}}
  897. // {{{ class MDB2_Driver_Common extends PEAR
  898. /**
  899. * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
  900. *
  901. * @package MDB2
  902. * @category Database
  903. * @author Lukas Smith <smith@pooteeweet.org>
  904. */
  905. class MDB2_Driver_Common
  906. {
  907. // {{{ Variables (Properties)
  908. /**
  909. * @var MDB2_Driver_Datatype_Common
  910. */
  911. public $datatype;
  912. /**
  913. * @var MDB2_Extended
  914. */
  915. public $extended;
  916. /**
  917. * @var MDB2_Driver_Function_Common
  918. */
  919. public $function;
  920. /**
  921. * @var MDB2_Driver_Manager_Common
  922. */
  923. public $manager;
  924. /**
  925. * @var MDB2_Driver_Native_Commonn
  926. */
  927. public $native;
  928. /**
  929. * @var MDB2_Driver_Reverse_Common
  930. */
  931. public $reverse;
  932. /**
  933. * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
  934. * @var int
  935. * @access public
  936. */
  937. public $db_index = 0;
  938. /**
  939. * DSN used for the next query
  940. * @var array
  941. * @access protected
  942. */
  943. public $dsn = array();
  944. /**
  945. * DSN that was used to create the current connection
  946. * @var array
  947. * @access protected
  948. */
  949. public $connected_dsn = array();
  950. /**
  951. * connection resource
  952. * @var mixed
  953. * @access protected
  954. */
  955. public $connection = 0;
  956. /**
  957. * if the current opened connection is a persistent connection
  958. * @var bool
  959. * @access protected
  960. */
  961. public $opened_persistent;
  962. /**
  963. * the name of the database for the next query
  964. * @var string
  965. * @access public
  966. */
  967. public $database_name = '';
  968. /**
  969. * the name of the database currently selected
  970. * @var string
  971. * @access protected
  972. */
  973. public $connected_database_name = '';
  974. /**
  975. * server version information
  976. * @var string
  977. * @access protected
  978. */
  979. public $connected_server_info = '';
  980. /**
  981. * list of all supported features of the given driver
  982. * @var array
  983. * @access public
  984. */
  985. public $supported = array(
  986. 'sequences' => false,
  987. 'indexes' => false,
  988. 'affected_rows' => false,
  989. 'summary_functions' => false,
  990. 'order_by_text' => false,
  991. 'transactions' => false,
  992. 'savepoints' => false,
  993. 'current_id' => false,
  994. 'limit_queries' => false,
  995. 'LOBs' => false,
  996. 'replace' => false,
  997. 'sub_selects' => false,
  998. 'triggers' => false,
  999. 'auto_increment' => false,
  1000. 'primary_key' => false,
  1001. 'result_introspection' => false,
  1002. 'prepared_statements' => false,
  1003. 'identifier_quoting' => false,
  1004. 'pattern_escaping' => false,
  1005. 'new_link' => false,
  1006. );
  1007. /**
  1008. * Array of supported options that can be passed to the MDB2 instance.
  1009. *
  1010. * The options can be set during object creation, using
  1011. * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
  1012. * also be set after the object is created, using MDB2::setOptions() or
  1013. * MDB2_Driver_Common::setOption().
  1014. * The list of available option includes:
  1015. * <ul>
  1016. * <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
  1017. * <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
  1018. * <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
  1019. * <li>$options['result_class'] -> string: class used for result sets</li>
  1020. * <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
  1021. * <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
  1022. * <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
  1023. * <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
  1024. * <li>$options['persistent'] -> boolean: persistent connection?</li>
  1025. * <li>$options['debug'] -> integer: numeric debug level</li>
  1026. * <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
  1027. * <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
  1028. * <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
  1029. * <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
  1030. * <li>$options['log_line_break'] -> string: line-break format</li>
  1031. * <li>$options['idxname_format'] -> string: pattern for index name</li>
  1032. * <li>$options['seqname_format'] -> string: pattern for sequence name</li>
  1033. * <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
  1034. * <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
  1035. * <li>$options['seqcol_name'] -> string: sequence column name</li>
  1036. * <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
  1037. * <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
  1038. * <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
  1039. * <li>$options['portability'] -> integer: portability constant</li>
  1040. * <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
  1041. * <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
  1042. * <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
  1043. * <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
  1044. * <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
  1045. * <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
  1046. * <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
  1047. * <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
  1048. * <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
  1049. * </ul>
  1050. *
  1051. * @var array
  1052. * @access public
  1053. * @see MDB2::connect()
  1054. * @see MDB2::factory()
  1055. * @see MDB2::singleton()
  1056. * @see MDB2_Driver_Common::setOption()
  1057. */
  1058. public $options = array(
  1059. 'ssl' => false,
  1060. 'field_case' => CASE_LOWER,
  1061. 'disable_query' => false,
  1062. 'result_class' => 'MDB2_Result_%s',
  1063. 'buffered_result_class' => 'MDB2_BufferedResult_%s',
  1064. 'result_wrap_class' => false,
  1065. 'result_buffering' => true,
  1066. 'fetch_class' => 'stdClass',
  1067. 'persistent' => false,
  1068. 'debug' => 0,
  1069. 'debug_handler' => 'MDB2_defaultDebugOutput',
  1070. 'debug_expanded_output' => false,
  1071. 'default_text_field_length' => 4096,
  1072. 'lob_buffer_length' => 8192,
  1073. 'log_line_break' => "\n",
  1074. 'idxname_format' => '%s_idx',
  1075. 'seqname_format' => '%s_seq',
  1076. 'savepoint_format' => 'MDB2_SAVEPOINT_%s',
  1077. 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
  1078. 'seqcol_name' => 'sequence',
  1079. 'quote_identifier' => false,
  1080. 'use_transactions' => true,
  1081. 'decimal_places' => 2,
  1082. 'portability' => MDB2_PORTABILITY_ALL,
  1083. 'modules' => array(
  1084. 'ex' => 'Extended',
  1085. 'dt' => 'Datatype',
  1086. 'mg' => 'Manager',
  1087. 'rv' => 'Reverse',
  1088. 'na' => 'Native',
  1089. 'fc' => 'Function',
  1090. ),
  1091. 'emulate_prepared' => false,
  1092. 'datatype_map' => array(),
  1093. 'datatype_map_callback' => array(),
  1094. 'nativetype_map_callback' => array(),
  1095. 'lob_allow_url_include' => false,
  1096. 'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
  1097. 'max_identifiers_length' => 30,
  1098. 'default_fk_action_onupdate' => 'RESTRICT',
  1099. 'default_fk_action_ondelete' => 'RESTRICT',
  1100. );
  1101. /**
  1102. * string array
  1103. * @var string
  1104. * @access public
  1105. */
  1106. public $string_quoting = array(
  1107. 'start' => "'",
  1108. 'end' => "'",
  1109. 'escape' => false,
  1110. 'escape_pattern' => false,
  1111. );
  1112. /**
  1113. * identifier quoting
  1114. * @var array
  1115. * @access public
  1116. */
  1117. public $identifier_quoting = array(
  1118. 'start' => '"',
  1119. 'end' => '"',
  1120. 'escape' => '"',
  1121. );
  1122. /**
  1123. * sql comments
  1124. * @var array
  1125. * @access protected
  1126. */
  1127. public $sql_comments = array(
  1128. array('start' => '--', 'end' => "\n", 'escape' => false),
  1129. array('start' => '/*', 'end' => '*/', 'escape' => false),
  1130. );
  1131. /**
  1132. * comparision wildcards
  1133. * @var array
  1134. * @access protected
  1135. */
  1136. protected $wildcards = array('%', '_');
  1137. /**
  1138. * column alias keyword
  1139. * @var string
  1140. * @access protected
  1141. */
  1142. public $as_keyword = ' AS ';
  1143. /**
  1144. * warnings
  1145. * @var array
  1146. * @access protected
  1147. */
  1148. public $warnings = array();
  1149. /**
  1150. * string with the debugging information
  1151. * @var string
  1152. * @access public
  1153. */
  1154. public $debug_output = '';
  1155. /**
  1156. * determine if there is an open transaction
  1157. * @var bool
  1158. * @access protected
  1159. */
  1160. public $in_transaction = false;
  1161. /**
  1162. * the smart transaction nesting depth
  1163. * @var int
  1164. * @access protected
  1165. */
  1166. public $nested_transaction_counter = null;
  1167. /**
  1168. * the first error that occured inside a nested transaction
  1169. * @var MDB2_Error|bool
  1170. * @access protected
  1171. */
  1172. protected $has_transaction_error = false;
  1173. /**
  1174. * result offset used in the next query
  1175. * @var int
  1176. * @access public
  1177. */
  1178. public $offset = 0;
  1179. /**
  1180. * result limit used in the next query
  1181. * @var int
  1182. * @access public
  1183. */
  1184. public $limit = 0;
  1185. /**
  1186. * Database backend used in PHP (mysql, odbc etc.)
  1187. * @var string
  1188. * @access public
  1189. */
  1190. public $phptype;
  1191. /**
  1192. * Database used with regards to SQL syntax etc.
  1193. * @var string
  1194. * @access public
  1195. */
  1196. public $dbsyntax;
  1197. /**
  1198. * the last query sent to the driver
  1199. * @var string
  1200. * @access public
  1201. */
  1202. public $last_query;
  1203. /**
  1204. * the default fetchmode used
  1205. * @var int
  1206. * @access public
  1207. */
  1208. public $fetchmode = MDB2_FETCHMODE_ORDERED;
  1209. /**
  1210. * array of module instances
  1211. * @var array
  1212. * @access protected
  1213. */
  1214. protected $modules = array();
  1215. /**
  1216. * determines of the PHP4 destructor emulation has been enabled yet
  1217. * @var array
  1218. * @access protected
  1219. */
  1220. protected $destructor_registered = true;
  1221. /**
  1222. * @var PEAR
  1223. */
  1224. protected $pear;
  1225. // }}}
  1226. // {{{ constructor: function __construct()
  1227. /**
  1228. * Constructor
  1229. */
  1230. function __construct()
  1231. {
  1232. end($GLOBALS['_MDB2_databases']);
  1233. $db_index = key($GLOBALS['_MDB2_databases']) + 1;
  1234. $GLOBALS['_MDB2_databases'][$db_index] = &$this;
  1235. $this->db_index = $db_index;
  1236. $this->pear = new PEAR;
  1237. }
  1238. // }}}
  1239. // {{{ destructor: function __destruct()
  1240. /**
  1241. * Destructor
  1242. */
  1243. function __destruct()
  1244. {
  1245. $this->disconnect(false);
  1246. }
  1247. // }}}
  1248. // {{{ function free()
  1249. /**
  1250. * Free the internal references so that the instance can be destroyed
  1251. *
  1252. * @return bool true on success, false if result is invalid
  1253. *
  1254. * @access public
  1255. */
  1256. function free()
  1257. {
  1258. unset($GLOBALS['_MDB2_databases'][$this->db_index]);
  1259. unset($this->db_index);
  1260. return MDB2_OK;
  1261. }
  1262. // }}}
  1263. // {{{ function __toString()
  1264. /**
  1265. * String conversation
  1266. *
  1267. * @return string representation of the object
  1268. *
  1269. * @access public
  1270. */
  1271. function __toString()
  1272. {
  1273. $info = get_class($this);
  1274. $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
  1275. if ($this->connection) {
  1276. $info.= ' [connected]';
  1277. }
  1278. return $info;
  1279. }
  1280. // }}}
  1281. // {{{ function errorInfo($error = null)
  1282. /**
  1283. * This method is used to collect information about an error
  1284. *
  1285. * @param mixed error code or resource
  1286. *
  1287. * @return array with MDB2 errorcode, native error code, native message
  1288. *
  1289. * @access public
  1290. */
  1291. function errorInfo($error = null)
  1292. {
  1293. return array($error, null, null);
  1294. }
  1295. // }}}
  1296. // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  1297. /**
  1298. * This method is used to communicate an error and invoke error
  1299. * callbacks etc. Basically a wrapper for PEAR::raiseError
  1300. * without the message string.
  1301. *
  1302. * @param mixed $code integer error code, or a PEAR error object (all
  1303. * other parameters are ignored if this parameter is
  1304. * an object
  1305. * @param int $mode error mode, see PEAR_Error docs
  1306. * @param mixed $options If error mode is PEAR_ERROR_TRIGGER, this is the
  1307. * error level (E_USER_NOTICE etc). If error mode is
  1308. * PEAR_ERROR_CALLBACK, this is the callback function,
  1309. * either as a function name, or as an array of an
  1310. * object and method name. For other error modes this
  1311. * parameter is ignored.
  1312. * @param string $userinfo Extra debug information. Defaults to the last
  1313. * query and native error code.
  1314. * @param string $method name of the method that triggered the error
  1315. * @param string $dummy1 not used
  1316. * @param bool $dummy2 not used
  1317. *
  1318. * @return PEAR_Error instance of a PEAR Error object
  1319. * @access public
  1320. * @see PEAR_Error
  1321. */
  1322. function &raiseError($code = null,
  1323. $mode = null,
  1324. $options = null,
  1325. $userinfo = null,
  1326. $method = null,
  1327. $dummy1 = null,
  1328. $dummy2 = false
  1329. ) {
  1330. $userinfo = "[Error message: $userinfo]\n";
  1331. // The error is yet a MDB2 error object
  1332. if (MDB2::isError($code)) {
  1333. // because we use the static PEAR::raiseError, our global
  1334. // handler should be used if it is set
  1335. if ((null === $mode) && !empty($this->_default_error_mode)) {
  1336. $mode = $this->_default_error_mode;
  1337. $options = $this->_default_error_options;
  1338. }
  1339. if (null === $userinfo) {
  1340. $userinfo = $code->getUserinfo();
  1341. }
  1342. $code = $code->getCode();
  1343. } elseif ($code == MDB2_ERROR_NOT_FOUND) {
  1344. // extension not loaded: don't call $this->errorInfo() or the script
  1345. // will die
  1346. } elseif (isset($this->connection)) {
  1347. if (!empty($this->last_query)) {
  1348. $userinfo.= "[Last executed query: {$this->last_query}]\n";
  1349. }
  1350. $native_errno = $native_msg = null;
  1351. list($code, $native_errno, $native_msg) = $this->errorInfo($code);
  1352. if ((null !== $native_errno) && $native_errno !== '') {
  1353. $userinfo.= "[Native code: $native_errno]\n";
  1354. }
  1355. if ((null !== $native_msg) && $native_msg !== '') {
  1356. $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
  1357. }
  1358. if (null !== $method) {
  1359. $userinfo = $method.': '.$userinfo;
  1360. }
  1361. }
  1362. $err = $this->pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
  1363. if ($err->getMode() !== PEAR_ERROR_RETURN
  1364. && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
  1365. $this->has_transaction_error = $err;
  1366. }
  1367. return $err;
  1368. }
  1369. // }}}
  1370. // {{{ function resetWarnings()
  1371. /**
  1372. * reset the warning array
  1373. *
  1374. * @return void
  1375. *
  1376. * @access public
  1377. */
  1378. function resetWarnings()
  1379. {
  1380. $this->warnings = array();
  1381. }
  1382. // }}}
  1383. // {{{ function getWarnings()
  1384. /**
  1385. * Get all warnings in reverse order.
  1386. * This means that the last warning is the first element in the array
  1387. *
  1388. * @return array with warnings
  1389. *
  1390. * @access public
  1391. * @see resetWarnings()
  1392. */
  1393. function getWarnings()
  1394. {
  1395. return array_reverse($this->warnings);
  1396. }
  1397. // }}}
  1398. // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
  1399. /**
  1400. * Sets which fetch mode should be used by default on queries
  1401. * on this connection
  1402. *
  1403. * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
  1404. * or MDB2_FETCHMODE_OBJECT
  1405. * @param string the class name of the object to be returned
  1406. * by the fetch methods when the
  1407. * MDB2_FETCHMODE_OBJECT mode is selected.
  1408. * If no class is specified by default a cast
  1409. * to object from the assoc array row will be
  1410. * done. There is also the possibility to use
  1411. * and extend the 'MDB2_row' class.
  1412. *
  1413. * @return mixed MDB2_OK or MDB2 Error Object
  1414. *
  1415. * @access public
  1416. * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
  1417. */
  1418. function setFetchMode($fetchmode, $object_class = 'stdClass')
  1419. {
  1420. switch ($fetchmode) {
  1421. case MDB2_FETCHMODE_OBJECT:
  1422. $this->options['fetch_class'] = $object_class;
  1423. case MDB2_FETCHMODE_ORDERED:
  1424. case MDB2_FETCHMODE_ASSOC:
  1425. $this->fetchmode = $fetchmode;
  1426. break;
  1427. default:
  1428. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1429. 'invalid fetchmode mode', __FUNCTION__);
  1430. }
  1431. return MDB2_OK;
  1432. }
  1433. // }}}
  1434. // {{{ function setOption($option, $value)
  1435. /**
  1436. * set the option for the db class
  1437. *
  1438. * @param string option name
  1439. * @param mixed value for the option
  1440. *
  1441. * @return mixed MDB2_OK or MDB2 Error Object
  1442. *
  1443. * @access public
  1444. */
  1445. function setOption($option, $value)
  1446. {
  1447. if (array_key_exists($option, $this->options)) {
  1448. $this->options[$option] = $value;
  1449. return MDB2_OK;
  1450. }
  1451. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1452. "unknown option $option", __FUNCTION__);
  1453. }
  1454. // }}}
  1455. // {{{ function getOption($option)
  1456. /**
  1457. * Returns the value of an option
  1458. *
  1459. * @param string option name
  1460. *
  1461. * @return mixed the option value or error object
  1462. *
  1463. * @access public
  1464. */
  1465. function getOption($option)
  1466. {
  1467. if (array_key_exists($option, $this->options)) {
  1468. return $this->options[$option];
  1469. }
  1470. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1471. "unknown option $option", __FUNCTION__);
  1472. }
  1473. // }}}
  1474. // {{{ function debug($message, $scope = '', $is_manip = null)
  1475. /**
  1476. * set a debug message
  1477. *
  1478. * @param string message that should be appended to the debug variable
  1479. * @param string usually the method name that triggered the debug call:
  1480. * for example 'query', 'prepare', 'execute', 'parameters',
  1481. * 'beginTransaction', 'commit', 'rollback'
  1482. * @param array contains context information about the debug() call
  1483. * common keys are: is_manip, time, result etc.
  1484. *
  1485. * @return void
  1486. *
  1487. * @access public
  1488. */
  1489. function debug($message, $scope = '', $context = array())
  1490. {
  1491. if ($this->options['debug'] && $this->options['debug_handler']) {
  1492. if (!$this->options['debug_expanded_output']) {
  1493. if (!empty($context['when']) && $context['when'] !== 'pre') {
  1494. return null;
  1495. }
  1496. $context = empty($context['is_manip']) ? false : $context['is_manip'];
  1497. }
  1498. return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
  1499. }
  1500. return null;
  1501. }
  1502. // }}}
  1503. // {{{ function getDebugOutput()
  1504. /**
  1505. * output debug info
  1506. *
  1507. * @return string content of the debug_output class variable
  1508. *
  1509. * @access public
  1510. */
  1511. function getDebugOutput()
  1512. {
  1513. return $this->debug_output;
  1514. }
  1515. // }}}
  1516. // {{{ function escape($text)
  1517. /**
  1518. * Quotes a string so it can be safely used in a query. It will quote
  1519. * the text so it can safely be used within a query.
  1520. *
  1521. * @param string the input string to quote
  1522. * @param bool escape wildcards
  1523. *
  1524. * @return string quoted string
  1525. *
  1526. * @access public
  1527. */
  1528. function escape($text, $escape_wildcards = false)
  1529. {
  1530. if ($escape_wildcards) {
  1531. $text = $this->escapePattern($text);
  1532. }
  1533. $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
  1534. return $text;
  1535. }
  1536. // }}}
  1537. // {{{ function escapePattern($text)
  1538. /**
  1539. * Quotes pattern (% and _) characters in a string)
  1540. *
  1541. * @param string the input string to quote
  1542. *
  1543. * @return string quoted string
  1544. *
  1545. * @access public
  1546. */
  1547. function escapePattern($text)
  1548. {
  1549. if ($this->string_quoting['escape_pattern']) {
  1550. $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
  1551. foreach ($this->wildcards as $wildcard) {
  1552. $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
  1553. }
  1554. }
  1555. return $text;
  1556. }
  1557. // }}}
  1558. // {{{ function quoteIdentifier($str, $check_option = false)
  1559. /**
  1560. * Quote a string so it can be safely used as a table or column name
  1561. *
  1562. * Delimiting style depends on which database driver is being used.
  1563. *
  1564. * NOTE: just because you CAN use delimited identifiers doesn't mean
  1565. * you SHOULD use them. In general, they end up causing way more
  1566. * problems than they solve.
  1567. *
  1568. * NOTE: if you have table names containing periods, don't use this method
  1569. * (@see bug #11906)
  1570. *
  1571. * Portability is broken by using the following characters inside
  1572. * delimited identifiers:
  1573. * + backtick (<kbd>`</kbd>) -- due to MySQL
  1574. * + double quote (<kbd>"</kbd>) -- due to Oracle
  1575. * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
  1576. *
  1577. * Delimited identifiers are known to generally work correctly under
  1578. * the following drivers:
  1579. * + mssql
  1580. * + mysql
  1581. * + mysqli
  1582. * + oci8
  1583. * + pgsql
  1584. * + sqlite
  1585. *
  1586. * InterBase doesn't seem to be able to use delimited identifiers
  1587. * via PHP 4. They work fine under PHP 5.
  1588. *
  1589. * @param string identifier name to be quoted
  1590. * @param bool check the 'quote_identifier' option
  1591. *
  1592. * @return string quoted identifier string
  1593. *
  1594. * @access public
  1595. */
  1596. function quoteIdentifier($str, $check_option = false)
  1597. {
  1598. if ($check_option && !$this->options['quote_identifier']) {
  1599. return $str;
  1600. }
  1601. $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
  1602. $parts = explode('.', $str);
  1603. foreach (array_keys($parts) as $k) {
  1604. $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
  1605. }
  1606. return implode('.', $parts);
  1607. }
  1608. // }}}
  1609. // {{{ function getAsKeyword()
  1610. /**
  1611. * Gets the string to alias column
  1612. *
  1613. * @return string to use when aliasing a column
  1614. */
  1615. function getAsKeyword()
  1616. {
  1617. return $this->as_keyword;
  1618. }
  1619. // }}}
  1620. // {{{ function getConnection()
  1621. /**
  1622. * Returns a native connection
  1623. *
  1624. * @return mixed a valid MDB2 connection object,
  1625. * or a MDB2 error object on error
  1626. *
  1627. * @access public
  1628. */
  1629. function getConnection()
  1630. {
  1631. $result = $this->connect();
  1632. if (MDB2::isError($result)) {
  1633. return $result;
  1634. }
  1635. return $this->connection;
  1636. }
  1637. // }}}
  1638. // {{{ function _fixResultArrayValues(&$row, $mode)
  1639. /**
  1640. * Do all necessary conversions on result arrays to fix DBMS quirks
  1641. *
  1642. * @param array the array to be fixed (passed by reference)
  1643. * @param array bit-wise addition of the required portability modes
  1644. *
  1645. * @return void
  1646. *
  1647. * @access protected
  1648. */
  1649. function _fixResultArrayValues(&$row, $mode)
  1650. {
  1651. switch ($mode) {
  1652. case MDB2_PORTABILITY_EMPTY_TO_NULL:
  1653. foreach ($row as $key => $value) {
  1654. if ($value === '') {
  1655. $row[$key] = null;
  1656. }
  1657. }
  1658. break;
  1659. case MDB2_PORTABILITY_RTRIM:
  1660. foreach ($row as $key => $value) {
  1661. if (is_string($value)) {
  1662. $row[$key] = rtrim($value);
  1663. }
  1664. }
  1665. break;
  1666. case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
  1667. $tmp_row = array();
  1668. foreach ($row as $key => $value) {
  1669. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1670. }
  1671. $row = $tmp_row;
  1672. break;
  1673. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
  1674. foreach ($row as $key => $value) {
  1675. if ($value === '') {
  1676. $row[$key] = null;
  1677. } elseif (is_string($value)) {
  1678. $row[$key] = rtrim($value);
  1679. }
  1680. }
  1681. break;
  1682. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1683. $tmp_row = array();
  1684. foreach ($row as $key => $value) {
  1685. if (is_string($value)) {
  1686. $value = rtrim($value);
  1687. }
  1688. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1689. }
  1690. $row = $tmp_row;
  1691. break;
  1692. case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1693. $tmp_row = array();
  1694. foreach ($row as $key => $value) {
  1695. if ($value === '') {
  1696. $value = null;
  1697. }
  1698. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1699. }
  1700. $row = $tmp_row;
  1701. break;
  1702. case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
  1703. $tmp_row = array();
  1704. foreach ($row as $key => $value) {
  1705. if ($value === '') {
  1706. $value = null;
  1707. } elseif (is_string($value)) {
  1708. $value = rtrim($value);
  1709. }
  1710. $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
  1711. }
  1712. $row = $tmp_row;
  1713. break;
  1714. }
  1715. }
  1716. // }}}
  1717. // {{{ function loadModule($module, $property = null, $phptype_specific = null)
  1718. /**
  1719. * loads a module
  1720. *
  1721. * @param string name of the module that should be loaded
  1722. * (only used for error messages)
  1723. * @param string name of the property into which the class will be loaded
  1724. * @param bool if the class to load for the module is specific to the
  1725. * phptype
  1726. *
  1727. * @return object on success a reference to the given module is returned
  1728. * and on failure a PEAR error
  1729. *
  1730. * @access public
  1731. */
  1732. function loadModule($module, $property = null, $phptype_specific = null)
  1733. {
  1734. if (!$property) {
  1735. $property = strtolower($module);
  1736. }
  1737. if (!isset($this->{$property})) {
  1738. $version = $phptype_specific;
  1739. if ($phptype_specific !== false) {
  1740. $version = true;
  1741. $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
  1742. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  1743. }
  1744. if ($phptype_specific === false
  1745. || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
  1746. ) {
  1747. $version = false;
  1748. $class_name = 'MDB2_'.$module;
  1749. $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
  1750. }
  1751. $err = MDB2::loadClass($class_name, $this->getOption('debug'));
  1752. if (MDB2::isError($err)) {
  1753. return $err;
  1754. }
  1755. // load module in a specific version
  1756. if ($version) {
  1757. if (method_exists($class_name, 'getClassName')) {
  1758. $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
  1759. if ($class_name != $class_name_new) {
  1760. $class_name = $class_name_new;
  1761. $err = MDB2::loadClass($class_name, $this->getOption('debug'));
  1762. if (MDB2::isError($err)) {
  1763. return $err;
  1764. }
  1765. }
  1766. }
  1767. }
  1768. if (!MDB2::classExists($class_name)) {
  1769. $err = $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
  1770. "unable to load module '$module' into property '$property'", __FUNCTION__);
  1771. return $err;
  1772. }
  1773. $this->{$property} = new $class_name($this->db_index);
  1774. $this->modules[$module] = $this->{$property};
  1775. if ($version) {
  1776. // this will be used in the connect method to determine if the module
  1777. // needs to be loaded with a different version if the server
  1778. // version changed in between connects
  1779. $this->loaded_version_modules[] = $property;
  1780. }
  1781. }
  1782. return $this->{$property};
  1783. }
  1784. // }}}
  1785. // {{{ function __call($method, $params)
  1786. /**
  1787. * Calls a module method using the __call magic method
  1788. *
  1789. * @param string Method name.
  1790. * @param array Arguments.
  1791. *
  1792. * @return mixed Returned value.
  1793. */
  1794. function __call($method, $params)
  1795. {
  1796. $module = null;
  1797. if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
  1798. && isset($this->options['modules'][$match[1]])
  1799. ) {
  1800. $module = $this->options['modules'][$match[1]];
  1801. $method = strtolower($match[2]).$match[3];
  1802. if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
  1803. $result = $this->loadModule($module);
  1804. if (MDB2::isError($result)) {
  1805. return $result;
  1806. }
  1807. }
  1808. } else {
  1809. foreach ($this->modules as $key => $foo) {
  1810. if (is_object($this->modules[$key])
  1811. && method_exists($this->modules[$key], $method)
  1812. ) {
  1813. $module = $key;
  1814. break;
  1815. }
  1816. }
  1817. }
  1818. if (null !== $module) {
  1819. return call_user_func_array(array(&$this->modules[$module], $method), $params);
  1820. }
  1821. trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
  1822. }
  1823. // }}}
  1824. // {{{ function beginTransaction($savepoint = null)
  1825. /**
  1826. * Start a transaction or set a savepoint.
  1827. *
  1828. * @param string name of a savepoint to set
  1829. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1830. *
  1831. * @access public
  1832. */
  1833. function beginTransaction($savepoint = null)
  1834. {
  1835. $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1836. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1837. 'transactions are not supported', __FUNCTION__);
  1838. }
  1839. // }}}
  1840. // {{{ function commit($savepoint = null)
  1841. /**
  1842. * Commit the database changes done during a transaction that is in
  1843. * progress or release a savepoint. This function may only be called when
  1844. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1845. * transaction is implicitly started after committing the pending changes.
  1846. *
  1847. * @param string name of a savepoint to release
  1848. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1849. *
  1850. * @access public
  1851. */
  1852. function commit($savepoint = null)
  1853. {
  1854. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1855. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1856. 'commiting transactions is not supported', __FUNCTION__);
  1857. }
  1858. // }}}
  1859. // {{{ function rollback($savepoint = null)
  1860. /**
  1861. * Cancel any database changes done during a transaction or since a specific
  1862. * savepoint that is in progress. This function may only be called when
  1863. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1864. * transaction is implicitly started after canceling the pending changes.
  1865. *
  1866. * @param string name of a savepoint to rollback to
  1867. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1868. *
  1869. * @access public
  1870. */
  1871. function rollback($savepoint = null)
  1872. {
  1873. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1874. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1875. 'rolling back transactions is not supported', __FUNCTION__);
  1876. }
  1877. // }}}
  1878. // {{{ function inTransaction($ignore_nested = false)
  1879. /**
  1880. * If a transaction is currently open.
  1881. *
  1882. * @param bool if the nested transaction count should be ignored
  1883. * @return int|bool - an integer with the nesting depth is returned if a
  1884. * nested transaction is open
  1885. * - true is returned for a normal open transaction
  1886. * - false is returned if no transaction is open
  1887. *
  1888. * @access public
  1889. */
  1890. function inTransaction($ignore_nested = false)
  1891. {
  1892. if (!$ignore_nested && isset($this->nested_transaction_counter)) {
  1893. return $this->nested_transaction_counter;
  1894. }
  1895. return $this->in_transaction;
  1896. }
  1897. // }}}
  1898. // {{{ function setTransactionIsolation($isolation)
  1899. /**
  1900. * Set the transacton isolation level.
  1901. *
  1902. * @param string standard isolation level
  1903. * READ UNCOMMITTED (allows dirty reads)
  1904. * READ COMMITTED (prevents dirty reads)
  1905. * REPEATABLE READ (prevents nonrepeatable reads)
  1906. * SERIALIZABLE (prevents phantom reads)
  1907. * @param array some transaction options:
  1908. * 'wait' => 'WAIT' | 'NO WAIT'
  1909. * 'rw' => 'READ WRITE' | 'READ ONLY'
  1910. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1911. *
  1912. * @access public
  1913. * @since 2.1.1
  1914. */
  1915. function setTransactionIsolation($isolation, $options = array())
  1916. {
  1917. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  1918. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1919. 'isolation level setting is not supported', __FUNCTION__);
  1920. }
  1921. // }}}
  1922. // {{{ function beginNestedTransaction($savepoint = false)
  1923. /**
  1924. * Start a nested transaction.
  1925. *
  1926. * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
  1927. *
  1928. * @access public
  1929. * @since 2.1.1
  1930. */
  1931. function beginNestedTransaction()
  1932. {
  1933. if ($this->in_transaction) {
  1934. ++$this->nested_transaction_counter;
  1935. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1936. if ($this->supports('savepoints') && $savepoint) {
  1937. return $this->beginTransaction($savepoint);
  1938. }
  1939. return MDB2_OK;
  1940. }
  1941. $this->has_transaction_error = false;
  1942. $result = $this->beginTransaction();
  1943. $this->nested_transaction_counter = 1;
  1944. return $result;
  1945. }
  1946. // }}}
  1947. // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
  1948. /**
  1949. * Finish a nested transaction by rolling back if an error occured or
  1950. * committing otherwise.
  1951. *
  1952. * @param bool if the transaction should be rolled back regardless
  1953. * even if no error was set within the nested transaction
  1954. * @return mixed MDB_OK on commit/counter decrementing, false on rollback
  1955. * and a MDB2 error on failure
  1956. *
  1957. * @access public
  1958. * @since 2.1.1
  1959. */
  1960. function completeNestedTransaction($force_rollback = false)
  1961. {
  1962. if ($this->nested_transaction_counter > 1) {
  1963. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1964. if ($this->supports('savepoints') && $savepoint) {
  1965. if ($force_rollback || $this->has_transaction_error) {
  1966. $result = $this->rollback($savepoint);
  1967. if (!MDB2::isError($result)) {
  1968. $result = false;
  1969. $this->has_transaction_error = false;
  1970. }
  1971. } else {
  1972. $result = $this->commit($savepoint);
  1973. }
  1974. } else {
  1975. $result = MDB2_OK;
  1976. }
  1977. --$this->nested_transaction_counter;
  1978. return $result;
  1979. }
  1980. $this->nested_transaction_counter = null;
  1981. $result = MDB2_OK;
  1982. // transaction has not yet been rolled back
  1983. if ($this->in_transaction) {
  1984. if ($force_rollback || $this->has_transaction_error) {
  1985. $result = $this->rollback();
  1986. if (!MDB2::isError($result)) {
  1987. $result = false;
  1988. }
  1989. } else {
  1990. $result = $this->commit();
  1991. }
  1992. }
  1993. $this->has_transaction_error = false;
  1994. return $result;
  1995. }
  1996. // }}}
  1997. // {{{ function failNestedTransaction($error = null, $immediately = false)
  1998. /**
  1999. * Force setting nested transaction to failed.
  2000. *
  2001. * @param mixed value to return in getNestededTransactionError()
  2002. * @param bool if the transaction should be rolled back immediately
  2003. * @return bool MDB2_OK
  2004. *
  2005. * @access public
  2006. * @since 2.1.1
  2007. */
  2008. function failNestedTransaction($error = null, $immediately = false)
  2009. {
  2010. if (null !== $error) {
  2011. $error = $this->has_transaction_error ? $this->has_transaction_error : true;
  2012. } elseif (!$error) {
  2013. $error = true;
  2014. }
  2015. $this->has_transaction_error = $error;
  2016. if (!$immediately) {
  2017. return MDB2_OK;
  2018. }
  2019. return $this->rollback();
  2020. }
  2021. // }}}
  2022. // {{{ function getNestedTransactionError()
  2023. /**
  2024. * The first error that occured since the transaction start.
  2025. *
  2026. * @return MDB2_Error|bool MDB2 error object if an error occured or false.
  2027. *
  2028. * @access public
  2029. * @since 2.1.1
  2030. */
  2031. function getNestedTransactionError()
  2032. {
  2033. return $this->has_transaction_error;
  2034. }
  2035. // }}}
  2036. // {{{ connect()
  2037. /**
  2038. * Connect to the database
  2039. *
  2040. * @return true on success, MDB2 Error Object on failure
  2041. */
  2042. function connect()
  2043. {
  2044. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2045. 'method not implemented', __FUNCTION__);
  2046. }
  2047. // }}}
  2048. // {{{ databaseExists()
  2049. /**
  2050. * check if given database name is exists?
  2051. *
  2052. * @param string $name name of the database that should be checked
  2053. *
  2054. * @return mixed true/false on success, a MDB2 error on failure
  2055. * @access public
  2056. */
  2057. function databaseExists($name)
  2058. {
  2059. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2060. 'method not implemented', __FUNCTION__);
  2061. }
  2062. // }}}
  2063. // {{{ setCharset($charset, $connection = null)
  2064. /**
  2065. * Set the charset on the current connection
  2066. *
  2067. * @param string charset
  2068. * @param resource connection handle
  2069. *
  2070. * @return true on success, MDB2 Error Object on failure
  2071. */
  2072. function setCharset($charset, $connection = null)
  2073. {
  2074. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2075. 'method not implemented', __FUNCTION__);
  2076. }
  2077. // }}}
  2078. // {{{ function disconnect($force = true)
  2079. /**
  2080. * Log out and disconnect from the database.
  2081. *
  2082. * @param boolean $force whether the disconnect should be forced even if the
  2083. * connection is opened persistently
  2084. *
  2085. * @return mixed true on success, false if not connected and error object on error
  2086. *
  2087. * @access public
  2088. */
  2089. function disconnect($force = true)
  2090. {
  2091. $this->connection = 0;
  2092. $this->connected_dsn = array();
  2093. $this->connected_database_name = '';
  2094. $this->opened_persistent = null;
  2095. $this->connected_server_info = '';
  2096. $this->in_transaction = null;
  2097. $this->nested_transaction_counter = null;
  2098. return MDB2_OK;
  2099. }
  2100. // }}}
  2101. // {{{ function setDatabase($name)
  2102. /**
  2103. * Select a different database
  2104. *
  2105. * @param string name of the database that should be selected
  2106. *
  2107. * @return string name of the database previously connected to
  2108. *
  2109. * @access public
  2110. */
  2111. function setDatabase($name)
  2112. {
  2113. $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
  2114. $this->database_name = $name;
  2115. if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
  2116. $this->disconnect(false);
  2117. }
  2118. return $previous_database_name;
  2119. }
  2120. // }}}
  2121. // {{{ function getDatabase()
  2122. /**
  2123. * Get the current database
  2124. *
  2125. * @return string name of the database
  2126. *
  2127. * @access public
  2128. */
  2129. function getDatabase()
  2130. {
  2131. return $this->database_name;
  2132. }
  2133. // }}}
  2134. // {{{ function setDSN($dsn)
  2135. /**
  2136. * set the DSN
  2137. *
  2138. * @param mixed DSN string or array
  2139. *
  2140. * @return MDB2_OK
  2141. *
  2142. * @access public
  2143. */
  2144. function setDSN($dsn)
  2145. {
  2146. $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
  2147. $dsn = MDB2::parseDSN($dsn);
  2148. if (array_key_exists('database', $dsn)) {
  2149. $this->database_name = $dsn['database'];
  2150. unset($dsn['database']);
  2151. }
  2152. $this->dsn = array_merge($dsn_default, $dsn);
  2153. return $this->disconnect(false);
  2154. }
  2155. // }}}
  2156. // {{{ function getDSN($type = 'string', $hidepw = false)
  2157. /**
  2158. * return the DSN as a string
  2159. *
  2160. * @param string format to return ("array", "string")
  2161. * @param string string to hide the password with
  2162. *
  2163. * @return mixed DSN in the chosen type
  2164. *
  2165. * @access public
  2166. */
  2167. function getDSN($type = 'string', $hidepw = false)
  2168. {
  2169. $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
  2170. $dsn['phptype'] = $this->phptype;
  2171. $dsn['database'] = $this->database_name;
  2172. if ($hidepw) {
  2173. $dsn['password'] = $hidepw;
  2174. }
  2175. switch ($type) {
  2176. // expand to include all possible options
  2177. case 'string':
  2178. $dsn = $dsn['phptype'].
  2179. ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
  2180. '://'.$dsn['username'].':'.
  2181. $dsn['password'].'@'.$dsn['hostspec'].
  2182. ($dsn['port'] ? (':'.$dsn['port']) : '').
  2183. '/'.$dsn['database'];
  2184. break;
  2185. case 'array':
  2186. default:
  2187. break;
  2188. }
  2189. return $dsn;
  2190. }
  2191. // }}}
  2192. // {{{ _isNewLinkSet()
  2193. /**
  2194. * Check if the 'new_link' option is set
  2195. *
  2196. * @return boolean
  2197. *
  2198. * @access protected
  2199. */
  2200. function _isNewLinkSet()
  2201. {
  2202. return (isset($this->dsn['new_link'])
  2203. && ($this->dsn['new_link'] === true
  2204. || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
  2205. || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
  2206. )
  2207. );
  2208. }
  2209. // }}}
  2210. // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
  2211. /**
  2212. * execute a query as database administrator
  2213. *
  2214. * @param string the SQL query
  2215. * @param mixed array that contains the types of the columns in
  2216. * the result set
  2217. * @param bool if the query is a manipulation query
  2218. *
  2219. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2220. *
  2221. * @access public
  2222. */
  2223. function standaloneQuery($query, $types = null, $is_manip = false)
  2224. {
  2225. $offset = $this->offset;
  2226. $limit = $this->limit;
  2227. $this->offset = $this->limit = 0;
  2228. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  2229. $connection = $this->getConnection();
  2230. if (MDB2::isError($connection)) {
  2231. return $connection;
  2232. }
  2233. $result = $this->_doQuery($query, $is_manip, $connection, false);
  2234. if (MDB2::isError($result)) {
  2235. return $result;
  2236. }
  2237. if ($is_manip) {
  2238. $affected_rows = $this->_affectedRows($connection, $result);
  2239. return $affected_rows;
  2240. }
  2241. $result = $this->_wrapResult($result, $types, true, true, $limit, $offset);
  2242. return $result;
  2243. }
  2244. // }}}
  2245. // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
  2246. /**
  2247. * Changes a query string for various DBMS specific reasons
  2248. *
  2249. * @param string query to modify
  2250. * @param bool if it is a DML query
  2251. * @param int limit the number of rows
  2252. * @param int start reading from given offset
  2253. *
  2254. * @return string modified query
  2255. *
  2256. * @access protected
  2257. */
  2258. function _modifyQuery($query, $is_manip, $limit, $offset)
  2259. {
  2260. return $query;
  2261. }
  2262. // }}}
  2263. // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2264. /**
  2265. * Execute a query
  2266. * @param string query
  2267. * @param bool if the query is a manipulation query
  2268. * @param resource connection handle
  2269. * @param string database name
  2270. *
  2271. * @return result or error object
  2272. *
  2273. * @access protected
  2274. */
  2275. function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2276. {
  2277. $this->last_query = $query;
  2278. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  2279. if ($result) {
  2280. if (MDB2::isError($result)) {
  2281. return $result;
  2282. }
  2283. $query = $result;
  2284. }
  2285. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2286. 'method not implemented', __FUNCTION__);
  2287. return $err;
  2288. }
  2289. // }}}
  2290. // {{{ function _affectedRows($connection, $result = null)
  2291. /**
  2292. * Returns the number of rows affected
  2293. *
  2294. * @param resource result handle
  2295. * @param resource connection handle
  2296. *
  2297. * @return mixed MDB2 Error Object or the number of rows affected
  2298. *
  2299. * @access private
  2300. */
  2301. function _affectedRows($connection, $result = null)
  2302. {
  2303. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2304. 'method not implemented', __FUNCTION__);
  2305. }
  2306. // }}}
  2307. // {{{ function &exec($query)
  2308. /**
  2309. * Execute a manipulation query to the database and return the number of affected rows
  2310. *
  2311. * @param string the SQL query
  2312. *
  2313. * @return mixed number of affected rows on success, a MDB2 error on failure
  2314. *
  2315. * @access public
  2316. */
  2317. function exec($query)
  2318. {
  2319. $offset = $this->offset;
  2320. $limit = $this->limit;
  2321. $this->offset = $this->limit = 0;
  2322. $query = $this->_modifyQuery($query, true, $limit, $offset);
  2323. $connection = $this->getConnection();
  2324. if (MDB2::isError($connection)) {
  2325. return $connection;
  2326. }
  2327. $result = $this->_doQuery($query, true, $connection, $this->database_name);
  2328. if (MDB2::isError($result)) {
  2329. return $result;
  2330. }
  2331. $affectedRows = $this->_affectedRows($connection, $result);
  2332. return $affectedRows;
  2333. }
  2334. // }}}
  2335. // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
  2336. /**
  2337. * Send a query to the database and return any results
  2338. *
  2339. * @param string the SQL query
  2340. * @param mixed array that contains the types of the columns in
  2341. * the result set
  2342. * @param mixed string which specifies which result class to use
  2343. * @param mixed string which specifies which class to wrap results in
  2344. *
  2345. * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
  2346. *
  2347. * @access public
  2348. */
  2349. function query($query, $types = null, $result_class = true, $result_wrap_class = true)
  2350. {
  2351. $offset = $this->offset;
  2352. $limit = $this->limit;
  2353. $this->offset = $this->limit = 0;
  2354. $query = $this->_modifyQuery($query, false, $limit, $offset);
  2355. $connection = $this->getConnection();
  2356. if (MDB2::isError($connection)) {
  2357. return $connection;
  2358. }
  2359. $result = $this->_doQuery($query, false, $connection, $this->database_name);
  2360. if (MDB2::isError($result)) {
  2361. return $result;
  2362. }
  2363. $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
  2364. return $result;
  2365. }
  2366. // }}}
  2367. // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
  2368. /**
  2369. * wrap a result set into the correct class
  2370. *
  2371. * @param resource result handle
  2372. * @param mixed array that contains the types of the columns in
  2373. * the result set
  2374. * @param mixed string which specifies which result class to use
  2375. * @param mixed string which specifies which class to wrap results in
  2376. * @param string number of rows to select
  2377. * @param string first row to select
  2378. *
  2379. * @return mixed an MDB2_Result, a MDB2 error on failure
  2380. *
  2381. * @access protected
  2382. */
  2383. function _wrapResult($result_resource, $types = array(), $result_class = true,
  2384. $result_wrap_class = true, $limit = null, $offset = null)
  2385. {
  2386. if ($types === true) {
  2387. if ($this->supports('result_introspection')) {
  2388. $this->loadModule('Reverse', null, true);
  2389. $tableInfo = $this->reverse->tableInfo($result_resource);
  2390. if (MDB2::isError($tableInfo)) {
  2391. return $tableInfo;
  2392. }
  2393. $types = array();
  2394. $types_assoc = array();
  2395. foreach ($tableInfo as $field) {
  2396. $types[] = $field['mdb2type'];
  2397. $types_assoc[$field['name']] = $field['mdb2type'];
  2398. }
  2399. } else {
  2400. $types = null;
  2401. }
  2402. }
  2403. if ($result_class === true) {
  2404. $result_class = $this->options['result_buffering']
  2405. ? $this->options['buffered_result_class'] : $this->options['result_class'];
  2406. }
  2407. if ($result_class) {
  2408. $class_name = sprintf($result_class, $this->phptype);
  2409. if (!MDB2::classExists($class_name)) {
  2410. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2411. 'result class does not exist '.$class_name, __FUNCTION__);
  2412. return $err;
  2413. }
  2414. $result = new $class_name($this, $result_resource, $limit, $offset);
  2415. if (!MDB2::isResultCommon($result)) {
  2416. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2417. 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
  2418. return $err;
  2419. }
  2420. if (!empty($types)) {
  2421. $err = $result->setResultTypes($types);
  2422. if (MDB2::isError($err)) {
  2423. $result->free();
  2424. return $err;
  2425. }
  2426. }
  2427. if (!empty($types_assoc)) {
  2428. $err = $result->setResultTypes($types_assoc);
  2429. if (MDB2::isError($err)) {
  2430. $result->free();
  2431. return $err;
  2432. }
  2433. }
  2434. if ($result_wrap_class === true) {
  2435. $result_wrap_class = $this->options['result_wrap_class'];
  2436. }
  2437. if ($result_wrap_class) {
  2438. if (!MDB2::classExists($result_wrap_class)) {
  2439. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2440. 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
  2441. return $err;
  2442. }
  2443. $result = new $result_wrap_class($result, $this->fetchmode);
  2444. }
  2445. return $result;
  2446. }
  2447. return $result_resource;
  2448. }
  2449. // }}}
  2450. // {{{ function getServerVersion($native = false)
  2451. /**
  2452. * return version information about the server
  2453. *
  2454. * @param bool determines if the raw version string should be returned
  2455. *
  2456. * @return mixed array with version information or row string
  2457. *
  2458. * @access public
  2459. */
  2460. function getServerVersion($native = false)
  2461. {
  2462. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2463. 'method not implemented', __FUNCTION__);
  2464. }
  2465. // }}}
  2466. // {{{ function setLimit($limit, $offset = null)
  2467. /**
  2468. * set the range of the next query
  2469. *
  2470. * @param string number of rows to select
  2471. * @param string first row to select
  2472. *
  2473. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2474. *
  2475. * @access public
  2476. */
  2477. function setLimit($limit, $offset = null)
  2478. {
  2479. if (!$this->supports('limit_queries')) {
  2480. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2481. 'limit is not supported by this driver', __FUNCTION__);
  2482. }
  2483. $limit = (int)$limit;
  2484. if ($limit < 0) {
  2485. return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2486. 'it was not specified a valid selected range row limit', __FUNCTION__);
  2487. }
  2488. $this->limit = $limit;
  2489. if (null !== $offset) {
  2490. $offset = (int)$offset;
  2491. if ($offset < 0) {
  2492. return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2493. 'it was not specified a valid first selected range row', __FUNCTION__);
  2494. }
  2495. $this->offset = $offset;
  2496. }
  2497. return MDB2_OK;
  2498. }
  2499. // }}}
  2500. // {{{ function subSelect($query, $type = false)
  2501. /**
  2502. * simple subselect emulation: leaves the query untouched for all RDBMS
  2503. * that support subselects
  2504. *
  2505. * @param string the SQL query for the subselect that may only
  2506. * return a column
  2507. * @param string determines type of the field
  2508. *
  2509. * @return string the query
  2510. *
  2511. * @access public
  2512. */
  2513. function subSelect($query, $type = false)
  2514. {
  2515. if ($this->supports('sub_selects') === true) {
  2516. return $query;
  2517. }
  2518. if (!$this->supports('sub_selects')) {
  2519. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2520. 'method not implemented', __FUNCTION__);
  2521. }
  2522. $col = $this->queryCol($query, $type);
  2523. if (MDB2::isError($col)) {
  2524. return $col;
  2525. }
  2526. if (!is_array($col) || count($col) == 0) {
  2527. return 'NULL';
  2528. }
  2529. if ($type) {
  2530. $this->loadModule('Datatype', null, true);
  2531. return $this->datatype->implodeArray($col, $type);
  2532. }
  2533. return implode(', ', $col);
  2534. }
  2535. // }}}
  2536. // {{{ function replace($table, $fields)
  2537. /**
  2538. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  2539. * query, except that if there is already a row in the table with the same
  2540. * key field values, the old row is deleted before the new row is inserted.
  2541. *
  2542. * The REPLACE type of query does not make part of the SQL standards. Since
  2543. * practically only MySQL and SQLite implement it natively, this type of
  2544. * query isemulated through this method for other DBMS using standard types
  2545. * of queries inside a transaction to assure the atomicity of the operation.
  2546. *
  2547. * @param string name of the table on which the REPLACE query will
  2548. * be executed.
  2549. * @param array associative array that describes the fields and the
  2550. * values that will be inserted or updated in the specified table. The
  2551. * indexes of the array are the names of all the fields of the table.
  2552. * The values of the array are also associative arrays that describe
  2553. * the values and other properties of the table fields.
  2554. *
  2555. * Here follows a list of field properties that need to be specified:
  2556. *
  2557. * value
  2558. * Value to be assigned to the specified field. This value may be
  2559. * of specified in database independent type format as this
  2560. * function can perform the necessary datatype conversions.
  2561. *
  2562. * Default: this property is required unless the Null property is
  2563. * set to 1.
  2564. *
  2565. * type
  2566. * Name of the type of the field. Currently, all types MDB2
  2567. * are supported except for clob and blob.
  2568. *
  2569. * Default: no type conversion
  2570. *
  2571. * null
  2572. * bool property that indicates that the value for this field
  2573. * should be set to null.
  2574. *
  2575. * The default value for fields missing in INSERT queries may be
  2576. * specified the definition of a table. Often, the default value
  2577. * is already null, but since the REPLACE may be emulated using
  2578. * an UPDATE query, make sure that all fields of the table are
  2579. * listed in this function argument array.
  2580. *
  2581. * Default: 0
  2582. *
  2583. * key
  2584. * bool property that indicates that this field should be
  2585. * handled as a primary key or at least as part of the compound
  2586. * unique index of the table that will determine the row that will
  2587. * updated if it exists or inserted a new row otherwise.
  2588. *
  2589. * This function will fail if no key field is specified or if the
  2590. * value of a key field is set to null because fields that are
  2591. * part of unique index they may not be null.
  2592. *
  2593. * Default: 0
  2594. *
  2595. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2596. *
  2597. * @access public
  2598. */
  2599. function replace($table, $fields)
  2600. {
  2601. if (!$this->supports('replace')) {
  2602. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2603. 'replace query is not supported', __FUNCTION__);
  2604. }
  2605. $count = count($fields);
  2606. $condition = $values = array();
  2607. for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
  2608. $name = key($fields);
  2609. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  2610. $value = 'NULL';
  2611. } else {
  2612. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  2613. $value = $this->quote($fields[$name]['value'], $type);
  2614. }
  2615. $values[$name] = $value;
  2616. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  2617. if ($value === 'NULL') {
  2618. return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2619. 'key value '.$name.' may not be NULL', __FUNCTION__);
  2620. }
  2621. $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
  2622. }
  2623. }
  2624. if (empty($condition)) {
  2625. return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2626. 'not specified which fields are keys', __FUNCTION__);
  2627. }
  2628. $result = null;
  2629. $in_transaction = $this->in_transaction;
  2630. if (!$in_transaction && MDB2::isError($result = $this->beginTransaction())) {
  2631. return $result;
  2632. }
  2633. $connection = $this->getConnection();
  2634. if (MDB2::isError($connection)) {
  2635. return $connection;
  2636. }
  2637. $condition = ' WHERE '.implode(' AND ', $condition);
  2638. $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
  2639. $result = $this->_doQuery($query, true, $connection);
  2640. if (!MDB2::isError($result)) {
  2641. $affected_rows = $this->_affectedRows($connection, $result);
  2642. $insert = '';
  2643. foreach ($values as $key => $value) {
  2644. $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
  2645. }
  2646. $values = implode(', ', $values);
  2647. $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
  2648. $result = $this->_doQuery($query, true, $connection);
  2649. if (!MDB2::isError($result)) {
  2650. $affected_rows += $this->_affectedRows($connection, $result);;
  2651. }
  2652. }
  2653. if (!$in_transaction) {
  2654. if (MDB2::isError($result)) {
  2655. $this->rollback();
  2656. } else {
  2657. $result = $this->commit();
  2658. }
  2659. }
  2660. if (MDB2::isError($result)) {
  2661. return $result;
  2662. }
  2663. return $affected_rows;
  2664. }
  2665. // }}}
  2666. // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
  2667. /**
  2668. * Prepares a query for multiple execution with execute().
  2669. * With some database backends, this is emulated.
  2670. * prepare() requires a generic query as string like
  2671. * 'INSERT INTO numbers VALUES(?,?)' or
  2672. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  2673. * The ? and :name and are placeholders which can be set using
  2674. * bindParam() and the query can be sent off using the execute() method.
  2675. * The allowed format for :name can be set with the 'bindname_format' option.
  2676. *
  2677. * @param string the query to prepare
  2678. * @param mixed array that contains the types of the placeholders
  2679. * @param mixed array that contains the types of the columns in
  2680. * the result set or MDB2_PREPARE_RESULT, if set to
  2681. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  2682. * @param mixed key (field) value (parameter) pair for all lob placeholders
  2683. *
  2684. * @return mixed resource handle for the prepared query on success,
  2685. * a MDB2 error on failure
  2686. *
  2687. * @access public
  2688. * @see bindParam, execute
  2689. */
  2690. function prepare($query, $types = null, $result_types = null, $lobs = array())
  2691. {
  2692. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  2693. $offset = $this->offset;
  2694. $limit = $this->limit;
  2695. $this->offset = $this->limit = 0;
  2696. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  2697. if ($result) {
  2698. if (MDB2::isError($result)) {
  2699. return $result;
  2700. }
  2701. $query = $result;
  2702. }
  2703. $placeholder_type_guess = $placeholder_type = null;
  2704. $question = '?';
  2705. $colon = ':';
  2706. $positions = array();
  2707. $position = 0;
  2708. while ($position < strlen($query)) {
  2709. $q_position = strpos($query, $question, $position);
  2710. $c_position = strpos($query, $colon, $position);
  2711. if ($q_position && $c_position) {
  2712. $p_position = min($q_position, $c_position);
  2713. } elseif ($q_position) {
  2714. $p_position = $q_position;
  2715. } elseif ($c_position) {
  2716. $p_position = $c_position;
  2717. } else {
  2718. break;
  2719. }
  2720. if (null === $placeholder_type) {
  2721. $placeholder_type_guess = $query[$p_position];
  2722. }
  2723. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  2724. if (MDB2::isError($new_pos)) {
  2725. return $new_pos;
  2726. }
  2727. if ($new_pos != $position) {
  2728. $position = $new_pos;
  2729. continue; //evaluate again starting from the new position
  2730. }
  2731. if ($query[$position] == $placeholder_type_guess) {
  2732. if (null === $placeholder_type) {
  2733. $placeholder_type = $query[$p_position];
  2734. $question = $colon = $placeholder_type;
  2735. if (!empty($types) && is_array($types)) {
  2736. if ($placeholder_type == ':') {
  2737. if (is_int(key($types))) {
  2738. $types_tmp = $types;
  2739. $types = array();
  2740. $count = -1;
  2741. }
  2742. } else {
  2743. $types = array_values($types);
  2744. }
  2745. }
  2746. }
  2747. if ($placeholder_type == ':') {
  2748. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  2749. $parameter = preg_replace($regexp, '\\1', $query);
  2750. if ($parameter === '') {
  2751. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2752. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  2753. return $err;
  2754. }
  2755. $positions[$p_position] = $parameter;
  2756. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  2757. // use parameter name in type array
  2758. if (isset($count) && isset($types_tmp[++$count])) {
  2759. $types[$parameter] = $types_tmp[$count];
  2760. }
  2761. } else {
  2762. $positions[$p_position] = count($positions);
  2763. }
  2764. $position = $p_position + 1;
  2765. } else {
  2766. $position = $p_position;
  2767. }
  2768. }
  2769. $class_name = 'MDB2_Statement_'.$this->phptype;
  2770. $statement = null;
  2771. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  2772. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  2773. return $obj;
  2774. }
  2775. // }}}
  2776. // {{{ function _skipDelimitedStrings($query, $position, $p_position)
  2777. /**
  2778. * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
  2779. * Check if the placeholder is contained within a delimited string.
  2780. * If so, skip it and advance the position, otherwise return the current position,
  2781. * which is valid
  2782. *
  2783. * @param string $query
  2784. * @param integer $position current string cursor position
  2785. * @param integer $p_position placeholder position
  2786. *
  2787. * @return mixed integer $new_position on success
  2788. * MDB2_Error on failure
  2789. *
  2790. * @access protected
  2791. */
  2792. function _skipDelimitedStrings($query, $position, $p_position)
  2793. {
  2794. $ignores = array();
  2795. $ignores[] = $this->string_quoting;
  2796. $ignores[] = $this->identifier_quoting;
  2797. $ignores = array_merge($ignores, $this->sql_comments);
  2798. foreach ($ignores as $ignore) {
  2799. if (!empty($ignore['start'])) {
  2800. if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
  2801. $end_quote = $start_quote;
  2802. do {
  2803. if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
  2804. if ($ignore['end'] === "\n") {
  2805. $end_quote = strlen($query) - 1;
  2806. } else {
  2807. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2808. 'query with an unterminated text string specified', __FUNCTION__);
  2809. return $err;
  2810. }
  2811. }
  2812. } while ($ignore['escape']
  2813. && $end_quote-1 != $start_quote
  2814. && $query[($end_quote - 1)] == $ignore['escape']
  2815. && ( $ignore['escape_pattern'] !== $ignore['escape']
  2816. || $query[($end_quote - 2)] != $ignore['escape'])
  2817. );
  2818. $position = $end_quote + 1;
  2819. return $position;
  2820. }
  2821. }
  2822. }
  2823. return $position;
  2824. }
  2825. // }}}
  2826. // {{{ function quote($value, $type = null, $quote = true)
  2827. /**
  2828. * Convert a text value into a DBMS specific format that is suitable to
  2829. * compose query statements.
  2830. *
  2831. * @param string text string value that is intended to be converted.
  2832. * @param string type to which the value should be converted to
  2833. * @param bool quote
  2834. * @param bool escape wildcards
  2835. *
  2836. * @return string text string that represents the given argument value in
  2837. * a DBMS specific format.
  2838. *
  2839. * @access public
  2840. */
  2841. function quote($value, $type = null, $quote = true, $escape_wildcards = false)
  2842. {
  2843. $result = $this->loadModule('Datatype', null, true);
  2844. if (MDB2::isError($result)) {
  2845. return $result;
  2846. }
  2847. return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
  2848. }
  2849. // }}}
  2850. // {{{ function getDeclaration($type, $name, $field)
  2851. /**
  2852. * Obtain DBMS specific SQL code portion needed to declare
  2853. * of the given type
  2854. *
  2855. * @param string type to which the value should be converted to
  2856. * @param string name the field to be declared.
  2857. * @param string definition of the field
  2858. *
  2859. * @return string DBMS specific SQL code portion that should be used to
  2860. * declare the specified field.
  2861. *
  2862. * @access public
  2863. */
  2864. function getDeclaration($type, $name, $field)
  2865. {
  2866. $result = $this->loadModule('Datatype', null, true);
  2867. if (MDB2::isError($result)) {
  2868. return $result;
  2869. }
  2870. return $this->datatype->getDeclaration($type, $name, $field);
  2871. }
  2872. // }}}
  2873. // {{{ function compareDefinition($current, $previous)
  2874. /**
  2875. * Obtain an array of changes that may need to applied
  2876. *
  2877. * @param array new definition
  2878. * @param array old definition
  2879. *
  2880. * @return array containing all changes that will need to be applied
  2881. *
  2882. * @access public
  2883. */
  2884. function compareDefinition($current, $previous)
  2885. {
  2886. $result = $this->loadModule('Datatype', null, true);
  2887. if (MDB2::isError($result)) {
  2888. return $result;
  2889. }
  2890. return $this->datatype->compareDefinition($current, $previous);
  2891. }
  2892. // }}}
  2893. // {{{ function supports($feature)
  2894. /**
  2895. * Tell whether a DB implementation or its backend extension
  2896. * supports a given feature.
  2897. *
  2898. * @param string name of the feature (see the MDB2 class doc)
  2899. *
  2900. * @return bool|string if this DB implementation supports a given feature
  2901. * false means no, true means native,
  2902. * 'emulated' means emulated
  2903. *
  2904. * @access public
  2905. */
  2906. function supports($feature)
  2907. {
  2908. if (array_key_exists($feature, $this->supported)) {
  2909. return $this->supported[$feature];
  2910. }
  2911. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2912. "unknown support feature $feature", __FUNCTION__);
  2913. }
  2914. // }}}
  2915. // {{{ function getSequenceName($sqn)
  2916. /**
  2917. * adds sequence name formatting to a sequence name
  2918. *
  2919. * @param string name of the sequence
  2920. *
  2921. * @return string formatted sequence name
  2922. *
  2923. * @access public
  2924. */
  2925. function getSequenceName($sqn)
  2926. {
  2927. return sprintf($this->options['seqname_format'],
  2928. preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
  2929. }
  2930. // }}}
  2931. // {{{ function getIndexName($idx)
  2932. /**
  2933. * adds index name formatting to a index name
  2934. *
  2935. * @param string name of the index
  2936. *
  2937. * @return string formatted index name
  2938. *
  2939. * @access public
  2940. */
  2941. function getIndexName($idx)
  2942. {
  2943. return sprintf($this->options['idxname_format'],
  2944. preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
  2945. }
  2946. // }}}
  2947. // {{{ function nextID($seq_name, $ondemand = true)
  2948. /**
  2949. * Returns the next free id of a sequence
  2950. *
  2951. * @param string name of the sequence
  2952. * @param bool when true missing sequences are automatic created
  2953. *
  2954. * @return mixed MDB2 Error Object or id
  2955. *
  2956. * @access public
  2957. */
  2958. function nextID($seq_name, $ondemand = true)
  2959. {
  2960. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2961. 'method not implemented', __FUNCTION__);
  2962. }
  2963. // }}}
  2964. // {{{ function lastInsertID($table = null, $field = null)
  2965. /**
  2966. * Returns the autoincrement ID if supported or $id or fetches the current
  2967. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  2968. *
  2969. * @param string name of the table into which a new row was inserted
  2970. * @param string name of the field into which a new row was inserted
  2971. *
  2972. * @return mixed MDB2 Error Object or id
  2973. *
  2974. * @access public
  2975. */
  2976. function lastInsertID($table = null, $field = null)
  2977. {
  2978. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2979. 'method not implemented', __FUNCTION__);
  2980. }
  2981. // }}}
  2982. // {{{ function currID($seq_name)
  2983. /**
  2984. * Returns the current id of a sequence
  2985. *
  2986. * @param string name of the sequence
  2987. *
  2988. * @return mixed MDB2 Error Object or id
  2989. *
  2990. * @access public
  2991. */
  2992. function currID($seq_name)
  2993. {
  2994. $this->warnings[] = 'database does not support getting current
  2995. sequence value, the sequence value was incremented';
  2996. return $this->nextID($seq_name);
  2997. }
  2998. // }}}
  2999. // {{{ function queryOne($query, $type = null, $colnum = 0)
  3000. /**
  3001. * Execute the specified query, fetch the value from the first column of
  3002. * the first row of the result set and then frees
  3003. * the result set.
  3004. *
  3005. * @param string $query the SELECT query statement to be executed.
  3006. * @param string $type optional argument that specifies the expected
  3007. * datatype of the result set field, so that an eventual
  3008. * conversion may be performed. The default datatype is
  3009. * text, meaning that no conversion is performed
  3010. * @param mixed $colnum the column number (or name) to fetch
  3011. *
  3012. * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
  3013. *
  3014. * @access public
  3015. */
  3016. function queryOne($query, $type = null, $colnum = 0)
  3017. {
  3018. $result = $this->query($query, $type);
  3019. if (!MDB2::isResultCommon($result)) {
  3020. return $result;
  3021. }
  3022. $one = $result->fetchOne($colnum);
  3023. $result->free();
  3024. return $one;
  3025. }
  3026. // }}}
  3027. // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  3028. /**
  3029. * Execute the specified query, fetch the values from the first
  3030. * row of the result set into an array and then frees
  3031. * the result set.
  3032. *
  3033. * @param string the SELECT query statement to be executed.
  3034. * @param array optional array argument that specifies a list of
  3035. * expected datatypes of the result set columns, so that the eventual
  3036. * conversions may be performed. The default list of datatypes is
  3037. * empty, meaning that no conversion is performed.
  3038. * @param int how the array data should be indexed
  3039. *
  3040. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3041. *
  3042. * @access public
  3043. */
  3044. function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  3045. {
  3046. $result = $this->query($query, $types);
  3047. if (!MDB2::isResultCommon($result)) {
  3048. return $result;
  3049. }
  3050. $row = $result->fetchRow($fetchmode);
  3051. $result->free();
  3052. return $row;
  3053. }
  3054. // }}}
  3055. // {{{ function queryCol($query, $type = null, $colnum = 0)
  3056. /**
  3057. * Execute the specified query, fetch the value from the first column of
  3058. * each row of the result set into an array and then frees the result set.
  3059. *
  3060. * @param string $query the SELECT query statement to be executed.
  3061. * @param string $type optional argument that specifies the expected
  3062. * datatype of the result set field, so that an eventual
  3063. * conversion may be performed. The default datatype is text,
  3064. * meaning that no conversion is performed
  3065. * @param mixed $colnum the column number (or name) to fetch
  3066. *
  3067. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3068. * @access public
  3069. */
  3070. function queryCol($query, $type = null, $colnum = 0)
  3071. {
  3072. $result = $this->query($query, $type);
  3073. if (!MDB2::isResultCommon($result)) {
  3074. return $result;
  3075. }
  3076. $col = $result->fetchCol($colnum);
  3077. $result->free();
  3078. return $col;
  3079. }
  3080. // }}}
  3081. // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  3082. /**
  3083. * Execute the specified query, fetch all the rows of the result set into
  3084. * a two dimensional array and then frees the result set.
  3085. *
  3086. * @param string the SELECT query statement to be executed.
  3087. * @param array optional array argument that specifies a list of
  3088. * expected datatypes of the result set columns, so that the eventual
  3089. * conversions may be performed. The default list of datatypes is
  3090. * empty, meaning that no conversion is performed.
  3091. * @param int how the array data should be indexed
  3092. * @param bool if set to true, the $all will have the first
  3093. * column as its first dimension
  3094. * @param bool used only when the query returns exactly
  3095. * two columns. If true, the values of the returned array will be
  3096. * one-element arrays instead of scalars.
  3097. * @param bool if true, the values of the returned array is
  3098. * wrapped in another array. If the same key value (in the first
  3099. * column) repeats itself, the values will be appended to this array
  3100. * instead of overwriting the existing values.
  3101. *
  3102. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3103. *
  3104. * @access public
  3105. */
  3106. function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
  3107. $rekey = false, $force_array = false, $group = false)
  3108. {
  3109. $result = $this->query($query, $types);
  3110. if (!MDB2::isResultCommon($result)) {
  3111. return $result;
  3112. }
  3113. $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
  3114. $result->free();
  3115. return $all;
  3116. }
  3117. // }}}
  3118. // {{{ function delExpect($error_code)
  3119. /**
  3120. * This method deletes all occurences of the specified element from
  3121. * the expected error codes stack.
  3122. *
  3123. * @param mixed $error_code error code that should be deleted
  3124. * @return mixed list of error codes that were deleted or error
  3125. *
  3126. * @uses PEAR::delExpect()
  3127. */
  3128. public function delExpect($error_code)
  3129. {
  3130. return $this->pear->delExpect($error_code);
  3131. }
  3132. // }}}
  3133. // {{{ function expectError($code)
  3134. /**
  3135. * This method is used to tell which errors you expect to get.
  3136. * Expected errors are always returned with error mode
  3137. * PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
  3138. * and this method pushes a new element onto it. The list of
  3139. * expected errors are in effect until they are popped off the
  3140. * stack with the popExpect() method.
  3141. *
  3142. * Note that this method can not be called statically
  3143. *
  3144. * @param mixed $code a single error code or an array of error codes to expect
  3145. *
  3146. * @return int the new depth of the "expected errors" stack
  3147. *
  3148. * @uses PEAR::expectError()
  3149. */
  3150. public function expectError($code = '*')
  3151. {
  3152. return $this->pear->expectError($code);
  3153. }
  3154. // }}}
  3155. // {{{ function getStaticProperty($class, $var)
  3156. /**
  3157. * If you have a class that's mostly/entirely static, and you need static
  3158. * properties, you can use this method to simulate them. Eg. in your method(s)
  3159. * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
  3160. * You MUST use a reference, or they will not persist!
  3161. *
  3162. * @param string $class The calling classname, to prevent clashes
  3163. * @param string $var The variable to retrieve.
  3164. * @return mixed A reference to the variable. If not set it will be
  3165. * auto initialised to NULL.
  3166. *
  3167. * @uses PEAR::getStaticProperty()
  3168. */
  3169. public function &getStaticProperty($class, $var)
  3170. {
  3171. $tmp = $this->pear->getStaticProperty($class, $var);
  3172. return $tmp;
  3173. }
  3174. // }}}
  3175. // {{{ function loadExtension($ext)
  3176. /**
  3177. * OS independant PHP extension load. Remember to take care
  3178. * on the correct extension name for case sensitive OSes.
  3179. *
  3180. * @param string $ext The extension name
  3181. * @return bool Success or not on the dl() call
  3182. *
  3183. * @uses PEAR::loadExtension()
  3184. */
  3185. public function loadExtension($ext)
  3186. {
  3187. return $this->pear->loadExtension($ext);
  3188. }
  3189. // }}}
  3190. // {{{ function popErrorHandling()
  3191. /**
  3192. * Pop the last error handler used
  3193. *
  3194. * @return bool Always true
  3195. *
  3196. * @see PEAR::pushErrorHandling
  3197. * @uses PEAR::popErrorHandling()
  3198. */
  3199. public function popErrorHandling()
  3200. {
  3201. return $this->pear->popErrorHandling();
  3202. }
  3203. // }}}
  3204. // {{{ function popExpect()
  3205. /**
  3206. * This method pops one element off the expected error codes
  3207. * stack.
  3208. *
  3209. * @return array the list of error codes that were popped
  3210. *
  3211. * @uses PEAR::popExpect()
  3212. */
  3213. public function popExpect()
  3214. {
  3215. return $this->pear->popExpect();
  3216. }
  3217. // }}}
  3218. // {{{ function pushErrorHandling($mode, $options = null)
  3219. /**
  3220. * Push a new error handler on top of the error handler options stack. With this
  3221. * you can easily override the actual error handler for some code and restore
  3222. * it later with popErrorHandling.
  3223. *
  3224. * @param mixed $mode (same as setErrorHandling)
  3225. * @param mixed $options (same as setErrorHandling)
  3226. *
  3227. * @return bool Always true
  3228. *
  3229. * @see PEAR::setErrorHandling
  3230. * @uses PEAR::pushErrorHandling()
  3231. */
  3232. public function pushErrorHandling($mode, $options = null)
  3233. {
  3234. return $this->pear->pushErrorHandling($mode, $options);
  3235. }
  3236. // }}}
  3237. // {{{ function registerShutdownFunc($func, $args = array())
  3238. /**
  3239. * Use this function to register a shutdown method for static
  3240. * classes.
  3241. *
  3242. * @param mixed $func The function name (or array of class/method) to call
  3243. * @param mixed $args The arguments to pass to the function
  3244. * @return void
  3245. *
  3246. * @uses PEAR::registerShutdownFunc()
  3247. */
  3248. public function registerShutdownFunc($func, $args = array())
  3249. {
  3250. return $this->pear->registerShutdownFunc($func, $args);
  3251. }
  3252. // }}}
  3253. // {{{ function setErrorHandling($mode = null, $options = null)
  3254. /**
  3255. * Sets how errors generated by this object should be handled.
  3256. * Can be invoked both in objects and statically. If called
  3257. * statically, setErrorHandling sets the default behaviour for all
  3258. * PEAR objects. If called in an object, setErrorHandling sets
  3259. * the default behaviour for that object.
  3260. *
  3261. * @param int $mode
  3262. * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
  3263. * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
  3264. * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
  3265. *
  3266. * @param mixed $options
  3267. * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
  3268. * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
  3269. *
  3270. * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
  3271. * to be the callback function or method. A callback
  3272. * function is a string with the name of the function, a
  3273. * callback method is an array of two elements: the element
  3274. * at index 0 is the object, and the element at index 1 is
  3275. * the name of the method to call in the object.
  3276. *
  3277. * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
  3278. * a printf format string used when printing the error
  3279. * message.
  3280. *
  3281. * @access public
  3282. * @return void
  3283. * @see PEAR_ERROR_RETURN
  3284. * @see PEAR_ERROR_PRINT
  3285. * @see PEAR_ERROR_TRIGGER
  3286. * @see PEAR_ERROR_DIE
  3287. * @see PEAR_ERROR_CALLBACK
  3288. * @see PEAR_ERROR_EXCEPTION
  3289. *
  3290. * @since PHP 4.0.5
  3291. * @uses PEAR::setErrorHandling($mode, $options)
  3292. */
  3293. public function setErrorHandling($mode = null, $options = null)
  3294. {
  3295. return $this->pear->setErrorHandling($mode, $options);
  3296. }
  3297. /**
  3298. * @uses PEAR::staticPopErrorHandling()
  3299. */
  3300. public function staticPopErrorHandling()
  3301. {
  3302. return $this->pear->staticPopErrorHandling();
  3303. }
  3304. // }}}
  3305. // {{{ function staticPushErrorHandling($mode, $options = null)
  3306. /**
  3307. * @uses PEAR::staticPushErrorHandling($mode, $options)
  3308. */
  3309. public function staticPushErrorHandling($mode, $options = null)
  3310. {
  3311. return $this->pear->staticPushErrorHandling($mode, $options);
  3312. }
  3313. // }}}
  3314. // {{{ function &throwError($message = null, $code = null, $userinfo = null)
  3315. /**
  3316. * Simpler form of raiseError with fewer options. In most cases
  3317. * message, code and userinfo are enough.
  3318. *
  3319. * @param mixed $message a text error message or a PEAR error object
  3320. *
  3321. * @param int $code a numeric error code (it is up to your class
  3322. * to define these if you want to use codes)
  3323. *
  3324. * @param string $userinfo If you need to pass along for example debug
  3325. * information, this parameter is meant for that.
  3326. *
  3327. * @return object a PEAR error object
  3328. * @see PEAR::raiseError
  3329. * @uses PEAR::&throwError()
  3330. */
  3331. public function &throwError($message = null, $code = null, $userinfo = null)
  3332. {
  3333. $tmp = $this->pear->throwError($message, $code, $userinfo);
  3334. return $tmp;
  3335. }
  3336. // }}}
  3337. }
  3338. // }}}
  3339. // {{{ class MDB2_Result
  3340. /**
  3341. * The dummy class that all user space result classes should extend from
  3342. *
  3343. * @package MDB2
  3344. * @category Database
  3345. * @author Lukas Smith <smith@pooteeweet.org>
  3346. */
  3347. class MDB2_Result
  3348. {
  3349. }
  3350. // }}}
  3351. // {{{ class MDB2_Result_Common extends MDB2_Result
  3352. /**
  3353. * The common result class for MDB2 result objects
  3354. *
  3355. * @package MDB2
  3356. * @category Database
  3357. * @author Lukas Smith <smith@pooteeweet.org>
  3358. */
  3359. class MDB2_Result_Common extends MDB2_Result
  3360. {
  3361. // {{{ Variables (Properties)
  3362. public $db;
  3363. public $result;
  3364. public $rownum = -1;
  3365. public $types = array();
  3366. public $types_assoc = array();
  3367. public $values = array();
  3368. public $offset;
  3369. public $offset_count = 0;
  3370. public $limit;
  3371. public $column_names;
  3372. // }}}
  3373. // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)
  3374. /**
  3375. * Constructor
  3376. */
  3377. function __construct($db, &$result, $limit = 0, $offset = 0)
  3378. {
  3379. $this->db = $db;
  3380. $this->result = $result;
  3381. $this->offset = $offset;
  3382. $this->limit = max(0, $limit - 1);
  3383. }
  3384. // }}}
  3385. // {{{ function setResultTypes($types)
  3386. /**
  3387. * Define the list of types to be associated with the columns of a given
  3388. * result set.
  3389. *
  3390. * This function may be called before invoking fetchRow(), fetchOne(),
  3391. * fetchCol() and fetchAll() so that the necessary data type
  3392. * conversions are performed on the data to be retrieved by them. If this
  3393. * function is not called, the type of all result set columns is assumed
  3394. * to be text, thus leading to not perform any conversions.
  3395. *
  3396. * @param array variable that lists the
  3397. * data types to be expected in the result set columns. If this array
  3398. * contains less types than the number of columns that are returned
  3399. * in the result set, the remaining columns are assumed to be of the
  3400. * type text. Currently, the types clob and blob are not fully
  3401. * supported.
  3402. *
  3403. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3404. *
  3405. * @access public
  3406. */
  3407. function setResultTypes($types)
  3408. {
  3409. $load = $this->db->loadModule('Datatype', null, true);
  3410. if (MDB2::isError($load)) {
  3411. return $load;
  3412. }
  3413. $types = $this->db->datatype->checkResultTypes($types);
  3414. if (MDB2::isError($types)) {
  3415. return $types;
  3416. }
  3417. foreach ($types as $key => $value) {
  3418. if (is_numeric($key)) {
  3419. $this->types[$key] = $value;
  3420. } else {
  3421. $this->types_assoc[$key] = $value;
  3422. }
  3423. }
  3424. return MDB2_OK;
  3425. }
  3426. // }}}
  3427. // {{{ function seek($rownum = 0)
  3428. /**
  3429. * Seek to a specific row in a result set
  3430. *
  3431. * @param int number of the row where the data can be found
  3432. *
  3433. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3434. *
  3435. * @access public
  3436. */
  3437. function seek($rownum = 0)
  3438. {
  3439. $target_rownum = $rownum - 1;
  3440. if ($this->rownum > $target_rownum) {
  3441. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3442. 'seeking to previous rows not implemented', __FUNCTION__);
  3443. }
  3444. while ($this->rownum < $target_rownum) {
  3445. $this->fetchRow();
  3446. }
  3447. return MDB2_OK;
  3448. }
  3449. // }}}
  3450. // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3451. /**
  3452. * Fetch and return a row of data
  3453. *
  3454. * @param int how the array data should be indexed
  3455. * @param int number of the row where the data can be found
  3456. *
  3457. * @return int data array on success, a MDB2 error on failure
  3458. *
  3459. * @access public
  3460. */
  3461. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3462. {
  3463. $err = MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3464. 'method not implemented', __FUNCTION__);
  3465. return $err;
  3466. }
  3467. // }}}
  3468. // {{{ function fetchOne($colnum = 0)
  3469. /**
  3470. * fetch single column from the next row from a result set
  3471. *
  3472. * @param int|string the column number (or name) to fetch
  3473. * @param int number of the row where the data can be found
  3474. *
  3475. * @return string data on success, a MDB2 error on failure
  3476. * @access public
  3477. */
  3478. function fetchOne($colnum = 0, $rownum = null)
  3479. {
  3480. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3481. $row = $this->fetchRow($fetchmode, $rownum);
  3482. if (!is_array($row) || MDB2::isError($row)) {
  3483. return $row;
  3484. }
  3485. if (!array_key_exists($colnum, $row)) {
  3486. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3487. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3488. }
  3489. return $row[$colnum];
  3490. }
  3491. // }}}
  3492. // {{{ function fetchCol($colnum = 0)
  3493. /**
  3494. * Fetch and return a column from the current row pointer position
  3495. *
  3496. * @param int|string the column number (or name) to fetch
  3497. *
  3498. * @return mixed data array on success, a MDB2 error on failure
  3499. * @access public
  3500. */
  3501. function fetchCol($colnum = 0)
  3502. {
  3503. $column = array();
  3504. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3505. $row = $this->fetchRow($fetchmode);
  3506. if (is_array($row)) {
  3507. if (!array_key_exists($colnum, $row)) {
  3508. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3509. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3510. }
  3511. do {
  3512. $column[] = $row[$colnum];
  3513. } while (is_array($row = $this->fetchRow($fetchmode)));
  3514. }
  3515. if (MDB2::isError($row)) {
  3516. return $row;
  3517. }
  3518. return $column;
  3519. }
  3520. // }}}
  3521. // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  3522. /**
  3523. * Fetch and return all rows from the current row pointer position
  3524. *
  3525. * @param int $fetchmode the fetch mode to use:
  3526. * + MDB2_FETCHMODE_ORDERED
  3527. * + MDB2_FETCHMODE_ASSOC
  3528. * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
  3529. * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
  3530. * @param bool if set to true, the $all will have the first
  3531. * column as its first dimension
  3532. * @param bool used only when the query returns exactly
  3533. * two columns. If true, the values of the returned array will be
  3534. * one-element arrays instead of scalars.
  3535. * @param bool if true, the values of the returned array is
  3536. * wrapped in another array. If the same key value (in the first
  3537. * column) repeats itself, the values will be appended to this array
  3538. * instead of overwriting the existing values.
  3539. *
  3540. * @return mixed data array on success, a MDB2 error on failure
  3541. *
  3542. * @access public
  3543. * @see getAssoc()
  3544. */
  3545. function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
  3546. $force_array = false, $group = false)
  3547. {
  3548. $all = array();
  3549. $row = $this->fetchRow($fetchmode);
  3550. if (MDB2::isError($row)) {
  3551. return $row;
  3552. } elseif (!$row) {
  3553. return $all;
  3554. }
  3555. $shift_array = $rekey ? false : null;
  3556. if (null !== $shift_array) {
  3557. if (is_object($row)) {
  3558. $colnum = count(get_object_vars($row));
  3559. } else {
  3560. $colnum = count($row);
  3561. }
  3562. if ($colnum < 2) {
  3563. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3564. 'rekey feature requires atleast 2 column', __FUNCTION__);
  3565. }
  3566. $shift_array = (!$force_array && $colnum == 2);
  3567. }
  3568. if ($rekey) {
  3569. do {
  3570. if (is_object($row)) {
  3571. $arr = get_object_vars($row);
  3572. $key = reset($arr);
  3573. unset($row->{$key});
  3574. } else {
  3575. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  3576. || $fetchmode == MDB2_FETCHMODE_OBJECT
  3577. ) {
  3578. $key = reset($row);
  3579. unset($row[key($row)]);
  3580. } else {
  3581. $key = array_shift($row);
  3582. }
  3583. if ($shift_array) {
  3584. $row = array_shift($row);
  3585. }
  3586. }
  3587. if ($group) {
  3588. $all[$key][] = $row;
  3589. } else {
  3590. $all[$key] = $row;
  3591. }
  3592. } while (($row = $this->fetchRow($fetchmode)));
  3593. } elseif ($fetchmode == MDB2_FETCHMODE_FLIPPED) {
  3594. do {
  3595. foreach ($row as $key => $val) {
  3596. $all[$key][] = $val;
  3597. }
  3598. } while (($row = $this->fetchRow($fetchmode)));
  3599. } else {
  3600. do {
  3601. $all[] = $row;
  3602. } while (($row = $this->fetchRow($fetchmode)));
  3603. }
  3604. return $all;
  3605. }
  3606. // }}}
  3607. // {{{ function rowCount()
  3608. /**
  3609. * Returns the actual row number that was last fetched (count from 0)
  3610. * @return int
  3611. *
  3612. * @access public
  3613. */
  3614. function rowCount()
  3615. {
  3616. return $this->rownum + 1;
  3617. }
  3618. // }}}
  3619. // {{{ function numRows()
  3620. /**
  3621. * Returns the number of rows in a result object
  3622. *
  3623. * @return mixed MDB2 Error Object or the number of rows
  3624. *
  3625. * @access public
  3626. */
  3627. function numRows()
  3628. {
  3629. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3630. 'method not implemented', __FUNCTION__);
  3631. }
  3632. // }}}
  3633. // {{{ function nextResult()
  3634. /**
  3635. * Move the internal result pointer to the next available result
  3636. *
  3637. * @return true on success, false if there is no more result set or an error object on failure
  3638. *
  3639. * @access public
  3640. */
  3641. function nextResult()
  3642. {
  3643. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3644. 'method not implemented', __FUNCTION__);
  3645. }
  3646. // }}}
  3647. // {{{ function getColumnNames()
  3648. /**
  3649. * Retrieve the names of columns returned by the DBMS in a query result or
  3650. * from the cache.
  3651. *
  3652. * @param bool If set to true the values are the column names,
  3653. * otherwise the names of the columns are the keys.
  3654. * @return mixed Array variable that holds the names of columns or an
  3655. * MDB2 error on failure.
  3656. * Some DBMS may not return any columns when the result set
  3657. * does not contain any rows.
  3658. *
  3659. * @access public
  3660. */
  3661. function getColumnNames($flip = false)
  3662. {
  3663. if (!isset($this->column_names)) {
  3664. $result = $this->_getColumnNames();
  3665. if (MDB2::isError($result)) {
  3666. return $result;
  3667. }
  3668. $this->column_names = $result;
  3669. }
  3670. if ($flip) {
  3671. return array_flip($this->column_names);
  3672. }
  3673. return $this->column_names;
  3674. }
  3675. // }}}
  3676. // {{{ function _getColumnNames()
  3677. /**
  3678. * Retrieve the names of columns returned by the DBMS in a query result.
  3679. *
  3680. * @return mixed Array variable that holds the names of columns as keys
  3681. * or an MDB2 error on failure.
  3682. * Some DBMS may not return any columns when the result set
  3683. * does not contain any rows.
  3684. *
  3685. * @access private
  3686. */
  3687. function _getColumnNames()
  3688. {
  3689. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3690. 'method not implemented', __FUNCTION__);
  3691. }
  3692. // }}}
  3693. // {{{ function numCols()
  3694. /**
  3695. * Count the number of columns returned by the DBMS in a query result.
  3696. *
  3697. * @return mixed integer value with the number of columns, a MDB2 error
  3698. * on failure
  3699. *
  3700. * @access public
  3701. */
  3702. function numCols()
  3703. {
  3704. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3705. 'method not implemented', __FUNCTION__);
  3706. }
  3707. // }}}
  3708. // {{{ function getResource()
  3709. /**
  3710. * return the resource associated with the result object
  3711. *
  3712. * @return resource
  3713. *
  3714. * @access public
  3715. */
  3716. function getResource()
  3717. {
  3718. return $this->result;
  3719. }
  3720. // }}}
  3721. // {{{ function bindColumn($column, &$value, $type = null)
  3722. /**
  3723. * Set bind variable to a column.
  3724. *
  3725. * @param int column number or name
  3726. * @param mixed variable reference
  3727. * @param string specifies the type of the field
  3728. *
  3729. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3730. *
  3731. * @access public
  3732. */
  3733. function bindColumn($column, &$value, $type = null)
  3734. {
  3735. if (!is_numeric($column)) {
  3736. $column_names = $this->getColumnNames();
  3737. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  3738. if ($this->db->options['field_case'] == CASE_LOWER) {
  3739. $column = strtolower($column);
  3740. } else {
  3741. $column = strtoupper($column);
  3742. }
  3743. }
  3744. $column = $column_names[$column];
  3745. }
  3746. $this->values[$column] =& $value;
  3747. if (null !== $type) {
  3748. $this->types[$column] = $type;
  3749. }
  3750. return MDB2_OK;
  3751. }
  3752. // }}}
  3753. // {{{ function _assignBindColumns($row)
  3754. /**
  3755. * Bind a variable to a value in the result row.
  3756. *
  3757. * @param array row data
  3758. *
  3759. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3760. *
  3761. * @access private
  3762. */
  3763. function _assignBindColumns($row)
  3764. {
  3765. $row = array_values($row);
  3766. foreach ($row as $column => $value) {
  3767. if (array_key_exists($column, $this->values)) {
  3768. $this->values[$column] = $value;
  3769. }
  3770. }
  3771. return MDB2_OK;
  3772. }
  3773. // }}}
  3774. // {{{ function free()
  3775. /**
  3776. * Free the internal resources associated with result.
  3777. *
  3778. * @return bool true on success, false if result is invalid
  3779. *
  3780. * @access public
  3781. */
  3782. function free()
  3783. {
  3784. $this->result = false;
  3785. return MDB2_OK;
  3786. }
  3787. // }}}
  3788. }
  3789. // }}}
  3790. // {{{ class MDB2_Row
  3791. /**
  3792. * The simple class that accepts row data as an array
  3793. *
  3794. * @package MDB2
  3795. * @category Database
  3796. * @author Lukas Smith <smith@pooteeweet.org>
  3797. */
  3798. class MDB2_Row
  3799. {
  3800. // {{{ constructor: function __construct(&$row)
  3801. /**
  3802. * constructor
  3803. *
  3804. * @param resource row data as array
  3805. */
  3806. function __construct(&$row)
  3807. {
  3808. foreach ($row as $key => $value) {
  3809. $this->$key = &$row[$key];
  3810. }
  3811. }
  3812. // }}}
  3813. }
  3814. // }}}
  3815. // {{{ class MDB2_Statement_Common
  3816. /**
  3817. * The common statement class for MDB2 statement objects
  3818. *
  3819. * @package MDB2
  3820. * @category Database
  3821. * @author Lukas Smith <smith@pooteeweet.org>
  3822. */
  3823. class MDB2_Statement_Common
  3824. {
  3825. // {{{ Variables (Properties)
  3826. var $db;
  3827. var $statement;
  3828. var $query;
  3829. var $result_types;
  3830. var $types;
  3831. var $values = array();
  3832. var $limit;
  3833. var $offset;
  3834. var $is_manip;
  3835. // }}}
  3836. // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3837. /**
  3838. * Constructor
  3839. */
  3840. function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3841. {
  3842. $this->db = $db;
  3843. $this->statement = $statement;
  3844. $this->positions = $positions;
  3845. $this->query = $query;
  3846. $this->types = (array)$types;
  3847. $this->result_types = (array)$result_types;
  3848. $this->limit = $limit;
  3849. $this->is_manip = $is_manip;
  3850. $this->offset = $offset;
  3851. }
  3852. // }}}
  3853. // {{{ function bindValue($parameter, &$value, $type = null)
  3854. /**
  3855. * Set the value of a parameter of a prepared query.
  3856. *
  3857. * @param int the order number of the parameter in the query
  3858. * statement. The order number of the first parameter is 1.
  3859. * @param mixed value that is meant to be assigned to specified
  3860. * parameter. The type of the value depends on the $type argument.
  3861. * @param string specifies the type of the field
  3862. *
  3863. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3864. *
  3865. * @access public
  3866. */
  3867. function bindValue($parameter, $value, $type = null)
  3868. {
  3869. if (!is_numeric($parameter)) {
  3870. if (strpos($parameter, ':') === 0) {
  3871. $parameter = substr($parameter, 1);
  3872. }
  3873. }
  3874. if (!in_array($parameter, $this->positions)) {
  3875. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3876. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3877. }
  3878. $this->values[$parameter] = $value;
  3879. if (null !== $type) {
  3880. $this->types[$parameter] = $type;
  3881. }
  3882. return MDB2_OK;
  3883. }
  3884. // }}}
  3885. // {{{ function bindValueArray($values, $types = null)
  3886. /**
  3887. * Set the values of multiple a parameter of a prepared query in bulk.
  3888. *
  3889. * @param array specifies all necessary information
  3890. * for bindValue() the array elements must use keys corresponding to
  3891. * the number of the position of the parameter.
  3892. * @param array specifies the types of the fields
  3893. *
  3894. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3895. *
  3896. * @access public
  3897. * @see bindParam()
  3898. */
  3899. function bindValueArray($values, $types = null)
  3900. {
  3901. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3902. $parameters = array_keys($values);
  3903. $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
  3904. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  3905. foreach ($parameters as $key => $parameter) {
  3906. $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
  3907. if (MDB2::isError($err)) {
  3908. if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
  3909. //ignore (extra value for missing placeholder)
  3910. continue;
  3911. }
  3912. $this->db->popExpect();
  3913. $this->db->popErrorHandling();
  3914. return $err;
  3915. }
  3916. }
  3917. $this->db->popExpect();
  3918. $this->db->popErrorHandling();
  3919. return MDB2_OK;
  3920. }
  3921. // }}}
  3922. // {{{ function bindParam($parameter, &$value, $type = null)
  3923. /**
  3924. * Bind a variable to a parameter of a prepared query.
  3925. *
  3926. * @param int the order number of the parameter in the query
  3927. * statement. The order number of the first parameter is 1.
  3928. * @param mixed variable that is meant to be bound to specified
  3929. * parameter. The type of the value depends on the $type argument.
  3930. * @param string specifies the type of the field
  3931. *
  3932. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3933. *
  3934. * @access public
  3935. */
  3936. function bindParam($parameter, &$value, $type = null)
  3937. {
  3938. if (!is_numeric($parameter)) {
  3939. if (strpos($parameter, ':') === 0) {
  3940. $parameter = substr($parameter, 1);
  3941. }
  3942. }
  3943. if (!in_array($parameter, $this->positions)) {
  3944. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3945. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3946. }
  3947. $this->values[$parameter] =& $value;
  3948. if (null !== $type) {
  3949. $this->types[$parameter] = $type;
  3950. }
  3951. return MDB2_OK;
  3952. }
  3953. // }}}
  3954. // {{{ function bindParamArray(&$values, $types = null)
  3955. /**
  3956. * Bind the variables of multiple a parameter of a prepared query in bulk.
  3957. *
  3958. * @param array specifies all necessary information
  3959. * for bindParam() the array elements must use keys corresponding to
  3960. * the number of the position of the parameter.
  3961. * @param array specifies the types of the fields
  3962. *
  3963. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3964. *
  3965. * @access public
  3966. * @see bindParam()
  3967. */
  3968. function bindParamArray(&$values, $types = null)
  3969. {
  3970. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3971. $parameters = array_keys($values);
  3972. foreach ($parameters as $key => $parameter) {
  3973. $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
  3974. if (MDB2::isError($err)) {
  3975. return $err;
  3976. }
  3977. }
  3978. return MDB2_OK;
  3979. }
  3980. // }}}
  3981. // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
  3982. /**
  3983. * Execute a prepared query statement.
  3984. *
  3985. * @param array specifies all necessary information
  3986. * for bindParam() the array elements must use keys corresponding
  3987. * to the number of the position of the parameter.
  3988. * @param mixed specifies which result class to use
  3989. * @param mixed specifies which class to wrap results in
  3990. *
  3991. * @return mixed MDB2_Result or integer (affected rows) on success,
  3992. * a MDB2 error on failure
  3993. * @access public
  3994. */
  3995. function execute($values = null, $result_class = true, $result_wrap_class = false)
  3996. {
  3997. if (null === $this->positions) {
  3998. return MDB2::raiseError(MDB2_ERROR, null, null,
  3999. 'Prepared statement has already been freed', __FUNCTION__);
  4000. }
  4001. $values = (array)$values;
  4002. if (!empty($values)) {
  4003. $err = $this->bindValueArray($values);
  4004. if (MDB2::isError($err)) {
  4005. return MDB2::raiseError(MDB2_ERROR, null, null,
  4006. 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
  4007. }
  4008. }
  4009. $result = $this->_execute($result_class, $result_wrap_class);
  4010. return $result;
  4011. }
  4012. // }}}
  4013. // {{{ function _execute($result_class = true, $result_wrap_class = false)
  4014. /**
  4015. * Execute a prepared query statement helper method.
  4016. *
  4017. * @param mixed specifies which result class to use
  4018. * @param mixed specifies which class to wrap results in
  4019. *
  4020. * @return mixed MDB2_Result or integer (affected rows) on success,
  4021. * a MDB2 error on failure
  4022. * @access private
  4023. */
  4024. function _execute($result_class = true, $result_wrap_class = false)
  4025. {
  4026. $this->last_query = $this->query;
  4027. $query = '';
  4028. $last_position = 0;
  4029. foreach ($this->positions as $current_position => $parameter) {
  4030. if (!array_key_exists($parameter, $this->values)) {
  4031. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  4032. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  4033. }
  4034. $value = $this->values[$parameter];
  4035. $query.= substr($this->query, $last_position, $current_position - $last_position);
  4036. if (!isset($value)) {
  4037. $value_quoted = 'NULL';
  4038. } else {
  4039. $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
  4040. $value_quoted = $this->db->quote($value, $type);
  4041. if (MDB2::isError($value_quoted)) {
  4042. return $value_quoted;
  4043. }
  4044. }
  4045. $query.= $value_quoted;
  4046. $last_position = $current_position + 1;
  4047. }
  4048. $query.= substr($this->query, $last_position);
  4049. $this->db->offset = $this->offset;
  4050. $this->db->limit = $this->limit;
  4051. if ($this->is_manip) {
  4052. $result = $this->db->exec($query);
  4053. } else {
  4054. $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
  4055. }
  4056. return $result;
  4057. }
  4058. // }}}
  4059. // {{{ function free()
  4060. /**
  4061. * Release resources allocated for the specified prepared query.
  4062. *
  4063. * @return mixed MDB2_OK on success, a MDB2 error on failure
  4064. *
  4065. * @access public
  4066. */
  4067. function free()
  4068. {
  4069. if (null === $this->positions) {
  4070. return MDB2::raiseError(MDB2_ERROR, null, null,
  4071. 'Prepared statement has already been freed', __FUNCTION__);
  4072. }
  4073. $this->statement = null;
  4074. $this->positions = null;
  4075. $this->query = null;
  4076. $this->types = null;
  4077. $this->result_types = null;
  4078. $this->limit = null;
  4079. $this->is_manip = null;
  4080. $this->offset = null;
  4081. $this->values = null;
  4082. return MDB2_OK;
  4083. }
  4084. // }}}
  4085. }
  4086. // }}}
  4087. // {{{ class MDB2_Module_Common
  4088. /**
  4089. * The common modules class for MDB2 module objects
  4090. *
  4091. * @package MDB2
  4092. * @category Database
  4093. * @author Lukas Smith <smith@pooteeweet.org>
  4094. */
  4095. class MDB2_Module_Common
  4096. {
  4097. // {{{ Variables (Properties)
  4098. /**
  4099. * contains the key to the global MDB2 instance array of the associated
  4100. * MDB2 instance
  4101. *
  4102. * @var int
  4103. * @access protected
  4104. */
  4105. protected $db_index;
  4106. // }}}
  4107. // {{{ constructor: function __construct($db_index)
  4108. /**
  4109. * Constructor
  4110. */
  4111. function __construct($db_index)
  4112. {
  4113. $this->db_index = $db_index;
  4114. }
  4115. // }}}
  4116. // {{{ function getDBInstance()
  4117. /**
  4118. * Get the instance of MDB2 associated with the module instance
  4119. *
  4120. * @return object MDB2 instance or a MDB2 error on failure
  4121. *
  4122. * @access public
  4123. */
  4124. function getDBInstance()
  4125. {
  4126. if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
  4127. $result = $GLOBALS['_MDB2_databases'][$this->db_index];
  4128. } else {
  4129. $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  4130. 'could not find MDB2 instance');
  4131. }
  4132. return $result;
  4133. }
  4134. // }}}
  4135. }
  4136. // }}}
  4137. // {{{ function MDB2_closeOpenTransactions()
  4138. /**
  4139. * Close any open transactions form persistent connections
  4140. *
  4141. * @return void
  4142. *
  4143. * @access public
  4144. */
  4145. function MDB2_closeOpenTransactions()
  4146. {
  4147. reset($GLOBALS['_MDB2_databases']);
  4148. while (next($GLOBALS['_MDB2_databases'])) {
  4149. $key = key($GLOBALS['_MDB2_databases']);
  4150. if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
  4151. && $GLOBALS['_MDB2_databases'][$key]->in_transaction
  4152. ) {
  4153. $GLOBALS['_MDB2_databases'][$key]->rollback();
  4154. }
  4155. }
  4156. }
  4157. // }}}
  4158. // {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
  4159. /**
  4160. * default debug output handler
  4161. *
  4162. * @param object reference to an MDB2 database object
  4163. * @param string usually the method name that triggered the debug call:
  4164. * for example 'query', 'prepare', 'execute', 'parameters',
  4165. * 'beginTransaction', 'commit', 'rollback'
  4166. * @param string message that should be appended to the debug variable
  4167. * @param array contains context information about the debug() call
  4168. * common keys are: is_manip, time, result etc.
  4169. *
  4170. * @return void|string optionally return a modified message, this allows
  4171. * rewriting a query before being issued or prepared
  4172. *
  4173. * @access public
  4174. */
  4175. function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
  4176. {
  4177. $db->debug_output.= $scope.'('.$db->db_index.'): ';
  4178. $db->debug_output.= $message.$db->getOption('log_line_break');
  4179. return $message;
  4180. }
  4181. // }}}
  4182. ?>