MDB2.php 148 KB

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