MDB2.php 140 KB

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