Bajwa Consulting Need senior Oracle DBA help? Performance tuning, Cloud migrations, GoldenGate, backup and DR. Plus 70+ free DBA scripts.
Visit bajwaconsulting.com →

Sunday, November 29, 2026

Python Cheat Sheet for DBAs

A one-page Python 3 cheat sheet for DBAs and anyone starting with Python. Every example runs as shown in Python 3.9 or later.

Running Python

python3 --version
python3                      # interactive shell, exit() to leave
python3 myscript.py          # run a script

# Virtual environment: one per project, keeps packages separate
python3 -m venv ~/venvs/dba
source ~/venvs/dba/bin/activate
pip install oracledb

Variables and types

name = "ORCL"              # str
port = 1521                # int
used_pct = 82.5            # float
is_open = True             # bool
nothing = None             # no value

type(port)                 # <class 'int'>
int("42"), float("3.5"), str(1521)

Strings

s = "  Oracle Database  "
s.strip()                  # 'Oracle Database'
s.lower(), s.upper()
s.replace("Oracle", "PostgreSQL")
"ORA-00600".startswith("ORA-")      # True
"a,b,c".split(",")         # ['a', 'b', 'c']
"-".join(["2026", "11", "25"])      # '2026-11-25'

db, pct = "ORCL", 82.456
print(f"{db} tablespace is {pct:.1f}% full")   # ORCL tablespace is 82.5% full

Lists

dbs = ["ORCL", "TEST", "DEV"]
dbs.append("PROD")
dbs[0]                     # 'ORCL'
dbs[-1]                    # 'PROD'
dbs[1:3]                   # ['TEST', 'DEV']
len(dbs)                   # 4
"DEV" in dbs               # True
sorted(dbs)
dbs.remove("TEST")

Dictionaries

db = {"name": "ORCL", "port": 1521, "version": "19c"}
db["name"]                 # 'ORCL'
db.get("owner", "unknown") # default if the key is missing
db["port"] = 1522
for key, value in db.items():
    print(key, value)

Tuples and sets

point = (10, 20)           # tuple: cannot be changed
x, y = point               # unpacking

hosts = {"db1", "db2", "db1"}   # set: {'db1', 'db2'}, no duplicates
hosts.add("db3")
{"db1", "db2"} & {"db2", "db3"}  # {'db2'} intersection

Conditions and loops

if used_pct >= 90:
    print("CRITICAL")
elif used_pct >= 80:
    print("WARNING")
else:
    print("OK")

for db in dbs:
    print(db)

for i, db in enumerate(dbs, start=1):
    print(i, db)

count = 0
while count < 3:
    count += 1

for n in range(5):         # 0, 1, 2, 3, 4
    if n == 3:
        break

Comprehensions

squares = [n * n for n in range(5)]                 # [0, 1, 4, 9, 16]
usage = {"USERS": 91.2, "SYSAUX": 64.0, "DATA": 88.5}
full = [t for t, pct in usage.items() if pct > 85]  # ['USERS', 'DATA']
upper = {db: db.lower() for db in dbs}

Functions

def pct_used(used_mb, total_mb, decimals=1):
    """Return the percentage used."""
    return round(used_mb / total_mb * 100, decimals)

pct_used(850, 1000)                 # 85.0
pct_used(total_mb=1000, used_mb=850, decimals=0)

def log(*messages, level="INFO"):
    print(level, *messages)

Errors

try:
    pct = pct_used(850, 0)
except ZeroDivisionError:
    pct = None
except Exception as e:
    print(f"Unexpected error: {e}")
finally:
    print("done")

raise ValueError("port must be a number")

Files

with open("alert_ORCL.log") as f:          # file closes automatically
    for line in f:
        if "ORA-" in line:
            print(line.rstrip())

with open("report.txt", "w") as f:
    f.write("All databases OK\n")

import csv, json
with open("dbs.csv") as f:
    for row in csv.DictReader(f):
        print(row["name"])

data = json.loads('{"name": "ORCL"}')
text = json.dumps(data, indent=2)

Useful modules

import os, sys, datetime, subprocess, re

os.environ.get("ORACLE_SID")
os.path.exists("/u01/app/oracle")
datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
re.findall(r"ORA-\d{5}", line)
result = subprocess.run(["df", "-h"], capture_output=True, text=True)
print(result.stdout)
sys.exit(1)                # exit with an error code

Classes (the basics)

class Database:
    def __init__(self, name, port=1521):
        self.name = name
        self.port = port

    def dsn(self, host):
        return f"{host}:{self.port}/{self.name}"

orcl = Database("ORCL")
orcl.dsn("dbhost1")        # 'dbhost1:1521/ORCL'

Connecting to Oracle with python-oracledb

import getpass
import oracledb

conn = oracledb.connect(user="system",
                        password=getpass.getpass("Password: "),
                        dsn="dbhost1:1521/ORCLPDB1")
with conn.cursor() as cur:
    cur.execute("""
        SELECT tablespace_name, ROUND(used_percent, 1)
        FROM   dba_tablespace_usage_metrics
        WHERE  used_percent > :limit
        ORDER  BY 2 DESC""", limit=80)
    for name, pct in cur:
        print(f"{name:20} {pct:5.1f}%")
conn.close()

Never put passwords in a script. Ask for them with getpass, read them from an environment variable, or use a wallet or a secrets manager. Always use bind variables (:limit), never string formatting, to pass values into SQL.

Script template

#!/usr/bin/env python3
"""Check something and exit with 0 (OK) or 1 (problem)."""
import sys

def main():
    problems = []
    # ... checks go here ...
    for p in problems:
        print(p)
    return 1 if problems else 0

if __name__ == "__main__":
    sys.exit(main())

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Friday, November 27, 2026

Splunk for DBAs: Basics and the SPL Commands I Use Most

Splunk collects machine data (log files, metrics, events) into indexes and lets you search it with the Search Processing Language (SPL). For a DBA, that means one place to search alert logs, listener logs, OS logs and application errors across every server. This post covers the basics and the SPL commands I use most.

Key terms

TermMeaning
IndexWhere data is stored, for example oracle or os. Always name the index in your search; it is much faster.
SourcetypeThe format of the data, such as oracle:alert or linux_secure. It decides how fields are extracted.
SourceThe file or input the event came from, such as /u01/app/oracle/diag/.../alert_ORCL.log.
HostThe server that sent the event.
EventOne record, usually one log entry, with a timestamp.
FieldA named value in an event, such as host or an extracted ora_error.
ForwarderThe Universal Forwarder agent on each server that sends files to Splunk.

Your first searches

Open Search & Reporting, pick a time range in the time picker (for example "Last 24 hours"), and type:

index=oracle sourcetype=oracle:alert "ORA-"

Search terms are combined with AND by default. Use OR and NOT in capitals, and quotes for exact phrases:

index=oracle ("ORA-00600" OR "ORA-07445") NOT host=testdb*
index=os sourcetype=linux_secure "Failed password"

Click a field in the left sidebar to see its top values, and click a value to add it to the search.

The pipe

Like in a Unix shell, | passes the results of one command to the next. The first part finds events; the commands after the pipes shape them:

index=oracle "ORA-" | stats count by host | sort - count

SPL commands I use most

CommandWhat it doesExample
statsCounts, sums, averages by field| stats count by host
timechartStatistics over time, for a chart| timechart span=1h count by host
top / rareMost or least common values| top limit=10 ora_error
tableShow only chosen fields| table _time host ora_error
sortSort results (- means descending)| sort - count
dedupKeep one event per value| dedup host
rexExtract a field with a regular expression| rex "(?<ora_error>ORA-\d{5})"
evalCalculate a new field| eval gb=round(bytes/1024/1024/1024,2)
whereFilter on a calculated condition| where count > 10
renameRename fields for display| rename count AS "Errors"
head / tailFirst or last N results| head 20
lookupAdd fields from a CSV lookup table| lookup db_owners host OUTPUT team
transactionGroup related events into one| transaction host maxspan=5m

Useful searches for DBAs

ORA- errors in alert logs, by database server and error code:

index=oracle sourcetype=oracle:alert "ORA-"
| rex "(?<ora_error>ORA-\d{5})"
| stats count by host ora_error
| sort - count

Hourly trend of ORA- errors, one line per host:

index=oracle sourcetype=oracle:alert "ORA-"
| timechart span=1h count by host

Databases that restarted in the last 7 days (set the time picker to "Last 7 days"):

index=oracle sourcetype=oracle:alert "Starting ORACLE instance"
| table _time host
| sort - _time

Failed SSH logins on database servers:

index=os sourcetype=linux_secure "Failed password"
| rex "from (?<src_ip>\d+\.\d+\.\d+\.\d+)"
| stats count by host src_ip
| where count > 5

Listener connections per service per hour:

index=oracle sourcetype=oracle:listener "establish"
| rex "SERVICE_NAME=(?<service>[^\)]+)"
| timechart span=1h count by service

SPL does not use -- for comments. To add a comment inside a search, wrap it in three backticks: ```count errors per host```.

Sourcetype names depend on how your Splunk admin set up the inputs. Run index=oracle | stats count by sourcetype to see what you have.

Saving searches, alerts and dashboards

  • Save As → Report keeps a search you run often.
  • Save As → Alert runs the search on a schedule and emails you (or opens a ticket) when there are results. For example: "ORA-00600 in the last 15 minutes, any host".
  • Save As → Dashboard Panel adds the chart to a dashboard, such as a daily database health page.

Tips for fast searches

  • Always start with index= and, if you can, sourcetype=.
  • Use the smallest time range that answers your question.
  • Filter as early as possible, before the first pipe, and use stats rather than transaction when you can.
  • Use | fields host ora_error early to carry only the fields you need.

To practice, Splunk offers a free trial of Splunk Enterprise and free introductory training on its website.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Thursday, November 26, 2026

SQL Server Trusted Connections: Who Am I Connected As?

A question I get from Oracle DBAs who also look after SQL Server: an ODBC connection can use a user ID and password, or a trusted connection. With a trusted connection, who am I connected as? And can a query show that name?

What a trusted connection is

A trusted connection is Windows Authentication. SQL Server does not get a user name and password from the ODBC settings. Instead, Windows passes along the identity of the process that opens the connection, using Kerberos or NTLM. Any user ID typed into the ODBC data source is ignored.

Usually that is the person logged in to the machine, but not always:

  • A program running as a Windows service or scheduled task connects as that service account, for example DOMAIN\svc_reports.
  • A program started with Run as different user connects as that user.
  • A web application in IIS connects as its application pool account, unless it is set up to pass on the browser user's identity.

The query: who am I?

SELECT SUSER_SNAME()     AS login_name,      -- DOMAIN\username for a trusted connection
       ORIGINAL_LOGIN()  AS original_login,  -- the real login, even after EXECUTE AS
       SYSTEM_USER       AS system_user,
       USER_NAME()       AS database_user;   -- the database user it maps to (often dbo)

Use ORIGINAL_LOGIN() in code that may run under EXECUTE AS; SUSER_SNAME() then shows the impersonated login instead.

The detailed version: how did I authenticate?

SELECT s.login_name,
       s.nt_domain,
       s.nt_user_name,          -- filled in only for Windows authentication
       s.original_login_name,
       s.host_name,
       c.auth_scheme            -- KERBEROS or NTLM = trusted; SQL = user id/password
FROM   sys.dm_exec_sessions    s
JOIN   sys.dm_exec_connections c ON c.session_id = s.session_id
WHERE  s.session_id = @@SPID;
Connection typelogin_nament_user_nameauth_scheme
Trusted (Windows)DOMAIN\yournameyournameKERBEROS or NTLM
User ID / passwordthe SQL loginemptySQL

Seeing a user's own session needs no extra permission. To see other people's sessions in sys.dm_exec_sessions, you need VIEW SERVER STATE (in SQL Server 2022 and later, VIEW SERVER PERFORMANCE STATE is enough).

For Oracle DBAs

The closest Oracle equivalents are OS-authenticated users (IDENTIFIED EXTERNALLY, the old OPS$ accounts) and Kerberos authentication. To see who you are in Oracle:

SELECT SYS_CONTEXT('USERENV','SESSION_USER')        AS db_user,
       SYS_CONTEXT('USERENV','OS_USER')             AS os_user,
       SYS_CONTEXT('USERENV','AUTHENTICATION_METHOD') AS auth_method,
       SYS_CONTEXT('USERENV','HOST')                AS client_host
FROM   dual;

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

ORA-22992: Loading BLOB Text over a Database Link (19c/21c)

A reader's question: a table on a remote database stores plain text in a BLOB column (a CLOB would have been the better choice). Loading it into a staging area over a database link took 218 minutes. Converting the BLOB to VARCHAR2 pieces in a view on the source cut it to 2 minutes. But putting the pieces back together into one CLOB on the target failed with:

ORA-22992: cannot use LOB locators selected from remote tables

Here is why it happens, and the approach I recommend for Oracle 19c and 21c.

The setup

The view on the source database returns two VARCHAR2 pieces for normal rows, and a CLOB only for the large ones:

CREATE OR REPLACE VIEW owner.table_v AS
SELECT id,
       date_col,
       UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(blob_col, 2000, 1))    AS clob_pt1,
       UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(blob_col, 2000, 2001)) AS clob_pt2,
       CASE WHEN DBMS_LOB.GETLENGTH(blob_col) > 4000
            THEN TO_CLOB(blob_col, NLS_CHARSET_ID('AL32UTF8'))
       END AS clob_col
FROM   owner.source_table;

Why 2000? DBMS_LOB.SUBSTR on a BLOB returns a RAW, and a RAW in SQL is limited to 2000 bytes (with the default MAX_STRING_SIZE=STANDARD), so two pieces cover the first 4000 bytes.

On the target, both of these work on their own:

-- Short rows: concatenate the two VARCHAR2 pieces
INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_pt1 || clob_pt2
FROM   owner.table_v@db_lnk;

-- Long rows: copy the remote CLOB straight in
INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_col
FROM   owner.table_v@db_lnk;

But this fails with ORA-22992:

INSERT INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col,
       CASE WHEN clob_col IS NOT NULL
            THEN clob_col
            ELSE clob_pt1 || clob_pt2
       END
FROM   owner.table_v@db_lnk;

Why it fails

The CASE statement is not the real problem; the remote LOB is. Oracle can copy a remote LOB column as it is into a local LOB column. That is a supported distributed operation. But once the remote LOB is part of an expression evaluated on the local database, such as a CASE, a concatenation or a function call, Oracle needs the remote LOB's locator locally, and that is what ORA-22992 refuses.

  • Plain copy of a remote LOB column: works.
  • Remote LOB inside a local expression: can fail with ORA-22992.
  • Expression evaluated fully on the remote side (for example inside the view): usually works.

Oracle 12.2 and later relaxed many remote LOB restrictions, but mixing a remote LOB with locally built values in one expression can still fail, depending on the plan. Test on your exact versions.

Also check the logic: the overflow CLOB should win when it is present, so the CASE must return clob_col when it is NOT NULL. Swapping the branches is an easy mistake.

Recommended fix: two inserts

Both halves already work separately, so keep them separate:

-- 1. Rows that fit in the two pieces (no remote LOB involved)
INSERT /*+ APPEND */ INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, TO_CLOB(clob_pt1 || clob_pt2)
FROM   owner.table_v@db_lnk
WHERE  clob_col IS NULL;
COMMIT;

-- 2. Large rows: plain copy of the remote CLOB
INSERT /*+ APPEND */ INTO sa.testtable (id, date_col, clob_col)
SELECT id, date_col, clob_col
FROM   owner.table_v@db_lnk
WHERE  clob_col IS NOT NULL;
COMMIT;

The COMMIT after each insert is needed: after a direct-path (APPEND) insert, the same session cannot touch that table again until it commits (ORA-12838).

Most rows go through the fast first insert; only the few large rows pay the LOB cost in the second.

A UNION ALL of the two queries in one INSERT looks neater, but Oracle may still combine both branches into one expression and raise ORA-22992 again. The two separate statements are the safer choice.

Watch the BLOB-to-text conversion

  • Use the right conversion. From 12.2, TO_CLOB(blob_col, csid) converts a BLOB to a CLOB using the character set you name, such as NLS_CHARSET_ID('AL32UTF8'). On older versions, use DBMS_LOB.CONVERTTOCLOB in PL/SQL. Find out which character set the application really used to write the BLOBs.
  • Multibyte characters can be split. UTL_RAW.CAST_TO_VARCHAR2 works on bytes. With UTF-8 text, a character can be cut in half at byte 2000, which gives a corrupted character in both pieces. If the text is not plain ASCII, check rows near the boundary, or use the CLOB path for all of them.
  • Measure length in bytes. Use DBMS_LOB.GETLENGTH(blob_col), which returns bytes for a BLOB, to decide which rows need the CLOB path.

Better long-term options

  • Convert on the source. If you control the source database, convert the BLOB to a CLOB there once, in a staging table or a column, with the correct character set. The target then does a plain CLOB copy, which works over a database link.
  • Extended data types. With MAX_STRING_SIZE=EXTENDED (12c and later), VARCHAR2 and RAW in SQL can be up to 32767 bytes, so one piece can carry much more text without a LOB. Changing this parameter cannot be undone and requires running utl32k.sql in upgrade mode, so plan it carefully and test it first.
  • Fix the data type. If the column only ever holds text, ask the application owner to change it to a CLOB. That removes the conversion problems at the root.

Why the view made it 100 times faster

Fetching LOBs over a database link is slow because each LOB value can need extra network round trips. VARCHAR2 values travel in normal row batches. Turning most LOB values into VARCHAR2 on the source side, so only the few large rows are fetched as LOBs, is what took the load from 218 minutes to 2. A SQL trace of both versions would show the difference in round trips.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

Wednesday, November 25, 2026

Oracle GoldenGate Bidirectional Replication: On-Premises to AWS EC2

This post sets up bidirectional (active-active) replication with Oracle GoldenGate between an on-premises Oracle database and an Oracle database running on Amazon EC2. Both databases accept changes, and each change is copied to the other side. It is a common pattern during a cloud migration: you keep both sides live, move users over gradually, and keep a way back.

The commands use GoldenGate 21c or later (Microservices Architecture) with the Admin Client. Classic Architecture was deprecated in 19c and is not available in 21c and later, so new setups should use Microservices.

The setup

SideDatabaseExtractReplicat
On premisesONPREM (19c, PDB SALESPDB)EXTAREPA (applies changes from AWS)
AWS EC2AWSDB (19c, PDB SALESPDB)EXTBREPB (applies changes from on premises)

Each side runs its own GoldenGate deployment. A distribution path sends each side's trail files to the other side over a secure WebSocket connection.

Before you start: active-active rules

  • Every replicated table needs a primary key or unique key. Without one, GoldenGate cannot find the right row to update on the other side.
  • Avoid key collisions. If both sides insert rows using sequences, give each side its own range. The simplest way is odd and even numbers: on premises START WITH 1 INCREMENT BY 2, on AWS START WITH 2 INCREMENT BY 2. Identity columns need the same treatment.
  • Stop the loop. A change applied by Replicat must not be captured again by the local Extract and sent back. Integrated Replicat tags its transactions, and Extract excludes them with TRANLOGOPTIONS EXCLUDETAG.
  • Plan for conflicts. If the same row is changed on both sides at the same moment, one change must win. Oracle's automatic conflict detection and resolution (latest timestamp wins) handles most cases.
  • Triggers and cascading deletes should fire only for local user changes, not for rows applied by Replicat. Integrated Replicat suppresses triggers by default; check any custom code that runs on DML.

1. Network between on premises and AWS

  • Connect the data center and the VPC with Site-to-Site VPN or Direct Connect. Do not open GoldenGate ports to the internet.
  • Allow the GoldenGate ports between the two deployments only, in the EC2 security group and the on-premises firewall. The ports are the ones you chose when you created the deployments (Service Manager, Administration, Distribution and Receiver services).
  • Use TLS certificates for the deployments so the distribution paths use wss://.

2. Prepare both databases

Run on both ONPREM and AWSDB, in CDB$ROOT unless noted:

-- ARCHIVELOG mode and force logging
SELECT log_mode, force_logging FROM v$database;
ALTER DATABASE FORCE LOGGING;

-- Minimal supplemental logging and the GoldenGate parameter
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;
ALTER SYSTEM SET enable_goldengate_replication = TRUE SCOPE=BOTH;
ALTER SYSTEM SET streams_pool_size = 2G SCOPE=BOTH;   -- for integrated Extract and Replicat

-- GoldenGate administrator (common user)
CREATE USER c##ggadmin IDENTIFIED BY "ChangeMe#2026" CONTAINER=ALL;
GRANT DBA TO c##ggadmin CONTAINER=ALL;
EXEC DBMS_GOLDENGATE_AUTH.GRANT_ADMIN_PRIVILEGE('C##GGADMIN', container => 'ALL');

Use a strong password of your own and store it only in the GoldenGate credential store.

3. Credentials and schema logging (each side)

In the Admin Client, connected to that side's deployment:

ALTER CREDENTIALSTORE ADD USER c##ggadmin@onprem-scan:1521/ONPREM ALIAS onprem_root DOMAIN OracleGoldenGate
ALTER CREDENTIALSTORE ADD USER c##ggadmin@onprem-scan:1521/SALESPDB ALIAS onprem_pdb DOMAIN OracleGoldenGate

DBLOGIN USERIDALIAS onprem_pdb DOMAIN OracleGoldenGate
ADD SCHEMATRANDATA sales ALLCOLS

Do the same on AWS with aliases aws_root and aws_pdb.

4. Automatic conflict detection and resolution

Turn on Oracle's automatic CDR for each replicated table, on both databases. It adds a hidden timestamp column and resolves update conflicts with "latest timestamp wins":

BEGIN
  FOR t IN (SELECT table_name FROM dba_tables WHERE owner = 'SALES') LOOP
    DBMS_GOLDENGATE_ADM.ADD_AUTO_CDR(schema_name => 'SALES', table_name => t.table_name);
  END LOOP;
END;
/
SELECT table_owner, table_name FROM dba_gg_auto_cdr_tables;

5. Extract on each side

Parameter file for EXTA (on premises). EXTB on AWS is the same with its own names:

EXTRACT exta
USERIDALIAS onprem_root DOMAIN OracleGoldenGate
EXTTRAIL ea
TRANLOGOPTIONS EXCLUDETAG 00        -- skip changes applied by the local Replicat
DDL INCLUDE MAPPED
TABLE salespdb.sales.*;
DBLOGIN USERIDALIAS onprem_root DOMAIN OracleGoldenGate
ADD EXTRACT exta, INTEGRATED TRANLOG, BEGIN NOW
REGISTER EXTRACT exta DATABASE CONTAINER (salespdb)
ADD EXTTRAIL ea, EXTRACT exta
START EXTRACT exta

6. Initial load

If the AWS database starts empty, load it from on premises before starting the Replicats. The safest method is an export at a known SCN (Data Pump FLASHBACK_SCN), then starting the AWS Replicat after that SCN. I describe it step by step in my tutorial on GoldenGate initial load at SCN. Do not allow users to change data on AWS until the initial load is complete and REPB has caught up.

7. Distribution paths

From the on-premises deployment, send trail ea to AWS; from the AWS deployment, send trail eb back:

-- On premises
ADD DISTPATH dp_to_aws SOURCE trail://localhost:9002/services/v2/sources?trail=ea
    TARGET wss://ec2-gg.example.internal:9103/services/v2/targets?trail=ra

-- On AWS
ADD DISTPATH dp_to_onprem SOURCE trail://localhost:9002/services/v2/sources?trail=eb
    TARGET wss://onprem-gg.example.internal:9103/services/v2/targets?trail=rb

Replace the host names and ports with your own Distribution and Receiver service ports.

8. Replicat on each side

REPLICAT repb
USERIDALIAS aws_pdb DOMAIN OracleGoldenGate
DBOPTIONS INTEGRATEDPARAMS (parallelism 4)
MAP salespdb.sales.*, TARGET sales.*;
ADD REPLICAT repb, INTEGRATED, EXTTRAIL ra
START REPLICAT repb, AFTERCSN 4517823     -- the SCN of the initial load

Integrated Replicat tags its transactions with tag 00 by default, which is why each Extract uses EXCLUDETAG 00. Start REPA on premises the same way, reading trail rb.

9. Test before you trust it

  1. Insert a row on premises; it should appear on AWS within seconds. Repeat in the other direction.
  2. Update the same row on both sides at almost the same time; check that both end up with the newer value and that DBA_APPLY_ERROR is empty.
  3. Check that the row did not bounce back and forth: the trail statistics should show it once in each direction.
  4. Watch lag: INFO ALL and LAG REPLICAT repb in the Admin Client, or the Performance Metrics page in the web UI.
  5. Stop the network link for a few minutes and restart it; both sides should catch up without errors.

Day-to-day checks

INFO ALL
STATS REPLICAT repb, TOTAL, LATEST
VIEW REPORT repb

-- In the database
SELECT apply_name, status FROM dba_apply;
SELECT * FROM dba_apply_error;

Oracle GoldenGate is licensed separately from the database. Check your license before you build this in production, and test the whole design, including conflicts and a cutover, on test databases first.

More DBA scripts are in my GitHub repository: github.com/sbajwa55/dba-scripts. For help with Oracle, cloud migrations or AWS, visit Bajwa Consulting Services.

My New Book: AWS for Database Administrators

After many years of working as an Oracle DBA, from Data Guard 10g to Exadata, RAC and GoldenGate, I have written the book I wish I had when I started moving databases to the cloud.

AWS for Database Administrators: From On-Premises to Cloud

Available now on Kindle: amazon.com/dp/B0HSLZWVJ7
Paperback: amazon.com/dp/B0HSWBFD76

The book is for DBAs who know how to keep Oracle, PostgreSQL, MySQL or SQL Server running on premises and now need to do the same on AWS. It explains which of your skills carry over, which responsibilities move to AWS, and which ones are still yours, such as backups, recovery testing, security and performance.

What is inside

  • The DBA role in the cloud, and AWS core concepts and networking
  • Choosing a database service: Amazon RDS, Aurora or a database on EC2
  • High availability and disaster recovery on AWS
  • Migration: assessment and planning, schema conversion and DMS, native tools such as Data Pump and GoldenGate, cutover, rollback and validation
  • Security, monitoring and performance tuning
  • Backup, recovery, patching and upgrades
  • Cost optimization, infrastructure as code and automation
  • Beyond relational databases, and planning your career path

Hands-on labs

The book includes step-by-step practice labs with the commands, expected output, troubleshooting and cleanup for each one. The lab code is free on GitHub: github.com/sbajwa55/aws-for-dbas-labs.

Book details, updates and the companion lab code are on the book page: bajwaconsulting.com/publications/aws-for-database-administrators.html.

If you read it, I would be grateful for a short review on Amazon. And if your team needs help with an Oracle or PostgreSQL migration to AWS, you can reach me through Bajwa Consulting Services.

Sandeep Bajwa