Skip to content

Guide: migrate from a relational database

This guide moves an application from tables to aggregates: how to model them, how to load the data, how each kind of query is rewritten, and what stays SQL. The example is a small shop on SQLite (any relational database reads the same way through its driver); the loader and the rewritten queries run in CI and check that OliviaDB gives the same answers as SQL on the source (tools/docs-snippets.py, group guide-relational).

Four tables become two aggregates: customer, orders and lines nest; product stays separate and is referred to Tables customer id PK, name, email orders customer_id FK, no, placed, total order_line customer_id, no FK, line, sku FK product sku PK, title, price Aggregates aggregate Customer [id] name, email child Order [placed desc, no] status, total child Line [line] product: ref Product, quantity, price aggregate Product [sku] title, price nest

Four tables become two aggregates: customer, orders and lines nest; product stays a record of its own, referred to

1. Model: which tables become one aggregate

Walk the foreign keys and ask, for each table, whose is this row?

  • A table whose rows belong to one parent row and are read with it (orders of a customer, lines of an order) becomes a child type of the parent. Its foreign key to the parent disappears: the position in the tree says it. Its own key becomes the child's key, often with a sort part (Order [placed: timestamp desc, no: int32]: newest first).
  • A table referred to by many and owned by none (products, merchants, currencies) stays an aggregate of its own; the referring column becomes a ref field, checked on write.
  • A lookup table of a few fixed values becomes an enum.
  • A many-to-many link table becomes a child type holding refs, under the side that reads it.
  • A unique column you search by (email) becomes an index; a non-unique one too (without unique), or async when it may lag the write.
  • Columns become numbered, typed fields; NUMERIC(p,s) becomes decimal(p,s), VARCHAR(n) string(n), unbounded text text, TIMESTAMP timestamp.

The source:

CREATE TABLE product  (sku TEXT PRIMARY KEY, title TEXT NOT NULL, price NUMERIC NOT NULL);
CREATE TABLE customer (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE NOT NULL);
CREATE TABLE orders   (customer_id INTEGER NOT NULL REFERENCES customer(id), no INTEGER NOT NULL,
                       placed TEXT NOT NULL, status TEXT NOT NULL, total NUMERIC NOT NULL,
                       PRIMARY KEY (customer_id, no));
CREATE TABLE order_line (customer_id INTEGER NOT NULL, no INTEGER NOT NULL, line INTEGER NOT NULL,
                       sku TEXT NOT NULL REFERENCES product(sku), quantity INTEGER NOT NULL, price NUMERIC NOT NULL,
                       PRIMARY KEY (customer_id, no, line),
                       FOREIGN KEY (customer_id, no) REFERENCES orders(customer_id, no));
INSERT INTO product VALUES ('TEA-1', 'Green tea', '4.50'), ('MUG-2', 'Blue mug', '9.00');
INSERT INTO customer VALUES (1, 'Ada Lovelace', 'ada@example.org'), (2, 'Alan Turing', 'alan@example.org');
INSERT INTO orders VALUES (1, 1, '2026-11-02T10:00:00Z', 'S', '18.00'), (1, 2, '2026-11-20T16:30:00Z', 'O', '9.00'),
                          (2, 1, '2026-11-05T08:15:00Z', 'S', '4.50');
INSERT INTO order_line VALUES (1, 1, 1, 'TEA-1', 2, '4.50'), (1, 1, 2, 'MUG-2', 1, '9.00'),
                              (1, 2, 1, 'MUG-2', 1, '9.00'), (2, 1, 1, 'TEA-1', 1, '4.50');

The schema it becomes, with a profile for the loader and one for the shop's service:

schema shop version 1

aggregate Product {
  key sku: string(16)
  1 title: string(80)
  2 price: decimal(12,2)
}

aggregate Customer {
  key id: int32
  1 name:  string(80)
  2 email: string(120)

  child Order [placed: timestamp desc, no: int32] unique {
    1 status: enum { open = "O", shipped = "S" }
    2 total:  decimal(12,2)

    child Line [line: int16] unique {
      1 product:  ref Product
      2 quantity: int32
      3 price:    decimal(12,2)
    }
  }
}

index customer_by_email on Customer(email) unique

profile loader for service "loader" {
  insert Product
  insert Customer
  insert Customer/{id}/Order
  insert Customer/{id}/Order/{o}/Line
}

profile shop for service "shop" {
  get    Product/{sku}
  get    Customer/{id}/**
  list   Customer/{id}/Order limit 50
  lookup customer_by_email -> Customer
}

Choose the aggregate by the transactions you need: a transaction writes within one aggregate record. If two rows must change atomically, they belong to the same aggregate; if they change independently, keeping them apart keeps writers from conflicting.

2. Load the data

Start a server with the schema (as in Get started):

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 365 \
  -subj /CN=localhost -addext subjectAltName=DNS:localhost,IP:127.0.0.1 \
  -addext basicConstraints=critical,CA:FALSE -addext extendedKeyUsage=serverAuth \
  -keyout server.key -out server.pem 2>/dev/null
(umask 077; openssl rand -hex 24 > api-key-loader; openssl rand -hex 24 > api-key)
cat > config.json <<EOF2
{"listen": "127.0.0.1:8443", "native_listen": "127.0.0.1:7655", "dir": "data",
 "tls": {"cert": "server.pem", "key": "server.key"}, "schema": "shop.olv",
 "api_keys": [
   {"sha256": "$(oliviadb-server --hash-key "$(cat api-key-loader)")", "tenant": "shop", "principal": "loader", "profiles": ["read", "memory"]},
   {"sha256": "$(oliviadb-server --hash-key "$(cat api-key)")", "tenant": "shop", "principal": "shop", "profiles": ["read"]}]}
EOF2
oliviadb-server --config config.json >> server.log 2>&1 &
echo $! > oliviadb.pid
until curl -fsS --cacert server.pem https://localhost:8443/readyz; do sleep 0.2; done

Then read the source and write each record: referenced aggregates first (a ref must name an existing node), then each customer with its orders and lines as one transaction, so a failed load leaves no half customer and can be resumed by skipping customers that exist (an insert of an existing node answers 409).

"""Load the relational database (SQLite here: any DB-API driver reads the same way) into
OliviaDB: products first (lines refer to them), then one transaction per customer with its
orders and their lines."""

import os
import sqlite3

from oliviadb.native import NativeClient

src = sqlite3.connect("source.db")
key = open("api-key-loader").read().strip()
with NativeClient.connect_tls("localhost", 7655, "token", key, ca_file=os.environ["OLIVIADB_CA_FILE"]) as db:
    for sku, title, price in src.execute("SELECT sku, title, price FROM product"):
        db.write("POST", f"Product/{sku}", {"fields": {"title": title, "price": str(price)}})
    for cid, name, email in src.execute("SELECT id, name, email FROM customer ORDER BY id"):
        ops = [{"op": "insert", "path": f"Customer/{cid}", "fields": {"name": name, "email": email}}]
        orders = src.execute("SELECT no, placed, status, total FROM orders WHERE customer_id = ?", (cid,)).fetchall()
        for no, placed, status, total in orders:
            order = f"Customer/{cid}/Order/{placed},{no}"
            ops.append({"op": "insert", "path": order,
                        "fields": {"status": {"O": "open", "S": "shipped"}[status], "total": str(total)}})
            lines = src.execute("SELECT line, sku, quantity, price FROM order_line WHERE customer_id = ? AND no = ?",
                                (cid, no)).fetchall()
            for line, sku, qty, price in lines:
                ops.append({"op": "insert", "path": f"{order}/Line/{line}",
                            "fields": {"product": sku, "quantity": qty, "price": str(price)}})
        db.txn({"ops": ops})  # all of the customer, or nothing
print("loaded")

For large volumes, run several loaders over disjoint key ranges at once (each transaction is one customer, so they do not conflict), and keep each transaction under the request limit (1 MiB of JSON over HTTP). Changes made in the source during the load are caught up from its change log after the bulk load, then the application switches over.

3. Rewrite the queries

"""The application's queries before (SQL on the source) and after (OliviaDB): the same answers."""

import os
import sqlite3
from decimal import Decimal

from oliviadb.native import NativeClient

src = sqlite3.connect("source.db")
key = open("api-key").read().strip()
with NativeClient.connect_tls("localhost", 7655, "token", key, ca_file=os.environ["OLIVIADB_CA_FILE"]) as db:
    # 1. A customer's orders with their lines: a join of three tables -> one tree read.
    sql = src.execute("""SELECT o.no, l.line, l.sku, l.quantity FROM orders o
                         JOIN order_line l ON l.customer_id = o.customer_id AND l.no = o.no
                         WHERE o.customer_id = 1 ORDER BY o.placed DESC, l.line""").fetchall()
    tree = db.get("Customer/1", {"tree": "true"}).to_json(False)
    got = [(o["key"]["no"], ln["key"]["line"], ln["fields"]["product"], ln["fields"]["quantity"])
           for o in tree["children"]["Order"] for ln in o["children"]["Line"]]
    assert got == sql, (got, sql)

    # 2. The newest orders of a customer: ORDER BY placed DESC LIMIT n -> a listing in key order.
    sql = [r[0] for r in src.execute("SELECT no FROM orders WHERE customer_id = 1 ORDER BY placed DESC LIMIT 1")]
    page = db.get("Customer/1/Order", {"limit": "1"}).to_json(True)
    assert [n["key"]["no"] for n in page["nodes"]] == sql

    # 3. A customer by a unique column: WHERE email = ? -> a lookup through an index.
    sql = src.execute("SELECT id FROM customer WHERE email = 'alan@example.org'").fetchone()[0]
    hits = db.lookup("customer_by_email", {"key": "alan@example.org"}).nodes()
    assert hits[0].to_json("")["key"]["id"] == sql

    # 4. A sum over children: computed from the tree that was read anyway.
    sql = Decimal(str(src.execute("SELECT SUM(total) FROM orders WHERE customer_id = 1").fetchone()[0]))
    assert sum(Decimal(o["fields"]["total"]) for o in tree["children"]["Order"]) == sql
print("the same answers")
python3 -c 'import sqlite3; sqlite3.connect("source.db").executescript(open("source.sql").read())'
OLIVIADB_CA_FILE=$PWD/server.pem python3 load.py
OLIVIADB_CA_FILE=$PWD/server.pem python3 queries.py
SQL OliviaDB
A join of a parent and its children one tree read: GET Customer/1?tree=true (with each=N to cap every listing)
WHERE parent_id = ? ORDER BY k LIMIT n a listing of the child type in key order, limit, after for the next page, to for a range
WHERE unique_column = ? a lookup through a declared index
SUM, COUNT over a parent's children computed from the tree already read, or a field kept up to date in the same transaction (add)
A full-text LIKE '%..%' search <aggregate>: ranked text within a token budget
UPDATE ... SET n = n + ? update with add: relative, no lost update
SELECT ... FOR UPDATE then UPDATE an unchanged since <version> precondition in the transaction (optimistic)
A multi-table BEGIN ... COMMIT POST /v1/txn within one aggregate record; across records, the pattern of transfers
Ad-hoc reports across all customers the change stream into your warehouse (change stream)

What stays SQL

The SQL projection serves hierarchical databases as read-only tables over the PostgreSQL wire protocol (psql, JDBC, BI tools), today for DL/I databases (an IMS replica, the image's demo bank). Aggregates of the schema language are not projected to SQL yet: read them over the network API, or feed reporting from the change stream.

Ask your agent

Using the oliviadb-migrate skill, read the DDL of our PostgreSQL schema in db/schema.sql, propose OliviaDB aggregates (which tables nest, which stay separate, enums, indexes) with the reasons, write the .olv file and a loader that copies the data customer by customer, and rewrite the queries in src/repo/ with tests that compare the answers with the source.