Transactions and consistency
Know which calls are atomic, group several writes into one transaction with rpc(), and keep two users from overwriting each other's changes.
Aurabase runs every request in its own PostgreSQL transaction and commits it when the request ends. There is no way to open a transaction in one SDK or REST call and commit it in another. To make several writes succeed or fail together, put them in one request: a database function called with rpc(), or one SQL request from a server.
Prerequisites#
-
A linked project:
aura link <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema. -
AURABASE_URLin the environment, for the SDK examples.
The examples create the table qd_tx_accounts and the functions qd_tx_transfer and qd_tx_isolation, then remove them. They run with the service_role key, on a server.
create table qd_tx_accounts (
id int primary key,
owner text not null,
balance int not null check (balance >= 0),
version int not null default 1
);
insert into qd_tx_accounts values (1, 'ada', 100, 1), (2, 'bob', 50, 1); ℹ No results (0 rows).One request, one transaction#
| Call | Transaction | If one part fails |
|---|---|---|
insert([row1, row2, …]), POST with an array | One | No row is written. |
update(…) or delete() with a filter | One | No row changes. |
rpc('f', …) | One, around the whole function | Everything the function did is rolled back. |
aura db raw "stmt1; stmt2", db.sql() | One, around all statements | Every statement is rolled back. |
| Two SDK calls in a row | Two | The first stays committed. |
| A direct PostgreSQL connection | Yours: begin … commit | You decide. |
Transaction control is refused through aura db raw and db.sql(): begin, commit, rollback, savepoint and set transaction answer Operation not allowed in a raw query: transaction control (BEGIN / COMMIT / ROLLBACK / SAVEPOINT / SET TRANSACTION). The query already runs inside a transaction managed by the service. Multi-request transactions from the SDK are not available.
Several writes in one function#
A transfer debits one account and credits another: both or neither. In a PL/pgSQL function, the first error stops the function and rolls back every write it made:
create function qd_tx_transfer(p_from int, p_to int, p_amount int) returns void
language plpgsql as $$
begin
update qd_tx_accounts set balance = balance + p_amount, version = version + 1 where id = p_to;
update qd_tx_accounts set balance = balance - p_amount, version = version + 1 where id = p_from;
if not found then
raise exception 'account % not found', p_from;
end if;
end
$$;
grant execute on function qd_tx_transfer(int, int, int) to aura_authenticated; ℹ No results (0 rows).import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const balances = async () =>
(await admin.from('qd_tx_accounts').select('owner, balance').order('id')).data!.map((r) => `${r.owner}=${r.balance}`).join(' ')
const ok = await admin.rpc('qd_tx_transfer', { p_from: 1, p_to: 2, p_amount: 30 })
console.log('transfer 30:', ok.error, '|', await balances())
const overdraw = await admin.rpc('qd_tx_transfer', { p_from: 1, p_to: 2, p_amount: 500 })
console.log('transfer 500:', overdraw.error?.code, '|', await balances())
const ghost = await admin.rpc('qd_tx_transfer', { p_from: 9, p_to: 2, p_amount: 1 })
console.log('from account 9:', ghost.error?.message, '|', await balances())transfer 30: null | ada=70 bob=80
transfer 500: CHECK_VIOLATION | ada=70 bob=80
from account 9: account 9 not found | ada=70 bob=80In the two failed calls, Bob's account was credited first, then the function failed: the credit was rolled back with the rest. The function is security invoker: a signed-in user who calls it needs policies that let it update both rows. When the rule is "anyone may transfer from their own account", check the owner inside the function with auth.uid(), or use a security definer function as described in Database functions.
Several statements from a server#
From a server with the service_role key, one aura db raw (or db.sql()) request runs all its statements in one transaction:
aura db raw "update qd_tx_accounts set balance = balance + 10 where id = 2; update qd_tx_accounts set balance = balance - 500 where id = 1" || true
aura db raw "select owner, balance from qd_tx_accounts order by id"Error: [400] BAD_REQUEST: Invalid request: new row for relation "qd_tx_accounts" violates check constraint "qd_tx_accounts_balance_check"
balance │ owner
────────┼──────
70 │ ada
80 │ bob
ℹ 2 row(s).The first update was rolled back with the second. --dry-run (dryRun: true in db.sql()) runs the statements and rolls the transaction back, to try a change before applying it. set local works inside such a request (set local statement_timeout = '5s'); a set without local is accepted but can outlive the request on the pooled connection: always write set local. See Run SQL.
Isolation level#
Requests run at PostgreSQL's default level, read committed: each statement sees the rows committed before it started.
create function qd_tx_isolation() returns text language sql stable as $$ select current_setting('transaction_isolation') $$; ℹ No results (0 rows).import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
console.log((await admin.rpc('qd_tx_isolation')).data)read committedset transaction isolation level serializable is refused through aura db raw, and a function cannot change the level of the transaction that calls it. If you need repeatable read or serializable, use a direct connection (Connect to your database), or design the write so that read committed is enough: a single update … where … statement, a check constraint, a unique key, or the version check below.
Concurrent updates#
Two users load the same row, change it, and save. Without care, the second save silently overwrites the first. A version column detects it: each update requires the version it read and increments it. A stale update matches no row:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const { data: row } = await admin.from('qd_tx_accounts').select('balance, version').eq('id', 1).single()
const first = await admin.from('qd_tx_accounts').update({ balance: row!.balance + 5, version: row!.version + 1 })
.eq('id', 1).eq('version', row!.version).select('balance, version')
console.log('first save:', first.data)
const second = await admin.from('qd_tx_accounts').update({ balance: row!.balance - 5, version: row!.version + 1 })
.eq('id', 1).eq('version', row!.version).select('balance, version')
console.log('second save, stale version:', second.data, second.meta?.rows_affected)first save: [ { balance: 75, version: 3 } ]
second save, stale version: [] 0When rows_affected is 0, reload the row and ask the user, or retry with the new values. An updated_at timestamp works the same way as a version number.
Row locks#
Inside one request, select … for update locks the selected rows until the transaction ends, so a concurrent request that wants to change them waits. It is useful inside a function that reads a row, decides, then writes it:
create function qd_tx_withdraw(p_id int, p_amount int) returns int
language plpgsql as $$
declare
current int;
begin
select balance into current from qd_tx_accounts where id = p_id for update;
if current < p_amount then
raise exception 'insufficient funds';
end if;
update qd_tx_accounts set balance = balance - p_amount where id = p_id;
return current - p_amount;
end
$$;(Excerpt, not replayed: the same pattern as qd_tx_transfer.) A lock taken by an SDK select() would end with its request, so locks only make sense inside a function or a single SQL request. A request blocked on a lock keeps waiting; the gateway stops waiting for it after 30 seconds by default and answers 408, while PostgreSQL may still run the statement.
Result#
aura db raw "select owner, balance, version from qd_tx_accounts order by id" balance │ owner │ version
────────┼───────┼────────
75 │ ada │ 3
80 │ bob │ 2
ℹ 2 row(s).Common errors#
| Message | Cause | Fix |
|---|---|---|
Operation not allowed in a raw query: transaction control (BEGIN / COMMIT / ROLLBACK / SAVEPOINT / SET TRANSACTION) … | begin, commit, savepoint or set transaction in aura db raw or db.sql(). | Remove them: the request is already one transaction. |
400 CHECK_VIOLATION … from rpc() | A statement of the function broke a constraint; the whole function was rolled back. | Check the input, or test the condition first and raise a clear message. |
400 POSTGREST_ERROR <message> from rpc() | The function raised an exception; nothing it did was kept. | Handle it in the app. |
data: [], meta.rows_affected: 0 on a versioned update | Another request changed the row first. | Reload and retry, or ask the user. |
408 after about 30 seconds | A request waited too long, for example on a lock. | Keep transactions short; take locks in a consistent order. |
Clean up#
aura db raw "drop function if exists qd_tx_transfer(int, int, int); drop function if exists qd_tx_isolation()"
aura db raw "drop table qd_tx_accounts" ℹ No results (0 rows).
ℹ No results (0 rows).