Homelab / Lab project
Lab project · November 2026 · Live

Oracle Retail
Lab.

I moved my server's database from PostgreSQL to Oracle AI Database 26ai Free and rebuilt it the way professionally run Oracle retail systems are built: dedicated tablespaces, a schema owner nobody logs in as, application accounts with roles and synonyms, PL/SQL batch packages, scheduled jobs and Data Pump exports. This is the complete guide to how I did it, with the real commands, output and screenshots.

26ai
Oracle AI Database Free, in Docker
381k
rows migrated from PostgreSQL 17
13/13
tables reconciled: counts and checksums
77s
total load time for the migration
0
rows lost · PostgreSQL kept for rollback
Purpose

Learning how the systems at work really run

At work I use an Oracle-based retail merchandising system every day: item and location data, uploads, batch jobs and reporting views. I see it from the front end. I wanted to understand what sits underneath it, so I built a small version of that environment at home and moved real data into it.

The goal of this project is to imitate how those systems operate (how the database is laid out, who is allowed to do what, how batch jobs record their runs, how data is backed up and moved), so I get a better understanding of how the systems work and build a stronger foundation in professionally run retail systems.

The data is real and in use: my server's telemetry database (every file on the RAID, Plex, container stats, backups and game-server events) that powers my admin dashboard. It now runs on Oracle, 24/7, with the old PostgreSQL database kept as a rollback.

Goals I set

  1. Mirror the work setup: the same Oracle building blocks and naming conventions a retail system uses.
  2. Migrate without losing anything: prove every row moved, with counts and checksums.
  3. Keep the dashboard working with no change to the website.
  4. Least privilege for every account, the way production systems are locked down.
  5. Back it up the Oracle way (Data Pump), on a schedule, into the existing encrypted backups.
  6. Document it well enough that someone else could rebuild it from this page.

What mirrors the systems at work

Each concept below is something I deal with at work from the user side. In the lab I built it myself.

Concept in a retail systemHow the lab implements itWhy it matters
Separate data and index tablespacesSERVERDB_DATA and SERVERDB_INDEX, bigfile, autoextend with capsStorage is planned and capped per purpose, and indexes can be managed apart from tables.
One schema owns the applicationSERVERDB is a schema-only account (NO AUTHENTICATION): it owns every object, but nobody can sign in as itNobody can accidentally drop or change the application's tables from a normal session.
Application and user accountsSERVERDB_ETL (batch), SERVERDB_WEB (dashboard), SERVERDB_DEV (analyst), each with private synonyms to the owner's objectsEvery person and program gets only what its job needs, and every access is traceable to an account.
RolesSERVERDB_RW for batch, SERVERDB_RO for reporting, granted with 26ai schema-level privilegesPermissions belong to the job, not to individual users.
*_SQL PL/SQL packagesJOB_RUN_SQL: functions return BOOLEAN and pass errors back in O_error_message, with I_/O_/L_ prefixesThis is the calling convention used by the packaged retail code I read at work.
Y/N indicator columns, V_ viewsOK_IND, OVERDUE_IND; reporting views such as V_FOLDER_USAGE and V_JOB_LATESTReporting reads stable views, so the tables underneath can change.
Staging tables for uploadsGlobal temporary table RAID_SCAN_STAGE: load, validate and apply in one transactionThis is how bulk uploads work: stage the data first, then apply it as a set.
Batch schedule and run logCollector jobs every 5 min to nightly, each logged in JOB_RUN through an autonomous transactionWhen a batch fails, the log says which job, when, and why.
Exports and refreshesNightly DBMS_SCHEDULER job runs a Data Pump schema export into the encrypted backupThis is the standard way Oracle shops move and restore data.
SQL DeveloperSQL Developer Web (ORDS) with a read-only analyst sign-inIt's the same kind of tool analysts use to query the system.
Design

The architecture after the move

One Oracle container holds a pluggable database, FREEPDB1. Each program connects with its own account, and nothing is exposed to the internet.

PostgreSQL → Oracle

What had to be translated

Both are SQL databases, but they differ in a lot of small ways. This is the translation sheet I worked from.

PostgreSQL (before)Oracle 26ai (after)Note
Schemas files.*, plex.*, stats.* …One owner schema, table prefixes RAID_, PLEX_, HOST_In Oracle a schema is a user, so one owner with prefixed tables follows the retail pattern.
bigserialNUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY"By default" accepts the migrated ids; the identity is then moved past them with START WITH LIMIT VALUE.
timestamptzTIMESTAMP stored in UTCViews convert to America/New_York with FROM_TZ … AT TIME ZONE only where a local day matters.
booleanVARCHAR2(1) 'Y'/'N' + CHECKRetail convention (*_IND). The API turns it back into true/false.
text, inetVARCHAR2(n)Sized from the real maximum lengths I measured first (longest path: 308 bytes).
INSERT … ON CONFLICT DO NOTHINGexecutemany(batcherrors=True) and ignore ORA-00001Duplicates are skipped row by row, while any other error still fails the job.
ON CONFLICT DO UPDATEMERGE INTO … USING (SELECT … FROM dual)Oracle's standard upsert.
COPY into a temp tableGlobal temporary table + batched array inserts (5,000 rows)344k rows staged and applied in 36 seconds.
DISTINCT ONROW_NUMBER() OVER (PARTITION BY …)"Latest row per group" is an analytic function in Oracle.
LEFT JOIN LATERALOUTER APPLYPairs each game join with the next leave.
array_agg, FILTER (WHERE)JSON_ARRAYAGG, LISTAGG(DISTINCT), COUNT(CASE …)
pg_size_pretty()My own PL/SQL function SIZE_PRETTYIt produces the same output, so the reports read the same.
Partial index WHERE deleted_at IS NULLFunction-based index on CASE WHEN deleted_at IS NULL THEN …Oracle doesn't index rows where every key is NULL, which gives the same effect as a partial index.
'' (empty string)NULLThe biggest behavioural difference. See the notes in steps 4 and 8.
Step-by-step guide

How I did it, step by step

Every command and output below is from the actual build on my server. Passwords, IP addresses and personal data are left out.

1
Preparation

Plan the move and the rollback before touching anything

Before changing anything I took an inventory of the old system: 13 tables, 380,908 rows (344k of them in the file catalogue), the collector's six jobs, the API's 16 queries, and everything else that connected to the database. I checked the other stacks and Uptime Kuma, and nothing else did. I also measured the longest values in each text column so I could size the Oracle columns properly.

  • Rollback first: the compose file, collector, API, Dockerfile and secrets were copied to *.postgres-bak files. The PostgreSQL data volume would be stopped but never deleted.
  • Run both side by side: Oracle went up next to PostgreSQL, so the dashboard kept working during the build.
  • Rehearse: I ran a full trial migration and tested every collector job against Oracle before the real cut-over, then emptied the tables and did it for real.
Mirrors workThis is the same order a change ticket follows: impact assessment, a back-out plan, a rehearsal in a test environment, then the production change in a short window.
2
Infrastructure

Run Oracle AI Database 26ai Free in Docker

Oracle publishes an official container image of its free edition. I pinned an exact release instead of latest, so an automatic update can never change the database version on me. The Free edition is capped at 2 CPU threads, 2 GB of RAM and 12 GB of user data, which is plenty for this workload.

~/docker/serverdb/docker-compose.yml (excerpt)
  oracle:
    image: container-registry.oracle.com/database/free:23.26.3.0
    container_name: serverdb-oracle
    hostname: serverdb-oracle
    restart: unless-stopped
    env_file: oracle.env               # ORACLE_PWD (SYS/SYSTEM) + app account passwords for setup
    environment:
      TZ: America/New_York
      ORACLE_CHARACTERSET: AL32UTF8
    ports:
      - "1521:1521"                    # LAN access for SQL Developer / sqlplus; do not port-forward
    volumes:
      - oracle-data:/opt/oracle/oradata
      - ./oracle/sql:/opt/serverdb:ro                           # install scripts (run by hand: install.sh)
      - ./dpdump:/opt/oracle/dpdump_serverdb                    # nightly Data Pump export (backed up by restic)
    healthcheck:
      test: ["CMD", "/opt/oracle/checkDBStatus.sh"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 300s
NotePort 1521 is reachable on the home network for SQL Developer, but it isn't forwarded through the router. The data files live in a named Docker volume, and the install scripts are mounted read-only.
GotchaThe image ships with a pre-built database, so the "run on first start" setup folder never ran my scripts. I switched to an explicit deploy script, install.sh, that a DBA runs by hand with sqlplus / as sysdba. That's closer to how changes are deployed at work anyway.
3
Database design

Tablespaces, a schema-only owner and application accounts

The install is a master script (install.sql) that stops on the first error (WHENEVER SQLERROR EXIT), writes a spool log, and calls six numbered scripts. The first one lays out the storage and the accounts:

oracle/sql/01_tablespaces_users.sql
CREATE BIGFILE TABLESPACE serverdb_data
  DATAFILE '/opt/oracle/oradata/FREE/FREEPDB1/serverdb_data01.dbf'
  SIZE 512M AUTOEXTEND ON NEXT 128M MAXSIZE 7G;

CREATE BIGFILE TABLESPACE serverdb_index
  DATAFILE '/opt/oracle/oradata/FREE/FREEPDB1/serverdb_index01.dbf'
  SIZE 256M AUTOEXTEND ON NEXT 64M MAXSIZE 3G;

-- Schema owner. NO AUTHENTICATION = a "schema-only" account: it owns every
-- object but nobody can log in as it. DDL is deployed by a DBA.
CREATE USER serverdb NO AUTHENTICATION
  DEFAULT TABLESPACE serverdb_data
  QUOTA UNLIMITED ON serverdb_data
  QUOTA UNLIMITED ON serverdb_index;

-- Roles: what a job is allowed to do, independent of who holds it.
-- reporting / dashboard: SELECT only
CREATE ROLE serverdb_ro;
-- batch / collector: SELECT + DML + package execute
CREATE ROLE serverdb_rw;

-- Application accounts (the passwords are passed in by the installer).
CREATE USER serverdb_etl IDENTIFIED BY "&etl_pw"
  DEFAULT TABLESPACE serverdb_data;
CREATE USER serverdb_web IDENTIFIED BY "&web_pw"
  DEFAULT TABLESPACE serverdb_data;

GRANT CREATE SESSION TO serverdb_etl, serverdb_web;
GRANT serverdb_rw TO serverdb_etl;
GRANT serverdb_ro TO serverdb_web;
Mirrors workRetail installs keep data and indexes in separate tablespaces and have one owner schema that applications never sign in as. A schema-only account (new in 23ai/26ai) enforces that: the owner has no password at all.
Gotcha: SQL*Plus and trailing commentsMy first run failed with ORA-01919: role does not exist. I had written CREATE ROLE serverdb_ro; -- comment, and in SQL*Plus a comment after the semicolon means the line doesn't end the statement. The next two lines got merged into it. I moved the comments onto their own lines, wrote an uninstall script, and re-ran it clean.
sqlplus / as sysdba @install.sql — end of the clean run
==== serverdb install complete ====

OBJECT_TYPE                OBJECTS      VALID
----------------------- ---------- ----------
FUNCTION                         1          1
INDEX                           25         25
INDEX PARTITION                  2          2
PACKAGE                          1          1
PACKAGE BODY                     1          1
SEQUENCE                         4          4
TABLE                           15         15
TABLE PARTITION                  2          2
VIEW                            16         16

9 rows selected.
4
Data model

Tables, partitions, staging and reporting views

Every table has named constraints, its primary-key index in SERVERDB_INDEX, and COMMENT ON documentation in the data dictionary. The file catalogue is the largest table:

oracle/sql/02_tables.sql — RAID_FILE
CREATE TABLE raid_file (
  file_id      NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  path         VARCHAR2(2000) NOT NULL,
  top_folder   VARCHAR2(255)  NOT NULL,
  name         VARCHAR2(1000) NOT NULL,
  ext          VARCHAR2(20),
  category     VARCHAR2(20)   NOT NULL,
  size_bytes   NUMBER(16)     NOT NULL,
  modified_at  TIMESTAMP      NOT NULL,
  quick_hash   VARCHAR2(40),
  first_seen   TIMESTAMP      DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL,
  last_seen    TIMESTAMP      DEFAULT SYS_EXTRACT_UTC(SYSTIMESTAMP) NOT NULL,
  deleted_at   TIMESTAMP,
  CONSTRAINT pk_raid_file PRIMARY KEY (file_id) USING INDEX TABLESPACE serverdb_index,
  CONSTRAINT uk_raid_file_path UNIQUE (path) USING INDEX TABLESPACE serverdb_index
);
CREATE INDEX raid_file_i1 ON raid_file (quick_hash)  TABLESPACE serverdb_index;
interval partitioning
CREATE TABLE container_sample (
  sample_ts       TIMESTAMP     NOT NULL,
  container_name  VARCHAR2(128) NOT NULL,
  state           VARCHAR2(20)  NOT NULL,
  health          VARCHAR2(20),
  restart_count   NUMBER(8),
  started_at      TIMESTAMP,
  cpu_pct         NUMBER,
  mem_bytes       NUMBER(16),
  net_rx_bytes    NUMBER(18),
  net_tx_bytes    NUMBER(18),
  blk_read        NUMBER(18),
  blk_write       NUMBER(18),
  CONSTRAINT pk_container_sample PRIMARY KEY (container_name, sample_ts)
    USING INDEX LOCAL TABLESPACE serverdb_index
)
PARTITION BY RANGE (sample_ts) INTERVAL (NUMTOYMINTERVAL(1, 'MONTH'))
  (PARTITION p_initial VALUES LESS THAN (TIMESTAMP '2026-11-01 00:00:00'));
staging table + NULL-safe key
-- Staging table for the nightly scan (like an RMS staging table for an upload):
-- rows exist only for the loading transaction.
CREATE GLOBAL TEMPORARY TABLE raid_scan_stage (
  path         VARCHAR2(2000),
  top_folder   VARCHAR2(255),
  name         VARCHAR2(1000),
  ext          VARCHAR2(20),
  category     VARCHAR2(20),
  size_bytes   NUMBER(16),
  modified_at  TIMESTAMP
) ON COMMIT DELETE ROWS;

-- NULL-safe natural key so re-reading a log never creates duplicates.
CREATE UNIQUE INDEX game_event_uk ON game_event
  (server_name, event_ts, event_type, NVL(player, '~'), NVL(ip_address, '~')) TABLESPACE serverdb_index;
Why partition?Container stats arrive every 5 minutes (about 9,000 rows a day). With monthly interval partitions, Oracle creates each new month on its own, and old data can be removed by dropping a partition instead of running a huge DELETE.
partitions Oracle created automatically

TABLE_NAME        PARTITION_NA   NUM_ROWS HIGH_VALUE
----------------- ------------ ---------- ----------------------------------------
CONTAINER_SAMPLE  P_INITIAL             0 TIMESTAMP' 2026-11-01 00:00:00'
CONTAINER_SAMPLE  SYS_P517          20584 TIMESTAMP' 2026-12-01 00:00:00'
HOST_SAMPLE       P_INITIAL             0 TIMESTAMP' 2026-11-01 00:00:00'
HOST_SAMPLE       SYS_P516            710 TIMESTAMP' 2026-12-01 00:00:00'

4 rows selected.
Gotcha: in Oracle, '' IS NULLPostgreSQL treats an empty string and NULL as different values. Oracle stores '' as NULL. Anonymous port-scanner events used to have player = '' under a NOT NULL rule, which would fail in Oracle. I made the column nullable and built the unique key with NVL(player, '~'), so re-reading a log still can't create duplicates.

The reporting views do the Postgres-specific work with Oracle features, for example OUTER APPLY to pair game sessions and JSON_ARRAYAGG for duplicate-file lists:

04_views.sql — V_GAME_SESSION
CREATE OR REPLACE VIEW v_game_session AS
  SELECT j.server_name, j.player, j.event_ts AS joined_at, l.left_at,
         ROUND((CAST(NVL(l.left_at, SYS_EXTRACT_UTC(SYSTIMESTAMP)) AS DATE)
                - CAST(j.event_ts AS DATE)) * 86400) AS duration_sec
  FROM   game_event j
  OUTER  APPLY (SELECT MIN(e.event_ts) AS left_at
                FROM   game_event e
                WHERE  e.server_name = j.server_name
                AND    e.player      = j.player
                AND    e.event_type  = 'leave'
                AND    e.event_ts   >= j.event_ts) l
  WHERE  j.event_type = 'join';
04_views.sql — V_DUPLICATES
CREATE OR REPLACE VIEW v_duplicates AS
  SELECT quick_hash, size_bytes, size_pretty(size_bytes) AS size_text,
         COUNT(*) AS copies,
         size_bytes * (COUNT(*) - 1) AS wasted_bytes,
         size_pretty(size_bytes * (COUNT(*) - 1)) AS wasted_text,
         JSON_ARRAYAGG(path ORDER BY path RETURNING CLOB) AS paths_json
  FROM   v_raid_file_current
  WHERE  quick_hash IS NOT NULL
  GROUP  BY quick_hash, size_bytes
  HAVING COUNT(*) > 1
  ORDER  BY size_bytes * (COUNT(*) - 1) DESC;
5
PL/SQL

A batch-control package, written the retail way

Every collector job starts and finishes through JOB_RUN_SQL. I followed the conventions of packaged retail code: a <AREA>_SQL package, functions that return BOOLEAN, an O_error_message parameter, and I_/O_/L_ prefixes.

03_plsql.sql — specification
CREATE OR REPLACE PACKAGE job_run_sql AUTHID DEFINER AS
  -------------------------------------------------------------------------
  -- Batch-control API for the collector. Both functions run as autonomous
  -- transactions, so the run log is kept even when the job itself rolls back.
  -------------------------------------------------------------------------
  FUNCTION start_run (O_error_message IN OUT VARCHAR2,
                      O_run_id        OUT    job_run.run_id%TYPE,
                      I_job           IN     job_run.job%TYPE)
  RETURN BOOLEAN;

  FUNCTION finish_run (O_error_message IN OUT VARCHAR2,
                       I_run_id        IN     job_run.run_id%TYPE,
                       I_ok_ind        IN     job_run.ok_ind%TYPE,
                       I_row_count     IN     job_run.row_count%TYPE,
                       I_error_msg     IN     job_run.error_msg%TYPE)
  RETURN BOOLEAN;
END job_run_sql;
03_plsql.sql — body (start_run)
CREATE OR REPLACE PACKAGE BODY job_run_sql AS

  FUNCTION start_run (O_error_message IN OUT VARCHAR2,
                      O_run_id        OUT    job_run.run_id%TYPE,
                      I_job           IN     job_run.job%TYPE)
  RETURN BOOLEAN
  IS
    PRAGMA AUTONOMOUS_TRANSACTION;
    L_program VARCHAR2(64) := 'JOB_RUN_SQL.START_RUN';
  BEGIN
    IF I_job IS NULL THEN
      O_error_message := L_program || ': I_job is required';
      RETURN FALSE;
    END IF;
    INSERT INTO job_run (job) VALUES (I_job)
    RETURNING run_id INTO O_run_id;
    COMMIT;
    RETURN TRUE;
  EXCEPTION
    WHEN OTHERS THEN
      ROLLBACK;
      O_error_message := L_program || ': ' || SQLERRM;
      RETURN FALSE;
  END start_run;
Why an autonomous transaction?PRAGMA AUTONOMOUS_TRANSACTION commits the log row on its own. If a job fails and rolls back its data, the record that it ran, and why it failed, is kept.
6
Security

Roles, schema privileges and synonyms

Permissions are granted to roles, and the roles are granted to accounts. Oracle 23ai/26ai added schema-level privileges, so one grant covers every current and future table in SERVERDB. Private synonyms let the accounts write raid_file instead of serverdb.raid_file.

05_security.sql
GRANT SELECT ANY TABLE ON SCHEMA serverdb TO serverdb_ro;

GRANT SELECT ANY TABLE, INSERT ANY TABLE, UPDATE ANY TABLE, DELETE ANY TABLE
  ON SCHEMA serverdb TO serverdb_rw;
GRANT EXECUTE ANY PROCEDURE ON SCHEMA serverdb TO serverdb_rw;
refresh_synonyms.sql (re-runnable)
BEGIN
  FOR u IN (SELECT username FROM dba_users WHERE username IN ('SERVERDB_ETL', 'SERVERDB_WEB', 'SERVERDB_DEV')) LOOP
    FOR o IN (SELECT object_name FROM dba_objects
              WHERE  owner = 'SERVERDB'
              AND    object_type IN ('TABLE', 'VIEW', 'PACKAGE', 'FUNCTION', 'PROCEDURE')
              AND    object_name NOT LIKE 'BIN$%') LOOP
      EXECUTE IMMEDIATE 'CREATE OR REPLACE SYNONYM ' || u.username || '.' || o.object_name
                     || ' FOR SERVERDB.' || o.object_name;
    END LOOP;
  END LOOP;
END;
/
GotchaMy first design used a database logon trigger owned by SYSTEM to set CURRENT_SCHEMA. 26ai refused it with ORA-01031: insufficient privileges. Synonyms turned out to be the better answer anyway, because that's how application users see the owner schema in a retail install.

Then I tested the lock-down rather than assuming it worked. The dashboard account can read but not change data, and nobody can sign in as the owner:

least-privilege test, signed in as SERVERDB_WEB
USER is "SERVERDB_WEB"

LIVE_FILES
----------
    343938

1 row selected.

DELETE FROM raid_file WHERE ROWNUM = 1
            *
ERROR at line 1:
ORA-41900: missing DELETE privilege on "SERVERDB"."RAID_FILE"
Help: https://docs.oracle.com/error-help/db/ora-41900/


UPDATE job_run SET ok_ind = 'Y' WHERE ROWNUM = 1
       *
ERROR at line 1:
ORA-41900: missing UPDATE privilege on "SERVERDB"."JOB_RUN"
Help: https://docs.oracle.com/error-help/db/ora-41900/


ERROR:
ORA-01017: invalid credential or not authorized; logon denied
Help: https://docs.oracle.com/error-help/db/ora-01017/


Warning: You are no longer connected to ORACLE.
7
Application code

Port the Python collector and API to python-oracledb

Both programs switched from psycopg to python-oracledb in thin mode, which is pure Python and doesn't need the Oracle Instant Client. Most of the work was rewriting every SQL statement: %s placeholders became :1/:name bind variables, upserts became MERGE, and the timestamps became UTC.

collector.py — batched inserts, skip duplicates
def execmany(cur, sql, rows, ignore_dups=False):
    """executemany in batches. ignore_dups: skip ORA-00001 rows (Postgres' ON CONFLICT DO NOTHING)."""
    done = 0
    for i in range(0, len(rows), BATCH):
        chunk = rows[i:i + BATCH]
        set_types(cur, chunk)
        cur.executemany(sql, chunk, batcherrors=ignore_dups)
        if ignore_dups:
            errs = cur.getbatcherrors()
            bad = [e for e in errs if e.code != 1]
            if bad:
                raise RuntimeError(f"{len(bad)} rows rejected, first: {bad[0].message}")
            done += len(chunk) - len(errs)
        else:
            done += len(chunk)
    return done
collector.py — every job goes through JOB_RUN_SQL
def run_job(name, fn):
    conn = connect()
    try:
        with conn.cursor() as cur:   # JOB_RUN_SQL commits autonomously: the log survives a rollback
            err, rid = cur.var(str, 4000), cur.var(int)
            if not cur.callfunc("job_run_sql.start_run", bool, [err, rid, name]):
                raise RuntimeError(err.getvalue())
            rid = rid.getvalue()
        t = time.time()
collector.py — applying the nightly scan from the staging table
        # 2. Apply it to RAID_FILE: new, changed, still there, gone.
        cur.execute("""INSERT INTO raid_file (path, top_folder, name, ext, category, size_bytes, modified_at)
                       SELECT s.path, s.top_folder, s.name, s.ext, s.category, s.size_bytes, s.modified_at
                       FROM   raid_scan_stage s
                       WHERE  NOT EXISTS (SELECT 1 FROM raid_file f WHERE f.path = s.path)""")
        added = cur.rowcount
        cur.execute("""MERGE INTO raid_file f USING raid_scan_stage s ON (f.path = s.path)
                       WHEN MATCHED THEN UPDATE SET f.size_bytes = s.size_bytes, f.modified_at = s.modified_at,
                         f.quick_hash = NULL, f.top_folder = s.top_folder, f.category = s.category
                       WHERE f.size_bytes <> s.size_bytes OR f.modified_at <> s.modified_at""")
        changed = cur.rowcount
        cur.execute("""MERGE INTO raid_file f USING raid_scan_stage s ON (f.path = s.path)
                       WHEN MATCHED THEN UPDATE SET f.last_seen = :now, f.deleted_at = NULL""", now=now)
        cur.execute("""UPDATE raid_file f SET deleted_at = :now
                       WHERE  deleted_at IS NULL
                       AND    NOT EXISTS (SELECT 1 FROM raid_scan_stage s WHERE s.path = f.path)""", now=now)
        removed = cur.rowcount
Keeping the website unchangedThe dashboard's JavaScript expects lower-case keys, true/false values and lists. The API changes Oracle's upper-case columns, Y/N indicators and LISTAGG strings back into that shape, so no change to the website was needed.
api.py — shaping Oracle rows for the dashboard
def rows_as_dicts(cur):
    """Oracle returns upper-case column names; the dashboard expects the old lower-case keys."""
    cols = [d[0].lower() for d in cur.description]
    out = []
    for r in cur.fetchall():
        row = {}
        for c, v in zip(cols, r):
            if c == "rows_loaded":
                c = "rows"
            if c in BOOL_COLS:
                v = None if v is None else v == "Y"
            elif c in LIST_COLS:
                v = v.split(",") if v else []
            elif c in JSON_COLS:
                v = (json.loads(v) if isinstance(v, str) else v or [])[:4]
            row[c] = v
        out.append(row)
    return out
collector/Dockerfile
FROM python:3.13.15-slim
# Debian slim (not Alpine): oracledb ships glibc wheels only.
# oracledb runs in "thin" mode: pure Python, no Oracle Instant Client needed.
# psycopg stays in the image only for the one-off PostgreSQL -> Oracle migration.
RUN pip install --no-cache-dir "oracledb==3.4.2" "psycopg[binary]==3.2.10" "tzdata==2025.2"
WORKDIR /app
CMD ["python", "-u", "/app/collector.py"]
Gotchas I hitoracledb has no pre-built package for Alpine Linux and tried to compile itself (there's no gcc in Alpine), so the image moved to Debian slim. GROUPS is a reserved word in Oracle, so the alias had to be quoted. Also, 26ai returns JSON_ARRAYAGG results as Python lists already, so calling json.loads() on them raised an error until I checked the type first.
8
Data migration

Migrate every row, then prove it

With the old collector stopped (so the source couldn't change), a one-off script read each PostgreSQL table with a server-side cursor, converted the values (UTC timestamps, Y/N, text IPs, '' → NULL), and inserted them in batches of 5,000. Then it reconciled each table: row counts plus a checksum column, source against target.

python migrate_pg_to_oracle.py — the real cut-over run
source: PostgreSQL 170006   target: Oracle 23.26.3.0.0 (127.0.0.1:1521/FREEPDB1)

source table               target table            rows   secs
--------------------------------------------------------------
meta.job_run               job_run                1,489    0.1
meta.ingested_file         ingested_file         11,116    0.3
files.file                 raid_file            344,342   75.3
files.scan                 raid_scan                  4    0.1
files.sorter_move          sorter_move                1    0.0
plex.library               plex_library               6    0.1
plex.item                  plex_item              1,597    0.1
plex.account               plex_account              67    0.0
plex.watch                 plex_watch                10    0.0
stats.host_sample          host_sample              709    0.0
stats.container_sample     container_sample      20,554    0.8
backups.run                backup_run                40    0.0
games.event                game_event               973    0.1
--------------------------------------------------------------
loaded in                                       76.9 s

RECONCILIATION
table                pg rows  ora rows        pg checksum       ora checksum  result
--------------------------------------------------------------------------------------
job_run                1,489     1,489          1,507,808          1,507,808  MATCH
ingested_file         11,116    11,116         77,240,268         77,240,268  MATCH
raid_file            344,342   344,342  2,174,045,554,838  2,174,045,554,838  MATCH
raid_scan                  4         4  5,810,096,130,463  5,810,096,130,463  MATCH
sorter_move                1         1                  1                  1  MATCH
plex_library               6         6                 21                 21  MATCH
plex_item              1,597     1,597    584,371,950,633    584,371,950,633  MATCH
plex_account              67        67     33,166,619,581     33,166,619,581  MATCH
plex_watch                10        10                 55                 55  MATCH
host_sample              709       709  7,082,127,847,424  7,082,127,847,424  MATCH
container_sample      20,554    20,554  5,588,332,371,968  5,588,332,371,968  MATCH
backup_run                40        40            354,762            354,762  MATCH
game_event               973       973                 63                 63  MATCH
--------------------------------------------------------------------------------------
all tables reconciled
The trial run caught two "mismatches"JOB_RUN differed because the old collector was still writing during the rehearsal. That was expected, and it's why the real run froze the source first. GAME_EVENT differed because PostgreSQL's COUNT(DISTINCT player) counted '' as a player and Oracle's did not (it's NULL there). I fixed the checksum to compare like with like, not the data.
post_migrate.sql
ALTER TABLE serverdb.job_run    MODIFY run_id   GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE);
ALTER TABLE serverdb.raid_file  MODIFY file_id  GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE);
ALTER TABLE serverdb.raid_scan  MODIFY scan_id  GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE);
ALTER TABLE serverdb.game_event MODIFY event_id GENERATED BY DEFAULT ON NULL AS IDENTITY (START WITH LIMIT VALUE);
PROMPT identity columns reset

EXEC DBMS_STATS.GATHER_SCHEMA_STATS('SERVERDB', cascade => TRUE);
PROMPT schema statistics gathered
Mirrors workCounts and checksums by table are how retail data loads are validated: a load isn't finished until it reconciles.
9
Go-live

Cut over, verify, and keep the rollback ready

The compose file now points the collector and API at Oracle. I started them, called every API endpoint, and ran each collector job, including the nightly scan of all 343,938 files (36 seconds). Only then did I stop PostgreSQL. Its container was removed, but its data volume was kept, frozen at the moment of migration, with a separate compose file to bring it back.

reporting views after cut-over (as SERVERDB_ETL)
-- where the RAID space goes (V_FOLDER_USAGE)

TOP_FOLDER                FILES SIZE
-------------------- ---------- ----------
Plex                      22241 840 GB
proxmox-backups              24 447 GB
AMP1                     320329 59 GB
Software                     14 2818 MB
Games                       638 2458 MB
server-backups              114 1372 MB
Projects                    296 24 MB
Documents                    77 8541 kB

8 rows selected.

-- batch control: last run of each collector job (V_JOB_LATEST)

JOB      STARTED           OK   ROW_COUNT ERROR
-------- ----------------- --- ---------- ----------
backups  2026-11-13 09:40  Y           40
files    2026-11-13 09:41  Y       343938
games    2026-11-13 09:40  Y            8
plex     2026-11-13 09:40  Y         1607
sorter   2026-11-13 09:40  Y            1
stats    2026-11-13 09:40  Y           31

6 rows selected.

-- interval partitions created automatically, one per month
SELECT table_name, partition_name, num_rows, SUBSTR(high_value, 1, 34) AS high_value FROM user_tab_partitions ORDER BY table_name, partition_position
                                                    *
ERROR at line 1:
ORA-00932: expression is of data type LONG, which is incompatible with expected data type CHAR
Help: https://docs.oracle.com/error-help/db/ora-00932/
docker-compose.postgres-rollback.yml
# ROLLBACK ONLY. The PostgreSQL 17 database serverdb ran on until 2026-11-13.
# Its data volume (serverdb_serverdb-data) was kept, frozen at the moment of migration.
# To roll back:
#   1. cp collector/collector.py.postgres-bak collector/collector.py   (same for api/api.py,
#      collector/Dockerfile, api.env.postgres-bak -> api.env, docker-compose.yml.postgres-bak)
#   2. docker compose -f docker-compose.postgres-rollback.yml up -d   (or the restored main file)
10
Operations

Nightly Data Pump exports with DBMS_SCHEDULER

Oracle's own scheduler runs a Data Pump schema export at 00:30 each night into a folder that my existing restic backup picks up at 01:00. From there it's encrypted, deduplicated, and pulled to the off-site Raspberry Pi. A restore is one impdp command.

oracle/sql/06_scheduler.sql
BEGIN
  DBMS_SCHEDULER.CREATE_JOB(
    job_name        => 'SYSTEM.SERVERDB_NIGHTLY_EXPORT',
    job_type        => 'PLSQL_BLOCK',
    job_action      => q'[
DECLARE
  L_handle NUMBER;
  L_state  VARCHAR2(30);
BEGIN
  L_handle := DBMS_DATAPUMP.OPEN(operation => 'EXPORT', job_mode => 'SCHEMA',
                                 job_name  => 'SERVERDB_EXP_' || TO_CHAR(SYSDATE, 'YYYYMMDDHH24MISS'));
  DBMS_DATAPUMP.ADD_FILE(L_handle, 'serverdb.dmp', 'SERVERDB_DPDUMP', reusefile => 1);
  DBMS_DATAPUMP.ADD_FILE(L_handle, 'serverdb_export.log', 'SERVERDB_DPDUMP',
                         filetype => DBMS_DATAPUMP.KU$_FILE_TYPE_LOG_FILE, reusefile => 1);
  DBMS_DATAPUMP.METADATA_FILTER(L_handle, 'SCHEMA_EXPR', q'{IN ('SERVERDB')}');
  DBMS_DATAPUMP.START_JOB(L_handle);
  DBMS_DATAPUMP.WAIT_FOR_JOB(L_handle, L_state);
  IF L_state <> 'COMPLETED' THEN
    RAISE_APPLICATION_ERROR(-20001, 'serverdb export ended in state ' || L_state);
  END IF;
END;]',
    start_date      => TO_TIMESTAMP_TZ(TO_CHAR(SYSDATE + 1, 'YYYY-MM-DD') || ' 00:30 America/New_York',
                                       'YYYY-MM-DD HH24:MI TZR'),
    repeat_interval => 'FREQ=DAILY; BYHOUR=0; BYMINUTE=30; BYSECOND=0',
    enabled         => TRUE,
    comments        => 'Nightly Data Pump export of the SERVERDB schema for the restic backup.');
END;
/
serverdb_export.log — first run (tested by hand)
. . exported "SERVERDB"."HOST_SAMPLE":"SYS_P516"          60.6 KB     710 rows
. . exported "SERVERDB"."BACKUP_RUN"                        16 KB      40 rows
. . exported "SERVERDB"."PLEX_LIBRARY"                     6.1 KB       6 rows
. . exported "SERVERDB"."PLEX_ACCOUNT"                     6.3 KB      67 rows
Master table "SYSTEM"."SERVERDB_EXP_20261113094128" successfully loaded/unloaded
******************************************************************************
Dump file set for SYSTEM.SERVERDB_EXP_20261113094128 is:
  /opt/oracle/dpdump_serverdb/serverdb.dmp
Job "SYSTEM"."SERVERDB_EXP_20261113094128" successfully completed at Fri Nov 13 09:43:10 2026 elapsed 0 00:01:35

-- scheduler state
JOB_NAME                   STATE      NEXT_RUN
-------------------------- ---------- ----------------------
SERVERDB_NIGHTLY_EXPORT    SCHEDULED  2026-11-14 00:30 EST
Why this mattersThe Postgres database was never in the nightly backup, because its data sat in a Docker volume outside the backed-up folder. Moving to Oracle closed that gap with a proper, restorable export.
11
Tooling

SQL Developer Web for a read-only analyst

I installed Oracle REST Data Services, which provides SQL Developer in the browser, and created SERVERDB_DEV: an analyst account with the read-only role and its own synonyms. ORDS is an optional tool that I start when I need it. It listens on localhost only, and I reach it through an SSH tunnel.

127.0.0.1:8181/ords/serverdb_dev/_sdw — SQL Developer Web
SQL Developer Web: the navigator lists the SERVERDB tables, views and packages through synonyms, and the worksheet shows V_FOLDER_USAGE results
Screenshot
Signed in as the read-only analyst. The navigator shows the owner's objects through synonyms, and the worksheet queries the V_FOLDER_USAGE reporting view.
SQL worksheet · V_JOB_LATEST
SQL Developer Web worksheet showing the last run of each collector job with OK_IND Y
Screenshot
The batch run log: every collector job's last run, status and row count.
ORDS sign-in
Oracle Database Actions sign-in page
Screenshot
Database Actions sign-in. Only the analyst account is REST-enabled.
GotchaThe schema-only owner doesn't appear in SQL Developer Web's schema picker, because an account that can't sign in isn't listed. Giving the analyst account synonyms solved that, the same way it does for the application accounts.
Results

Live on Oracle, and the dashboard didn't notice

The admin dashboard has been reading from Oracle since the cut-over, with the same page and the same numbers.

13/13
tables reconciled on counts and checksums
36s
nightly scan of 343,938 files, staged and applied
256MB
used across both tablespaces (PostgreSQL was 399 MB)
63
schema objects (plus partitions), all VALID
www.ryangray.online/data
The server data dashboard, now served from Oracle: CPU, memory, RAID, disk, containers and backups
Screenshot
The /data dashboard after the cut-over, with every number coming from the Oracle SERVERDB schema.
Lessons learned

What this taught me about how retail systems work

The most useful lessons came from the things that broke.

Why nobody signs in as the owner

A schema-only owner, roles, and synonyms per account explain why at work I see "the tables" without ever being able to change their structure.

A load isn't done until it reconciles

Counts and checksums by table found two differences. Both were explainable, but I only knew that because I checked.

Empty string is NULL

Oracle's '' IS NULL rule affects unique keys, NOT NULL rules and even COUNT(DISTINCT). It explains a lot of "blank" field behaviour I've seen in retail data.

Stage, then apply

Loading into a staging table and applying it as a set in one transaction is how uploads stay all-or-nothing.

Batch logs survive failures

Autonomous transactions are why a failed batch still leaves a record of what happened.

Always have a way back

Rehearse first, freeze the source, keep the old system intact, and write down the rollback before the change goes in.

Next steps

Where the lab goes from here

The platform is in place. Next I want to use it to practise the parts of retail data work I deal with most.

  1. A small item / location / inventory model

    Item, location and stock-on-hand tables with sample data, plus a staged CSV upload and validation package, to practise how item and location uploads are processed.

  2. Query tuning with execution plans

    Use EXPLAIN PLAN, autotrace and index choices on the 344k-row file catalogue to learn why some reports are fast and others aren't.

  3. Restore drills and flashback

    A scheduled test restore of the nightly Data Pump export into a scratch schema, and Flashback Query for "what did this row look like an hour ago?"