Packages

Embedded Relate graph databases for Elixir/OTP applications

Current section

Files

Jump to
relatex docs api elixir spec.md
Raw

docs/api/elixir/spec.md

# Relatex API

## Store lifecycle

`Relatex.start_link(opts \\ [])` starts a linked GenServer with one database and one connection in the default session namespace. 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. |
| `: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 and transaction batches per owner. A transaction uses one slot regardless of batch size. |
| `: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 competing live owner still 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.

## 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 store 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 work submitted before the stop and then closes the connection. 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.

## 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. For temporal, spatial and vector parameters, bind their components and construct the value 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: [...]}}` |

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.

## 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)