Beruflich Dokumente
Kultur Dokumente
DistributedDatabaseArchitecture
HomogenousDistributedDatabaseSystems
AhomogenousdistributeddatabasesystemisanetworkoftwoormoreOracle Databasesthatresideononeormoremachines.Figure291 illustrates adistributed systemthatconnectsthreedatabases:hq,mfg,andsales.Anapplicationcan simultaneouslyaccessormodifythedatainseveraldatabasesinasingle distributedenvironment.Forexample,asinglequeryfromaManufacturingclient
onlocaldatabasemfgcanretrievejoineddatafromtheproductstableonthelocal
Inthisway,adistributedsystemgivestheappearanceofnativedataaccess.Users onmfgdonothavetoknowthatthedatatheyaccessresidesonremotedatabases.
DistributedDatabaseArchitecture
Figure291
Manufacturing
HomogeneousDistributedDatabase
DistributedDatabase
MFG.ACME.COM HQ.ACME.COM
Headquarters
Oracle
Oracle
Oracle
.
. .
Sales
SALES.ACME.COM
. . .
DistributedDatabasesVersusDistributedProcessing
Thetermsdistributeddatabaseanddistributedprocessingarecloselyrelated,yet
havedistinctmeanings.Theredenitionsareasfollows:
...
3
DistributedDatabaseArchitecture
DistributedDatabasesVersusReplicatedDatabases
Thetermsdistributeddatabasesystemanddatabasereplicationarerelated,yet distinct.Inapure(thatis,notreplicated)distributeddatabase,thesystemmanages asinglecopyofalldataandsupportingdatabaseobjects.Typically,distributed databaseapplicationsusedistributedtransactionstoaccessbothlocalandremote dataandmodifytheglobaldatabaseinrealtime.
Note:
Thisbookdiscussesonlypuredistributeddatabases.
Thetermreplicationreferstotheoperationofcopyingandmaintainingdatabase objectsinmultipledatabasesbelongingtoadistributedsystem.Whilereplication reliesondistributeddatabasetechnology,databasereplicationoffersapplications benetsthatarenotpossiblewithinapuredistributeddatabaseenvironment. Mostcommonly,replicationisusedtoimprovelocaldatabaseperformanceand protecttheavailabilityofapplicationsbecausealternatedataaccessoptionsexist. Forexample,anapplicationmaynormallyaccessalocaldatabaseratherthana remoteservertominimizenetworktrafcandachievemaximumperformance. Furthermore,theapplicationcancontinuetofunctionifthelocalserverexperiences afailure,butotherserverswithreplicateddataremainaccessible.
DistributedDatabaseArchitecture
SeeAlso:
OracleDatabaseAdvancedReplicationformoreinformationabout
OracleDatabasereplicationfeatures
OracleStreamsConceptsandAdministrationforinformation
aboutOracleStreams,anothermethodofsharinginformation betweendatabases
HeterogeneousDistributedDatabaseSystems
Inaheterogeneousdistributeddatabasesystem,atleastoneofthedatabasesisa nonOracleDatabasesystem.Totheapplication,theheterogeneousdistributed databasesystemappearsasasingle,local,OracleDatabase.ThelocalOracle Databaseserverhidesthedistributionandheterogeneityofthedata. TheOracleDatabaseserveraccessesthenonOracleDatabasesystemusingOracle HeterogeneousServicesinconjunctionwithanagent.IfyouaccessthenonOracle DatabasedatastoreusinganOracleTransparentGateway,thentheagentisa systemspecicapplication.Forexample,ifyouincludeaSybasedatabaseinan OracleDatabasedistributedsystem,thenyouneedtoobtainaSybasespecic transparentgatewaysothattheOracleDatabaseinthesystemcancommunicate withit. Alternatively,youcanusegenericconnectivitytoaccessnonOracleDatabasedata storessolongasthenonOracleDatabasesystemsupportstheODBCorOLEDB protocols. Otherthantheintroductorymaterialpresentedinthis chapter,thisbookdoesnotdiscussOracleHeterogeneousServices. SeeOracleDatabaseHeterogeneousConnectivityAdministrator'sGuide formoredetailedinformationaboutHeterogeneousServices.
Note:
HeterogeneousServices
HeterogeneousServices(HS)isanintegratedcomponentwithintheOracle DatabaseserverandtheenablingtechnologyforthecurrentsuiteofOracle TransparentGatewayproducts.HSprovidesthecommonarchitectureand administrationmechanismsforOracleDatabasegatewayproductsandother heterogeneousaccessfacilities.Also,itprovidesupwardlycompatiblefunctionality forusersofmostoftheearlierOracleTransparentGatewayreleases.
DistributedDatabaseArchitecture
TransparentGatewayAgents
ForeachnonOracleDatabasesystemthatyouaccess,HeterogeneousServicescan useatransparentgatewayagenttointerfacewiththespeciednonOracleDatabase system.TheagentisspecictothenonOracleDatabasesystem,soeachtypeof systemrequiresadifferentagent. ThetransparentgatewayagentfacilitatescommunicationbetweenOracleDatabase andnonOracleDatabasesystemsandusestheHeterogeneousServicescomponent intheOracleDatabaseserver.TheagentexecutesSQLandtransactionalrequestsat thenonOracleDatabasesystemonbehalfoftheOracleDatabaseserver. YourOraclesuppliedgatewayspecicdocumentation forinformationabouttransparentgateways
SeeAlso:
GenericConnectivity
GenericconnectivityenablesyoutoconnecttononOracleDatabasedatastoresby usingeitheraHeterogeneousServicesODBCagentoraHeterogeneousServices OLEDBagent.BothareincludedwithyourOracleproductasastandardfeature. AnydatasourcecompatiblewiththeODBCorOLEDBstandardscanbeaccessed usingagenericconnectivityagent. Theadvantagetogenericconnectivityisthatitmaynotberequiredforyouto purchaseandcongureaseparatesystemspecicagent.YouuseanODBCorOLE DBdriverthatcaninterfacewiththeagent.However,somedataaccessfeaturesare onlyavailablewithtransparentgatewayagents.
Client/ServerDatabaseArchitecture
AdatabaseserveristheOraclesoftwaremanagingadatabase,andaclientisan applicationthatrequestsinformationfromaserver.Eachcomputerinanetworkisa nodethatcanhostoneormoredatabases.Eachnodeinadistributeddatabase systemcanactasaclient,aserver,orboth,dependingonthesituation. InFigure292 , thehostforthehqdatabaseisactingasadatabaseserverwhena statementisissuedagainstitslocaldata(forexample,thesecondstatementineach transactionissuesastatementagainstthelocaldepttable),butisactingasaclient whenitissuesastatementagainstremotedata(forexample,therststatementin eachtransactionisissuedagainsttheremotetableempinthesalesdatabase).
DistributedDatabaseArchitecture
Figure292
Server
AnOracleDatabaseDistributedDatabaseSystem
Server
Oracle Net
Network DatabaseLink
CONNECTTO...
Oracle Net
IDENTIFIEDBY...
DEPTTable HQ Database
Application
TRANSACTION
INSERTINTOEMP@SALES..; DELETEFROMDEPT..; SELECT... FROMEMP@SALES...; COMMIT;
DatabaseLinks
Thisqueryisindirectbecausetheobjectyouareaccessingisnotonthedatabaseto whichyouaredirectlyconnected.
DatabaseLinks
Thecentralconceptindistributeddatabasesystemsisadatabaselink.Adatabase linkisaconnectionbetweentwophysicaldatabaseserversthatallowsaclientto accessthemasonelogicaldatabase. Thissectioncontainsthefollowingtopics:
WhatAreDatabaseLinks?
Adatabaselinkisapointerthatdenesaonewaycommunicationpathfroman OracleDatabaseservertoanotherdatabaseserver.Thelinkpointerisactually denedasanentryinadatadictionarytable.Toaccessthelink,youmustbe connectedtothelocaldatabasethatcontainsthedatadictionaryentry. Adatabaselinkconnectionisonewayinthesensethataclientconnectedtolocal databaseAcanusealinkstoredindatabaseAtoaccessinformationinremote databaseB,butusersconnectedtodatabaseBcannotusethesamelinktoaccess dataindatabaseA.IflocalusersondatabaseBwanttoaccessdataondatabaseA, thentheymustdenealinkthatisstoredinthedatadictionaryofdatabaseB. Adatabaselinkconnectionallowslocaluserstoaccessdataonaremotedatabase. Forthisconnectiontooccur,eachdatabaseinthedistributedsystemmusthavea uniqueglobaldatabasenameinthenetworkdomain.Theglobaldatabasename uniquelyidentiesadatabaseserverinadistributedsystem.
DatabaseLinks
DatabaseLink
Select* FROMemp
PUBLICSYNONYM
Local database
emp>emp@HQ.ACME.COM
Remote database
EMPtable
DatabaseLinks
TypeofLink Fixeduserlink
Description Usersconnectusingtheusernameandpasswordreferencedin thelink.Forexample,ifJaneusesaxeduserlinkthatconnects tothehqdatabasewiththeusernameandpassword scott/tiger,thensheconnectsasscott,Janehasallthe privilegesinhqgrantedtoscottdirectly,andallthedefault rolesthatscotthasbeengrantedinthehqdatabase. Auserconnectsasaglobaluser.Alocalusercanconnectasa globaluserinthecontextofastoredprocedure,withoutstoring theglobaluser'spasswordinalinkdenition.Forexample, JanecanaccessaprocedurethatScottwrote,accessingScott's accountandScott'sschemaonthehqdatabase.Currentuser linksareanaspectofOracleAdvancedSecurity.
Currentuserlink
CreatedatabaselinksusingtheCREATEDATABASELINKstatement.Afteralinkis created,youcanuseittospecifyschemaobjectsinSQLstatements.
SeeAlso:
OracleDatabaseSQLReferenceforsyntaxoftheCREATE
DATABASEstatement
OracleAdvancedSecurityAdministrator'sGuideforinformation aboutOracleAdvancedSecurity
WhatAreSharedDatabaseLinks?
Ashareddatabaselinkisalinkbetweenalocalserverprocessandtheremote database.Thelinkissharedbecausemultipleclientprocessescanusethesamelink simultaneously. Whenalocaldatabaseisconnectedtoaremotedatabasethroughadatabaselink, eitherdatabasecanrunindedicatedorsharedservermode.Thefollowingtable illustratesthepossibilities:
LocalDatabaseMode Dedicated Dedicated Sharedserver Sharedserver RemoteDatabaseMode Dedicated Sharedserver Dedicated Sharedserver
DatabaseLinks
Ashareddatabaselinkcanexistinanyofthesefourcongurations.Sharedlinks differfromstandarddatabaselinksinthefollowingways:
Differentusersaccessingthesameschemaobjectthroughadatabaselinkcan shareanetworkconnection. Whenauserneedstoestablishaconnectiontoaremoteserverfromaparticular serverprocess,theprocesscanreuseconnectionsalreadyestablishedtothe remoteserver.Thereuseoftheconnectioncanoccuriftheconnectionwas establishedonthesameserverprocesswiththesamedatabaselink,possiblyin adifferentsession.Inanonshareddatabaselink,aconnectionisnotshared acrossmultiplesessions. Whenyouuseashareddatabaselinkinasharedserverconguration,a networkconnectionisestablisheddirectlyoutofthesharedserverprocessin thelocalserver.Foranonshareddatabaselinkonalocalsharedserver,this connectionwouldhavebeenestablishedthroughthelocaldispatcher,requiring contextswitchesforthelocaldispatcher,andrequiringdatatogothroughthe dispatcher. OracleNetServicesAdministrator'sGuideforinformation aboutsharedserver
SeeAlso:
WhyUseDatabaseLinks?
Thegreatadvantageofdatabaselinksisthattheyallowuserstoaccessanother user'sobjectsinaremotedatabasesothattheyareboundedbytheprivilegesetof theobjectowner.Inotherwords,alocalusercanaccessalinktoaremotedatabase withouthavingtobeauserontheremotedatabase. Forexample,assumethatemployeessubmitexpensereportstoAccountsPayable (A/P),andfurthersupposethatauserusinganA/Papplicationneedstoretrieve informationaboutemployeesfromthehqdatabase.TheA/Pusersshouldbeable toconnecttothehqdatabaseandexecuteastoredprocedureintheremotehq databasethatretrievesthedesiredinformation.TheA/Pusersshouldnotneedto behqdatabaseuserstodotheirjobs;theyshouldonlybeabletoaccesshq informationinacontrolledwayaslimitedbytheprocedure. Databaselinksallowyoutograntlimitedaccessonremotedatabasestolocalusers. Byusingcurrentuserlinks,youcancreatecentrallymanagedglobaluserswhose passwordinformationishiddenfrombothadministratorsandnonadministrative users.Forexample,A/Puserscanaccessthehqdatabaseasscott,butunlike xeduserlinks,scott'scredentialsarenotstoredwheredatabaseuserscansee them.
DatabaseLinks
GlobalDatabaseNamesinDatabaseLinks
Tounderstandhowadatabaselinkworks,youmustrstunderstandwhataglobal databasenameis.Eachdatabaseinadistributeddatabaseisuniquelyidentiedby itsglobaldatabasename.Thedatabaseformsaglobaldatabasenamebyprexing thedatabasenetworkdomain,speciedbytheDB_DOMAINinitializationparameter atdatabasecreation,withtheindividualdatabasename,speciedbytheDB_NAME initializationparameter. Forexample,Figure294 illustrates arepresentativehierarchicalarrangementof databasesthroughoutanetwork.
DatabaseLinks
Figure294
HierarchicalArrangementofNetworkedDatabases
EDU COM ORG
Educational Institutions
Other Companies
NonCommercial Organizations
ACME_TOOLS
ACME_AUTO
DIVISION1 DIVISION2
DIVISION3
ASIA
AMERICAS
EUROPE
US
MEXICO
UK
GERMANY
Sales Employees(HR)
HQ
Sales
Sales
Sales
Sales
Employees(HR)
mfg.division3.acme_tools.com
sales.us.americas.acme_auto.com
DatabaseLinks
NamesforDatabaseLinks
Typically,adatabaselinkhasthesamenameastheglobaldatabasenameofthe remotedatabasethatitreferences.Forexample,iftheglobaldatabasenameofa databaseissales.us.oracle.com,thenthedatabaselinkisalsocalled sales.us.oracle.com. WhenyousettheinitializationparameterGLOBAL_NAMEStoTRUE,thedatabase ensuresthatthenameofthedatabaselinkisthesameastheglobaldatabasename oftheremotedatabase.Forexample,iftheglobaldatabasenameforhqis hq.acme.com,andGLOBAL_NAMESisTRUE,thenthelinknamemustbecalled hq.acme.com.Notethatthedatabasechecksthedomainpartoftheglobal databasenameasstoredinthedatadictionary,nottheDB_DOMAINsettinginthe initializationparameterle(see"ChangingtheDomaininaGlobalDatabaseName" onpage304). IfyousettheinitializationparameterGLOBAL_NAMEStoFALSE,thenyouarenot requiredtouseglobalnaming.Youcanthennamethedatabaselinkwhateveryou want.Forexample,youcannameadatabaselinktohq.acme.comasfoo. Oraclerecommendsthatyouuseglobalnamingbecause manyusefulfeatures,includingReplication,requireglobalnaming.
Note:
DatabaseLinks
TypesofDatabaseLinks
OracleDatabaseletsyoucreateprivate,public,andglobaldatabaselinks.These basiclinktypesdifferaccordingtowhichusersareallowedaccesstotheremote database:
Type Private Owner Userwhocreatedthelink. Viewownershipdata through: DBA_DB_LINKS
ALL_DB_LINKS USER_DB_LINKS
Public
Createsadatabasewidelink.Allusersand PL/SQLsubprogramsinthedatabasecanuse thelinktoaccessdatabaseobjectsinthe correspondingremotedatabase. Createsanetworkwidelink.WhenanOracle networkusesadirectoryserver,thedirectory serverautomaticallycreateandmanagesglobal databaselinks(asnetservicenames)forevery OracleDatabaseinthenetwork.Usersand PL/SQLsubprogramsinanydatabasecanuse agloballinktoaccessobjectsinthe correspondingremotedatabase. Note:InearlierreleasesofOracleDatabase,a globaldatabaselinkreferredtoadatabaselink thatwasregisteredwithanOracleNames server.TheuseofanOracleNamesserverhas beendeprecated.Inthisdocument,global databaselinksrefertotheuseofnetservice namesfromthedirectoryserver.
Global
DatabaseLinks
TypeofLink Publicdatabaselink
Globaldatabaselink
SeeAlso:
UsersofDatabaseLinks
Whencreatingthelink,youdeterminewhichusershouldconnecttotheremote databasetoaccessthedata.Thefollowingtableexplainsthedifferencesamongthe categoriesofusersinvolvedindatabaselinks:
SampleLink CreationSyntax CREATEPUBLIC DATABASELINKhq USING'hq';
UserType Connecteduser
Currentuser
DatabaseLinks
UserType Fixeduser
ConnectedUserDatabaseLinks
Connecteduserlinkshavenoconnectstringassociatedwiththem.Theadvantage ofaconnecteduserlinkisthatauserreferencingthelinkconnectstotheremote databaseasthesameuser.Furthermore,becausenoconnectstringisassociated withthelink,nopasswordisstoredincleartextinthedatadictionary. Connecteduserlinkshavesomedisadvantages.Becausetheselinksrequireusersto haveaccountsandprivilegesontheremotedatabasestowhichtheyareattempting toconnect,theyrequiremoreprivilegeadministrationforadministrators.Also, givingusersmoreprivilegesthantheyneedviolatesthefundamentalsecurity conceptofleastprivilege:usersshouldonlybegiventheprivilegestheyneedto performtheirjobs. Theabilitytouseaconnecteduserdatabaselinkdependsonseveralfactors,chief amongthemwhethertheuserisauthenticatedbythedatabaseusingapassword,or externallyauthenticatedbytheoperatingsystemoranetworkauthentication service.Iftheuserisexternallyauthenticated,thentheabilitytouseaconnected userlinkalsodependsonwhethertheremotedatabaseacceptsremote authenticationofusers,whichissetbytheREMOTE_OS_AUTHENTinitialization parameter. TheREMOTE_OS_AUTHENTparameteroperatesasfollows:
REMOTE_OS_AUTHENTValueConsequences TRUEfortheremotedatabase Anexternallyauthenticatedusercanconnecttothe remotedatabaseusingaconnecteduserdatabaselink.
DatabaseLinks
FixedUserDatabaseLinks
Abenetofaxeduserlinkisthatitconnectsauserinaprimarydatabasetoa remotedatabasewiththesecuritycontextoftheuserspeciedintheconnectstring. Forexample,localuserjoecancreateapublicdatabaselinkinjoe'sschemathat speciesthexeduserscottwithpasswordtiger.Ifjaneusesthexeduser linkinaquery,thenjaneistheuseronthelocaldatabase,butsheconnectstothe remotedatabaseasscott/tiger. Fixeduserlinkshaveausernameandpasswordassociatedwiththeconnectstring. Theusernameandpasswordarestoredinunencryptedforminthedatadictionary intheLINK$table. Thefactthattheusernameandpasswordarestoredin unencryptedforminthedatadictionarycreatesapotentialsecurity weaknessofxeduserdatabaselinks.
Caution:
Ifthe07_DICTIONARY_ACCESSIBILITYinitializationparameter issettoTRUE,auserwiththeSELECTANYTABLEsystem privilegehasaccesstothedatadictionary,andthusthe authenticationassociatedwithaxeduseriscompromised. ThedefaultfortheO7_DICTIONARY_ACCESSIBILITY initializationparameterisFALSE. Foranexampleofthissecurityproblem,assumethatjanedoesnothaveprivileges touseaprivatelinkthatconnectstothehqdatabaseasscott/tiger,buthas SELECTANYTABLEprivilegeonadatabaseinwhichtheO7_DICTIONARY_ ACCESSIBILITYinitializationparameterissettoTRUE.ShecanselectfromLINK$ andreadthattheconnectstringtohqisscott/tiger.Ifjanehasanaccounton thehostonwhichhqresides,thenshecanconnecttothehostandthenconnectto hqasscottusingthepasswordtiger.Shewillhaveallscott'sprivilegesifshe connectslocallyandanyauditrecordswillberecordedasifshewerescott.
DatabaseLinks
CurrentUserDatabaseLinks
Currentuserdatabaselinksmakeuseofaglobaluser.Aglobalusermustbe authenticatedbyanX.509certicateorapassword,andbeauseronbothdatabases involvedinthelink. TheuserinvokingtheCURRENT_USERlinkdoesnothavetobeaglobaluser.For example,ifjaneisauthenticated(notasaglobaluser)bypasswordtothe AccountsPayabledatabase,shecanaccessastoredproceduretoretrievedatafrom thehqdatabase.Theprocedureusesacurrentuserdatabaselink,whichconnects hertohqasglobaluserscott. Userscottisaglobaluserandauthenticated throughacerticateoverSSL,butjaneisnot. Notethatcurrentuserdatabaselinkshavetheseconsequences:
Ifthecurrentuserdatabaselinkisnotaccessedfromwithinastoredobject,then thecurrentuseristhesameastheconnecteduseraccessingthelink.For example,ifscottissuesaSELECTstatementthroughacurrentuserlink,then thecurrentuserisscott. Whenexecutingastoredobjectsuchasaprocedure,view,ortriggerthat accessesadatabaselink,thecurrentuseristheuserthatownsthestoredobject, andnottheuserthatcallstheobject.Forexample,ifjanecallsprocedure scott.p(createdbyscott),andacurrentuserlinkappearswithinthecalled procedure,thenscottisthecurrentuserofthelink. Ifthestoredobjectisaninvokerrightsfunction,procedure,orpackage,then theinvoker'sauthorizationIDisusedtoconnectasaremoteuser.Forexample, ifuserjanecallsprocedurescott.p(aninvokerrightsprocedurecreatedby scott),andthelinkappearsinsideprocedurescott.p,thenjaneisthe currentuser. Youcannotconnecttoadatabaseasanenterpriseuserandthenuseacurrent userlinkinastoredprocedurethatexistsinashared,globalschema.For example,ifuserjaneaccessesastoredprocedureinthesharedschemaguest ondatabasehq,shecannotuseacurrentuserlinkinthisschematologontoa remotedatabase.
DatabaseLinks
SeeAlso:
invokerrightsfunctions,procedures,orpackages.
CreationofDatabaseLinks:Examples
CreatedatabaselinksusingtheCREATEDATABASELINK statement.Thetable givesexamplesofSQLstatementsthatcreatedatabaselinksinalocaldatabaseto theremotesales.us.americas.acme_auto.comdatabase:
SQLStatement CREATEDATABASELINK sales.us.americas.acme_ auto.comUSING'sales_us'; CREATEDATABASELINKfoo CONNECTTOCURRENT_USERUSING 'am_sls'; CREATEDATABASELINK sales.us.americas.acme_ auto.comCONNECTTOscott IDENTIFIEDBYtigerUSING 'sales_us'; CREATEPUBLICDATABASELINK salesCONNECTTOscott IDENTIFIEDBYtigerUSING 'rev';
CREATESHAREDPUBLICDATABASE
ConnectsAs Connecteduser
Currentglobaluser
scottusingpassword tiger
salesusingnetservice namerev
scottusingpassword tiger
Publicxed user
salesusingnetservice namesales
DatabaseLinks
SeeAlso:
DATABASELINKstatementsyntax
SchemaObjectsandDatabaseLinks
Afteryouhavecreatedadatabaselink,youcanexecuteSQLstatementsthataccess objectsontheremotedatabase.Forexample,toaccessremoteobjectempusing databaselinkfoo,youcanissue:
SELECT*FROMemp@foo;
NamingofSchemaObjectsUsingDatabaseLinks
OracleDatabaseusestheglobaldatabasenametonametheschemaobjectsglobally usingthefollowingscheme: schema.schema_object@global_database_name where:
schema isacollectionoflogicalstructuresofdata,orschemaobjects.A schemaisownedbyadatabaseuserandhasthesamenameasthatuser.Each userownsasingleschema. schema_objectisalogicaldatastructurelikeatable,index,view,synonym, procedure,package,oradatabaselink. global_database_nameisthenamethatuniquelyidentiesaremote database.Thisnamemustbethesameastheconcatenationoftheremote databaseinitializationparametersDB_NAMEandDB_DOMAIN,unlessthe parameterGLOBAL_NAMESissettoFALSE,inwhichcaseanynameis acceptable.
Forexample,usingadatabaselinktodatabasesales.division3.acme.com,a userorapplicationcanreferenceremotedataasfollows:
DatabaseLinks
SELECT*FROMscott.emp@sales.division3.acme.com;#emptableinscott'sschema SELECTlocFROMscott.dept@sales.division3.acme.com;
AuthorizationforAccessingRemoteSchemaObjects
Toaccessaremoteschemaobject,youmustbegrantedaccesstotheremoteobject intheremotedatabase.Further,toperformanyupdates,inserts,ordeletesonthe remoteobject,youmustbegrantedtheSELECTprivilegeontheobject,alongwith theUPDATE,INSERT,orDELETEprivilege.Unlikewhenaccessingalocalobject, theSELECTprivilegeisnecessaryforaccessingaremoteobjectbecausethe databasehasnoremotedescribecapability.ThedatabasemustdoaSELECT*on theremoteobjectinordertodetermineitsstructure.
SynonymsforSchemaObjects
OracleDatabaseletsyoucreatesynonymssothatyoucanhidethedatabaselink namefromtheuser.Asynonymallowsaccesstoatableonaremotedatabaseusing thesamesyntaxthatyouwouldusetoaccessatableonalocaldatabase.For example,assumeyouissuethefollowingqueryagainstatableinaremotedatabase:
SELECT*FROMemp@hq.acme.com;
Youcancreatethesynonymempforemp@hq.acme.comsothatyoucanissuethe followingqueryinsteadtoaccessthesamedata:
SELECT*FROMemp;
SchemaObjectNameResolution
Toresolveapplicationreferencestoschemaobjects(aprocesscalledname resolution),thedatabaseformsobjectnameshierarchically.Forexample,the databaseguaranteesthateachschemawithinadatabasehasauniquename,and thatwithinaschemaeachobjecthasauniquename.Asaresult,aschemaobject nameisalwaysuniquewithinthedatabase.Furthermore,thedatabaseresolves applicationreferencestothelocalnameoftheobject.
DatabaseLinks
Youthenissuethefollowingstatementsusingdatabaselinkhq.acme.comto accessobjectsinthescottandjaneschemasonremotedatabasehq:
SELECT*FROMscott.emp@hq.acme.com; INSERTINTOjane.accounts@hq.acme.com(acc_no,acc_name,balance) VALUES(5001,'BOWER',2000); UPDATEjane.accounts@hq.acme.com SETbalance=balance+500; DELETEFROMjane.accounts@hq.acme.com WHEREacc_name='BOWER';
DatabaseLinkRestrictions
Youcannotperformthefollowingoperationsusingdatabaselinks:
DistributedDatabaseAdministration
connectingasscott,janereceivesscott'sdefaultrolesontheremote database.JanecannotissueSETROLEtoobtainanondefaultrole.
DistributedDatabaseAdministration
Thefollowingsectionsexplainsomeofthetopicsrelatingtodatabasemanagement inanOracleDatabasedistributeddatabasesystem:
tolearnaboutheterogeneousservicesconcepts
SiteAutonomy
Siteautonomymeansthateachserverparticipatinginadistributeddatabaseis administeredindependentlyfromallotherdatabases.Althoughseveraldatabases canworktogether,eachdatabaseisaseparaterepositoryofdatathatismanaged individually.SomeofthebenetsofsiteautonomyinanOracleDatabase distributeddatabaseinclude:
Nodesofthesystemcanmirrorthelogicalorganizationofcompaniesorgroups thatneedtomaintainindependence.
Localadministratorscontrolcorrespondinglocaldata.Therefore,eachdatabase
administrator'sdomainofresponsibilityissmallerandmoremanageable.
DistributedDatabaseAdministration
DistributedDatabaseSecurity
Thedatabasesupportsallofthesecurityfeaturesthatareavailablewitha nondistributeddatabaseenvironmentfordistributeddatabasesystems,including:
Loginpacketencryptionforclienttoserverandservertoserverconnections
Thefollowingsectionsexplainsomeadditionaltopicstoconsiderwhenconguring anOracleDatabasedistributeddatabasesystem:
DistributedDatabaseAdministration
AuthenticationThroughDatabaseLinks
Databaselinksareeitherprivateorpublic,authenticatedornonauthenticated.You createpubliclinksbyspecifyingthePUBLICkeywordinthelinkcreation statement.Forexample,youcanissue:
CREATEPUBLICDATABASELINKfooUSING'sales';
Thistabledescribeshowusersaccesstheremotedatabasethroughthelink:
LinkType Private Authenticated No SecurityAccess Whenconnectingtotheremotedatabase,thedatabase usessecurityinformation(userid/password)takenfrom thelocalsession.Hence,thelinkisaconnecteduser databaselink.Passwordsmustbesynchronizedbetween thetwodatabases. Theuserid/passwordistakenfromthelinkdenition ratherthanfromthelocalsessioncontext.Hence,thelink isaxeduserdatabaselink. Thiscongurationallowspasswordstobedifferentonthe twodatabases,butthelocaldatabaselinkpasswordmust matchtheremotedatabasepassword.Thepasswordis storedincleartextonthelocalsystemcatalog,addinga securityrisk. Public No Worksthesameasaprivatenonauthenticatedlink,except thatalluserscanreferencethispointertotheremote database. Allusersonthelocaldatabasecanaccesstheremote databaseandallusethesameuserid/passwordtomake theconnection.Also,thepasswordisstoredincleartext inthelocalcatalog,soyoucanseethepasswordifyou havesufcientprivilegesinthelocaldatabase.
Private
Yes
Public
Yes
DistributedDatabaseAdministration
AuthenticationWithoutPasswords
Whenusingaconnecteduserorcurrentuserdatabaselink,youcanuseanexternal authenticationsourcesuchasKerberostoobtainendtoendsecurity.Inendtoend authentication,credentialsarepassedfromservertoserverandcanbe authenticatedbyadatabaseserverbelongingtothesamedomain.Forexample,if janeisauthenticatedexternallyonalocaldatabase,andwantstouseaconnected userlinktoconnectasherselftoaremotedatabase,thelocalserverpassesthe securitytickettotheremotedatabase.
SupportingUserAccountsandRoles
Inadistributeddatabasesystem,youmustcarefullyplantheuseraccountsand rolesthatarenecessarytosupportapplicationsusingthesystem.Notethat:
Asyoucreatethedatabaselinksforthenodesinadistributeddatabasesystem,
determinewhichuseraccountsandroleseachsiteneedstosupportservertoserver
connectionsthatusethelinks. Inadistributedenvironment,userstypicallyrequireaccesstomanynetwork services.Whenyoumustcongureseparateauthenticationsforeachusertoaccess eachnetworkservice,securityadministrationcanbecomeunwieldy,especiallyfor largesystems. "CreatingDatabaseLinks" onpage308 formore informationabouttheuseraccountsthatmustbeavailableto supportdifferenttypesofdatabaselinksinthesystem
SeeAlso:
CentralizedUserandPrivilegeManagement
Thedatabaseprovidesdifferentwaysforyoutomanagetheusersandprivileges involvedinadistributedsystem.Forexample,youhavetheseoptions:
Enterpriseusermanagement.Youcancreateglobaluserswhoareauthenticated
throughSSLorbyusingpasswords,thenmanagetheseusersandtheir privilegesinadirectorythroughanindependententerprisedirectoryservice.
Networkauthenticationservice.Thiscommontechniquesimpliessecurity managementfordistributedenvironments.YoucanusetheOracleAdvanced
DistributedDatabaseAdministration
managementistocreatethefollowing:
Aglobaluserinacentralizeddirectory Auserineverydatabasethattheglobalusermustconnectto
Forexample,youcancreateaglobalusercalledfredwiththefollowingSQL statement:
CREATEUSERfredIDENTIFIEDGLOBALLYAS'CN=fredadams,O=Oracle,C=England';
DistributedDatabaseAdministration
Note:
Youcannotaccessacurrentuserdatabaselinkinashared
schema. Forexample,supposejane,bill,andscottalluseahumanresources application.Thehqapplicationobjectsareallcontainedintheguestschemaon thehqdatabase.Inthiscase,youcancreatealocalglobaluseraccounttobeusedas asharedschema.Thisglobalusername,thatis,sharedschemaname,isguest. jane,bill,andscottareallcreatedasenterpriseusersinthedirectoryservice. Theyarealsomappedtotheguestschemainthedirectory,andcanbeassigned differentauthorizationsinthehqapplication. Figure295 illustrates anexampleofglobalusersecurityusingtheenterprise directoryservice:
Figure295 GlobalUserSecurity
LDAP
SSL
HQ
SSL
SSL
SSLpassword
SALES
SCOTT
Assumethattheenterprisedirectoryservicecontainsthefollowinginformationon enterpriseusersforhqandsales:
Database tb Role clerk1 Schema guest EnterpriseUsers bill scott
DistributedDatabaseAdministration
Database sales
Role clerk2
Schema guest
Also,assumethatthelocaladministratorsforhqandsaleshaveissuedstatements asfollows:
Database hq CREATEStatements
CREATEUSERguestIDENTIFIEDGLOBALLYAS''; CREATEROLEclerk1GRANTselectONemp; CREATEPUBLICDATABASELINKsales_linkCONNECTASCURRENT_USER USING'sales';
sales
CREATEUSERguestIDENTIFIEDGLOBALLYAS''; CREATEROLEclerk2GRANTselectONdept;
EnterpriseuserscottisauthenticatedusingSSLorapassword. Userscottissuesthefollowingstatement:
SELECTe.ename,d.loc FROMempe,dept@sales_linkd WHEREe.deptno=d.deptno;
3. 4.
DatabaseshqandsalesmutuallyauthenticateoneanotherusingSSL. Databasehqqueriestheenterprisedirectoryservicetodeterminewhether enterpriseuserscotthasaccesstohq,anddiscoversscottcanaccesslocal schemaguestusingroleclerk1. Databasesalesqueriestheenterprisedirectoryservicetodeterminewhether enterpriseuserscotthasaccesstosales,anddiscoversscottcanaccess localschemaguestusingroleclerk2. Enterpriseuserscottlogsintosalestoschemaguestwithroleclerk2and issuesaSELECTtoobtaintherequiredinformationandtransferittohq. Databasehqreceivestherequesteddatafromsalesandreturnsittotheclient scott.
5.
6. 7.
DistributedDatabaseAdministration
OracleAdvancedSecurityAdministrator'sGuideformore informationaboutenterpriseusersecurity
SeeAlso:
DataEncryption
TheOracleAdvancedSecurityoptionalsoenablesOracleNetandrelatedproducts tousenetworkdataencryptionandchecksummingsothatdatacannotbereador altered.ItprotectsdatafromunauthorizedviewingbyusingtheRSADataSecurity RC4ortheDataEncryptionStandard(DES)encryptionalgorithm. Toensurethatdatahasnotbeenmodied,deleted,orreplayedduring transmission,thesecurityservicesoftheOracleAdvancedSecurityoptioncan generateacryptographicallysecuremessagedigestandincludeitwitheachpacket sentacrossthenetwork. OracleAdvancedSecurityAdministrator'sGuideformore informationabouttheseandotherfeaturesoftheOracleAdvanced Securityoption
SeeAlso:
AuditingDatabaseLinks
Youmustalwaysperformauditingoperationslocally.Thatis,ifauseractsinalocal databaseandaccessesaremotedatabasethroughadatabaselink,thelocalactions areauditedinthelocaldatabase,andtheremoteactionsareauditedintheremote database,providedappropriateauditoptionsaresetintherespectivedatabases. Theremotedatabasecannotdeterminewhetherasuccessfulconnectrequestand subsequentSQLstatementscomefromanotherserverorfromalocallyconnected client.Forexample,assumethefollowing:
Youcanaudittheglobalusernameforglobalusers.
DistributedDatabaseAdministration
AdministrationTools
Thedatabaseadministratorhasseveralchoicesfortoolstousewhenmanagingan OracleDatabasedistributeddatabasesystem:
EnterpriseManager
EnterpriseManageristheOracleDatabaseadministrationtoolthatprovidesa graphicaluserinterface(GUI).EnterpriseManagerprovidesadministrative functionalityfordistributeddatabasesthroughaneasytouseinterface.Youcanuse EnterpriseManagerto:
Administermultipledatabases.YoucanuseEnterpriseManagertoadministera
singledatabaseortosimultaneouslyadministermultipledatabases.
featureifyouneedtoexecutelengthystatementsrepeatedlyinadistributed databasesystem.
Managesecurityfeaturessuchasglobalusers,globalroles,andtheenterprise directoryservice.
ThirdPartyAdministrationTools
Currentlymorethan60companiesproducemorethan150productsthathelp manageOracleDatabasesandnetworks,providingatrulyopenenvironment.
TransactionProcessinginaDistributedSystem
SNMPSupport
Besidesitsnetworkadministrationcapabilities,OracleSimpleNetwork ManagementProtocol(SNMP)supportallowsanOracleDatabaseservertobe locatedandqueriedbyanySNMPbasednetworkmanagementsystem.SNMPis theacceptedstandardunderlyingmanypopularnetworkmanagementsystems suchas:
informationaboutSNMP
OracleSNMPSupportReferenceGuideformore
TransactionProcessinginaDistributedSystem
AtransactionisalogicalunitofworkconstitutedbyoneormoreSQLstatements executedbyasingleuser.Atransactionbeginswiththeuser'srstexecutableSQL statementandendswhenitiscommittedorrolledbackbythatuser. Aremotetransactioncontainsonlystatementsthataccessasingleremotenode.A distributedtransactioncontainsstatementsthataccessmorethanonenode. Thefollowingsectionsdeneimportantconceptsintransactionprocessingand explainhowtransactionsaccessdatainadistributeddatabase:
TransactionProcessinginaDistributedSystem
RemoteSQLStatements
Aremotequerystatementisaquerythatselectsinformationfromoneormore remotetables,allofwhichresideatthesameremotenode.Forexample,the followingqueryaccessesdatafromthedepttableinthescottschemaofthe remotesalesdatabase:
SELECT*FROMscott.dept@sales.us.americas.acme_auto.com;
DistributedSQLStatements
Adistributedquerystatementretrievesinformationfromtwoormorenodes.For example,thefollowingqueryaccessesdatafromthelocaldatabaseaswellasthe remotesalesdatabase:
SELECTename,dname FROMscott.empe,scott.dept@sales.us.americas.acme_auto.comd WHEREe.deptno=d.deptno;
TransactionProcessinginaDistributedSystem
WHEREdeptno=10;
END;
COMMIT;
Thedatabasesendsstatementsintheprogramtotheremotenodes,andtheir executionsucceedsorfailsasaunit.
SharedSQLforRemoteandDistributedStatements
ThemechanicsofaremoteordistributedstatementusingsharedSQLare essentiallythesameasthoseofalocalstatement.TheSQLtextmustmatch,andthe referencedobjectsmustmatch.Ifavailable,sharedSQLareascanbeusedforthe localandremotehandlingofanystatementordecomposedquery.
SeeAlso:
sharedSQL
OracleDatabaseConceptsformoreinformationabout
RemoteTransactions
Aremotetransactioncontainsoneormoreremotestatements,allofwhichreference
asingleremotenode.Forexample,thefollowingtransactioncontainstwo statements,eachofwhichaccessestheremotesalesdatabase:
UPDATEscott.dept@sales.us.americas.acme_auto.com SETloc='NEWYORK' WHEREdeptno=10; UPDATEscott.emp@sales.us.americas.acme_auto.com SETdeptno=11 WHEREdeptno=10; COMMIT;
DistributedTransactions
Adistributedtransactionisatransactionthatincludesoneormorestatementsthat, individuallyorasagroup,updatedataontwoormoredistinctnodesofa distributeddatabase.Forexample,thistransactionupdatesthelocaldatabaseand theremotesalesdatabase:
UPDATEscott.dept@sales.us.americas.acme_auto.com SETloc='NEWYORK' WHEREdeptno=10; UPDATEscott.emp SETdeptno=11 WHEREdeptno=10;
TransactionProcessinginaDistributedSystem
COMMIT;
Ifallstatementsofatransactionreferenceonlyasingle remotenode,thetransactionisremote,notdistributed.
Note:
TwoPhaseCommitMechanism
Adatabasemustguaranteethatallstatementsinatransaction,distributedor nondistributed,eithercommitorrollbackasaunit.Theeffectsofanongoing transactionshouldbeinvisibletoallothertransactionsatallnodes;this transparencyshouldbetruefortransactionsthatincludeanytypeofoperation, includingqueries,updates,orremoteprocedurecalls.
Thegeneralmechanismsoftransactioncontrolinanondistributeddatabaseare discussedintheOracleDatabaseConcepts.Inadistributeddatabase,thedatabase
mustcoordinatetransactioncontrolwiththesamecharacteristicsoveranetwork andmaintaindataconsistency,evenifanetworkorsystemfailureoccurs.
Thedatabasetwophasecommitmechanismguaranteesthatalldatabaseservers
DatabaseLinkNameResolution
Aglobalobjectnameisanobjectspeciedusingadatabaselink.Theessential componentsofaglobalobjectnameare:
Thefollowingtableshowsthecomponentsofanexplicitlyspeciedglobaldatabase objectname:
TransactionProcessinginaDistributedSystem
NameResolutionWhentheGlobalDatabaseNameIsComplete
AssumethatyouissuethefollowingSQLstatement,whichspeciesacomplete globaldatabasename:
SELECT*FROMemp@prod1.us.oracle.com;
NameResolutionWhentheGlobalDatabaseNameIsPartial
Ifanypartofthedomainisspecied,thedatabaseassumesthatacompleteglobal databasenameisspecied.IfaSQLstatementspeciesapartialglobaldatabase name(thatis,onlythedatabasecomponentisspecied),thedatabaseappendsthe valueintheDB_DOMAINinitializationparametertothevalueintheDB_NAME
TransactionProcessinginaDistributedSystem
initializationparametertoconstructacompletename.Forexample,assumeyou issuethefollowingstatements:
CONNECTscott/tiger@locdb SELECT*FROMscott.emp@orders;
NameResolutionWhenNoGlobalDatabaseNameIsSpecified
Ifaglobalobjectnamereferencesanobjectinthelocaldatabaseandadatabaselink nameisnotspeciedusingthe@symbol,thenthedatabaseautomaticallydetects thattheobjectislocalanddoesnotsearchfororusedatabaselinkstoresolvethe objectreference.Forexample,assumethatyouissuethefollowingstatements:
CONNECTscott/tiger@locdb SELECT*fromscott.emp;
Becausethesecondstatementdoesnotspecifyaglobaldatabasenameusinga databaselinkconnectstring,thedatabasedoesnotsearchfordatabaselinks.
TerminatingtheSearchforNameResolution
Thedatabasedoesnotnecessarilystopsearchingformatchingdatabaselinkswhen itndstherstmatch.Thedatabasemustsearchformatchingprivate,public,and networkdatabaselinksuntilitdeterminesacompletepathtotheremotedatabase (botharemoteaccountandservicename). Therstmatchdeterminestheremoteschemaasillustratedinthefollowingtable:
UserOperation Donotspecifythe CONNECTclause Dospecifythe CONNECTTO... IDENTIFIEDBY clause DatabaseResponse Usesaconnecteduser databaselink Usesaxeduser databaselink Example CREATEDATABASELINKk1USING 'prod' CREATEDATABASELINKk2 CONNECTTOscottIDENTIFIEDBY tigerUSING'prod'
TransactionProcessinginaDistributedSystem
DatabaseResponse Usesacurrentuser databaselink Searchesuntilitndsa linkspecifyinga databasestring.If matchingdatabase linksarefoundanda stringisnever identied,thedatabase returnsanerror.
SchemaObjectNameResolution
AfterthelocalOracleDatabaseconnectstothespeciedremotedatabaseonbehalf ofthelocaluserthatissuedtheSQLstatement,objectresolutioncontinuesasifthe remoteuserhadissuedtheassociatedSQLstatement.Therstmatchdetermines theremoteschemaaccordingtothefollowingrules:
TypeofLinkSpecied Axeduserdatabaselink Aconnecteduserdatabaselink Acurrentuserdatabaselink LocationofObjectResolution Schemaspeciedinthelinkcreationstatement Connecteduser'sremoteschema Currentuser'sschema
TransactionProcessinginaDistributedSystem
ExampleofGlobalObjectNameResolution:CompleteObjectName
Thisexampleillustrateshowthedatabaseresolvesacompleteglobalobjectname anddeterminestheappropriatepathtotheremotedatabaseusingbothaprivate andpublicdatabaselink.Forthisexample,assumethefollowing:
Considerthefollowingstatementsissuedbyscottatthelocaldatabase:
CONNECTscott/tiger@hq
Later,JWARDconnectsandissuesthefollowingstatements:
CONNECTjward/bronco@hq
Thedatabaseprocessesthenalstatementasfollows:
1.
Thedatabasedeterminesthatacompleteglobalobjectnameisreferencedin jward'sUPDATEstatement.Therefore,thesystembeginssearchinginthelocal databaseforadatabaselinkwithamatchingname. Thedatabasendsamatchingprivatedatabaselinkintheschemajward. Nevertheless,theprivatedatabaselink jward.sales.division3.acme.comdoesnotindicateacompletepathto theremotesalesdatabase,onlyaremoteaccount.Therefore,thedatabasenow searchesforamatchingpublicdatabaselink. Thedatabasendsthepublicdatabaselinkinscott'sschema.Fromthis publicdatabaselink,thedatabasetakestheservicenamedbstring.
2.
3.
TransactionProcessinginaDistributedSystem
4.
5. 6.
ExampleofGlobalObjectNameResolution:PartialObjectName
Thisexampleillustrateshowthedatabaseresolvesapartialglobalobjectnameand determinestheappropriatepathtotheremotedatabaseusingbothaprivateand publicdatabaselink. Forthisexample,assumethat:
Theremotedatabaseisnamedsales.division3.acme.com. Thelocaldatabaseisnamedhq.division3.acme.com. Adirectoryserver(andtherefore,globaldatabaselinks)isnotavailable. Atableempontheremotedatabasesalesiscontainedintheschematsmith, butnotinschemascott. Apublicsynonymnamedempresidesatremotedatabasesalesandpointsto tsmith.empintheremotedatabasesales. Thepublicdatabaselinkin"ExampleofGlobalObjectNameResolution: CompleteObjectName" onpage2940 isalreadycreatedonlocaldatabasehq:
CREATEPUBLICDATABASELINKsales.division3.acme.com CONNECTTOguestIDENTIFIEDBYnetwork USING'dbstring';
Considerthefollowingstatementsissuedatlocaldatabasehq:
CONNECTscott/tiger@hq
ThedatabaseprocessesthenalDELETEstatementasfollows:
TransactionProcessinginaDistributedSystem
1.
2. 3.
4. 5. 6. 7.
GlobalNameResolutioninViews,Synonyms,andProcedures
Aview,synonym,orPL/SQLprogramunit(forexample,aprocedure,function,or trigger)canreferencearemoteschemaobjectbyitsglobalobjectname.Iftheglobal
objectnameiscomplete,thenthedatabasestoresthedenitionoftheobjectwithout
expandingtheglobalobjectname.Ifthenameispartial,however,thedatabase expandsthenameusingthedomainofthelocaldatabasename.
Thefollowingtableexplainswhenthedatabasecompletestheexpansionofapartial
globalobjectnameforviews,synonyms,andprogramunits:
TransactionProcessinginaDistributedSystem
UserOperation Createaview
Createasynonym
Compileaprogramunit
WhatHappensWhenGlobalNamesChange
Globalnamechangescanaffectviews,synonyms,andproceduresthatreference remotedatausingpartialglobalobjectnames.Iftheglobalnameofthereferenced databasechanges,viewsandproceduresmaytrytoreferenceanonexistentor incorrectdatabase.Ontheotherhand,synonymsdonotexpanddatabaselink namesatruntime,sotheydonotchange.
ScenariosforGlobalNameChanges
Forexample,considertwodatabasesnamedsales.uk.acme.comand hq.uk.acme.com.Also,assumethatthesalesdatabasecontainsthefollowing viewandsynonym:
CREATEVIEWemployee_namesAS SELECTenameFROMscott.emp@hr; CREATESYNONYMemployeeFORscott.emp@hr;
sales.uk.acme.combecomessales.us.acme.com hq.uk.acme.combecomeshq.us.acme.com
Thefollowingtabledescribesqueryexpansionbeforeandafterthechangeinglobal names:
DistributedDatabaseApplicationDevelopment
sales.uk.acme.combecomessales.us.acme.com hq.uk.acme.comisnotchanged
Thefollowingtabledescribesqueryexpansionbeforeandafterthechangeinglobal names:
Queryonsales SELECT*FROM employee_names SELECT*FROM employee ExpansionBeforeChange SELECT*FROM scott.emp@hr.uk.acme.com SELECT*FROM scott.emp@hr.uk.acme.com ExpansionAfterChange SELECT*FROM scott.emp@hr.us.acme.com SELECT*FROM scott.emp@hr.uk.acme.com
DistributedDatabaseApplicationDevelopment
Applicationdevelopmentinadistributedsystemraisesissuesthatarenot applicableinanondistributedsystem.Thissectioncontainsthefollowingtopics relevantfordistributedapplicationdevelopment:
DistributedDatabaseApplicationDevelopment
TransparencyinaDistributedDatabaseSystem
Withminimaleffort,youcandevelopapplicationsthatmakeanOracleDatabase distributeddatabasesystemtransparenttousersthatworkwiththesystem.The goaloftransparencyistomakeadistributeddatabasesystemappearasthoughitis asingleOracleDatabase.Consequently,thesystemdoesnotburdendevelopersand usersofthesystemwithcomplexitiesthatwouldotherwisemakedistributed databaseapplicationdevelopmentchallenginganddetractfromuserproductivity. Thefollowingsectionsexplainmoreabouttransparencyinadistributeddatabase system.
LocationTransparency
AnOracleDatabasedistributeddatabasesystemhasfeaturesthatallowapplication developersandadministratorstohidethephysicallocationofdatabaseobjectsfrom applicationsandusers.Locationtransparencyexistswhenausercanuniversally refertoadatabaseobjectsuchasatable,regardlessofthenodetowhichan applicationconnects.Locationtransparencyhasseveralbenets,including:
Now,ratherthanaccesstheremotetableswithaquerysuchas:
SELECTename,dname FROMscott.emp@sales.us.americas.acme_auto.come, scott.dept@sales.us.americas.acme_auto.comd
DistributedDatabaseApplicationDevelopment
WHEREe.deptno=d.deptno;
Anapplicationcanissueamuchsimplerquerythatdoesnothavetoaccountforthe locationoftheremotetables.
SELECTename,dname FROMempe,deptd WHEREe.deptno=d.deptno;
Inadditiontosynonyms,developerscanalsouseviewsandstoredproceduresto establishlocationtransparencyforapplicationsthatworkinadistributeddatabase system. SQLandCOMMITTransparency TheOracleDatabasedistributeddatabasearchitecturealsoprovidesquery,update, andtransactiontransparency.Forexample,standardSQLstatementssuchas SELECT,INSERT,UPDATE,andDELETEworkjustastheydoinanondistributed databaseenvironment.Additionally,applicationscontroltransactionsusingthe standardSQLstatementsCOMMIT,SAVEPOINT,andROLLBACK.Thereisno requirementforcomplexprogrammingorotherspecialoperationstoprovide distributedtransactioncontrol.
DistributedDatabaseApplicationDevelopment
ReplicationTransparency
Thedatabasealsoprovidemanyfeaturestotransparentlyreplicatedataamongthe nodesofthesystem.FormoreinformationaboutOracleDatabasereplication features,seeOracleDatabaseAdvancedReplication.
RemoteProcedureCalls(RPCs)
DeveloperscancodePL/SQLpackagesandprocedurestosupportapplicationsthat workwithadistributeddatabase.Applicationscanmakelocalprocedurecallsto performworkatthelocaldatabaseandremoteprocedurecalls(RPCs)toperform workataremotedatabase. Whenaprogramcallsaremoteprocedure,thelocalserverpassesallprocedure parameterstotheremoteserverinthecall.Forexample,thefollowingPL/SQL programunitcallsthepackagedproceduredel_emplocatedattheremotesales databaseandpassesittheparameter1257:
BEGIN emp_mgmt.del_emp@sales.us.americas.acme_auto.com(1257);
END;
DistributedQueryOptimization
DistributedqueryoptimizationisanOracleDatabasefeaturethatreducesthe amountofdatatransferrequiredbetweensiteswhenatransactionretrievesdata fromremotetablesreferencedinadistributedSQLstatement. Distributedqueryoptimizationusescostbasedoptimizationtondorgenerate SQLexpressionsthatextractonlythenecessarydatafromremotetables,process thatdataataremotesiteorsometimesatthelocalsite,andsendtheresultstothe
CharacterSetSupportforDistributedEnvironments
CharacterSetSupportforDistributedEnvironments
OracleDatabasesupportsenvironmentsinwhichclients,OracleDatabaseservers, andnonOracleDatabaseserversusedifferentcharactersets.NCHARsupportis providedforheterogeneousenvironments.YoucansetavarietyofNational LanguageSupport(NLS)andHeterogeneousServices(HS)environmentvariables andinitializationparameterstocontroldataconversionbetweendifferentcharacter sets. CharactersettingsaredenedbythefollowingNLSandHSparameters:
Parameters NLS_LANG (environmentvariable) NLS_LANGUAGE NLS_CHARACTERSET NLS_TERRITORY HS_LANGUAGE Environment ClientServer ClientServer NotHeterogeneousDistributed HeterogeneousDistributed HeterogeneousDistributed NonOracleDatabase server Transparentgateway NLS_NCHAR
(environmentvariable)
HeterogeneousDistributed
OracleDatabaseserver Transparentgateway
HS_NLS_NCHAR
CharacterSetSupportforDistributedEnvironments
SeeAlso:
OracleDatabaseGlobalizationSupportGuideforinformation
aboutNLSparameters
OracleDatabaseHeterogeneousConnectivityAdministrator'sGuide
forinformationaboutHSparameters
Client/ServerEnvironment
Inaclient/serverenvironment,settheclientcharactersettobethesameasora subsetoftheOracleDatabaseservercharacterset,asillustratedinFigure296 :
Figure296 NLSParameterSettingsinaClientServerEnvironment
Oracle
HomogeneousDistributedEnvironment
Inanonheterogeneousenvironment,theclientandservercharactersetsshouldbe eitherthesameasorsubsetsofthemainservercharacterset,asillustratedin Figure297 :
CharacterSetSupportforDistributedEnvironments
Figure297
NLSParameterSettingsinaHomogeneousEnvironment
Oracle
Oracle
HeterogeneousDistributedEnvironment
Inaheterogeneousenvironment,theNLSsettingsoftheclient,thetransparent gateway,andthenonOracleDatabasedatasourceshouldbeeitherthesameora subsetofthedatabaseservercharactersetasillustratedinFigure298.Transparent gatewayshavefullglobalizationsupport.
CharacterSetSupportforDistributedEnvironments
Figure298
NLSParameterSettingsinaHeterogeneousEnvironment
Oracle
NonOracle
Administrator'sGuideformoredetailedinformationabout HeterogeneousServices
CharacterSetSupportforDistributedEnvironments
ManagingaDistributedDatabase
Thischapterdescribeshowtomanageandmaintainadistributeddatabasesystem andcontainsthefollowingtopics:
ManagingGlobalNamesinaDistributedSystem
Inadistributeddatabasesystem,eachdatabaseshouldhaveauniqueglobal databasename.Globaldatabasenamesuniquelyidentifyadatabaseinthesystem. Aprimaryadministrationtaskinadistributedsystemismanagingthecreationand alterationofglobaldatabasenames. Thissectioncontainsthefollowingtopics:
ManagingGlobalNamesinaDistributedSystem
ChangingaGlobalDatabaseName:Scenario
UnderstandingHowGlobalDatabaseNamesAreFormed
Aglobaldatabasenameisformedfromtwocomponents:adatabasenameanda domain.Thedatabasenameandthedomainnamearedeterminedbythefollowing initializationparametersatdatabasecreation:
Component Databasename Domain containingthe database Parameter DB_NAME DB_DOMAIN Requirements Mustbeeightcharactersorless. MustfollowstandardInternet conventions.Levelsindomain namesmustbeseparatedbydots andtheorderofdomainnamesis fromleaftoroot,lefttoright. Example sales us.acme.com
Theseareexamplesofvalidglobaldatabasenames:
DB_NAME sales
sales
mktg payroll
DeterminingWhetherGlobalNamingIsEnforced
Thenamethatyougivetoalinkonthelocaldatabasedependsonwhetherthe remotedatabasethatyouwanttoaccessenforcesglobalnaming.Iftheremote databaseenforcesglobalnaming,thenyoumustusetheremotedatabaseglobal databasenameasthenameofthelink.Forexample,ifyouareconnectedtothe
ManagingGlobalNamesinaDistributedSystem
HQ.ACME.COM@SN1 HQ.ACME.COM@SN2
SeeAlso: "UsingConnectionQualierstoSpecifyServiceNames WithinLinkNames" onpage3013 formoreinformationabout usingservicesnamesinlinknames
/
SQL>@globalnames NAMEVALUE global_namesFALSE
ViewingaGlobalDatabaseName
UsethedatadictionaryviewGLOBAL_NAMEtoviewthedatabaseglobalname.For example,issuethefollowing:
SELECT*FROMGLOBAL_NAME;
GLOBAL_NAME SALES.AU.ORACLE.COM
ManagingGlobalNamesinaDistributedSystem
ChangingtheDomaininaGlobalDatabaseName
UsetheALTERDATABASEstatementtochangethedomaininadatabaseglobal name.Notethatafterthedatabaseiscreated,changingtheinitializationparameter DB_DOMAINhasnoeffectontheglobaldatabasenameorontheresolutionof databaselinknames. Thefollowingexampleshowsthesyntaxfortherenamingstatement,wheredatabase isadatabasenameanddomainisthenetworkdomain:
ALTERDATABASERENAMEGLOBAL_NAMETO
database.domain;
Usethefollowingproceduretochangethedomaininaglobaldatabasename:
1.
Determinethecurrentglobaldatabasename.Forexample,issue:
SELECT*FROMGLOBAL_NAME;
GLOBAL_NAME SALES.AU.ORACLE.COM
2.
RenametheglobaldatabasenameusinganALTERDATABASEstatement.For example,enter:
ALTERDATABASERENAMEGLOBAL_NAMETOsales.us.oracle.com;
3.
QuerytheGLOBAL_NAMEtabletocheckthenewname.Forexample,enter:
SELECT*FROMGLOBAL_NAME;
GLOBAL_NAME
SALES.US.ORACLE.COM
ChangingaGlobalDatabaseName:Scenario
Inthisscenario,youchangethedomainpartoftheglobaldatabasenameofthe localdatabase.Youalsocreatedatabaselinksusingpartiallyspeciedglobalnames totesthowOracleDatabaseresolvesthenames.Youdiscoverthatthedatabase resolvesthepartialnamesusingthedomainpartofthecurrentglobaldatabase nameofthelocaldatabase,notthevaluefortheinitializationparameterDB_ DOMAIN.
1.
YouconnecttoSALES.US.ACME.COMandquerytheGLOBAL_NAMEdata dictionaryviewtodeterminethecurrentdatabaseglobalname:
ManagingGlobalNamesinaDistributedSystem
2.
YouquerytheV$PARAMETERviewtodeterminethecurrentsettingfortheDB_ DOMAINinitializationparameter:
SELECTNAME,VALUEFROMV$PARAMETERWHERENAME='db_domain';
NAMEVALUE db_domainUS.ACME.COM
3.
Youthencreateadatabaselinktoadatabasecalledhq,usingonlya partiallyspeciedglobalname:
CREATEDATABASELINKhqUSING'sales';
YouqueryUSER_DB_LINKStodeterminewhichdomainnamethedatabase usestoresolvethepartiallyspeciedglobaldatabasename:
SELECTDB_LINKFROMUSER_DB_LINKS;
DB_LINK HQ.US.ACME.COM
BecauseyouhavereceivedwordthatthesalesdatabasewillmovetoJapan, yourenamethesalesdatabasetosales.jp.acme.com:
ALTERDATABASERENAMEGLOBAL_NAMETOsales.jp.acme.com; SELECT*FROMGLOBAL_NAME; GLOBAL_NAME
ManagingGlobalNamesinaDistributedSystem
SALES.JP.ACME.COM
6.
ManagingGlobalNamesinaDistributedSystem
SALES.ASIA.JP.ACME.COM
9.
YouqueryV$PARAMETERtoagaincheckthesettingfortheparameterDB_ DOMAIN:
SELECTNAME,VALUEFROMV$PARAMETER WHERENAME='db_domain'; NAMEVALUE db_domainUS.ACME.COM
DB_LINKStodeterminehowthedatabaseresolvesthepartiallyspecied globalname:
CREATEDATABASELINKwarehouseUSING'warehouse'; SELECTDB_LINKFROMUSER_DB_LINKS; DB_LINK HQ.US.ACME.COM SUPPLY.JP.ACME.COM WAREHOUSE.ASIA.JP.ACME.COM
CreatingDatabaseLinks
CreatingDatabaseLinks
Tosupportapplicationaccesstothedataandschemaobjectsthroughouta distributeddatabasesystem,youmustcreateallnecessarydatabaselinks.This sectioncontainsthefollowingtopics:
ObtainingPrivilegesNecessaryforCreatingDatabaseLinks
Adatabaselinkisapointerinthelocaldatabasethatletsyouaccessobjectsona remotedatabase.Tocreateaprivatedatabaselink,youmusthavebeengrantedthe properprivileges.Thefollowingtableillustrateswhichprivilegesarerequiredon whichdatabaseforwhichtypeoflink:
Privilege CREATEDATABASELINK CREATEPUBLICDATABASELINK CREATESESSION Database Local Local Remote RequiredFor Creationofaprivatedatabaselink. Creationofapublicdatabaselink. Creationofanytypeofdatabaselink.
/
SQL>@privs DatabaseLinkPrivileges CREATEDATABASELINK CREATEPUBLICDATABASELINK CREATESESSION
CreatingDatabaseLinks
SpecifyingLinkTypes
Whenyoucreateadatabaselink,youmustdecidewhowillhaveaccesstoit.The followingsectionsdescribehowtocreatethethreebasictypesoflinks:
CreatingPrivateDatabaseLinks
Tocreateaprivatedatabaselink,specifythefollowing(wherelink_nameisthe globaldatabasenameoranarbitrarylinkname):
CREATEDATABASELINK
link_name...;
Followingareexamplesofprivatedatabaselinks:
SQLStatement CREATEDATABASELINK supply.us.acme.com; Result Aprivatelinkusingtheglobaldatabasenametothe remotesupplydatabase. Thelinkusestheuserid/passwordoftheconnected user.Soifscott(identiedbytiger)usesthelink inaquery,thelinkestablishesaconnectiontothe remotedatabaseasscott/tiger. CREATEDATABASELINKlink_2 CONNECTTOjaneIDENTIFIED BYdoeUSING'us_supply'; Aprivatexeduserlinkcalledlink_2tothe databasewithservicenameus_supply.Thelink connectstotheremotedatabasewiththe userid/passwordofjane/doeregardlessofthe connecteduser. Aprivatelinkcalledlink_1tothedatabasewith servicenameus_supply.Thelinkusesthe userid/passwordofthecurrentusertologontothe remotedatabase. Note:Thecurrentusermaynotbethesameasthe connecteduser,andmustbeaglobaluseronboth databasesinvolvedinthelink(see"Usersof DatabaseLinks" onpage2916). Currentuserlinks arepartoftheOracleAdvancedSecurityoption. SeeAlso: OracleDatabaseSQLReferenceforCREATEDATABASE
CREATEDATABASELINKlink_1
CONNECTTOCURRENT_USER USING'us_supply';
LINKsyntax
CreatingDatabaseLinks
CreatingPublicDatabaseLinks
Tocreateapublicdatabaselink,usethekeywordPUBLIC(wherelink_nameisthe globaldatabasenameoranarbitrarylinkname):
CREATEPUBLICDATABASELINK
link_name...;
Followingareexamplesofpublicdatabaselinks:
SQLStatement CREATEPUBLICDATABASELINK supply.us.acme.com; Result Apubliclinktotheremotesupplydatabase. Thelinkusestheuserid/passwordofthe connecteduser.Soifscott(identiedby tiger)usesthelinkinaquery,thelink establishesaconnectiontotheremotedatabase asscott/tiger. Apubliclinkcalledpu_linktothedatabase withservicenamesupply.Thelinkusesthe userid/passwordofthecurrentusertolog ontotheremotedatabase. Note:Thecurrentusermaynotbethesameas theconnecteduser,andmustbeaglobaluser onbothdatabasesinvolvedinthelink(see "UsersofDatabaseLinks" onpage2916).
CREATEPUBLICDATABASELINK
CREATEPUBLICDATABASELINK pu_linkCONNECTTOCURRENT_
USERUSING'supply';
sales.us.acme.comCONNECTTO janeIDENTIFIEDBYdoe;
SeeAlso:
DATABASELINKsyntax
OracleDatabaseSQLReferenceforCREATEPUBLIC
CreatingGlobalDatabaseLinks
Inearlierreleases,youdenedglobaldatabaselinksintheOracleNamesserver. TheOracleNamesserverhasbeendeprecated.Now,youcanuseadirectoryserver inwhichdatabasesareidentiedbynetservicenames.Inthisdocumenttheseare whatarereferredtoasglobaldatabaselinks. SeetheOracleNetServicesAdministrator'sGuidetolearnhowtocreatedirectory entriesthatactasglobaldatabaselinks.
CreatingDatabaseLinks
SpecifyingLinkUsers
Adatabaselinkdenesacommunicationpathfromonedatabasetoanother.When anapplicationusesadatabaselinktoaccessaremotedatabase,OracleDatabase establishesadatabasesessionintheremotedatabaseonbehalfofthelocal applicationrequest. Whenyoucreateaprivateorpublicdatabaselink,youcandeterminewhich schemaontheremotedatabasethelinkwillestablishconnectionstobycreating xeduser,currentuser,andconnecteduserdatabaselinks.
CreatingFixedUserDatabaseLinks
Tocreateaxeduserdatabaselink,youembedthecredentials(inthiscase,a usernameandpassword)requiredtoaccesstheremotedatabaseinthedenitionof thelink:
CREATEDATABASELINK...CONNECTTO
usernameIDENTIFIEDBY
password...;
Followingareexamplesofxeduserdatabaselinks:
SQLStatement CREATEPUBLICDATABASELINK supply.us.acme.comCONNECT TOscottAStiger; CREATEDATABASELINKfoo CONNECTTOjaneIDENTIFIED BYdoeUSING'finance'; Result Apubliclinkusingtheglobaldatabasenametothe remotesupplydatabase.Thelinkconnectstothe remotedatabasewiththeuserid/password scott/tiger. Aprivatexeduserlinkcalledfootothedatabase withservicenamefinance.Thelinkconnectsto theremotedatabasewiththeuserid/password jane/doe.
CreatingConnectedUserandCurrentUserDatabaseLinks
Connecteduserandcurrentuserdatabaselinksdonotincludecredentialsinthe denitionofthelink.Thecredentialsusedtoconnecttotheremotedatabasecan changedependingontheuserthatreferencesthedatabaselinkandtheoperation performedbytheapplication.
CreatingDatabaseLinks
dblink...[USING'net_service_name'];
Forexample,tocreateaconnecteduserdatabaselink,usethefollowingsyntax:
CREATEDATABASELINKsales.division3.acme.comUSING'sales';
CreatingaCurrentUserDatabaseLink Tocreateacurrentuserdatabaselink,usethe
dblinkCONNECTTOCURRENT_USER
Forexample,tocreateaconnecteduserdatabaselinktothesalesdatabase,you mightusethefollowingsyntax:
CREATEDATABASELINKsalesCONNECTTOCURRENT_USERUSING'sales';
Touseacurrentuserdatabaselink,thecurrentusermustbe aglobaluseronbothdatabasesinvolvedinthelink.
Note: SeeAlso: OracleDatabaseSQLReferenceformoresyntax
informationaboutcreatingdatabaselinks
CreatingDatabaseLinks
UsingConnectionQualierstoSpecifyServiceNamesWithinLinkNames
Insomesituations,youmaywanttohaveseveraldatabaselinksofthesametype (forexample,public)thatpointtothesameremotedatabase,yetestablish connectionstotheremotedatabaseusingdifferentcommunicationpathways.Some casesinwhichthisstrategyisusefulare:
Notethatinthisexample,therearetwo@symbols.
UsingSharedDatabaseLinks
UsingSharedDatabaseLinks
Everyapplicationthatreferencesaremoteserverusingastandarddatabaselink establishesaconnectionbetweenthelocaldatabaseandtheremotedatabase.Many usersrunningapplicationssimultaneouslycancauseahighnumberofconnections betweenthelocalandremotedatabases. Shareddatabaselinksenableyoutolimitthenumberofnetworkconnections requiredbetweenthelocalserverandtheremoteserver. Thissectioncontainsthefollowingtopics:
DeterminingWhethertoUseSharedDatabaseLinks
Lookcarefullyatyourapplicationandsharedservercongurationtodetermine whethertousesharedlinks.Asimpleguidelineistouseshareddatabaselinks whenthenumberofusersaccessingadatabaselinkisexpectedtobemuchlarger thanthenumberofserverprocessesinthelocaldatabase. Thefollowingtableillustratesthreepossiblecongurationsinvolvingdatabase links:
LinkType Nonshared ServerMode Dedicated/shared server Consequences Ifyourapplicationusesastandardpublicdatabase link,and100userssimultaneouslyrequirea connection,then100directnetworkconnectionsto theremotedatabasearerequired. If10sharedserverprocessesexistinthelocal sharedservermodedatabase,then100usersthat usethesamedatabaselinkrequire10orfewer networkconnectionstotheremoteserver.Each localsharedserverprocessmayonlyneedone connectiontotheremoteserver.
Shared
Sharedserver
UsingSharedDatabaseLinks
LinkType Shared
ServerMode Dedicated
Shareddatabaselinksarenotusefulinallsituations.Assumethatonlyoneuser accessestheremoteserver.Ifthisuserdenesashareddatabaselinkand10shared serverprocessesexistinthelocaldatabase,thenthisusercanrequireupto10 networkconnectionstotheremoteserver.Becausetheusercanuseeachshared serverprocess,eachprocesscanestablishaconnectiontotheremoteserver. Clearly,anonshareddatabaselinkispreferableinthissituationbecauseitrequires onlyonenetworkconnection.Shareddatabaselinksleadtomorenetwork connectionsinsingleuserscenarios,sousesharedlinksonlywhenmanyusers needtousethesamelink.Typically,sharedlinksareusedforpublicdatabaselinks, butcanalsobeusedforprivatedatabaselinkswhenmanyclientsaccessthesame localschema(andthereforethesameprivatedatabaselink). Inamultitieredenvironment,thereisarestrictionthatif youuseashareddatabaselinktoconnecttoaremotedatabase, thenthatremotedatabasecannotlinktoanotherdatabasewitha databaselinkthatcannotbemigrated.Thatlinkmustuseashared server,oritmustbeanothershareddatabaselink.
Note:
CreatingSharedDatabaseLinks
Tocreateashareddatabaselink,usethekeywordSHAREDintheCREATE DATABASELINK statement:
dblink_name usernameIDENTIFIEDBY password]|[CONNECTTOCURRENT_USER] AUTHENTICATEDBY schema_nameIDENTIFIEDBY password [USING'service_name'];
CREATESHAREDDATABASELINK [CONNECTTO
Thefollowingexamplecreatesaxeduser,sharedlinktodatabasesales, connectingasscottandauthenticatedaskeith:
CREATESHAREDDATABASELINKlink2sales CONNECTTOscottIDENTIFIEDBYtiger
UsingSharedDatabaseLinks
AUTHENTICATEDBYkeithIDENTIFIEDBYrichards USING'sales';
CREATEDATABASELINKstatement
OracleDatabaseSQLReferenceforinformationaboutthe
ConguringSharedDatabaseLinks
Youcancongureshareddatabaselinksinthefollowingways:
CreatingSharedLinkstoDedicatedServers CreatingSharedLinkstoSharedServers
CreatingSharedLinkstoDedicatedServers
InthecongurationillustratedinFigure301 , asharedserverprocessinthelocal serverownsadedicatedremoteserverprocess.Theadvantageisthatadirect networktransportexistsbetweenthelocalsharedserverandtheremotededicated server.Adisadvantageisthatextrabackendserverprocessesareneeded. Theremoteservercaneitherbeasharedserverordedicated server.Thereisadedicatedconnectionbetweenthelocaland remoteservers.Whentheremoteserverisasharedserver,youcan forceadedicatedserverconnectionbyusingthe (SERVER=DEDICATED)clauseinthedenitionoftheservicename.
Note:
UsingSharedDatabaseLinks
Figure301
ASharedDatabaseLinktoDedicatedServerProcesses
User Process
ClientWorkstation DatabaseServer
DispatcherProcesses
Oracle ServerCode
SystemGlobalArea
SystemGlobalArea
CreatingSharedLinkstoSharedServers
ThecongurationillustratedinFigure302 uses sharedserverprocessesonthe remoteserver.Thiscongurationeliminatestheneedformorededicatedservers, butrequirestheconnectiontogothroughthedispatcherontheremoteserver.Note thatboththelocalandtheremoteservermustbeconguredassharedservers.
ManagingDatabaseLinks
Figure302
SharedDatabaseLinktoSharedServer
User Process User Process
ClientWorkstation
DatabaseServer
DispatcherProcesses
DispatcherProcesses
Oracle ServerCode
Oracle ServerCode
SystemGlobalArea
SystemGlobalArea
OracleNetServicesAdministrator'sGuideforinformation aboutthesharedserveroption
SeeAlso:
ManagingDatabaseLinks
Thissectioncontainsthefollowingtopics:
ClosingDatabaseLinks DroppingDatabaseLinks
ManagingDatabaseLinks
LimitingtheNumberofActiveDatabaseLinkConnections
ClosingDatabaseLinks
Ifyouaccessadatabaselinkinasession,thenthelinkremainsopenuntilyouclose thesession.Alinkisopeninthesensethataprocessisactiveoneachoftheremote databasesaccessedthroughthelink.Thissituationhasthefollowingconsequences:
Ifyouwanttoclosealink,issuethefollowingstatement,wherelinknamerefersto thenameofthelink:
ALTERSESSIONCLOSEDATABASELINK
linkname;
Notethatthisstatementonlyclosesthelinksthatareactiveinyourcurrentsession.
DroppingDatabaseLinks
Youcandropadatabaselinkjustasyoucandropatableorview.Ifthelinkis private,thenitmustbeinyourschema.Ifthelinkispublic,thenyoumusthavethe DROPPUBLICDATABASELINKsystemprivilege. Thestatementsyntaxisasfollows,wheredblinkisthenameofthelink:
DROP[PUBLIC]DATABASELINK
dblink;
ProcedureforDroppingaPrivateDatabaseLink
1.
ConnecttothelocaldatabaseusingSQL*Plus.Forexample,enter:
ManagingDatabaseLinks
CONNECTscott/tiger@local_db
2.
QueryUSER_DB_LINKStoviewthelinksthatyouown.Forexample,enter:
SELECTDB_LINKFROMUSER_DB_LINKS;
3.
DropthedesiredlinkusingtheDROPDATABASELINKstatement.For example,enter:
DROPDATABASELINKsales.us.oracle.com;
ProcedureforDroppingaPublicDatabaseLink
1.
ConnecttothelocaldatabaseasauserwiththeDROPPUBLICDATABASE LINKprivilege.Forexample,enter:
CONNECTSYSTEM/password@local_dbASSYSDBA
2.
QueryDBA_DB_LINKStoviewthepubliclinks.Forexample,enter:
SELECTDB_LINKFROMUSER_DB_LINKS WHEREOWNER='PUBLIC'; DB_LINK DBL1.US.ORACLE.COM SALES.US.ORACLE.COM INST2.US.ORACLE.COM RMAN2.US.ORACLE.COM 4rowsselected.
3.
DropthedesiredlinkusingtheDROPPUBLICDATABASELINKstatement. Forexample,enter:
DROPPUBLICDATABASELINKsales.us.oracle.com;
LimitingtheNumberofActiveDatabaseLinkConnections
Youcanlimitthenumberofconnectionsfromauserprocesstoremotedatabases usingthestaticinitializationparameterOPEN_LINKS.Thisparametercontrolsthe
ViewingInformationAboutDatabaseLinks
ViewingInformationAboutDatabaseLinks
Thedatadictionaryofeachdatabasestoresthedenitionsofallthedatabaselinks inthedatabase.Youcanusedatadictionarytablesandviewstogaininformation aboutthelinks.Thissectioncontainsthefollowingtopics:
DeterminingWhichLinksAreintheDatabase DeterminingWhichLinkConnectionsAreOpen
DeterminingWhichLinksAreintheDatabase
Thefollowingviewsshowthedatabaselinksthathavebeendenedatthelocal databaseandstoredinthedatadictionary:
View DBA_DB_LINKS
ALL_DB_LINKS
USER_DB_LINKS
Thesedatadictionaryviewscontainthesamebasicinformationaboutdatabase links,withsomeexceptions:
ViewingInformationAboutDatabaseLinks
Description Theuserwhocreatedthedatabaselink.Ifthelinkis public,thentheuserislistedasPUBLIC. Thenameofthedatabaselink. Ifthelinkdenitionincludesaxeduser,thenthis columndisplaystheusernameofthexeduser.If thereisnoxeduser,thecolumnisNULL. Thepasswordforloggingintotheremotedatabase. Thenetservicenameusedtoconnecttotheremote database. Creationtimeofthedatabaselink.
PASSWORD
HOST CREATED
Here,thescriptisinvokedandtheresultingoutputisshown:
SQL>@link_script
AuthorizationforViewingPasswordInformation
OnlyUSER_DB_LINKScontainsacolumnforpasswordinformation.However,if youareanadministrativeuser(SYSoruserswhoconnectASSYSDBA),thenyou
ViewingInformationAboutDatabaseLinks
BeinggrantedspecicobjectprivilegefortheLINK$table BeinggrantedtheSELECTANYDICTIONARYsystemprivilege
OracleDatabaseSecurityGuideformoreinformation aboutprivilegesnecessarytoviewobjectsintheSYSschema SeeAlso:
ViewingPasswordInformation
YoucancreateandrunthefollowingscriptinSQL*Plustoobtainpassword information(sampleoutputincluded):
COLUSERIDFORMATA10 COLPASSWORDFORMATA10 SELECTUSERID,PASSWORD FROMSYS.LINK$ WHEREPASSWORDISNOTNULL
/
SQL>@linkpwd USERIDPASSWORD SYSORACLE BLAKETYGER SCOTTTIGER 3rowsselected.
ViewingAuthenticationPasswords
ItispossibletoviewAUTHENTICATEDBY...IDENTIFIEDBY...usernames andpasswordsforalllinksinthedatabasebyqueryingtheLINK$table.Youcan createandrunthefollowingscriptinSQL*Plustoobtainpasswordinformation (sampleoutputincluded):
COLAUTHUSRFORMATA10 COLAUTHPWDFORMATA10 SELECTAUTHUSRASuserid,AUTHPWDASpassword FROMSYS.LINK$ WHEREPASSWORDISNOTNULL
ViewingInformationAboutDatabaseLinks
Youcanalsoviewthelinkandpasswordinformationtogetherinajoinbycreating andexecutingthefollowingscript(sampleoutputincluded):
COLOWNERFORMATA8 COLDB_LINKFORMATA15 COLUSERNAMEFORMATA8HEADING"CON_USER" COLPASSWORDFORMATA8HEADING"CON_PWD" COLAUTHUSRFORMATA8HEADING"AUTH_USER" COLAUTHPWDFORMATA8HEADING"AUTH_PWD" COLHOSTFORMATA7HEADING"SERVICE" COLCREATEDFORMATA10 SELECTDISTINCTd.OWNER,d.DB_LINK,d.USERNAME,l.PASSWORD, l.AUTHUSR,l.AUTHPWD,d.HOST,d.CREATED FROMDBA_DB_LINKSd,SYS.LINK$l WHEREPASSWORDISNOTNULL ANDd.USERNAME=l.USERID
/
SQL>@user_and_pwd OWNERDB_LINKCON_USERCON_PWDAUTH_USEAUTH_PWDSERVICECREATED JANEDBL.ACME.COMBLAKETYGERELLIEMAYora5123JUN99 PUBLICDBL1.ACME.COMSCOTTTIGERora5123JUN99 SYSTARGET.ACME.COMSYSORACLEinst123JUN99
DeterminingWhichLinkConnectionsAreOpen
Youmaynditusefultodeterminewhichdatabaselinkconnectionsarecurrently openinyoursession.NotethatifyouconnectasSYSDBA,youcannotqueryaview todetermineallthelinksopenforallsessions;youcanonlyaccessthelink informationinthesessionwithinwhichyouareworking. Thefollowingviewsshowthedatabaselinkconnectionsthatarecurrentlyopenin yourcurrentsession:
ViewingInformationAboutDatabaseLinks
Thesedatadictionaryviewscontainthesamebasicinformationaboutdatabase links,withoneexception:
Which Views? All All All All All All All
Description Thenameofthedatabaselink. Theownerofthedatabaselink. Whetherthedatabaselinkiscurrentlyloggedon. Whetherthedatabaselinkishomogeneous(NO)or heterogeneous(YES). Thecommunicationprotocolforthedatabaselink. Whethercursorsareopenforthedatabaselink. Whetherthedatabaselinkisaccessedina transactionthathasnotyetbeencommittedor rolledback. Whethertherewasanupdateonthedatabaselink. Thecommitpointstrengthofthetransactions usingthedatabaselink. Theinstancefromwhichtheviewinformation wasobtained.
Forexample,youcancreateandexecutethescriptbelowtodeterminewhichlinks areopen(sampleoutputincluded):
COLDB_LINKFORMATA25 COLOWNER_IDFORMAT99999HEADING"OWNID" COLLOGGED_ONFORMATA5HEADING"LOGON" COLHETEROGENEOUSFORMATA5HEADING"HETER" COLPROTOCOLFORMATA8 COLOPEN_CURSORSFORMAT999HEADING"OPN_CUR"
CreatingLocationTransparency
COLIN_TRANSACTIONFORMATA3HEADING"TXN"
COLUPDATE_SENTFORMATA6HEADING"UPDATE"
COLCOMMIT_POINT_STRENGTHFORMAT99999HEADING"C_P_S" SELECT*FROMV$DBLINK
/
SQL>@dblink DB_LINKOWNIDLOGONHETERPROTOCOLOPN_CURTXNUPDATEC_P_S
INST2.ACME.COM0YESYESUNKN0YESYES255
CreatingLocationTransparency
Afteryouhaveconguredthenecessarydatabaselinks,youcanusevarioustools tohidethedistributednatureofthedatabasesystemfromusers.Inotherwords, userscanaccessremoteobjectsasiftheywerelocalobjects.Thefollowingsections explainhowtohidedistributedfunctionalityfromusers:
UsingViewstoCreateLocationTransparency
Localviewscanprovidelocationtransparencyforlocalandremotetablesina distributeddatabasesystem. Forexample,assumethattableempisstoredinalocaldatabaseandtabledeptis storedinaremotedatabase.Tomakethesetablestransparenttousersofthesystem, youcancreateaviewinthelocaldatabasethatjoinslocalandremotedata:
CREATEVIEWcompanyAS SELECTa.empno,a.ename,b.dname FROMscott.empa,jward.dept@hq.acme.comb WHEREa.deptno=b.deptno;
CreatingLocationTransparency
Figure303
ViewsandLocationTransparency
Database Server
SCOTT.EMPTable EMPNOENAME 7329 7499 7521 7566 SMITH ALLEN WARD JONES JOB CLERK SALESMAN
SALESMAN
MANAGER
COMPANYView EMPNOENAME 7329 7499 7521 7566 SMITH ALLEN WARD JONES DNAME MARKETING SALES SALES MARKETING Database Server
Theownerofthelocalviewcangrantonlythoseobjectprivilegesonthelocalview thathavebeengrantedbytheremoteuser.(Theremoteuserisimpliedbythetype
CreatingLocationTransparency
ofdatabaselink).Thisissimilartoprivilegemanagementforviewsthatreference localdata.
UsingSynonymstoCreateLocationTransparency
Synonymsareusefulinbothdistributedandnondistributedenvironmentsbecause theyhidetheidentityoftheunderlyingobject,includingitslocationinadistributed databasesystem.Ifyoumustrenameormovetheunderlyingobject,youonlyneed toredenethesynonym;applicationsbasedonthesynonymcontinuetofunction normally.SynonymsalsosimplifySQLstatementsforusersinadistributed databasesystem.
CreatingSynonyms
Youcancreatesynonymsforthefollowing:
synonym_name
FOR[schema.]object_name[@database_link_name];
where:
CreatingLocationTransparency
ManagingPrivilegesandSynonyms
Asynonymisareferencetoanactualobject.Auserwhohasaccesstoasynonym foraparticularschemaobjectmustalsohaveprivilegesontheunderlyingschema objectitself.Forexample,iftheuserattemptstoaccessasynonymbutdoesnot haveprivilegesonthetableitidenties,anerroroccursindicatingthatthetableor viewdoesnotexist. Assumescottcreateslocalsynonymempasanaliasforremoteobject scott.emp@sales.acme.com.scottcannotgrantobjectprivilegesonthe synonymtoanotherlocaluser.scottcannotgrantlocalprivilegesforthesynonym becausethisoperationamountstograntingprivilegesfortheremoteemptableon
CreatingLocationTransparency
thesalesdatabase,whichisnotallowed.Thisbehaviorisdifferentfromprivilege managementforsynonymsthatarealiasesforlocaltablesorviews. Therefore,youcannotmanagelocalprivilegeswhensynonymsareusedforlocation transparency.Securityforthebaseobjectiscontrolledentirelyattheremotenode. Forexample,useradmincannotgrantobjectprivilegesfortheemp_synsynonym. Unlikeadatabaselinkreferencedinavieworproceduredenition,adatabaselink referencedinasynonymisresolvedbyrstlookingforaprivatelinkownedbythe schemaineffectatthetimethereferencetothesynonymisparsed.Therefore,to ensurethedesiredobjectresolution,itisespeciallyimportanttospecifytheschema oftheunderlyingobjectinthedenitionofasynonym.
UsingProcedurestoCreateLocationTransparency
PL/SQLprogramunitscalledprocedurescanprovidelocationtransparency.You havetheseoptions:
UsingLocalProcedurestoReferenceRemoteData
Proceduresorfunctions(eitherstandaloneorinpackages)cancontainSQL statementsthatreferenceremotedata.Forexample,considertheprocedurecreated bythefollowingstatement:
CREATEPROCEDUREfire_emp(enumNUMBER)AS BEGIN DELETEFROMemp@hq.acme.com WHEREempno=enum;
END;
CreatingLocationTransparency
Giventhissynonym,youcancreatethefire_empprocedureusingthefollowing statement:
CREATEPROCEDUREfire_emp(enumNUMBER)AS BEGIN DELETEFROMempWHEREempno=enum;
END;
UsingLocalProcedurestoCallRemoteProcedures
Youcanusealocalproceduretocallaremoteprocedure.Theremoteprocedurecan thenexecutetherequiredDML.Forexample,assumethatscottconnectsto local_dbandcreatesthefollowingprocedure:
CONNECTscott/tiger@local_db
CREATEPROCEDUREfire_emp(enumNUMBER)
AS
BEGIN EXECUTEterm_emp@hq.acme.com;
END;
Now,assumethatscottconnectstotheremotedatabaseandcreatestheremote procedure:
CONNECTscott/tiger@hq.acme.com
CREATEPROCEDUREterm_emp(enumNUMBER)
AS
BEGIN DELETEFROMempWHEREempno=enum;
END;
Whenauserorapplicationconnectedtolocal_dbcallsthefire_empprocedure, thisprocedureinturncallstheremoteterm_empprocedureonhq.acme.com.
UsingLocalSynonymstoReferenceRemoteProcedures
Forexample,scottconnectstothelocalsales.acme.comdatabaseandcreates thefollowingprocedure:
CREATEPROCEDUREfire_emp(enumNUMBER)AS
ManagingStatementTransparency
END;
Alocaluseronsupplycanusethissynonymtoexecutetheprocedureonsales.
ManagingProceduresandPrivileges
Assumealocalprocedureincludesastatementthatreferencesaremotetableor view.Theownerofthelocalprocedurecangranttheexecuteprivilegetoanyuser, therebygivingthatusertheabilitytoexecutetheprocedureand,indirectly,access remotedata. Ingeneral,proceduresaidinsecurity.Privilegesforobjectsreferencedwithina proceduredonotneedtobeexplicitlygrantedtothecallingusers.
ManagingStatementTransparency
ThedatabaseallowsthefollowingstandardDMLstatementstoreferenceremote tables:
ManagingStatementTransparency
WHEREe.deptno=d.deptno;
RestrictionsforStatementTransparency: Severalrestrictionsapplytostatementtransparency.
NotethatinHeterogeneousSystems,apassthroughfacilityletsyouexecute DDL.
OracleDatabasesupportstheUSERENVfunctionforqueries
only.
ManagingaDistributedDatabase:Examples
informationabouttheDBMS_SQLpackage
PL/SQLPackagesandTypesReferenceformore
ManagingaDistributedDatabase:Examples
Thissectionpresentsexamplesillustratingmanagementofdatabaselinks:
Example1:CreatingaPublicFixedUserDatabaseLink
Thefollowingstatementsconnecttothelocaldatabaseasjaneandcreateapublic xeduserdatabaselinktodatabasesalesforscott.Thedatabaseisaccessed throughitsnetservicenamesldb:
CONNECTjane/doe@local
ManagingaDistributedDatabase:Examples
Example2:CreatingaPublicFixedUserSharedDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseasdanaandcreatesapublic linktothesalesdatabase(usingitsnetservicenamesldb).Thelinkallowsa connectiontotheremotedatabaseasscottandauthenticatesthisuserasscott:
CONNECTdana/sculley@local
Example3:CreatingaPublicConnectedUserDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseaslarryandcreatesapublic linktothedatabasewiththenetservicenamesldb:
CONNECTlarry/oracle@local
CREATEPUBLICDATABASELINKredwood USING'sldb';
ManagingaDistributedDatabase:Examples
Anyuserconnectedtothelocaldatabasecanusetheredwooddatabaselink.The connecteduserinthelocaldatabasewhousesthedatabaselinkdeterminesthe remoteschema. Ifscottistheconnecteduserandusesthedatabaselink,thenthedatabaselink connectstotheremoteschemascott.Iffoxistheconnecteduserandusesthe databaselink,thenthedatabaselinkconnectstoremoteschemafox. Thefollowingstatementfailsforlocaluserfoxinthelocaldatabasewhenthe remoteschemafoxcannotresolvetheempschemaobject.Thatis,ifthefox schemainthesales.division3.acme.com doesnothaveempasatable,view, or(public)synonym,anerrorwillbereturned.
CONNECTfox/mulder@local
SELECT*FROMemp@redwood;
Example4:CreatingaPublicConnectedUserSharedDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseasneilandcreatesashared, publiclinktothesalesdatabase(usingitsnetservicenamesldb).Theuseris authenticatedbytheuserid/passwordofcrazy/horse.Thefollowingstatement createsapublic,connecteduser,shareddatabaselink:
CONNECTneil/young@local
ManagingaDistributedDatabase:Examples
Example5:CreatingaPublicCurrentUserDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseastheconnecteduserand createsapubliclinktothesalesdatabase(usingitsnetservicenamesldb).The followingstatementcreatesapubliccurrentuserdatabaselink:
CONNECTbart/simpson@local
Note:
Tousethislink,thecurrentusermustbeaglobaluser.
CREATEPROCEDUREfire_emp(enumNUMBER)
AS
BEGIN DELETEFROMemp@sales.division3.acme.com WHEREempno=enum;
END;
GRANTEXECUTEONfire_empTOford;
Now,assumethatfordconnectstothelocaldatabaseandrunsscott'sprocedure:
CONNECTford/fairlane@local_db
EXECUTEPROCEDUREscott.fire_emp(enum10345);
ManagingaDistributedDatabase:Examples
DevelopingApplicationsforaDistributed DatabaseSystem
Thischapterdescribesconsiderationsimportantwhendevelopinganapplicationto runinadistributeddatabasesystem.Itcontainsthefollowingtopics:
Fundamentalsformoreinformationaboutapplicationdevelopment inanOracleDatabaseenvironment
ManagingtheDistributionofApplicationData
Inadistributeddatabaseenvironment,coordinatewiththedatabaseadministrator todeterminethebestlocationforthedata.Someissuestoconsiderare:
ControllingConnectionsEstablishedbyDatabaseLinks
ControllingConnectionsEstablishedbyDatabaseLinks
WhenaglobalobjectnameisreferencedinaSQLstatementorremoteprocedure call,databaselinksestablishaconnectiontoasessionintheremotedatabaseon
behalfofthelocaluser.Theremoteconnectionandsessionareonlycreatedifthe connectionhasnotalreadybeenestablishedpreviouslyforthelocalusersession.
Theconnectionsandsessionsestablishedtoremotedatabasespersistforthe durationofthelocaluser'ssession,unlesstheapplicationoruserexplicitly terminatesthem.NotethatwhenyouissueaSELECTstatementacrossadatabase link,atransactionlockisplacedontheundosegments.Torereleasethesegment, youmustissueaCOMMITorROLLBACKstatement. Terminatingremoteconnectionsestablishedusingdatabaselinksisusefulfor disconnectinghighcostconnectionsthatarenolongerrequiredbytheapplication. YoucanterminatearemoteconnectionandsessionusingtheALTERSESSION statementwiththeCLOSEDATABASELINKclause.Forexample,assumeyouissue thefollowingtransactions:
SELECT*FROMemp@sales; COMMIT;
Thefollowingstatementterminatesthesessionintheremotedatabasepointedtoby
thesalesdatabaselink:
ALTERSESSIONCLOSEDATABASELINKsales;
abouttheALTERSESSIONstatement
MaintainingReferentialIntegrityinaDistributedSystem
Ifapartofadistributedstatementfails,forexample,duetoanintegrityconstraint
violation,thedatabasereturnserrornumberORA02055.Subsequentstatementsor
procedurecallsreturnerrornumberORA02067untilaROLLBACKorROLLBACK TOSAVEPOINTisissued.
TuningDistributedQueries
Designyourapplicationtocheckforanyreturnederrormessagesthatindicatethat aportionofthedistributedupdatehasfailed.Ifyoudetectafailure,youshouldroll backtheentiretransactionbeforeallowingtheapplicationtoproceed. Thedatabasedoesnotpermitdeclarativereferentialintegrityconstraintstobe denedacrossnodesofadistributedsystem.Inotherwords,adeclarative referentialintegrityconstraintononetablecannotspecifyaforeignkeythat referencesaprimaryoruniquekeyofaremotetable.Nevertheless,youcan maintainparent/childtablerelationshipsacrossnodesusingtriggers. Ifyoudecidetodenereferentialintegrityacrossthenodesofadistributed databaseusingtriggers,beawarethatnetworkfailurescanlimittheaccessibilityof notonlytheparenttable,butalsothechildtable.Forexample,assumethatthe childtableisinthesalesdatabaseandtheparenttableisinthehqdatabase.Ifthe networkconnectionbetweenthetwodatabasesfails,someDMLstatementsagainst thechildtable(thosethatinsertrowsintothechildtableorupdateaforeignkey valueinthechildtable)cannotproceedbecausethereferentialintegritytriggers musthaveaccesstotheparenttableinthehqdatabase.
SeeAlso: OracleDatabaseApplicationDeveloper'sGuide
Fundamentalsformoreinformationaboutusingtriggerstoenforce referentialintegrity
TuningDistributedQueries
ThelocalOracleDatabaseserverbreaksthedistributedqueryintoacorresponding numberofremotequeries,whichitthensendstotheremotenodesforexecution. Theremotenodesexecutethequeriesandsendtheresultsbacktothelocalnode. Thelocalnodethenperformsanynecessarypostprocessingandreturnstheresults totheuserorapplication. Youhaveseveraloptionsfordesigningyourapplicationtooptimizequery processing.Thissectioncontainsthefollowingtopics:
TuningDistributedQueries
UsingCollocatedInlineViews
Themosteffectivewayofoptimizingdistributedqueriesistoaccesstheremote databasesaslittleaspossibleandtoretrieveonlytherequireddata. Forexample,assumeyoureferenceveremotetablesfromtwodifferentremote databasesinadistributedqueryandhaveacomplexlter(forexample,WHERE r1.salary+r2.salary>50000).Youcanimprovetheperformanceofthe querybyrewritingthequerytoaccesstheremotedatabasesonceandtoapplythe lterattheremotesite.Thisrewritecauseslessdatatobetransferredtothequery executionsite. Rewritingyourquerytoaccesstheremotedatabaseonceisachievedbyusing collocatedinlineviews.Thefollowingtermsneedtobedened:
UsingCostBasedOptimization
Inadditiontorewritingyourquerieswithcollocatedinlineviews,thecostbased optimizationmethodoptimizesdistributedqueriesaccordingtothegathered
statisticsofthereferencedtablesandthecomputationsperformedbytheoptimizer.
TuningDistributedQueries
andrewritesitas:
CREATETABLEAS( SELECTl.a,l.b,v.c,v.d,v.e FROM( SELECTr1.c,r1.d,r1.e,r2.b,r2.c FROMremote1r1,remote2r2 WHEREr1.c=r2.c ANDr1.e>300 )v,locall WHEREl.c=r1.c );
HowDoesCostBasedOptimizationWork?
Themaintaskofoptimizationistorewriteadistributedquerytousecollocated inlineviews.Thisoptimizationisperformedinthreesteps:
1. 2. 3.
TuningDistributedQueries
SettingUpCostBasedOptimization
Afteryouhavesetupyoursystemtousecostbasedoptimizationtoimprovethe performanceofdistributedqueries,theoperationistransparenttotheuser.Inother words,theoptimizationoccursautomaticallywhenthequeryisissued.
Youneedtocompletethefollowingtaskstosetupyoursystemtotakeadvantageof
costbasedoptimization:
SettingUptheEnvironment AnalyzingTables
SettingUptheEnvironment Toenablecostbasedoptimization,settheOPTIMIZER_
IssueoneofthefollowingstatementstosettheOPTIMIZER_MODEinitialization parameteratthesessionlevel:
ALTERSESSIONOPTIMIZER_MODE=CHOOSE; ALTERSESSIONOPTIMIZER_MODE=COST;
distributedquery,youmustprovideaccuratestatisticsforthetablesinvolved.You dothisusingtheDBMS_STATSpackageortheANALYZEstatement.
TuningDistributedQueries
END; SeeAlso:
OracleDatabasePerformanceTuningGuideforinformationabout
generatingstatistics
PL/SQLPackagesandTypesReferenceforadditionalinformation
onusingtheDBMS_STATSpackage
UsingHints
Ifastatementisnotsufcientlyoptimized,thenyoucanusehintstoextendthe capabilityofcostbasedoptimization.Specically,ifyouwriteyourownqueryto utilizecollocatedinlineviews,instructthecostbasedoptimizernottorewriteyour distributedquery. Additionally,ifyouhavespecialknowledgeaboutthedatabaseenvironment(such asstatistics,load,networkandCPUlimitations,distributedqueries,andsoforth),
TuningDistributedQueries
youcanspecifyahinttoguidecostbasedoptimization.Forexample,ifyouhave writtenyourownoptimizedqueryusingcollocatedinlineviewsthatarebasedon yourknowledgeofthedatabaseenvironment,specifytheNO_MERGEhintto preventtheoptimizerfromrewritingyourquery. Thistechniqueisespeciallyhelpfulifyourdistributedquerycontainsanaggregate, subquery,orcomplexSQL.Becausethistypeofdistributedquerycannotbe rewrittenbytheoptimizer,specifyingNO_MERGEcausestheoptimizertoskipthe stepsdescribedin"HowDoesCostBasedOptimizationWork?" onpage315. TheDRIVING_SITEhintletsyoudenearemotesitetoactasthequeryexecution site.Inthisway,thequeryexecutesontheremotesite,whichthenreturnsthedata tothelocalsite.Thishintisespeciallyhelpfulwhentheremotesitecontainsthe majorityofthedata.
SeeAlso:
informationaboutusinghints
OracleDatabasePerformanceTuningGuideformore
UsingtheNO_MERGEHint TheNO_MERGEhintpreventsthedatabasefrommerginganinlineviewintoa
potentiallynoncollocatedSQLstatement(see"UsingHints" onpage317). Thishint isembeddedintheSELECTstatementandcanappeareitheratthebeginningofthe
SELECTstatementwiththeinlineviewasanargumentorinthequeryblockthat denestheinlineview.
/*withargument*/
Typically,youusethishintwhenyouhavedevelopedanoptimizedquerybasedon yourknowledgeofyourdatabaseenvironment.
UsingtheDRIVING_SITEHint
TheDRIVING_SITEhintletsyouspecifythesitewherethequeryexecutionis performed.Itisbesttoletcostbasedoptimizationdeterminewheretheexecution
TuningDistributedQueries
AnalyzingtheExecutionPlan
Animportantaspecttotuningdistributedqueriesisanalyzingtheexecutionplan. Thefeedbackthatyoureceivefromyouranalysisisanimportantelementtotesting andverifyingyourdatabase.Vericationbecomesespeciallyimportantwhenyou wanttocompareplans.Forexample,comparingtheexecutionplanforadistributed queryoptimizedbycostbasedoptimizationtoaplanforaquerymanually optimizedusinghints,collocatedinlineviews,andothertechniques.
OracleDatabasePerformanceTuningGuidefordetailed informationaboutexecutionplans,theEXPLAINPLANstatement, andhowtointerprettheresults SeeAlso:
PreparingtheDatabasetoStorethePlan
Beforeyoucanviewtheexecutionplanforthedistributedquery,preparethe databasetostoretheexecutionplan.Youcanperformthispreparationbyexecuting ascript.Executethefollowingscripttoprepareyourdatabasetostoreanexecution plan:
SQL>@UTLXPLAN.SQL
Theutlxplan.sqllecanbefoundinthe$ORACLE_ HOME/rdbms/admindirectory.
Note:
Afteryouexecuteutlxplan.sql,atable,PLAN_TABLE,iscreatedinthecurrent schematotemporarilystoretheexecutionplan.
GeneratingtheExecutionPlan
Afteryouhavepreparedthedatabasetostoretheexecutionplan,youarereadyto viewtheplanforaspeciedquery.InsteadofdirectlyexecutingaSQLstatement, appendthestatementtotheEXPLAINPLANFORclause.Forexample,youcan executethefollowing:
TuningDistributedQueries
ViewingtheExecutionPlan
AfteryouhaveexecutedtheprecedingSQLstatement,theexecutionplanisstored temporarilyinthePLAN_TABLEthatyoucreatedearlier.Toviewtheresultsofthe executionplan,executethefollowingscript:
@UTLXPLS.SQL
Theutlxpls.sqlcanbefoundinthe$ORACLE_ HOME/rdbms/admindirectory.
Note:
Executingtheutlxpls.sqlscriptdisplaystheexecutionplanfortheSELECT statementthatyouspecied.Theresultsareformattedasfollows:
PlanTable |Operation|Name|Rows|Bytes|Cost|Pstart|Pstop| |SELECTSTATEMENT||||||| |NESTEDLOOPS||||||| |VIEW||||||| |REMOTE||||||| |TABLEACCESSBYINDEXRO|DEPT|||||| |INDEXUNIQUESCAN|PK_DEPT||||||
HandlingErrorsinRemoteProcedures
ToviewtheSQLstatementthatwillbeexecutedattheremotesite,executethe followingselectstatement:
SELECTOTHER FROMPLAN_TABLE WHEREoperation='REMOTE';
Followingissampleoutput:
SELECTDISTINCT"A1"."DEPTNO"FROM"EMP""A1" GROUPBY"A1"."DEPTNO"HAVINGCOUNT("A1"."DEPTNO")>3
Ifyouarehavingdifcultyviewingtheentirecontentsof theOTHERcolumn,executethefollowingSQL*Pluscommand:
Note:
SETLONG9999999
HandlingErrorsinRemoteProcedures
Whenthedatabaseexecutesaprocedurelocallyorataremotelocation,fourtypes ofexceptionscanoccur:
Whenusinglocalprocedures,youcantrapthesemessagesbywritinganexception handlersuchasthefollowing
BEGIN ... EXCEPTION WHENZERO_DIVIDETHEN /*...handletheexception*/
END;
HandlingErrorsinRemoteProcedures
...
EXCEPTION WHENnull_salaryTHEN ...
END;
aboutPL/SQLprocedures
PL/SQLUser'sGuideandReferenceformoreinformation
DistributedTransactionsConcepts
ThischapterdescribeswhatdistributedtransactionsareandhowOracleDatabase maintainstheirintegrity.Thefollowingtopicsarecontainedinthischapter:
WhatAreDistributedTransactions?
Adistributedtransactionincludesoneormorestatementsthat,individuallyorasa group,updatedataontwoormoredistinctnodesofadistributeddatabase.For example,assumethedatabasecongurationdepictedinFigure321:
WhatAreDistributedTransactions?
Figure321
DistributedSystem
depttable OracleNet databaselink HQ
MAINT
SCOTT
Thefollowingdistributedtransactionexecutedbyscottupdatesthelocalsales database,theremotehqdatabase,andtheremotemaintdatabase:
UPDATEscott.dept@hq.us.acme.com SETloc='REDWOODSHORES' WHEREdeptno=10; UPDATEscott.emp SETdeptno=11 WHEREdeptno=10; UPDATEscott.bldg@maint.us.acme.com SETroom=1225 WHEREroom=1163; COMMIT;
Ifallstatementsofatransactionreferenceonlyasingle remotenode,thenthetransactionisremote,notdistributed.
Note:
Therearetwotypesofpermissibleoperationsindistributedtransactions:
DMLandDDLTransactions TransactionControlStatements
WhatAreDistributedTransactions?
DMLandDDLTransactions
ThefollowingaretheDMLandDDLoperationssupportedinadistributed transaction:
YoucanexecuteDMLandDDLstatementsinparallel,andINSERTdirectload statementsserially,butnotethefollowingrestrictions:
AllremoteoperationsmustbeSELECTstatements. Thesestatementsmustnotbeclausesinanotherdistributedtransaction. Ifthetablereferencedinthetable_expression_clauseofanINSERT,UPDATE,or DELETEstatementisremote,thenexecutionisserialratherthanparallel. YoucannotperformremoteoperationsafterissuingparallelDML/DDLor directloadINSERT. IfthetransactionbeginsusingXAorOCI,itexecutesserially. Noloopbackoperationscanbeperformedonthetransactionoriginatingthe paralleloperation.Forexample,youcannotreferencearemoteobjectthatis actuallyasynonymforalocalobject. IfyouperformadistributedoperationotherthanaSELECTinthetransaction, noDMLisparallelized.
TransactionControlStatements
Thefollowingarethesupportedtransactioncontrolstatements:
SessionTreesforDistributedTransactions
SeeAlso:
OracleDatabaseSQLReferenceformoreinformation
abouttheseSQLstatements
SessionTreesforDistributedTransactions
Asthestatementsinadistributedtransactionareissued,thedatabasedenesa sessiontreeofallnodesparticipatinginthetransaction.Asessiontreeisa hierarchicalmodelthatdescribestherelationshipsamongsessionsandtheirroles. Figure322 illustrates asessiontree:
Figure322 ExampleofaSessionTree
COMMIT;
SALES.ACME.COM
Client
Allnodesparticipatinginthesessiontreeofadistributedtransactionassumeoneor moreofthefollowingroles:
Role Client Description Anodethatreferencesinformationinadatabasebelongingtoa differentnode.
SessionTreesforDistributedTransactions
Theroleanodeplaysinadistributedtransactionisdeterminedby:
Clients
Anodeactsasaclientwhenitreferencesinformationfromadatabaseonanother node.Thereferencednodeisadatabaseserver.InFigure322 , thenodesalesisa clientofthenodesthathostthewarehouseandfinancedatabases.
DatabaseServers
Adatabaseserverisanodethathostsadatabasefromwhichaclientrequestsdata. InFigure322 , anapplicationatthesalesnodeinitiatesadistributedtransaction thataccessesdatafromthewarehouseandfinancenodes.Therefore, sales.acme.comhastheroleofclientnode,andwarehouseandfinanceare bothdatabaseservers.Inthisexample,salesisadatabaseserverandaclient becausetheapplicationalsomodiesdatainthesalesdatabase.
LocalCoordinators
Anodethatmustreferencedataonothernodestocompleteitspartinthe
distributedtransactioniscalledalocalcoordinator.InFigure322 , salesisalocal coordinatorbecauseitcoordinatesthenodesitdirectlyreferences:warehouseand
SessionTreesforDistributedTransactions
GlobalCoordinator
Thenodewherethedistributedtransactionoriginatesiscalledtheglobal coordinator.Thedatabaseapplicationissuingthedistributedtransactionisdirectly connectedtothenodeactingastheglobalcoordinator.Forexample,inFigure322, thetransactionissuedatthenodesalesreferencesinformationfromthedatabase serverswarehouseandfinance.Therefore,sales.acme.comistheglobal coordinatorofthisdistributedtransaction. Theglobalcoordinatorbecomestheparentorrootofthesessiontree.Theglobal coordinatorperformsthefollowingoperationsduringadistributedtransaction:
CommitPointSite
Thejobofthecommitpointsiteistoinitiateacommitorrollbackoperationas instructedbytheglobalcoordinator.Thesystemadministratoralwaysdesignates onenodetobethecommitpointsiteinthesessiontreebyassigningallnodesa commitpointstrength.Thenodeselectedascommitpointsiteshouldbethenode thatstoresthemostcriticaldata.
SessionTreesforDistributedTransactions
WAREHOUSE
COMMIT_POINT_STRENGTH=75
SALES
COMMIT_POINT_STRENGTH=100
FINANCE
COMMIT_POINT_STRENGTH=50
Thecommitpointsiteisdistinctfromallothernodesinvolvedinadistributed transactionintheseways:
Thecommitpointsiteneverentersthepreparedstate.Consequently,ifthe commitpointsitestoresthemostcriticaldata,thisdataneverremainsindoubt, evenifafailureoccurs.Infailuresituations,failednodesremaininaprepared state,holdingnecessarylocksondatauntilindoubttransactionsareresolved. Thecommitpointsitecommitsbeforetheothernodesinvolvedinthe transaction.Ineffect,theoutcomeofadistributedtransactionatthecommit pointsitedetermineswhetherthetransactionatallnodesiscommittedorrolled back:theothernodesfollowtheleadofthecommitpointsite.Theglobal coordinatorensuresthatallnodescompletethetransactioninthesamemanner asthecommitpointsite.
HowaDistributedTransactionCommits
Adistributedtransactionisconsideredcommittedafterallnoncommitpointsites areprepared,andthetransactionhasbeenactuallycommittedatthecommitpoint
SessionTreesforDistributedTransactions
CommitPointStrength
Everydatabaseservermustbeassignedacommitpointstrength.Ifadatabase serverisreferencedinadistributedtransaction,thevalueofitscommitpoint strengthdetermineswhichroleitplaysinthetwophasecommit.Specically,the commitpointstrengthdetermineswhetheragivennodeisthecommitpointsitein thedistributedtransactionandthuscommitsbeforealloftheothernodes.This valueisspeciedusingtheinitializationparameterCOMMIT_POINT_STRENGTH. Thissectionexplainshowthedatabasedeterminesthecommitpointsite. Thecommitpointsite,whichisdeterminedatthebeginningofthepreparephase,is selectedonlyfromthenodesparticipatinginthetransaction.Thefollowing sequenceofeventsoccurs:
1. 2. 3.
4.
SessionTreesforDistributedTransactions
Figure324
CommitPointStrengthsandDeterminationoftheCommitPointSite
SALES.ACME.COM (45)
Thefollowingconditionsapplywhendeterminingthecommitpointsite:
TwoPhaseCommitMechanism
SeeAlso:
"SpecifyingtheCommitPointStrengthofaNode"onpage331 tolearnhowtosetthecommitpointstrengthofanode
OracleDatabaseReferenceformoreinformationaboutthe
initializationparameterCOMMIT_POINT_STRENGTH
TwoPhaseCommitMechanism
Unlikeatransactiononalocaldatabase,adistributedtransactioninvolvesaltering dataonmultipledatabases.Consequently,distributedtransactionprocessingis morecomplicated,becausethedatabasemustcoordinatethecommittingorrolling backofthechangesinatransactionasaselfcontainedunit.Inotherwords,the entiretransactioncommits,ortheentiretransactionrollsback. Thedatabaseensurestheintegrityofdatainadistributedtransactionusingthe twophasecommitmechanism.Inthepreparephase,theinitiatingnodeinthe transactionaskstheotherparticipatingnodestopromisetocommitorrollbackthe transaction.Duringthecommitphase,theinitiatingnodeasksallparticipating nodestocommitthetransaction.Ifthisoutcomeisnotpossible,thenallnodesare askedtorollback. Allparticipatingnodesinadistributedtransactionshouldperformthesameaction: theyshouldeitherallcommitorallperformarollbackofthetransaction.The databaseautomaticallycontrolsandmonitorsthecommitorrollbackofa distributedtransactionandmaintainstheintegrityoftheglobaldatabase(the
collectionofdatabasesparticipatinginthetransaction)usingthetwophasecommit
Commitphase
TwoPhaseCommitMechanism
Phase Forgetphase
Description Theglobalcoordinatorforgetsaboutthetransaction.
Thissectioncontainsthefollowingtopics:
PreparePhase
Therstphaseincommittingadistributedtransactionisthepreparephase.Inthis phase,thedatabasedoesnotactuallycommitorrollbackthetransaction.Instead, allnodesreferencedinadistributedtransaction(exceptthecommitpointsite, describedinthe"CommitPointSite"onpage326)aretoldtopreparetocommit.By preparing,anode:
Whenanoderespondstotheglobalcoordinatorthatitispreparedtocommit,the preparednodepromisestoeithercommitorrollbackthetransactionlater,butdoes notmakeaunilateraldecisiononwhethertocommitorrollbackthetransaction. Thepromisemeansthatifaninstancefailureoccursatthispoint,thenodecanuse theredorecordsintheonlinelogtorecoverthedatabasebacktothepreparephase. Queriesthatstartafteranodehaspreparedcannotaccess theassociatedlockeddatauntilallphasescomplete.Thetimeis insignicantunlessafailureoccurs(see"DecidingHowtoHandle InDoubtTransactions" onpage337).
Note:
TypesofResponsesinthePreparePhase
Whenanodeistoldtoprepare,itcanrespondinthefollowingways:
TwoPhaseCommitMechanism
PreparedResponse Whenanodehassuccessfullyprepared,itissuesaprepared
Consequence Thereadonlynodesrecognize theirstatuswhenaskedto prepare.Theygivetheirlocal coordinatorsareadonly response.Thus,thecommitphase completesfasterbecausethe databaseeliminatesreadonly nodesfromsubsequent processing. Allnodesrecognizethattheyare readonlyduringpreparephase, sonocommitphaseisrequired. Theglobalcoordinator,not knowingwhetherallnodesare readonly,muststillperformthe preparephase.
Completelyreadonly withpreparephase
Alloffollowingoccur:
TwoPhaseCommitMechanism
Conditions Alloffollowingoccur:
Consequence Onlyqueriesareallowedinthe transaction,soglobalcoordinator doesnothavetoperform twophasecommit.Changesby othertransactionsdonotdegrade globaltransactionlevelread consistencybecauseofglobal SCNcoordinationamongnodes. Thetransactiondoesnotuse undosegments.
actions:
1. 2.
StepsinthePreparePhase
Tocompletethepreparephase,eachnodeexcludingthecommitpointsiteperforms thefollowingsteps:
1. 2.
stepsandreturnsareadonlyresponse(see"ReadOnlyResponse" on page3212).
TwoPhaseCommitMechanism
3. 4. 5. 6.
Thenodeallocatestheresourcesitneedstocommitthetransactionifdatais changed. Thenodesavesredorecordscorrespondingtochangesmadebythetransaction toitsredolog. Thenodeguaranteesthatlocksheldforthetransactionareabletosurvivea failure. Thenoderespondstotheinitiatingnodewithapreparedresponse(see "PreparedResponse" onpage3212) or,ifitsattemptortheattemptofoneofits descendentstopreparewasunsuccessful,withanabortresponse(see"Abort Response" onpage3213).
CommitPhase
Thesecondphaseincommittingadistributedtransactionisthecommitphase. Beforethisphaseoccurs,allnodesotherthanthecommitpointsitereferencedinthe distributedtransactionhaveguaranteedthattheyareprepared,thatis,theyhave thenecessaryresourcestocommitthetransaction.
StepsintheCommitPhase
Thecommitphaseconsistsofthefollowingsteps:
1. 2. 3. 4. 5. 6.
TwoPhaseCommitMechanism
7.
Theparticipatingnodesnotifytheglobalcoordinatorthattheyhavecommitted.
Whenthecommitphaseiscomplete,thedataonallnodesofthedistributedsystem isconsistent.
GuaranteeingGlobalDatabaseConsistency
Eachcommittedtransactionhasanassociatedsystemchangenumber(SCN)to uniquelyidentifythechangesmadebytheSQLstatementswithinthattransaction. TheSCNfunctionsasaninternaltimestampthatuniquelyidentiesacommitted versionofthedatabase. Inadistributedsystem,theSCNsofcommunicatingnodesarecoordinatedwhen allofthefollowingactionsoccur:
Amongotherbenets,thecoordinationofSCNsamongthenodesofadistributed systemensuresglobalreadconsistencyatboththestatementandtransactionlevel. Ifnecessary,globaltimebasedrecoverycanalsobecompleted. Duringthepreparephase,thedatabasedeterminesthehighestSCNatallnodes involvedinthetransaction.ThetransactionthencommitswiththehighSCNatthe commitpointsite.ThecommitSCNisthensenttoallpreparednodeswiththe commitdecision. "ManagingReadConsistency" onpage3325 for informationaboutmanagingtimelagissuesinreadconsistency
SeeAlso:
ForgetPhase
Aftertheparticipatingnodesnotifythecommitpointsitethattheyhavecommitted, thecommitpointsitecanforgetaboutthetransaction.Thefollowingstepsoccur:
1.
2. 3.
InDoubtTransactions
InDoubtTransactions
Thetwophasecommitmechanismensuresthatallnodeseithercommitorperform arollbacktogether.Whathappensifanyofthethreephasesfailsbecauseofa systemornetworkerror?Thetransactionbecomesindoubt. Distributedtransactionscanbecomeindoubtinthefollowingways:
AutomaticResolutionofInDoubtTransactions
Inthemajorityofcases,thedatabaseresolvestheindoubttransaction automatically.Assumethattherearetwonodes,localandremote,inthe followingscenarios.Thelocalnodeisthecommitpointsite.Userscottconnectsto localandexecutesandcommitsadistributedtransactionthatupdateslocaland remote.
FailureDuringthePreparePhase
Figure325 illustrates thesequenceofeventswhenthereisafailureduringthe preparephaseofadistributedtransaction:
InDoubtTransactions
Figure325
FailureDuringPreparePhase
Alldatabasesperform rollback
Crashesbeforegiving prepareresponse
2
Local
AsksREMOTEtoprepare Remote
COMMIT_POINT_STRENGTH=100
COMMIT_POINT_STRENGTH=200
Issuesdistributed transaction
SCOTT
Thefollowingstepsoccur:
1. 2.
3. 4.
FailureDuringtheCommitPhase
Figure326 illustrates thesequenceofeventswhenthereisafailureduringthe commitphaseofadistributedtransaction:
InDoubtTransactions
Figure326
FailureDuringCommitPhase
6 4 3
Local
Receivescommitmessage, butcannotrespond
Remote
COMMIT_POINT_STRENGTH=200
COMMIT_POINT_STRENGTH=100
Issuesdistributed transaction
SCOTT
Thefollowingstepsoccur:
1. 2.
UserScottconnectstolocalandexecutesadistributedtransaction. Theglobalcoordinator,whichinthiscaseisalsothecommitpointsite,requests alldatabasesotherthanthecommitpointsitetopromisetocommitorrollback whentoldtodoso. Thecommitpointsitereceivesapreparedmessagefromremotesayingthatit willcommit. Thecommitpointsitecommitsthetransactionlocally,thensendsacommit messagetoremoteaskingittocommit. Theremotedatabasereceivesthecommitmessage,butcannotrespond becauseofanetworkfailure. ThetransactionisultimatelycommittedontheremotedatabasebytheRECO processafterthenetworkisrestored. "DecidingHowtoHandleInDoubtTransactions" on page337foradescriptionoffailuresituationsandhowthe databaseresolvesinterveningfailuresduringtwophasecommit
SeeAlso:
3. 4. 5. 6.
InDoubtTransactions
ManualResolutionofInDoubtTransactions
Youshouldonlyneedtoresolveanindoubttransactioninthefollowingcases:
Resolutionofindoubttransactionscanbecomplicated.Theprocedurerequiresthat youdothefollowing:
transactions:
Thefollowingsectionsexplainhowtoresolveindoubt
RelevanceofSystemChangeNumbersforInDoubtTransactions
Asystemchangenumber(SCN)isaninternaltimestampforacommittedversion ofthedatabase.TheOracleDatabaseserverusestheSCNclockvaluetoguarantee transactionconsistency.Forexample,whenausercommitsatransaction,the databaserecordsanSCNforthiscommitintheredolog. ThedatabaseusesSCNstocoordinatedistributedtransactionsamongdifferent databases.Forexample,thedatabaseusesSCNsinthefollowingway:
1. 2. 3.
DistributedTransactionProcessing:CaseStudy
canalsobeusedtoidentifythetransactionlater,forexample,indistributed recovery.
DistributedTransactionProcessing:CaseStudy
Inthisscenario,acompanyhasseparateOracleDatabaseservers, sales.acme.comandwarehouse.acme.com.Asusersinsertsalesrecordsinto thesalesdatabase,associatedrecordsarebeingupdatedatthewarehouse database. Thiscasestudyofdistributedprocessingillustrates:
Stage1:ClientApplicationIssuesDMLStatements
AttheSalesdepartment,asalespersonusesSQL*Plustoenterasalesorderand thencommitit.TheapplicationissuesanumberofSQLstatementstoenterthe orderintothesalesdatabaseandupdatetheinventoryinthewarehouse database:
CONNECTscott/tiger@sales.acme.com...; INSERTINTOorders...; UPDATEinventory@warehouse.acme.com...; INSERTINTOorders...; UPDATEinventory@warehouse.acme.com...; COMMIT;
DistributedTransactionProcessing:CaseStudy
Figure327
DeningtheSessionTree
SALES.ACME.COM
Notethefollowingaspectsofthetransaction:
Anorderentryapplicationrunningonthesalesdatabaseinitiatesthe transaction.Therefore,sales.acme.com istheglobalcoordinatorforthe distributedtransaction. Theorderentryapplicationinsertsanewsalesrecordintothesalesdatabase andupdatestheinventoryatthewarehouse.Therefore,thenodes sales.acme.comandwarehouse.acme.com arebothdatabaseservers. Becausesales.acme.comupdatestheinventory,itisaclientof warehouse.acme.com.
DistributedTransactionProcessing:CaseStudy
Stage2:OracleDatabaseDeterminesCommitPointSite
ThedatabasedeterminesthecommitpointsiteimmediatelyfollowingtheCOMMIT statement.sales.acme.com,theglobalcoordinator,isdeterminedtobethe commitpointsite,asshowninFigure328 . "CommitPointStrength" onpage328 formore informationabouthowthecommitpointsiteisdetermined
SeeAlso: Figure328 DeterminingtheCommitPointSite
SALES.ACME.COM
Stage3:GlobalCoordinatorSendsPrepareResponse
Thepreparestageinvolvesthefollowingsteps:
1.
Afterthedatabasedeterminesthecommitpointsite,theglobalcoordinator sendsthepreparemessagetoalldirectlyreferencednodesofthesessiontree, excludingthecommitpointsite.Inthisexample,warehouse.acme.comisthe onlynodeaskedtoprepare. Nodewarehouse.acme.com triestoprepare.Ifanodecanguaranteethatit cancommitthelocallydependentpartofthetransactionandcanrecordthe commitinformationinitslocalredolog,thenthenodecansuccessfullyprepare. Inthisexample,onlywarehouse.acme.comreceivesapreparemessage becausesales.acme.comisthecommitpointsite. Nodewarehouse.acme.comrespondstosales.acme.comwithaprepared message.
2.
3.
Aseachnodeprepares,itsendsamessagebacktothenodethataskedittoprepare. Dependingontheresponses,oneofthefollowingcanhappen:
DistributedTransactionProcessing:CaseStudy
Figure329
SALES.ACME.COM
1.SalestoWarehouse 2.WarehousetoSales
Prepared Pleaseprepare
Stage4:CommitPointSiteCommits
Thecommittingofthetransactionbythecommitpointsiteinvolvesthefollowing steps:
1.
2.
DistributedTransactionProcessing:CaseStudy
Stage5:CommitPointSiteInformsGlobalCoordinatorofCommit
Thisstageinvolvesthefollowingsteps:
1.
2.
Stage6:GlobalandLocalCoordinatorsTellAllNodestoCommit
Thecommittingofthetransactionbyallthenodesinthetransactioninvolvesthe followingsteps:
1. 2. 3.
DistributedTransactionProcessing:CaseStudy
Figure3210
InstructingNodestoCommit
SALES.ACME.COM
SalestoWarehouse: Commit
Stage7:GlobalCoordinatorandCommitPointSiteCompletetheCommit
Thecompletionofthecommitofthetransactionoccursinthefollowingsteps:
1. 2. 3.
Afterallreferencednodesandtheglobalcoordinatorhavecommittedthe transaction,theglobalcoordinatorinformsthecommitpointsiteofthisfact. Thecommitpointsite,whichhasbeenwaitingforthismessage,erasesthe statusinformationaboutthisdistributedtransaction. Thecommitpointsiteinformstheglobalcoordinatorthatitisnished.Inother words,thecommitpointsiteforgetsaboutcommittingthedistributed transaction.Thisactionispermissiblebecauseallnodesinvolvedinthe twophasecommithavecommittedthetransactionsuccessfully,sotheywill neverhavetodetermineitsstatusinthefuture. Theglobalcoordinatornalizesthetransactionbyforgettingaboutthe transactionitself.
4.
AfterthecompletionoftheCOMMITphase,thedistributedtransactionisitself
complete.Thestepsdescribedareaccomplishedautomaticallyandinafractionofa
second.
DistributedTransactionProcessing:CaseStudy
ManagingDistributedTransactions
Thischapterdescribeshowtomanageandtroubleshootdistributedtransactions. Thefollowingtopicsareincludedinthischapter:
SpecifyingtheCommitPointStrengthofaNode NamingTransactions ViewingInformationAboutDistributedTransactions DecidingHowtoHandleInDoubtTransactions ManuallyOverridingInDoubtTransactions PurgingPendingRowsfromtheDataDictionary ManuallyCommittinganInDoubtTransaction:Example DataAccessFailuresDuetoLocks SimulatingDistributedTransactionFailure ManagingReadConsistency
SpecifyingtheCommitPointStrengthofaNode
Thedatabasewiththehighestcommitpointstrengthdetermineswhichnode commitsrstinadistributedtransaction.Whenspecifyingacommitpointstrength foreachnode,ensurethatthemostcriticalserverwillbenonblockingifafailure occursduringaprepareorcommitphase.TheCOMMIT_POINT_STRENGTH initializationparameterdeterminesthecommitpointstrengthofanode. Thedefaultvalueisoperatingsystemdependent.Therangeofvaluesisanyinteger from0to255.Forexample,tosetthecommitpointstrengthofadatabaseto200, includethefollowinglineinthedatabaseinitializationparameterle:
NamingTransactions
COMMIT_POINT_STRENGTH=200
Becausethecommitpointsitestoresinformationaboutthestatusofthe transaction,thecommitpointsiteshouldnotbeanodethatisfrequently unreliableorunavailableincaseothernodesneedinformationabout transactionstatus. Setthecommitpointstrengthforadatabaserelativetotheamountofcritical shareddatainthedatabase.Forexample,adatabaseonamainframecomputer usuallysharesmoredataamongusersthanadatabaseonaPC.Therefore,set thecommitpointstrengthofthemainframetoahighervaluethanthePC. "CommitPointSite" onpage326 foraconceptual overviewofcommitpoints
SeeAlso:
NamingTransactions
Youcannameatransaction.Thisisusefulforidentifyingaspecicdistributed transactionandreplacestheuseoftheCOMMITCOMMENTstatementforthis purpose.
Tonameatransaction,usetheSETTRANSACTION...NAMEstatement.For
example:
SETTRANSACTIONISOLATIONLEVELSERIALIZABLE NAME'updateinventorycheckpoint0';
ViewingInformationAboutDistributedTransactions
ViewingInformationAboutDistributedTransactions
Thedatadictionaryofeachdatabasestoresinformationaboutallopendistributed transactions.Youcanusedatadictionarytablesandviewstogaininformation aboutthetransactions.Thissectioncontainsthefollowingtopics:
DeterminingtheIDNumberandStatusofPreparedTransactions TracingtheSessionTreeofInDoubtTransactions
DeterminingtheIDNumberandStatusofPreparedTransactions
Thefollowingviewshowsthedatabaselinksthathavebeendenedatthelocal databaseandstoredinthedatadictionary:
View DBA_2PC_PENDING Purpose Listsallindoubtdistributedtransactions.Theviewisempty untilpopulatedbyanindoubttransaction.Afterthe transactionisresolved,theviewispurged.
ViewingInformationAboutDistributedTransactions
MIXED TRAN_COMMENT
HOST COMMIT#
Executethefollowingscript,namedpending_txn_script,toquerypertinent informationinDBA_2PC_PENDING(sampleoutputincluded):
COLLOCAL_TRAN_IDFORMATA13
ViewingInformationAboutDistributedTransactions
/
SQL>@pending_txn_script LOCAL_TRAN_IDGLOBAL_TRAN_IDSTATEMIXHOSTCOMMIT# 1.15.870HQ.ACME.COM.ef192da4.1.15.870commitnodlsun183115499
TracingtheSessionTreeofInDoubtTransactions
Thefollowingviewshowswhichindoubttransactionsareincomingfromaremote clientandwhichareoutgoingtoaremoteserver:
View DBA_2PC_NEIGHBORS Purpose Listsallincoming(fromremoteclient)andoutgoing(toremote server)indoubtdistributedtransactions.Italsoindicates whetherthelocalnodeisthecommitpointsiteinthe transaction. Theviewisemptyuntilpopulatedbyanindoubttransaction. Afterthetransactionisresolved,theviewispurged.
Whenatransactionisindoubt,youmayneedtodeterminewhichnodesperformed whichrolesinthesessiontree.Usetothisviewtodetermine:
ViewingInformationAboutDistributedTransactions
Thefollowingtableshowsthemostrelevantcolumns(foranaccountofallthe columnsintheview,seeOracleDatabaseReference):
Table332 Column LOCAL_TRAN_ID DBA_2PC_NEIGHBORS Description Localtransactionidentierwiththeformat integer.integer.integer. Note:WhenLOCAL_TRAN_IDandGLOBAL_TRAN_ID.DBA_ 2PC_PENDINGforaconnectionarethesame,thenodeisthe globalcoordinatorofthetransaction. IN_OUT DATABASE INforincomingtransactions;OUTforoutgoingtransactions. Forincomingtransactions,thenameoftheclientdatabasethat requestedinformationfromthislocalnode;foroutgoing transactions,thenameofthedatabaselinkusedtoaccess informationonaremoteserver. Forincomingtransactions,thelocalaccountusedtoconnectby theremotedatabaselink;foroutgoingtransactions,theowner ofthedatabaselink. Cisacommitmessage;Niseitheramessageindicatinga preparedstateorarequestforareadonlycommit. WhenIN_OUTisOUT,Cmeansthatthechildattheremoteend oftheconnectionisthecommitpointsiteandknowswhetherto commitorterminate.Nmeansthatthelocalnodeisinforming theremotenodethatitisprepared. WhenIN_OUTisIN,Cmeansthatthelocalnodeoradatabase attheremoteendofanoutgoingconnectionisthecommitpoint site.Nmeansthattheremotenodeisinformingthelocalnode thatitisprepared.
DBUSER_OWNER
INTERFACE
Executethefollowingscript,namedneighbors_script,toquerypertinent informationinDBA_2PC_PENDING(sampleoutputincluded):
COLLOCAL_TRAN_IDFORMATA13 COLIN_OUTFORMATA6 COLDATABASEFORMATA25 COLDBUSER_OWNERFORMATA15 COLINTERFACEFORMATA3 SELECTLOCAL_TRAN_ID,IN_OUT,DATABASE,DBUSER_OWNER,INTERFACE FROMDBA_2PC_NEIGHBORS
DecidingHowtoHandleInDoubtTransactions
1.15.870outSALES.ACME.COMSYSC
DecidingHowtoHandleInDoubtTransactions
Atransactionisindoubtwhenthereisafailureduringanyaspectofthetwophase commit.Distributedtransactionsbecomeindoubtinthefollowingways:
DiscoveringProblemswithaTwoPhaseCommit
Theuserapplicationthatcommitsadistributedtransactionisinformedofa problembyoneofthefollowingerrormessages:
ORA02050:transaction someremotedbsmaybeindoubt
IDrolledback,
DecidingHowtoHandleInDoubtTransactions
IDcommitted, IDindoubt
Arobustapplicationshouldsaveinformationaboutatransactionifitreceivesany oftheprecedingerrors.Thisinformationcanbeusedlaterifmanualdistributed transactionrecoveryisdesired. Noactionisrequiredbytheadministratorofanynodethathasoneormore indoubtdistributedtransactionsduetoanetworkorsystemfailure.Theautomatic recoveryfeaturesofthedatabasetransparentlycompleteanyindoubttransaction sothatthesameoutcomeoccursonallnodesofasessiontree(thatis,allcommitor allrollback)afterthenetworkorsystemfailureisresolved. Inextendedoutages,however,youcanforcethecommitorrollbackofatransaction toreleaseanylockeddata.Applicationsmustaccountforsuchpossibilities.
DeterminingWhethertoPerformaManualOverride
Overrideaspecicindoubttransactionmanuallyonlywhenoneofthefollowing conditionsexists:
Theindoubttransactionlocksdatathatisrequiredbyothertransactions.This situationoccurswhentheORA01591errormessageinterfereswithuser transactions. Anindoubttransactionpreventstheextentsofaundosegmentfrombeing usedbyothertransactions.TherstportionofthelocaltransactionIDofan indoubtdistributedtransactioncorrespondstotheIDoftheundosegment,as listedbythedatadictionaryviewDBA_2PC_PENDING. Thefailurepreventingthetwophasecommitphasestocompletecannotbe correctedinanacceptabletimeperiod.Examplesofsuchcasesincludea telecommunicationnetworkthathasbeendamagedoradamageddatabasethat requiresalongrecoverytime.
DecidingHowtoHandleInDoubtTransactions
AnalyzingtheTransactionData
Ifyoudecidetoforcethetransactiontocomplete,analyzeavailableinformation withthefollowinggoalsinmind.
FindaNodethatCommittedorRolledBack
UsetheDBA_2PC_PENDINGviewtondanodethathaseithercommittedorrolled backthetransaction.Ifyoucanndanodethathasalreadyresolvedthe transaction,thenyoucanfollowtheactiontakenatthatnode.
LookforTransactionComments
SeeifanyinformationisgivenintheTRAN_COMMENTcolumnofDBA_2PC_ PENDINGforthedistributedtransaction.CommentsareincludedintheCOMMENT clauseoftheCOMMITstatement,oriftransactionnamingisused,thetransaction nameisplacedintheTRAN_COMMENTeldwhenthetransactioniscommitted. Forexample,thecommentofanindoubtdistributedtransactioncanindicatethe originofthetransactionandwhattypeoftransactionitis:
COMMITCOMMENT'Finance/Accts_pay/Trans_type10B';
TheSETTRANSACTION...NAMEstatementcouldalsohavebeenused(andis preferable)toprovidethisinformationinatransactionname.
SeeAlso:
"NamingTransactions" onpage332
LookforTransactionAdvice
SeeifanyinformationisgivenintheADVICEcolumnofDBA_2PC_PENDINGfor thedistributedtransaction.Anapplicationcanprescribeadviceaboutwhetherto forcethecommitorforcetherollbackofseparatepartsofadistributedtransaction withtheADVISEclauseoftheALTERSESSIONstatement. Theadvicesentduringthepreparephasetoeachnodeistheadviceineffectatthe timethemostrecentDMLstatementexecutedatthatdatabaseinthecurrent transaction. Forexample,consideradistributedtransactionthatmovesanemployeerecord
fromtheemptableatonenodetotheemptableatanothernode.Thetransactioncan
protecttherecordevenwhenadministratorsindependentlyforcetheindoubt transactionateachnodebyincludingthefollowingsequenceofSQLstatements:
ALTERSESSIONADVISECOMMIT; INSERTINTOemp@hq...;/*advicetocommitatHQ*/
ManuallyOverridingInDoubtTransactions
ManuallyOverridingInDoubtTransactions
UsetheCOMMITorROLLBACKstatementwiththeFORCEoptionandatextstring thatindicateseitherthelocalorglobaltransactionIDoftheindoubttransactionto commit. Inallexamples,thetransactioniscommittedorrolledback onthelocalnode,andthelocalpendingtransactiontablerecordsa valueofforcedcommitorforcedterminationfortheSTATEcolumn therowforthistransaction.
Note:
Thissectioncontainsthefollowingtopics:
ManuallyCommittinganInDoubtTransaction ManuallyRollingBackanInDoubtTransaction
ManuallyCommittinganInDoubtTransaction
Beforeattemptingtocommitthetransaction,ensurethatyouhavetheproper privileges.Notethefollowingrequirements:
UserCommittingtheTransaction You Anotheruser PrivilegeRequired FORCETRANSACTION FORCEANYTRANSACTION
CommittingUsingOnlytheTransactionID
ThefollowingSQLstatementcommitsanindoubttransaction:
COMMITFORCE'transaction_id';
ManuallyOverridingInDoubtTransactions
CommittingUsinganSCN
Optionally,youcanspecifytheSCNforthetransactionwhenforcingatransaction tocommit.ThisfeatureletsyoucommitanindoubttransactionwiththeSCN assignedwhenitwascommittedatothernodes. Consequently,youmaintainthesynchronizedcommittimeofthedistributed transactionevenifthereisafailure.SpecifyanSCNonlywhenyoucandetermine theSCNofthesametransactionalreadycommittedatanothernode. Forexample,assumeyouwanttomanuallycommitatransactionwiththe followingglobaltransactionID:
SALES.ACME.COM.55d1c563.1.93.29
SeeAlso:
OracleDatabaseSQLReferenceformoreinformation
aboutusingtheCOMMITstatement
ManuallyRollingBackanInDoubtTransaction
Beforeattemptingtorollbacktheindoubtdistributedtransaction,ensurethatyou havetheproperprivileges.Notethefollowingrequirements:
UserCommittingtheTransaction You PrivilegeRequired FORCETRANSACTION
PurgingPendingRowsfromtheDataDictionary
UserCommittingtheTransaction Anotheruser
PrivilegeRequired FORCEANYTRANSACTION
ThefollowingSQLstatementrollsbackanindoubttransaction:
ROLLBACKFORCE'transaction_id';
2.9.4,usethefollowingstatement:
ROLLBACKFORCE'2.9.4';
Note:
Youcannotrollbackanindoubttransactiontoasavepoint.
OracleDatabaseSQLReferenceformoreinformation
SeeAlso:
aboutusingtheROLLBACKstatement
PurgingPendingRowsfromtheDataDictionary
BeforeRECOrecoversanindoubttransaction,thetransactionappearsinDBA_ 2PC_PENDING.STATEasCOLLECTING,COMMITTED,orPREPARED.Ifyouforcean indoubttransactionusingCOMMITFORCEorROLLBACKFORCE,thenthestates FORCEDCOMMITorFORCEDROLLBACK mayappear. Automaticrecoverynormallydeletesentriesinthesestates.Theonlyexceptionis whenrecoverydiscoversaforcedtransactionthatisinastateinconsistentwith othersitesinthetransaction.Inthiscase,theentrycanbeleftinthetableandthe MIXEDcolumninDBA_2PC_PENDINGhasavalueofYES.Theseentriescanbe cleanedupwiththeDBMS_TRANSACTION.PURGE_MIXEDprocedure. Ifautomaticrecoveryisnotpossiblebecausearemotedatabasehasbeen permanentlylost,thenrecoverycannotidentifytherecreateddatabasebecauseit receivesanewdatabaseIDwhenitisrecreated.Inthiscase,youmustusethe PURGE_LOST_DB_ENTRYprocedureintheDBMS_TRANSACTIONpackagetoclean uptheentries.Theentriesdonotholdupdatabaseresources,sothereisnourgency incleaningthemup.
PurgingPendingRowsfromtheDataDictionary
ExecutingthePURGE_LOST_DB_ENTRYProcedure
Tomanuallyremoveanentryfromthedatadictionary,usethefollowingsyntax (wheretrans_idistheidentierforthetransaction):
DBMS_TRANSACTION.PURGE_LOST_DB_ENTRY('trans_id');
Forexample,topurgependingdistributedtransaction1.44.99,enterthe followingstatementinSQL*Plus:
EXECUTEDBMS_TRANSACTION.PURGE_LOST_DB_ENTRY('1.44.99');
Executethisprocedureonlyifsignicantrecongurationhasoccurredsothat automaticrecoverycannotresolvethetransaction.Examplesinclude:
DeterminingWhentoUseDBMS_TRANSACTION
Thefollowingtablesindicateswhatthevariousstatesindicateaboutthedistributed transactionwhattheadministrator'sactionshouldbe:
STATE Column Collecting StateofGlobal Transaction Rolledback StateofLocal Transaction Rolledback
NormalAction None
AlternativeAction PURGE_LOST_DB_ ENTRY(onlyif autorecoverycannot resolvetransaction) PURGE_LOST_DB_ ENTRY(onlyif autorecoverycannot resolvetransaction) Forcecommitor rollback
CommittedCommitted
Committed
None
Prepared
Unknown
Prepared
None
ManuallyCommittinganInDoubtTransaction:Example
NormalAction None
Forced rollback
Unknown
Rolledback
None
Forced commit
Mixed
Committed
Forced
rollback
Mixed
Rolledback
ManuallyCommittinganInDoubtTransaction:Example
Figure331 , illustratesafailureduringthecommitofadistributedtransaction.In thisfailurecase,thepreparephasecompletes.Duringthecommitphase,however, thecommitconrmationofthecommitpointsiteneverreachestheglobal coordinator,eventhoughthecommitpointsitecommittedthetransaction. Inventorydataislockedandcannotbeaccessedbecausetheindoubttransactionis criticaltoothertransactions.Further,thelocksmustbehelduntiltheindoubt transactioneithercommitsorrollsback.
ManuallyCommittinganInDoubtTransaction:Example
Figure331
ExampleofanInDoubtDistributedTransaction
SALES.ACME.COM prepared
commit HQ.ACME.COM
Step1:RecordUserFeedback
Theusersofthelocaldatabasesystemthatconictwiththelocksoftheindoubt transactionreceivethefollowingerrormessage:
ORA01591:lockheldbyindoubtdistributedtransaction1.21.17
Step2:QueryDBA_2PC_PENDING
AfterconnectingwithSQL*Plustowarehouse,querythelocalDBA_2PC_ PENDINGdatadictionaryviewtogaininformationabouttheindoubttransaction:
ManuallyCommittinganInDoubtTransaction:Example
CONNECTSYS/password@warehouse.acme.com SELECT*FROMDBA_2PC_PENDINGWHERELOCAL_TRAN_ID='1.21.17';
Thedatabasereturnsthefollowinginformation:
ColumnNameValue LOCAL_TRAN_ID1.21.17 GLOBAL_TRAN_IDSALES.ACME.COM.55d1c563.1.93.29 STATEprepared MIXEDno ADVICE TRAN_COMMENTSales/NewOrder/Trans_type10B FAIL_TIME31MAY91 FORCE_TIME RETRY_TIME31MAY91 OS_USERSWILLIAMS OS_TERMINALTWA139: HOSTsystem1 DB_USERSWILLIAMS COMMIT#
DeterminingtheGlobalTransactionID
TheglobaltransactionIDisthecommontransactionIDthatisthesameonevery nodeforadistributedtransaction.Itisoftheform: global_database_name.hhhhhhhh.local_transaction_id where:
global_database_name
isthedatabasenameoftheglobalcoordinator.
ManuallyCommittinganInDoubtTransaction:Example
DeterminingtheStateoftheTransaction
Thetransactiononthisnodeisinapreparedstate:
STATEprepared
Therefore,warehousewaitsforitscoordinatortosendeitheracommitora rollbackrequest.
LookingforCommentsorAdvice
Thetransactioncommentoradvicecanincludeinformationaboutthistransaction. Ifso,usethiscommenttoyouradvantage.Inthisexample,theoriginand transactiontypeisinthetransactioncomment:
TRAN_COMMENTSales/NewOrder/Trans_type10B
Step3:QueryDBA_2PC_NEIGHBORSonLocalNode
Thepurposeofthisstepistoclimbthesessiontreesothatyoundcoordinators, eventuallyreachingtheglobalcoordinator.Alongtheway,youmaynda coordinatorthathasresolvedthetransaction.Ifnot,youcaneventuallyworkyour waytothecommitpointsite,whichwillalwayshaveresolvedtheindoubt transaction.Totracethesessiontree,querytheDBA_2PC_NEIGHBORSviewoneach node. Inthiscase,youquerythisviewonthewarehousedatabase:
CONNECTSYS/password@warehouse.acme.com SELECT*FROMDBA_2PC_NEIGHBORS WHERELOCAL_TRAN_ID='1.21.17' ORDERBYSESS#,IN_OUT; ColumnNameValue LOCAL_TRAN_ID1.21.17 IN_OUTin DATABASESALES.ACME.COM
ManuallyCommittinganInDoubtTransaction:Example
ObtainingDatabaseRoleandDatabaseLinkInformation
TheDBA_2PC_NEIGHBORSviewprovidesinformationaboutconnections associatedwithanindoubttransaction.Informationforeachconnectionis different,basedonwhethertheconnectionisinbound(IN_OUT=in)or outbound(IN_OUT=out):
IN_OUT in Meaning Yournodeisaserverof anothernode. DATABASE Liststhenameofthe clientdatabasethat connectedtoyournode. DBUSER_OWNER Liststhelocalaccountfor thedatabaselink connectionthat correspondstothe indoubttransaction. Liststheownerofthe databaselinkforthe indoubttransaction.
out
Yournodeisaclientof otherservers.
Inthisexample,theIN_OUTcolumnrevealsthatthewarehousedatabaseisa serverforthesalesclient,asspeciedintheDATABASEcolumn:
IN_OUTin DATABASESALES.ACME.COM
Theconnectiontowarehousewasestablishedthroughadatabaselinkfromthe swilliamsaccount,asshownbytheDBUSER_OWNERcolumn:
DBUSER_OWNERSWILLIAMS
DeterminingtheCommitPointSite
Additionally,theINTERFACEcolumntellswhetherthelocalnodeorasubordinate nodeisthecommitpointsite:
INTERFACEN
Neitherwarehousenoranyofitsdescendantsisthecommitpointsite,asshown bytheINTERFACEcolumn.
ManuallyCommittinganInDoubtTransaction:Example
Step4:QueryingDataDictionaryViewsonAllNodes
Atthispoint,youcancontacttheadministratoratthelocatednodesandaskeach persontorepeatSteps2and3usingtheglobaltransactionID. Ifyoucandirectlyconnecttothesenodeswithanother network,youcanrepeatSteps2and3yourself.
Note:
Forexample,thefollowingresultsarereturnedwhenSteps2and3areperformed atsalesandhq.
CheckingtheStatusofPendingTransactionsatsales
Atthisstage,thesalesadministratorqueriestheDBA_2PC_PENDINGdata dictionaryview:
SQL>CONNECTSYS/password@sales.acme.com SQL>SELECT*FROMDBA_2PC_PENDING >WHEREGLOBAL_TRAN_ID='SALES.ACME.COM.55d1c563.1.93.29'; ColumnNameValue LOCAL_TRAN_ID1.93.29 GLOBAL_TRAN_IDSALES.ACME.COM.55d1c563.1.93.29 STATEprepared MIXEDno ADVICE TRAN_COMMENTSales/NewOrder/Trans_type10B FAIL_TIME31MAY91 FORCE_TIME RETRY_TIME31MAY91 OS_USERSWILLIAMS OS_TERMINALTWA139: HOSTsystem1 DB_USERSWILLIAMS COMMIT#
DeterminingtheCoordinatorsandCommitPointSiteatsales
Next,thesalesadministratorqueriesDBA_2PC_NEIGHBORStodeterminethe globalandlocalcoordinatorsaswellasthecommitpointsite:
SELECT*FROMDBA_2PC_NEIGHBORS WHEREGLOBAL_TRAN_ID='SALES.ACME.COM.55d1c563.1.93.29'
ManuallyCommittinganInDoubtTransaction:Example
ORDERBYSESS#,IN_OUT;
Thisqueryreturnsthreerows:
Reformattedinformationcorrespondingtotherowsforthewarehouseconnection appearsbelow:
ColumnNameValue LOCAL_TRAN_ID1.93.29 IN_OUTOUT DATABASEWAREHOUSE.ACME.COM DBUSER_OWNERSWILLIAMS INTERFACEN DBID55d1c563 SESS#1 BRANCH1
Reformattedinformationcorrespondingtotherowsforthehqconnectionappears below:
ColumnNameValue LOCAL_TRAN_ID1.93.29 IN_OUTOUT DATABASEHQ.ACME.COM DBUSER_OWNERALLEN INTERFACEC DBID00000390 SESS#1 BRANCH1
Theinformationfromthepreviousqueriesrevealthefollowing:
ManuallyCommittinganInDoubtTransaction:Example
CheckingtheStatusofPendingTransactionsatHQ
Atthisstage,thehqadministratorqueriestheDBA_2PC_PENDINGdatadictionary view:
SELECT*FROMDBA_2PC_PENDING@hq.acme.com WHEREGLOBAL_TRAN_ID='SALES.ACME.COM.55d1c563.1.93.29'; ColumnNameValue LOCAL_TRAN_ID1.45.13 GLOBAL_TRAN_IDSALES.ACME.COM.55d1c563.1.93.29 STATECOMMIT MIXEDNO ACTION TRAN_COMMENTSales/NewOrder/Trans_type10B FAIL_TIME31MAY91 FORCE_TIME RETRY_TIME31MAY91 OS_USERSWILLIAMS OS_TERMINALTWA139: HOSTSYSTEM1 DB_USERSWILLIAMS COMMIT#129314
Atthispoint,youhavefoundanodethatresolvedthetransaction.Astheview reveals,ithasbeencommittedandassignedacommitIDnumber:
STATECOMMIT COMMIT#129314
Step5:CommittheInDoubtTransaction
Youcontacttheadministratorofthesalesdatabase,whomanuallycommitsthe indoubttransactionusingtheglobalID:
SQL>CONNECTSYS/password@sales.acme.com SQL>COMMITFORCE'SALES.ACME.COM.55d1c563.1.93.29';
Asadministratorofthewarehousedatabase,youmanuallycommittheindoubt transactionusingtheglobalID:
DataAccessFailuresDuetoLocks
SQL>CONNECTSYS/password@warehouse.acme.com SQL>COMMITFORCE'SALES.ACME.COM.55d1c563.1.93.29';
Step6:CheckforMixedOutcomeUsingDBA_2PC_PENDING
Afteryoumanuallyforceatransactiontocommitorrollback,thecorresponding rowinthependingtransactiontableremains.Thestateofthetransactionischanged dependingonhowyouforcedthetransaction. EveryOracleDatabasehasapendingtransactiontable.Thisisaspecialtablethat storesinformationaboutdistributedtransactionsastheyproceedthroughthe twophasecommitphases.Youcanquerythependingtransactiontableofa databasethroughtheDBA_2PC_PENDINGdatadictionaryview(seeTable331).
Alsoofparticularinterestinthependingtransactiontableisthemixedoutcomeag
asindicatedinDBA_2PC_PENDING.MIXED.Youcanmakethewrongchoiceifa pendingtransactionisforcedtocommitorrollback.Forexample,thelocal administratorrollsbackthetransaction,buttheothernodescommitit.Incorrect decisionsaredetectedautomatically,andthedamageagforthecorresponding pendingtransactionrecordisset(MIXED=yes). TheRECO(Recoverer)backgroundprocessusestheinformationinthepending transactiontabletonalizethestatusofindoubttransactions.Youcanalsousethe informationinthependingtransactiontabletomanuallyoverridetheautomatic recoveryproceduresforpendingdistributedtransactions. AlltransactionsautomaticallyresolvedbyRECOareremovedfromthepending transactiontable.Additionally,allinformationaboutindoubttransactionscorrectly resolvedbyanadministrator(ascheckedwhenRECOreestablishes communication)areautomaticallyremovedfromthependingtransactiontable. However,allrowsresolvedbyanadministratorthatresultinamixedoutcome acrossnodesremaininthependingtransactiontableofallinvolvednodesuntil theyaremanuallydeletedusingDBMS_TRANSACTIONS.PURGE_MIXED.
DataAccessFailuresDuetoLocks
WhenyouissueaSQLstatement,thedatabaseattemptstolocktheresources neededtosuccessfullyexecutethestatement.Iftherequesteddataiscurrentlyheld bystatementsofotheruncommittedtransactions,however,andremainslockedfor alongtime,atimeoutoccurs. Considerthefollowingscenariosinvolvingdataaccessfailure:
TransactionTimeouts
SimulatingDistributedTransactionFailure
LocksfromInDoubtTransactions
TransactionTimeouts
ADMLstatementthatrequireslocksonaremotedatabasecanbeblockedif anothertransactionownlocksontherequesteddata.Iftheselockscontinuetoblock therequestingSQLstatement,thenthefollowingsequenceofeventsoccurs:
1. 2. 3.
LocksfromInDoubtTransactions
AqueryorDMLstatementthatrequireslocksonalocaldatabasecanbeblocked indenitelyduetothelockedresourcesofanindoubtdistributedtransaction.In thiscase,thedatabaseissuesthefollowingerrormessage:
ORA01591:lockheldbyindoubtdistributedtransaction
identifier
SimulatingDistributedTransactionFailure
Youcanforcethefailureofadistributedtransactionforthefollowingreasons:
ToobserveRECOautomaticallyresolvingthelocalportionofthetransaction
SimulatingDistributedTransactionFailure
Topracticemanuallyresolvingindoubtdistributedtransactionsandobserving theresults
Thissectiondescribesthefeaturesavailableandthestepsnecessarytoperformsuch operations.
ForcingaDistributedTransactiontoFail
YoucanincludecommentsintheCOMMENTparameteroftheCOMMITstatement.To intentionallyinduceafailureduringthetwophasecommitphasesofadistributed transaction,includethefollowingcommentintheCOMMENTparameter:
COMMITCOMMENT'ORA2PCCRASHTESTn';
wherenisoneofthefollowingintegers:
n 1 2 3 4 5 6 7 8 9 10 Effect Crashcommitpointaftercollect Crashnoncommitpointsiteaftercollect Crashbeforeprepare(noncommitpoint site) Crashafterprepare(noncommitpointsite) Crashcommitpointsitebeforecommit Crashcommitpointsiteaftercommit Crashnoncommitpointsitebeforecommit Crashnoncommitpointsiteaftercommit Crashcommitpointsitebeforeforget Crashnoncommitpointsitebeforeforget
ORA02054:transaction1.93.29indoubt ORA02059:ORA_CRASH_TERST_7incommitcomment
ManagingReadConsistency
Atthispoint,theindoubtdistributedtransactionappearsintheDBA_2PC_ PENDINGview.Ifenabled,RECOautomaticallyresolvesthetransaction.
DisablingandEnablingRECO
TheRECObackgroundprocessofanOracleDatabaseinstanceautomatically resolvesfailuresinvolvingdistributedtransactions.Atexponentiallygrowingtime intervals,theRECObackgroundprocessofanodeattemptstorecoverthelocal portionofanindoubtdistributedtransaction. RECOcanuseanexistingconnectionorestablishanewconnectiontoothernodes involvedinthefailedtransaction.Whenaconnectionisestablished,RECO automaticallyresolvesallindoubttransactions.Rowscorrespondingtoany resolvedindoubttransactionsareautomaticallyremovedfromthepending transactiontableofeachdatabase. YoucanenableanddisableRECOusingtheALTERSYSTEMstatementwiththe ENABLE/DISABLEDISTRIBUTEDRECOVERYoptions.Forexample,youcan temporarilydisableRECOtoforcethefailureofatwophasecommitandmanually resolvetheindoubttransaction. ThefollowingstatementdisablesRECO:
ALTERSYSTEMDISABLEDISTRIBUTEDRECOVERY;
Alternatively,thefollowingstatementenablesRECOsothatindoubttransactions areautomaticallyresolved:
ALTERSYSTEMENABLEDISTRIBUTEDRECOVERY;
ManagingReadConsistency
AnimportantrestrictionexistsintheOracleDatabaseimplementationof distributedreadconsistency.Theproblemarisesbecauseeachsystemhasitsown SCN,whichyoucanviewasthedatabaseinternaltimestamp.TheOracleDatabase serverusestheSCNtodecidewhichversionofdataisreturnedfromaquery.
ManagingReadConsistency
absolutelysynchronized:awindowalwaysexistsinwhichonenodemayhavean SCNthatissomewhatinthepastwithrespecttotheSCNofanothernode. BecauseoftheSCNgap,youcanexecuteaquerythatusesaslightlyoldsnapshot, sothatthemostrecentchangestotheremotedatabasearenotseen.Inaccordance withreadconsistency,aquerycanthereforeretrieveconsistent,butoutofdate data.NotethatalldataretrievedbythequerywillbefromtheoldSCN,sothatifa locallyexecutedupdatetransactionupdatestwotablesataremotenode,thendata selectedfrombothtablesinthenextremoteaccesscontaindatapriortotheupdate. OneconsequenceoftheSCNgapisthattwoconsecutiveSELECTstatementscan retrievedifferentdataeventhoughnoDMLhasbeenexecutedbetweenthetwo statements.Forexample,youcanissueanupdatestatementandthencommitthe updateontheremotedatabase.WhenyouissueaSELECTstatementonaview basedonthisremotetable,theviewdoesnotshowtheupdatetotherow.Thenext timethatyouissuetheSELECTstatement,theupdateispresent. YoucanusethefollowingtechniquestoensurethattheSCNsofthetwomachines aresynchronizedjustbeforeaquery:
orrollbackthecurrenttransactionbeforeissuingtheremotequery.