Typed clients¶
What it does: oliviadb codegen reads a schema and writes, for Rust, Java, TypeScript or
Python, a model per node type and typed paths, so a program reads and writes Customer,
Account and Entry values instead of paths and JSON. With --profile the profile is the
contract: an operation it does not grant, or a field it does not let change, does not
compile (in Python, mypy rejects it). The code runs on the official client of its language,
over HTTP or the native protocol, with the same calls on both.
This page uses the schema of the Get started path as the server serves it
after step 4 (version 2, profile app), and the server and
settings of step 2.
Client versions
Typed code needs the clients of release 0.1.2 or later (oliviadb crate, oliviadb-client
for Java, @olivia-db/client, oliviadb for Python); generate it with the oliviadb of the
same release.
Generate the code¶
oliviadb schema client is oliviadb codegen for one profile (it requires --profile);
oliviadb codegen FILE --lang L --out DIR without --profile writes the whole schema, for
services that read under several profiles. Generate from the schema the server serves, and
again whenever it changes.
oliviadb schema client bank.olv --lang rust --profile app --out bank-app
A crate bank-app on the oliviadb crate. Add it to your application's Cargo.toml:
bank-app = { path = "bank-app" }, with the oliviadb crate of the same release. --sdk path:DIR makes the
crate depend on a checkout of the client instead.
oliviadb schema client bank.olv --lang java --profile app --out src
Sources in the package com.oliviadb.gen.bank.app (--package names another): one record
per node type, its paths, Index, and BankDb. Compile them with your code, with
oliviadb-client on the class path.
oliviadb schema client bank.olv --lang ts --profile app --out .
One module, bank_app.ts, on @olivia-db/client. Node.js 22.18 or later runs it as it
is; tsc --strict checks it with your code.
oliviadb schema client bank.olv --lang python --profile app --out .
A package bank_app (typed, with py.typed) on the oliviadb client. Run mypy
--strict on your code to have the profile checked before it runs.
What is generated, per node type of the profile:
| Rust | Java | TypeScript | Python | |
|---|---|---|---|---|
| model | struct Customer |
record Customer |
interface Customer |
@dataclass Customer |
| new node | NewCustomer |
Customer.New |
NewCustomer |
Customer.New |
| path, collection | Customer::key("42"), .accounts() |
Customer.key("42"), .accounts() |
the same | the same |
| change | AccountPatch::new().add_balance(..) |
a -> a.addBalance(..) |
{ add: { balance } } |
Account.Patch(add_balance=..) |
| enum | enum AccountStatus |
enum AccountStatus |
"open" \| "closed" |
class AccountStatus(Enum) |
Decimals are exact (Decimal, BigDecimal, the client's Decimal, decimal.Decimal),
timestamps and dates are the language's own (Python datetime, Java Instant and
LocalDate, TypeScript Instant and PlainDate of the client). A tree read fills the child
lists (accounts, entries) and sets is_tree; a node read leaves them empty.
The program¶
Each program opens customer TR1 (or TJ1, TS1, TP1) with an account, posts an entry
and changes the balance in one transaction, reads the customer back as one tree, pages through
its accounts, finds it through the account_by_number index, changes its e-mail address with
a checked read-change-write, watches what changed, reads untyped, and reads customer C1,
which step 4 wrote under version 1 of the schema. Reads go over the
native protocol; the change stream's batches are HTTP requests, so watch uses a second
Db over HTTP.
use bank_app::*;
use oliviadb::native::{Native, TlsOptions};
fn main() -> oliviadb::Result<()> {
let env = |k: &str| std::env::var(k).unwrap();
let (key, ca) = (env("OLIVIADB_KEY"), env("OLIVIADB_CA_FILE"));
let tls = TlsOptions { ca_file: Some(ca.clone().into()), server_name: None };
let addr = format!("{}:{}", env("OLIVIADB_NATIVE_HOST"), env("OLIVIADB_NATIVE_PORT"));
let db = Db::new(Native::connect_tls(&addr, &tls, "token", &key)?);
let http = Db::new(oliviadb::Client::builder([env("OLIVIADB_URL")]).api_key(&key).ca_file(&ca)?.build()?);
// Where the accounts' change stream is now: the watch below starts there.
let since = http.watch(Customer::any().accounts()).send()?.position;
// New nodes are typed, keys included.
db.insert(Customer::all(), NewCustomer { id: "TR1".into(), name: "Grace Hopper".into(), branch: "B1".into(), email: "".into() }).send()?;
let eur = Customer::key("TR1").account("TR1-EUR");
let opened = NewAccount { number: "TR1-EUR".into(), currency: "EUR".into(), balance: "100.00".parse()?, status: AccountStatus::Open };
db.insert(Customer::key("TR1").accounts(), opened).send()?;
// One transaction: the entry and the balance, all or none.
db.txn(|t| {
let entry = NewEntry { posted: "2026-12-01T10:00:00Z".parse()?, seq: 1, amount: "-12.50".parse()?, memo: "coffee beans".into() };
t.insert(eur.entries(), entry)?;
t.update(eur.clone(), AccountPatch::new().add_balance("-12.50".parse()?))
})?;
// The customer and everything under it, as models.
let c = db.get(Customer::key("TR1")).tree().send()?;
let a = &c.accounts[0];
println!("{} {} {} {}", c.name, a.number, a.balance, a.entries[0].memo);
assert_eq!(a.balance, "87.50".parse()?);
// A listing, page by page.
let mut page = db.list(Customer::key("TR1").accounts()).limit(50).send()?;
loop {
for a in &page.nodes {
println!("account {} {:?}", a.number, a.status);
}
let Some(next) = page.next else { break };
page = db.list(Customer::key("TR1").accounts()).after(Cursor::next(&next)).limit(50).send()?;
}
// The unique index: the customer of an account number, or none.
let owner = db.lookup(Index::account_by_number("TR1-EUR")).send()?;
assert_eq!(owner.map(|c| c.id), Some("TR1".to_string()));
// Read, change, write back on the condition that nobody wrote in between (retried if so).
db.txn(|t| t.update_checked(Customer::key("TR1"), |c| c.email = "grace@example.com".into()))?;
// What changed under the accounts since `since`, each change as a model.
for ch in http.watch(Customer::any().accounts()).from(&since).send()?.changes {
match ch.after {
Some(AccountChange::Account(a)) => println!("{:?} account {} {}", ch.op, a.number, a.balance),
Some(AccountChange::Entry(e)) => println!("{:?} entry {} {}", ch.op, e.posted, e.amount),
None => println!("{:?} {}", ch.op, ch.path),
}
}
// Untyped access, for tools: any path, fields as JSON.
let n = db.get_untyped(Path::root("Customer").key(["TR1"])).send()?;
println!("{} {}", n.path, n.fields["email"]);
// C1 was written under version 1, before `email` existed: read by field number.
let c1 = db.get(Customer::key("C1")).tree().send()?;
assert_eq!((c1.email.as_str(), c1.accounts[0].balance), ("", "100.00".parse()?));
// Errors carry the server's status: inserting TR1 again is a conflict.
let again = NewCustomer { id: "TR1".into(), name: "Grace Hopper".into(), branch: "B1".into(), email: "".into() };
match db.insert(Customer::all(), again).send() {
Err(e) if e.status() == Some(409) => println!("TR1 exists"),
other => panic!("{other:?}"),
}
Ok(())
}
cargo run.
import com.oliviadb.client.NativeClient;
import com.oliviadb.client.OliviaDbClient;
import com.oliviadb.client.OliviaDbException;
import com.oliviadb.client.dsl.Path;
import com.oliviadb.gen.bank.app.*;
import java.math.BigDecimal;
import java.net.URI;
import java.time.Instant;
public class Main {
static void check(boolean ok, String what) {
if (!ok) throw new IllegalStateException(what);
}
public static void main(String[] args) {
var env = System.getenv();
String key = env.get("OLIVIADB_KEY");
var tls = new NativeClient.TlsOptions().caFile(java.nio.file.Path.of(env.get("OLIVIADB_CA_FILE")));
try (NativeClient nat = NativeClient.connectTls(env.get("OLIVIADB_NATIVE_HOST"),
Integer.parseInt(env.get("OLIVIADB_NATIVE_PORT")), tls, "token", key)) {
var db = new BankDb(nat);
var http = new BankDb(OliviaDbClient.builder(URI.create(env.get("OLIVIADB_URL"))).apiKey(key).build());
// Where the accounts' change stream is now: the watch below starts there.
String since = http.watch(Customer.any().accounts()).send().position();
// New nodes are typed, keys included.
db.insert(Customer.all(), new Customer.New("TJ1", "Grace Hopper", "B1", "")).send();
var eur = Customer.key("TJ1").account("TJ1-EUR");
db.insert(Customer.key("TJ1").accounts(),
new Account.New("TJ1-EUR", "EUR", new BigDecimal("100.00"), AccountStatus.OPEN)).send();
// One transaction: the entry and the balance, all or none.
db.txn(t -> {
t.insert(eur.entries(), new Entry.New(Instant.parse("2026-12-01T10:00:00Z"), 1, new BigDecimal("-12.50"), "coffee beans"));
t.update(eur, a -> a.addBalance(new BigDecimal("-12.50")));
});
// The customer and everything under it, as models.
Customer c = db.get(Customer.key("TJ1")).tree().send();
Account a = c.accounts().get(0);
System.out.println(c.name() + " " + a.number() + " " + a.balance() + " " + a.entries().get(0).memo());
check(a.balance().equals(new BigDecimal("87.50")), "balance " + a.balance());
// A listing, page by page.
var page = db.list(Customer.key("TJ1").accounts()).limit(50).send();
while (true) {
for (Account x : page.nodes()) System.out.println("account " + x.number() + " " + x.status());
if (page.next() == null) break;
page = db.list(Customer.key("TJ1").accounts()).afterNext(page.next()).limit(50).send();
}
// The unique index: the customer of an account number, or none.
var owner = db.lookup(Index.accountByNumber("TJ1-EUR")).send();
check(owner.map(Customer::id).orElse("").equals("TJ1"), "owner");
// Read, change, write back on the condition that nobody wrote in between (retried if so).
db.txn(t -> t.updateChecked(Customer.key("TJ1"), x -> new Customer(
x.id(), x.name(), x.branch(), "grace@example.com", x.cards(), x.accounts(), x.isTree())));
// What changed under the accounts since `since`, each change as a model.
for (var ch : http.watch(Customer.any().accounts()).from(since).send().changes()) {
if (ch.after() instanceof Account x) System.out.println(ch.op() + " account " + x.number() + " " + x.balance());
else if (ch.after() instanceof Entry e) System.out.println(ch.op() + " entry " + e.posted() + " " + e.amount());
}
// Untyped access, for tools: any path, fields as JSON.
var n = db.getUntyped(Path.root("Customer").key("TJ1")).send();
System.out.println(n.path() + " " + n.fields().path("email").asText());
// C1 was written under version 1, before `email` existed: read by field number.
Customer c1 = db.get(Customer.key("C1")).tree().send();
check(c1.email().isEmpty() && c1.accounts().get(0).balance().equals(new BigDecimal("100.00")), "C1");
// Errors carry the server's status: inserting TJ1 again is a conflict.
try {
db.insert(Customer.all(), new Customer.New("TJ1", "Grace Hopper", "B1", "")).send();
check(false, "a second TJ1");
} catch (OliviaDbException e) {
check(e.status() == 409, "status " + e.status());
System.out.println("TJ1 exists");
}
}
}
}
Compile the generated sources and Main.java with the client on the class path ($CLASSPATH:
the client and its dependencies) into classes, then run Main. The HTTP client (the Db
the watch uses) trusts the server through Java's trust store, made from the certificate of
step 1 as in step 5; the native connection
takes the CA file itself:
keytool -importcert -noprompt -alias oliviadb -file server.pem -keystore oliviadb.jks -storepass changeit
java -Djavax.net.ssl.trustStore=oliviadb.jks -Djavax.net.ssl.trustStorePassword=changeit -cp "classes:$CLASSPATH" Main
import { Customer, Db, Decimal, Index, Instant, Path } from "./bank_app.ts";
import { OliviaDbClient, OliviaDbError } from "@olivia-db/client";
import { NativeClient } from "@olivia-db/client/native";
const env = process.env;
const key = env.OLIVIADB_KEY!;
const native = await NativeClient.connectTls(env.OLIVIADB_NATIVE_HOST!, Number(env.OLIVIADB_NATIVE_PORT), "token", key, {
caFile: env.OLIVIADB_CA_FILE,
});
const db = new Db(native);
const http = new Db(new OliviaDbClient({ baseUrl: env.OLIVIADB_URL!, apiKey: key }));
try {
// Where the accounts' change stream is now: the watch below starts there.
const since = (await http.watch(Customer.any().accounts())).position;
// New nodes are typed, keys included.
await db.insert(Customer.all(), { id: "TS1", name: "Grace Hopper", branch: "B1", email: "" });
const eur = Customer.key("TS1").account("TS1-EUR");
await db.insert(Customer.key("TS1").accounts(), {
number: "TS1-EUR", currency: "EUR", balance: Decimal.parse("100.00"), status: "open",
});
// One transaction: the entry and the balance, all or none.
await db.txn((t) => {
t.insert(eur.entries(), {
posted: Instant.parse("2026-12-01T10:00:00Z"), seq: 1, amount: Decimal.parse("-12.50"), memo: "coffee beans",
});
t.update(eur, { add: { balance: Decimal.parse("-12.50") } });
});
// The customer and everything under it, as models.
const c = await db.get(Customer.key("TS1"), { tree: true });
const a = (c.accounts ?? [])[0];
console.log(c.name, a.number, a.balance.toString(), (a.entries ?? [])[0].memo);
if (a.balance.toString() !== "87.50") throw new Error(`balance ${a.balance.toString()}`);
// A listing, page by page.
let page = await db.list(Customer.key("TS1").accounts(), { limit: 50 });
for (;;) {
for (const x of page.nodes) console.log("account", x.number, x.status);
if (page.next === undefined) break;
page = await db.list(Customer.key("TS1").accounts(), { after: { next: page.next }, limit: 50 });
}
// The unique index: the customer of an account number, or undefined.
const owner = await db.lookup(Index.accountByNumber("TS1-EUR"));
if (owner?.id !== "TS1") throw new Error("owner");
// Read, change, write back on the condition that nobody wrote in between (retried if so).
await db.txn(async (t) => {
await t.updateChecked(Customer.key("TS1"), (x) => {
x.email = "grace@example.com";
});
});
// What changed under the accounts since `since`, each change as a model.
for (const ch of (await http.watch(Customer.any().accounts(), { from: since })).changes) {
const x = ch.after;
if (x?.type === "Account") console.log(ch.op, "account", x.node.number, x.node.balance.toString());
else if (x?.type === "Entry") console.log(ch.op, "entry", x.node.posted.toString(), x.node.amount.toString());
}
// Untyped access, for tools: any path, fields as JSON.
const n = await db.getUntyped(Path.root("Customer").key("TS1"));
console.log(n.path, n.fields.email);
// C1 was written under version 1, before `email` existed: read by field number.
const c1 = await db.get(Customer.key("C1"), { tree: true });
if (c1.email !== "" || (c1.accounts ?? [])[0].balance.toString() !== "100.00") throw new Error("C1");
// Errors carry the server's status: inserting TS1 again is a conflict.
try {
await db.insert(Customer.all(), { id: "TS1", name: "Grace Hopper", branch: "B1", email: "" });
throw new Error("a second TS1");
} catch (e) {
if (!(e instanceof OliviaDbError) || e.status !== 409) throw e;
console.log("TS1 exists");
}
} finally {
native.close();
}
node main.ts (or compile it with tsc first).
import dataclasses
import datetime
import os
from decimal import Decimal
from bank_app import Account, AccountStatus, Customer, Db, Entry, Index, Path
from oliviadb import OliviaDbClient, OliviaDbError
from oliviadb.native import NativeClient
env = os.environ
key = env["OLIVIADB_KEY"]
with NativeClient.connect_tls(env["OLIVIADB_NATIVE_HOST"], int(env["OLIVIADB_NATIVE_PORT"]), "token", key,
ca_file=env["OLIVIADB_CA_FILE"]) as native:
db = Db(native)
http = Db(OliviaDbClient(env["OLIVIADB_URL"], api_key=key))
# Where the accounts' change stream is now: the watch below starts there.
since = http.watch(Customer.any().accounts()).position
# New nodes are typed, keys included.
db.insert(Customer.all(), Customer.New(id="TP1", name="Grace Hopper", branch="B1", email=""))
eur = Customer.key("TP1").account("TP1-EUR")
db.insert(Customer.key("TP1").accounts(),
Account.New(number="TP1-EUR", currency="EUR", balance=Decimal("100.00"), status=AccountStatus.OPEN))
# One transaction: the entry and the balance, all or none.
with db.txn() as t:
posted = datetime.datetime(2026, 12, 1, 10, tzinfo=datetime.timezone.utc)
t.insert(eur.entries(), Entry.New(posted=posted, seq=1, amount=Decimal("-12.50"), memo="coffee beans"))
t.update(eur, Account.Patch(add_balance=Decimal("-12.50")))
# The customer and everything under it, as models.
c = db.get(Customer.key("TP1"), tree=True)
a = c.accounts[0]
print(c.name, a.number, a.balance, a.entries[0].memo)
assert a.balance == Decimal("87.50"), a.balance
# A listing, page by page.
page = db.list(Customer.key("TP1").accounts(), limit=50)
while True:
for x in page.nodes:
print("account", x.number, x.status.name)
if page.next is None:
break
page = db.list(Customer.key("TP1").accounts(), after=page.next, limit=50)
# The unique index: the customer of an account number, or None.
owner = db.lookup(Index.account_by_number("TP1-EUR"))
assert owner is not None and owner.id == "TP1"
# Read, change, write back on the condition that nobody wrote in between (retried if so).
db.run_txn(lambda t: t.update_checked(Customer.key("TP1"), lambda x: dataclasses.replace(x, email="grace@example.com")))
# What changed under the accounts since `since`, each change as a model.
for ch in http.watch(Customer.any().accounts(), from_=since).changes:
if isinstance(ch.after, Account):
print(ch.op, "account", ch.after.number, ch.after.balance)
elif isinstance(ch.after, Entry):
print(ch.op, "entry", ch.after.posted, ch.after.amount)
# Untyped access, for tools: any path, fields as JSON.
n = db.get_untyped(Path.root("Customer").key("TP1"))
print(n.path, n.fields["email"])
# C1 was written under version 1, before `email` existed: read by field number.
c1 = db.get(Customer.key("C1"), tree=True)
assert c1.email == "" and c1.accounts[0].balance == Decimal("100.00")
# Errors carry the server's status: inserting TP1 again is a conflict.
try:
db.insert(Customer.all(), Customer.New(id="TP1", name="Grace Hopper", branch="B1", email=""))
raise AssertionError("a second TP1")
except OliviaDbError as e:
assert e.status == 409, e.status
print("TP1 exists")
python3 main.py.
Reading, writing, transactions¶
- Reads take typed paths:
get(path)(a node; withtreeits subtree; withas_ofat a version),list(collection)(a page;after,to,prefix,limit; give a page'snextback asafterfor the next one),lookup(Index.name(parts))(auniqueindex gives the record's root or none, another index a list of hits),searchwhere the profile grants it. - Writes:
insert(collection, new node),update(path, patch)(a patch sets fields and adds to numbers:addchanges a value relative to the stored one, in the transaction, without a read first),delete(path)where granted. txncollects operations and sends them as one transaction, all or none, within one customer (the profile'stxn scope aggregate).update_checked(updateChecked) reads a node, lets your function change the model, and writes back the fields it changed on the condition that the node is unchanged since the read; when another writer came first the server answers 412 and the transaction runs again, at most three times. In Python,with db.txn()runs once;db.run_txn(f)retries.- Watch (
watchgrants):watch(path)gives a batch of changes afterfrom(nowby default,start, or a position a batch gave) with the position after them, over HTTP; over the native protocol the changes stream as they come (stream(),watchStream,watch_stream). Each change has its operation, path and the node before and after as models of the types under the watched path. - Untyped access stays for tools and dynamic paths:
get_untyped,list_untyped(getUntyped,listUntyped) on aPath, with the fields as JSON.
After a schema change¶
Every stored node keeps the layout it was written with. Code generated from the schema the
server serves reads a node written under an older version by field number: a field the
older version did not have reads as its default ("" for C1's email above), a field the code
does not have is ignored, a renamed field is read under its new name. The client learns an older
layout's fields from the native protocol's type descriptors, or over HTTP from GET
/v1/layouts/{id}, once per layout. Writes always use the generated (deployed) version: an
update of an older node writes it back in the new layout.
Two versions can only conflict where oliviadb schema plan would have refused the change
(another type, length or scale under the same field number). Code generated from such a version
fails on those nodes with SchemaMismatch naming the field and both types; it never guesses.
Regenerate after every deployed change, and keep the code of a version until every service
reading with it is deployed with the new one: code a version behind reads newer nodes too (it
ignores the fields it does not know).
Errors¶
| Rust | Java | TypeScript | Python | |
|---|---|---|---|---|
| the server refused (403 not granted, 404, 409 exists, 412 changed since) | Error::Api, e.status() |
OliviaDbException, e.status() |
OliviaDbError, e.status |
OliviaDbError, e.status |
| a field's type conflicts with the generated code | Error::SchemaMismatch |
SchemaMismatchException |
SchemaMismatchError |
SchemaMismatchError |
| the answer lacks a field the model requires (code generated without the caller's profile) | Error::Decode |
DecodeException |
DecodeError |
DecodeError |
An operation the profile does not grant is not a run-time error: it does not exist on the path
(Rust, Java, TypeScript compile errors; mypy in Python). The server checks the profile again on
every call, so code generated without --profile gets 403 for what the caller's profile does
not grant.
By hand or with your coding agent¶
By hand: generate the code into your project, commit it or generate it in the build, and regenerate when the schema changes. With the OliviaDB skills installed (step 0):
Ask your agent
Using the oliviadb-develop skill, generate the typed TypeScript client of profile app from
bank.olv and write a function that posts an entry to an account and changes its balance in
one transaction, with a test against a local server.
The whole interface, per language: the specification
(sdk-dsl.md); the requests underneath: network API.