Skip to content

The SQL projection

The replica's hierarchical databases as read-only SQL tables, served over the PostgreSQL wire protocol, so that psql, JDBC (pgJDBC), ODBC and BI tools connect without a driver of OliviaDB's own. The hierarchy stays the system of record; SQL is a window for reading and reports. Open crate oliviadb-sql (open/crates/oliviadb-sql), server oliviadb-sql-server, or oliviadb-ha-node --sql on the nodes of an HA pair.

Where it runs

  • On the standby of an HA pair, and on a single node. A primary that has a standby refuses SQL sessions and statements (SQLSTATE 57P03, naming the standby): reports do not load the node that takes the writes. After a failover the promoted node serves alone until a standby is back; then the projection moves to the new standby. The decision is taken at the start of a session and before every statement (oliviadb_sql::server::Serving; in oliviadb-ha-node from Node::has_standby: the standby acknowledged within t_fail).
  • Each node reads its own copy of the data (layer-1 data is applied by each node from the same change stream, docs/ha.md).
  • Every session knows the version it reads and how fresh it is: SHOW oliviadb.version (the newest version), SHOW oliviadb.position (the source time of the newest change applied), SHOW oliviadb.lag_ms (now minus that source time), SHOW oliviadb.role (standby, primary, single). The startup parameters report in_hot_standby and default_transaction_read_only = on.

Tables

SQL hierarchy
schema database (DBD name, lower case)
table segment type
view <segment>_<field>_<values> one REDEFINES variant of the segment
column field of the segment's layout (lower case, - as _)
primary key the concatenated key: the sequence fields of the ancestors and the segment, plus an occurrence number where twins are not told apart by a unique key
foreign key the ancestors' key columns, referencing the parent table
  • Key columns are named <ancestor>_<field> for ancestors and by the field's name for the segment itself; occurrence numbers are <ancestor>_seq and seq (1, 2, ... among twins under the same parent with the same key, in hierarchic order). A segment without a sequence field has seq only.
  • Columns come from the layout (spec/schema.md 4): the registry's default layout of the segment when the store has one (copybooks registered from the semantic catalog, Java classes), else the semantic catalog's layout, else the DBD's FIELD statements.
  • Every version is decoded by its writer's layout (the layout number in its meta header), else by the default valid at its version; values are matched to columns by field name, and a field the writer's layout lacks reads as NULL. As-of reads therefore show history in the layout it was written with.
  • Types: character fields varchar(n); packed decimal numeric(2n-1, scale); zoned decimal numeric(n, scale); binary numeric(5|10|20, scale); other bytes bytea; occurrence numbers integer. Bytes that are not valid for a numeric field's encoding read as NULL; in a character field as the text x: followed by the bytes in hexadecimal.
  • REDEFINES: the base table holds the fields every variant has. Each variant is a view with the base columns and that variant's fields, holding the rows of that variant: the variant the writer recorded in the version (Java @When, native clients), else the variant whose discriminator values the row's discriminator field has.
  • Without ORDER BY rows come in hierarchic sequence (key order of the source).

Rights

A user's profile is an agent PSB (docs/agent-data.md): PSBGEN source with SENSEG, SENFLD and PROCOPT, plus OliviaDB's ROWS, MASK and PDATA statements. It is compiled by the same code as for agents (oliviadb_dli_view::agentpsb::AgentPsb::compile), from the first version:

  • a segment outside SENSEG is not a table of the session (not in any catalog either);
  • a field outside SENFLD (or every field but the key under PROCOPT=K) is not a column;
  • ROWS predicates filter rows (with the user's attributes, $USER.<attr>);
  • MASK (REDACT, TOKEN, PARTIAL) and PDATA columns are text and show the masked value; filters compare the masked value, and a masked key column never steers a key lookup, so a hidden value cannot be found by querying for it. TOKEN uses the installation's key (key_file): tokens equal those the agent API shows.

Masks and predicates are applied by the engine to every row before anything else sees it (filters, joins, aggregates, results).

Reading as of a version

SELECT ... AS OF VERSION 7392811893096448;
SELECT ... AS OF SOURCE 15781339290763182080;      -- a source time (store clock)
SELECT ... AS OF TIMESTAMP '2026-01-05 10:00:00';  -- UTC, converted to a source time
SET oliviadb.as_of = '2026-01-05 10:00:00';             -- for the session; RESET oliviadb.as_of

A source time selects the version that holds the database as the change stream left it at that time (the newest unit applied at or before it); a time before the first unit is refused (22023). A version beyond what the node holds is refused.

Plans, limits

  • A table is read by key when equalities fix its leading key columns (from the root down; a join on the foreign key is a key lookup per outer row), else by a scan of the segment type, which skips other subtrees.
  • EXPLAIN shows the plan: Index Scan using <table>_pkey with the key condition, or Seq Scan, the filters, the row predicate, the version read, and the limits.
  • Limits come from the user's profile in the configuration: scan_rows (rows a statement's scans without a key may read; default 100 000; "unlimited") and timeout_ms (default 30 000), lowered by SET statement_timeout. Exceeding them ends the statement with 54000 or 57014. A client's cancel request ends it too.
  • The system's lock is held for at most 512 entries at a time: a long report never holds the change stream applier back, and reads one consistent version (MVCC).

SQL

Read-only: INSERT, UPDATE, DELETE, DDL, SELECT ... FOR UPDATE, READ WRITE transactions are refused with 25006. Supported:

  • SELECT [DISTINCT] ... FROM t [alias] {[INNER|LEFT|CROSS] JOIN t ON ...} | , t with derived tables (SELECT ...) alias, WHERE, GROUP BY, HAVING, ORDER BY (columns, aliases, positions), LIMIT/OFFSET/FETCH FIRST, AS OF;
  • expressions: arithmetic in exact decimals, ||, comparisons, AND OR NOT, IS NULL, IN (list), IN (SELECT ...), EXISTS, scalar subqueries (correlated), LIKE/ILIKE, ~ and !~ regular expressions (literals, ., classes, groups, * + ?, anchors), BETWEEN, CASE, casts, row_number() OVER (PARTITION BY ... ORDER BY ...);
  • functions: count sum min max avg string_agg bool_and bool_or, upper lower trim length substr concat coalesce nullif abs round, version() current_database() current_schema() current_user, oliviadb_version() oliviadb_role() oliviadb_position();
  • SET, RESET, SHOW, BEGIN/COMMIT/ROLLBACK (each statement reads the newest version, or the session's oliviadb.as_of), EXPLAIN.

Not supported (refused by name): UNION/INTERSECT/EXCEPT, RIGHT/FULL joins, window functions other than row_number, floating-point literals, COPY, the function call protocol. Texts compare by code points (no collations).

Catalogs

information_schema (schemata, tables, views, columns, table_constraints, key_column_usage, referential_constraints) and the parts of pg_catalog clients read (pg_namespace, pg_class, pg_attribute, pg_type, pg_index, pg_constraint, pg_settings, and empty pg_description, pg_trigger, pg_policy, ...), with format_type, pg_get_indexdef, pg_get_constraintdef, ::regclass. All show only what the session's profile lets it see. A few client queries that use constructs outside the subset are answered from the projection's own catalogs (psql's publications and triggers of a table, pgJDBC's primary and foreign key metadata; oliviadb_sql::pgcat).

Tested clients: psql 16 (\dt, \dn, \d table with keys and referencing tables, queries, TLS) and pgJDBC 42.7.15 (statements, prepared statements with server-side preparation and binary transfer, ResultSetMetaData, DatabaseMetaData.getTables, getColumns, getPrimaryKeys, getImportedKeys).

Protocol and authentication

PostgreSQL frontend/backend protocol 3.0: simple and extended query (named statements and portals, Execute with a row limit, binary results for integers, numeric, text and bytea, binary parameters for integers and text), cancel requests. Authentication is SCRAM-SHA-256 (no channel binding); an unknown user goes through the same exchange and fails like a wrong password. TLS when the configuration names a certificate.

Configuration

{
  "listen": "0.0.0.0:5432",
  "replica": "replica", "library": "library",
  "databases": ["CUSTDB"],
  "load": [{"dbd": "CUSTDB", "unload": "CUSTUNLD.rdw"}],
  "apply": ["capture.log"],
  "tls": {"cert": "server.pem", "key": "server.key"},
  "key_file": "master.key",
  "users": [
    {"name": "teller", "password": "SCRAM-SHA-256$4096:...", "psb": "teller.psb",
     "attrs": {"branch": "NORTH"}, "scan_rows": 100000, "timeout_ms": 30000}
  ]
}

oliviadb-sql-server --scram PASSWORD prints a verifier for password ("plain:..." is accepted for tests). load fills a replica directory that does not exist yet from unloaded databases ("format": the build's first unload reader when absent; the enterprise build reads IMS HD Reorganization Unload data sets, format hd, and the other formats of oliviadb-dli-migrate); apply applies change logs (units already applied are skipped): a file name is read by the build's first change log reader, {"log": FILE, "format": NAME} by the reader of that format. The open build has no such readers and refuses load and apply; the enterprise build (oliviadb-ha-node --sql) reads IMS logs with data capture records (format ims-data-capture, crate oliviadb-dli-capture). Relative paths are relative to the file. OLIVIADB_SQL_LOG=1 logs statements and errors on standard error.

Evidence

Expected rows come from outside OliviaDB: segments built by the tests themselves (code page 037, packed decimal) and the rows PostgreSQL returns for the same tables and statements; psql (tests/psql.rs: a local psql named by OLIVIADB_PSQL, psql in an existing container named by OLIVIADB_PSQL_CONTAINER, else a throwaway postgres:16 container; without any the tests report themselves skipped), pgJDBC (dli/oliviadb-sql-jdbc-test of the oliviadb-java repository), and the HA pair across kill -9 of the primary (oliviadb-enterprise/crates/oliviadb-ha/tests/e2e_sql.rs). Rights tests: a column outside SENFLD is absent, a masked column masked, a segment outside SENSEG absent, rows outside ROWS absent, writes refused.

Open

  • Indexes beyond the primary key: secondary indexes (XDFLD) are not used by plans yet; asynchronous indexes with a freshness mark are not built.
  • Range conditions on key columns are filters on a scan (character keys sort by their encoded bytes, SQL texts by code points); 88-level meanings are not columns.
  • Logical databases and logical relationships, GSAM, HSAM: not served (as for agents).
  • ODBC and BI tools beyond psql and pgJDBC are untested; Arrow Flight for extracts.
  • The change stream is applied at startup (apply); a node that applies a live stream embeds oliviadb_sql::server::Server next to its applier.