Writing
create, update, upsert and delete, with typed conflicts and optimistic concurrency.
| Method | Returns |
|---|---|
create(data, args?) | The row |
create(data[], args?) | The rows |
update(key, patch, args?) | The row, or not_found |
update({ where }, patch, args?) | { count }, or the rows with returning: true |
upsert(data, { onConflict }) | The row |
upsert(data[], { onConflict }) | The rows |
delete(key) | Nothing, or not_found |
delete({ where }, args?) | { count }, or the rows with returning: true |
A key is the primary key value, or an object of the columns for a composite
key. { where } is a filter: the write applies to every row it matches.
Inserts are typed by the generated Insert shape: required columns are
required, columns with defaults are optional, and generated identity
columns are rejected.
Choosing what comes back
Writes return the full row by default. Narrow it with select, or skip it
with returning: false:
await db.customers.create(data, { select: ["id"] });
await db.auditLog.create(entry, { returning: false });RLS and returning
Returning rows needs a SELECT policy that matches the new row. If users may
insert rows they cannot read, use returning: false. Otherwise the insert
fails with forbidden after it passed your INSERT policy.
update and delete by filter return { count }. Pass returning: true to
get the written rows instead, narrowed with select and include as in reads.
create and upsert with an array work the other way round: they return the
rows, and returning: false gives { count }. The result type follows the
returning value you pass:
| Call | returning: true | returning: false | Not passed | boolean variable |
|---|---|---|---|---|
create(row), update(key) | The row | null | The row | The row or null |
create(rows), upsert(rows) | The rows | { count } | The rows | The rows or { count } |
update({ where }), delete({ where }) | The rows | { count } | { count } | The rows or { count } |
const sent = await db.invoices
.update(
{ where: { status: "draft", dueAt: { lte: today } } },
{ status: "sent" },
{ returning: true, select: ["id", "number"] },
)
.orThrow();A write by filter needs a where that filters rows: an empty where, or one
whose conditions are all undefined, returns invalid_request instead of
writing every row. Pass allowAll: true to update when you mean the whole
table; for delete, filter on a column that every row matches. An update
by key whose patch sets no columns changes nothing: it reads the current row with the same where, select and
include and returns it (null with returning: false), or not_found when
no row matches. An update({ where }) with an empty patch returns
{ count: 0 }, or
the matching rows with returning: true. This lets you build a patch from
optional fields without a guard. When an extension such as
updated-at is installed, an empty patch still
runs as a write, because the plugin may fill in a column; a plugin that
leaves it empty gets invalid_request.
On a table with a trash column, a
delete({ where }) with returning: true keeps RETURNING on the update it becomes, so it needs
a SELECT policy that still shows the soft-deleted row.
Limiting bulk writes
maxAffected caps how many rows an update or delete by filter may change.
When the where matches more, the write fails with max_affected (400) and
changes nothing:
const result = await db.sessions.delete(
{ where: { userId } },
{ maxAffected: 50 },
);
if (result.error?.kind === "max_affected") {
// the filter matched more rows than expected
}Over PostgREST this sends Prefer: handling=strict, max-affected=50, which
needs PostgREST 13 or later. On an older server, set
createSupabase(schema, { postgrestVersion: "12.2" }) and a call with
maxAffected fails with invalid_request before any request. The
Postgres executor and
PowerSync count the rows inside the statement or
transaction and roll the write back. The requireMaxAffected guard in
guards() and the require-max-affected
lint rule make the cap mandatory.
Counting writes
update and delete by filter count the written rows exactly. Pass
count: "planned" or count: "estimated" to use the Postgres planner's
estimate over PostgREST instead; create and upsert with an array and
returning: false take the same option. The SQL executors always return the
statement's own row count.
Conditional updates
update matches the row by its key. Add where for anything else the row
must meet, such as its tenant or a status it may only leave once. A row with
this key that doesn't match comes back as not_found, in one request:
const result = await db.invitations.update(
id,
{ acceptedAt: now },
{ where: { organizationId, status: { in: ["pending", "resent"] } } },
);Upserts
onConflict takes a unique constraint name from the generated UniqueKeys,
'primaryKey', or a column list:
await db.customers.upsert(data, {
onConflict: "customers_organization_id_kvk_key",
});
await db.tags.upsert(rows, {
onConflict: ["organizationId", "name"],
ignoreDuplicates: true,
});upsert with an array sends the rows sorted by the conflict columns, with nulls last.
Two requests that upsert overlapping rows then lock them in the same order and
wait for each other instead of deadlocking. The returned rows follow that
order, not the order you passed.
Bulk inserts
create and upsert with an array send one request over PostgREST however many
rows you pass. Rows can leave out different columns: a missing column gets
its default. Pass defaultToNull: true to write null for missing columns
instead, as supabase-js does by default. On the Postgres executor, one statement
takes at most 65,535 bind parameters (one per column value), so a larger
insert runs as several statements in one transaction: either every row is
written or none is. Clients without transaction (a custom SqlClient) run
the statements one after the other, and an error leaves the earlier ones
written.
Optimistic concurrency
Pass the values you read in expect. If the row changed in the meantime, the
update fails with stale (412) instead of overwriting it. expect takes the
same operators as where; plain values mean equality:
const result = await db.customers.update(
id,
{ name },
{ expect: { updatedAt } },
);
if (result.error?.kind === "stale") {
// reload and ask the user
}Telling stale from not_found takes a second request that checks whether
the row exists. Use where for conditions that are not about a concurrent
change, such as a tenant guard, so a miss is not_found without the probe.
Conflicts
Unique violations come back as conflict with the constraint and columns, so
forms can point at the right field:
const result = await db.tags.create({ organizationId, name });
if (
result.error?.kind === "conflict" &&
result.error.columns?.includes("name")
) {
form.setError("name", { message: "Tag already exists" });
}Last updated on