# Relatex API

## Store lifecycle

`Relatex.start_link(opts \\ [])` starts a linked GenServer with a database and its default connection. It accepts these options.

| Option | Meaning |
| --- | --- |
| `:database` | UTF-8 store URI, default `":memory:"`. The engine also treats an empty string as an in-memory store. A nonempty directory path or a local `.rl` file persists data. |
| `:read_only` | Boolean, default `false`. A read-only owner opens an existing durable store at its committed snapshot. On `":memory:"` it opens an empty graph with the same write fence. |
| `:namespace` | Initial connection namespace as a binary. Omitting it or passing `nil` uses the engine default, `"neo4j"`. |
| `:statement_timeout` | Per-statement engine budget in milliseconds, default 5000. Zero clears the deadline. Time waiting for another caller is outside the budget. |
| `:max_in_flight` | Positive integer or `:infinity` (default). Counts outstanding queries, transactions, checkpoints and configuration changes for this connection. A transaction uses one slot for its full duration. |
| `:name` | Optional GenServer registration name, accepted anywhere a server reference can be passed. |

An invalid `:max_in_flight` raises `ArgumentError`. The owner supports `{Relatex, opts}` as an OTP child. A failed engine open returns `{:error, %Relatex.Error{}}`. `Relatex.stop(db)` synchronously disconnects, closes the database and returns `:ok` on success. A normal stop ends a transient child. After an abnormal owner exit, a supervisor restarting the child with the same store URI waits for in-flight native work and can reopen the store. A second writer receives the engine’s lock error. Reopening the same persistent store reads its committed data. A native library runs with the operating-system privileges and crash domain of its BEAM node.

### Independent live sessions

`Relatex.connect(db, opts)` returns `{:ok, session_pid}` on success. Call it on the database owner to acquire an additional native connection to the **same** open graph, including `":memory:"`. A session has its own namespace (default `"neo4j"`), statement timeout (5000 ms), and admission limit (`:infinity`). These values can be set independently using `:namespace`, `:statement_timeout`, and `:max_in_flight`. The optional `:name` uses normal GenServer registration. A duplicate name returns the OTP startup error. Store path and read-only access mode belong to the database. Sessions opened from a read-only snapshot share that snapshot and its write fence.

Both database and session references accept queries, transactions, checkpoint, namespace/timeout setters, admission inspection and stop. `checkpoint/1` always targets the underlying database. `stop(session)` closes only that connection. `stop(db)` closes all its sessions and the database. If the database process dies, existing sessions belong to the old instance and must be reacquired from the replacement. If a session process dies, the database and its other sessions remain available. The database supervises the session on its own BEAM node, so its lifetime is independent of the process that called `connect/2`.

Each connection serializes its own work. Separate connections can execute concurrently and see committed changes on the live graph according to Relate's transaction isolation. Each finite admission limit applies to that connection. The application controls the total session count. Opening a directory with `start_link(read_only: true, database: path)` creates a separate frozen snapshot, described below.

### Snapshots and checkpoints

A directory reader can open while its writer runs. It sees the checkpoint plus committed WAL records present at open. Subsequent commits become visible after closing and reopening the reader. A `.rl` file allows multiple readers together or one exclusive writer. A missing read-only store returns an error and leaves the path absent. Relate enforces the read-only fence on statements, explicit transactions and checkpoints.

`Relatex.checkpoint(db)` returns `:ok` after the engine finishes its checkpoint, or `{:error, %Relatex.Error{}}`. Normal durable commits already write to the WAL. A checkpoint lets a host choose when to materialize a snapshot. It uses one admission slot and runs between operations.

### Connection settings

`Relatex.set_namespace(db, namespace)` and `Relatex.set_statement_timeout(db, milliseconds)` return `:ok` or `{:error, %Relatex.Error{}}`. The changes take effect on subsequent statements for **every caller** of this owner. Use a statement-local `USE` clause when one caller needs a different namespace. An unknown namespace returns an engine error and preserves the current setting. A timeout of zero clears the engine deadline. Each setter uses one admission slot and a batch runs through commit or rollback before a setter can take effect. Restarting restores the startup options.

## Admission under contention

For local callers using the current client, a finite owner reserves a slot before the caller sends statement text, parameters, or an entire batch. Reservations, queued operations and the operation executing on the connection share the same limit. A full owner returns `{:error, %Relatex.Error{code: "Relatex.Overloaded", stage: "admission", gql_status: nil, retryable: true}}`. Relate has received no statement from that request. The application decides when to retry. Each connection admits work independently.

The connection processes submitted operations in the order the owner forwards them. Concurrent callers have no ordering guarantee across processes. Each transaction retains exclusive use of the connection through commit or rollback. If a caller exits before submitting an acquired reservation, the owner reclaims its slot. Once submitted, the operation holds its slot until completion even when its caller exits. Explicit `stop/1` drains submitted queries and batches and closes the connection. Shutdown can abort an open interactive transaction while the callback is between statements. A caller racing the shutdown can receive a binding error while the owner is closing or an exit after the owner stops. Graceful OTP shutdown also drains submitted work. A supervisor can forcibly terminate a child that exceeds its shutdown budget.

The limit counts operations. Bounded mode relays materialized results through the admission owner. Page large results in Cypher to bound transferred rows and memory. Statement size, result size and mailbox scheduling delay are separate concerns. Current local callers keep the payload until admission. Calls across BEAM nodes use the original request format for compatibility with Relatex 0.1.0 peers. The finite owner applies the same capacity check to incoming operations using this format, after their payload has reached its mailbox. The BEAM still schedules small admission messages, and the engine deadline begins when a statement executes. With the unbounded default, the native connection remains directly owned by one process.

`Relatex.admission_stats(db)` reads the owner without reserving a slot. A finite owner can answer while the executor is busy. It returns `{:ok, %{max_in_flight: limit, in_flight: count, rejected: count}}`. The first count includes reservations and submitted operations until the owner receives their replies. The second counts capacity refusals since this owner started. Restarting resets both. A closing finite owner can return a binding error. An unbounded owner answers in mailbox order with `%{max_in_flight: :infinity, in_flight: :untracked, rejected: 0}` inside the same success tuple.

On a remote owner running 0.1.x or 0.2.x, `admission_stats/1`, `checkpoint/1`, the two setters, `connect/2` and interactive transactions return a binding error identifying the unsupported operation. Queries and batches continue to use their published message shapes. Typed input parameters require a 0.3 or newer owner.

## Statements and errors

`Relatex.query(db, cypher, params \\ %{})` returns `{:ok, %Relatex.Result{}}` or `{:error, %Relatex.Error{}}`. Parameters are string-keyed maps. Bind values with Cypher placeholders such as `$session`. Accepted inputs are nil, booleans, signed int64, finite floats, the special float tuples below, UTF-8 binaries, proper lists, and nested binary-keyed maps. Parameter keys may contain up to 4096 bytes and must be free of NUL. Strings retain embedded NUL. Containers have a 64-level nesting limit. Temporal, duration, point and vector parameters accept the tagged forms below, including inside lists and maps. Each tag takes the exact atom-keyed component map returned by the reader. Bind graph entities by an application key or element ID and match them in Cypher.

`columns` holds the ordered column names. Each list in `rows` follows that order. `namespace` is the resolved graph name and `query_type` is the engine classification (`"r"`, `"w"`, `"rw"`, or `"s"`). Result values belong to the BEAM after the query returns. This API materializes the complete result. Use Cypher projection, aggregation or pagination when retrieving many rows.

| Cypher value | BEAM representation |
| --- | --- |
| Null, boolean, integer, string, list, map | `nil`, boolean, integer, UTF-8 binary, list, map with binary keys |
| Float | Elixir float or `{:float, :nan \| :infinity \| :negative_infinity}` |
| Node | `{:node, %{id: ..., element_id: ..., labels: [...], properties: %{...}}}` |
| Relationship | `{:relationship, fields}` with `:id`, `:element_id`, `:type`, `:properties`, `:start_id`, `:end_id`, `:start_element_id`, `:end_element_id` |
| Path | `{:path, %{elements: [...]}}` in traversal order |
| Date, time, datetime | A tagged tuple with `:date`, `:time`, `:local_time`, `:datetime`, or `:local_datetime` and a component map. Date fields are year, month and day. Time fields are hour, minute, second and nanosecond. Zoned variants also include offset_seconds and zone. |
| Duration | `{:duration, %{months: ..., days: ..., seconds: ..., nanoseconds: ...}}` |
| Point | `{:point, %{srid: ..., coordinates: [...]}}` |
| Vector | `{:vector, %{dtype: ..., coordinates: [...]}}` |

Use an empty binary for the zone of a fixed-offset time or datetime. A named-zone `:time` uses the region’s offset at the current instant and reads back with an empty zone. For a `:datetime` with a nonempty IANA zone, Relate resolves the offset from the region and wall time, even when the caller supplies a different `offset_seconds`. During an autumn clock change, rebinding a zoned datetime can move it to the earlier occurrence of the same wall time. To preserve a specific occurrence **and** its region, bind explicit-offset text such as `"2024-11-03T01:30:00-05:00[America/New_York]"` and use `datetime($text)`. To preserve just the instant and fixed offset of a returned `{:datetime, fields}`, bind `{:datetime, %{fields | zone: ""}}`.

The temporal `nanosecond` and duration `nanoseconds` fields preserve native precision. Point coordinates are two or three floats. Vector dtypes are binaries. `INTEGER8`, `INTEGER16`, `INTEGER32` and `INTEGER` take integer coordinates. `FLOAT16`, `BFLOAT16`, `FLOAT32` and `FLOAT` take floats. Relate checks coordinate range and exact representation for the declared dtype. For example, `1.5` is exact in `FLOAT32`. Pass full-precision doubles as `FLOAT` or round to the intended precision in the application before binding. Invalid parameters fail before the statement executes.

### Statement metadata

| Result field | Meaning |
| --- | --- |
| `bookmark` | Engine-issued `"relate:<n>"` for an auto-commit mutation. A read, an empty write pipeline, EXPLAIN and a statement inside an explicit transaction return `nil`. |
| `stats` | Map with all 11 engine mutation counters, including zeros. Keys such as `"nodes_created"` and `"relationships_created"` are binaries. |
| `notifications` | Engine warning maps with binary keys, including code and remedy. An ordinary successful query returns `[]`. |
| `plan` | Structured `relate.plan/v1` map for EXPLAIN and PROFILE, otherwise `nil`. |
| `elapsed_ms`, `parse_ms`, `plan_ms`, `execute_ms` | Engine wall-clock milliseconds as floats. Elapsed includes parse, planning, execution and the gaps between phases. Admission wait and BEAM result conversion are outside this measurement. |

The fields above are `nil` when the reply comes from a pre-0.3 remote owner. On those peers the explicit batch commit bookmark remains available in the transaction return tuple.

Engine errors expose `code`, `gql_status`, `stage`, `retryable`, and `message`. Both statement failures and C ABI call failures use this shape. Binding errors use code `"Relatex.BindingError"`, stage `"binding"`, nil GQL status and `retryable: false`. If the engine succeeds and an Elixir result cannot be decoded, the code is `"Relatex.DecodeError"`, stage `"decode"`, and `retryable` is false. An auto-commit write can already be durable. A batch rolls back on this error. A statement exceeding its native timeout returns an engine error. The connection can serve subsequent queries.

## Transactions

`Relatex.transaction(db, [{cypher, params}, ...])` runs the ordered batch on one connection. Other admitted operations wait for the batch to finish. Success returns `{:ok, [result, ...], bookmark_or_nil}`. A write bookmark is an engine-issued string. A transaction that commits no writes can return nil. A failed statement rolls back the batch and returns its error. A failed commit returns its original engine error. The owner rolls back a pending transaction or confirms that the connection can start and roll back a fresh transaction. Once recovery succeeds, callers can use the same owner again. If recovery fails, the owner stops and closes the connection.

### Interactive transactions

Pass a one-argument function to `Relatex.transaction(connection, fun)`, or use its callback spelling `Relatex.with_transaction(connection, fun)`, to make decisions between statements. The function runs once in the calling process. Its argument is a transaction handle for the selected connection. Call `Relatex.query(tx, cypher, params)` to see intermediate results, including this transaction’s own writes. Other calls on the same connection cannot interleave. One admission slot covers all statements, the time spent in the callback, and its commit or rollback. Each statement has its own engine deadline.

| Callback outcome | Transaction result |
| --- | --- |
| Callback returns a value and all statements succeed | Commits and returns `{:ok, value, bookmark_or_nil}`. |
| Callback calls `Relatex.rollback(tx, reason)` | Rolls back and returns `{:error, reason}` if all preceding queries succeeded. |
| A scoped query fails during binding, execution or decoding | The first scoped query error prevents commit and takes precedence over a later explicit rollback reason. If the callback otherwise completes normally, the transaction returns that error. |
| Callback raises, throws or exits | Rolls back and propagates the failure to the caller. |
| Caller dies or its BEAM node disconnects before submitting commit | The owner rolls back and releases the connection. |
| Commit fails | Returns the engine error, including its retryability. No successful commit bookmark is issued. |

Use `tx` only from the callback process and only within that invocation. Use the supplied handle for work on that connection. Calling the same connection directly from its callback or nesting a transaction on it returns a binding error. Returning an ordinary value, including an error tuple, is a successful callback return. Use `rollback/2` to abort for an application-level reason. A new transaction on another session has an independent commit boundary. Keep external side effects outside a callback you might retry. A caller that loses contact after submitting a commit may need to reconcile its outcome before replaying it.

## Build compatibility

The compiler selects a checksum-pinned Relate v1.5.0 SDK and verifies C ABI version 2 when the NIF loads. Normal builds require Elixir, OTP headers, make and a C compiler. Release downloads also use curl, tar and sha256sum or shasum. Set `RELATEX_FFI_DIR` for an offline or upstream-checkout build with compatible native artifacts. CI and development toolchain versions live in the repository's `.tool-versions`. [Upstream C contract](https://github.com/relatedb/relate/blob/v1.5.0/docs/api/c/spec.md)
