Skip to content

5. Connect an application

What this step does: an application opens customer RS1 (or JV1, JS1, PY1) with an account, posts an entry to the account and changes its balance in one transaction, then reads the customer back as one tree. It uses typed code generated from the schema (a model per node type, typed paths, the profile's grants checked by the compiler) on the official client of its language, over the native protocol: one long-lived TLS connection carrying many requests at once, reads answered in rows that are decoded field by field (protocols).

Install the client

Client versions

The typed code below needs the clients of release 0.1.2 or later, and the oliviadb command of the same release to generate it.

cargo add oliviadb

Java 17 or later; Maven:

<dependency>
  <groupId>com.olivia-db</groupId>
  <artifactId>oliviadb-client</artifactId>
  <version>0.1.2</version>
</dependency>

Java trusts a server certificate through a trust store: keytool -importcert -noprompt -alias oliviadb -file server.pem -keystore oliviadb.jks -storepass changeit, then run with -Djavax.net.ssl.trustStore=oliviadb.jks -Djavax.net.ssl.trustStorePassword=changeit (the native connection below takes the CA file directly).

Node.js 18 or later:

npm install @olivia-db/client

Python 3.10 or later:

pip install oliviadb

Generate the typed code

From the schema the server serves (step 4), for the profile the application holds a key of (app); generate again whenever the schema changes:

oliviadb schema client bank.olv --lang rust   --profile app --out bank-app   # a crate
oliviadb schema client bank.olv --lang java   --profile app --out src        # package com.oliviadb.gen.bank.app
oliviadb schema client bank.olv --lang ts     --profile app --out .          # bank_app.ts
oliviadb schema client bank.olv --lang python --profile app --out .          # package bank_app
ls bank-app/src src/com/oliviadb/gen/bank/app bank_app.ts bank_app

Each language needs only its own line. What is generated and how to add it to a project: typed clients.

The program

Each program reads the settings of step 2 (. ./oliviadb.env) and checks what it reads back: 100.00 opened, 12.50 posted, 87.50 left.

use bank_app::*;
use oliviadb::native::{Native, TlsOptions};

fn main() -> oliviadb::Result<()> {
    let env = |k: &str| std::env::var(k).unwrap();
    let addr = format!("{}:{}", env("OLIVIADB_NATIVE_HOST"), env("OLIVIADB_NATIVE_PORT"));
    let tls = TlsOptions { ca_file: Some(env("OLIVIADB_CA_FILE").into()), server_name: None };
    let db = Db::new(Native::connect_tls(&addr, &tls, "token", &env("OLIVIADB_KEY"))?);

    // New nodes are typed, keys included.
    db.insert(Customer::all(), NewCustomer { id: "RS1".into(), name: "Grace Hopper".into(), branch: "B1".into(), email: "".into() }).send()?;
    let eur = Customer::key("RS1").account("RS1-EUR");
    let opened = NewAccount { number: "RS1-EUR".into(), currency: "EUR".into(), balance: "100.00".parse()?, status: AccountStatus::Open };
    db.insert(Customer::key("RS1").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: one read, decoded from rows into models.
    let c = db.get(Customer::key("RS1")).tree().send()?;
    for a in &c.accounts {
        println!("{} account {} balance {}", c.name, a.number, a.balance);
        for e in &a.entries {
            println!("entry {} {}", e.amount, e.memo);
        }
    }
    assert_eq!(c.accounts[0].balance, "87.50".parse()?);
    Ok(())
}

Cargo.toml: bank-app = { path = "bank-app" } and the oliviadb crate; cargo run.

import com.oliviadb.client.NativeClient;
import com.oliviadb.gen.bank.app.*;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        var tls = new NativeClient.TlsOptions().caFile(Path.of(System.getenv("OLIVIADB_CA_FILE")));
        try (NativeClient nat = NativeClient.connectTls(System.getenv("OLIVIADB_NATIVE_HOST"),
                Integer.parseInt(System.getenv("OLIVIADB_NATIVE_PORT")), tls, "token", System.getenv("OLIVIADB_KEY"))) {
            var db = new BankDb(nat);

            // New nodes are typed, keys included.
            db.insert(Customer.all(), new Customer.New("JV1", "Grace Hopper", "B1", "")).send();
            var eur = Customer.key("JV1").account("JV1-EUR");
            db.insert(Customer.key("JV1").accounts(),
                    new Account.New("JV1-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: one read, decoded from rows into models.
            Customer c = db.get(Customer.key("JV1")).tree().send();
            for (Account a : c.accounts()) {
                System.out.println(c.name() + " account " + a.number() + " balance " + a.balance());
                for (Entry e : a.entries()) System.out.println("entry " + e.amount() + " " + e.memo());
            }
            BigDecimal balance = c.accounts().get(0).balance();
            if (!balance.equals(new BigDecimal("87.50"))) throw new IllegalStateException(balance.toString());
        }
    }
}

Compile the generated sources and Main.java with the client on the class path, then run Main.

import { Customer, Db, Decimal, Instant } from "./bank_app.ts";
import { NativeClient } from "@olivia-db/client/native";

const env = process.env;
const native = await NativeClient.connectTls(env.OLIVIADB_NATIVE_HOST!, Number(env.OLIVIADB_NATIVE_PORT), "token",
  env.OLIVIADB_KEY!, { caFile: env.OLIVIADB_CA_FILE });
const db = new Db(native);
try {
  // New nodes are typed, keys included.
  await db.insert(Customer.all(), { id: "JS1", name: "Grace Hopper", branch: "B1", email: "" });
  const eur = Customer.key("JS1").account("JS1-EUR");
  await db.insert(Customer.key("JS1").accounts(), {
    number: "JS1-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: one read, decoded from rows into models.
  const c = await db.get(Customer.key("JS1"), { tree: true });
  for (const a of c.accounts ?? []) {
    console.log(c.name, "account", a.number, "balance", a.balance.toString());
    for (const e of a.entries ?? []) console.log("entry", e.amount.toString(), e.memo);
  }
  const balance = (c.accounts ?? [])[0].balance.toString();
  if (balance !== "87.50") throw new Error(balance);
} finally {
  native.close();
}

node main.ts (Node.js runs the TypeScript as it is; tsc --strict checks it).

import datetime
import os
from decimal import Decimal

from bank_app import Account, AccountStatus, Customer, Db, Entry
from oliviadb.native import NativeClient

env = os.environ
with NativeClient.connect_tls(env["OLIVIADB_NATIVE_HOST"], int(env["OLIVIADB_NATIVE_PORT"]), "token",
                              env["OLIVIADB_KEY"], ca_file=env["OLIVIADB_CA_FILE"]) as native:
    db = Db(native)

    # New nodes are typed, keys included.
    db.insert(Customer.all(), Customer.New(id="PY1", name="Grace Hopper", branch="B1", email=""))
    eur = Customer.key("PY1").account("PY1-EUR")
    db.insert(Customer.key("PY1").accounts(),
              Account.New(number="PY1-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: one read, decoded from rows into models.
    c = db.get(Customer.key("PY1"), tree=True)
    for a in c.accounts:
        print(c.name, "account", a.number, "balance", a.balance)
        for e in a.entries:
            print("entry", e.amount, e.memo)
    assert c.accounts[0].balance == Decimal("87.50"), c.accounts[0].balance

python3 main.py (mypy --strict main.py checks the profile before it runs).

What to know about these calls:

  • Paths are typed: Customer.key("PY1").account("PY1-EUR") is the path Customer/PY1/Account/PY1-EUR; a key of several parts takes each part with its type (Entry: a timestamp and a number). An operation the profile does not grant does not exist on the path, so it does not compile.
  • add changes a number relative to its current value inside the transaction: no read first, no lost update.
  • A transaction writes within one customer (the profile's txn scope aggregate, the default). Moving money between two customers is two transactions; the banking guide shows how to make that safe.
  • Errors come back as the status and problem document of step 2; a 409 on an insert means the node exists, 403 that the profile does not grant the call.
  • Over HTTP the same code runs on the HTTP client: Db::new(Client) instead of the native connection. Lookups, listings page by page, checked updates, watches and untyped access: typed clients.

Without generated code

The clients also take paths and JSON directly: write, txn and get on the native connection, or the HTTP routes POST /v1/aggregates/..., POST /v1/txn and GET /v1/aggregates/...?tree=true (HTTP API by example). Use them for tools that work with any schema; the typed code is built on them.

With your coding agent

With the OliviaDB skills installed (step 0), the agent writes such code from one request:

Ask your agent

Using the oliviadb-develop skill, write a Java service method that posts an entry to an account of a customer and updates the balance in one OliviaDB transaction, and a test that runs it against a local server.

Next: the banking application guide, or the protocols to choose between HTTP and the native protocol.