Consulte seu banco de dados com o JavaScript SDK
Os fluxos diários de aura.db, as regras que recusam chamadas inseguras e como proteger uma tabela com segurança em nível de linha.
aura.from('todos') is the form used throughout this documentation: it is a shortcut for aura.db.from('todos'), the same call. Every call returns { data, error } and never throws unless you ask it to (see Errors and debugging). The examples run with the service_role key on a server; an app uses the anon key and a signed-in user, and row level security decides what it sees (Protect a table). Each section links to the page that covers its topic in depth.
Read rows#
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('todos')
.select('title, done')
.eq('done', false)
.order('title')
.limit(20)
console.log(data, error)[
{ title: 'Add a row level security policy', done: false },
{ title: 'Create a table', done: false },
{ title: 'Invite a teammate', done: false }
] nullFilters chain: eq, neq, gt, gte, lt, lte, like, ilike, in, is, and the others listed in Filter operators. Related tables nest in select() through foreign keys: Join tables and nest rows. More on reads: Read rows.
Insert, update and delete#
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const alice = '00000000-0000-4000-8000-0000000000a1'
// Insert one row, or an array of rows
const inserted = await admin.from('todos').insert({ user_id: alice, title: 'Write the docs' }).select('title, done')
console.log('insert:', inserted.data, inserted.error)
// Update and delete need a filter
const updated = await admin.from('todos').update({ done: true }).eq('title', 'Write the docs').select('title, done')
console.log('update:', updated.data, updated.error)
const deleted = await admin.from('todos').delete().eq('title', 'Write the docs').select('title')
console.log('delete:', deleted.data, deleted.error)insert: [ { title: 'Write the docs', done: false } ] null
update: [ { title: 'Write the docs', done: true } ] null
delete: [ { title: 'Write the docs' } ] nullName the columns you want back with .select('a, b'). insert() and update() currently return the written rows even without .select() (the gateway answers every POST and PATCH with the full rows); delete() returns nothing unless you chain .select(). An update that matched no row returns [] and says why in meta.hint; so does a delete with .select(), while a delete without it returns null.
Rules that protect you from mistakes:
- A batch insert needs the same keys in every row. Rows with different keys return
400 INVALID_BODYwithAll object keys must match. Fill the missing keys withnull. update()anddelete()without a filter are refused by the client with the error codeUNFILTERED_MUTATION, before any request is sent. The REST API has no such guard. To change every row on purpose, run SQL from a server.upsert()does not update existing rows today. On a key that already exists it answers409 DUPLICATE_KEYinstead of updating the row (it inserts new keys normally). Useinsert … on conflict … do updatein SQL or in a function called withrpc(): Insert and upsert rows.
More: Insert and upsert rows, Update and delete rows.
One row, many rows, counts#
import { createClient } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
// Exactly one row: an error if there are none or several
const one = await admin.from('profiles').select('username').eq('username', 'alice').single()
console.log('single:', one.data, one.error)
const none = await admin.from('profiles').select('username').eq('username', 'nobody').single()
console.log('single, no row:', none.error?.status, none.error?.code)
// Zero or one row: data is null when nothing matches
const maybe = await admin.from('profiles').select('username').eq('username', 'nobody').maybeSingle()
console.log('maybeSingle:', maybe.data, maybe.error)
// Rows and their total
const page = await admin.from('todos').select('title', { count: 'exact' }).order('title').range(0, 1)
console.log('page:', page.data!.length, 'of', page.count)
// The total only, no rows
const { count } = await admin.from('todos').select('*', { count: 'exact', head: true })
console.log('count:', count)single: { username: 'alice' } null
single, no row: 406 PGRST116
maybeSingle: null null
page: 2 of 4
count: 4count: 'exact' counts every matching row. 'planned' and 'estimated' are faster on very large tables and approximate. Pages, the 1,000-row cap and keyset pagination: Paginate and count rows.
Protect a table#
Tables created through Aurabase (db.sql(), migrations, Studio, or the table API) automatically get ENABLE and FORCE ROW LEVEL SECURITY (unless you explicitly include DISABLE ROW LEVEL SECURITY in your DDL batch). With no policies yet, anon and authenticated callers see []. Tables created via a direct Postgres connection need enable row level security explicitly. Add the policies you need:
create policy todos_own_read on todos
for select to aura_authenticated
using (auth.uid() = owner);The canonical database roles are aura_anon, aura_authenticated and aura_service_role (group aliases anon, authenticated, service_role also map to them on managed clusters). auth.uid() is NULL for the public key and a user id for a signed-in user. See Row-Level Security.
A service_role key bypasses RLS by design: keep it on your server.
SQL functions and rpc#
Create a function from a server, then call it from anywhere with rpc():
await admin.db.createFunction({
name: 'add',
args: [
{ name: 'a', data_type: 'int', mode: 'IN' },
{ name: 'b', data_type: 'int', mode: 'IN' },
],
returns: 'int',
language: 'sql',
body: 'SELECT a + b',
grant_execute_to: ['anon', 'authenticated'],
})const { data } = await aura.rpc('add', { a: 1, b: 2 }) // → 3grant_execute_tois required to call it. Without it, only theservice_rolekey can execute the function. Another role that is not listed gets403 permission denied for function. Bothauthenticatedandaura_authenticatedare accepted. This also holds for functions you create withdb.sql()or a migration on projects created after this change (the defaultEXECUTEprivilege ofPUBLICis revoked): addgrant execute on function hello(text) to aura_authenticated;yourself.- A new function is callable after a few seconds. Until the API reloads its schema,
rpc()returns404 Could not find the function. - Functions via SQL (
db.sql()):CREATE FUNCTION/CREATE OR REPLACE FUNCTIONis allowed inSECURITY INVOKERmode (default);SECURITY DEFINERis rejected on/rawand must be created throughcreateFunction(POST /v1/db/{project_id}/functions) or CLI/migrations with explicitgrant_execute_to.
Arguments, results, filters on returned rows and errors: Call functions with rpc().
Run SQL from a server#
import { createAdminClient } from '@aurabase/aurabase-js'
const admin = createAdminClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
await admin.db.sql(`
create table if not exists todos (
id uuid primary key default gen_random_uuid(),
title text not null,
done boolean not null default false,
owner uuid,
created_at timestamptz not null default now()
)
`)db.sql() needs a service_role key. It refuses a DELETE without a WHERE, and it does not read system catalogs such as pg_class or pg_roles. To list your tables, use admin.db.schema(). One db.sql() call runs in one transaction: Transactions and consistency.
Errors and debugging#
error is an AuraError with status (the HTTP status, 0 when the SDK refused the call before sending it), code (COLUMN_NOT_FOUND, DUPLICATE_KEY, PGRST116…), message, hint when the server proposes a fix, and details, the full error body of the response (with upstream_code, the PostgreSQL or PostgREST code, and request_id). throwOnError() throws the same object instead of returning it, and isAuraError() recognizes it. buildQueryString() shows the query a builder would send, without sending it:
import { createClient, isAuraError } from '@aurabase/aurabase-js'
const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const { error } = await admin.from('todos').select('titel')
console.log(error?.status, error?.code, error?.message)
console.log('hint:', error?.hint)
console.log('upstream:', (error?.details as { error?: { upstream_code?: string } })?.error?.upstream_code)
try {
await admin.from('todos').select('titel').throwOnError()
} catch (e) {
console.log('thrown:', isAuraError(e) && e.code)
}
const query = admin.from('todos').select('title').eq('done', false).order('title').limit(2)
console.log(query.buildQueryString())400 COLUMN_NOT_FOUND column todos.titel does not exist
hint: Perhaps you meant to reference the column "todos.title".
upstream: 42703
thrown: COLUMN_NOT_FOUND
select=title&done=eq.false&order=title.asc&limit=2A builder you forget to await sends nothing: logging it prints not executed — did you forget await? with the query it would send. Branch on error.code in your application; the codes of each kind of request are listed in the Common errors section of each page linked above.
Pagination, row cap and exact numbers
- A read returns at most 1,000 rows — the default and the hard ceiling, whatever
limit()orrange()you ask for.meta.has_moreistruewhen more rows match; ask forcount: 'exact'to also getmeta.total. - Page through a big table with keyset pagination, which costs the same on the millionth page:
aura.from('events').select('id,label').limit(1000).after('id', lastId)(it is.order('id').gt('id', lastId))..cursor()is MongoDB-only;offsetgets slower the deeper you go. - Numbers beyond JavaScript's 2^53. A
bigintabove 9,007,199,254,740,991 loses its last digits when parsed as a JS number: create the client with{ parseBigIntAsString: true }to receive those values as strings. Anumericis returned as a JSON number when it is exactly representable, and as an exact decimal string otherwise (long values such as12345678901234567890.123456789). count: 'planned'and'estimated'are only estimates. They come from PostgreSQL's statistics, which are empty on a table that was just loaded (a 60-row table can report 430). Usecount: 'exact'when the number matters. A count is lost on inserts and updates for now (count: null): count with a separate read.- A
vectorcolumn comes back as a string such as"[0.1,0.2,0.3]": parse it withJSON.parseto get anumber[]. - A view reads with your privileges. Views you create (SQL, migration) get
security_invoker = true, so the policies of the underlying tables apply to the reader. Never writewith (security_invoker = false): such a view ignores those policies, and the anon key could read and even write the table through it (Views). db.sql()retries a429after theRetry-Afterdelay (a refused request never ran)./rawis limited per project; for bulk loads use the typedinsert()with an array.