MDB2.php 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577
  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. if (!property_exists($this, 'loaded_version_modules')) {
  1781. $this->loaded_version_modules = null;
  1782. }
  1783. else {
  1784. $this->loaded_version_modules[] = $property;
  1785. }
  1786. }
  1787. }
  1788. return $this->{$property};
  1789. }
  1790. // }}}
  1791. // {{{ function __call($method, $params)
  1792. /**
  1793. * Calls a module method using the __call magic method
  1794. *
  1795. * @param string Method name.
  1796. * @param array Arguments.
  1797. *
  1798. * @return mixed Returned value.
  1799. */
  1800. function __call($method, $params)
  1801. {
  1802. $module = null;
  1803. if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
  1804. && isset($this->options['modules'][$match[1]])
  1805. ) {
  1806. $module = $this->options['modules'][$match[1]];
  1807. $method = strtolower($match[2]).$match[3];
  1808. if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
  1809. $result = $this->loadModule($module);
  1810. if (MDB2::isError($result)) {
  1811. return $result;
  1812. }
  1813. }
  1814. } else {
  1815. foreach ($this->modules as $key => $foo) {
  1816. if (is_object($this->modules[$key])
  1817. && method_exists($this->modules[$key], $method)
  1818. ) {
  1819. $module = $key;
  1820. break;
  1821. }
  1822. }
  1823. }
  1824. if (null !== $module) {
  1825. return call_user_func_array(array(&$this->modules[$module], $method), $params);
  1826. }
  1827. trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
  1828. }
  1829. // }}}
  1830. // {{{ function beginTransaction($savepoint = null)
  1831. /**
  1832. * Start a transaction or set a savepoint.
  1833. *
  1834. * @param string name of a savepoint to set
  1835. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1836. *
  1837. * @access public
  1838. */
  1839. function beginTransaction($savepoint = null)
  1840. {
  1841. $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1842. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1843. 'transactions are not supported', __FUNCTION__);
  1844. }
  1845. // }}}
  1846. // {{{ function commit($savepoint = null)
  1847. /**
  1848. * Commit the database changes done during a transaction that is in
  1849. * progress or release a savepoint. This function may only be called when
  1850. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1851. * transaction is implicitly started after committing the pending changes.
  1852. *
  1853. * @param string name of a savepoint to release
  1854. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1855. *
  1856. * @access public
  1857. */
  1858. function commit($savepoint = null)
  1859. {
  1860. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1861. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1862. 'commiting transactions is not supported', __FUNCTION__);
  1863. }
  1864. // }}}
  1865. // {{{ function rollback($savepoint = null)
  1866. /**
  1867. * Cancel any database changes done during a transaction or since a specific
  1868. * savepoint that is in progress. This function may only be called when
  1869. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  1870. * transaction is implicitly started after canceling the pending changes.
  1871. *
  1872. * @param string name of a savepoint to rollback to
  1873. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1874. *
  1875. * @access public
  1876. */
  1877. function rollback($savepoint = null)
  1878. {
  1879. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  1880. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1881. 'rolling back transactions is not supported', __FUNCTION__);
  1882. }
  1883. // }}}
  1884. // {{{ function inTransaction($ignore_nested = false)
  1885. /**
  1886. * If a transaction is currently open.
  1887. *
  1888. * @param bool if the nested transaction count should be ignored
  1889. * @return int|bool - an integer with the nesting depth is returned if a
  1890. * nested transaction is open
  1891. * - true is returned for a normal open transaction
  1892. * - false is returned if no transaction is open
  1893. *
  1894. * @access public
  1895. */
  1896. function inTransaction($ignore_nested = false)
  1897. {
  1898. if (!$ignore_nested && isset($this->nested_transaction_counter)) {
  1899. return $this->nested_transaction_counter;
  1900. }
  1901. return $this->in_transaction;
  1902. }
  1903. // }}}
  1904. // {{{ function setTransactionIsolation($isolation)
  1905. /**
  1906. * Set the transacton isolation level.
  1907. *
  1908. * @param string standard isolation level
  1909. * READ UNCOMMITTED (allows dirty reads)
  1910. * READ COMMITTED (prevents dirty reads)
  1911. * REPEATABLE READ (prevents nonrepeatable reads)
  1912. * SERIALIZABLE (prevents phantom reads)
  1913. * @param array some transaction options:
  1914. * 'wait' => 'WAIT' | 'NO WAIT'
  1915. * 'rw' => 'READ WRITE' | 'READ ONLY'
  1916. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1917. *
  1918. * @access public
  1919. * @since 2.1.1
  1920. */
  1921. function setTransactionIsolation($isolation, $options = array())
  1922. {
  1923. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  1924. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  1925. 'isolation level setting is not supported', __FUNCTION__);
  1926. }
  1927. // }}}
  1928. // {{{ function beginNestedTransaction($savepoint = false)
  1929. /**
  1930. * Start a nested transaction.
  1931. *
  1932. * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
  1933. *
  1934. * @access public
  1935. * @since 2.1.1
  1936. */
  1937. function beginNestedTransaction()
  1938. {
  1939. if ($this->in_transaction) {
  1940. ++$this->nested_transaction_counter;
  1941. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1942. if ($this->supports('savepoints') && $savepoint) {
  1943. return $this->beginTransaction($savepoint);
  1944. }
  1945. return MDB2_OK;
  1946. }
  1947. $this->has_transaction_error = false;
  1948. $result = $this->beginTransaction();
  1949. $this->nested_transaction_counter = 1;
  1950. return $result;
  1951. }
  1952. // }}}
  1953. // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
  1954. /**
  1955. * Finish a nested transaction by rolling back if an error occured or
  1956. * committing otherwise.
  1957. *
  1958. * @param bool if the transaction should be rolled back regardless
  1959. * even if no error was set within the nested transaction
  1960. * @return mixed MDB_OK on commit/counter decrementing, false on rollback
  1961. * and a MDB2 error on failure
  1962. *
  1963. * @access public
  1964. * @since 2.1.1
  1965. */
  1966. function completeNestedTransaction($force_rollback = false)
  1967. {
  1968. if ($this->nested_transaction_counter > 1) {
  1969. $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
  1970. if ($this->supports('savepoints') && $savepoint) {
  1971. if ($force_rollback || $this->has_transaction_error) {
  1972. $result = $this->rollback($savepoint);
  1973. if (!MDB2::isError($result)) {
  1974. $result = false;
  1975. $this->has_transaction_error = false;
  1976. }
  1977. } else {
  1978. $result = $this->commit($savepoint);
  1979. }
  1980. } else {
  1981. $result = MDB2_OK;
  1982. }
  1983. --$this->nested_transaction_counter;
  1984. return $result;
  1985. }
  1986. $this->nested_transaction_counter = null;
  1987. $result = MDB2_OK;
  1988. // transaction has not yet been rolled back
  1989. if ($this->in_transaction) {
  1990. if ($force_rollback || $this->has_transaction_error) {
  1991. $result = $this->rollback();
  1992. if (!MDB2::isError($result)) {
  1993. $result = false;
  1994. }
  1995. } else {
  1996. $result = $this->commit();
  1997. }
  1998. }
  1999. $this->has_transaction_error = false;
  2000. return $result;
  2001. }
  2002. // }}}
  2003. // {{{ function failNestedTransaction($error = null, $immediately = false)
  2004. /**
  2005. * Force setting nested transaction to failed.
  2006. *
  2007. * @param mixed value to return in getNestededTransactionError()
  2008. * @param bool if the transaction should be rolled back immediately
  2009. * @return bool MDB2_OK
  2010. *
  2011. * @access public
  2012. * @since 2.1.1
  2013. */
  2014. function failNestedTransaction($error = null, $immediately = false)
  2015. {
  2016. if (null !== $error) {
  2017. $error = $this->has_transaction_error ? $this->has_transaction_error : true;
  2018. } elseif (!$error) {
  2019. $error = true;
  2020. }
  2021. $this->has_transaction_error = $error;
  2022. if (!$immediately) {
  2023. return MDB2_OK;
  2024. }
  2025. return $this->rollback();
  2026. }
  2027. // }}}
  2028. // {{{ function getNestedTransactionError()
  2029. /**
  2030. * The first error that occured since the transaction start.
  2031. *
  2032. * @return MDB2_Error|bool MDB2 error object if an error occured or false.
  2033. *
  2034. * @access public
  2035. * @since 2.1.1
  2036. */
  2037. function getNestedTransactionError()
  2038. {
  2039. return $this->has_transaction_error;
  2040. }
  2041. // }}}
  2042. // {{{ connect()
  2043. /**
  2044. * Connect to the database
  2045. *
  2046. * @return true on success, MDB2 Error Object on failure
  2047. */
  2048. function connect()
  2049. {
  2050. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2051. 'method not implemented', __FUNCTION__);
  2052. }
  2053. // }}}
  2054. // {{{ databaseExists()
  2055. /**
  2056. * check if given database name is exists?
  2057. *
  2058. * @param string $name name of the database that should be checked
  2059. *
  2060. * @return mixed true/false on success, a MDB2 error on failure
  2061. * @access public
  2062. */
  2063. function databaseExists($name)
  2064. {
  2065. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2066. 'method not implemented', __FUNCTION__);
  2067. }
  2068. // }}}
  2069. // {{{ setCharset($charset, $connection = null)
  2070. /**
  2071. * Set the charset on the current connection
  2072. *
  2073. * @param string charset
  2074. * @param resource connection handle
  2075. *
  2076. * @return true on success, MDB2 Error Object on failure
  2077. */
  2078. function setCharset($charset, $connection = null)
  2079. {
  2080. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2081. 'method not implemented', __FUNCTION__);
  2082. }
  2083. // }}}
  2084. // {{{ function disconnect($force = true)
  2085. /**
  2086. * Log out and disconnect from the database.
  2087. *
  2088. * @param boolean $force whether the disconnect should be forced even if the
  2089. * connection is opened persistently
  2090. *
  2091. * @return mixed true on success, false if not connected and error object on error
  2092. *
  2093. * @access public
  2094. */
  2095. function disconnect($force = true)
  2096. {
  2097. $this->connection = 0;
  2098. $this->connected_dsn = array();
  2099. $this->connected_database_name = '';
  2100. $this->opened_persistent = null;
  2101. $this->connected_server_info = '';
  2102. $this->in_transaction = null;
  2103. $this->nested_transaction_counter = null;
  2104. return MDB2_OK;
  2105. }
  2106. // }}}
  2107. // {{{ function setDatabase($name)
  2108. /**
  2109. * Select a different database
  2110. *
  2111. * @param string name of the database that should be selected
  2112. *
  2113. * @return string name of the database previously connected to
  2114. *
  2115. * @access public
  2116. */
  2117. function setDatabase($name)
  2118. {
  2119. $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
  2120. $this->database_name = $name;
  2121. if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
  2122. $this->disconnect(false);
  2123. }
  2124. return $previous_database_name;
  2125. }
  2126. // }}}
  2127. // {{{ function getDatabase()
  2128. /**
  2129. * Get the current database
  2130. *
  2131. * @return string name of the database
  2132. *
  2133. * @access public
  2134. */
  2135. function getDatabase()
  2136. {
  2137. return $this->database_name;
  2138. }
  2139. // }}}
  2140. // {{{ function setDSN($dsn)
  2141. /**
  2142. * set the DSN
  2143. *
  2144. * @param mixed DSN string or array
  2145. *
  2146. * @return MDB2_OK
  2147. *
  2148. * @access public
  2149. */
  2150. function setDSN($dsn)
  2151. {
  2152. $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
  2153. $dsn = MDB2::parseDSN($dsn);
  2154. if (array_key_exists('database', $dsn)) {
  2155. $this->database_name = $dsn['database'];
  2156. unset($dsn['database']);
  2157. }
  2158. $this->dsn = array_merge($dsn_default, $dsn);
  2159. return $this->disconnect(false);
  2160. }
  2161. // }}}
  2162. // {{{ function getDSN($type = 'string', $hidepw = false)
  2163. /**
  2164. * return the DSN as a string
  2165. *
  2166. * @param string format to return ("array", "string")
  2167. * @param string string to hide the password with
  2168. *
  2169. * @return mixed DSN in the chosen type
  2170. *
  2171. * @access public
  2172. */
  2173. function getDSN($type = 'string', $hidepw = false)
  2174. {
  2175. $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
  2176. $dsn['phptype'] = $this->phptype;
  2177. $dsn['database'] = $this->database_name;
  2178. if ($hidepw) {
  2179. $dsn['password'] = $hidepw;
  2180. }
  2181. switch ($type) {
  2182. // expand to include all possible options
  2183. case 'string':
  2184. $dsn = $dsn['phptype'].
  2185. ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
  2186. '://'.$dsn['username'].':'.
  2187. $dsn['password'].'@'.$dsn['hostspec'].
  2188. ($dsn['port'] ? (':'.$dsn['port']) : '').
  2189. '/'.$dsn['database'];
  2190. break;
  2191. case 'array':
  2192. default:
  2193. break;
  2194. }
  2195. return $dsn;
  2196. }
  2197. // }}}
  2198. // {{{ _isNewLinkSet()
  2199. /**
  2200. * Check if the 'new_link' option is set
  2201. *
  2202. * @return boolean
  2203. *
  2204. * @access protected
  2205. */
  2206. function _isNewLinkSet()
  2207. {
  2208. return (isset($this->dsn['new_link'])
  2209. && ($this->dsn['new_link'] === true
  2210. || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
  2211. || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
  2212. )
  2213. );
  2214. }
  2215. // }}}
  2216. // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
  2217. /**
  2218. * execute a query as database administrator
  2219. *
  2220. * @param string the SQL query
  2221. * @param mixed array that contains the types of the columns in
  2222. * the result set
  2223. * @param bool if the query is a manipulation query
  2224. *
  2225. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2226. *
  2227. * @access public
  2228. */
  2229. function standaloneQuery($query, $types = null, $is_manip = false)
  2230. {
  2231. $offset = $this->offset;
  2232. $limit = $this->limit;
  2233. $this->offset = $this->limit = 0;
  2234. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  2235. $connection = $this->getConnection();
  2236. if (MDB2::isError($connection)) {
  2237. return $connection;
  2238. }
  2239. $result = $this->_doQuery($query, $is_manip, $connection, false);
  2240. if (MDB2::isError($result)) {
  2241. return $result;
  2242. }
  2243. if ($is_manip) {
  2244. $affected_rows = $this->_affectedRows($connection, $result);
  2245. return $affected_rows;
  2246. }
  2247. $result = $this->_wrapResult($result, $types, true, true, $limit, $offset);
  2248. return $result;
  2249. }
  2250. // }}}
  2251. // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
  2252. /**
  2253. * Changes a query string for various DBMS specific reasons
  2254. *
  2255. * @param string query to modify
  2256. * @param bool if it is a DML query
  2257. * @param int limit the number of rows
  2258. * @param int start reading from given offset
  2259. *
  2260. * @return string modified query
  2261. *
  2262. * @access protected
  2263. */
  2264. function _modifyQuery($query, $is_manip, $limit, $offset)
  2265. {
  2266. return $query;
  2267. }
  2268. // }}}
  2269. // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2270. /**
  2271. * Execute a query
  2272. * @param string query
  2273. * @param bool if the query is a manipulation query
  2274. * @param resource connection handle
  2275. * @param string database name
  2276. *
  2277. * @return result or error object
  2278. *
  2279. * @access protected
  2280. */
  2281. function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  2282. {
  2283. $this->last_query = $query;
  2284. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  2285. if ($result) {
  2286. if (MDB2::isError($result)) {
  2287. return $result;
  2288. }
  2289. $query = $result;
  2290. }
  2291. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2292. 'method not implemented', __FUNCTION__);
  2293. return $err;
  2294. }
  2295. // }}}
  2296. // {{{ function _affectedRows($connection, $result = null)
  2297. /**
  2298. * Returns the number of rows affected
  2299. *
  2300. * @param resource result handle
  2301. * @param resource connection handle
  2302. *
  2303. * @return mixed MDB2 Error Object or the number of rows affected
  2304. *
  2305. * @access private
  2306. */
  2307. function _affectedRows($connection, $result = null)
  2308. {
  2309. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2310. 'method not implemented', __FUNCTION__);
  2311. }
  2312. // }}}
  2313. // {{{ function &exec($query)
  2314. /**
  2315. * Execute a manipulation query to the database and return the number of affected rows
  2316. *
  2317. * @param string the SQL query
  2318. *
  2319. * @return mixed number of affected rows on success, a MDB2 error on failure
  2320. *
  2321. * @access public
  2322. */
  2323. function exec($query)
  2324. {
  2325. $offset = $this->offset;
  2326. $limit = $this->limit;
  2327. $this->offset = $this->limit = 0;
  2328. $query = $this->_modifyQuery($query, true, $limit, $offset);
  2329. $connection = $this->getConnection();
  2330. if (MDB2::isError($connection)) {
  2331. return $connection;
  2332. }
  2333. $result = $this->_doQuery($query, true, $connection, $this->database_name);
  2334. if (MDB2::isError($result)) {
  2335. return $result;
  2336. }
  2337. $affectedRows = $this->_affectedRows($connection, $result);
  2338. return $affectedRows;
  2339. }
  2340. // }}}
  2341. // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
  2342. /**
  2343. * Send a query to the database and return any results
  2344. *
  2345. * @param string the SQL query
  2346. * @param mixed array that contains the types of the columns in
  2347. * the result set
  2348. * @param mixed string which specifies which result class to use
  2349. * @param mixed string which specifies which class to wrap results in
  2350. *
  2351. * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
  2352. *
  2353. * @access public
  2354. */
  2355. function query($query, $types = null, $result_class = true, $result_wrap_class = true)
  2356. {
  2357. $offset = $this->offset;
  2358. $limit = $this->limit;
  2359. $this->offset = $this->limit = 0;
  2360. $query = $this->_modifyQuery($query, false, $limit, $offset);
  2361. $connection = $this->getConnection();
  2362. if (MDB2::isError($connection)) {
  2363. return $connection;
  2364. }
  2365. $result = $this->_doQuery($query, false, $connection, $this->database_name);
  2366. if (MDB2::isError($result)) {
  2367. return $result;
  2368. }
  2369. $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
  2370. return $result;
  2371. }
  2372. // }}}
  2373. // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
  2374. /**
  2375. * wrap a result set into the correct class
  2376. *
  2377. * @param resource result handle
  2378. * @param mixed array that contains the types of the columns in
  2379. * the result set
  2380. * @param mixed string which specifies which result class to use
  2381. * @param mixed string which specifies which class to wrap results in
  2382. * @param string number of rows to select
  2383. * @param string first row to select
  2384. *
  2385. * @return mixed an MDB2_Result, a MDB2 error on failure
  2386. *
  2387. * @access protected
  2388. */
  2389. function _wrapResult($result_resource, $types = array(), $result_class = true,
  2390. $result_wrap_class = true, $limit = null, $offset = null)
  2391. {
  2392. if ($types === true) {
  2393. if ($this->supports('result_introspection')) {
  2394. $this->loadModule('Reverse', null, true);
  2395. $tableInfo = $this->reverse->tableInfo($result_resource);
  2396. if (MDB2::isError($tableInfo)) {
  2397. return $tableInfo;
  2398. }
  2399. $types = array();
  2400. $types_assoc = array();
  2401. foreach ($tableInfo as $field) {
  2402. $types[] = $field['mdb2type'];
  2403. $types_assoc[$field['name']] = $field['mdb2type'];
  2404. }
  2405. } else {
  2406. $types = null;
  2407. }
  2408. }
  2409. if ($result_class === true) {
  2410. $result_class = $this->options['result_buffering']
  2411. ? $this->options['buffered_result_class'] : $this->options['result_class'];
  2412. }
  2413. if ($result_class) {
  2414. $class_name = sprintf($result_class, $this->phptype);
  2415. if (!MDB2::classExists($class_name)) {
  2416. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2417. 'result class does not exist '.$class_name, __FUNCTION__);
  2418. return $err;
  2419. }
  2420. $result = new $class_name($this, $result_resource, $limit, $offset);
  2421. if (!MDB2::isResultCommon($result)) {
  2422. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2423. 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
  2424. return $err;
  2425. }
  2426. if (!empty($types)) {
  2427. $err = $result->setResultTypes($types);
  2428. if (MDB2::isError($err)) {
  2429. $result->free();
  2430. return $err;
  2431. }
  2432. }
  2433. if (!empty($types_assoc)) {
  2434. $err = $result->setResultTypes($types_assoc);
  2435. if (MDB2::isError($err)) {
  2436. $result->free();
  2437. return $err;
  2438. }
  2439. }
  2440. if ($result_wrap_class === true) {
  2441. $result_wrap_class = $this->options['result_wrap_class'];
  2442. }
  2443. if ($result_wrap_class) {
  2444. if (!MDB2::classExists($result_wrap_class)) {
  2445. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  2446. 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
  2447. return $err;
  2448. }
  2449. $result = new $result_wrap_class($result, $this->fetchmode);
  2450. }
  2451. return $result;
  2452. }
  2453. return $result_resource;
  2454. }
  2455. // }}}
  2456. // {{{ function getServerVersion($native = false)
  2457. /**
  2458. * return version information about the server
  2459. *
  2460. * @param bool determines if the raw version string should be returned
  2461. *
  2462. * @return mixed array with version information or row string
  2463. *
  2464. * @access public
  2465. */
  2466. function getServerVersion($native = false)
  2467. {
  2468. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2469. 'method not implemented', __FUNCTION__);
  2470. }
  2471. // }}}
  2472. // {{{ function setLimit($limit, $offset = null)
  2473. /**
  2474. * set the range of the next query
  2475. *
  2476. * @param string number of rows to select
  2477. * @param string first row to select
  2478. *
  2479. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2480. *
  2481. * @access public
  2482. */
  2483. function setLimit($limit, $offset = null)
  2484. {
  2485. if (!$this->supports('limit_queries')) {
  2486. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2487. 'limit is not supported by this driver', __FUNCTION__);
  2488. }
  2489. $limit = (int)$limit;
  2490. if ($limit < 0) {
  2491. return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2492. 'it was not specified a valid selected range row limit', __FUNCTION__);
  2493. }
  2494. $this->limit = $limit;
  2495. if (null !== $offset) {
  2496. $offset = (int)$offset;
  2497. if ($offset < 0) {
  2498. return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2499. 'it was not specified a valid first selected range row', __FUNCTION__);
  2500. }
  2501. $this->offset = $offset;
  2502. }
  2503. return MDB2_OK;
  2504. }
  2505. // }}}
  2506. // {{{ function subSelect($query, $type = false)
  2507. /**
  2508. * simple subselect emulation: leaves the query untouched for all RDBMS
  2509. * that support subselects
  2510. *
  2511. * @param string the SQL query for the subselect that may only
  2512. * return a column
  2513. * @param string determines type of the field
  2514. *
  2515. * @return string the query
  2516. *
  2517. * @access public
  2518. */
  2519. function subSelect($query, $type = false)
  2520. {
  2521. if ($this->supports('sub_selects') === true) {
  2522. return $query;
  2523. }
  2524. if (!$this->supports('sub_selects')) {
  2525. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2526. 'method not implemented', __FUNCTION__);
  2527. }
  2528. $col = $this->queryCol($query, $type);
  2529. if (MDB2::isError($col)) {
  2530. return $col;
  2531. }
  2532. if (!is_array($col) || count($col) == 0) {
  2533. return 'NULL';
  2534. }
  2535. if ($type) {
  2536. $this->loadModule('Datatype', null, true);
  2537. return $this->datatype->implodeArray($col, $type);
  2538. }
  2539. return implode(', ', $col);
  2540. }
  2541. // }}}
  2542. // {{{ function replace($table, $fields)
  2543. /**
  2544. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  2545. * query, except that if there is already a row in the table with the same
  2546. * key field values, the old row is deleted before the new row is inserted.
  2547. *
  2548. * The REPLACE type of query does not make part of the SQL standards. Since
  2549. * practically only MySQL and SQLite implement it natively, this type of
  2550. * query isemulated through this method for other DBMS using standard types
  2551. * of queries inside a transaction to assure the atomicity of the operation.
  2552. *
  2553. * @param string name of the table on which the REPLACE query will
  2554. * be executed.
  2555. * @param array associative array that describes the fields and the
  2556. * values that will be inserted or updated in the specified table. The
  2557. * indexes of the array are the names of all the fields of the table.
  2558. * The values of the array are also associative arrays that describe
  2559. * the values and other properties of the table fields.
  2560. *
  2561. * Here follows a list of field properties that need to be specified:
  2562. *
  2563. * value
  2564. * Value to be assigned to the specified field. This value may be
  2565. * of specified in database independent type format as this
  2566. * function can perform the necessary datatype conversions.
  2567. *
  2568. * Default: this property is required unless the Null property is
  2569. * set to 1.
  2570. *
  2571. * type
  2572. * Name of the type of the field. Currently, all types MDB2
  2573. * are supported except for clob and blob.
  2574. *
  2575. * Default: no type conversion
  2576. *
  2577. * null
  2578. * bool property that indicates that the value for this field
  2579. * should be set to null.
  2580. *
  2581. * The default value for fields missing in INSERT queries may be
  2582. * specified the definition of a table. Often, the default value
  2583. * is already null, but since the REPLACE may be emulated using
  2584. * an UPDATE query, make sure that all fields of the table are
  2585. * listed in this function argument array.
  2586. *
  2587. * Default: 0
  2588. *
  2589. * key
  2590. * bool property that indicates that this field should be
  2591. * handled as a primary key or at least as part of the compound
  2592. * unique index of the table that will determine the row that will
  2593. * updated if it exists or inserted a new row otherwise.
  2594. *
  2595. * This function will fail if no key field is specified or if the
  2596. * value of a key field is set to null because fields that are
  2597. * part of unique index they may not be null.
  2598. *
  2599. * Default: 0
  2600. *
  2601. * @return mixed MDB2_OK on success, a MDB2 error on failure
  2602. *
  2603. * @access public
  2604. */
  2605. function replace($table, $fields)
  2606. {
  2607. if (!$this->supports('replace')) {
  2608. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2609. 'replace query is not supported', __FUNCTION__);
  2610. }
  2611. $count = count($fields);
  2612. $condition = $values = array();
  2613. for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
  2614. $name = key($fields);
  2615. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  2616. $value = 'NULL';
  2617. } else {
  2618. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  2619. $value = $this->quote($fields[$name]['value'], $type);
  2620. }
  2621. $values[$name] = $value;
  2622. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  2623. if ($value === 'NULL') {
  2624. return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2625. 'key value '.$name.' may not be NULL', __FUNCTION__);
  2626. }
  2627. $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
  2628. }
  2629. }
  2630. if (empty($condition)) {
  2631. return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  2632. 'not specified which fields are keys', __FUNCTION__);
  2633. }
  2634. $result = null;
  2635. $in_transaction = $this->in_transaction;
  2636. if (!$in_transaction && MDB2::isError($result = $this->beginTransaction())) {
  2637. return $result;
  2638. }
  2639. $connection = $this->getConnection();
  2640. if (MDB2::isError($connection)) {
  2641. return $connection;
  2642. }
  2643. $condition = ' WHERE '.implode(' AND ', $condition);
  2644. $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
  2645. $result = $this->_doQuery($query, true, $connection);
  2646. if (!MDB2::isError($result)) {
  2647. $affected_rows = $this->_affectedRows($connection, $result);
  2648. $insert = '';
  2649. foreach ($values as $key => $value) {
  2650. $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
  2651. }
  2652. $values = implode(', ', $values);
  2653. $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
  2654. $result = $this->_doQuery($query, true, $connection);
  2655. if (!MDB2::isError($result)) {
  2656. $affected_rows += $this->_affectedRows($connection, $result);;
  2657. }
  2658. }
  2659. if (!$in_transaction) {
  2660. if (MDB2::isError($result)) {
  2661. $this->rollback();
  2662. } else {
  2663. $result = $this->commit();
  2664. }
  2665. }
  2666. if (MDB2::isError($result)) {
  2667. return $result;
  2668. }
  2669. return $affected_rows;
  2670. }
  2671. // }}}
  2672. // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
  2673. /**
  2674. * Prepares a query for multiple execution with execute().
  2675. * With some database backends, this is emulated.
  2676. * prepare() requires a generic query as string like
  2677. * 'INSERT INTO numbers VALUES(?,?)' or
  2678. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  2679. * The ? and :name and are placeholders which can be set using
  2680. * bindParam() and the query can be sent off using the execute() method.
  2681. * The allowed format for :name can be set with the 'bindname_format' option.
  2682. *
  2683. * @param string the query to prepare
  2684. * @param mixed array that contains the types of the placeholders
  2685. * @param mixed array that contains the types of the columns in
  2686. * the result set or MDB2_PREPARE_RESULT, if set to
  2687. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  2688. * @param mixed key (field) value (parameter) pair for all lob placeholders
  2689. *
  2690. * @return mixed resource handle for the prepared query on success,
  2691. * a MDB2 error on failure
  2692. *
  2693. * @access public
  2694. * @see bindParam, execute
  2695. */
  2696. function prepare($query, $types = null, $result_types = null, $lobs = array())
  2697. {
  2698. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  2699. $offset = $this->offset;
  2700. $limit = $this->limit;
  2701. $this->offset = $this->limit = 0;
  2702. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  2703. if ($result) {
  2704. if (MDB2::isError($result)) {
  2705. return $result;
  2706. }
  2707. $query = $result;
  2708. }
  2709. $placeholder_type_guess = $placeholder_type = null;
  2710. $question = '?';
  2711. $colon = ':';
  2712. $positions = array();
  2713. $position = 0;
  2714. while ($position < strlen($query)) {
  2715. $q_position = strpos($query, $question, $position);
  2716. $c_position = strpos($query, $colon, $position);
  2717. if ($q_position && $c_position) {
  2718. $p_position = min($q_position, $c_position);
  2719. } elseif ($q_position) {
  2720. $p_position = $q_position;
  2721. } elseif ($c_position) {
  2722. $p_position = $c_position;
  2723. } else {
  2724. break;
  2725. }
  2726. if (null === $placeholder_type) {
  2727. $placeholder_type_guess = $query[$p_position];
  2728. }
  2729. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  2730. if (MDB2::isError($new_pos)) {
  2731. return $new_pos;
  2732. }
  2733. if ($new_pos != $position) {
  2734. $position = $new_pos;
  2735. continue; //evaluate again starting from the new position
  2736. }
  2737. if ($query[$position] == $placeholder_type_guess) {
  2738. if (null === $placeholder_type) {
  2739. $placeholder_type = $query[$p_position];
  2740. $question = $colon = $placeholder_type;
  2741. if (!empty($types) && is_array($types)) {
  2742. if ($placeholder_type == ':') {
  2743. if (is_int(key($types))) {
  2744. $types_tmp = $types;
  2745. $types = array();
  2746. $count = -1;
  2747. }
  2748. } else {
  2749. $types = array_values($types);
  2750. }
  2751. }
  2752. }
  2753. if ($placeholder_type == ':') {
  2754. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  2755. $parameter = preg_replace($regexp, '\\1', $query);
  2756. if ($parameter === '') {
  2757. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2758. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  2759. return $err;
  2760. }
  2761. $positions[$p_position] = $parameter;
  2762. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  2763. // use parameter name in type array
  2764. if (isset($count) && isset($types_tmp[++$count])) {
  2765. $types[$parameter] = $types_tmp[$count];
  2766. }
  2767. } else {
  2768. $positions[$p_position] = count($positions);
  2769. }
  2770. $position = $p_position + 1;
  2771. } else {
  2772. $position = $p_position;
  2773. }
  2774. }
  2775. $class_name = 'MDB2_Statement_'.$this->phptype;
  2776. $statement = null;
  2777. $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  2778. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  2779. return $obj;
  2780. }
  2781. // }}}
  2782. // {{{ function _skipDelimitedStrings($query, $position, $p_position)
  2783. /**
  2784. * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
  2785. * Check if the placeholder is contained within a delimited string.
  2786. * If so, skip it and advance the position, otherwise return the current position,
  2787. * which is valid
  2788. *
  2789. * @param string $query
  2790. * @param integer $position current string cursor position
  2791. * @param integer $p_position placeholder position
  2792. *
  2793. * @return mixed integer $new_position on success
  2794. * MDB2_Error on failure
  2795. *
  2796. * @access protected
  2797. */
  2798. function _skipDelimitedStrings($query, $position, $p_position)
  2799. {
  2800. $ignores = array();
  2801. $ignores[] = $this->string_quoting;
  2802. $ignores[] = $this->identifier_quoting;
  2803. $ignores = array_merge($ignores, $this->sql_comments);
  2804. foreach ($ignores as $ignore) {
  2805. if (!empty($ignore['start'])) {
  2806. if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
  2807. $end_quote = $start_quote;
  2808. do {
  2809. if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
  2810. if ($ignore['end'] === "\n") {
  2811. $end_quote = strlen($query) - 1;
  2812. } else {
  2813. $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
  2814. 'query with an unterminated text string specified', __FUNCTION__);
  2815. return $err;
  2816. }
  2817. }
  2818. } while ($ignore['escape']
  2819. && $end_quote-1 != $start_quote
  2820. && $query[($end_quote - 1)] == $ignore['escape']
  2821. && ( $ignore['escape_pattern'] !== $ignore['escape']
  2822. || $query[($end_quote - 2)] != $ignore['escape'])
  2823. );
  2824. $position = $end_quote + 1;
  2825. return $position;
  2826. }
  2827. }
  2828. }
  2829. return $position;
  2830. }
  2831. // }}}
  2832. // {{{ function quote($value, $type = null, $quote = true)
  2833. /**
  2834. * Convert a text value into a DBMS specific format that is suitable to
  2835. * compose query statements.
  2836. *
  2837. * @param string text string value that is intended to be converted.
  2838. * @param string type to which the value should be converted to
  2839. * @param bool quote
  2840. * @param bool escape wildcards
  2841. *
  2842. * @return string text string that represents the given argument value in
  2843. * a DBMS specific format.
  2844. *
  2845. * @access public
  2846. */
  2847. function quote($value, $type = null, $quote = true, $escape_wildcards = false)
  2848. {
  2849. $result = $this->loadModule('Datatype', null, true);
  2850. if (MDB2::isError($result)) {
  2851. return $result;
  2852. }
  2853. return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
  2854. }
  2855. // }}}
  2856. // {{{ function getDeclaration($type, $name, $field)
  2857. /**
  2858. * Obtain DBMS specific SQL code portion needed to declare
  2859. * of the given type
  2860. *
  2861. * @param string type to which the value should be converted to
  2862. * @param string name the field to be declared.
  2863. * @param string definition of the field
  2864. *
  2865. * @return string DBMS specific SQL code portion that should be used to
  2866. * declare the specified field.
  2867. *
  2868. * @access public
  2869. */
  2870. function getDeclaration($type, $name, $field)
  2871. {
  2872. $result = $this->loadModule('Datatype', null, true);
  2873. if (MDB2::isError($result)) {
  2874. return $result;
  2875. }
  2876. return $this->datatype->getDeclaration($type, $name, $field);
  2877. }
  2878. // }}}
  2879. // {{{ function compareDefinition($current, $previous)
  2880. /**
  2881. * Obtain an array of changes that may need to applied
  2882. *
  2883. * @param array new definition
  2884. * @param array old definition
  2885. *
  2886. * @return array containing all changes that will need to be applied
  2887. *
  2888. * @access public
  2889. */
  2890. function compareDefinition($current, $previous)
  2891. {
  2892. $result = $this->loadModule('Datatype', null, true);
  2893. if (MDB2::isError($result)) {
  2894. return $result;
  2895. }
  2896. return $this->datatype->compareDefinition($current, $previous);
  2897. }
  2898. // }}}
  2899. // {{{ function supports($feature)
  2900. /**
  2901. * Tell whether a DB implementation or its backend extension
  2902. * supports a given feature.
  2903. *
  2904. * @param string name of the feature (see the MDB2 class doc)
  2905. *
  2906. * @return bool|string if this DB implementation supports a given feature
  2907. * false means no, true means native,
  2908. * 'emulated' means emulated
  2909. *
  2910. * @access public
  2911. */
  2912. function supports($feature)
  2913. {
  2914. if (array_key_exists($feature, $this->supported)) {
  2915. return $this->supported[$feature];
  2916. }
  2917. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2918. "unknown support feature $feature", __FUNCTION__);
  2919. }
  2920. // }}}
  2921. // {{{ function getSequenceName($sqn)
  2922. /**
  2923. * adds sequence name formatting to a sequence name
  2924. *
  2925. * @param string name of the sequence
  2926. *
  2927. * @return string formatted sequence name
  2928. *
  2929. * @access public
  2930. */
  2931. function getSequenceName($sqn)
  2932. {
  2933. return sprintf($this->options['seqname_format'],
  2934. preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
  2935. }
  2936. // }}}
  2937. // {{{ function getIndexName($idx)
  2938. /**
  2939. * adds index name formatting to a index name
  2940. *
  2941. * @param string name of the index
  2942. *
  2943. * @return string formatted index name
  2944. *
  2945. * @access public
  2946. */
  2947. function getIndexName($idx)
  2948. {
  2949. return sprintf($this->options['idxname_format'],
  2950. preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
  2951. }
  2952. // }}}
  2953. // {{{ function nextID($seq_name, $ondemand = true)
  2954. /**
  2955. * Returns the next free id of a sequence
  2956. *
  2957. * @param string name of the sequence
  2958. * @param bool when true missing sequences are automatic created
  2959. *
  2960. * @return mixed MDB2 Error Object or id
  2961. *
  2962. * @access public
  2963. */
  2964. function nextID($seq_name, $ondemand = true)
  2965. {
  2966. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2967. 'method not implemented', __FUNCTION__);
  2968. }
  2969. // }}}
  2970. // {{{ function lastInsertID($table = null, $field = null)
  2971. /**
  2972. * Returns the autoincrement ID if supported or $id or fetches the current
  2973. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  2974. *
  2975. * @param string name of the table into which a new row was inserted
  2976. * @param string name of the field into which a new row was inserted
  2977. *
  2978. * @return mixed MDB2 Error Object or id
  2979. *
  2980. * @access public
  2981. */
  2982. function lastInsertID($table = null, $field = null)
  2983. {
  2984. return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  2985. 'method not implemented', __FUNCTION__);
  2986. }
  2987. // }}}
  2988. // {{{ function currID($seq_name)
  2989. /**
  2990. * Returns the current id of a sequence
  2991. *
  2992. * @param string name of the sequence
  2993. *
  2994. * @return mixed MDB2 Error Object or id
  2995. *
  2996. * @access public
  2997. */
  2998. function currID($seq_name)
  2999. {
  3000. $this->warnings[] = 'database does not support getting current
  3001. sequence value, the sequence value was incremented';
  3002. return $this->nextID($seq_name);
  3003. }
  3004. // }}}
  3005. // {{{ function queryOne($query, $type = null, $colnum = 0)
  3006. /**
  3007. * Execute the specified query, fetch the value from the first column of
  3008. * the first row of the result set and then frees
  3009. * the result set.
  3010. *
  3011. * @param string $query the SELECT query statement to be executed.
  3012. * @param string $type optional argument that specifies the expected
  3013. * datatype of the result set field, so that an eventual
  3014. * conversion may be performed. The default datatype is
  3015. * text, meaning that no conversion is performed
  3016. * @param mixed $colnum the column number (or name) to fetch
  3017. *
  3018. * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
  3019. *
  3020. * @access public
  3021. */
  3022. function queryOne($query, $type = null, $colnum = 0)
  3023. {
  3024. $result = $this->query($query, $type);
  3025. if (!MDB2::isResultCommon($result)) {
  3026. return $result;
  3027. }
  3028. $one = $result->fetchOne($colnum);
  3029. $result->free();
  3030. return $one;
  3031. }
  3032. // }}}
  3033. // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  3034. /**
  3035. * Execute the specified query, fetch the values from the first
  3036. * row of the result set into an array and then frees
  3037. * the result set.
  3038. *
  3039. * @param string the SELECT query statement to be executed.
  3040. * @param array optional array argument that specifies a list of
  3041. * expected datatypes of the result set columns, so that the eventual
  3042. * conversions may be performed. The default list of datatypes is
  3043. * empty, meaning that no conversion is performed.
  3044. * @param int how the array data should be indexed
  3045. *
  3046. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3047. *
  3048. * @access public
  3049. */
  3050. function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
  3051. {
  3052. $result = $this->query($query, $types);
  3053. if (!MDB2::isResultCommon($result)) {
  3054. return $result;
  3055. }
  3056. $row = $result->fetchRow($fetchmode);
  3057. $result->free();
  3058. return $row;
  3059. }
  3060. // }}}
  3061. // {{{ function queryCol($query, $type = null, $colnum = 0)
  3062. /**
  3063. * Execute the specified query, fetch the value from the first column of
  3064. * each row of the result set into an array and then frees the result set.
  3065. *
  3066. * @param string $query the SELECT query statement to be executed.
  3067. * @param string $type optional argument that specifies the expected
  3068. * datatype of the result set field, so that an eventual
  3069. * conversion may be performed. The default datatype is text,
  3070. * meaning that no conversion is performed
  3071. * @param mixed $colnum the column number (or name) to fetch
  3072. *
  3073. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3074. * @access public
  3075. */
  3076. function queryCol($query, $type = null, $colnum = 0)
  3077. {
  3078. $result = $this->query($query, $type);
  3079. if (!MDB2::isResultCommon($result)) {
  3080. return $result;
  3081. }
  3082. $col = $result->fetchCol($colnum);
  3083. $result->free();
  3084. return $col;
  3085. }
  3086. // }}}
  3087. // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  3088. /**
  3089. * Execute the specified query, fetch all the rows of the result set into
  3090. * a two dimensional array and then frees the result set.
  3091. *
  3092. * @param string the SELECT query statement to be executed.
  3093. * @param array optional array argument that specifies a list of
  3094. * expected datatypes of the result set columns, so that the eventual
  3095. * conversions may be performed. The default list of datatypes is
  3096. * empty, meaning that no conversion is performed.
  3097. * @param int how the array data should be indexed
  3098. * @param bool if set to true, the $all will have the first
  3099. * column as its first dimension
  3100. * @param bool used only when the query returns exactly
  3101. * two columns. If true, the values of the returned array will be
  3102. * one-element arrays instead of scalars.
  3103. * @param bool if true, the values of the returned array is
  3104. * wrapped in another array. If the same key value (in the first
  3105. * column) repeats itself, the values will be appended to this array
  3106. * instead of overwriting the existing values.
  3107. *
  3108. * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
  3109. *
  3110. * @access public
  3111. */
  3112. function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
  3113. $rekey = false, $force_array = false, $group = false)
  3114. {
  3115. $result = $this->query($query, $types);
  3116. if (!MDB2::isResultCommon($result)) {
  3117. return $result;
  3118. }
  3119. $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
  3120. $result->free();
  3121. return $all;
  3122. }
  3123. // }}}
  3124. // {{{ function delExpect($error_code)
  3125. /**
  3126. * This method deletes all occurences of the specified element from
  3127. * the expected error codes stack.
  3128. *
  3129. * @param mixed $error_code error code that should be deleted
  3130. * @return mixed list of error codes that were deleted or error
  3131. *
  3132. * @uses PEAR::delExpect()
  3133. */
  3134. public function delExpect($error_code)
  3135. {
  3136. return $this->pear->delExpect($error_code);
  3137. }
  3138. // }}}
  3139. // {{{ function expectError($code)
  3140. /**
  3141. * This method is used to tell which errors you expect to get.
  3142. * Expected errors are always returned with error mode
  3143. * PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
  3144. * and this method pushes a new element onto it. The list of
  3145. * expected errors are in effect until they are popped off the
  3146. * stack with the popExpect() method.
  3147. *
  3148. * Note that this method can not be called statically
  3149. *
  3150. * @param mixed $code a single error code or an array of error codes to expect
  3151. *
  3152. * @return int the new depth of the "expected errors" stack
  3153. *
  3154. * @uses PEAR::expectError()
  3155. */
  3156. public function expectError($code = '*')
  3157. {
  3158. return $this->pear->expectError($code);
  3159. }
  3160. // }}}
  3161. // {{{ function getStaticProperty($class, $var)
  3162. /**
  3163. * If you have a class that's mostly/entirely static, and you need static
  3164. * properties, you can use this method to simulate them. Eg. in your method(s)
  3165. * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
  3166. * You MUST use a reference, or they will not persist!
  3167. *
  3168. * @param string $class The calling classname, to prevent clashes
  3169. * @param string $var The variable to retrieve.
  3170. * @return mixed A reference to the variable. If not set it will be
  3171. * auto initialised to NULL.
  3172. *
  3173. * @uses PEAR::getStaticProperty()
  3174. */
  3175. public function &getStaticProperty($class, $var)
  3176. {
  3177. $tmp =& $this->pear->getStaticProperty($class, $var);
  3178. return $tmp;
  3179. }
  3180. // }}}
  3181. // {{{ function popErrorHandling()
  3182. /**
  3183. * Pop the last error handler used
  3184. *
  3185. * @return bool Always true
  3186. *
  3187. * @see PEAR::pushErrorHandling
  3188. * @uses PEAR::popErrorHandling()
  3189. */
  3190. public function popErrorHandling()
  3191. {
  3192. return $this->pear->popErrorHandling();
  3193. }
  3194. // }}}
  3195. // {{{ function popExpect()
  3196. /**
  3197. * This method pops one element off the expected error codes
  3198. * stack.
  3199. *
  3200. * @return array the list of error codes that were popped
  3201. *
  3202. * @uses PEAR::popExpect()
  3203. */
  3204. public function popExpect()
  3205. {
  3206. return $this->pear->popExpect();
  3207. }
  3208. // }}}
  3209. // {{{ function pushErrorHandling($mode, $options = null)
  3210. /**
  3211. * Push a new error handler on top of the error handler options stack. With this
  3212. * you can easily override the actual error handler for some code and restore
  3213. * it later with popErrorHandling.
  3214. *
  3215. * @param mixed $mode (same as setErrorHandling)
  3216. * @param mixed $options (same as setErrorHandling)
  3217. *
  3218. * @return bool Always true
  3219. *
  3220. * @see PEAR::setErrorHandling
  3221. * @uses PEAR::pushErrorHandling()
  3222. */
  3223. public function pushErrorHandling($mode, $options = null)
  3224. {
  3225. return $this->pear->pushErrorHandling($mode, $options);
  3226. }
  3227. // }}}
  3228. // {{{ function registerShutdownFunc($func, $args = array())
  3229. /**
  3230. * Use this function to register a shutdown method for static
  3231. * classes.
  3232. *
  3233. * @param mixed $func The function name (or array of class/method) to call
  3234. * @param mixed $args The arguments to pass to the function
  3235. * @return void
  3236. *
  3237. * @uses PEAR::registerShutdownFunc()
  3238. */
  3239. public function registerShutdownFunc($func, $args = array())
  3240. {
  3241. return $this->pear->registerShutdownFunc($func, $args);
  3242. }
  3243. // }}}
  3244. // {{{ function setErrorHandling($mode = null, $options = null)
  3245. /**
  3246. * Sets how errors generated by this object should be handled.
  3247. * Can be invoked both in objects and statically. If called
  3248. * statically, setErrorHandling sets the default behaviour for all
  3249. * PEAR objects. If called in an object, setErrorHandling sets
  3250. * the default behaviour for that object.
  3251. *
  3252. * @param int $mode
  3253. * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
  3254. * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
  3255. * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
  3256. *
  3257. * @param mixed $options
  3258. * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
  3259. * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
  3260. *
  3261. * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
  3262. * to be the callback function or method. A callback
  3263. * function is a string with the name of the function, a
  3264. * callback method is an array of two elements: the element
  3265. * at index 0 is the object, and the element at index 1 is
  3266. * the name of the method to call in the object.
  3267. *
  3268. * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
  3269. * a printf format string used when printing the error
  3270. * message.
  3271. *
  3272. * @access public
  3273. * @return void
  3274. * @see PEAR_ERROR_RETURN
  3275. * @see PEAR_ERROR_PRINT
  3276. * @see PEAR_ERROR_TRIGGER
  3277. * @see PEAR_ERROR_DIE
  3278. * @see PEAR_ERROR_CALLBACK
  3279. * @see PEAR_ERROR_EXCEPTION
  3280. *
  3281. * @since PHP 4.0.5
  3282. * @uses PEAR::setErrorHandling($mode, $options)
  3283. */
  3284. public function setErrorHandling($mode = null, $options = null)
  3285. {
  3286. return $this->pear->setErrorHandling($mode, $options);
  3287. }
  3288. /**
  3289. * @uses PEAR::staticPopErrorHandling()
  3290. */
  3291. public function staticPopErrorHandling()
  3292. {
  3293. return $this->pear->staticPopErrorHandling();
  3294. }
  3295. // }}}
  3296. // {{{ function staticPushErrorHandling($mode, $options = null)
  3297. /**
  3298. * @uses PEAR::staticPushErrorHandling($mode, $options)
  3299. */
  3300. public function staticPushErrorHandling($mode, $options = null)
  3301. {
  3302. return $this->pear->staticPushErrorHandling($mode, $options);
  3303. }
  3304. // }}}
  3305. // {{{ function &throwError($message = null, $code = null, $userinfo = null)
  3306. /**
  3307. * Simpler form of raiseError with fewer options. In most cases
  3308. * message, code and userinfo are enough.
  3309. *
  3310. * @param mixed $message a text error message or a PEAR error object
  3311. *
  3312. * @param int $code a numeric error code (it is up to your class
  3313. * to define these if you want to use codes)
  3314. *
  3315. * @param string $userinfo If you need to pass along for example debug
  3316. * information, this parameter is meant for that.
  3317. *
  3318. * @return object a PEAR error object
  3319. * @see PEAR::raiseError
  3320. * @uses PEAR::&throwError()
  3321. */
  3322. public function &throwError($message = null, $code = null, $userinfo = null)
  3323. {
  3324. $tmp =& $this->pear->throwError($message, $code, $userinfo);
  3325. return $tmp;
  3326. }
  3327. // }}}
  3328. }
  3329. // }}}
  3330. // {{{ class MDB2_Result
  3331. /**
  3332. * The dummy class that all user space result classes should extend from
  3333. *
  3334. * @package MDB2
  3335. * @category Database
  3336. * @author Lukas Smith <smith@pooteeweet.org>
  3337. */
  3338. class MDB2_Result
  3339. {
  3340. }
  3341. // }}}
  3342. // {{{ class MDB2_Result_Common extends MDB2_Result
  3343. /**
  3344. * The common result class for MDB2 result objects
  3345. *
  3346. * @package MDB2
  3347. * @category Database
  3348. * @author Lukas Smith <smith@pooteeweet.org>
  3349. */
  3350. class MDB2_Result_Common extends MDB2_Result
  3351. {
  3352. // {{{ Variables (Properties)
  3353. public $db;
  3354. public $result;
  3355. public $rownum = -1;
  3356. public $types = array();
  3357. public $types_assoc = array();
  3358. public $values = array();
  3359. public $offset;
  3360. public $offset_count = 0;
  3361. public $limit;
  3362. public $column_names;
  3363. // }}}
  3364. // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)
  3365. /**
  3366. * Constructor
  3367. */
  3368. function __construct($db, &$result, $limit = 0, $offset = 0)
  3369. {
  3370. $this->db = $db;
  3371. $this->result = $result;
  3372. $this->offset = $offset;
  3373. $this->limit = max(0, $limit - 1);
  3374. }
  3375. // }}}
  3376. // {{{ function setResultTypes($types)
  3377. /**
  3378. * Define the list of types to be associated with the columns of a given
  3379. * result set.
  3380. *
  3381. * This function may be called before invoking fetchRow(), fetchOne(),
  3382. * fetchCol() and fetchAll() so that the necessary data type
  3383. * conversions are performed on the data to be retrieved by them. If this
  3384. * function is not called, the type of all result set columns is assumed
  3385. * to be text, thus leading to not perform any conversions.
  3386. *
  3387. * @param array variable that lists the
  3388. * data types to be expected in the result set columns. If this array
  3389. * contains less types than the number of columns that are returned
  3390. * in the result set, the remaining columns are assumed to be of the
  3391. * type text. Currently, the types clob and blob are not fully
  3392. * supported.
  3393. *
  3394. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3395. *
  3396. * @access public
  3397. */
  3398. function setResultTypes($types)
  3399. {
  3400. $load = $this->db->loadModule('Datatype', null, true);
  3401. if (MDB2::isError($load)) {
  3402. return $load;
  3403. }
  3404. $types = $this->db->datatype->checkResultTypes($types);
  3405. if (MDB2::isError($types)) {
  3406. return $types;
  3407. }
  3408. foreach ($types as $key => $value) {
  3409. if (is_numeric($key)) {
  3410. $this->types[$key] = $value;
  3411. } else {
  3412. $this->types_assoc[$key] = $value;
  3413. }
  3414. }
  3415. return MDB2_OK;
  3416. }
  3417. // }}}
  3418. // {{{ function seek($rownum = 0)
  3419. /**
  3420. * Seek to a specific row in a result set
  3421. *
  3422. * @param int number of the row where the data can be found
  3423. *
  3424. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3425. *
  3426. * @access public
  3427. */
  3428. function seek($rownum = 0)
  3429. {
  3430. $target_rownum = $rownum - 1;
  3431. if ($this->rownum > $target_rownum) {
  3432. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3433. 'seeking to previous rows not implemented', __FUNCTION__);
  3434. }
  3435. while ($this->rownum < $target_rownum) {
  3436. $this->fetchRow();
  3437. }
  3438. return MDB2_OK;
  3439. }
  3440. // }}}
  3441. // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3442. /**
  3443. * Fetch and return a row of data
  3444. *
  3445. * @param int how the array data should be indexed
  3446. * @param int number of the row where the data can be found
  3447. *
  3448. * @return int data array on success, a MDB2 error on failure
  3449. *
  3450. * @access public
  3451. */
  3452. function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  3453. {
  3454. $err = MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3455. 'method not implemented', __FUNCTION__);
  3456. return $err;
  3457. }
  3458. // }}}
  3459. // {{{ function fetchOne($colnum = 0)
  3460. /**
  3461. * fetch single column from the next row from a result set
  3462. *
  3463. * @param int|string the column number (or name) to fetch
  3464. * @param int number of the row where the data can be found
  3465. *
  3466. * @return string data on success, a MDB2 error on failure
  3467. * @access public
  3468. */
  3469. function fetchOne($colnum = 0, $rownum = null)
  3470. {
  3471. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3472. $row = $this->fetchRow($fetchmode, $rownum);
  3473. if (!is_array($row) || MDB2::isError($row)) {
  3474. return $row;
  3475. }
  3476. if (!array_key_exists($colnum, $row)) {
  3477. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3478. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3479. }
  3480. return $row[$colnum];
  3481. }
  3482. // }}}
  3483. // {{{ function fetchCol($colnum = 0)
  3484. /**
  3485. * Fetch and return a column from the current row pointer position
  3486. *
  3487. * @param int|string the column number (or name) to fetch
  3488. *
  3489. * @return mixed data array on success, a MDB2 error on failure
  3490. * @access public
  3491. */
  3492. function fetchCol($colnum = 0)
  3493. {
  3494. $column = array();
  3495. $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
  3496. $row = $this->fetchRow($fetchmode);
  3497. if (is_array($row)) {
  3498. if (!array_key_exists($colnum, $row)) {
  3499. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3500. 'column is not defined in the result set: '.$colnum, __FUNCTION__);
  3501. }
  3502. do {
  3503. $column[] = $row[$colnum];
  3504. } while (is_array($row = $this->fetchRow($fetchmode)));
  3505. }
  3506. if (MDB2::isError($row)) {
  3507. return $row;
  3508. }
  3509. return $column;
  3510. }
  3511. // }}}
  3512. // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
  3513. /**
  3514. * Fetch and return all rows from the current row pointer position
  3515. *
  3516. * @param int $fetchmode the fetch mode to use:
  3517. * + MDB2_FETCHMODE_ORDERED
  3518. * + MDB2_FETCHMODE_ASSOC
  3519. * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
  3520. * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
  3521. * @param bool if set to true, the $all will have the first
  3522. * column as its first dimension
  3523. * @param bool used only when the query returns exactly
  3524. * two columns. If true, the values of the returned array will be
  3525. * one-element arrays instead of scalars.
  3526. * @param bool if true, the values of the returned array is
  3527. * wrapped in another array. If the same key value (in the first
  3528. * column) repeats itself, the values will be appended to this array
  3529. * instead of overwriting the existing values.
  3530. *
  3531. * @return mixed data array on success, a MDB2 error on failure
  3532. *
  3533. * @access public
  3534. * @see getAssoc()
  3535. */
  3536. function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
  3537. $force_array = false, $group = false)
  3538. {
  3539. $all = array();
  3540. $row = $this->fetchRow($fetchmode);
  3541. if (MDB2::isError($row)) {
  3542. return $row;
  3543. } elseif (!$row) {
  3544. return $all;
  3545. }
  3546. $shift_array = $rekey ? false : null;
  3547. if (null !== $shift_array) {
  3548. if (is_object($row)) {
  3549. $colnum = count(get_object_vars($row));
  3550. } else {
  3551. $colnum = count($row);
  3552. }
  3553. if ($colnum < 2) {
  3554. return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
  3555. 'rekey feature requires atleast 2 column', __FUNCTION__);
  3556. }
  3557. $shift_array = (!$force_array && $colnum == 2);
  3558. }
  3559. if ($rekey) {
  3560. do {
  3561. if (is_object($row)) {
  3562. $arr = get_object_vars($row);
  3563. $key = reset($arr);
  3564. unset($row->{$key});
  3565. } else {
  3566. if ( $fetchmode == MDB2_FETCHMODE_ASSOC
  3567. || $fetchmode == MDB2_FETCHMODE_OBJECT
  3568. ) {
  3569. $key = reset($row);
  3570. unset($row[key($row)]);
  3571. } else {
  3572. $key = array_shift($row);
  3573. }
  3574. if ($shift_array) {
  3575. $row = array_shift($row);
  3576. }
  3577. }
  3578. if ($group) {
  3579. $all[$key][] = $row;
  3580. } else {
  3581. $all[$key] = $row;
  3582. }
  3583. } while (($row = $this->fetchRow($fetchmode)));
  3584. } elseif ($fetchmode == MDB2_FETCHMODE_FLIPPED) {
  3585. do {
  3586. foreach ($row as $key => $val) {
  3587. $all[$key][] = $val;
  3588. }
  3589. } while (($row = $this->fetchRow($fetchmode)));
  3590. } else {
  3591. do {
  3592. $all[] = $row;
  3593. } while (($row = $this->fetchRow($fetchmode)));
  3594. }
  3595. return $all;
  3596. }
  3597. // }}}
  3598. // {{{ function rowCount()
  3599. /**
  3600. * Returns the actual row number that was last fetched (count from 0)
  3601. * @return int
  3602. *
  3603. * @access public
  3604. */
  3605. function rowCount()
  3606. {
  3607. return $this->rownum + 1;
  3608. }
  3609. // }}}
  3610. // {{{ function numRows()
  3611. /**
  3612. * Returns the number of rows in a result object
  3613. *
  3614. * @return mixed MDB2 Error Object or the number of rows
  3615. *
  3616. * @access public
  3617. */
  3618. function numRows()
  3619. {
  3620. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3621. 'method not implemented', __FUNCTION__);
  3622. }
  3623. // }}}
  3624. // {{{ function nextResult()
  3625. /**
  3626. * Move the internal result pointer to the next available result
  3627. *
  3628. * @return true on success, false if there is no more result set or an error object on failure
  3629. *
  3630. * @access public
  3631. */
  3632. function nextResult()
  3633. {
  3634. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3635. 'method not implemented', __FUNCTION__);
  3636. }
  3637. // }}}
  3638. // {{{ function getColumnNames()
  3639. /**
  3640. * Retrieve the names of columns returned by the DBMS in a query result or
  3641. * from the cache.
  3642. *
  3643. * @param bool If set to true the values are the column names,
  3644. * otherwise the names of the columns are the keys.
  3645. * @return mixed Array variable that holds the names of columns or an
  3646. * MDB2 error on failure.
  3647. * Some DBMS may not return any columns when the result set
  3648. * does not contain any rows.
  3649. *
  3650. * @access public
  3651. */
  3652. function getColumnNames($flip = false)
  3653. {
  3654. if (!isset($this->column_names)) {
  3655. $result = $this->_getColumnNames();
  3656. if (MDB2::isError($result)) {
  3657. return $result;
  3658. }
  3659. $this->column_names = $result;
  3660. }
  3661. if ($flip) {
  3662. return array_flip($this->column_names);
  3663. }
  3664. return $this->column_names;
  3665. }
  3666. // }}}
  3667. // {{{ function _getColumnNames()
  3668. /**
  3669. * Retrieve the names of columns returned by the DBMS in a query result.
  3670. *
  3671. * @return mixed Array variable that holds the names of columns as keys
  3672. * or an MDB2 error on failure.
  3673. * Some DBMS may not return any columns when the result set
  3674. * does not contain any rows.
  3675. *
  3676. * @access private
  3677. */
  3678. function _getColumnNames()
  3679. {
  3680. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3681. 'method not implemented', __FUNCTION__);
  3682. }
  3683. // }}}
  3684. // {{{ function numCols()
  3685. /**
  3686. * Count the number of columns returned by the DBMS in a query result.
  3687. *
  3688. * @return mixed integer value with the number of columns, a MDB2 error
  3689. * on failure
  3690. *
  3691. * @access public
  3692. */
  3693. function numCols()
  3694. {
  3695. return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  3696. 'method not implemented', __FUNCTION__);
  3697. }
  3698. // }}}
  3699. // {{{ function getResource()
  3700. /**
  3701. * return the resource associated with the result object
  3702. *
  3703. * @return resource
  3704. *
  3705. * @access public
  3706. */
  3707. function getResource()
  3708. {
  3709. return $this->result;
  3710. }
  3711. // }}}
  3712. // {{{ function bindColumn($column, &$value, $type = null)
  3713. /**
  3714. * Set bind variable to a column.
  3715. *
  3716. * @param int column number or name
  3717. * @param mixed variable reference
  3718. * @param string specifies the type of the field
  3719. *
  3720. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3721. *
  3722. * @access public
  3723. */
  3724. function bindColumn($column, &$value, $type = null)
  3725. {
  3726. if (!is_numeric($column)) {
  3727. $column_names = $this->getColumnNames();
  3728. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  3729. if ($this->db->options['field_case'] == CASE_LOWER) {
  3730. $column = strtolower($column);
  3731. } else {
  3732. $column = strtoupper($column);
  3733. }
  3734. }
  3735. $column = $column_names[$column];
  3736. }
  3737. $this->values[$column] =& $value;
  3738. if (null !== $type) {
  3739. $this->types[$column] = $type;
  3740. }
  3741. return MDB2_OK;
  3742. }
  3743. // }}}
  3744. // {{{ function _assignBindColumns($row)
  3745. /**
  3746. * Bind a variable to a value in the result row.
  3747. *
  3748. * @param array row data
  3749. *
  3750. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3751. *
  3752. * @access private
  3753. */
  3754. function _assignBindColumns($row)
  3755. {
  3756. $row = array_values($row);
  3757. foreach ($row as $column => $value) {
  3758. if (array_key_exists($column, $this->values)) {
  3759. $this->values[$column] = $value;
  3760. }
  3761. }
  3762. return MDB2_OK;
  3763. }
  3764. // }}}
  3765. // {{{ function free()
  3766. /**
  3767. * Free the internal resources associated with result.
  3768. *
  3769. * @return bool true on success, false if result is invalid
  3770. *
  3771. * @access public
  3772. */
  3773. function free()
  3774. {
  3775. $this->result = false;
  3776. return MDB2_OK;
  3777. }
  3778. // }}}
  3779. }
  3780. // }}}
  3781. // {{{ class MDB2_Row
  3782. /**
  3783. * The simple class that accepts row data as an array
  3784. *
  3785. * @package MDB2
  3786. * @category Database
  3787. * @author Lukas Smith <smith@pooteeweet.org>
  3788. */
  3789. class MDB2_Row
  3790. {
  3791. // {{{ constructor: function __construct(&$row)
  3792. /**
  3793. * constructor
  3794. *
  3795. * @param resource row data as array
  3796. */
  3797. function __construct(&$row)
  3798. {
  3799. foreach ($row as $key => $value) {
  3800. $this->$key = &$row[$key];
  3801. }
  3802. }
  3803. // }}}
  3804. }
  3805. // }}}
  3806. // {{{ class MDB2_Statement_Common
  3807. /**
  3808. * The common statement class for MDB2 statement objects
  3809. *
  3810. * @package MDB2
  3811. * @category Database
  3812. * @author Lukas Smith <smith@pooteeweet.org>
  3813. */
  3814. class MDB2_Statement_Common
  3815. {
  3816. // {{{ Variables (Properties)
  3817. var $db;
  3818. var $statement;
  3819. var $query;
  3820. var $result_types;
  3821. var $types;
  3822. var $values = array();
  3823. var $limit;
  3824. var $offset;
  3825. var $is_manip;
  3826. // }}}
  3827. // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3828. /**
  3829. * Constructor
  3830. */
  3831. function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
  3832. {
  3833. $this->db = $db;
  3834. $this->statement = $statement;
  3835. $this->positions = $positions;
  3836. $this->query = $query;
  3837. $this->types = (array)$types;
  3838. $this->result_types = (array)$result_types;
  3839. $this->limit = $limit;
  3840. $this->is_manip = $is_manip;
  3841. $this->offset = $offset;
  3842. }
  3843. // }}}
  3844. // {{{ function bindValue($parameter, &$value, $type = null)
  3845. /**
  3846. * Set the value of a parameter of a prepared query.
  3847. *
  3848. * @param int the order number of the parameter in the query
  3849. * statement. The order number of the first parameter is 1.
  3850. * @param mixed value that is meant to be assigned to specified
  3851. * parameter. The type of the value depends on the $type argument.
  3852. * @param string specifies the type of the field
  3853. *
  3854. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3855. *
  3856. * @access public
  3857. */
  3858. function bindValue($parameter, $value, $type = null)
  3859. {
  3860. if (!is_numeric($parameter)) {
  3861. if (strpos($parameter, ':') === 0) {
  3862. $parameter = substr($parameter, 1);
  3863. }
  3864. }
  3865. if (!in_array($parameter, $this->positions)) {
  3866. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3867. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3868. }
  3869. $this->values[$parameter] = $value;
  3870. if (null !== $type) {
  3871. $this->types[$parameter] = $type;
  3872. }
  3873. return MDB2_OK;
  3874. }
  3875. // }}}
  3876. // {{{ function bindValueArray($values, $types = null)
  3877. /**
  3878. * Set the values of multiple a parameter of a prepared query in bulk.
  3879. *
  3880. * @param array specifies all necessary information
  3881. * for bindValue() the array elements must use keys corresponding to
  3882. * the number of the position of the parameter.
  3883. * @param array specifies the types of the fields
  3884. *
  3885. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3886. *
  3887. * @access public
  3888. * @see bindParam()
  3889. */
  3890. function bindValueArray($values, $types = null)
  3891. {
  3892. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3893. $parameters = array_keys($values);
  3894. $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
  3895. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  3896. foreach ($parameters as $key => $parameter) {
  3897. $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
  3898. if (MDB2::isError($err)) {
  3899. if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
  3900. //ignore (extra value for missing placeholder)
  3901. continue;
  3902. }
  3903. $this->db->popExpect();
  3904. $this->db->popErrorHandling();
  3905. return $err;
  3906. }
  3907. }
  3908. $this->db->popExpect();
  3909. $this->db->popErrorHandling();
  3910. return MDB2_OK;
  3911. }
  3912. // }}}
  3913. // {{{ function bindParam($parameter, &$value, $type = null)
  3914. /**
  3915. * Bind a variable to a parameter of a prepared query.
  3916. *
  3917. * @param int the order number of the parameter in the query
  3918. * statement. The order number of the first parameter is 1.
  3919. * @param mixed variable that is meant to be bound to specified
  3920. * parameter. The type of the value depends on the $type argument.
  3921. * @param string specifies the type of the field
  3922. *
  3923. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3924. *
  3925. * @access public
  3926. */
  3927. function bindParam($parameter, &$value, $type = null)
  3928. {
  3929. if (!is_numeric($parameter)) {
  3930. if (strpos($parameter, ':') === 0) {
  3931. $parameter = substr($parameter, 1);
  3932. }
  3933. }
  3934. if (!in_array($parameter, $this->positions)) {
  3935. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  3936. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  3937. }
  3938. $this->values[$parameter] =& $value;
  3939. if (null !== $type) {
  3940. $this->types[$parameter] = $type;
  3941. }
  3942. return MDB2_OK;
  3943. }
  3944. // }}}
  3945. // {{{ function bindParamArray(&$values, $types = null)
  3946. /**
  3947. * Bind the variables of multiple a parameter of a prepared query in bulk.
  3948. *
  3949. * @param array specifies all necessary information
  3950. * for bindParam() the array elements must use keys corresponding to
  3951. * the number of the position of the parameter.
  3952. * @param array specifies the types of the fields
  3953. *
  3954. * @return mixed MDB2_OK on success, a MDB2 error on failure
  3955. *
  3956. * @access public
  3957. * @see bindParam()
  3958. */
  3959. function bindParamArray(&$values, $types = null)
  3960. {
  3961. $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
  3962. $parameters = array_keys($values);
  3963. foreach ($parameters as $key => $parameter) {
  3964. $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
  3965. if (MDB2::isError($err)) {
  3966. return $err;
  3967. }
  3968. }
  3969. return MDB2_OK;
  3970. }
  3971. // }}}
  3972. // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
  3973. /**
  3974. * Execute a prepared query statement.
  3975. *
  3976. * @param array specifies all necessary information
  3977. * for bindParam() the array elements must use keys corresponding
  3978. * to the number of the position of the parameter.
  3979. * @param mixed specifies which result class to use
  3980. * @param mixed specifies which class to wrap results in
  3981. *
  3982. * @return mixed MDB2_Result or integer (affected rows) on success,
  3983. * a MDB2 error on failure
  3984. * @access public
  3985. */
  3986. function execute($values = null, $result_class = true, $result_wrap_class = false)
  3987. {
  3988. if (null === $this->positions) {
  3989. return MDB2::raiseError(MDB2_ERROR, null, null,
  3990. 'Prepared statement has already been freed', __FUNCTION__);
  3991. }
  3992. $values = (array)$values;
  3993. if (!empty($values)) {
  3994. $err = $this->bindValueArray($values);
  3995. if (MDB2::isError($err)) {
  3996. return MDB2::raiseError(MDB2_ERROR, null, null,
  3997. 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
  3998. }
  3999. }
  4000. $result = $this->_execute($result_class, $result_wrap_class);
  4001. return $result;
  4002. }
  4003. // }}}
  4004. // {{{ function _execute($result_class = true, $result_wrap_class = false)
  4005. /**
  4006. * Execute a prepared query statement helper method.
  4007. *
  4008. * @param mixed specifies which result class to use
  4009. * @param mixed specifies which class to wrap results in
  4010. *
  4011. * @return mixed MDB2_Result or integer (affected rows) on success,
  4012. * a MDB2 error on failure
  4013. * @access private
  4014. */
  4015. function _execute($result_class = true, $result_wrap_class = false)
  4016. {
  4017. $this->last_query = $this->query;
  4018. $query = '';
  4019. $last_position = 0;
  4020. foreach ($this->positions as $current_position => $parameter) {
  4021. if (!array_key_exists($parameter, $this->values)) {
  4022. return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  4023. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  4024. }
  4025. $value = $this->values[$parameter];
  4026. $query.= substr($this->query, $last_position, $current_position - $last_position);
  4027. if (!isset($value)) {
  4028. $value_quoted = 'NULL';
  4029. } else {
  4030. $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
  4031. $value_quoted = $this->db->quote($value, $type);
  4032. if (MDB2::isError($value_quoted)) {
  4033. return $value_quoted;
  4034. }
  4035. }
  4036. $query.= $value_quoted;
  4037. $last_position = $current_position + 1;
  4038. }
  4039. $query.= substr($this->query, $last_position);
  4040. $this->db->offset = $this->offset;
  4041. $this->db->limit = $this->limit;
  4042. if ($this->is_manip) {
  4043. $result = $this->db->exec($query);
  4044. } else {
  4045. $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
  4046. }
  4047. return $result;
  4048. }
  4049. // }}}
  4050. // {{{ function free()
  4051. /**
  4052. * Release resources allocated for the specified prepared query.
  4053. *
  4054. * @return mixed MDB2_OK on success, a MDB2 error on failure
  4055. *
  4056. * @access public
  4057. */
  4058. function free()
  4059. {
  4060. if (null === $this->positions) {
  4061. return MDB2::raiseError(MDB2_ERROR, null, null,
  4062. 'Prepared statement has already been freed', __FUNCTION__);
  4063. }
  4064. $this->statement = null;
  4065. $this->positions = null;
  4066. $this->query = null;
  4067. $this->types = null;
  4068. $this->result_types = null;
  4069. $this->limit = null;
  4070. $this->is_manip = null;
  4071. $this->offset = null;
  4072. $this->values = null;
  4073. return MDB2_OK;
  4074. }
  4075. // }}}
  4076. }
  4077. // }}}
  4078. // {{{ class MDB2_Module_Common
  4079. /**
  4080. * The common modules class for MDB2 module objects
  4081. *
  4082. * @package MDB2
  4083. * @category Database
  4084. * @author Lukas Smith <smith@pooteeweet.org>
  4085. */
  4086. class MDB2_Module_Common
  4087. {
  4088. // {{{ Variables (Properties)
  4089. /**
  4090. * contains the key to the global MDB2 instance array of the associated
  4091. * MDB2 instance
  4092. *
  4093. * @var int
  4094. * @access protected
  4095. */
  4096. protected $db_index;
  4097. // }}}
  4098. // {{{ constructor: function __construct($db_index)
  4099. /**
  4100. * Constructor
  4101. */
  4102. function __construct($db_index)
  4103. {
  4104. $this->db_index = $db_index;
  4105. }
  4106. // }}}
  4107. // {{{ function getDBInstance()
  4108. /**
  4109. * Get the instance of MDB2 associated with the module instance
  4110. *
  4111. * @return object MDB2 instance or a MDB2 error on failure
  4112. *
  4113. * @access public
  4114. */
  4115. function getDBInstance()
  4116. {
  4117. if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
  4118. $result = $GLOBALS['_MDB2_databases'][$this->db_index];
  4119. } else {
  4120. $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  4121. 'could not find MDB2 instance');
  4122. }
  4123. return $result;
  4124. }
  4125. // }}}
  4126. }
  4127. // }}}
  4128. // {{{ function MDB2_closeOpenTransactions()
  4129. /**
  4130. * Close any open transactions form persistent connections
  4131. *
  4132. * @return void
  4133. *
  4134. * @access public
  4135. */
  4136. function MDB2_closeOpenTransactions()
  4137. {
  4138. reset($GLOBALS['_MDB2_databases']);
  4139. while (next($GLOBALS['_MDB2_databases'])) {
  4140. $key = key($GLOBALS['_MDB2_databases']);
  4141. if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
  4142. && $GLOBALS['_MDB2_databases'][$key]->in_transaction
  4143. ) {
  4144. $GLOBALS['_MDB2_databases'][$key]->rollback();
  4145. }
  4146. }
  4147. }
  4148. // }}}
  4149. // {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
  4150. /**
  4151. * default debug output handler
  4152. *
  4153. * @param object reference to an MDB2 database object
  4154. * @param string usually the method name that triggered the debug call:
  4155. * for example 'query', 'prepare', 'execute', 'parameters',
  4156. * 'beginTransaction', 'commit', 'rollback'
  4157. * @param string message that should be appended to the debug variable
  4158. * @param array contains context information about the debug() call
  4159. * common keys are: is_manip, time, result etc.
  4160. *
  4161. * @return void|string optionally return a modified message, this allows
  4162. * rewriting a query before being issued or prepared
  4163. *
  4164. * @access public
  4165. */
  4166. function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
  4167. {
  4168. $db->debug_output.= $scope.'('.$db->db_index.'): ';
  4169. $db->debug_output.= $message.$db->getOption('log_line_break');
  4170. return $message;
  4171. }
  4172. // }}}
  4173. ?>