Sie sind auf Seite 1von 154

KCAUNIVERSITY BIT4306:DISTRIBUTEDDATABASES

DistributedDatabaseArchitecture

HomogenousDistributedDatabaseSystems
AhomogenousdistributeddatabasesystemisanetworkoftwoormoreOracle Databasesthatresideononeormoremachines.Figure291 illustrates adistributed systemthatconnectsthreedatabases:hq,mfg,andsales.Anapplicationcan simultaneouslyaccessormodifythedatainseveraldatabasesinasingle distributedenvironment.Forexample,asinglequeryfromaManufacturingclient
onlocaldatabasemfgcanretrievejoineddatafromtheproductstableonthelocal

databaseandthedepttableontheremotehqdatabase. Foraclientapplication,thelocationandplatformofthedatabasesaretransparent. Youcanalsocreatesynonymsforremoteobjectsinthedistributedsystemsothat userscanaccessthemwiththesamesyntaxaslocalobjects.Forexample,ifyouare connectedtodatabasemfgbutwanttoaccessdataondatabasehq,creatinga synonymonmfgfortheremotedepttableenablesyoutoissuethisquery:


SELECT*FROMdept;

Inthisway,adistributedsystemgivestheappearanceofnativedataaccess.Users onmfgdonothavetoknowthatthedatatheyaccessresidesonremotedatabases.

DistributedDatabaseArchitecture

Figure291
Manufacturing

HomogeneousDistributedDatabase
DistributedDatabase
MFG.ACME.COM HQ.ACME.COM

Headquarters

Oracle

Oracle

Oracle

.
. .
Sales

SALES.ACME.COM

. . .

AnOracleDatabasedistributeddatabasesystemcanincorporateOracleDatabases ofdifferentversions.AllsupportedreleasesofOracleDatabasecanparticipateina distributeddatabasesystem.Nevertheless,theapplicationsthatworkwiththe distributeddatabasemustunderstandthefunctionalitythatisavailableateach nodeinthesystem.AdistributeddatabaseapplicationcannotexpectanOracle7 databasetounderstandtheSQLextensionsthatareonlyavailablewithOracle Database.

DistributedDatabasesVersusDistributedProcessing
Thetermsdistributeddatabaseanddistributedprocessingarecloselyrelated,yet

havedistinctmeanings.Theredenitionsareasfollows:

...
3

DistributedDatabaseArchitecture

Distributeddatabase Asetofdatabasesinadistributedsystemthatcanappeartoapplicationsasa singledatasource.

Distributedprocessing Theoperationsthatoccurswhenanapplicationdistributesitstasksamong differentcomputersinanetwork.Forexample,adatabaseapplicationtypically distributesfrontendpresentationtaskstoclientcomputersandallowsa


backenddatabaseservertomanagesharedaccesstoadatabase.Consequently,

adistributeddatabaseapplicationprocessingsystemismorecommonly referredtoasaclient/serverdatabaseapplicationsystem. Distributeddatabasesystemsemployadistributedprocessingarchitecture.For example,anOracleDatabaseserveractsasaclientwhenitrequestsdatathat anotherOracleDatabaseservermanages.

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

EMPTable Sales Database

Application
TRANSACTION
INSERTINTOEMP@SALES..; DELETEFROMDEPT..; SELECT... FROMEMP@SALES...; COMMIT;

. . . Aclientcanconnectdirectlyorindirectlytoadatabaseserver.Adirectconnection occurswhenaclientconnectstoaserverandaccessesinformationfromadatabase containedonthatserver.Forexample,ifyouconnecttothehqdatabaseandaccess thedepttableonthisdatabaseasinFigure292 , youcanissuethefollowing:


SELECT*FROMdept;

Thisqueryisdirectbecauseyouarenotaccessinganobjectonaremotedatabase. Incontrast,anindirectconnectionoccurswhenaclientconnectstoaserverand thenaccessesinformationcontainedinadatabaseonadifferentserver.For example,ifyouconnecttothehqdatabasebutaccesstheemptableontheremote salesdatabaseasinFigure292,youcanissuethefollowing:


SELECT*FROMemp@sales;

DatabaseLinks

Thisqueryisindirectbecausetheobjectyouareaccessingisnotonthedatabaseto whichyouaredirectlyconnected.

DatabaseLinks
Thecentralconceptindistributeddatabasesystemsisadatabaselink.Adatabase linkisaconnectionbetweentwophysicaldatabaseserversthatallowsaclientto accessthemasonelogicaldatabase. Thissectioncontainsthefollowingtopics:

WhatAreDatabaseLinks? WhyUseDatabaseLinks? GlobalDatabaseNamesinDatabaseLinks NamesforDatabaseLinks TypesofDatabaseLinks UsersofDatabaseLinks CreationofDatabaseLinks:Examples SchemaObjectsandDatabaseLinks DatabaseLinkRestrictions

WhatAreDatabaseLinks?
Adatabaselinkisapointerthatdenesaonewaycommunicationpathfroman OracleDatabaseservertoanotherdatabaseserver.Thelinkpointerisactually denedasanentryinadatadictionarytable.Toaccessthelink,youmustbe connectedtothelocaldatabasethatcontainsthedatadictionaryentry. Adatabaselinkconnectionisonewayinthesensethataclientconnectedtolocal databaseAcanusealinkstoredindatabaseAtoaccessinformationinremote databaseB,butusersconnectedtodatabaseBcannotusethesamelinktoaccess dataindatabaseA.IflocalusersondatabaseBwanttoaccessdataondatabaseA, thentheymustdenealinkthatisstoredinthedatadictionaryofdatabaseB. Adatabaselinkconnectionallowslocaluserstoaccessdataonaremotedatabase. Forthisconnectiontooccur,eachdatabaseinthedistributedsystemmusthavea uniqueglobaldatabasenameinthenetworkdomain.Theglobaldatabasename uniquelyidentiesadatabaseserverinadistributedsystem.

DatabaseLinks

Figure293 shows anexampleofuserscottaccessingtheemptableontheremote databasewiththeglobalnamehq.acme.com:


Figure293
UserScott

DatabaseLink

Select* FROMemp

PUBLICSYNONYM

Local database

emp>emp@HQ.ACME.COM

Database link (unidirectional)

Remote database

EMPtable

Databaselinksareeitherprivateorpublic.Iftheyareprivate,thenonlytheuser whocreatedthelinkhasaccess;iftheyarepublic,thenalldatabaseusershave access. Oneprincipaldifferenceamongdatabaselinksisthewaythatconnectionstoa remotedatabaseoccur.Usersaccessaremotedatabasethroughthefollowingtypes oflinks:


TypeofLink Connecteduserlink Description Usersconnectasthemselves,whichmeansthattheymusthave anaccountontheremotedatabasewiththesameusernameas theiraccountonthelocaldatabase.

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

Byusingxeduserlinks,youcancreatenonglobaluserswhosepassword informationisstoredinunencryptedformintheLINK$datadictionarytable.Fixed userlinksareeasytocreateandrequirelowoverheadbecausetherearenoSSLor directoryrequirements,butasecurityriskresultsfromthestorageofpassword informationinthedatadictionary.


SeeAlso:

"UsersofDatabaseLinks" onpage2916 foranexplanationof databaselinkusers "ViewingInformationAboutDatabaseLinks" for an explanationofhowtohidepasswordsfromnonadministrative users

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

JAPAN HQ Finance Sales mfg

US

MEXICO

UK

GERMANY

Sales Employees(HR)

HQ

Sales

Sales

Sales

Sales

Employees(HR)

Thenameofadatabaseisformedbystartingattheleafofthetreeandfollowinga pathtotheroot.Forexample,themfgdatabaseisindivision3oftheacme_ toolsbranchofthecomdomain.Theglobaldatabasenameformfgiscreatedby concatenatingthenodesinthetreeasfollows:

mfg.division3.acme_tools.com

Whileseveraldatabasescanshareanindividualname,eachdatabasemusthavea uniqueglobaldatabasename.Forexample,thenetworkdomains us.americas.acme_auto.comanduk.europe.acme_auto.comeachcontain asalesdatabase.Theglobaldatabasenamingsystemdistinguishesthesales databaseintheamericasdivisionfromthesalesdatabaseintheeurope divisionasfollows:

sales.us.americas.acme_auto.com

DatabaseLinks

sales.uk.europe.acme_auto.com "ManagingGlobalNamesinaDistributedSystem" on page301tolearnhowtospecifyandchangeglobaldatabase names


SeeAlso:

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:

Afteryouhaveenabledglobalnaming,databaselinksareessentiallytransparentto usersofadistributeddatabasebecausethenameofadatabaselinkisthesameas theglobalnameofthedatabasetowhichthelinkpoints.Forexample,thefollowing statementcreatesadatabaselinkinthelocaldatabasetoremotedatabasesales:


CREATEPUBLICDATABASELINKsales.division3.acme.comUSING'sales1';

OracleDatabaseReferenceformoreinformationabout specifyingtheinitializationparameterGLOBAL_NAMES SeeAlso:

DatabaseLinks

TypesofDatabaseLinks
OracleDatabaseletsyoucreateprivate,public,andglobaldatabaselinks.These basiclinktypesdifferaccordingtowhichusersareallowedaccesstotheremote database:
Type Private Owner Userwhocreatedthelink. Viewownershipdata through: DBA_DB_LINKS

Description Createslinkinaspecicschemaofthelocal database.Onlytheownerofaprivatedatabase linkorPL/SQLsubprogramsintheschema canusethislinktoaccessdatabaseobjectsin thecorrespondingremotedatabase.

ALL_DB_LINKS USER_DB_LINKS

Public

UsercalledPUBLIC.View ownershipdatathrough viewsshownforprivate databaselinks. UsercalledPUBLIC.View ownershipdatathrough viewsshownforprivate databaselinks.

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

Determiningthetypeofdatabaselinkstoemployinadistributeddatabasedepends onthespecicrequirementsoftheapplicationsusingthesystem.Considerthese featureswhenmakingyourchoice:


TypeofLink Privatedatabaselink Features Thislinkismoresecurethanapublicorgloballink,because onlytheowneroftheprivatelink,orsubprogramswithinthe sameschema,canusethelinktoaccesstheremotedatabase.

DatabaseLinks

TypeofLink Publicdatabaselink

Features WhenmanyusersrequireanaccesspathtoaremoteOracle Database,youcancreateasinglepublicdatabaselinkforall usersinadatabase. WhenanOraclenetworkusesadirectoryserver,an administratorcanconvenientlymanageglobaldatabaselinks foralldatabasesinthesystem.Databaselinkmanagementis centralizedandsimple.

Globaldatabaselink

SeeAlso:

"SpecifyingLinkTypes" onpage309 tolearnhowtocreate differenttypesofdatabaselinks "ViewingInformationAboutDatabaseLinks" onpage3021 to learnhowtoaccessinformationaboutlinks

UsersofDatabaseLinks
Whencreatingthelink,youdeterminewhichusershouldconnecttotheremote databasetoaccessthedata.Thefollowingtableexplainsthedifferencesamongthe categoriesofusersinvolvedindatabaselinks:
SampleLink CreationSyntax CREATEPUBLIC DATABASELINKhq USING'hq';

UserType Connecteduser

Description Alocaluseraccessingadatabaselinkinwhichnoxedusername andpasswordhavebeenspecied.IfSYSTEMaccessesapubliclink inaquery,thentheconnecteduserisSYSTEM,andthedatabase connectstotheSYSTEMschemaintheremotedatabase. Note:Aconnecteduserdoesnothavetobetheuserwhocreatedthe link,butisanyuserwhoisaccessingthelink.

Currentuser

AglobaluserinaCURRENT_USERdatabaselink.Theglobaluser mustbeauthenticatedbyanX.509certicate(anSSLauthenticated enterpriseuser)orapassword(apasswordauthenticatedenterprise user),andbeauseronbothdatabasesinvolvedinthelink.Current userlinksareanaspectoftheOracleAdvancedSecurityoption. SeeOracleAdvancedSecurityAdministrator'sGuideforinformation aboutglobalsecurity

CREATEPUBLIC DATABASELINKhq CONNECTTO CURRENT_USER using'hq';

DatabaseLinks

UserType Fixeduser

Description Auserwhoseusername/passwordispartofthelinkdenition.Ifa linkincludesaxeduser,thenthexeduser'susernameand passwordareusedtoconnecttotheremotedatabase.

SampleLink CreationSyntax CREATEPUBLIC DATABASELINKhq CONNECTTOjane IDENTIFIEDBY doeUSING'hq';

"SpecifyingLinkUsers" onpage3011 tolearnhowto specifyuserswherecreatinglinks


SeeAlso:

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

REMOTE_OS_AUTHENTValueConsequences FALSEfortheremotedatabase Anexternallyauthenticatedusercannotconnecttothe remotedatabaseusingaconnecteduserdatabaselink unlessasecureprotocoloranetworkauthentication servicesupportedbytheOracleAdvancedSecurity optionisused.

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

OracleDatabaseSecurityGuideformoreinformation aboutsystemprivilegesandtheO7_DICTIONARY_ ACCESSIBILITYinitializationparameter SeeAlso:

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:

"DistributedDatabaseSecurity" onpage2925 formore informationaboutsecurityissuesrelatingtodatabaselinks OracleAdvancedSecurityAdministrator'sGuide


PL/SQLUser'sGuideandReferenceformoreinformationabout

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

ConnectsToDatabase salesusingnetservice namesales_us salesusingservice nameam_sls salesusingnetservice namesales_us

ConnectsAs Connecteduser

LinkType Private connected user Private currentuser Privatexed user

Currentglobaluser

scottusingpassword tiger

salesusingnetservice namerev

scottusingpassword tiger

Publicxed user

LINKsales.us.americas.acme_ auto.comCONNECTTOscott IDENTIFIEDBYtiger AUTHENTICATEDBYanupam IDENTIFIEDBYbhideUSING 'sales';

salesusingnetservice namesales

scottusingpassword tiger,authenticatedas anupamusingpassword bhide

Shared publicxed user

DatabaseLinks

SeeAlso:

"CreatingDatabaseLinks" onpage308 tolearnhowtocreate link


OracleDatabaseSQLReferenceforinformationabouttheCREATE

DATABASELINKstatementsyntax

SchemaObjectsandDatabaseLinks
Afteryouhavecreatedadatabaselink,youcanexecuteSQLstatementsthataccess objectsontheremotedatabase.Forexample,toaccessremoteobjectempusing databaselinkfoo,youcanissue:
SELECT*FROMemp@foo;

Youmustalsobeauthorizedintheremotedatabasetoaccessspecicremote objects. Constructingproperlyformedobjectnamesusingdatabaselinksisanessential aspectofdatamanipulationindistributedsystems.

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;

IfGLOBAL_NAMESissettoFALSE,thenyoucanuseanynameforthelinkto sales.division3.acme.com.Forexample,youcancallthelinkfoo.Then,you canaccesstheremotedatabaseasfollows:


SELECTnameFROMscott.emp@foo;#linknamedifferentfromglobalname

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;

"UsingSynonymstoCreateLocationTransparency" on page3028tolearnhowtocreatesynonymsforobjectsspecied usingdatabaselinks


SeeAlso:

SchemaObjectNameResolution
Toresolveapplicationreferencestoschemaobjects(aprocesscalledname resolution),thedatabaseformsobjectnameshierarchically.Forexample,the databaseguaranteesthateachschemawithinadatabasehasauniquename,and thatwithinaschemaeachobjecthasauniquename.Asaresult,aschemaobject nameisalwaysuniquewithinthedatabase.Furthermore,thedatabaseresolves applicationreferencestothelocalnameoftheobject.

DatabaseLinks

Inadistributeddatabase,aschemaobjectsuchasatableisaccessibletoall applicationsinthesystem.Thedatabaseextendsthehierarchicalnamingmodel withglobaldatabasenamestoeffectivelycreateglobalobjectnamesandresolve referencestotheschemaobjectsinadistributeddatabasesystem.Forexample,a querycanreferencearemotetablebyspecifyingitsfullyqualiedname,including thedatabaseinwhichitresides. Forexample,assumethatyouconnecttothelocaldatabaseasuserSYSTEM:


CONNECTSYSTEM/password@sales1

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:

Grantprivilegesonremoteobjects ExecuteDESCRIBEoperationsonsomeremoteobjects.Thefollowingremote objects,however,dosupportDESCRIBEoperations: Tables Views Procedures Functions

Analyzeremoteobjects Deneorenforcereferentialintegrity Grantrolestousersinaremotedatabase Obtainnondefaultrolesonaremotedatabase.Forexample,ifjaneconnectsto thelocaldatabaseandexecutesastoredprocedurethatusesaxeduserlink

DistributedDatabaseAdministration

connectingasscott,janereceivesscott'sdefaultrolesontheremote database.JanecannotissueSETROLEtoobtainanondefaultrole.

Executehashqueryjoinsthatusesharedserverconnections UseacurrentuserlinkwithoutauthenticationthroughSSL,password,orNT nativeauthentication

DistributedDatabaseAdministration
Thefollowingsectionsexplainsomeofthetopicsrelatingtodatabasemanagement inanOracleDatabasedistributeddatabasesystem:

SiteAutonomy DistributedDatabaseSecurity AuditingDatabaseLinks AdministrationTools


SeeAlso:

Chapter30,"ManagingaDistributedDatabase" to learnhowto administerhomogenoussystems


OracleDatabaseHeterogeneousConnectivityAdministrator'sGuide

tolearnaboutheterogeneousservicesconcepts

SiteAutonomy
Siteautonomymeansthateachserverparticipatinginadistributeddatabaseis administeredindependentlyfromallotherdatabases.Althoughseveraldatabases canworktogether,eachdatabaseisaseparaterepositoryofdatathatismanaged individually.SomeofthebenetsofsiteautonomyinanOracleDatabase distributeddatabaseinclude:

Nodesofthesystemcanmirrorthelogicalorganizationofcompaniesorgroups thatneedtomaintainindependence.
Localadministratorscontrolcorrespondinglocaldata.Therefore,eachdatabase

administrator'sdomainofresponsibilityissmallerandmoremanageable.

Independentfailuresarelesslikelytodisruptothernodesofthedistributed database.Nosingledatabasefailureneedhaltalldistributedoperationsorbea performancebottleneck.

DistributedDatabaseAdministration

Administratorscanrecoverfromisolatedsystemfailuresindependentlyfrom othernodesinthesystem. Adatadictionaryexistsforeachlocaldatabase.Aglobalcatalogisnot necessarytoaccesslocaldata. Nodescanupgradesoftwareindependently.

AlthoughOracleDatabasepermitsyoutomanageeachdatabaseinadistributed databasesystemindependently,youshouldnotignoretheglobalrequirementsof thesystem.Forexample,youmayneedto:

Createadditionaluseraccountsineachdatabasetosupportthelinksthatyou createtofacilitateservertoserverconnections. SetadditionalinitializationparameterssuchasCOMMIT_POINT_STRENGTH, andOPEN_LINKS.

DistributedDatabaseSecurity
Thedatabasesupportsallofthesecurityfeaturesthatareavailablewitha nondistributeddatabaseenvironmentfordistributeddatabasesystems,including:

Passwordauthenticationforusersandroles Sometypesofexternalauthenticationforusersandrolesincluding: Kerberosversion5forconnecteduserlinks DCEforconnecteduserlinks

Loginpacketencryptionforclienttoserverandservertoserverconnections

Thefollowingsectionsexplainsomeadditionaltopicstoconsiderwhenconguring anOracleDatabasedistributeddatabasesystem:

AuthenticationThroughDatabaseLinks AuthenticationWithoutPasswords SupportingUserAccountsandRoles CentralizedUserandPrivilegeManagement DataEncryption OracleAdvancedSecurityAdministrator'sGuideformore informationaboutexternalauthentication


SeeAlso:

DistributedDatabaseAdministration

AuthenticationThroughDatabaseLinks
Databaselinksareeitherprivateorpublic,authenticatedornonauthenticated.You createpubliclinksbyspecifyingthePUBLICkeywordinthelinkcreation statement.Forexample,youcanissue:
CREATEPUBLICDATABASELINKfooUSING'sales';

YoucreateauthenticatedlinksbyspecifyingtheCONNECTTOclause, AUTHENTICATEDBYclause,orbothclausestogetherinthedatabaselinkcreation statement.Forexample,youcanissue:


CREATEDATABASELINKsalesCONNECTTOscottIDENTIFIEDBYtigerUSING'sales'; CREATESHAREDPUBLICDATABASELINKsalesCONNECTTOmickIDENTIFIEDBYjagger AUTHENTICATEDBYdavidIDENTIFIEDBYbowieUSING'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:

Theuseraccountsnecessarytoestablishservertoserverconnectionsmustbe availableinalldatabasesofthedistributeddatabasesystem. Therolesnecessarytomakeavailableapplicationprivilegestodistributed databaseapplicationusersmustbepresentinalldatabasesofthedistributed databasesystem.

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

SecurityoptiontoenhanceOracleNetandthesecurityofanOracleDatabase distributeddatabasesystem.WindowsNTnativeauthenticationisanexample ofanonOracleauthenticationsolution. OracleAdvancedSecurityAdministrator'sGuideformore informationaboutglobalusersecurity


SeeAlso: SchemaDependentGlobalUsers Oneoptionforcentralizinguserandprivilege

managementistocreatethefollowing:

Aglobaluserinacentralizeddirectory Auserineverydatabasethattheglobalusermustconnectto

Forexample,youcancreateaglobalusercalledfredwiththefollowingSQL statement:
CREATEUSERfredIDENTIFIEDGLOBALLYAS'CN=fredadams,O=Oracle,C=England';

Thissolutionallowsasingleglobalusertobeauthenticatedbyacentralized directory. Theschemadependentglobalusersolutionhastheconsequencethatyoumust createausercalledfredoneverydatabasethatthisusermustaccess.Becausemost usersneedpermissiontoaccessanapplicationschemabutdonotneedtheirown schemas,thecreationofaseparateaccountineachdatabaseforeveryglobaluser createssignicantoverhead.Becauseofthisproblem,thedatabasealsosupports schemaindependentusers,whichareglobalusersthatanaccessasingle,generic schemaineverydatabase.


SchemaIndependentGlobalUsers Thedatabasesupportsfunctionalitythatallowsa

globalusertobecentrallymanagedbyanenterprisedirectoryservice.Userswho aremanagedinthedirectoryarecalledenterpriseusers.Thisdirectorycontains informationabout:


Whichdatabasesinadistributedsystemanenterpriseusercanaccess Whichroleoneachdatabaseanenterpriseusercanuse Whichschemaoneachdatabaseanenterpriseusercanconnectto

Theadministratorofeachdatabaseisnotrequiredtocreateaglobaluseraccount foreachenterpriseuseroneachdatabasetowhichtheenterpriseuserneedsto connect.Instead,multipleenterpriseuserscanconnecttothesamedatabase schema,calledasharedschema.

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

EnterpriseUsers jane scott

Also,assumethatthelocaladministratorsforhqandsaleshaveissuedstatements asfollows:
Database hq CREATEStatements
CREATEUSERguestIDENTIFIEDGLOBALLYAS''; CREATEROLEclerk1GRANTselectONemp; CREATEPUBLICDATABASELINKsales_linkCONNECTASCURRENT_USER USING'sales';

sales

CREATEUSERguestIDENTIFIEDGLOBALLYAS''; CREATEROLEclerk2GRANTselectONdept;

Assumethatenterpriseuserscottrequestsaconnectiontolocaldatabasehqin ordertoexecuteadistributedtransactioninvolvingsales.Thefollowingsteps occur(notnecessarilyinthisexactorder):


1. 2.

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:

Fixeduserlinkhq.acme.comconnectslocaluserjanetotheremotehq databaseasremoteuserscott. Userscottisauditedontheremotedatabase.

Actionsperformedduringtheremotedatabasesessionareauditedasifscottwere connectedlocallytohqandperformingthesameactionsthere.Youmustsetaudit optionsintheremotedatabasetocapturetheactionsoftheusernameinthiscase, scottonthehqdatabaseembeddedinthelinkifthedesiredeffectistoaudit whatjaneisdoingintheremotedatabase.


Note:

Youcanaudittheglobalusernameforglobalusers.

DistributedDatabaseAdministration

Youcannotsetlocalauditingoptionsonremoteobjects.Therefore,youcannotaudit useofadatabaselink,althoughaccesstoremoteobjectscanbeauditedonthe remotedatabase.

AdministrationTools
Thedatabaseadministratorhasseveralchoicesfortoolstousewhenmanagingan OracleDatabasedistributeddatabasesystem:

EnterpriseManager ThirdPartyAdministrationTools SNMPSupport

EnterpriseManager
EnterpriseManageristheOracleDatabaseadministrationtoolthatprovidesa graphicaluserinterface(GUI).EnterpriseManagerprovidesadministrative functionalityfordistributeddatabasesthroughaneasytouseinterface.Youcanuse EnterpriseManagerto:

Administermultipledatabases.YoucanuseEnterpriseManagertoadministera

singledatabaseortosimultaneouslyadministermultipledatabases.

Centralizedatabaseadministrationtasks.Youcanadministerbothlocaland remotedatabasesrunningonanyOracleDatabaseplatforminanylocation worldwide.Inaddition,theseOracleDatabaseplatformscanbeconnectedby anynetworkprotocolssupportedbyOracleNet. DynamicallyexecuteSQL,PL/SQL,andEnterpriseManagercommands.You canuseEnterpriseManagertoenter,edit,andexecutestatements.Enterprise Manageralsomaintainsahistoryofstatementsexecuted.


Thus,youcanreexecutestatementswithoutretypingthem,aparticularlyuseful

featureifyouneedtoexecutelengthystatementsrepeatedlyinadistributed databasesystem.

Managesecurityfeaturessuchasglobalusers,globalroles,andtheenterprise directoryservice.

ThirdPartyAdministrationTools
Currentlymorethan60companiesproducemorethan150productsthathelp manageOracleDatabasesandnetworks,providingatrulyopenenvironment.

TransactionProcessinginaDistributedSystem

SNMPSupport
Besidesitsnetworkadministrationcapabilities,OracleSimpleNetwork ManagementProtocol(SNMP)supportallowsanOracleDatabaseservertobe locatedandqueriedbyanySNMPbasednetworkmanagementsystem.SNMPis theacceptedstandardunderlyingmanypopularnetworkmanagementsystems suchas:

HPOpenView DigitalPOLYCENTERManageronNetView IBMNetView/6000 NovellNetWareManagementSystem SunSoftSunNetManager


SeeAlso:

informationaboutSNMP

OracleSNMPSupportReferenceGuideformore

TransactionProcessinginaDistributedSystem
AtransactionisalogicalunitofworkconstitutedbyoneormoreSQLstatements executedbyasingleuser.Atransactionbeginswiththeuser'srstexecutableSQL statementandendswhenitiscommittedorrolledbackbythatuser. Aremotetransactioncontainsonlystatementsthataccessasingleremotenode.A distributedtransactioncontainsstatementsthataccessmorethanonenode. Thefollowingsectionsdeneimportantconceptsintransactionprocessingand explainhowtransactionsaccessdatainadistributeddatabase:

RemoteSQLStatements DistributedSQLStatements SharedSQLforRemoteandDistributedStatements RemoteTransactions DistributedTransactions TwoPhaseCommitMechanism DatabaseLinkNameResolution SchemaObjectNameResolution

TransactionProcessinginaDistributedSystem

RemoteSQLStatements
Aremotequerystatementisaquerythatselectsinformationfromoneormore remotetables,allofwhichresideatthesameremotenode.Forexample,the followingqueryaccessesdatafromthedepttableinthescottschemaofthe remotesalesdatabase:
SELECT*FROMscott.dept@sales.us.americas.acme_auto.com;

Aremoteupdatestatementisanupdatethatmodiesdatainoneormoretables, allofwhicharelocatedatthesameremotenode.Forexample,thefollowingquery updatesthedepttableinthescottschemaoftheremotesalesdatabase:


UPDATEscott.dept@mktng.us.americas.acme_auto.com SETloc='NEWYORK' WHEREdeptno=10;

Aremoteupdatecanincludeasubquerythatretrievesdata fromoneormoreremotenodes,butbecausetheupdatehappensat onlyasingleremotenode,thestatementisclassiedasaremote update.


Note:

DistributedSQLStatements
Adistributedquerystatementretrievesinformationfromtwoormorenodes.For example,thefollowingqueryaccessesdatafromthelocaldatabaseaswellasthe remotesalesdatabase:
SELECTename,dname FROMscott.empe,scott.dept@sales.us.americas.acme_auto.comd WHEREe.deptno=d.deptno;

Adistributedupdatestatementmodiesdataontwoormorenodes.Adistributed updateispossibleusingaPL/SQLsubprogramunitsuchasaprocedureortrigger thatincludestwoormoreremoteupdatesthataccessdataondifferentnodes.For example,thefollowingPL/SQLprogramunitupdatestablesonthelocaldatabase andtheremotesalesdatabase:


BEGIN UPDATEscott.dept@sales.us.americas.acme_auto.com SETloc='NEWYORK' WHEREdeptno=10; UPDATEscott.emp SETdeptno=11

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

participatinginadistributedtransactioneitherallcommitorallrollbackthe statementsinthetransaction.Atwophasecommitmechanismalsoprotects implicitDMLoperationsperformedbyintegrityconstraints,remoteprocedure calls,andtriggers. Chapter32,"DistributedTransactionsConcepts" for moreinformationabouttheOracleDatabasetwophasecommit mechanism


SeeAlso:

DatabaseLinkNameResolution
Aglobalobjectnameisanobjectspeciedusingadatabaselink.Theessential componentsofaglobalobjectnameare:

Objectname Databasename Domain

Thefollowingtableshowsthecomponentsofanexplicitlyspeciedglobaldatabase objectname:

TransactionProcessinginaDistributedSystem

Statement SELECT*FROM joan.dept@sales.acme.com SELECT*FROM emp@mktg.us.acme.com

Object dept emp

Database sales mktg

Domain acme.com us.acme.com

WheneveraSQLstatementincludesareferencetoaglobalobjectname,the databasesearchesforadatabaselinkwithanamethatmatchesthedatabasename speciedintheglobalobjectname.Forexample,ifyouissuethefollowing statement:


SELECT*FROMscott.emp@orders.us.acme.com;

Thedatabasesearchesforadatabaselinkcalledorders.us.acme.com.The databaseperformsthisoperationtodeterminethepathtothespeciedremote database. Thedatabasealwayssearchesformatchingdatabaselinksinthefollowingorder:


1. 2. 3.

PrivatedatabaselinksintheschemaoftheuserwhoissuedtheSQLstatement. Publicdatabaselinksinthelocaldatabase. Globaldatabaselinks(onlyifadirectoryserverisavailable).

NameResolutionWhentheGlobalDatabaseNameIsComplete
AssumethatyouissuethefollowingSQLstatement,whichspeciesacomplete globaldatabasename:
SELECT*FROMemp@prod1.us.oracle.com;

Inthiscase,boththedatabasename(prod1)anddomaincomponents (us.oracle.com)arespecied,sothedatabasesearchesforprivate,public,and globaldatabaselinks.Thedatabasesearchesonlyforlinksthatmatchthespecied globaldatabasename.

NameResolutionWhentheGlobalDatabaseNameIsPartial
Ifanypartofthedomainisspecied,thedatabaseassumesthatacompleteglobal databasenameisspecied.IfaSQLstatementspeciesapartialglobaldatabase name(thatis,onlythedatabasecomponentisspecied),thedatabaseappendsthe valueintheDB_DOMAINinitializationparametertothevalueintheDB_NAME

TransactionProcessinginaDistributedSystem

initializationparametertoconstructacompletename.Forexample,assumeyou issuethefollowingstatements:
CONNECTscott/tiger@locdb SELECT*FROMscott.emp@orders;

Ifthenetworkdomainforlocdbisus.acme.com,thenthedatabaseappendsthis domaintoorderstoconstructthecompleteglobaldatabasenameof orders.us.acme.com.Thedatabasesearchesfordatabaselinksthatmatchonly theconstructedglobalname.Ifamatchinglinkisnotfound,thedatabasereturnsan errorandtheSQLstatementcannotexecute.

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

UserOperation SpecifytheCONNECT TOCURRENT_USER clause Donotspecifythe USINGclause

DatabaseResponse Usesacurrentuser databaselink Searchesuntilitndsa linkspecifyinga databasestring.If matchingdatabase linksarefoundanda stringisnever identied,thedatabase returnsanerror.

Example CREATEDATABASELINKk3 CONNECTTOCURRENT_USERUSING 'prod' CREATEDATABASELINKk4 CONNECTTOCURRENT_USER

Afterthedatabasedeterminesacompletepath,itcreatesaremotesession, assumingthatanidenticalconnectionisnotalreadyopenonbehalfofthesame localsession.Ifasessionalreadyexists,thedatabasereusesit.

SchemaObjectNameResolution
AfterthelocalOracleDatabaseconnectstothespeciedremotedatabaseonbehalf ofthelocaluserthatissuedtheSQLstatement,objectresolutioncontinuesasifthe remoteuserhadissuedtheassociatedSQLstatement.Therstmatchdetermines theremoteschemaaccordingtothefollowingrules:
TypeofLinkSpecied Axeduserdatabaselink Aconnecteduserdatabaselink Acurrentuserdatabaselink LocationofObjectResolution Schemaspeciedinthelinkcreationstatement Connecteduser'sremoteschema Currentuser'sschema

Ifthedatabasecannotndtheobject,thenitcheckspublicobjectsoftheremote database.Ifitcannotresolvetheobject,thentheestablishedremotesessionremains buttheSQLstatementcannotexecuteandreturnsanerror. Thefollowingareexamplesofglobalobjectnameresolutioninadistributed databasesystem.Forallthefollowingexamples,assumethat:

TransactionProcessinginaDistributedSystem

ExampleofGlobalObjectNameResolution:CompleteObjectName
Thisexampleillustrateshowthedatabaseresolvesacompleteglobalobjectname anddeterminestheappropriatepathtotheremotedatabaseusingbothaprivate andpublicdatabaselink.Forthisexample,assumethefollowing:

Theremotedatabaseisnamedsales.division3.acme.com. Thelocaldatabaseisnamedhq.division3.acme.com. Adirectoryserver(andtherefore,globaldatabaselinks)isnotavailable. Aremotetableempiscontainedintheschematsmith.

Considerthefollowingstatementsissuedbyscottatthelocaldatabase:
CONNECTscott/tiger@hq

CREATEPUBLICDATABASELINKsales.division3.acme.com CONNECTTOguestIDENTIFIEDBYnetwork USING'dbstring';

Later,JWARDconnectsandissuesthefollowingstatements:
CONNECTjward/bronco@hq

CREATEDATABASELINKsales.division3.acme.com CONNECTTOtsmithIDENTIFIEDBYradio; UPDATEtsmith.emp@sales.division3.acme.com SETdeptno=40 WHEREdeptno=10;

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.

Combinedwiththeremoteaccounttakenfromthematchingprivatexeduser databaselink,thedatabasedeterminesacompletepathandproceedsto establishaconnectiontotheremotesalesdatabaseasusertsmith/radio. Theremotedatabasecannowresolvetheobjectreferencetotheemptable.The databasesearchesinthetsmithschemaandndsthereferencedemptable. Theremotedatabasecompletestheexecutionofthestatementandreturnsthe resultstothelocaldatabase.

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

CREATEDATABASELINKsales.division3.acme.com; DELETEFROMemp@sales WHEREempno=4299;

ThedatabaseprocessesthenalDELETEstatementasfollows:

TransactionProcessinginaDistributedSystem

1.

Thedatabasenoticesthatapartialglobalobjectnameisreferencedinscott's DELETEstatement.Itexpandsittoacompleteglobalobjectnameusingthe domainofthelocaldatabaseasfollows:


DELETEFROMemp@sales.division3.acme.com WHEREempno=4299;

2. 3.

Thedatabasesearchesthelocaldatabaseforadatabaselinkwithamatching name. Thedatabasendsamatchingprivateconnecteduserlinkintheschemascott, buttheprivatedatabaselinkindicatesnopathatall.Thedatabaseusesthe connectedusername/passwordastheremoteaccountportionofthepathand thensearchesforandndsamatchingpublicdatabaselink:


CREATEPUBLICDATABASELINKsales.division3.acme.com CONNECTTOguestIDENTIFIEDBYnetwork USING'dbstring';

4. 5. 6. 7.

Thedatabasetakesthedatabasenetservicenamedbstringfromthepublic databaselink.Atthispoint,thedatabasehasdeterminedacompletepath. Thedatabaseconnectstotheremotedatabaseasscott/tigerandsearches foranddoesnotndanobjectnamedempintheschemascott. Theremotedatabasesearchesforapublicsynonymnamedempandndsit. Theremotedatabaseexecutesthestatementandreturnstheresultstothelocal database.

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

DatabaseResponse Doesnotexpandpartialglobalnames.Thedatadictionary storestheexacttextofthedeningquery.Instead,thedatabase expandsapartialglobalobjectnameeachtimeastatementthat usestheviewisparsed. Expandspartialglobalnames.Thedenitionofthesynonym storedinthedatadictionaryincludestheexpandedglobal objectname. Expandspartialglobalnames.

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;

Thedatabaseexpandstheemployeesynonymdenitionandstoresitas: scott.emp@hr.uk.acme.com First,considerthesituationwhereboththe SalesandHumanResourcesdepartmentsarerelocatedtotheUnitedStates. Consequently,thecorrespondingglobaldatabasenamesarebothchangedas follows:


Scenario1:BothDatabasesChangeNames

sales.uk.acme.combecomessales.us.acme.com hq.uk.acme.combecomeshq.us.acme.com

Thefollowingtabledescribesqueryexpansionbeforeandafterthechangeinglobal names:

DistributedDatabaseApplicationDevelopment

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

NowconsiderthatonlytheSalesdepartment ismovedtotheUnitedStates;HumanResourcesremainsintheUK.Consequently, thecorrespondingglobaldatabasenamesarebothchangedasfollows:


Scenario2:OneDatabaseChangesNames

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

Inthiscase,thedeningqueryoftheemployee_namesviewexpandstoa nonexistentglobaldatabasename.Ontheotherhand,theemployeesynonym continuestoreferencethecorrectdatabase,hq.uk.acme.com.

DistributedDatabaseApplicationDevelopment
Applicationdevelopmentinadistributedsystemraisesissuesthatarenot applicableinanondistributedsystem.Thissectioncontainsthefollowingtopics relevantfordistributedapplicationdevelopment:

TransparencyinaDistributedDatabaseSystem RemoteProcedureCalls(RPCs) DistributedQueryOptimization

DistributedDatabaseApplicationDevelopment

SeeAlso: Chapter31,"DevelopingApplicationsforaDistributed DatabaseSystem" to learnhowtodevelopapplicationsfor distributedsystems

TransparencyinaDistributedDatabaseSystem
Withminimaleffort,youcandevelopapplicationsthatmakeanOracleDatabase distributeddatabasesystemtransparenttousersthatworkwiththesystem.The goaloftransparencyistomakeadistributeddatabasesystemappearasthoughitis asingleOracleDatabase.Consequently,thesystemdoesnotburdendevelopersand usersofthesystemwithcomplexitiesthatwouldotherwisemakedistributed databaseapplicationdevelopmentchallenginganddetractfromuserproductivity. Thefollowingsectionsexplainmoreabouttransparencyinadistributeddatabase system.

LocationTransparency
AnOracleDatabasedistributeddatabasesystemhasfeaturesthatallowapplication developersandadministratorstohidethephysicallocationofdatabaseobjectsfrom applicationsandusers.Locationtransparencyexistswhenausercanuniversally refertoadatabaseobjectsuchasatable,regardlessofthenodetowhichan applicationconnects.Locationtransparencyhasseveralbenets,including:

Accesstoremotedataissimple,becausedatabaseusersdonotneedtoknow thephysicallocationofdatabaseobjects. Administratorscanmovedatabaseobjectswithnoimpactonendusersor existingdatabaseapplications.

Typically,administratorsanddevelopersusesynonymstoestablishlocation transparencyforthetablesandsupportingobjectsinanapplicationschema.For example,thefollowingstatementscreatesynonymsinadatabasefortablesin another,remotedatabase.


CREATEPUBLICSYNONYMemp FORscott.emp@sales.us.americas.acme_auto.com; CREATEPUBLICSYNONYMdept FORscott.dept@sales.us.americas.acme_auto.com;

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.

Thestatementsinasingletransactioncanreferenceanynumberoflocalor remotetables. Thedatabaseguaranteesthatallnodesinvolvedinadistributedtransaction takethesameaction:theyeitherallcommitorallrollbackthetransaction. Ifanetworkorsystemfailureoccursduringthecommitofadistributed transaction,thetransactionisautomaticallyandtransparentlyresolvedglobally. Specically,whenthenetworkorsystemisrestored,thenodeseitherall commitorallrollbackthetransaction.

Internaltothedatabase,eachcommittedtransactionhasanassociatedsystem changenumber(SCN)touniquelyidentifythechangesmadebythestatements withinthattransaction.Inadistributeddatabase,theSCNsofcommunicating nodesarecoordinatedwhen:

Aconnectionisestablishedusingthepathdescribedbyoneormoredatabase links. AdistributedSQLstatementisexecuted. Adistributedtransactioniscommitted.

DistributedDatabaseApplicationDevelopment

Amongotherbenets,thecoordinationofSCNsamongthenodesofadistributed databasesystemallowsglobaldistributedreadconsistencyatboththestatement andtransactionlevel.Ifnecessary,globaldistributedtimebasedrecoverycanalso becompleted.

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;

InorderfortheRPCtosucceed,thecalledproceduremustexistattheremotesite, andtheuserbeingconnectedtomusthavetheproperprivilegestoexecutethe procedure. Whendevelopingpackagesandproceduresfordistributeddatabasesystems, developersmustcodewithanunderstandingofwhatprogramunitsshoulddoat remotelocations,andhowtoreturntheresultstoacallingapplication.

DistributedQueryOptimization
DistributedqueryoptimizationisanOracleDatabasefeaturethatreducesthe amountofdatatransferrequiredbetweensiteswhenatransactionretrievesdata fromremotetablesreferencedinadistributedSQLstatement. Distributedqueryoptimizationusescostbasedoptimizationtondorgenerate SQLexpressionsthatextractonlythenecessarydatafromremotetables,process thatdataataremotesiteorsometimesatthelocalsite,andsendtheresultstothe

CharacterSetSupportforDistributedEnvironments

localsitefornalprocessing.Thisoperationreducestheamountofrequireddata transferwhencomparedtothetimeittakestotransferallthetabledatatothelocal siteforprocessing. UsingvariouscostbasedoptimizerhintssuchasDRIVING_SITE,NO_MERGE,and INDEX,youcancontrolwhereOracleDatabaseprocessesthedataandhowit accessesthedata. "UsingCostBasedOptimization"onpage314formore informationaboutcostbasedoptimization


SeeAlso:

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)

DenedFor Client OracleDatabaseserver

HeterogeneousDistributed

OracleDatabaseserver Transparentgateway

HS_NLS_NCHAR

CharacterSetSupportforDistributedEnvironments

SeeAlso:

OracleDatabaseGlobalizationSupportGuideforinformation

aboutNLSparameters

OracleDatabaseHeterogeneousConnectivityAdministrator'sGuide

forinformationaboutHSparameters

Client/ServerEnvironment
Inaclient/serverenvironment,settheclientcharactersettobethesameasora subsetoftheOracleDatabaseservercharacterset,asillustratedinFigure296 :
Figure296 NLSParameterSettingsinaClientServerEnvironment

NLS_LANG= NLSsettingsof Oracleserveror subsetofit

Oracle

HomogeneousDistributedEnvironment
Inanonheterogeneousenvironment,theclientandservercharactersetsshouldbe eitherthesameasorsubsetsofthemainservercharacterset,asillustratedin Figure297 :

CharacterSetSupportforDistributedEnvironments

Figure297

NLSParameterSettingsinaHomogeneousEnvironment

NLS_LANG= NLSsettingsofOracle server(s)orsubset(s) ofit

Oracle

Oracle

NLSsettingsimilaror subsetoftheother Oracleserver

HeterogeneousDistributedEnvironment
Inaheterogeneousenvironment,theNLSsettingsoftheclient,thetransparent gateway,andthenonOracleDatabasedatasourceshouldbeeitherthesameora subsetofthedatabaseservercharactersetasillustratedinFigure298.Transparent gatewayshavefullglobalizationsupport.

CharacterSetSupportforDistributedEnvironments

Figure298

NLSParameterSettingsinaHeterogeneousEnvironment

NLS_LANG= NLSsettingsofOracle serverorsubsetofit

Oracle

Gateway Agent NLSsettingstobethe sameorthesubset ofOracleserver NLSsetting

NonOracle

Inaheterogeneousenvironment,onlytransparentgatewaysbuiltwithHS technologysupportcompleteNCHARcapabilities.Whetheraspecictransparent gatewaysupportsNCHARdependsonthenonOracleDatabasedatasourceitis targeting.ForinformationonhowaparticulartransparentgatewayhandlesNCHAR support,consultthesystemspecictransparentgatewaydocumentation.


SeeAlso: OracleDatabaseHeterogeneousConnectivity

Administrator'sGuideformoredetailedinformationabout HeterogeneousServices

CharacterSetSupportforDistributedEnvironments

ManagingaDistributedDatabase
Thischapterdescribeshowtomanageandmaintainadistributeddatabasesystem andcontainsthefollowingtopics:

ManagingGlobalNamesinaDistributedSystem CreatingDatabaseLinks UsingSharedDatabaseLinks ManagingDatabaseLinks ViewingInformationAboutDatabaseLinks CreatingLocationTransparency ManagingStatementTransparency ManagingaDistributedDatabase:Examples

ManagingGlobalNamesinaDistributedSystem
Inadistributeddatabasesystem,eachdatabaseshouldhaveauniqueglobal databasename.Globaldatabasenamesuniquelyidentifyadatabaseinthesystem. Aprimaryadministrationtaskinadistributedsystemismanagingthecreationand alterationofglobaldatabasenames. Thissectioncontainsthefollowingtopics:

UnderstandingHowGlobalDatabaseNamesAreFormed DeterminingWhetherGlobalNamingIsEnforced ViewingaGlobalDatabaseName ChangingtheDomaininaGlobalDatabaseName

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

DB_DOMAIN au.oracle.com us.oracle.com us.oracle.com nonprofit.org

GlobalDatabaseName sales.au.oracle.com sales.us.oracle.com mktg.us.oracle.com payroll.nonprofit.org

mktg payroll

TheDB_DOMAINinitializationparameterisonlyimportantatdatabasecreationtime whenitisused,togetherwiththeDB_NAMEparameter,toformthedatabaseglobal name.Atthispoint,thedatabaseglobalnameisstoredinthedatadictionary.You mustchangetheglobalnameusinganALTERDATABASE statement,notby alteringtheDB_DOMAINparameterintheinitializationparameterle.Itisgood practice,however,tochangetheDB_DOMAINparametertoreectthechangeinthe domainnamebeforethenextdatabasestartup.

DeterminingWhetherGlobalNamingIsEnforced
Thenamethatyougivetoalinkonthelocaldatabasedependsonwhetherthe remotedatabasethatyouwanttoaccessenforcesglobalnaming.Iftheremote databaseenforcesglobalnaming,thenyoumustusetheremotedatabaseglobal databasenameasthenameofthelink.Forexample,ifyouareconnectedtothe

ManagingGlobalNamesinaDistributedSystem

localhqserverandwanttocreatealinktotheremotemfgdatabase,andmfg enforcesglobalnaming,thenyoumustusethemfgglobaldatabasenameasthe linkname. Youcanalsouseservicenamesaspartofthedatabaselinkname.Forexample,if youusetheservicenamessn1andsn2toconnecttodatabasehq.acme.com,and hqenforcesglobalnaming,thenyoucancreatethefollowinglinknamestohq:


HQ.ACME.COM@SN1 HQ.ACME.COM@SN2
SeeAlso: "UsingConnectionQualierstoSpecifyServiceNames WithinLinkNames" onpage3013 formoreinformationabout usingservicesnamesinlinknames

Todeterminewhetherglobalnamingonadatabaseisenforcedonadatabase,either examinethedatabaseinitializationparameterleorquerytheV$PARAMETERview. Forexample,toseewhetherglobalnamingisenforcedonmfg,youcouldstarta sessiononmfgandthencreateandexecutethefollowingglobalnames.sql script(sampleoutputincluded):


COLNAMEFORMATA12 COLVALUEFORMATA6 SELECTNAME,VALUEFROMV$PARAMETER WHERENAME='global_names'

/
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

CONNECTSYSTEM/password@sales.us.acme.com SELECT*FROMGLOBAL_NAME; GLOBAL_NAME SALES.US.ACME.COM

2.

YouquerytheV$PARAMETERviewtodeterminethecurrentsettingfortheDB_ DOMAINinitializationparameter:
SELECTNAME,VALUEFROMV$PARAMETERWHERENAME='db_domain';

NAMEVALUE db_domainUS.ACME.COM

3.

Youthencreateadatabaselinktoadatabasecalledhq,usingonlya partiallyspeciedglobalname:
CREATEDATABASELINKhqUSING'sales';

Thedatabaseexpandstheglobaldatabasenameforthislinkbyappendingthe domainpartoftheglobaldatabasenameofthelocaldatabasetothenameofthe databasespeciedinthelink.


4.

YouqueryUSER_DB_LINKStodeterminewhichdomainnamethedatabase usestoresolvethepartiallyspeciedglobaldatabasename:
SELECTDB_LINKFROMUSER_DB_LINKS;

DB_LINK HQ.US.ACME.COM

Thisresultindicatesthatthedomainpartoftheglobaldatabasenameofthe localdatabaseisus.acme.com.Thedatabaseusesthisdomaininresolving partialdatabaselinknameswhenthedatabaselinkiscreated.


5.

BecauseyouhavereceivedwordthatthesalesdatabasewillmovetoJapan, yourenamethesalesdatabasetosales.jp.acme.com:
ALTERDATABASERENAMEGLOBAL_NAMETOsales.jp.acme.com; SELECT*FROMGLOBAL_NAME; GLOBAL_NAME

ManagingGlobalNamesinaDistributedSystem

SALES.JP.ACME.COM

6.

YouqueryV$PARAMETERagainanddiscoverthatthevalueofDB_DOMAINis notchanged,althoughyourenamedthedomainpartoftheglobaldatabase name:


SELECTNAME,VALUEFROMV$PARAMETER WHERENAME='db_domain'; NAMEVALUE db_domainUS.ACME.COM

ThisresultindicatesthatthevalueoftheDB_DOMAINinitializationparameteris independentoftheALTERDATABASERENAMEGLOBAL_NAMEstatement.The ALTERDATABASEstatementdeterminesthedomainoftheglobaldatabase name,nottheDB_DOMAINinitializationparameter(althoughitisgoodpractice toalterDB_DOMAINtoreectthenewdomainname).


7.

Youcreateanotherdatabaselinktodatabasesupply,andthenqueryUSER_ DB_LINKStoseehowthedatabaseresolvesthedomainpartoftheglobal databasenameofsupply:


CREATEDATABASELINKsupplyUSING'supply'; SELECTDB_LINKFROMUSER_DB_LINKS; DB_LINK HQ.US.ACME.COM SUPPLY.JP.ACME.COM

Thisresultindicatesthatthedatabaseresolvesthepartiallyspeciedlinkname byusingthedomainjp.acme.com.Thisdomainisusedwhenthelinkis createdbecauseitisthedomainpartoftheglobaldatabasenameofthelocal database.ThedatabasedoesnotusetheDB_DOMAINinitializationparameter settingwhenresolvingthepartiallinkname.


8.

Youthenreceivewordthatyourpreviousinformationwasfaulty:saleswill beintheASIA.JP.ACME.COMdomain,nottheJP.ACME.COMdomain. Consequently,yourenametheglobaldatabasenameasfollows:


ALTERDATABASERENAMEGLOBAL_NAMETOsales.asia.jp.acme.com; SELECT*FROMGLOBAL_NAME; GLOBAL_NAME

ManagingGlobalNamesinaDistributedSystem

SALES.ASIA.JP.ACME.COM

9.

YouqueryV$PARAMETERtoagaincheckthesettingfortheparameterDB_ DOMAIN:
SELECTNAME,VALUEFROMV$PARAMETER WHERENAME='db_domain'; NAMEVALUE db_domainUS.ACME.COM

Theresultindicatesthatthedomainsettingintheparameterleisexactlythe sameasitwasbeforeyouissuedeitheroftheALTERDATABASERENAME statements.


10. Finally,youcreatealinktothewarehousedatabaseandagainqueryUSER_

DB_LINKStodeterminehowthedatabaseresolvesthepartiallyspecied globalname:
CREATEDATABASELINKwarehouseUSING'warehouse'; SELECTDB_LINKFROMUSER_DB_LINKS; DB_LINK HQ.US.ACME.COM SUPPLY.JP.ACME.COM WAREHOUSE.ASIA.JP.ACME.COM

Again,youseethatthedatabaseusesthedomainpartoftheglobaldatabase nameofthelocaldatabasetoexpandthepartiallinknameduringlinkcreation. Inordertocorrectthesupplydatabaselink,itmustbe droppedandrecreated.


Note: OracleDatabaseReferenceformoreinformationabout specifyingtheDB_NAMEandDB_DOMAINinitializationparameters SeeAlso:

CreatingDatabaseLinks

CreatingDatabaseLinks
Tosupportapplicationaccesstothedataandschemaobjectsthroughouta distributeddatabasesystem,youmustcreateallnecessarydatabaselinks.This sectioncontainsthefollowingtopics:

ObtainingPrivilegesNecessaryforCreatingDatabaseLinks SpecifyingLinkTypes SpecifyingLinkUsers


UsingConnectionQualierstoSpecifyServiceNamesWithinLinkNames

ObtainingPrivilegesNecessaryforCreatingDatabaseLinks
Adatabaselinkisapointerinthelocaldatabasethatletsyouaccessobjectsona remotedatabase.Tocreateaprivatedatabaselink,youmusthavebeengrantedthe properprivileges.Thefollowingtableillustrateswhichprivilegesarerequiredon whichdatabaseforwhichtypeoflink:
Privilege CREATEDATABASELINK CREATEPUBLICDATABASELINK CREATESESSION Database Local Local Remote RequiredFor Creationofaprivatedatabaselink. Creationofapublicdatabaselink. Creationofanytypeofdatabaselink.

Toseewhichprivilegesyoucurrentlyhaveavailable,queryROLE_SYS_PRIVS.For example,youcouldcreateandexecutethefollowingprivs.sqlscript(sample outputincluded):


SELECTDISTINCTPRIVILEGEAS"DatabaseLinkPrivileges" FROMROLE_SYS_PRIVS WHEREPRIVILEGEIN('CREATESESSION','CREATEDATABASELINK', 'CREATEPUBLICDATABASELINK')

/
SQL>@privs DatabaseLinkPrivileges CREATEDATABASELINK CREATEPUBLICDATABASELINK CREATESESSION

CreatingDatabaseLinks

SpecifyingLinkTypes
Whenyoucreateadatabaselink,youmustdecidewhowillhaveaccesstoit.The followingsectionsdescribehowtocreatethethreebasictypesoflinks:

CreatingPrivateDatabaseLinks CreatingPublicDatabaseLinks CreatingGlobalDatabaseLinks

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;

Apublicxeduserlinktotheremotesales database.Thelinkconnectstotheremote databasewiththeuserid/passwordof jane/doe.

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.

Whenanapplicationusesaxeduserdatabaselink,thelocalserveralways establishesaconnectiontoaxedremoteschemaintheremotedatabase.Thelocal serveralsosendsthexeduser'scredentialsacrossthenetworkwhenan applicationusesthelinktoaccesstheremotedatabase.

CreatingConnectedUserandCurrentUserDatabaseLinks
Connecteduserandcurrentuserdatabaselinksdonotincludecredentialsinthe denitionofthelink.Thecredentialsusedtoconnecttotheremotedatabasecan changedependingontheuserthatreferencesthedatabaselinkandtheoperation performedbytheapplication.

CreatingDatabaseLinks

Formanydistributedapplications,youdonotwantauser tohaveprivilegesinaremotedatabase.Onesimplewaytoachieve thisresultistocreateaprocedurethatcontainsaxeduseror currentuserdatabaselinkwithinit.Inthisway,theuseraccessing theproceduretemporarilyassumessomeoneelse'sprivileges.


Note:

Foranextendedconceptualdiscussionofthedistinctionbetweenconnectedusers andcurrentusers,see"UsersofDatabaseLinks" onpage2916.


CreatingaConnectedUserDatabaseLink Tocreateaconnecteduserdatabaselink,omit

theCONNECTTOclause.Thefollowingsyntaxcreatesaconnecteduserdatabase link,wheredblinkisthenameofthelinkandnet_service_nameisanoptionalconnect string:


CREATE[SHARED][PUBLIC]DATABASELINK

dblink...[USING'net_service_name'];

Forexample,tocreateaconnecteduserdatabaselink,usethefollowingsyntax:
CREATEDATABASELINKsales.division3.acme.comUSING'sales';

CreatingaCurrentUserDatabaseLink Tocreateacurrentuserdatabaselink,usethe

CONNECTTOCURRENT_USERclauseinthelinkcreationstatement.Currentuser linksareonlyavailablethroughtheOracleAdvancedSecurityoption. Thefollowingsyntaxcreatesacurrentuserdatabaselink,wheredblinkisthename ofthelinkandnet_service_nameisanoptionalconnectstring:


CREATE[SHARED][PUBLIC]DATABASELINK [USING'net_service_name'];

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:

AremotedatabaseispartofanOracleRealApplicationClustersconguration, soyoudeneseveralpublicdatabaselinksatyourlocalnodesothat connectionscanbeestablishedtospecicinstancesoftheremotedatabase. SomeclientsconnecttotheOracleDatabaseserverusingTCP/IPwhileothers useDECNET.

Tofacilitatesuchfunctionality,thedatabaseletsyoucreateadatabaselinkwithan optionalservicenameinthedatabaselinkname.Whencreatingadatabaselink,a servicenameisspeciedasthetrailingportionofthedatabaselinkname,separated byan@sign,asin@sales.Thisstringiscalledaconnectionqualier. Forexample,assumethatremotedatabasehq.acme.com ismanagedinaOracle RealApplicationClustersenvironment.Thehqdatabasehastwoinstancesnamed hq_1andhq_2.Thelocaldatabasecancontainthefollowingpublicdatabaselinks todenepathwaystotheremoteinstancesofthehqdatabase:


CREATEPUBLICDATABASELINKhq.acme.com@hq_1 USING'string_to_hq_1'; CREATEPUBLICDATABASELINKhq.acme.com@hq_2 USING'string_to_hq_2'; CREATEPUBLICDATABASELINKhq.acme.com USING'string_to_hq';

Noticeinthersttwoexamplesthataservicenameissimplyapartofthedatabase linkname.Thetextoftheservicenamedoesnotnecessarilyindicatehowa connectionistobeestablished;thisinformationisspeciedintheservicenameof theUSINGclause.Alsonoticethatinthethirdexample,aservicenameisnot speciedaspartofthelinkname.Inthiscase,justaswhenaservicenameis speciedaspartofthelinkname,theinstanceisdeterminedbytheUSINGstring. Touseaservicenametospecifyaparticularinstance,includetheservicenameat theendoftheglobalobjectname:


SELECT*FROMscott.emp@hq.acme.com@hq_1

Notethatinthisexample,therearetwo@symbols.

UsingSharedDatabaseLinks

UsingSharedDatabaseLinks
Everyapplicationthatreferencesaremoteserverusingastandarddatabaselink establishesaconnectionbetweenthelocaldatabaseandtheremotedatabase.Many usersrunningapplicationssimultaneouslycancauseahighnumberofconnections betweenthelocalandremotedatabases. Shareddatabaselinksenableyoutolimitthenumberofnetworkconnections requiredbetweenthelocalserverandtheremoteserver. Thissectioncontainsthefollowingtopics:

DeterminingWhethertoUseSharedDatabaseLinks CreatingSharedDatabaseLinks ConguringSharedDatabaseLinks "WhatAreSharedDatabaseLinks?" onpage2910 fora conceptualoverviewofshareddatabaselinks


SeeAlso:

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

Consequences If10clientsconnecttoalocaldedicatedserver,and eachclienthas10sessionsonthesameconnection (thusestablishing100sessionsoverall),andeach sessionreferencesthesameremotedatabase,then only10connectionsareneeded.Withanonshared databaselink,100connectionsareneeded.

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';

WheneveryouusethekeywordSHARED,theclauseAUTHENTICATEDBYis required.TheschemaspeciedintheAUTHENTICATEDBYclauseisonlyusedfor securityreasonsandcanbeconsideredadummyschema.Itisnotaffectedwhen usingshareddatabaselinks,nordoesitaffecttheusersoftheshareddatabaselink. TheAUTHENTICATEDBYclauseisrequiredtopreventunauthorizedclientsfrom masqueradingasadatabaselinkuserandgainingaccesstoprivilegedinformation.


SeeAlso:

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 Shared Server Processes

Oracle ServerCode Dedicated Server Process

Oracle ServerCode

SystemGlobalArea

SystemGlobalArea

CreatingSharedLinkstoSharedServers
ThecongurationillustratedinFigure302 uses sharedserverprocessesonthe remoteserver.Thiscongurationeliminatestheneedformorededicatedservers, butrequirestheconnectiontogothroughthedispatcherontheremoteserver.Note thatboththelocalandtheremoteservermustbeconguredassharedservers.

ManagingDatabaseLinks

Figure302

SharedDatabaseLinktoSharedServer
User Process User Process

ClientWorkstation
DatabaseServer

DispatcherProcesses

Shared Server Processes

DispatcherProcesses

Shared Server Processes

Oracle ServerCode

Oracle ServerCode

SystemGlobalArea

SystemGlobalArea

OracleNetServicesAdministrator'sGuideforinformation aboutthesharedserveroption
SeeAlso:

ManagingDatabaseLinks
Thissectioncontainsthefollowingtopics:

ClosingDatabaseLinks DroppingDatabaseLinks

ManagingDatabaseLinks

LimitingtheNumberofActiveDatabaseLinkConnections

ClosingDatabaseLinks
Ifyouaccessadatabaselinkinasession,thenthelinkremainsopenuntilyouclose thesession.Alinkisopeninthesensethataprocessisactiveoneachoftheremote databasesaccessedthroughthelink.Thissituationhasthefollowingconsequences:

If20usersopensessionsandaccessthesamepubliclinkinalocaldatabase, then20databaselinkconnectionsareopen. If20usersopensessionsandeachuseraccessesaprivatelink,then20database linkconnectionsareopen. Ifoneuserstartsasessionandaccesses20differentlinks,then20databaselink connectionsareopen.

Afteryoucloseasession,thelinksthatwereactiveinthesessionareautomatically closed.Youmayhaveoccasiontoclosethelinkmanually.Forexample,closelinks when:

Thenetworkconnectionestablishedbyalinkisusedinfrequentlyinan application. Theusersessionmustbeterminated.

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;

DB_LINK SALES.US.ORACLE.COM MKTG.US.ORACLE.COM 2rowsselected.

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

numberofremoteconnectionsthatasingleusersessioncanuseconcurrentlyin distributedtransactions. Notethefollowingconsiderationsforsettingthisparameter:

Thevalueshouldbegreaterthanorequaltothenumberofdatabasesreferred toinasingleSQLstatementthatreferencesmultipledatabases. Increasethevalueifseveraldistributeddatabasesareaccessedovertime.Thus, ifyouregularlyaccessthreedatabases,setOPEN_LINKSto3orgreater. ThedefaultvalueforOPEN_LINKSis4.IfOPEN_LINKSissetto0,thenno distributedtransactionsareallowed.


OracleDatabaseReferenceformoreinformationabout theOPEN_LINKSinitializationparameter SeeAlso:

ViewingInformationAboutDatabaseLinks
Thedatadictionaryofeachdatabasestoresthedenitionsofallthedatabaselinks inthedatabase.Youcanusedatadictionarytablesandviewstogaininformation aboutthelinks.Thissectioncontainsthefollowingtopics:

DeterminingWhichLinksAreintheDatabase DeterminingWhichLinkConnectionsAreOpen

DeterminingWhichLinksAreintheDatabase
Thefollowingviewsshowthedatabaselinksthathavebeendenedatthelocal databaseandstoredinthedatadictionary:
View DBA_DB_LINKS
ALL_DB_LINKS

Purpose Listsalldatabaselinksinthedatabase. Listsalldatabaselinksaccessibletotheconnecteduser. Listsalldatabaselinksownedbytheconnecteduser.

USER_DB_LINKS

Thesedatadictionaryviewscontainthesamebasicinformationaboutdatabase links,withsomeexceptions:

ViewingInformationAboutDatabaseLinks

Column OWNER DB_LINK USERNAME

WhichViews? AllexceptUSER_* All All

Description Theuserwhocreatedthedatabaselink.Ifthelinkis public,thentheuserislistedasPUBLIC. Thenameofthedatabaselink. Ifthelinkdenitionincludesaxeduser,thenthis columndisplaystheusernameofthexeduser.If thereisnoxeduser,thecolumnisNULL. Thepasswordforloggingintotheremotedatabase. Thenetservicenameusedtoconnecttotheremote database. Creationtimeofthedatabaselink.

PASSWORD

OnlyUSER_* All All

HOST CREATED

AnyusercanqueryUSER_DB_LINKStodeterminewhichdatabaselinksare availabletothatuser.OnlythosewithadditionalprivilegescanusetheALL_DB_ LINKSorDBA_DB_LINKSview. ThefollowingscriptqueriestheDBA_DB_LINKSviewtoaccesslinkinformation:


COLOWNERFORMATa10 COLUSERNAMEFORMATA8HEADING"USER" COLDB_LINKFORMATA30 COLHOSTFORMATA7HEADING"SERVICE" SELECT*FROMDBA_DB_LINKS

Here,thescriptisinvokedandtheresultingoutputisshown:
SQL>@link_script

OWNERDB_LINKUSERSERVICECREATED SYSTARGET.US.ACME.COMSYSinst123JUN99 PUBLICDBL1.UK.ACME.COMBLAKEora5123JUN99 PUBLICRMAN2.US.ACME.COMinst223JUN99 PUBLICDEPT.US.ACME.COMinst223JUN99 JANEDBL.UK.ACME.COMBLAKEora5123JUN99 SCOTTEMP.US.ACME.COMSCOTTinst223JUN99 6rowsselected.

AuthorizationforViewingPasswordInformation
OnlyUSER_DB_LINKScontainsacolumnforpasswordinformation.However,if youareanadministrativeuser(SYSoruserswhoconnectASSYSDBA),thenyou

ViewingInformationAboutDatabaseLinks

canviewpasswordsforalllinksinthedatabasebyqueryingtheLINK$table.Ifyou arenotanadministrativeuser,youcanbeauthorizedtoquerytheLINK$tableby oneofthefollowingmethods:


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

SQL>@authpwd USERIDPASSWORD ELLIEMAY 1rowselected.

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

View V$DBLINK GV$DBLINK

Purpose Listsallopendatabaselinksinyoursession,thatis,alldatabase linkswiththeIN_TRANSACTIONcolumnsettoYES. Listsallopendatabaselinksinyoursessionalongwiththeir correspondinginstances.ThisviewisusefulinanOracleReal ApplicationClustersconguration.

Thesedatadictionaryviewscontainthesamebasicinformationaboutdatabase links,withoneexception:
Which Views? All All All All All All All

Column DB_LINK OWNER_ID LOGGED_ON HETEROGENEOUS PROTOCOL OPEN_CURSORS IN_TRANSACTION

Description Thenameofthedatabaselink. Theownerofthedatabaselink. Whetherthedatabaselinkiscurrentlyloggedon. Whetherthedatabaselinkishomogeneous(NO)or heterogeneous(YES). Thecommunicationprotocolforthedatabaselink. Whethercursorsareopenforthedatabaselink. Whetherthedatabaselinkisaccessedina transactionthathasnotyetbeencommittedor rolledback. Whethertherewasanupdateonthedatabaselink. Thecommitpointstrengthofthetransactions usingthedatabaselink. Theinstancefromwhichtheviewinformation wasobtained.

UPDATE_SENT COMMIT_POINT_ STRENGTH INST_ID

All All GV$DBLINK only

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 UsingSynonymstoCreateLocationTransparency UsingProcedurestoCreateLocationTransparency

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

MGR 7902 7698 7698 7839

HIREDATE 17DEC88 20FEB89 22JUN92 02APR93

SAL 800.00 1600.00 1250.00 2975.00

COMM 300.00 300.00 500.00

DEPTNO 20 30 30 20 Sales Database

MANAGER

COMPANYView EMPNOENAME 7329 7499 7521 7566 SMITH ALLEN WARD JONES DNAME MARKETING SALES SALES MARKETING Database Server

JWARD.DEPT DEPTNODNAME 20 30 MARKETING SALES HQ Database

Whenusersaccessthisview,theydonotneedtoknowwherethedataisphysically stored,orifdatafrommorethanonetableisbeingaccessed.Thus,itiseasierfor themtogetrequiredinformation.Forexample,thefollowingqueryprovidesdata fromboththelocalandremotedatabasetable:


SELECT*FROMcompany;

Theownerofthelocalviewcangrantonlythoseobjectprivilegesonthelocalview thathavebeengrantedbytheremoteuser.(Theremoteuserisimpliedbythetype

CreatingLocationTransparency

ofdatabaselink).Thisissimilartoprivilegemanagementforviewsthatreference localdata.

UsingSynonymstoCreateLocationTransparency
Synonymsareusefulinbothdistributedandnondistributedenvironmentsbecause theyhidetheidentityoftheunderlyingobject,includingitslocationinadistributed databasesystem.Ifyoumustrenameormovetheunderlyingobject,youonlyneed toredenethesynonym;applicationsbasedonthesynonymcontinuetofunction normally.SynonymsalsosimplifySQLstatementsforusersinadistributed databasesystem.

CreatingSynonyms
Youcancreatesynonymsforthefollowing:

Tables Types Views Materializedviews Sequences Procedures Functions Packages

Allsynonymsareschemaobjectsthatarestoredinthedatadictionaryofthe databaseinwhichtheyarecreated.Tosimplifyremotetableaccessthrough databaselinks,asynonymcanallowsinglewordaccesstoremotedata,hidingthe specicobjectnameandthelocationfromusersofthesynonym. Thesyntaxtocreateasynonymis:


CREATE[PUBLIC]

synonym_name

FOR[schema.]object_name[@database_link_name];

where:

PUBLICisakeywordspecifyingthatthissynonymisavailabletoallusers. Omittingthisparametermakesasynonymprivate,andusableonlybythe creator.PublicsynonymscanbecreatedonlybyauserwithCREATEPUBLIC SYNONYMsystemprivilege.

CreatingLocationTransparency

synonym_namespeciesthealternateobjectnametobereferencedbyusers andapplications. schemaspeciestheschemaoftheobjectspeciedinobject_name.Omitting thisparameterusestheschemaofthecreatorastheschemaoftheobject. object_namespecieseitheratable,view,sequence,materializedview,type, procedure,functionorpackageasappropriate. database_link_namespeciesthedatabaselinkidentifyingtheremote databaseandschemainwhichtheobjectspeciedinobject_nameislocated.

Asynonymmustbeauniquelynamedobjectforitsschema.Ifaschemacontainsa schemaobjectandapublicsynonymexistswiththesamename,thenthedatabase alwaysndstheschemaobjectwhentheuserthatownstheschemareferencesthat name. Example:CreatingaPublicSynonym Assumethatineverydatabaseinadistributeddatabasesystem,apublicsynonym isdenedforthescott.emptablestoredinthehqdatabase:


CREATEPUBLICSYNONYMempFORscott.emp@hq.acme.com;

Youcandesignanemployeemanagementapplicationwithoutregardtowherethe applicationisusedbecausethelocationofthetablescott.emp@hq.acme.comis hiddenbythepublicsynonyms.SQLstatementsintheapplicationaccessthetable byreferencingthepublicsynonymemp. Furthermore,ifyoumovetheemptablefromthehqdatabasetothehrdatabase, thenyouonlyneedtochangethepublicsynonymsonthenodesofthesystem.The employeemanagementapplicationcontinuestofunctionproperlyonallnodes.

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 UsingLocalProcedurestoCallRemoteProcedures UsingLocalSynonymstoReferenceRemoteProcedures

UsingLocalProcedurestoReferenceRemoteData
Proceduresorfunctions(eitherstandaloneorinpackages)cancontainSQL statementsthatreferenceremotedata.Forexample,considertheprocedurecreated bythefollowingstatement:
CREATEPROCEDUREfire_emp(enumNUMBER)AS BEGIN DELETEFROMemp@hq.acme.com WHEREempno=enum;

END;

Whenauserorapplicationcallsthefire_empprocedure,itisnotapparentthata remotetableisbeingmodied. Asecondlayeroflocationtransparencyispossiblewhenthestatementsina procedureindirectlyreferenceremotedatausinglocalprocedures,views,or synonyms.Forexample,thefollowingstatementdenesalocalsynonym:


CREATESYNONYMempFORemp@hq.acme.com;

CreatingLocationTransparency

Giventhissynonym,youcancreatethefire_empprocedureusingthefollowing statement:
CREATEPROCEDUREfire_emp(enumNUMBER)AS BEGIN DELETEFROMempWHEREempno=enum;

END;

Ifyourenameormovethetableemp@hq,thenyouonlyneedtomodifythelocal synonymthatreferencesthetable.Noneoftheproceduresandapplicationsthatcall theprocedurerequiremodication.

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

BEGIN DELETEFROMemp@hq.acme.com WHEREempno=enum;

END;

Userpeggythenconnectstothesupply.acme.comdatabaseandcreatesthe followingsynonymfortheprocedurethatscottcreatedontheremotesales database:


SQL>CONNECTpeggy/hill@supply SQL>CREATEPUBLICSYNONYMempFORscott.fire_emp@sales.acme.com;

Alocaluseronsupplycanusethissynonymtoexecutetheprocedureonsales.

ManagingProceduresandPrivileges
Assumealocalprocedureincludesastatementthatreferencesaremotetableor view.Theownerofthelocalprocedurecangranttheexecuteprivilegetoanyuser, therebygivingthatusertheabilitytoexecutetheprocedureand,indirectly,access remotedata. Ingeneral,proceduresaidinsecurity.Privilegesforobjectsreferencedwithina proceduredonotneedtobeexplicitlygrantedtothecallingusers.

ManagingStatementTransparency
ThedatabaseallowsthefollowingstandardDMLstatementstoreferenceremote tables:

SELECT(queries) INSERT UPDATE DELETE SELECT...FORUPDATE(notalwayssupportedinHeterogeneousSystems) LOCKTABLE

Queriesincludingjoins,aggregates,subqueries,andSELECT...FORUPDATE canreferenceanynumberoflocalandremotetablesandviews.Forexample,the followingqueryjoinsinformationfromtworemotetables:


SELECTe.empno,e.ename,d.dname FROMscott.emp@sales.division3.acme.come,jward.dept@hq.acme.comd

ManagingStatementTransparency

WHEREe.deptno=d.deptno;

Inahomogeneousenvironment,UPDATE,INSERT,DELETE,andLOCKTABLE statementscanreferencebothlocalandremotetables.Noprogrammingis necessarytoupdateremotedata.Forexample,thefollowingstatementinsertsnew rowsintotheremotetableempinthescott.salesschemabyselectingrowsfrom theemptableinthejwardschemainthelocaldatabase:


INSERTINTOscott.emp@sales.division3.acme.com SELECT*FROMjward.emp;

RestrictionsforStatementTransparency: Severalrestrictionsapplytostatementtransparency.

Datamanipulationlanguagestatementsthatupdateobjectsonaremote nonOracleDatabasesystemcannotreferenceanyobjectsonthelocalOracle Database.Forexample,astatementsuchasthefollowingwillcauseanerrorto beraised:


INSERTINTOremote_table@linkasSELECT*FROMlocal_table;

WithinasingleSQLstatement,allreferencedLONGandLONGRAWcolumns, sequences,updatedtables,andlockedtablesmustbelocatedatthesamenode. ThedatabasedoesnotallowremoteDDLstatements(forexample,CREATE, ALTER,andDROP)inhomogeneoussystemsexceptthroughremoteexecution ofproceduresoftheDBMS_SQLpackage,asinthisexample:


DBMS_SQL.PARSE@link_name(crs,'droptableemp',v7);

NotethatinHeterogeneousSystems,apassthroughfacilityletsyouexecute DDL.

TheLISTCHAINEDROWSclauseofanANALYZEstatementcannotreference remotetables. Inadistributeddatabasesystem,thedatabasealwaysevaluates environmentallydependentSQLfunctionssuchasSYSDATE,USER,UID,and USERENVwithrespecttothelocalserver,nomatterwherethestatement(or portionofastatement)executes.


Note:

OracleDatabasesupportstheUSERENVfunctionforqueries

only.

ManagingaDistributedDatabase:Examples

Anumberofperformancerestrictionsrelatetoaccessofremoteobjects: Remoteviewsdonothavestatisticaldata. Queriesonpartitionedtablesmaynotbeoptimized. Nomorethan20indexesareconsideredforaremotetable. Nomorethan20columnsareusedforacompositeindex.

ThereisarestrictionintheOracleDatabaseimplementationofdistributedread consistencythatcancauseonenodetobeinthepastwithrespecttoanother node.Inaccordancewithreadconsistency,aquerymayendupretrieving consistent,butoutofdatedata.See"ManagingReadConsistency" on page3325tolearnhowtomanagethisproblem.


SeeAlso:

informationabouttheDBMS_SQLpackage

PL/SQLPackagesandTypesReferenceformore

ManagingaDistributedDatabase:Examples
Thissectionpresentsexamplesillustratingmanagementofdatabaselinks:

Example1:CreatingaPublicFixedUserDatabaseLink Example2:CreatingaPublicFixedUserSharedDatabaseLink Example3:CreatingaPublicConnectedUserDatabaseLink Example4:CreatingaPublicConnectedUserSharedDatabaseLink Example5:CreatingaPublicCurrentUserDatabaseLink

Example1:CreatingaPublicFixedUserDatabaseLink
Thefollowingstatementsconnecttothelocaldatabaseasjaneandcreateapublic xeduserdatabaselinktodatabasesalesforscott.Thedatabaseisaccessed throughitsnetservicenamesldb:
CONNECTjane/doe@local

CREATEPUBLICDATABASELINKsales.division3.acme.com CONNECTTOscottIDENTIFIEDBYtiger USING'sldb';

ManagingaDistributedDatabase:Examples

Afterexecutingthesestatements,anyuserconnectedtothelocaldatabasecanuse thesales.division3.acme.comdatabaselinktoconnecttotheremote database.Eachuserconnectstotheschemascottintheremotedatabase. Toaccessthetableemptableinscott'sremoteschema,ausercanissuethe followingSQLquery:


SELECT*FROMemp@sales.division3.acme.com;

Notethateachapplicationorusersessioncreatesaseparateconnectiontothe commonaccountontheserver.Theconnectiontotheremotedatabaseremains openforthedurationoftheapplicationorusersession.

Example2:CreatingaPublicFixedUserSharedDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseasdanaandcreatesapublic linktothesalesdatabase(usingitsnetservicenamesldb).Thelinkallowsa connectiontotheremotedatabaseasscottandauthenticatesthisuserasscott:
CONNECTdana/sculley@local

CREATESHAREDPUBLICDATABASELINKsales.division3.acme.com CONNECTTOscottIDENTIFIEDBYtiger AUTHENTICATEDBYscottIDENTIFIEDBYtiger USING'sldb';

Now,anyuserconnectedtothelocalsharedservercanusethisdatabaselinkto connecttotheremotesalesdatabasethroughasharedserverprocess.Theuser canthenquerytablesinthescottschema. Intheprecedingexample,eachlocalsharedservercanestablishoneconnectionto theremoteserver.Wheneveralocalsharedserverprocessneedstoaccessthe remoteserverthroughthesales.division3.acme.comdatabaselink,thelocal sharedserverprocessreusesestablishednetworkconnections.

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

CREATESHAREDPUBLICDATABASELINKsales.division3.acme.com AUTHENTICATEDBYcrazyIDENTIFIEDBYhorse USING'sldb';

Eachuserconnectedtothelocalservercanusethisshareddatabaselinktoconnect totheremotedatabaseandquerythetablesinthecorrespondingremoteschema. Eachlocal,sharedserverprocessestablishesoneconnectiontotheremoteserver. Wheneveralocalserverprocessneedstoaccesstheremoteserverthroughthe sales.division3.acme.comdatabaselink,thelocalprocessreusesestablished networkconnections,eveniftheconnecteduserisadifferentuser. Ifthisdatabaselinkisusedfrequently,eventuallyeverysharedserverinthelocal databasewillhavearemoteconnection.Atthispoint,nomorephysicalconnections areneededtotheremoteserver,evenifnewusersusethisshareddatabaselink.

ManagingaDistributedDatabase:Examples

Example5:CreatingaPublicCurrentUserDatabaseLink
Thefollowingexampleconnectstothelocaldatabaseastheconnecteduserand createsapubliclinktothesalesdatabase(usingitsnetservicenamesldb).The followingstatementcreatesapubliccurrentuserdatabaselink:
CONNECTbart/simpson@local

CREATEPUBLICDATABASELINKsales.division3.acme.com CONNECTTOCURRENT_USER USING'sldb';

Note:

Tousethislink,thecurrentusermustbeaglobaluser.

Theconsequencesofthisdatabaselinkareasfollows: Assumescottcreateslocalprocedurefire_empthatdeletesarowfromthe remoteemptable,andgrantsexecuteprivilegeonfire_emptoford.


CONNECTscott/tiger@local_db

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);

Whenfordexecutestheprocedurescott.fire_emp,theprocedurerunsunder scott'sprivileges.Becauseacurrentuserdatabaselinkisused,theconnectionis establishedtoscott'sremoteschema,notford'sremoteschema.Notethatscott mustbeaglobaluserwhileforddoesnothavetobeaglobaluser.

ManagingaDistributedDatabase:Examples

Ifaconnecteduserdatabaselinkwereusedinstead,the connectionwouldbetoford'sremoteschema.Formore informationaboutinvokerrightsandprivileges,seethePL/SQL User'sGuideandReference.


Note:

Youcanaccomplishthesameresultbyusingaxeduserdatabaselinktoscott's remoteschema.Withxeduserdatabaselinks,however,securitycanbe compromisedbecausescott'susernameandpasswordareavailableinreadable formatinthedatabase.

DevelopingApplicationsforaDistributed DatabaseSystem
Thischapterdescribesconsiderationsimportantwhendevelopinganapplicationto runinadistributeddatabasesystem.Itcontainsthefollowingtopics:

ManagingtheDistributionofApplicationData ControllingConnectionsEstablishedbyDatabaseLinks MaintainingReferentialIntegrityinaDistributedSystem TuningDistributedQueries HandlingErrorsinRemoteProcedures


SeeAlso: OracleDatabaseApplicationDeveloper'sGuide

Fundamentalsformoreinformationaboutapplicationdevelopment inanOracleDatabaseenvironment

ManagingtheDistributionofApplicationData
Inadistributeddatabaseenvironment,coordinatewiththedatabaseadministrator todeterminethebestlocationforthedata.Someissuestoconsiderare:

Numberoftransactionspostedfromeachlocation Amountofdata(portionoftable)usedbyeachnode Performancecharacteristicsandreliabilityofthenetwork Speedofvariousnodes,capacitiesofdisks Importanceofanodeorlinkwhenitisunavailable Needforreferentialintegrityamongtables

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;

Tocloseadatabaselinkconnectioninyourusersession,youmusthavetheALTER SESSIONsystemprivilege. Beforeclosingadatabaselink,rstcloseallcursorsthatuse thelinkandthenendyourcurrenttransactionifitusesthelink.


Note: SeeAlso: OracleDatabaseSQLReferenceformoreinformation

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:

UsingCollocatedInlineViews UsingCostBasedOptimization UsingHints AnalyzingtheExecutionPlan

TuningDistributedQueries

UsingCollocatedInlineViews
Themosteffectivewayofoptimizingdistributedqueriesistoaccesstheremote databasesaslittleaspossibleandtoretrieveonlytherequireddata. Forexample,assumeyoureferenceveremotetablesfromtwodifferentremote databasesinadistributedqueryandhaveacomplexlter(forexample,WHERE r1.salary+r2.salary>50000).Youcanimprovetheperformanceofthe querybyrewritingthequerytoaccesstheremotedatabasesonceandtoapplythe lterattheremotesite.Thisrewritecauseslessdatatobetransferredtothequery executionsite. Rewritingyourquerytoaccesstheremotedatabaseonceisachievedbyusing collocatedinlineviews.Thefollowingtermsneedtobedened:

Collocated Twoormoretableslocatedinthesamedatabase. Inlineview ASELECTstatementthatissubstitutedforatableinaparentSELECT statement.TheembeddedSELECTstatement,shownwithintheparenthesesis anexampleofaninlineview:


SELECTe.empno,e.ename,d.deptno,d.dname FROM(SELECTempno,enamefrom emp@orc1.world)e,deptd;

Collocatedinlineview Aninlineviewthatselectsdatafrommultipletablesfromasingledatabase only.Itreducestheamountoftimesthattheremotedatabaseisaccessed, improvingtheperformanceofadistributedquery.

Oraclerecommendsthatyouformyourdistributedqueryusingcollocatedinline viewstoincreasetheperformanceofyourdistributedquery.OracleDatabase costbasedoptimizationcantransparentlyrewritemanyofyourdistributedqueries totakeadvantageoftheperformancegainsofferedbycollocatedinlineviews.

UsingCostBasedOptimization
Inadditiontorewritingyourquerieswithcollocatedinlineviews,thecostbased optimizationmethodoptimizesdistributedqueriesaccordingtothegathered
statisticsofthereferencedtablesandthecomputationsperformedbytheoptimizer.

TuningDistributedQueries

Forexample,costbasedoptimizationanalyzesthefollowingquery.Theexample assumesthattablestatisticsareavailable.Notethatitanalyzesthequeryinsidea CREATETABLEstatement:


CREATETABLEAS( SELECTl.a,l.b,r1.c,r1.d,r1.e,r2.b,r2.c FROMlocall,remote1r1,remote2r2 WHEREl.c=r.c ANDr1.c=r2.c ANDr.e>300 );

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 );

Thealiasvisassignedtotheinlineview,whichcanthenbereferencedasatablein theprecedingSELECTstatement.Creatingacollocatedinlineviewreducesthe amountofqueriesperformedataremotesite,therebyreducingcostlynetwork trafc.

HowDoesCostBasedOptimizationWork?
Themaintaskofoptimizationistorewriteadistributedquerytousecollocated inlineviews.Thisoptimizationisperformedinthreesteps:
1. 2. 3.

Allmergeableviewsaremerged. Optimizerperformscollocatedqueryblocktest. Optimizerrewritesqueryusingcollocatedinlineviews.

Afterthequeryisrewritten,itisexecutedandthedatasetisreturnedtotheuser. Whilecostbasedoptimizationisperformedtransparentlytotheuser,itisunableto improvetheperformanceofseveraldistributedqueryscenarios.Specically,ifyour distributedquerycontainsanyofthefollowing,costbasedoptimizationisnot effective:

TuningDistributedQueries

Aggregates Subqueries ComplexSQL

Ifyourdistributedquerycontainsoneoftheseelements,see"UsingHints" on page317tolearnhowyoucanmodifyyourqueryandusehintstoimprovethe performanceofyourdistributedquery.

SettingUpCostBasedOptimization
Afteryouhavesetupyoursystemtousecostbasedoptimizationtoimprovethe performanceofdistributedqueries,theoperationistransparenttotheuser.Inother words,theoptimizationoccursautomaticallywhenthequeryisissued.
Youneedtocompletethefollowingtaskstosetupyoursystemtotakeadvantageof

costbasedoptimization:

SettingUptheEnvironment AnalyzingTables

SettingUptheEnvironment Toenablecostbasedoptimization,settheOPTIMIZER_

MODEinitializationparametertoCHOOSEorCOST.Youcansetthisparameterby: ModifyingtheOPTIMIZER_MODEparameterintheinitializationparameterle SettingitatsessionlevelbyissuinganALTERSESSIONstatement

IssueoneofthefollowingstatementstosettheOPTIMIZER_MODEinitialization parameteratthesessionlevel:
ALTERSESSIONOPTIMIZER_MODE=CHOOSE; ALTERSESSIONOPTIMIZER_MODE=COST;

OracleDatabasePerformanceTuningGuidefor informationonsettingtheOPTIMIZER_MODEinitialization parameterintheparameterleandforconguringyoursystemto useacostbasedoptimizationmethod SeeAlso: AnalyzingTables Forcostbasedoptimizationtoselectthemostefcientpathfora

distributedquery,youmustprovideaccuratestatisticsforthetablesinvolved.You dothisusingtheDBMS_STATSpackageortheANALYZEstatement.

TuningDistributedQueries

Youmustconnectlocallywithrespecttothetableswhen executingtheDBMS_STATSprocedureorANALYZEstatement.For example,youcannotexecutethefollowing:


Note:
ANALYZETABLEremote@remote.comCOMPUTESTATISTICS;

Youmustrstconnecttotheremotesiteandthenexecutethe precedingANALYZEstatement,ortheequivalentDBMS_STATS procedure. ThefollowingDBMS_STATSproceduresenablethegatheringofcertainclassesof optimizerstatistics:


GATHER_INDEX_STATS GATHER_TABLE_STATS GATHER_SCHEMA_STATS GATHER_DATABASE_STATS

Forexample,assumethatdistributedtransactionsroutinelyaccessthescott.dept table.Toensurethatthecostbasedoptimizerisstillpickingthebestplan,execute thefollowing:


BEGIN DBMS_STATS.GATHER_TABLE_STATS('scott','dept');

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*/

SELECT/*+NO_MERGE(v)*/t1.x,v.avg_y FROMt1,(SELECTx,AVG(y)ASavg_yFROMt2GROUPBYx)v, WHEREt1.x=v.xANDt1.y=1; /*inqueryblock*/ SELECTt1.x,v.avg_y FROMt1,(SELECT/*+NO_MERGE*/x,AVG(y)ASavg_yFROMt2GROUPBYx)v, WHEREt1.x=v.xANDt1.y=1;

Typically,youusethishintwhenyouhavedevelopedanoptimizedquerybasedon yourknowledgeofyourdatabaseenvironment.
UsingtheDRIVING_SITEHint

TheDRIVING_SITEhintletsyouspecifythesitewherethequeryexecutionis performed.Itisbesttoletcostbasedoptimizationdeterminewheretheexecution

TuningDistributedQueries

shouldbeperformed,butifyouprefertooverridetheoptimizer,youcanspecify theexecutionsitemanually. FollowingisanexampleofaSELECTstatementwithaDRIVING_SITEhint:


SELECT/*+DRIVING_SITE(dept)*/*FROMemp,dept@remote.com WHEREemp.deptno=dept.deptno;

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

EXPLAINPLANFOR SELECTd.dname FROMdeptd WHEREd.deptno IN(SELECTdeptno FROMemp@orc2.world GROUPBYdeptno HAVINGCOUNT(deptno)>3 )

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||||||

Ifyouaremanuallyoptimizingdistributedqueriesbywritingyourowncollocated inlineviewsorusinghints,itisbesttogenerateanexecutionplanbeforeandafter yourmanualoptimization.Withbothexecutionplans,youcancomparethe effectivenessofyourmanualoptimizationandmakechangesasnecessaryto improvetheperformanceofthedistributedquery.

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:

PL/SQLuserdenedexceptions,whichmustbedeclaredusingthekeyword EXCEPTION PL/SQLpredenedexceptionssuchastheNO_DATA_FOUNDkeyword SQLerrorssuchasORA00900andORA02015 ApplicationexceptionsgeneratedusingtheRAISE_APPLICATION_ERROR() procedure

Whenusinglocalprocedures,youcantrapthesemessagesbywritinganexception handlersuchasthefollowing
BEGIN ... EXCEPTION WHENZERO_DIVIDETHEN /*...handletheexception*/

END;

NoticethattheWHENclauserequiresanexceptionname.Iftheexceptiondoesnot haveaname,forexample,exceptionsgeneratedwithRAISE_APPLICATION_ ERROR,youcanassignoneusingPRAGMA_EXCEPTION_INIT.Forexample:

HandlingErrorsinRemoteProcedures

DECLARE null_salaryEXCEPTION; PRAGMAEXCEPTION_INIT(null_salary,20101); BEGIN ... RAISE_APPLICATION_ERROR(20101,'salaryismissing');

...
EXCEPTION WHENnull_salaryTHEN ...

END;

Whencallingaremoteprocedure,exceptionscanbehandledbyanexception handlerinthelocalprocedure.Theremoteproceduremustreturnanerrornumber tothelocal,callingprocedure,whichthenhandlestheexceptionasshowninthe previousexample.NotethatPL/SQLuserdenedexceptionsalwaysreturn ORA06510tothelocalprocedure. Therefore,itisnotpossibletodistinguishbetweentwodifferentuserdened exceptionsbasedontheerrornumber.Allotherremoteexceptionscanbehandled inthesamemanneraslocalexceptions.


SeeAlso:

aboutPL/SQLprocedures

PL/SQLUser'sGuideandReferenceformoreinformation

DistributedTransactionsConcepts
ThischapterdescribeswhatdistributedtransactionsareandhowOracleDatabase maintainstheirintegrity.Thefollowingtopicsarecontainedinthischapter:

WhatAreDistributedTransactions? SessionTreesforDistributedTransactions TwoPhaseCommitMechanism InDoubtTransactions DistributedTransactionProcessing:CaseStudy

WhatAreDistributedTransactions?
Adistributedtransactionincludesoneormorestatementsthat,individuallyorasa group,updatedataontwoormoredistinctnodesofadistributeddatabase.For example,assumethedatabasecongurationdepictedinFigure321:

WhatAreDistributedTransactions?

Figure321

DistributedSystem
depttable OracleNet databaselink HQ

emptable SALES bldgtable OracleNet


databaselink

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:

CREATETABLEASSELECT DELETE INSERT(defaultanddirectload) LOCKTABLE SELECT SELECTFORUPDATE

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:

COMMIT ROLLBACK SAVEPOINT

SessionTreesforDistributedTransactions

SeeAlso:

OracleDatabaseSQLReferenceformoreinformation

abouttheseSQLstatements

SessionTreesforDistributedTransactions
Asthestatementsinadistributedtransactionareissued,thedatabasedenesa sessiontreeofallnodesparticipatinginthetransaction.Asessiontreeisa hierarchicalmodelthatdescribestherelationshipsamongsessionsandtheirroles. Figure322 illustrates asessiontree:
Figure322 ExampleofaSessionTree

INSERTINTOorders...; UPDATEinventory@warehouse...; UPDATEaccts_rec@finance...;

COMMIT;

SALES.ACME.COM

GlobalCoordinator CommitPointSite DatabaseServer WAREHOUSE.ACME.COM


FINANCE.ACME.COM

Client

Allnodesparticipatinginthesessiontreeofadistributedtransactionassumeoneor moreofthefollowingroles:
Role Client Description Anodethatreferencesinformationinadatabasebelongingtoa differentnode.

SessionTreesforDistributedTransactions

Role Databaseserver Globalcoordinator Localcoordinator Commitpointsite

Description Anodethatreceivesarequestforinformationfromanother node. Thenodethatoriginatesthedistributedtransaction. Anodethatisforcedtoreferencedataonothernodesto completeitspartofthetransaction. Thenodethatcommitsorrollsbackthetransactionas instructedbytheglobalcoordinator.

Theroleanodeplaysinadistributedtransactionisdeterminedby:

Whetherthetransactionislocalorremote Thecommitpointstrengthofthenode("CommitPointSite" onpage326) Whetherallrequesteddataisavailableatanode,orwhetherothernodesneed tobereferencedtocompletethetransaction Whetherthenodeisreadonly

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

finance. Thenodesalesalsohappenstobetheglobalcoordinatorbecauseit coordinatesallthenodesinvolvedinthetransaction. Alocalcoordinatorisresponsibleforcoordinatingthetransactionamongthenodes itcommunicatesdirectlywithby:


Receivingandrelayingtransactionstatusinformationtoandfromthosenodes Passingqueriestothosenodes Receivingqueriesfromthosenodesandpassingthemontoothernodes Returningtheresultsofqueriestothenodesthatinitiatedthem

GlobalCoordinator
Thenodewherethedistributedtransactionoriginatesiscalledtheglobal coordinator.Thedatabaseapplicationissuingthedistributedtransactionisdirectly connectedtothenodeactingastheglobalcoordinator.Forexample,inFigure322, thetransactionissuedatthenodesalesreferencesinformationfromthedatabase serverswarehouseandfinance.Therefore,sales.acme.comistheglobal coordinatorofthisdistributedtransaction. Theglobalcoordinatorbecomestheparentorrootofthesessiontree.Theglobal coordinatorperformsthefollowingoperationsduringadistributedtransaction:

SendsallofthedistributedtransactionSQLstatements,remoteprocedurecalls, andsoforthtothedirectlyreferencednodes,thusformingthesessiontree Instructsalldirectlyreferencednodesotherthanthecommitpointsiteto preparethetransaction Instructsthecommitpointsitetoinitiatetheglobalcommitofthetransactionif allnodespreparesuccessfully Instructsallnodestoinitiateaglobalrollbackofthetransactionifthereisan abortresponse

CommitPointSite
Thejobofthecommitpointsiteistoinitiateacommitorrollbackoperationas instructedbytheglobalcoordinator.Thesystemadministratoralwaysdesignates onenodetobethecommitpointsiteinthesessiontreebyassigningallnodesa commitpointstrength.Thenodeselectedascommitpointsiteshouldbethenode thatstoresthemostcriticaldata.

SessionTreesforDistributedTransactions

Figure323 illustrates anexampleofdistributedsystem,withsalesservingasthe commitpointsite:


Figure323 CommitPointSite

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

site.Theredologatthecommitpointsiteisupdatedassoonasthedistributed transactioniscommittedatthisnode. Becausethecommitpointlogcontainsarecordofthecommit,thetransactionis consideredcommittedeventhoughsomeparticipatingnodesmaystillbeonlyin thepreparedstateandthetransactionnotyetactuallycommittedatthesenodes.In thesameway,adistributedtransactionisconsiderednotcommittedifthecommit hasnotbeenloggedatthecommitpointsite.

CommitPointStrength
Everydatabaseservermustbeassignedacommitpointstrength.Ifadatabase serverisreferencedinadistributedtransaction,thevalueofitscommitpoint strengthdetermineswhichroleitplaysinthetwophasecommit.Specically,the commitpointstrengthdetermineswhetheragivennodeisthecommitpointsitein thedistributedtransactionandthuscommitsbeforealloftheothernodes.This valueisspeciedusingtheinitializationparameterCOMMIT_POINT_STRENGTH. Thissectionexplainshowthedatabasedeterminesthecommitpointsite. Thecommitpointsite,whichisdeterminedatthebeginningofthepreparephase,is selectedonlyfromthenodesparticipatinginthetransaction.Thefollowing sequenceofeventsoccurs:
1. 2. 3.

Ofthenodesdirectlyreferencedbytheglobalcoordinator,thedatabaseselects thenodewiththehighestcommitpointstrengthasthecommitpointsite. Theinitiallyselectednodedeterminesifanyofthenodesfromwhichithasto obtaininformationforthistransactionhasahighercommitpointstrength. Eitherthenodewiththehighestcommitpointstrengthdirectlyreferencedin thetransactionoroneofitsserverswithahighercommitpointstrength becomesthecommitpointsite. Afterthenalcommitpointsitehasbeendetermined,theglobalcoordinator sendsprepareresponsestoallnodesparticipatinginthetransaction.

4.

Figure324 shows inasamplesessiontreethecommitpointstrengthsofeachnode (inparentheses)andshowsthenodechosenasthecommitpointsite:

SessionTreesforDistributedTransactions

Figure324

CommitPointStrengthsandDeterminationoftheCommitPointSite
SALES.ACME.COM (45)

HQ.ACME.COM (165) WAREHOUSE.ACME.COM (140)

GlobalCoordinator CommitPointSite FINANCE.ACME.COM (45) HR.ACME.COM (45) DatabaseServer Client

Thefollowingconditionsapplywhendeterminingthecommitpointsite:

Areadonlynodecannotbethecommitpointsite. Ifmultiplenodesdirectlyreferencedbytheglobalcoordinatorhavethesame commitpointstrength,thenthedatabasedesignatesoneoftheseasthecommit pointsite. Ifadistributedtransactionendswitharollback,thentheprepareandcommit phasesarenotneeded.Consequently,thedatabaseneverdeterminesacommit pointsite.Instead,theglobalcoordinatorsendsaROLLBACKstatementtoall nodesandendstheprocessingofthedistributedtransaction.

AsFigure324 illustrates, thecommitpointsiteandtheglobalcoordinatorcanbe differentnodesofthesessiontree.Thecommitpointstrengthofeachnodeis communicatedtothecoordinatorswhentheinitialconnectionsaremade.The coordinatorsretainthecommitpointstrengthsofeachnodetheyareindirect communicationwithsothatcommitpointsitescanbeefcientlyselectedduring twophasecommits.Therefore,itisnotnecessaryforthecommitpointstrengthto beexchangedbetweenacoordinatorandanodeeachtimeacommitoccurs.

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

mechanism.Thismechanismiscompletelytransparent,requiringnoprogramming onthepartoftheuserorapplicationdeveloper. Thecommitmechanismhasthefollowingdistinctphases,whichthedatabase performsautomaticallywheneverausercommitsadistributedtransaction:


Phase Preparephase Description Theinitiatingnode,calledtheglobalcoordinator,asks participatingnodesotherthanthecommitpointsitetopromise tocommitorrollbackthetransaction,evenifthereisafailure. Ifanynodecannotprepare,thetransactionisrolledback. Ifallparticipantsrespondtothecoordinatorthattheyare prepared,thenthecoordinatorasksthecommitpointsiteto commit.Afteritcommits,thecoordinatorasksallothernodes tocommitthetransaction.

Commitphase

TwoPhaseCommitMechanism

Phase Forgetphase

Description Theglobalcoordinatorforgetsaboutthetransaction.

Thissectioncontainsthefollowingtopics:

PreparePhase CommitPhase ForgetPhase

PreparePhase
Therstphaseincommittingadistributedtransactionisthepreparephase.Inthis phase,thedatabasedoesnotactuallycommitorrollbackthetransaction.Instead, allnodesreferencedinadistributedtransaction(exceptthecommitpointsite, describedinthe"CommitPointSite"onpage326)aretoldtopreparetocommit.By preparing,anode:

Recordsinformationintheredologssothatitcansubsequentlyeithercommit orrollbackthetransaction,regardlessofinterveningfailures Placesadistributedlockonmodiedtables,whichpreventsreads

Whenanoderespondstotheglobalcoordinatorthatitispreparedtocommit,the preparednodepromisestoeithercommitorrollbackthetransactionlater,butdoes notmakeaunilateraldecisiononwhethertocommitorrollbackthetransaction. Thepromisemeansthatifaninstancefailureoccursatthispoint,thenodecanuse theredorecordsintheonlinelogtorecoverthedatabasebacktothepreparephase. Queriesthatstartafteranodehaspreparedcannotaccess theassociatedlockeddatauntilallphasescomplete.Thetimeis insignicantunlessafailureoccurs(see"DecidingHowtoHandle InDoubtTransactions" onpage337).
Note:

TypesofResponsesinthePreparePhase
Whenanodeistoldtoprepare,itcanrespondinthefollowingways:

TwoPhaseCommitMechanism

Response Prepared Readonly Abort

Meaning Dataonthenodehasbeenmodiedbyastatementinthe distributedtransaction,andthenodehassuccessfullyprepared. Nodataonthenodehasbeen,orcanbe,modied(only queried),sonopreparationisnecessary. Thenodecannotsuccessfullyprepare.

PreparedResponse Whenanodehassuccessfullyprepared,itissuesaprepared

message.Themessageindicatesthatthenodehasrecordsofthechangesinthe onlinelog,soitispreparedeithertocommitorperformarollback.Themessage alsoguaranteesthatlocksheldforthetransactioncansurviveafailure.


ReadOnlyResponse Whenanodeisaskedtoprepare,andtheSQLstatements

affectingthedatabasedonotchangeanydataonthenode,thenoderespondswith areadonlymessage.Themessageindicatesthatthenodewillnotparticipateinthe commitphase. Therearethreecasesinwhichallorpartofadistributedtransactionisreadonly:


Case Partiallyreadonly Conditions Anyofthefollowingoccurs:

Consequence Thereadonlynodesrecognize theirstatuswhenaskedto prepare.Theygivetheirlocal coordinatorsareadonly response.Thus,thecommitphase completesfasterbecausethe databaseeliminatesreadonly nodesfromsubsequent processing. Allnodesrecognizethattheyare readonlyduringpreparephase, sonocommitphaseisrequired. Theglobalcoordinator,not knowingwhetherallnodesare readonly,muststillperformthe preparephase.

Onlyqueriesareissuedat oneormorenodes. Nodataischanged. Changesrolledbackdue totriggersringor constraintviolations.

Completelyreadonly withpreparephase

Alloffollowingoccur:

Nodatachanges. Transactionisnotstarted withSETTRANSACTION READONLYstatement.

TwoPhaseCommitMechanism

Case Completelyreadonly withouttwophase commit

Conditions Alloffollowingoccur:

Consequence Onlyqueriesareallowedinthe transaction,soglobalcoordinator doesnothavetoperform twophasecommit.Changesby othertransactionsdonotdegrade globaltransactionlevelread consistencybecauseofglobal SCNcoordinationamongnodes. Thetransactiondoesnotuse undosegments.

Nodatachanges. Transactionisstartedwith SETTRANSACTION READONLYstatement.

Notethatifadistributedtransactionissettoreadonly,thenitdoesnotuseundo segments.Ifmanyusersconnecttothedatabaseandtheirtransactionsarenotsetto READONLY,thentheyallocateundospaceeveniftheyareonlyperforming queries.


AbortResponse Whenanodecannotsuccessfullyprepare,itperformsthefollowing

actions:
1. 2.

Releasesresourcescurrentlyheldbythetransactionandrollsbackthelocal portionofthetransaction. Respondstothenodethatreferenceditinthedistributedtransactionwithan abortmessage.

Theseactionsthenpropagatetotheothernodesinvolvedinthedistributed transactionsothattheycanrollbackthetransactionandguaranteetheintegrityof thedataintheglobaldatabase.Thisresponseenforcestheprimaryruleofa distributedtransaction:allnodesinvolvedinthetransactioneitherallcommitorallroll backthetransactionatthesamelogicaltime.

StepsinthePreparePhase
Tocompletethepreparephase,eachnodeexcludingthecommitpointsiteperforms thefollowingsteps:
1. 2.

Thenoderequeststhatitsdescendants,thatis,thenodessubsequently referenced,preparetocommit. Thenodecheckstoseewhetherthetransactionchangesdataonitselforits


descendants.Ifthereisnochangetothedata,thenthenodeskipstheremaining

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).

Theseactionsguaranteethatthenodecansubsequentlycommitorrollbackthe transactiononthenode.ThepreparednodesthenwaituntilaCOMMITor ROLLBACKrequestisreceivedfromtheglobalcoordinator. Afterthenodesareprepared,thedistributedtransactionissaidtobeindoubt(see "InDoubtTransactions" onpage3216).It retainsindoubtstatusuntilallchanges areeithercommittedorrolledback.

CommitPhase
Thesecondphaseincommittingadistributedtransactionisthecommitphase. Beforethisphaseoccurs,allnodesotherthanthecommitpointsitereferencedinthe distributedtransactionhaveguaranteedthattheyareprepared,thatis,theyhave thenecessaryresourcestocommitthetransaction.

StepsintheCommitPhase
Thecommitphaseconsistsofthefollowingsteps:
1. 2. 3. 4. 5. 6.

Theglobalcoordinatorinstructsthecommitpointsitetocommit. Thecommitpointsitecommits. Thecommitpointsiteinformstheglobalcoordinatorthatithascommitted. Theglobalandlocalcoordinatorssendamessagetoallnodesinstructingthem tocommitthetransaction. Ateachnode,thedatabasecommitsthelocalportionofthedistributed transactionandreleaseslocks. Ateachnode,thedatabaserecordsanadditionalredoentryinthelocalredo log,indicatingthatthetransactionhascommitted.

TwoPhaseCommitMechanism

7.

Theparticipatingnodesnotifytheglobalcoordinatorthattheyhavecommitted.

Whenthecommitphaseiscomplete,thedataonallnodesofthedistributedsystem isconsistent.

GuaranteeingGlobalDatabaseConsistency
Eachcommittedtransactionhasanassociatedsystemchangenumber(SCN)to uniquelyidentifythechangesmadebytheSQLstatementswithinthattransaction. TheSCNfunctionsasaninternaltimestampthatuniquelyidentiesacommitted versionofthedatabase. Inadistributedsystem,theSCNsofcommunicatingnodesarecoordinatedwhen allofthefollowingactionsoccur:

Aconnectionoccursusingthepathdescribedbyoneormoredatabaselinks AdistributedSQLstatementexecutes Adistributedtransactioncommits

Amongotherbenets,thecoordinationofSCNsamongthenodesofadistributed systemensuresglobalreadconsistencyatboththestatementandtransactionlevel. Ifnecessary,globaltimebasedrecoverycanalsobecompleted. Duringthepreparephase,thedatabasedeterminesthehighestSCNatallnodes involvedinthetransaction.ThetransactionthencommitswiththehighSCNatthe commitpointsite.ThecommitSCNisthensenttoallpreparednodeswiththe commitdecision. "ManagingReadConsistency" onpage3325 for informationaboutmanagingtimelagissuesinreadconsistency
SeeAlso:

ForgetPhase
Aftertheparticipatingnodesnotifythecommitpointsitethattheyhavecommitted, thecommitpointsitecanforgetaboutthetransaction.Thefollowingstepsoccur:
1.

Afterreceivingnoticefromtheglobalcoordinatorthatallnodeshave committed,thecommitpointsiteerasesstatusinformationaboutthis transaction. Thecommitpointsiteinformstheglobalcoordinatorthatithaserasedthe statusinformation. Theglobalcoordinatorerasesitsowninformationaboutthetransaction.

2. 3.

InDoubtTransactions

InDoubtTransactions
Thetwophasecommitmechanismensuresthatallnodeseithercommitorperform arollbacktogether.Whathappensifanyofthethreephasesfailsbecauseofa systemornetworkerror?Thetransactionbecomesindoubt. Distributedtransactionscanbecomeindoubtinthefollowingways:

AservermachinerunningOracleDatabasesoftwarecrashes AnetworkconnectionbetweentwoormoreOracleDatabasesinvolvedin distributedprocessingisdisconnected Anunhandledsoftwareerroroccurs

TheRECOprocessautomaticallyresolvesindoubttransactionswhenthemachine, network,orsoftwareproblemisresolved.UntilRECOcanresolvethetransaction, thedataislockedforbothreadsandwrites.Thedatabaseblocksreadsbecauseit cannotdeterminewhichversionofthedatatodisplayforaquery. Thissectioncontainsthefollowingtopics:


AutomaticResolutionofInDoubtTransactions ManualResolutionofInDoubtTransactions RelevanceofSystemChangeNumbersforInDoubtTransactions

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.

UserScottconnectstolocalandexecutesadistributedtransaction. Theglobalcoordinator,whichinthisexampleisalsothecommitpointsite, requestsalldatabasesotherthanthecommitpointsitetopromisetocommitor rollbackwhentoldtodoso. Theremotedatabasecrashesbeforeissuingtheprepareresponsebackto local. ThetransactionisultimatelyrolledbackoneachdatabasebytheRECOprocess whentheremotesiteisrestored.

3. 4.

FailureDuringtheCommitPhase
Figure326 illustrates thesequenceofeventswhenthereisafailureduringthe commitphaseofadistributedtransaction:

InDoubtTransactions

Figure326

FailureDuringCommitPhase

6 4 3
Local

Alldatabasescommitafter networkrestored AsksREMOTEtocommit ReceivespreparemessagefromREMOTE AsksREMOTEtoprepare

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:

Theindoubttransactionhaslocksoncriticaldataorundosegments. Thecauseofthemachine,network,orsoftwarefailurecannotberepaired quickly.

Resolutionofindoubttransactionscanbecomplicated.Theprocedurerequiresthat youdothefollowing:

Identifythetransactionidenticationnumberfortheindoubttransaction. QuerytheDBA_2PC_PENDINGandDBA_2PC_NEIGHBORSviewstodetermine whetherthedatabasesinvolvedinthetransactionhavecommitted. Ifnecessary,forceacommitusingtheCOMMITFORCEstatementorarollback usingtheROLLBACKFORCEstatement.


SeeAlso:

transactions:

Thefollowingsectionsexplainhowtoresolveindoubt

"DecidingHowtoHandleInDoubtTransactions" onpage337 "ManuallyOverridingInDoubtTransactions" onpage3310

RelevanceofSystemChangeNumbersforInDoubtTransactions
Asystemchangenumber(SCN)isaninternaltimestampforacommittedversion ofthedatabase.TheOracleDatabaseserverusestheSCNclockvaluetoguarantee transactionconsistency.Forexample,whenausercommitsatransaction,the databaserecordsanSCNforthiscommitintheredolog. ThedatabaseusesSCNstocoordinatedistributedtransactionsamongdifferent databases.Forexample,thedatabaseusesSCNsinthefollowingway:
1. 2. 3.

Anapplicationestablishesaconnectionusingadatabaselink. ThedistributedtransactioncommitswiththehighestglobalSCNamongallthe databasesinvolved. ThecommitglobalSCNissenttoalldatabasesinvolvedinthetransaction.

SCNsareimportantfordistributedtransactionsbecausetheyfunctionasa synchronizedcommittimestampofatransaction,evenifthetransactionfails.Ifa transactionbecomesindoubt,anadministratorcanusethisSCNtocoordinate changesmadetotheglobaldatabase.TheglobalSCNforthetransactioncommit

DistributedTransactionProcessing:CaseStudy

canalsobeusedtoidentifythetransactionlater,forexample,indistributed recovery.

DistributedTransactionProcessing:CaseStudy
Inthisscenario,acompanyhasseparateOracleDatabaseservers, sales.acme.comandwarehouse.acme.com.Asusersinsertsalesrecordsinto thesalesdatabase,associatedrecordsarebeingupdatedatthewarehouse database. Thiscasestudyofdistributedprocessingillustrates:

Thedenitionofasessiontree Howacommitpointsiteisdetermined Whenpreparemessagesaresent Whenatransactionactuallycommits Whatinformationisstoredlocallyaboutthetransaction

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;

TheseSQLstatementsarepartofasingledistributedtransaction,guaranteeingthat allissuedSQLstatementssucceedorfailasaunit.Treatingthestatementsasaunit preventsthepossibilityofanorderbeingplacedandtheninventorynotbeing updatedtoreecttheorder.Ineffect,thetransactionguaranteestheconsistencyof dataintheglobaldatabase. AseachoftheSQLstatementsinthetransactionexecutes,thesessiontreeis dened,asshowninFigure327 .

DistributedTransactionProcessing:CaseStudy

Figure327

DeningtheSessionTree

INSERTINTOorders...; UPDATEinventory@warehouse...; INSERTINTOorders...; UPDATEinventory@warehouse...; COMMIT;

SALES.ACME.COM

SQL GlobalCoordinator CommitPointSite DatabaseServer WAREHOUSE.ACME.COM Client

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.

Thisstagecompletesthedenitionofthesessiontreeforthisdistributed transaction.Eachnodeinthetreehasacquiredthenecessarydatalockstoexecute theSQLstatementsthatreferencelocaldata.TheselocksremainevenaftertheSQL statementshavebeenexecuteduntilthetwophasecommitiscompleted.

DistributedTransactionProcessing:CaseStudy

Stage2:OracleDatabaseDeterminesCommitPointSite
ThedatabasedeterminesthecommitpointsiteimmediatelyfollowingtheCOMMIT statement.sales.acme.com,theglobalcoordinator,isdeterminedtobethe commitpointsite,asshowninFigure328 . "CommitPointStrength" onpage328 formore informationabouthowthecommitpointsiteisdetermined
SeeAlso: Figure328 DeterminingtheCommitPointSite

SALES.ACME.COM

Commit GlobalCoordinator CommitPointSite DatabaseServer WAREHOUSE.ACME.COM Client

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

Ifanyofthenodesaskedtopreparerespondswithanabortmessagetothe globalcoordinator,thentheglobalcoordinatortellsallnodestorollbackthe transaction,andtheoperationiscompleted. Ifallnodesaskedtopreparerespondwithapreparedorareadonlymessageto theglobalcoordinator,thatis,theyhavesuccessfullyprepared,thentheglobal coordinatorasksthecommitpointsitetocommitthetransaction.


SendingandAcknowledgingthePrepareMessage

Figure329

SALES.ACME.COM

1.SalestoWarehouse 2.WarehousetoSales
Prepared Pleaseprepare

GlobalCoordinator CommitPointSite DatabaseServer WAREHOUSE.ACME.COM Client

Stage4:CommitPointSiteCommits
Thecommittingofthetransactionbythecommitpointsiteinvolvesthefollowing steps:
1.

Nodesales.acme.com,receivingacknowledgmentthat warehouse.acme.comisprepared,instructsthecommitpointsitetocommit thetransaction. Thecommitpointsitenowcommitsthetransactionlocallyandrecordsthisfact initslocalredolog.

2.

Evenifwarehouse.acme.comhasnotyetcommitted,theoutcomeofthis transactionispredetermined.Inotherwords,thetransactionwillbecommittedat allnodeseveniftheabilityofagivennodetocommitisdelayed.

DistributedTransactionProcessing:CaseStudy

Stage5:CommitPointSiteInformsGlobalCoordinatorofCommit
Thisstageinvolvesthefollowingsteps:
1.

Thecommitpointsitetellstheglobalcoordinatorthatthetransactionhas committed.Becausethecommitpointsiteandglobalcoordinatorarethesame nodeinthisexample,nooperationisrequired.Thecommitpointsiteknows thatthetransactioniscommittedbecauseitrecordedthisfactinitsonlinelog. Theglobalcoordinatorconrmsthatthetransactionhasbeencommittedonall othernodesinvolvedinthedistributedtransaction.

2.

Stage6:GlobalandLocalCoordinatorsTellAllNodestoCommit
Thecommittingofthetransactionbyallthenodesinthetransactioninvolvesthe followingsteps:
1. 2. 3.

Aftertheglobalcoordinatorhasbeeninformedofthecommitatthecommit pointsite,ittellsallotherdirectlyreferencednodestocommit. Inturn,anylocalcoordinatorsinstructtheirserverstocommit,andsoon. Eachnode,includingtheglobalcoordinator,commitsthetransactionand recordsappropriateredologentrieslocally.Aseachnodecommits,theresource locksthatwerebeingheldlocallyforthattransactionarereleased.

InFigure3210 , sales.acme.com,whichisboththecommitpointsiteandthe globalcoordinator,hasalreadycommittedthetransactionlocally.salesnow instructswarehouse.acme.comtocommitthetransaction.

DistributedTransactionProcessing:CaseStudy

Figure3210

InstructingNodestoCommit

SALES.ACME.COM

SalestoWarehouse: Commit

GlobalCoordinator CommitPointSite DatabaseServer WAREHOUSE.ACME.COM Client

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

Thecommitpointstrengthisonlyusedtodeterminethecommitpointsiteina distributedtransaction. Whensettingthecommitpointstrengthforadatabase,notethefollowing considerations:

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';

Thisexampleshowsthattheuserstartedanewtransactionwithisolationlevel equaltoSERIALIZABLEandnamedit'updateinventorycheckpoint0'. Fordistributedtransactions,thenameissenttoparticipatingsiteswhena transactioniscommitted.IfaCOMMITCOMMENTexists,itisignoredwhena transactionnameexists. ThetransactionnameisdisplayedintheNAMEcolumnoftheV$TRANSACTION view,andintheTRAN_COMMENTeldoftheDBA_2PC_PENDINGviewwhenthe transactioniscommitted.

ViewingInformationAboutDistributedTransactions

ViewingInformationAboutDistributedTransactions
Thedatadictionaryofeachdatabasestoresinformationaboutallopendistributed transactions.Youcanusedatadictionarytablesandviewstogaininformation aboutthetransactions.Thissectioncontainsthefollowingtopics:

DeterminingtheIDNumberandStatusofPreparedTransactions TracingtheSessionTreeofInDoubtTransactions

DeterminingtheIDNumberandStatusofPreparedTransactions
Thefollowingviewshowsthedatabaselinksthathavebeendenedatthelocal databaseandstoredinthedatadictionary:
View DBA_2PC_PENDING Purpose Listsallindoubtdistributedtransactions.Theviewisempty untilpopulatedbyanindoubttransaction.Afterthe transactionisresolved,theviewispurged.

Usethisviewtodeterminetheglobalcommitnumberforaparticulartransaction ID.Youcanusethisglobalcommitnumberwhenmanuallyresolvinganindoubt transaction. Thefollowingtableshowsthemostrelevantcolumns(foradescriptionofallthe columnsintheview,seeOracleDatabaseReference):


Table331 Column LOCAL_TRAN_ID DBA_2PC_PENDING Description Localtransactionidentierintheformatinteger.integer.integer. Note:WhentheLOCAL_TRAN_IDandtheGLOBAL_TRAN_ID foraconnectionarethesame,thenodeistheglobalcoordinator ofthetransaction. GLOBAL_TRAN_ID Globaldatabaseidentierintheformatglobal_db_name.db_hex_ id.local_tran_id,wheredb_hex_idisaneightcharacter hexadecimalvalueusedtouniquelyidentifythedatabase.This commontransactionIDisthesameoneverynodefora distributedtransaction. Note:WhentheLOCAL_TRAN_IDandtheGLOBAL_TRAN_ID foraconnectionarethesame,thenodeistheglobalcoordinator ofthetransaction.

ViewingInformationAboutDistributedTransactions

Table331 Column STATE

(Cont.)DBA_2PC_PENDING Description STATEcanhavethefollowingvalues:

Collecting Thiscategorynormallyappliesonlytotheglobal coordinatororlocalcoordinators.Thenodeiscurrently collectinginformationfromotherdatabaseserversbeforeit candecidewhetheritcanprepare.

Prepared Thenodehaspreparedandmayormaynothave acknowledgedthistoitslocalcoordinatorwithaprepared message.However,nocommitrequesthasbeenreceived. Thenoderemainsprepared,holdinganylocalresource locksnecessaryforthetransactiontocommit.

Committed Thenode(anytype)hascommittedthetransaction,but othernodesinvolvedinthetransactionmaynothavedone thesame.Thatis,thetransactionisstillpendingatoneor morenodes.

ForcedCommit Apendingtransactioncanbeforcedtocommitatthe discretionofadatabaseadministrator.Thisentryoccursifa transactionismanuallycommittedatalocalnode.

Forcedtermination(rollback) Apendingtransactioncanbeforcedtorollbackatthe discretionofadatabaseadministrator.Thisentryoccursif thistransactionismanuallyrolledbackatalocalnode.

MIXED TRAN_COMMENT

YESmeansthatpartofthetransactionwascommittedonone nodeandrolledbackonanothernode. Transactioncommentor,ifusingtransactionnaming,the transactionnameisplacedherewhenthetransactionis committed. Nameofthehostmachine. Globalcommitnumberforcommittedtransactions.

HOST COMMIT#

Executethefollowingscript,namedpending_txn_script,toquerypertinent informationinDBA_2PC_PENDING(sampleoutputincluded):
COLLOCAL_TRAN_IDFORMATA13

ViewingInformationAboutDistributedTransactions

COLGLOBAL_TRAN_IDFORMATA30 COLSTATEFORMATA8 COLMIXEDFORMATA3 COLHOSTFORMATA10 COLCOMMIT#FORMATA10 SELECTLOCAL_TRAN_ID,GLOBAL_TRAN_ID,STATE,MIXED,HOST,COMMIT# FROMDBA_2PC_PENDING

/
SQL>@pending_txn_script LOCAL_TRAN_IDGLOBAL_TRAN_IDSTATEMIXHOSTCOMMIT# 1.15.870HQ.ACME.COM.ef192da4.1.15.870commitnodlsun183115499

Thisoutputindicatesthatlocaltransaction1.15.870hasbeencommittedonthis node,butitmaybependingononeormoreothernodes.BecauseLOCAL_TRAN_ID andthelocalpartofGLOBAL_TRAN_IDarethesame,thenodeistheglobal coordinatorofthetransaction.

TracingtheSessionTreeofInDoubtTransactions
Thefollowingviewshowswhichindoubttransactionsareincomingfromaremote clientandwhichareoutgoingtoaremoteserver:
View DBA_2PC_NEIGHBORS Purpose Listsallincoming(fromremoteclient)andoutgoing(toremote server)indoubtdistributedtransactions.Italsoindicates whetherthelocalnodeisthecommitpointsiteinthe transaction. Theviewisemptyuntilpopulatedbyanindoubttransaction. Afterthetransactionisresolved,theviewispurged.

Whenatransactionisindoubt,youmayneedtodeterminewhichnodesperformed whichrolesinthesessiontree.Usetothisviewtodetermine:

Alltheincomingandoutgoingconnectionsforagiventransaction Whetherthenodeisthecommitpointsiteinagiventransaction Whetherthenodeisaglobalcoordinatorinagiventransaction(becauseits localtransactionIDandglobaltransactionIDarethesame)

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

SQL>CONNECTSYS/password@hq.acme.com SQL>@neighbors_script LOCAL_TRAN_IDIN_OUTDATABASEDBUSER_OWNERINT

1.15.870outSALES.ACME.COMSYSC

Thisoutputindicatesthatthelocalnodesentanoutgoingrequesttoremoteserver salestocommittransaction1.15.870.Ifsalescommittedthetransactionbut noothernodedid,thenyouknowthatsalesisthecommitpointsite,becausethe commitpointsitealwayscommitsrst.

DecidingHowtoHandleInDoubtTransactions
Atransactionisindoubtwhenthereisafailureduringanyaspectofthetwophase commit.Distributedtransactionsbecomeindoubtinthefollowingways:

AservermachinerunningOracleDatabasesoftwarecrashes AnetworkconnectionbetweentwoormoreOracleDatabasesinvolvedin distributedprocessingisdisconnected Anunhandledsoftwareerroroccurs "InDoubtTransactions" onpage3216 foraconceptual overviewofindoubttransactions


SeeAlso:

Youcanmanuallyforcethecommitorrollbackofalocal,indoubtdistributed transaction.Becausethisoperationcangenerateconsistencyproblems,performit onlywhenspecicconditionsexist. Thissectioncontainsthefollowingtopics:


DiscoveringProblemswithaTwoPhaseCommit DeterminingWhethertoPerformaManualOverride AnalyzingtheTransactionData

DiscoveringProblemswithaTwoPhaseCommit
Theuserapplicationthatcommitsadistributedtransactionisinformedofa problembyoneofthefollowingerrormessages:
ORA02050:transaction someremotedbsmaybeindoubt

IDrolledback,

DecidingHowtoHandleInDoubtTransactions

ORA02053:transaction someremotedbsmaybeindoubt ORA02054:transaction

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.

Normally,youshouldmakeadecisiontolocallyforceanindoubtdistributed transactioninconsultationwithadministratorsatotherlocations.Awrongdecision canleadtodatabaseinconsistenciesthatcanbedifculttotraceandthatyoumust manuallycorrect. Ifnoneoftheseconditionsapply,alwaysallowtheautomaticrecoveryfeaturesof thedatabasetocompletethetransaction.Ifanyoftheseconditionsaremet, however,consideralocaloverrideoftheindoubttransaction.

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

ALTERSESSIONADVISEROLLBACK; DELETEFROMemp@sales...;/*advicetorollbackatSALES*/ ALTERSESSIONADVISENOTHING;

Ifyoumanuallyforcetheindoubttransactionfollowingthegivenadvice,theworst thatcanhappenisthateachnodehasacopyoftheemployeerecord;therecord cannotdisappear.

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

Thevariabletransaction_idistheidentierofthetransactionasspeciedineither theLOCAL_TRAN_IDorGLOBAL_TRAN_IDcolumnsoftheDBA_2PC_PENDING datadictionaryview. Forexample,assumethatyouqueryDBA_2PC_PENDINGanddeterminethat LOCAL_TRAN_IDforadistributedtransactionis1:45.13. YouthenissuethefollowingSQLstatementtoforcethecommitofthisindoubt transaction:


COMMITFORCE'1.45.13';

CommittingUsinganSCN
Optionally,youcanspecifytheSCNforthetransactionwhenforcingatransaction tocommit.ThisfeatureletsyoucommitanindoubttransactionwiththeSCN assignedwhenitwascommittedatothernodes. Consequently,youmaintainthesynchronizedcommittimeofthedistributed transactionevenifthereisafailure.SpecifyanSCNonlywhenyoucandetermine theSCNofthesametransactionalreadycommittedatanothernode. Forexample,assumeyouwanttomanuallycommitatransactionwiththe followingglobaltransactionID:
SALES.ACME.COM.55d1c563.1.93.29

First,querytheDBA_2PC_PENDINGviewofaremotedatabasealsoinvolvedwith thetransactioninquestion.NotetheSCNusedforthecommitofthetransactionat thatnode.SpecifytheSCNwhencommittingthetransactionatthelocalnode.For example,iftheSCNis829381993,issue:


COMMITFORCE'SALES.ACME.COM.55d1c563.1.93.29',829381993;

SeeAlso:

OracleDatabaseSQLReferenceformoreinformation

aboutusingtheCOMMITstatement

ManuallyRollingBackanInDoubtTransaction
Beforeattemptingtorollbacktheindoubtdistributedtransaction,ensurethatyou havetheproperprivileges.Notethefollowingrequirements:
UserCommittingtheTransaction You PrivilegeRequired FORCETRANSACTION

PurgingPendingRowsfromtheDataDictionary

UserCommittingtheTransaction Anotheruser

PrivilegeRequired FORCEANYTRANSACTION

ThefollowingSQLstatementrollsbackanindoubttransaction:
ROLLBACKFORCE'transaction_id';

Thevariabletransaction_idistheidentierofthetransactionasspeciedineither theLOCAL_TRAN_IDorGLOBAL_TRAN_IDcolumnsoftheDBA_2PC_PENDING datadictionaryview.


Forexample,torollbacktheindoubttransactionwiththelocaltransactionIDof

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

PL/SQLPackagesandTypesReferenceformore informationabouttheDBMS_TRANSACTIONpackage SeeAlso:

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:

Totallossoftheremotedatabase Recongurationinsoftwareresultinginlossoftwophasecommitcapability Lossofinformationfromanexternaltransactioncoordinatorsuchasa TPMonitor

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

STATE Column Forced commit

StateofGlobal Transaction Unknown

StateofLocal Transaction Committed

NormalAction None

AlternativeAction PURGE_LOST_DB_ ENTRY(onlyif autorecoverycannot resolvetransaction) PURGE_LOST_DB_ ENTRY(onlyif autorecoverycannot resolvetransaction)

Forced rollback

Unknown

Rolledback

None

Forced commit

Mixed

Committed

Manuallyremove inconsistencies thenusePURGE_ MIXED Manuallyremove inconsistencies thenusePURGE_ MIXED

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

Communicationbreak GlobalCoordinator prepared


WAREHOUSE.ACME.COM

commit HQ.ACME.COM

CommitPointSite DatabaseServer Client

Youcanmanuallyforcethelocalportionoftheindoubttransactionbyfollowing thestepsdetailedinthefollowingsections: Step1:RecordUserFeedback Step2:QueryDBA_2PC_PENDING Step3:QueryDBA_2PC_NEIGHBORSonLocalNode Step4:QueryingDataDictionaryViewsonAllNodes Step5:CommittheInDoubtTransaction Step6:CheckforMixedOutcomeUsingDBA_2PC_PENDING

Step1:RecordUserFeedback
Theusersofthelocaldatabasesystemthatconictwiththelocksoftheindoubt transactionreceivethefollowingerrormessage:
ORA01591:lockheldbyindoubtdistributedtransaction1.21.17

Inthiscase,1.21.17isthelocaltransactionIDoftheindoubtdistributed transaction.YoushouldrequestandrecordthisIDnumberfromusersthatreport problemstoidentifywhichindoubttransactionsshouldbeforced.

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.

hhhhhhhhistheinternaldatabaseidentieroftheglobalcoordinator(in hexadecimal). local_transaction_idisthecorrespondinglocaltransactionIDassigned ontheglobalcoordinator.

NotethatthelastportionoftheglobaltransactionIDandthelocaltransactionID matchattheglobalcoordinator.Intheexample,youcantellthatwarehouseisnot theglobalcoordinatorbecausethesenumbersdonotmatch:


LOCAL_TRAN_ID1.21.17 GLOBAL_TRAN_ID...1.93.29

ManuallyCommittinganInDoubtTransaction:Example

DeterminingtheStateoftheTransaction
Thetransactiononthisnodeisinapreparedstate:
STATEprepared

Therefore,warehousewaitsforitscoordinatortosendeitheracommitora rollbackrequest.

LookingforCommentsorAdvice
Thetransactioncommentoradvicecanincludeinformationaboutthistransaction. Ifso,usethiscommenttoyouradvantage.Inthisexample,theoriginand transactiontypeisinthetransactioncomment:
TRAN_COMMENTSales/NewOrder/Trans_type10B

ItcouldalsobeprovidedasatransactionnamewithaSETTRANSACTION... NAMEstatement. Thisinformationcanrevealsomethingthathelpsyoudecidewhethertocommitor rollbackthelocalportionofthetransaction.Ifusefulcommentsdonotaccompany anindoubttransaction,youmustcompletesomeextraadministrativeworktotrace thesessiontreeandndanodethathasresolvedthetransaction.

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

DBUSER_OWNERSWILLIAMS INTERFACEN DBID000003F4 SESS#1 BRANCH0100

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.

Liststhenameofthe databaselinkthat connectstotheremote node.

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:

Theconnectiontowarehouse Theconnectiontohq Theconnectionestablishedbytheuser

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:

salesistheglobalcoordinatorbecausethelocaltransactionIDandglobal transactionIDmatch. Twooutboundconnectionsareestablishedfromthisnode,butnoinbound connections.salesisnottheserverofanothernode. hqoroneofitsserversisthecommitpointsite.

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

Therefore,youcanforcetheindoubttransactiontocommitatyourlocaldatabase. Itisagoodideatocontactanyotheradministratorsyouknowthatcouldalso benetfromyourinvestigation.

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.

Atimeoutoccurs. Thedatabaserollsbackthestatement. Thedatabasereturnsthiserrormessagetotheuser:


ORA02049:timeout:distributedtransactionwaitingforlock

Becausethetransactiondidnotmodifydata,noactionsarenecessaryasaresultof thetimeout.Applicationsshouldproceedasifadeadlockhasbeenencountered. Theuserwhoexecutedthestatementcantrytoreexecutethestatementlater.Ifthe lockpersists,thentheusershouldcontactanadministratortoreporttheproblem.

LocksfromInDoubtTransactions
AqueryorDMLstatementthatrequireslocksonalocaldatabasecanbeblocked indenitelyduetothelockedresourcesofanindoubtdistributedtransaction.In thiscase,thedatabaseissuesthefollowingerrormessage:
ORA01591:lockheldbyindoubtdistributedtransaction

identifier

Inthiscase,thedatabaserollsbacktheSQLstatementimmediately.Theuserwho executedthestatementcantrytoreexecutethestatementlater.Ifthelockpersists, theusershouldcontactanadministratortoreporttheproblem,includingtheIDof theindoubtdistributedtransaction. Thechancesofthesesituationsoccurringarerareconsideringthelowprobabilityof failuresduringthecriticalportionsofthetwophasecommit.Evenifsuchafailure occurs,andassumingquickrecoveryfromanetworkorsystemfailure,problems areautomaticallyresolvedwithoutmanualintervention.Thus,problemsusually resolvebeforetheycanbedetectedbyusersordatabaseadministrators.

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

Forexample,thefollowingstatementreturnsthefollowingmessagesifthelocal commitpointstrengthisgreaterthantheremotecommitpointstrengthandboth nodesareupdated:


COMMITCOMMENT'ORA2PCCRASHTEST7';

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;

Singleprocessinstances(forexample,aPCrunning MSDOS)havenoseparatebackgroundprocesses,andthereforeno RECOprocess.Therefore,whenasingleprocessinstancethat participatesinadistributedsystemisstarted,youmustmanually enabledistributedrecoveryusingtheprecedingstatement.


Note:

ManagingReadConsistency
AnimportantrestrictionexistsintheOracleDatabaseimplementationof distributedreadconsistency.Theproblemarisesbecauseeachsystemhasitsown SCN,whichyoucanviewasthedatabaseinternaltimestamp.TheOracleDatabase serverusestheSCNtodecidewhichversionofdataisreturnedfromaquery.

ManagingReadConsistency

TheSCNsinadistributedtransactionaresynchronizedattheendofeachremote SQLstatementandatthestartandendofeachtransaction.Betweentwonodesthat haveheavytrafcandespeciallydistributedupdates,thesynchronizationis


frequent.Nevertheless,nopracticalwayexiststokeepSCNsinadistributedsystem

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:

BecauseSCNsaresynchronizedattheendofaremotequery,precedeeach remotequerywithadummyremotequerytothesamesite,forexample, SELECT*FROMDUAL@REMOTE.


BecauseSCNsaresynchronizedatthestartofeveryremotetransaction,commit

orrollbackthecurrenttransactionbeforeissuingtheremotequery.

Das könnte Ihnen auch gefallen