# `TypeDB.Transaction`
[🔗](https://github.com/NoeticEcho/TypedbEx/blob/v0.11.1/typedb/lib/typedb/transaction.ex#L1)

Explicit transactions.

A transaction is a lightweight handle: an id plus the connection it belongs to.
It is a plain struct, not a process, so it can be passed between processes
freely — TypeDB tracks the transaction server-side.

## Bracketed usage (preferred)

`TypeDB.transaction/5` commits on success and rolls back on error or exception,
which is what you want almost always:

    TypeDB.transaction(conn, "social", :write, fn tx ->
      {:ok, _} = TypeDB.Transaction.query(tx, "insert $p isa person, has name 'Alice';")
      {:ok, _} = TypeDB.Transaction.query(tx, "insert $p isa person, has name 'Bob';")
    end)

## Manual usage

When the commit point is not lexically scoped:

    {:ok, tx} = TypeDB.Transaction.open(conn, "social", :write)
    {:ok, _answer} = TypeDB.Transaction.query(tx, "insert $p isa person;")
    :ok = TypeDB.Transaction.commit(tx)

Always pair `open/4` with `commit/1` or `close/1`. **`rollback/1` is not one
of them** — it discards the writes and leaves the transaction open, which is
what makes it useful for retrying inside one transaction and useless as
cleanup. An abandoned transaction holds server-side resources until its
`transaction_timeout_millis` elapses — and a `:schema` transaction holds the
exclusive schema lock for that whole time, blocking every other schema change.

## A transport failure ends the transaction

When a request to a transaction fails with `:timeout` or `:transport`, the
driver hangs up, and TypeDB discards the transaction along with the client
that vanished. So the failure is terminal for the whole transaction, not for
the one query:

  * nothing the transaction wrote is committed — the rollback already
    happened, server-side, without being asked for;
  * `commit/1` and `rollback/1` on it now return `TSV12` — *"no open
    transaction"* — with status `404`;
  * `close/1` still answers `:ok`, which is why it is the cleanup that belongs
    in an `after` block.

It is the hanging up that does this, not the slowness. Measured against
3.12.1: a query that fails at `timeout: 300` kills its transaction, and the
identical query given `timeout: 120_000` runs for 80 seconds, returns, and
commits normally. A transaction dying under load is a `:timeout` that is too
tight, and `transaction_timeout_millis` plus a per-call `:timeout` are the two
knobs for it.

Cleaning up is not instant either: the server finishes the abandoned query
before answering, so the `close/1` that follows a timeout blocked for around
3.6 s in the same measurement. Budget for it if it runs under a deadline.

`TypeDB.transaction/5` needs none of this — it reports the failure from the
body rather than from its own cleanup, so the caller sees the `:timeout`.

## Transaction types

  * `:read` — read-only, no commit needed. Multiple readers run concurrently.
  * `:write` — data changes. Concurrent writers are allowed; conflicting
    commits fail at commit time.
  * `:schema` — schema changes. Takes an exclusive, database-wide lock.

A query is rejected if it needs more than the transaction grants: a `define`
requires `:schema`, an `insert` requires `:write` or `:schema`.

# `t`

```elixir
@type t() :: %TypeDB.Transaction{
  conn: TypeDB.Connection.t(),
  database: String.t(),
  id: String.t(),
  type: type()
}
```

# `type`

```elixir
@type type() :: :read | :write | :schema
```

# `analyze`

```elixir
@spec analyze(t(), String.t(), keyword()) :: {:ok, map()} | {:error, TypeDB.Error.t()}
```

Asks TypeDB to analyse a query without running it.

Returns the decoded pipeline structure: the query's stages, variables, and
inferred types. Useful for query tooling and for checking that a query
type-checks against the current schema before shipping it.

> #### Not covered by this driver's versioning {: .warning}
>
> The map is TypeDB's, passed through verbatim with string keys, and it is
> the one return value in this driver that SemVer does not cover. It is a
> diagnostic surface: the endpoint is not in TypeDB's published HTTP API
> reference, and its shape tracks the server rather than this package, so a
> TypeDB upgrade can change it inside a patch release of the driver.
>
> Modelling it as a struct would be a promise the driver cannot keep — every
> server change would either break the struct or be silently dropped by it.
> Match defensively, and do not build anything load-bearing on the shape.

# `analyze!`

```elixir
@spec analyze!(t(), String.t(), keyword()) :: map()
```

Analyses a query, raising on failure.

# `close`

```elixir
@spec close(
  t(),
  keyword()
) :: :ok | {:error, TypeDB.Error.t()}
```

Closes the transaction, discarding uncommitted writes.

Closing is idempotent and never fails on an already-closed transaction — it is
safe to call in an `after` block.

Takes the same `:timeout` and `:deadline` options as `commit/2`.

# `close!`

```elixir
@spec close!(
  t(),
  keyword()
) :: :ok
```

Closes the transaction, raising on failure.

# `commit`

```elixir
@spec commit(
  t(),
  keyword()
) :: :ok | {:error, TypeDB.Error.t()}
```

Commits the transaction.

The transaction is finished afterwards, whether or not the commit succeeded —
a failed commit does not leave anything to roll back.

Committing a `:read` transaction is an error; use `close/1`.

## Options

  * `:timeout` — overrides the connection's `:timeout` for this call. A commit
    is usually the most expensive request a transaction makes, since it is
    where the server does the work, so it is the one most likely to want more
    time than an ordinary query.
  * `:deadline` — overrides the connection's `:deadline`: a wall-clock budget
    in ms for this call including any retries.

# `commit!`

```elixir
@spec commit!(
  t(),
  keyword()
) :: :ok
```

Commits the transaction, raising on failure.

# `open`

```elixir
@spec open(TypeDB.Connection.t(), String.t(), type(), keyword()) ::
  {:ok, t()} | {:error, TypeDB.Error.t()}
```

Opens a transaction on `database`.

## Options

Transaction options (see `TypeDB.Options`) plus `:timeout` and `:deadline` for
the HTTP request itself. Any other key raises `ArgumentError`.

    TypeDB.Transaction.open(conn, "social", :schema,
      schema_lock_acquire_timeout_millis: 30_000
    )

# `open!`

```elixir
@spec open!(TypeDB.Connection.t(), String.t(), type(), keyword()) :: t()
```

Opens a transaction, raising on failure.

# `query`

```elixir
@spec query(t(), String.t(), keyword()) ::
  {:ok, TypeDB.Answer.t()} | {:error, TypeDB.Error.t()}
```

Runs a TypeQL query inside the transaction.

Nothing is persisted until `commit/1`.

## Options

Query options (see `TypeDB.Options`) plus:

  * `:timeout` — overrides the connection timeout for this request. Long
    analytical reads usually want this. It bounds one attempt; `:deadline`
    bounds the call.
  * `:deadline` — overrides the connection's `:deadline`: a wall-clock budget
    in ms for this call including any retries.
  * `:given_rows` — input rows for the query's `given` stage. See
    "Parameterised queries" below.

## Examples

    TypeDB.Transaction.query(tx, "match $p isa person; select $p;",
      include_instance_types: false,
      answer_count_limit: 1_000
    )

## Parameterised queries

Never interpolate user input into a query string — TypeQL injection is as real
as SQL injection. Use TypeDB's `given` stage (3.12+) instead: the values travel
beside the query rather than inside it, so they can never be parsed as TypeQL.

    TypeDB.Transaction.query(tx, """
      given $n: string;
      insert $p isa person, has name == $n;
    """, given_rows: [%{"n" => "Alice"}, %{"n" => "Bob"}])

The rest of the pipeline runs once per row, which also makes this the fast way
to write many rows: one request and one query compilation instead of N. For
2,000 rows against a local server, `bench/given.exs` measures 101ms this way,
1541ms for a single request whose query text carries 2,000 `insert`
statements, and 8830ms for 2,000 requests.

Declare every input variable in the `given` stage, and mark optional columns
with `?`:

    given $name: string, $age: integer?;

A query with a `given` stage requires rows, and rows require a `given` stage.
Each row is a map of variable name to a plain Elixir term or a concept from an
earlier answer; `nil` leaves an optional column unbound. `TypeDB.Given` lists
the accepted types and explains why the driver encodes them rather than
forwarding raw JSON.

**A request body has a size limit on TypeDB 3.12, and does not on 3.13.** It
is a limit on bytes rather than rows and there is no server-side flag for it.
Bisected to the KiB, through this driver, against both servers:

| | 3.12.1 | 3.13.0-rc0 |
| --- | --- | --- |
| largest body accepted | 2047 KiB | **512 MiB, the largest tried** |
| smallest body refused | 2048 KiB — `400 HSR2` | none found |

On 3.12 a body a little over the line is `400 HSR2` and a body far over it
presents as a `:transport` failure instead — see
[Recipes](recipes.html#load-a-lot-of-rows). On 3.13.0-rc0 neither happens: the
same sweep that stops at 2 MiB on 3.12.1 was accepted at 1, 2, 4, 8, 16, 32,
64, 128, 256 and 512 MiB.

**Batch large loads by payload size anyway.** The advice is unchanged and is
now about portability rather than about a limit: code written against 3.13
that sends a 4 MiB body fails on every 3.12 server it ever meets, and the
failure arrives as a `:transport` timeout rather than as anything that names
the cause. 512 MiB is also not a size a request should be — it is where the
measurement stopped, not a recommendation.

## Raises

A `:given_rows` value the driver cannot encode raises `TypeDB.Error` with kind
`:encode`. That happens while the request is being built, so there is no
request to return an error for. An option this function does not accept raises
`ArgumentError`, for the same reason and one step earlier. Everything the
*server* rejects comes back as `{:error, %TypeDB.Error{}}` as usual.

# `query!`

```elixir
@spec query!(t(), String.t(), keyword()) :: TypeDB.Answer.t()
```

Runs a query, raising on failure.

# `rollback`

```elixir
@spec rollback(
  t(),
  keyword()
) :: :ok | {:error, TypeDB.Error.t()}
```

Discards everything written so far, leaving the transaction open.

The transaction returns to the state it had when opened, so you can retry
inside the same transaction rather than reopening one.

Takes the same `:timeout` and `:deadline` options as `commit/2`.

# `rollback!`

```elixir
@spec rollback!(
  t(),
  keyword()
) :: :ok
```

Discards everything written so far, raising on failure.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
