Insert and upsert rows
Write new rows from your application or your server, know what each door returns and refuses, and get an insert-or-update that works today.
An insert adds rows to a table. The SDK (insert()), the REST API (POST /v1/db/{table}) and SQL (insert into …) all end up as the same PostgreSQL statement, checked by the same constraints and row level security policies. This page inserts rows through each door, then shows how to insert or update in one call.
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_URL(the URL of your project) andAURABASE_ANON_KEYin the environment, for the SDK andcurlexamples.
The examples create the table qd_insert_items and the function qd_insert_upsert_item, then remove them. Writes with the service_role key run on a server; a browser or mobile app uses the anon key and a signed-in user.
A table to write to#
create table qd_insert_items (
id uuid primary key default gen_random_uuid(),
sku text not null unique,
name text not null,
qty int not null default 0 check (qty >= 0),
updated_at timestamptz not null default now()
); ℹ No results (0 rows).Row level security is turned on for every table created through Aurabase, and this one has no policy yet: only the service_role key can read or write it. The examples below use that key, on a server.
Insert one row#
The same row, through the three doors. With the SDK, insert() takes an object; columns you leave out take their default (id, qty, updated_at here):
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const { data, error } = await admin.from('qd_insert_items').insert({ sku: 'LAMP-1', name: 'Desk lamp', qty: 4 }).select('sku, name, qty')
console.log(data, error)[ { sku: 'LAMP-1', name: 'Desk lamp', qty: 4 } ] nullOver REST, POST /v1/db/{table} with a JSON body. A single inserted row comes back as an object in data, with the status 201:
curl -s -X POST "$AURABASE_URL/v1/db/qd_insert_items?select=sku,name,qty" \
-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
-d '{"sku": "DESK-1", "name": "Standing desk", "qty": 1}' \
-w ' HTTP %{http_code}\n'{"data":{"sku":"DESK-1","name":"Standing desk","qty":1},"meta":{}} HTTP 201In SQL, returning gives back the columns you name:
aura db raw "insert into qd_insert_items (sku, name, qty) values ('CHAIR-1', 'Office chair', 2) returning sku, qty" qty │ sku
─────┼────────
2 │ CHAIR-1
ℹ 1 row(s).The REST path also accepts the project id, POST /v1/db/{project_id}/{table}: the SDK uses the shorter form, where the project comes from the URL of the project.
Insert many rows#
Pass an array to insert several rows in one request. The request is one transaction: if one row is refused, none is written.
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const ok = await admin.from('qd_insert_items').insert([
{ sku: 'PEN-1', name: 'Blue pen', qty: 50 },
{ sku: 'PEN-2', name: 'Red pen', qty: 30 },
]).select('sku')
console.log('two rows:', ok.data, ok.error)
const refused = await admin.from('qd_insert_items').insert([
{ sku: 'PEN-3', name: 'Green pen', qty: 10 },
{ sku: 'LAMP-1', name: 'Same sku again', qty: 1 },
])
console.log('one duplicate:', refused.error?.status, refused.error?.code)
const pen3 = await admin.from('qd_insert_items').select('sku').eq('sku', 'PEN-3')
console.log('PEN-3 written:', pen3.data)
const keys = await admin.from('qd_insert_items').insert([
{ sku: 'PEN-4', name: 'Black pen', qty: 5 },
{ sku: 'PEN-5', name: 'Grey pen' },
])
console.log('different keys:', keys.error?.status, keys.error?.code, keys.error?.message)two rows: [ { sku: 'PEN-1' }, { sku: 'PEN-2' } ] null
one duplicate: 409 DUPLICATE_KEY
PEN-3 written: []
different keys: 400 INVALID_BODY All object keys must matchEvery object of a batch needs the same keys: fill a missing value with null or with the value the default would give. To load thousands of rows, send them in batches of a few thousand per request; a request body is limited to 50 MB by default. This inserts 10,000 rows in five requests:
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const rows = Array.from({ length: 10_000 }, (_, i) => ({ sku: `BULK-${i}`, name: `Bulk item ${i}`, qty: i % 7 }))
for (let i = 0; i < rows.length; i += 2_000) {
const { error } = await admin.from('qd_insert_items').insert(rows.slice(i, i + 2_000)).select('sku')
if (error) throw error
}
const { count } = await admin.from('qd_insert_items').select('*', { count: 'exact', head: true }).like('sku', 'BULK-%')
console.log(count)10000.select('sku') keeps each response small: without it, every inserted row comes back with all its columns (see the next section). For a one-time load of millions of rows, a direct connection with COPY is faster: Connect to your database.
What comes back#
| Door | Response |
|---|---|
SDK insert() | data is an array of the inserted rows, with every column, even without .select(). .select('a, b') keeps only those columns. |
REST POST /v1/db/{table} | 201, {"data": …, "meta": {}}: an object for one row, an array for several. ?select=a,b keeps only those columns. |
SQL insert … returning … | The columns named by returning; no returning, no rows. |
insert() without .select() sends Prefer: return=minimal, but the gateway currently replaces it with return=representation on every POST: the rows come back anyway. For the same reason count is lost on an insert (insert(…).select().count('exact') gives count: null). Name the columns you need to keep responses small.
Insert as a signed-in user#
From an app, the user is signed in and the policies of the table decide. todos of the example schema has the policy todos_owner: with check (auth.uid() = user_id). A user can insert its own todos, and nobody else's:
import { createClient } from '@aurabase/aurabase-js'
const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const email = `insert-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
const signUp = await aura.auth.signUp({ email, password })
if (signUp.error) throw signUp.error
const { data: session, error } = await aura.auth.signInWithPassword({ email, password })
if (error) throw error
const me = session!.user.id
const mine = await aura.from('todos').insert({ user_id: me, title: 'Insert as a user' }).select('title, done')
console.log('own row:', mine.data, mine.error)
const other = await aura.from('todos').insert({ user_id: '00000000-0000-4000-8000-0000000000a1', title: 'For alice' })
console.log('other user:', other.error?.status, other.error?.code, other.error?.message)
const missing = await aura.from('todos').insert({ title: 'No owner' })
console.log('no user_id:', missing.error?.status, missing.error?.code)own row: [ { title: 'Insert as a user', done: false } ] null
other user: 403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "todos"
no user_id: 403 INSUFFICIENT_PRIVILEGEuser_id has no default in the example schema, so the app sends it: without it, the row is null-owned and the policy check refuses it before the not null constraint is checked. To fill it on the server instead, give the column default auth.uid(). The sign-up works because email confirmation is turned off on the test project; a project requires it by default.
Upsert: current state#
upsert() of the SDK, and POST /v1/db/{table}?on_conflict=<column> of the REST API, should update a row when its key already exists. They currently do not: on an existing key they answer 409 DUPLICATE_KEY, whatever Prefer header you send. Measured with SDK 0.7.5:
| Call | Key | Result |
|---|---|---|
upsert({ id, … }) | primary key exists | 409 DUPLICATE_KEY on …_pkey |
upsert({ sku, … }, { onConflict: 'sku' }) | unique column, value exists | 409 DUPLICATE_KEY on …_sku_key |
upsert({ sku, … }, { onConflict: 'sku' }) | new value | inserted, like insert() |
POST ?on_conflict=sku with Prefer: resolution=merge-duplicates or resolution=ignore-duplicates | value exists | 409 DUPLICATE_KEY |
upsert({ id, … }) on a generated always as identity key | any | 400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id" |
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const existing = await admin.from('qd_insert_items').upsert({ sku: 'LAMP-1', name: 'Desk lamp', qty: 9 }, { onConflict: 'sku' })
console.log('existing sku:', existing.error?.status, existing.error?.code, existing.error?.message)
const fresh = await admin.from('qd_insert_items').upsert({ sku: 'LAMP-2', name: 'Floor lamp', qty: 1 }, { onConflict: 'sku' }).select('sku, qty')
console.log('new sku:', fresh.data, fresh.error)existing sku: 409 DUPLICATE_KEY duplicate key value violates unique constraint "qd_insert_items_sku_key"
new sku: [ { sku: 'LAMP-2', qty: 1 } ] nullThe SDK has no ignoreDuplicates option. Until upsert() merges, use one of the two forms below.
Insert or update with on conflict#
In SQL, insert … on conflict (<unique columns>) do update inserts the row or updates the existing one, in one statement. excluded is the row you tried to insert:
insert into qd_insert_items (sku, name, qty)
values ('LAMP-1', 'Desk lamp', 9), ('LAMP-3', 'Wall lamp', 3)
on conflict (sku) do update
set qty = excluded.qty, name = excluded.name, updated_at = now()
returning sku, qty; qty │ sku
─────┼───────
9 │ LAMP-1
3 │ LAMP-3
ℹ 2 row(s).on conflict (sku) do nothing keeps the existing row instead, the equivalent of "ignore duplicates". The conflict target must be a primary key or a unique constraint (or unique index) on exactly those columns.
To offer the same from the SDK, put the statement in a function and call it with rpc(). The function runs as security invoker, so the caller needs the rights and policies to insert and update the table; here the server calls it with the service_role key:
create function qd_insert_upsert_item(p_sku text, p_name text, p_qty int)
returns setof qd_insert_items
language sql
as $$
insert into qd_insert_items (sku, name, qty)
values (p_sku, p_name, p_qty)
on conflict (sku) do update
set name = excluded.name, qty = excluded.qty, updated_at = now()
returning *;
$$; ℹ No results (0 rows).import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const first = await admin.rpc('qd_insert_upsert_item', { p_sku: 'LAMP-1', p_name: 'Desk lamp', p_qty: 12 }).select('sku, qty')
console.log(first.data, first.error)
const second = await admin.rpc('qd_insert_upsert_item', { p_sku: 'LAMP-4', p_name: 'Clip lamp', p_qty: 6 }).select('sku, qty')
console.log(second.data, second.error)[ { sku: 'LAMP-1', qty: 12 } ] null
[ { sku: 'LAMP-4', qty: 6 } ] nullA function created with aura db raw gets no EXECUTE for the public roles: to let signed-in users call it, add grant execute on function qd_insert_upsert_item(text, text, int) to aura_authenticated and the insert and update policies they need on the table. See Call functions with rpc() and Database functions.
Result#
aura db raw "select sku, name, qty from qd_insert_items where sku not like 'BULK-%' order by sku" name │ qty │ sku
──────────────┼──────┼────────
Office chair │ 2 │ CHAIR-1
Standing desk │ 1 │ DESK-1
Desk lamp │ 12 │ LAMP-1
Floor lamp │ 1 │ LAMP-2
Wall lamp │ 3 │ LAMP-3
Clip lamp │ 6 │ LAMP-4
Blue pen │ 50 │ PEN-1
Red pen │ 30 │ PEN-2
ℹ 8 row(s).Common errors#
| Message | Cause | Fix |
|---|---|---|
409 DUPLICATE_KEY duplicate key value violates unique constraint "…" | The key or a unique value already exists, including through upsert(). | Change the value, update the row, or use insert … on conflict … do update. |
403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "…" | No insert policy lets this role write this row (with check is false). | Write rows the user owns, or add a policy. The error hint proposes one. |
400 NOT_NULL_VIOLATION null value in column "…" … violates not-null constraint | A required column is missing. | Send it, or give the column a default (default auth.uid() for an owner column). |
400 INVALID_BODY All object keys must match | The objects of a batch do not have the same keys. | Give every object the same keys, with null where needed. |
400 COLUMN_NOT_FOUND … | A key of the body is not a column of the table. | Fix the name; regenerate your types after a schema change. |
400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id" | A value sent to a generated always as identity column. | Leave the column out. |
400 CHECK_VIOLATION new row for relation "…" violates check constraint "…" | A value outside a check rule. | Send a valid value. |
404 TABLE_NOT_FOUND … | The table does not exist, or was just created and the API has not reloaded its schema yet. | Check the name; retry after a second. |
Clean up#
The test user created by the user example stays in the project; delete it with aura auth users delete <user-id>.
aura db raw "drop function if exists qd_insert_upsert_item(text, text, int)"
aura db raw "drop table qd_insert_items"
aura db raw "delete from todos where title = 'Insert as a user'" ℹ No results (0 rows).
ℹ No results (0 rows).
ℹ No results (0 rows).