# Aurabase — Full Technical Documentation & Sovereign Architecture Reference > Aurabase is an EU-sovereign, unified, agent-native Backend-as-a-Service (BaaS) platform built in Rust. > Sovereign European alternative to Firebase and Supabase. > Hosted entirely within the European Union (Hetzner Cloud Germany eu-central zone and Scaleway Paris). GDPR-native by design and protected against US CLOUD Act extraterritoriality. > Website: https://aurabase.dev | Console: https://aurabase.dev | Documentation: https://aurabase.dev/en/docs --- ## 0. Quickstart (from the documentation, tested) ### Prerequisites We assume that `Node.js ≥ 20` is installed and a POSIX terminal is within range. No local database is required: Aurabase provisions a dedicated Postgres database for each project. Are you coming from Supabase or Firebase? Most concepts are transposable. See the [migration guide](/docs/guides/migration-supabase). ### Installing the SDK The official SDK exposes a typed client for CRUD, auth, realtime and storage. It works the same way in Next.js, React, Node, Bun or Deno. ```bash # Recommended pnpm add @aurabase/aurabase-js ``` ```bash npm install @aurabase/aurabase-js ``` ```bash yarn add @aurabase/aurabase-js ``` ```bash bun add @aurabase/aurabase-js ``` The package name includes the `@aurabase/` scope. The package `aurabase-js` without a scope is not maintained by Aurabase: do not install it. The SDK directly includes `@aurabase/aurabase-js/ssr` (`createServerClient`) export for Next.js (App Router, Server Actions, Middleware), Remix, Nuxt and SvelteKit with automatic session cookie management and anti-truncation chunking. ### Create a project Create a project from the Studio. When it becomes active, the Studio shows a **Copy your keys now** panel with a ready-to-use `.env.local` (copy it or download it): the `service_role` key appears there **once**, only its hash is kept afterwards. **Settings › Connection** later shows the project URL and the public anon key; if you lost the `service_role` key, regenerate it there (the previous one is revoked). `NEXT_PUBLIC_AURABASE_URL` and `NEXT_PUBLIC_AURABASE_ANON_KEY` can be published on the client side; `AURABASE_SERVICE_ROLE_KEY` stays strictly on the server side. ```bash NEXT_PUBLIC_AURABASE_URL=https://.aurabase.dev NEXT_PUBLIC_AURABASE_ANON_KEY=aura_anon_… AURABASE_SERVICE_ROLE_KEY=aura_sk_… ``` | Schema | Access | Contains | | --- | --- | --- | | `project_{uuid}` | You | Your application tables | | `project_{uuid}_auth` | System | `users`, `sessions`, `oauth_accounts`, `mfa` | | `project_{uuid}_storage` | System | `buckets`, `objects`, `rls_policies` | | `project_{uuid}_platform` | System | `functions`, `jobs`, `cron_jobs`, `api_keys` | The whole path also works from the CLI (see [CLI](/docs/cli) for the installation): `aura projects create` waits until the project is ready and prints the URL and the keys once. ```bash aura login aura projects create todos-app --json > project.json # waits until the project is active aura link --project-id "$(jq -r .id project.json)" export NEXT_PUBLIC_AURABASE_URL="$(jq -r .url project.json)" export AURABASE_SERVICE_ROLE_KEY="$(jq -r .service_role_key project.json)" aura db raw "create table todos (id bigint generated always as identity primary key, title text not null, done boolean not null default false, user_id uuid not null default auth.uid(), created_at timestamptz not null default now())" aura db raw "create policy todos_own_read on todos for select to aura_authenticated using (auth.uid() = user_id)" aura db raw "create policy todos_own_insert on todos for insert to aura_authenticated with check (auth.uid() = user_id)" aura db table realtime todos on aura db raw "select count(*) from todos" --as authenticated --user # see what that user sees ``` **Never include `AURABASE_SERVICE_ROLE_KEY` in a client bundle.** It bypasses all RLS policies, and the API refuses it from a browser (`401 SECRET_KEY_IN_BROWSER`). Reserve it for server calls (route handlers, server actions, jobs). ### Create a table Open **Database** in the Studio, click **SQL Editor** (the link at the bottom of the tables panel) and run this script. Row-level security is enabled on every table: the first two policies let each signed-in user read and create their own rows, the third one is an **example** that lets visitors read the table so you can see your first rows without signing in. Policies target the `aura_authenticated` role (`aura_anon` for visitors). ```sql create table todos ( id bigint generated always as identity primary key, title text not null, done boolean not null default false, user_id uuid not null default auth.uid(), created_at timestamptz not null default now() ); create policy "todos_own_read" on todos for select to aura_authenticated using (auth.uid() = user_id); create policy "todos_own_insert" on todos for insert to aura_authenticated with check (auth.uid() = user_id); -- Example only: any visitor can read every todo. Drop it before production: -- drop policy "todos_public_read" on todos; create policy "todos_public_read" on todos for select to aura_anon using (true); ``` Then generate the TypeScript types of your schema (the command reads `.env.local`): ```bash npx @aurabase/gen --out lib/aurabase.types.ts ``` ### First call Create a reusable Aurabase client by reading keys from environment variables, then query your first table. The paths below are relative to the root of your app: if your project uses a `src/` directory, put `lib/`, `components/` and `app/` inside it, so that the `@/` import alias resolves. ```typescript import { createClient } from '@aurabase/aurabase-js' import type { Database } from './aurabase.types' export const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, ) ``` Then, in a route handler or a server component: ```typescript import { aura } from '@/lib/aurabase' export async function GET() { const { data, error } = await aura .from('todos') .select('id, title, done') .order('created_at', { ascending: false }) .limit(10) if (error) throw error return Response.json(data) } ``` This returns the rows of the table, including without a signed-in user, thanks to the example policy `todos_public_read`. Without it (once you dropped it, as you should before production) a visitor gets `[]`: the other policies only open rows to `aura_authenticated`, so sign a user in first with `aura.auth.signInWithPassword({ email, password })` (see [Ready-made sign-in pages for Next.js](/docs/auth/nextjs-sign-in)). Regenerate the `Database` types with `npx @aurabase/gen` after each schema change. To insert a first row, sign a user up and in, then insert. The `user_id` column defaults to `auth.uid()`: ```typescript import { aura } from '../lib/aurabase' async function main() { const email = 'you@example.com' const password = 'a-strong-password' await aura.auth.signUp({ email, password }) // an account that already exists is fine: we sign in next // Without a session the insert below would run as an anonymous visitor and be refused by RLS. const signIn = await aura.auth.signInWithPassword({ email, password }) if (signIn.error) throw signIn.error const { data, error } = await aura.from('todos').insert({ title: 'First todo' }).select() console.log(data, error) } main().catch((err) => { console.error(err) process.exit(1) }) ``` Run it with `tsx`, which resolves the extensionless import and reads `.env.local`: ```bash pnpm add -D tsx pnpm approve-builds # pnpm 10+: allow esbuild's install script, then run: pnpm exec tsx --env-file=.env.local scripts/first-row.ts ``` With npm 11 or later, `npx tsx` fails with « You installed esbuild for another platform » because esbuild's install script is blocked by default. Use pnpm as above, or skip `tsx` and run the script with Node's built-in type stripping (Node 22.6+) after writing the two imports with their extension (`'../lib/aurabase.ts'`, `'./aurabase.types.ts'`): `node --env-file=.env.local --experimental-strip-types scripts/first-row.ts`. A new project requires users to confirm their email before `signInWithPassword` succeeds: without it, `signUp` works and the sign-in returns `EMAIL_NOT_CONFIRMED`. On the local stack the confirmation email is captured by Mailpit: open it with `kubectl -n aurabase-dev port-forward svc/aurabase-mailpit 8025:8025`, then http://localhost:8025. To skip the confirmation while you develop, turn it off with `aura auth settings set email_confirmation_required=false` (or in Studio › Authentication › Configuration). Turn it back on before production: otherwise anyone can sign up with any address. The `service_role` key has no signed-in user, so `auth.uid()` is `NULL` and an insert that relies on the default fails with `NOT_NULL_VIOLATION`. From a server, pass `user_id` explicitly. ### Connect realtime Three auto-negotiated transports: WebSocket, SSE, NATS. Customer chooses the best one based on the network — no configuration necessary. Enable realtime on the table once, with the CLI: ```bash aura db table realtime todos on ``` or with the HTTP API, from a server (values from `.env.local`): ```bash curl -X PUT "$NEXT_PUBLIC_AURABASE_URL/v1/db/schema/tables/todos/realtime" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ -d '{"enabled": true}' ``` Then subscribe to changes. A signed-in user receives the rows that its RLS policies let it read, including when the channel was opened before sign-in (it is re-authenticated automatically); a refused subscription reports `CHANNEL_ERROR` with the reason. ```typescript 'use client' import { aura } from '@/lib/aurabase' import { useEffect } from 'react' export function LiveTodos() { useEffect(() => { const channel = aura.realtime .channel('todos') .on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (change) => console.log(change.eventType, change.new), ) .subscribe((status, err) => { // In development React StrictMode mounts, unmounts and re-mounts the component: // the first CLOSED comes from that clean-up and is expected. if (status === 'SUBSCRIBED') console.log('realtime connected') if (status === 'CHANNEL_ERROR') console.error('realtime refused:', err?.message) }) return () => { void channel.unsubscribe() } }, []) return null } ``` Subscriptions are multiplexed over a single TCP connection. Open as many as you need — zero additional network costs. --- ## 1. Overview, Sovereignty & Rust Architecture ### Why Aurabase? European engineering teams, startups, and enterprises need sovereign alternatives to US hyperscalers without sacrificing modern developer experience: - **100% EU Hosting & CLOUD Act Immunity**: Standard hosting operates on Hetzner (German jurisdiction) and Scaleway (French jurisdiction), outside the direct scope of the US CLOUD Act. - **Data & Code Sovereignty**: Storage, computation, backups, and logs reside strictly within the European Union. - **Asynchronous Rust Architecture**: Microservices built with Tokio and Axum. Zero garbage collector pauses (deterministic sub-millisecond P99 latencies, low memory footprint). Zero-panic defensive design in production. - **Strict Multi-Tenant Isolation**: Each project gets a dedicated PostgreSQL 18 database with separated schemas on a managed CloudNativePG (CNPG) cluster — and an entirely dedicated CNPG cluster per organization on the Enterprise tier. - **Dual-Plane Network Architecture**: - **Management Plane (Control Plane)**: Listens on port 8090 (`api.aurabase.dev`), handling project provisioning, organizations, quotas, and billing. - **Data Plane**: Listens on port 8080 (`.aurabase.dev`), routing tenant application queries and realtime traffic. --- ## 2. Platform Services & Capabilities ### 1. Managed PostgreSQL 18 (Primary Relational Engine) - **Engine**: PostgreSQL 18 managed by the CloudNativePG (CNPG) Kubernetes operator. - **Validated & Active Extensions**: - `vector` (`pgvector`): Vector similarity search with HNSW and IVFFlat index support for AI/LLM applications. - `pg_trgm`: Trigram indexing and fuzzy text matching for search and autocompletion. - `pgcrypto` & `uuid-ossp`: Cryptographic functions, hashing, and UUID generation (`gen_random_uuid()`, `uuid_generate_v4()`). - Plus whitelisted self-service extensions (including `citext`, `hstore`, `ltree`, `unaccent`, `btree_gin`, `btree_gist`, `fuzzystrmatch`, `intarray`, `pg_stat_statements`, `pg_graphql`) via Studio Extensions or `POST /v1/db/{project_id}/schema/extensions`. *Transparency note*: `postgis`, `pg_cron`, `timescaledb`, and `pgmq` are not installed on the default runtime image. - **PgBouncer Pooling**: Transaction pooling enabled by default to absorb thousands of concurrent client connections. - **Row-Level Security (RLS)**: Enforced by default (`FORCE ROW LEVEL SECURITY`) on all tables created via Studio or API. ### 2. NoSQL & Document Store (MongoDB Compatible) - **Isolated Document Engine**: Flexible BSON/JSON document store per project for telemetry, IoT, dynamic e-commerce catalogs, and session storage. - **Query Operators & Pipelines**: Standard MongoDB operators (`$eq`, `$in`, `$gt`, `$regex`, etc.) and multi-stage aggregation pipelines (`$match`, `$group`, `$sort`, `$unwind`). - **Advanced Indexing & TTL**: Single, compound, and text indexes, plus **TTL** indexes (`expireAfterSeconds`) for automatic document expiration (ephemeral sessions and cache). - **Unified Realtime CDC**: Mutations on NoSQL collections are captured via Change Streams and distributed over the NATS JetStream bus using the exact same event envelope as Postgres CDC. ### 3. Authentication 2.1 & Identity Management - **Identity Providers**: - Email / Password (Argon2id / bcrypt secure hashing). - Magic links (short-lived, single-use login links). - Email / SMS OTP (6-digit one-time passcodes). - Anonymous authentication (smoothly convertible into permanent user accounts). - **15 OAuth 2.1 Providers**: Google, GitHub, Discord, Facebook, Twitter/X, Microsoft, Apple, Spotify, Twitch, Bitbucket, Zoom, Notion, Figma, Kakao, Snapchat. - Generic enterprise **OIDC** provider support (`oidc:`). - **Multi-Factor Security (MFA)**: - **Passkeys & WebAuthn**: Native FIDO2 hardware passkeys (Rust crate `webauthn-rs`) as a robust second factor or passwordless credential. - **MFA TOTP**: RFC 6238 compatible (Google Authenticator, 1Password, Apple Passwords). - **JWT Key Management**: - Access tokens signed with asymmetric **ES256** keys by default (or **RS256** published at `/.well-known/jwks.json` when an RSA key is configured in opt-in mode). ### 4. Sovereign S3 Object Storage - **S3 API Standard**: In-cluster backend powered by SeaweedFS (fully compatible with AWS S3 / Scaleway Object Storage). - **Features**: Simple and multipart uploads for large files, pre-signed temporary URLs (read/write), custom metadata. - **On-the-Fly Image Transformations**: - Parameters: `width`, `height`, `resize: cover|contain|fill` (mapped to `?fit=`), `quality`, `format`. - Supported output formats: `jpeg`, `png`, `webp`, `gif`. - AVIF: Serving existing AVIF files is supported; active conversion TO avif is not supported. ### 5. Realtime Engine & CDC (Change Data Capture) - **Protocols**: WebSockets and Server-Sent Events (SSE). - **High-Throughput Bus**: NATS JetStream orchestrating distributed messaging. - **Postgres CDC**: Logical WAL streaming (`wal2json`) with server-side column filtering (`filter: "col=operator.val"`). - **Collaboration Features**: - **Broadcast**: Direct peer-to-peer ephemeral messaging without database persistence (latency < 10ms). - **Presence**: Real-time collaborative user state tracking (online status, shared cursors). ### 6. Edge Functions (Dual Deno / WASM Runtimes) - **Two Execution Engines Available per Function**: - **Deno / TypeScript (V8 Isolates)**: Recommended for fast iteration. Standard `Deno.serve(handler)` syntax. Instant startup (< 5ms). - **WebAssembly WASM (Wasmtime 43)**: For precompiled high-performance binaries written in Rust, Go, C++, or any language targeting WASI. - **Triggers**: Direct synchronous HTTP invocation (`aura.functions.invoke()`) or scheduled Cron execution. - **Encrypted Secrets (Vault)**: Injected environment variables encrypted with **AES-256-GCM** at rest via `PUT /v1/functions/{project_id}/{name}/env`. ### 7. Scheduled Tasks (Cron Jobs) - **Periodic Execution**: Scheduled invocation of deployed Edge Functions using standard 5-field cron syntax (`0 * * * *`). - **Traceability**: Complete invocation history, stdout/stderr execution logs, and failure alerting. Does not invoke raw SQL directly without a function. ### 8. Multi-Channel Notifications & Signed Webhooks - **Channels**: Email (SMTP/Resend), SMS (Twilio), Mobile Push (FCM/APNs), Outgoing Webhooks. - **Idempotency & Retries**: Guaranteed at-most-once delivery with `x-aurabase-idempotency-key` and Dead-Letter Queue (DLQ) with up to 5 automatic retries. - **HMAC-SHA256 Signatures**: Standard Stripe convention: ```http X-Aurabase-Event-Id: evt_01J8Y6Q9K3M7Z... X-Aurabase-Signature: t=1724060000,v1=9f86d081884c7d659a2feaa0c55ad... ``` Signature computed over `"{timestamp}.{rawBody}"` with constant-time cryptographic verification. ### 9. Unified AI Gateway & Native RAG - **Multi-Model Router**: Native support for OpenAI, Anthropic (Claude 3.5 Sonnet), and Google Gemini. Any OpenAI-compatible endpoint (local Ollama, Mistral, Scaleway) supported via custom base URL. - **Ephemeral Session Tokens**: `aura.ai.session()` issues short-lived chat tokens without exposing project API keys in frontend clients. - **Vector Search & RAG**: Automatic text chunking (`ragIngest`), cosine similarity search (`semanticSearch`), and contextual answer synthesis (`rag`). - **AST-Verified NL2SQL**: Natural language to PostgreSQL translation checked by SQL Abstract Syntax Tree (AST) parser preventing mutations and enforcing a 100-row limit. ### 10. GraphQL API (Opt-in per Project, `pg_graphql`) - **Per-Project Activation**: Disabled by default. Enabled on demand via `POST /v1/control/projects/{id}/graphql/enable` or `aura projects graphql-enable `. - **Routes**: Queried via `POST /v1/db/{project_id}/graphql` (or `/graphql` on the project subdomain) as well as generic RPC `POST /v1/db/{project_id}/rpc/graphql`. Note `pg_graphql` inflects SQL `snake_case` names to `camelCase`. - **Inherited Security**: `SECURITY INVOKER` function directly applying user RLS rules without separate authentication layers. Introspection disabled by default. --- ## 3. Official TypeScript / JavaScript SDK (`@aurabase/aurabase-js`) The official TypeScript/JavaScript client (`@aurabase/aurabase-js`, distributed as a modular pnpm workspace with sub-packages `@aurabase/core`, `@aurabase/auth`, `@aurabase/db`, `@aurabase/storage`, `@aurabase/realtime`, `@aurabase/functions`, `@aurabase/ai`, and `@aurabase/notifications`) targets Node.js 20+, Bun, Deno, modern browsers, and edge runtimes. ### Installation: ```bash npm install @aurabase/aurabase-js # or install specific tree-shakable packages: npm install @aurabase/db @aurabase/auth @aurabase/storage @aurabase/realtime ``` ### Initialization: ```typescript import { createClient, createAdminClient } from '@aurabase/aurabase-js' import type { Database } from './aurabase.types' // auto-generated via 'aura db generate' // 1. Standard Client (Client-Side / Browser with Public Anon Key) // Note: The project URL contains the project identifier; no separate project ID argument is required. export const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, // https://.aurabase.dev process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, // aura_anon_xxx { auth: { persistSession: true, autoRefresh: true, flowType: 'pkce' }, retry: { enabled: true, maxRetries: 3 }, requestTimeoutMs: 30000, } ) // 2. Admin Client (Server-Side Only with Privileged service_role Key) // SECURITY WARNING: NEVER expose service_role in client-side bundles (throws a security exception) export const admin = createAdminClient( process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY! // aura_sk_xxx ) ``` ### Unified Response Format (`AuraResponse`): Every SDK method returns a discriminated union without throwing unhandled runtime exceptions: ```typescript type AuraResponse = | { data: T; error: null; meta?: ResponseMeta } // Success with data | { data: null; error: null; meta?: ResponseMeta } // Success 204 (no content) | { data: null; error: AuraError; meta?: ResponseMeta } // HTTP or business logic error // Standard boolean helper properties available on AuraError: // error.isNotFound, error.isUnauthorized, error.isForbidden, error.isRateLimited ``` ### Complete SDK Code Examples: #### 1. Database Operations & Query Builder ```typescript // Select with relational joins, column filtering, sorting, and pagination const { data: todos, error } = await aura.db .from('todos') .select('id, title, is_complete, priority, created_at, profiles(username, avatar_url)') .eq('is_complete', false) .gte('priority', 2) .order('created_at', { ascending: false }) .range(0, 19) // Insert single or multiple rows with automatic return const { data: newTodo } = await aura.db .from('todos') .insert({ title: 'Deploy sovereign microservice', priority: 3 }) .select() .single() // Update matching rows const { data: updated } = await aura.db .from('todos') .update({ is_complete: true }) .eq('id', 'todo-uuid-123') .select() // Delete matching rows await aura.db .from('todos') .delete() .eq('is_complete', true) // Call PostgreSQL Stored Function (RPC) const { data: monthlyStats } = await aura.db.rpc('calculate_org_usage', { org_id: 'org-uuid-456', fiscal_year: 2026, }) ``` #### 2. Authentication, OAuth & MFA ```typescript // Email & password sign-up const { data: authData } = await aura.auth.signUp({ email: 'developer@company.eu', password: 'SuperSecurePassword123!', }) // Sign in with password const { data: session } = await aura.auth.signInWithPassword({ email: 'developer@company.eu', password: 'SuperSecurePassword123!', }) // OAuth 2.1 login (15 supported providers) await aura.auth.signInWithOAuth('github', { redirectTo: 'https://myapp.eu/auth/callback', }) // Passwordless magic link await aura.auth.signInWithOtp({ email: 'developer@company.eu', }) // TOTP MFA Enrollment const { data: factor } = await aura.auth.mfa.enroll({ factorType: 'totp' }) // Display QR Code: factor.totp.qr_code (data URI) await aura.auth.mfa.verify({ factorId: factor.id, code: '123456' }) // Sign out and clear local session cookies/storage await aura.auth.signOut() ``` #### 3. Sovereign S3 Storage ```typescript // Simple and multipart file upload const { data: uploadInfo, error: uploadErr } = await aura.storage .from('documents') .upload('invoices/2026-001.pdf', pdfBlob, { contentType: 'application/pdf', upsert: true, }) // Generate temporary pre-signed URL (read or write) const { data: signed } = await aura.storage .from('documents') .createSignedUrl('invoices/2026-001.pdf', 3600) // valid for 1 hour // On-the-fly image transformations via public URL const transformedUrl = aura.storage .from('avatars') .getPublicUrl('user_1.jpg', { transform: { width: 300, height: 300, resize: 'cover', format: 'webp' }, }) ``` #### 4. Realtime CDC, Broadcast & Presence ```typescript const channel = aura.realtime.channel('project-updates') // Listen to Postgres CDC changes (INSERT, UPDATE, DELETE) with column filter channel.on('postgres_changes', { event: '*', schema: 'public', table: 'orders' }, (payload) => { console.log('Realtime DB change:', payload.eventType, payload.new) }) // Sub-10ms peer-to-peer broadcast messaging without database persistence channel.on('broadcast', { event: 'cursor-movement' }, ({ payload }) => { renderCursor(payload.x, payload.y) }) // Collaborative user presence tracking channel.on('presence', { event: 'sync' }, () => { const currentUsers = channel.presenceState() console.log('Online users:', currentUsers) }) await channel.subscribe(async (status) => { if (status === 'SUBSCRIBED') { await channel.track({ user: 'Developer 1', status: 'online' }) } }) ``` #### 5. AI Gateway & Native RAG ```typescript // 1. Unified Multi-Provider Chat Completion const { data: aiResponse, error: chatErr } = await aura.ai.chat( [{ role: 'user', content: 'Explain sovereign European cloud infrastructure' }], { provider: 'anthropic', model: 'claude-3-5-sonnet', temperature: 0.2, max_tokens: 1024 } ) console.log('AI Response:', aiResponse?.content, 'Tokens:', aiResponse?.output_tokens) // 2. Real-Time Token Streaming (SSE) for await (const chunk of aura.ai.chatStream( [{ role: 'user', content: 'Draft a data processing agreement under GDPR' }], { model: 'gpt-4o', temperature: 0.1 } )) { process.stdout.write(chunk.delta) } // 3. Ephemeral AI Sessions (Zero Secret Leakage on Frontend) // Mints a short-lived capability token with bounded token budget for client applications const session = await aura.ai.session() const { content, budget_remaining } = await session.chat([ { role: 'user', content: 'Summarize our privacy policy' } ]) // 4. Document Ingestion & Embeddings (pgvector) const { data: ingestResult } = await aura.ai.ragIngest({ document: 'European Data Protection Regulation full text...', namespace: 'legal-docs', metadata: { version: '2026.1', source: 'official-journal' }, chunk_size: 800, chunk_overlap: 150, }) // 5. Semantic Vector Search with sub-10ms Cosine Distance const { data: searchResults } = await aura.ai.semanticSearch( 'GDPR requirements for cloud storage', 'legal-docs', { threshold: 0.8, top_k: 5 } ) // 6. Context-Augmented RAG Synthesis const { data: ragAnswer } = await aura.ai.rag({ question: 'Where must customer backups be stored?', namespace: 'legal-docs', system: 'Answer accurately using only the provided context.', }) // 7. Natural Language to SQL (AST-Verified, Read-Only & Auto-Limited) const { data: sqlQuery } = await aura.ai.nl2sql( 'Show the top 5 organizations with highest storage usage', { dialect: 'postgresql', limit: 5 } ) console.log('Generated Safe SQL:', sqlQuery?.sql) ``` --- ## 4. Next.js 15/16 App Router & SSR Integration Supported via `@aurabase/aurabase-js/ssr` with automatic cookie chunking (RFC 6265): ```typescript import { createServerClient } from '@aurabase/aurabase-js/ssr' import { NextResponse, type NextRequest } from 'next/server' export async function proxy(request: NextRequest) { const response = NextResponse.next({ request }) const aura = createServerClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, { cookies: { getAll() { return request.cookies.getAll() }, setAll(cookies) { cookies.forEach(({ name, value, options }) => { request.cookies.set(name, value) response.cookies.set(name, value, options) }) }, }, } ) const { data: user } = await aura.auth.getUser() if (!user && request.nextUrl.pathname.startsWith('/dashboard')) { return NextResponse.redirect(new URL('/login', request.url)) } return response } ``` --- ## 5. Rust SDK (crate `aurabase`, folder `aurabase-rs/`) Official asynchronous Rust client for high-performance microservices: ```rust use aurabase::AuraClient; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] struct Post { id: String, title: String, published: bool, } #[tokio::main] async fn main() -> Result<(), Box> { let aura = AuraClient::new( &std::env::var("NEXT_PUBLIC_AURABASE_URL")?, &std::env::var("AURABASE_SERVICE_ROLE_KEY")?, None, ); let res = aura .from::("posts") .select("id,title,published") .eq("published", "true") .order("created_at", "desc") .limit(10) .execute() .await?; println!("Posts: {:?}", res.data); Ok(()) } ``` --- ## 6. Python & Dart SDKs Reference ### Python SDK (`aurabase-py`) Real source code located in `aurabase-py/` of the monorepo (import name `aurabase`). Not published on PyPI yet — install locally via: ```bash pip install -e ./aurabase-py ``` #### Synchronous & Asynchronous Usage: ```python from aurabase import create_client, AsyncAuraClient import asyncio # 1. Synchronous client (Scripts, CLI, Data Science) aura = create_client("https://.aurabase.dev", "aura_anon_xxx") todos = aura.from_("todos").select("id, title, is_complete").eq("is_complete", False).execute() print("Open todos:", todos.data) # 2. Asynchronous client (FastAPI, aiohttp, Starlette) async def main(): async_aura = AsyncAuraClient("https://.aurabase.dev", "aura_anon_xxx") res = await async_aura.from_("todos").select("*").limit(10).execute() print("Async result:", res.data) asyncio.run(main()) ``` ### Dart / Flutter SDK (`aurabase-dart`) Real source code located in `aurabase-dart/` (package name `aurabase`). Not published on pub.dev yet — include via Git dependency in `pubspec.yaml`: ```yaml dependencies: aurabase: git: url: https://github.com/Aurabase-cloud/Aurabase.git path: aurabase-dart ``` #### Usage: ```dart import 'package:aurabase/aurabase.dart'; void main() async { final aura = createClient( 'https://.aurabase.dev', 'aura_anon_xxx', ); final response = await aura .from('todos') .select('id, title, is_complete') .eq('is_complete', false) .execute(); print('Todos: ${response.data}'); } ``` --- ## 7. Aurabase CLI (`aura`) Complete Reference The Rust binary CLI `aura` (distributed on npm as `@aurabase/cli` with binary aliases `aura` and `aurabase`, and compileable from the monorepo via `cargo install --path aura-cli`) offers more than 80 subcommands across 10 functional domains. ### Installation: ```bash npm install -g @aurabase/cli # or run directly with npx: npx @aurabase/cli --help # or compile from source: cargo install --path aura-cli ``` ### Complete Command Inventory: #### 1. Configuration & Authentication ```bash aura init [project-name] # Initialize aurabase.toml configuration in current directory aura register # Interactive developer sign-up to Aurabase Cloud aura login # Authenticate via browser or API token aura logout # Terminate active CLI session and clear local credentials aura whoami # Display current authenticated user, organization, and project aura link --project-id # Link local working directory to a remote Aurabase project aura status # Display link status, active environments, and local stack health aura doctor # Comprehensive environment diagnostic (Docker, open ports, gateway) ``` #### 2. Local Container Stack & Development ```bash aura start # Start local development stack (Postgres, Auth, Storage, Realtime, Gateway) aura stop # Stop local development containers aura restart # Restart local stack aura dev # Start file watcher and local auto-reload aura studio # Open local Aurabase Studio in default browser (port 30300) aura logs [--service ] # Stream container runtime logs (gateway, auth, db, realtime, storage) ``` #### 3. Organization & Project Lifecycle ```bash aura orgs list # List all organizations you belong to aura orgs create # Create a new organization aura orgs use # Switch active organization context aura projects list # List all projects in current organization aura projects create # Provision a new dedicated cloud project aura projects delete # Permanently delete a project and release resources aura projects rename # Update project display name aura projects api-keys # Display project public anon key and private service_role key ``` #### 4. Project Authentication & User Management ```bash aura auth users # List registered project users with pagination aura auth sessions # Inspect and terminate active user sessions aura auth audit-log # Stream security and authentication audit events aura auth settings # Inspect and update OAuth 2.1, MFA and password policy settings aura auth email-templates # View and customize email verification and magic link templates ``` #### 5. Database, Schema & Migrations ```bash aura db migration new # Create a new timestamped SQL migration file in aurabase/migrations/ aura db push # Apply unapplied local SQL migrations to the cloud database aura db pull # Introspect remote PostgreSQL schema and write to local SQL aura db diff [--name ] # Compute schema diff between local and remote, generate migration aura db watch # Watch migration directory and auto-apply changes in development aura db generate # Introspect database schema and generate TypeScript types (aurabase.types.ts) aura db seed # Execute aurabase/seed.sql against the database aura db reset # Drop schema, re-run all migrations from scratch, and seed aura db status # Display migration version history and pending migrations aura db raw "" # Execute raw SQL statement (--dry-run and --read-only supported) aura db table list|create|drop # Table schema management with RLS and CDC toggles aura db policy list|create|drop # Row-Level Security policy manager aura db function list|create # PostgreSQL stored procedures and trigger functions aura db trigger list|create # SQL triggers management aura db backup create|restore # On-demand snapshot creation and point-in-time restore aura db connect # Open direct interactive psql session to project PostgreSQL ``` #### 6. Sovereign S3 Storage ```bash aura storage buckets # List all storage buckets aura storage mb # Create a new private or public bucket aura storage ls # List objects in a bucket aura storage cp # Upload or download objects with progress bar aura storage rm / # Delete an object or folder recursively ``` #### 7. Edge Functions (Deno / WASM) ```bash aura functions new # Scaffold a new function with Deno/TypeScript or WASM template aura functions deploy # Deploy function (direct file upload for Deno; precompiled .wasm binary for WASM) aura functions list # List deployed functions with runtimes, version, and cron schedules aura functions logs # Stream live execution logs (stdout/stderr) from deployed function aura functions invoke # Test invoke function from terminal with JSON payload ``` #### 8. Secrets Vault & Environment Variables ```bash aura secrets list --function # List configured environment variable keys (values masked) aura secrets set --function KEY=VAL # Set AES-256-GCM encrypted secrets for Edge Function aura env # Inspect or export local .env configuration ``` #### 9. Terminal UI, Autocompletion & Maintenance ```bash aura ui # Launch full-featured interactive Terminal UI (TUI) aura update # Self-update the aura CLI binary to the latest release aura completions # Generate shell autocompletion script ``` --- ## 8. Model Context Protocol (MCP) Server — 86 Tools Official MCP server (`@aurabase/mcp-server`) allowing AI assistants (Cursor, Claude Desktop, Windsurf, Google Antigravity, VS Code, ChatGPT) to control an Aurabase project. ### Transports: - **Local STDIO (default)**: `npx -y -p @aurabase/mcp-server aurabase-mcp --url https://.aurabase.dev --project-id --service-role-key aura_sk_...` — 82 tools with a project key (the 4 management-plane tools need management credentials). - **Local Streamable HTTP**: add `--transport http --port 3001 --auth-token `, then connect the client to `http://127.0.0.1:3001/mcp` with `Authorization: Bearer `. - **Hosted service** (`https://mcp.aurabase.dev/mcp`, OAuth 2.1): planned, not live yet. ### Security Controls: - `--read-only`: Restricts tool exposure to the 37 non-mutating inspection and analytics tools (blocks inserts, updates, deletes, schema drops, and admin operations). - `--allowed-tools `: Strict explicit whitelist of tools exposed to the model. ### Resources & Diagnostic Prompts: - **Resources**: `aurabase://schema` providing live PostgreSQL table schemas, types, and active constraints. - **Prompts**: Built-in prompt templates for security audits, TypeScript codegen, vector RAG setup, and query performance tuning. ### 86 Tools Across 12 Domains: - **Database (15)**: `list_tables`, `describe_table`, `execute_sql`, `query_table`, `insert_rows`, `update_rows`, `delete_rows`, `call_rpc`, `generate_types`, `diff_schema`, `apply_migration`, `list_migrations`, `explain_query`, `analyze_table`, `get_db_size`. - **RLS & SQL Functions (12)**: `list_rls_policies`, `create_rls_policy`, `update_rls_policy`, `drop_rls_policy`, `toggle_rls`, `get_security_advisors`, `list_sql_functions`, `create_sql_function`, `drop_sql_function`, `list_sql_triggers`, `create_sql_trigger`, `drop_sql_trigger`. - **Authentication (7)**: `list_users`, `get_user`, `create_user`, `update_user`, `delete_user`, `ban_user`, `generate_link`. - **S3 Storage (9)**: `list_buckets`, `get_bucket`, `create_bucket`, `empty_bucket`, `list_files`, `upload_file`, `move_file`, `delete_files`, `create_signed_url`. - **Edge Functions (6)**: `list_functions`, `get_function_info`, `deploy_function`, `invoke_function`, `delete_function`, `set_function_env`. - **AI Gateway & RAG (5)**: `ai_completion`, `index_document`, `rag_query`, `vector_search`, `create_vector_index`. - **Realtime (3)**: `list_realtime_channels`, `get_realtime_settings`, `update_realtime_settings`. - **Notifications (10)**: `send_email`, `send_push_notification`, `send_sms`, `list_notification_logs`, `get_notification_settings`, `update_notification_settings`, `list_notification_templates`, `create_notification_template`, `delete_notification_template`, `get_notification_stats`. - **Observability & Performance (5)**: `list_slow_queries`, `list_active_queries`, `cancel_query`, `get_performance_advisors`, `list_extensions`. - **Backups (5)**: `list_backups`, `create_backup`, `restore_backup`, `get_backup_schedule`, `set_backup_schedule`. - **Documentation (1)**: `search_docs`. - **API Keys & Management Plane (8)**: `create_api_key`, `list_api_keys`, `revoke_api_key`, `project_info`, `list_all_projects`, `switch_project`, `get_active_project`, `get_project_metrics`. --- ## 9. AI Gateway & Sovereign LLM API Reference (23 Endpoints) The Aurabase AI Gateway (`services/aura-ai`, proxied on the Data Plane via `.aurabase.dev/v1/ai` or `api.aurabase.dev/v1/ai`) provides a unified, sovereign European interface to modern large language models, high-performance vector embeddings, and RAG pipelines. ### Endpoints Inventory: | Method | Endpoint Path | Description | Authentication | |:---|:---|:---|:---| | `POST` | `/v1/ai/{project_id}/chat` | Synchronous multi-provider chat completion | `apikey` (anon / service_role) | | `POST` | `/v1/ai/{project_id}/chat/stream` | Real-time Server-Sent Events (SSE) token streaming | `apikey` (anon / service_role) | | `POST` | `/v1/ai/{project_id}/session` | Mint an ephemeral capability session token (300s TTL) | `apikey` (client/admin) | | `POST` | `/v1/ai/{project_id}/session/chat` | Ephemeral session chat with token budget deduction | `Authorization: Bearer ` ONLY | | `POST` | `/v1/ai/{project_id}/session/chat/stream` | Ephemeral session chat streaming | `Authorization: Bearer ` ONLY | | `POST` | `/v1/ai/{project_id}/session/embed` | Ephemeral session direct vector embedding computation | `Authorization: Bearer ` ONLY | | `POST` | `/v1/ai/{project_id}/embed` | Generate and persist embedding in PostgreSQL pgvector | `apikey` (anon / service_role) | | `GET` | `/v1/ai/{project_id}/search` | Semantic vector search by cosine distance (`query`, `namespace`) | `apikey` (anon / service_role) | | `POST` | `/v1/ai/{project_id}/rag/query` | Retrieval-Augmented Generation context query | `apikey` (anon / service_role) | | `POST` | `/v1/ai/{project_id}/rag/ingest` | Large document ingestion and chunking (up to 5 MB) | `apikey` (anon / service_role) | | `GET` | `/v1/ai/{project_id}/rag/namespaces` | List all distinct RAG namespaces for the project | `apikey` (anon / service_role) | | `DELETE`| `/v1/ai/{project_id}/rag/{namespace}` | Delete a RAG namespace and its indexed vectors | `apikey` (service_role / admin) | | `POST` | `/v1/ai/{project_id}/rag/{namespace}/reindex` | Reindex a namespace with active embedding model | `apikey` (service_role / admin) | | `POST` | `/v1/ai/{project_id}/nl2sql` | Natural language to PostgreSQL (AST-checked, read-only) | `apikey` (anon / service_role) | | `GET` | `/v1/ai/{project_id}/logs` | Observability logs (latency, tokens, provider, cost) | `apikey` (service_role / admin) | | `GET` | `/v1/ai/{project_id}/settings` | Inspect project AI settings (default provider, fallback) | `apikey` (anon / service_role) | | `PUT` | `/v1/ai/{project_id}/settings` | Update project AI settings (system prompt, fallback) | `apikey` (service_role / admin) | | `GET` | `/v1/ai/{project_id}/providers` | List configured providers (API keys masked) | `apikey` (service_role / admin) | | `GET` | `/v1/ai/{project_id}/providers/{provider}` | Inspect single provider configuration | `apikey` (service_role / admin) | | `POST` | `/v1/ai/{project_id}/providers/{provider}` | Upsert provider credentials (Vault Transit encrypted) | `apikey` (service_role / admin) | | `PATCH`| `/v1/ai/{project_id}/providers/{provider}` | Partial provider update | `apikey` (service_role / admin) | | `DELETE`| `/v1/ai/{project_id}/providers/{provider}` | Remove provider configuration | `apikey` (service_role / admin) | | `POST` | `/v1/ai/{project_id}/providers/{provider}/validate` | Test upstream provider API credentials and model | `apikey` (service_role / admin) | ### 1. Chat Completion API Specification #### `POST /v1/ai/{project_id}/chat` **Request Headers**: ```http POST /v1/ai/{project_id}/chat HTTP/1.1 Host: .aurabase.dev apikey: aura_anon_xxx Content-Type: application/json ``` **Request Body**: ```json { "messages": [ { "role": "user", "content": "Explain EU cloud sovereignty." } ], "system": "Answer concisely in 2 sentences.", "provider": "anthropic", "model": "claude-3-5-sonnet", "temperature": 0.2, "max_tokens": 1024 } ``` *Prompt Security Notice*: The `messages` array strictly accepts roles `"user"` and `"assistant"`. Injecting a `"system"` message inside the array is rejected with `HTTP 400 Bad Request`. System instructions must be passed via the `system` field, which is automatically composed under the project-level policy `system_prompt` to prevent adversarial jailbreaks. **Response Body (`200 OK`)**: ```json { "data": { "content": "European cloud sovereignty ensures data is hosted and processed entirely within the EU under GDPR...", "model": "claude-3-5-sonnet", "provider": "anthropic", "fallback_used": false, "input_tokens": 28, "output_tokens": 64, "reasoning_tokens": null, "finish_reason": "stop" } } ``` ### 2. Server-Sent Events (SSE) Streaming #### `POST /v1/ai/{project_id}/chat/stream` **Request Headers**: ```http POST /v1/ai/{project_id}/chat/stream HTTP/1.1 Host: .aurabase.dev apikey: aura_anon_xxx Accept: text/event-stream Content-Type: application/json ``` **Stream Events Protocol**: ```http event: delta data: {"content": "European"} event: delta data: {"content": " data"} event: delta data: {"content": " sovereignty"} event: done data: {"provider":"anthropic","fallback_used":false,"finish_reason":"stop","usage":{"input_tokens":28,"output_tokens":45,"reasoning_tokens":null}} ``` ### 3. Ephemeral AI Sessions (Zero Secret Leakage) To enable browser-based AI chats without exposing backend credentials or risking runaway costs: 1. **Minting Session Ticket**: Server calls `POST /v1/ai/{project_id}/session` with project `service_role` key: ```json { "data": { "ticket": "aura_sess_eyJhbGciOi...", "expires_at": 1730410000, "budget_remaining": 25000 } } ``` 2. **Client Invocation**: Frontend calls `/session/chat` or `/session/chat/stream` using **`Authorization: Bearer ` ONLY**: ```http POST /v1/ai/{project_id}/session/chat HTTP/1.1 Host: .aurabase.dev Authorization: Bearer aura_sess_eyJhbGciOi... Content-Type: application/json { "messages": [{ "role": "user", "content": "Summarize this page." }] } ``` *Budget Exceeded Handling*: When the ticket's allocated tokens are exhausted, the gateway responds with `HTTP 429 Too Many Requests` (`code: "session_budget_exceeded"`). ### 4. Vector Storage & Semantic Search (pgvector) - **Supported Dimensions Allowlist**: `[768, 1536, 3072]`. - `768`: Google Gemini `text-embedding-004`, Mistral `mistral-embed`. Stored in `embedding_768`. - `1536`: OpenAI `text-embedding-3-small`, `text-embedding-ada-002`. Stored in `embedding_1536`. - `3072`: OpenAI `text-embedding-3-large`. Stored in `embedding_3072` with HNSW `halfvec(3072)` index for sub-5ms latency. - **Index Isolation**: Embeddings are tracked by `embedding_model` to strictly prevent vector drift between disparate models. ### 5. AST-Verified NL2SQL #### `POST /v1/ai/{project_id}/nl2sql` Translates natural language questions directly into PostgreSQL queries: - **Introspected Schema**: Automatically analyzes actual database tables and column types with server-side caching. - **Abstract Syntax Tree (AST) Enforcement**: Parses generated SQL via `sqlparser`. Mutations (`INSERT`, `UPDATE`, `DELETE`, `DROP`, `ALTER`, `TRUNCATE`) and system catalog queries are rejected with `HTTP 400`. - **Enforced Row Limits**: Automatically injects a `LIMIT 100` clause if omitted by the model (maximum allowed limit: 1000). --- ## 10. Official Pricing & Plan Quotas Plan quotas and unit rates: https://aurabase.dev/en/pricing and https://aurabase.dev/en/pricing/calculator. - **Free**: €0 / month — 3 projects, 500 MB DB, 1 GB storage, Community support; 100,000 Edge Function invocations per month, 200 concurrent realtime connections. - **Pro**: €25 / month — 10 projects, 8 GB DB, 100 GB storage, Dedicated instance, Email support; 1,000,000 Edge Function invocations per month, 1,000 concurrent realtime connections. - **Team**: €99 / month — 50 projects, 32 GB DB, 1 TB storage, Priority support; 10,000,000 Edge Function invocations per month, 10,000 concurrent realtime connections. - **Enterprise**: custom quote — Unlimited projects, Dedicated cluster, 99.99% signed SLA, 24/7 dedicated support; 100,000,000 Edge Function invocations per month, 100,000 concurrent realtime connections. --- ## 11. Complete documentation (generated from the pages) ### Aurabase Documentation Source: https://aurabase.dev/en/docs.md # Aurabase Documentation > Everything you need to build, deploy and scale your applications on Aurabase. Concepts, practical guides, SDK and API references. ## Where to start? - [Quick start](https://aurabase.dev/en/docs/getting-started): Zero to an API in 5 minutes — Postgres + realtime included. - [Architecture](https://aurabase.dev/en/docs/architecture): Eight services, one network. Isolation by project schema. - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): Client typed for Next.js, React, Node, Bun, Deno. ## Start with a task Each link opens the page that walks through the task. - [Query data](https://aurabase.dev/en/docs/database/query-with-sdk): Read, write and count rows with aura.from(), and call SQL functions with rpc(). - [Authenticate users](https://aurabase.dev/en/docs/auth/authenticate-users): Sign users up and in, follow session changes, and manage sessions and MFA. - [Upload files](https://aurabase.dev/en/docs/storage/files-with-sdk): Create buckets, upload and download files, and share them with public or signed URLs. - [Subscribe to changes](https://aurabase.dev/en/docs/realtime/subscribe-with-sdk): Open realtime channels, listen to table changes, broadcast messages and track presence. - [Deploy a function](https://aurabase.dev/en/docs/functions/quickstart): Create, deploy and call an Edge Function with the aura CLI. - [Migrate from Supabase](https://aurabase.dev/en/docs/guides/migration-supabase): Move a Supabase project: same client API and RLS policies. - [Migrate from Firebase](https://aurabase.dev/en/docs/guides/migration-firebase): Move Firestore data, Auth users, Storage files and Cloud Functions. ## Build with an agent Give this prompt to your coding agent (Claude Code, Cursor, Codex…). It points the agent to the documentation index and to the MCP server of your project. **Prompt for your coding agent** ```text Use Aurabase as the backend of this app. Documentation: read https://aurabase.dev/llms.txt first. Every docs page is also available as Markdown: add .md to its URL, for example (the same works for every page): https://aurabase.dev/en/docs/getting-started.md Client: install @aurabase/aurabase-js and create the client with createClient(NEXT_PUBLIC_AURABASE_URL, NEXT_PUBLIC_AURABASE_ANON_KEY). Keep AURABASE_SERVICE_ROLE_KEY on the server: never put it in client code. Project access: to read the schema and run SQL, start the Aurabase MCP server over stdio (82 tools with a project key): npx -y -p @aurabase/mcp-server aurabase-mcp --url https://.aurabase.dev --project-id --service-role-key aura_sk_… The project id is in Studio › Settings › General. The service role key is shown once when the project is created; regenerate it in Studio › Settings › Connection if you lost it. ``` ## Products in detail - [Database (Postgres)](https://aurabase.dev/en/docs/database): Dedicated Postgres, isolated schemas, RLS, migrations, TS codegen. - [NoSQL Document Store](https://aurabase.dev/en/docs/nosql): MongoDB-compatible engine, dynamic JSON collections, aggregation pipelines. - [Auth](https://aurabase.dev/en/docs/auth): 15 OAuth providers, MFA TOTP, granular RBAC. - [Realtime](https://aurabase.dev/en/docs/realtime): Self-negotiated WebSocket, SSE, NATS. Presence, replay, cursors. - [Storage](https://aurabase.dev/en/docs/storage): S3-compatible, transforms AVIF/WebP, signed URLs, CDN 12 regions. - [Edge Functions](https://aurabase.dev/en/docs/functions): Deno and WASM multi-runtime, cron, DLQ, AI Gateway, preview deployments. ## SDKs & APIs - [Javascript SDK](https://aurabase.dev/en/docs/sdk-js): Complete reference · Next.js, React, Node, Bun, Deno - [REST API](https://aurabase.dev/en/docs/api-rest): Stripe-style reference with request/response ## Community and support > **Tip:** > > **The Discord community responds on average within 15 minutes.** For Enterprise support (dedicated Slack, 15 min SLA, success manager), see [Enterprise plans](https://aurabase.dev/en/enterprise). | Channel | Link | | --- | --- | | Discord | [discord.gg/62HY9GprNc](https://discord.gg/62HY9GprNc) | | GitHub | [github.com/Aurabase-cloud/Aurabase](https://github.com/Aurabase-cloud/Aurabase) | | Crates.io | [crates.io/crates/aurabase](https://crates.io/crates/aurabase) | | npm registry | [@aurabase/aurabase-js](https://www.npmjs.com/package/@aurabase/aurabase-js) | | Technical blog | [aurabase.hashnode.dev](https://aurabase.hashnode.dev/) | | Community | [dev.to/daylami](https://dev.to/daylami) | | Status | [aurabase.dev/en/status](https://aurabase.dev/en/status) | --- ### Quick start Source: https://aurabase.dev/en/docs/getting-started.md # Quick start > From zero to a queryable API: dedicated Postgres database, row-level security, realtime and TypeScript type generation included — no credit card required. **Prompt for your coding agent** ```text Set up Aurabase in this app by following this page: https://aurabase.dev/en/docs/getting-started.md Documentation: read https://aurabase.dev/llms.txt first. Every docs page is also available as Markdown: add .md to its URL, for example (the same works for every page): https://aurabase.dev/en/docs/getting-started.md Client: install @aurabase/aurabase-js and create the client with createClient(NEXT_PUBLIC_AURABASE_URL, NEXT_PUBLIC_AURABASE_ANON_KEY). Keep AURABASE_SERVICE_ROLE_KEY on the server: never put it in client code. Project access: to read the schema and run SQL, start the Aurabase MCP server over stdio (82 tools with a project key): npx -y -p @aurabase/mcp-server aurabase-mcp --url https://.aurabase.dev --project-id --service-role-key aura_sk_… The project id is in Studio › Settings › General. The service role key is shown once when the project is created; regenerate it in Studio › Settings › Connection if you lost it. ``` ## Quickstart Install the SDK, create the client and read your first rows. ### 1. Install the SDK Add the SDK to your project. The Rust tab installs the `aurabase` crate; the cURL tab checks that your project URL responds. **pnpm** ```bash tab="pnpm" pnpm add @aurabase/aurabase-js ``` **npm** ```bash tab="npm" npm install @aurabase/aurabase-js ``` **bun** ```bash tab="bun" bun add @aurabase/aurabase-js ``` **Rust** ```bash tab="Rust" cargo add aurabase tokio serde ``` **Python (soon)** ```bash tab="Python (soon)" # not published on PyPI yet: use the cURL / REST tab for now ``` **Dart / Flutter (soon)** ```bash tab="Dart / Flutter (soon)" # not published on pub.dev yet: use the cURL / REST tab for now ``` **cURL / REST** ```bash tab="cURL / REST" curl -s "$NEXT_PUBLIC_AURABASE_URL/health" ``` ### 2. Create the client Create the client with your project URL and anon key, both in Studio › Settings › Connection. Keep the service role key on the server. **TypeScript** ```typescript tab="TypeScript" import { createClient } from '@aurabase/aurabase-js' const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, ) ``` **Rust** ```rust tab="Rust" use aurabase::AuraClient; let aura = AuraClient::new( &std::env::var("NEXT_PUBLIC_AURABASE_URL")?, &std::env::var("NEXT_PUBLIC_AURABASE_ANON_KEY")?, None ); ``` **Python (soon)** ```python tab="Python (soon)" import os from aurabase import create_client aura = create_client( os.environ["NEXT_PUBLIC_AURABASE_URL"], os.environ["NEXT_PUBLIC_AURABASE_ANON_KEY"] ) ``` **Dart / Flutter (soon)** ```dart tab="Dart / Flutter (soon)" import 'dart:io'; import 'package:aurabase/aurabase.dart'; final aura = AuraClient( Platform.environment['NEXT_PUBLIC_AURABASE_URL']!, Platform.environment['NEXT_PUBLIC_AURABASE_ANON_KEY']!, ); ``` **cURL / REST** ```bash tab="cURL / REST" # Values from Studio › Settings › Connection export NEXT_PUBLIC_AURABASE_URL="https://.aurabase.dev" export NEXT_PUBLIC_AURABASE_ANON_KEY="aura_anon_…" ``` ### 3. Query the database Read up to 10 rows from `todos`. The table is created in the "Create a table" section below; until it exists, `error` is set. **TypeScript** ```typescript tab="TypeScript" // `todos` is created in "Create a table" below const { data, error } = await aura .from('todos') .select('id, title, done') .limit(10) console.log(data, error) ``` **Rust** ```rust tab="Rust" let res = aura .from::("todos") .select("id,title,done") .limit(10) .execute() .await?; let rows = res.into_result()?.unwrap_or_default(); // an HTTP error (bad key, RLS, missing table) becomes Err ``` **Python (soon)** ```python tab="Python (soon)" response = aura.table("todos").select("id, title, done").limit(10).execute() print(response.data) ``` **Dart / Flutter (soon)** ```dart tab="Dart / Flutter (soon)" final response = await aura .from('todos') .select('id, title, done') .limit(10); ``` **cURL / REST** ```bash tab="cURL / REST" curl -s "$NEXT_PUBLIC_AURABASE_URL/v1/db/todos?select=id,title,done&limit=10" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" ``` ## Prerequisites We assume that `Node.js ≥ 20` is installed and a POSIX terminal is within range. No local database is required: Aurabase provisions a dedicated Postgres database for each project. > **Note:** > > Are you coming from Supabase or Firebase? Most concepts are transposable. See the [migration guide](https://aurabase.dev/en/docs/guides/migration-supabase). ## Installing the SDK The official SDK exposes a typed client for CRUD, auth, realtime and storage. It works the same way in Next.js, React, Node, Bun or Deno. **pnpm** ```bash tab="pnpm" filename="terminal" # Recommended pnpm add @aurabase/aurabase-js ``` **npm** ```bash tab="npm" filename="terminal" npm install @aurabase/aurabase-js ``` **yarn** ```bash tab="yarn" filename="terminal" yarn add @aurabase/aurabase-js ``` **bun** ```bash tab="bun" filename="terminal" bun add @aurabase/aurabase-js ``` The package name includes the `@aurabase/` scope. The package `aurabase-js` without a scope is not maintained by Aurabase: do not install it. > **Tip:** > > The SDK directly includes `@aurabase/aurabase-js/ssr` (`createServerClient`) export for Next.js (App Router, Server Actions, Middleware), Remix, Nuxt and SvelteKit with automatic session cookie management and anti-truncation chunking. ## Create a project Create a project from the Studio. When it becomes active, the Studio shows a **Copy your keys now** panel with a ready-to-use `.env.local` (copy it or download it): the `service_role` key appears there **once**, only its hash is kept afterwards. **Settings › Connection** later shows the project URL and the public anon key; if you lost the `service_role` key, regenerate it there (the previous one is revoked). `NEXT_PUBLIC_AURABASE_URL` and `NEXT_PUBLIC_AURABASE_ANON_KEY` can be published on the client side; `AURABASE_SERVICE_ROLE_KEY` stays strictly on the server side. ```bash filename=".env.local" NEXT_PUBLIC_AURABASE_URL=https://.aurabase.dev NEXT_PUBLIC_AURABASE_ANON_KEY=aura_anon_… AURABASE_SERVICE_ROLE_KEY=aura_sk_… ``` | Schema | Access | Contains | | --- | --- | --- | | `project_{uuid}` | You | Your application tables | | `project_{uuid}_auth` | System | `users`, `sessions`, `oauth_accounts`, `mfa` | | `project_{uuid}_storage` | System | `buckets`, `objects`, `rls_policies` | | `project_{uuid}_platform` | System | `functions`, `jobs`, `cron_jobs`, `api_keys` | > **Prefer the terminal?** > > The whole path also works from the CLI (see [CLI](https://aurabase.dev/en/docs/cli) for the installation): `aura projects create` waits until the project is ready and prints the URL and the keys once. > > ```bash filename="terminal" > aura login > aura projects create todos-app --json > project.json # waits until the project is active > aura link --project-id "$(jq -r .id project.json)" > export NEXT_PUBLIC_AURABASE_URL="$(jq -r .url project.json)" > export AURABASE_SERVICE_ROLE_KEY="$(jq -r .service_role_key project.json)" > aura db raw "create table todos (id bigint generated always as identity primary key, title text not null, done boolean not null default false, user_id uuid not null default auth.uid(), created_at timestamptz not null default now())" > aura db raw "create policy todos_own_read on todos for select to aura_authenticated using (auth.uid() = user_id)" > aura db raw "create policy todos_own_insert on todos for insert to aura_authenticated with check (auth.uid() = user_id)" > aura db table realtime todos on > aura db raw "select count(*) from todos" --as authenticated --user # see what that user sees > ``` > **Service role key** > > **Never include `AURABASE_SERVICE_ROLE_KEY` in a client bundle.** It bypasses all RLS policies, and the API refuses it from a browser (`401 SECRET_KEY_IN_BROWSER`). Reserve it for server calls (route handlers, server actions, jobs). ## Create a table Open **Database** in the Studio, click **SQL Editor** (the link at the bottom of the tables panel) and run this script. Row-level security is enabled on every table: the first two policies let each signed-in user read and create their own rows, the third one is an **example** that lets visitors read the table so you can see your first rows without signing in. Policies target the `aura_authenticated` role (`aura_anon` for visitors). ```sql filename="todos.sql" create table todos ( id bigint generated always as identity primary key, title text not null, done boolean not null default false, user_id uuid not null default auth.uid(), created_at timestamptz not null default now() ); create policy "todos_own_read" on todos for select to aura_authenticated using (auth.uid() = user_id); create policy "todos_own_insert" on todos for insert to aura_authenticated with check (auth.uid() = user_id); -- Example only: any visitor can read every todo. Drop it before production: -- drop policy "todos_public_read" on todos; create policy "todos_public_read" on todos for select to aura_anon using (true); ``` Then generate the TypeScript types of your schema (the command reads `.env.local`): ```bash filename="terminal" npx @aurabase/gen --out lib/aurabase.types.ts ``` ## First call Create a reusable Aurabase client by reading keys from environment variables, then query your first table. The paths below are relative to the root of your app: if your project uses a `src/` directory, put `lib/`, `components/` and `app/` inside it, so that the `@/` import alias resolves. ```typescript filename="lib/aurabase.ts" import { createClient } from '@aurabase/aurabase-js' import type { Database } from './aurabase.types' export const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, ) ``` Then, in a route handler or a server component: ```typescript filename="app/api/todos/route.ts" import { aura } from '@/lib/aurabase' export async function GET() { const { data, error } = await aura .from('todos') .select('id, title, done') .order('created_at', { ascending: false }) .limit(10) if (error) throw error return Response.json(data) } ``` > **Tip:** > > This returns the rows of the table, including without a signed-in user, thanks to the example policy `todos_public_read`. Without it (once you dropped it, as you should before production) a visitor gets `[]`: the other policies only open rows to `aura_authenticated`, so sign a user in first with `aura.auth.signInWithPassword({ email, password })` (see [Ready-made sign-in pages for Next.js](https://aurabase.dev/en/docs/auth/nextjs-sign-in)). Regenerate the `Database` types with `npx @aurabase/gen` after each schema change. To insert a first row, sign a user up and in, then insert. The `user_id` column defaults to `auth.uid()`: ```typescript filename="scripts/first-row.ts" import { aura } from '../lib/aurabase' async function main() { const email = 'you@example.com' const password = 'a-strong-password' await aura.auth.signUp({ email, password }) // an account that already exists is fine: we sign in next // Without a session the insert below would run as an anonymous visitor and be refused by RLS. const signIn = await aura.auth.signInWithPassword({ email, password }) if (signIn.error) throw signIn.error const { data, error } = await aura.from('todos').insert({ title: 'First todo' }).select() console.log(data, error) } main().catch((err) => { console.error(err) process.exit(1) }) ``` Run it with `tsx`, which resolves the extensionless import and reads `.env.local`: ```bash filename="terminal" pnpm add -D tsx pnpm approve-builds # pnpm 10+: allow esbuild's install script, then run: pnpm exec tsx --env-file=.env.local scripts/first-row.ts ``` > **npm 11 blocks esbuild's install script** > > With npm 11 or later, `npx tsx` fails with « You installed esbuild for another platform » because esbuild's install script is blocked by default. Use pnpm as above, or skip `tsx` and run the script with Node's built-in type stripping (Node 22.6+) after writing the two imports with their extension (`'../lib/aurabase.ts'`, `'./aurabase.types.ts'`): `node --env-file=.env.local --experimental-strip-types scripts/first-row.ts`. > **Email confirmation is on by default** > > A new project requires users to confirm their email before `signInWithPassword` succeeds: without it, `signUp` works and the sign-in returns `EMAIL_NOT_CONFIRMED`. On the local stack the confirmation email is captured by Mailpit: open it with `kubectl -n aurabase-dev port-forward svc/aurabase-mailpit 8025:8025`, then http://localhost:8025. To skip the confirmation while you develop, turn it off with `aura auth settings set email_confirmation_required=false` (or in Studio › Authentication › Configuration). Turn it back on before production: otherwise anyone can sign up with any address. > **Warning:** > > The `service_role` key has no signed-in user, so `auth.uid()` is `NULL` and an insert that relies on the default fails with `NOT_NULL_VIOLATION`. From a server, pass `user_id` explicitly. ## Connect realtime Three auto-negotiated transports: WebSocket, SSE, NATS. Customer chooses the best one based on the network — no configuration necessary. Enable realtime on the table once, with the CLI: ```bash filename="terminal" aura db table realtime todos on ``` or with the HTTP API, from a server (values from `.env.local`): ```bash filename="terminal" curl -X PUT "$NEXT_PUBLIC_AURABASE_URL/v1/db/schema/tables/todos/realtime" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ -d '{"enabled": true}' ``` Then subscribe to changes. A signed-in user receives the rows that its RLS policies let it read, including when the channel was opened before sign-in (it is re-authenticated automatically); a refused subscription reports `CHANNEL_ERROR` with the reason. ```typescript filename="components/LiveTodos.tsx" 'use client' import { aura } from '@/lib/aurabase' import { useEffect } from 'react' export function LiveTodos() { useEffect(() => { const channel = aura.realtime .channel('todos') .on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (change) => console.log(change.eventType, change.new), ) .subscribe((status, err) => { // In development React StrictMode mounts, unmounts and re-mounts the component: // the first CLOSED comes from that clean-up and is expected. if (status === 'SUBSCRIBED') console.log('realtime connected') if (status === 'CHANNEL_ERROR') console.error('realtime refused:', err?.message) }) return () => { void channel.unsubscribe() } }, []) return null } ``` > **Tip:** > > Subscriptions are multiplexed over a single TCP connection. Open as many as you need — zero additional network costs. ## To go further - [Architecture](https://aurabase.dev/en/docs/architecture): The 8 services and their partitioning by project. - [Database](https://aurabase.dev/en/docs/database): Schemas, migrations, TypeScript codegen, RLS. - [Authentication](https://aurabase.dev/en/docs/auth): OAuth 15+, MFA, granular RBAC. - [Edge Functions](https://aurabase.dev/en/docs/functions): WASM multi-runtime, cron, DLQ, AI Gateway. --- ### Architecture Source: https://aurabase.dev/en/docs/architecture.md # Architecture > How a request travels from your client to Postgres, how organizations and projects are isolated, and how services scale. ## One backend, eight services Aurabase is a Rust monorepo that builds eight Axum services. Each service has its own port and its own `/v1//…` routes, and services talk to each other over NATS request/reply. All traffic from your applications goes through one gateway. A service can restart, crash or be deployed on its own. The gateway tracks the health of each service with a circuit breaker: after 5 failures within 60 seconds, it answers `503` for that service for 30 seconds, then tries it again. ## Services and responsibilities Each service owns one domain, its own SQL migrations and its own data. Your applications reach them only through the gateway. | Service | Domain | Responsibilities | | --- | --- | --- | | `aura-gateway` | API gateway | Proxy, authentication middleware, rate limiting, circuit breaker | | `aura-auth` | Authentication | Sign-up, sign-in, OAuth 2.1, TOTP MFA and WebAuthn, sessions, JWKS | | `aura-db` | Database | CRUD over PostgREST, versioned migrations, type generation, schema management | | `aura-realtime` | Realtime | WebSocket, SSE, event relay, presence, Postgres change data capture | | `aura-storage` | Storage | S3-compatible object storage, multipart upload, signed URLs, image transforms | | `aura-functions` | Edge Functions | WASM and Deno runtimes, cron, asynchronous job queue, dead-letter queue | | `aura-notifications` | Notifications | Transactional email (SMTP), SMS, mobile push, HMAC-signed webhooks | | `aura-ai` | AI Gateway | LLM inference through one endpoint, embeddings, RAG with pgvector | ## Isolation by organization and project Each organization gets its own PostgreSQL cluster, provisioned with CloudNativePG (CNPG) in a Kubernetes namespace reserved for it. No cluster, namespace or connection pool is shared between two organizations. The cluster's capacity (vCPU, memory, replicas) follows the organization's plan. Inside that cluster, each project gets its own Postgres database, split into four schemas. Each project has its own connection role, which is a member only of its own roles. Rights on a project's schemas are granted to those roles and never to `PUBLIC`. The gateway sets the connection `search_path` from the project in the client's JWT, and application tables are protected by row-level security (RLS). On the enterprise offer, a project can also get a dedicated CNPG cluster in its own namespace. Isolation then comes from the physical separation of clusters, in addition to permissions. | Schema | Owner | Content | | --- | --- | --- | | `project_{uuid}` | you | Your application tables | | `project_{uuid}_auth` | `aura-auth` | `users`, `sessions`, `oauth_accounts`, `mfa` | | `project_{uuid}_storage` | `aura-storage` | `buckets`, `objects`, `rls_policies` | | `project_{uuid}_platform` | platform | `functions`, `jobs`, `cron`, `api_keys`, `webhooks` | Three consequences follow: - **No cross-tenant access.** Two organizations never share a cluster, a namespace or a connection pool. - **Independent migrations.** Each project migrates and rolls back on its own. - **Plain export.** `pg_dump --schema='project_*'` dumps a project's data, extensions and policies. > **Shared schema** > > The `aura_console` schema is shared. It holds the `projects` table and the Studio sessions. No application data goes through it. ## From curl to Postgres The gateway checks every request before routing it. This is the path of `GET /v1/db/{projectId}/devices` from a REST client: ```text filename="request path" 1. TLS termination client → aura-gateway 2. Request ID and tracing request_id and trace_id are attached to the request 3. Rate limit token bucket, answers 429 when the limit is reached 4. Authentication JWT decoded and claims checked: sub, project_id, role 5. Circuit breaker the target service is HEALTHY, so the request goes through 6. Execution search_path set to the project's schemas, then the query runs under RLS ``` Each step writes structured logs with `tracing`, correlated by `request_id`. ## Scaling Services are stateless. To add capacity, start another replica of the binary and connect it to NATS. It joins the cluster and serves requests when it is ready. There is no leader election and no distributed coordination. ## To go further - [Database](https://aurabase.dev/en/docs/database): Postgres, schemas, migrations, RLS, TypeScript type generation - [Auth](https://aurabase.dev/en/docs/auth): OAuth, MFA, session lifecycle, RBAC - [Realtime](https://aurabase.dev/en/docs/realtime): WebSocket, SSE, presence, Postgres changes - [Storage](https://aurabase.dev/en/docs/storage): S3-compatible buckets, transforms, signed URLs - [Edge Functions](https://aurabase.dev/en/docs/functions): WASM and Deno runtimes, cron, dead-letter queue - [Conventions](https://aurabase.dev/en/docs/conventions): Naming of schemas, columns and RLS policies --- ### Agreements Source: https://aurabase.dev/en/docs/conventions.md # Agreements > Naming of schemas, columns, RLS policies, auth helpers, indexes. Stable, documented conventions so your team has one way to name things. ## One prefix per domain Each project receives four subschemas prefixed `project_{uuid}`. Your business tables go into the main schema; never create objects in system schemas. | Schema | Owner | Use | | --- | --- | --- | | `project_{uuid}` | you | Tables, views and business functions. This is the schema your unqualified SQL (`create table posts …`) lands in; it is named `public` only on the SQL you export with `aura db backup download` and `schema/dump`, which are portable. | | `project_{uuid}_auth` | `aura-auth` | Users, sessions and MFA. Do not modify. | | `project_{uuid}_storage` | `aura-storage` | Buckets, objects and storage policies | | `project_{uuid}_platform` | platform | Functions, jobs, cron and secrets | ## snake_case, plural, id uuid - **Plural** tables: `posts`, `comments`, `invoices` - **Columns** in `snake_case`: `created_at`, `user_id`, `last_seen_at` - **Primary keys** `id uuid primary key default gen_random_uuid()` — no `uuid_generate_v4()`. Prefer `uuid` over `bigint generated always as identity` when ids are exposed to clients (not guessable, no 2^53 precision issue in JavaScript); an identity column works too, and backups and restores handle it. - **Timestamps** `timestamptz`, never `timestamp` naked - **FKs** suffixed `_id`: `author_id`, `tenant_id` - **Booleans** prefixed `is_` or `has_` - **No column `project_id`** — the schematic is already the insulator ```sql filename="exemple" create table posts ( id uuid primary key default gen_random_uuid(), author_id uuid not null references users(id) on delete cascade, title text not null, is_published boolean not null default false, created_at timestamptz not null default now() ); ``` > **Warning:** > > Never add a `project_id` column. Isolation already comes from the schema, and such a column would add indexes without adding security. ## Three functions injected into each session The gateway opens Postgres connections with `request.jwt.claims` specified. The three helpers below read these claims and can be used anywhere in your policies. - `auth.uid()` — uuid of the current user, NULL if anon - `auth.role()` — text · `aura_anon` / `aura_authenticated` / `aura_service_role` (through the SDK and REST), `anon` / `authenticated` (through `aura db raw --as`) - `auth.tenant()` — uuid of the current tenant (multi-tenant RBAC) - `auth.has_role(name)` — boolean · true if the user has this application role - `auth.email()` — text · user email, read from the JWT - `auth.claim(key)` — jsonb · raw access to a custom claim ## A predictable name, an operation, a role Convention: `__`. Example: `posts_own_read`, `orders_admin_delete`. Always specify `to aura_authenticated` or `to aura_anon`. ```sql filename="naming" -- ✓ Good: table_scope_op create policy "posts_own_read" on posts for select … create policy "orders_admin_all" on orders for all … -- ✗ To avoid create policy "allow_stuff" -- too vague create policy "new_policy_42" -- not descriptive ``` ## Naming and when to index - **Name**: `idx_
_` or `uq_
_` (unique) - **Always index**: FKs, frequent `filter`/`order_by` columns, `where` of RLS policies - **Do not index**: Boolean columns with high cardinality low (use partial index), tables < 1000 rows - **pgvector**: `using hnsw` for > 100k vectors, `ivfflat` otherwise ## To go further - [Row-Level Security](https://aurabase.dev/en/docs/database/rls): Complete patterns with auth.uid() and auth.tenant(). - [Architecture](https://aurabase.dev/en/docs/architecture): Why schema-per-project rather than row-level tenant. - [Performance](https://aurabase.dev/en/docs/database/performance): Indexes, EXPLAIN ANALYZE, slow queries. - [Database](https://aurabase.dev/en/docs/database): CRUD SDK on top of Postgres. --- ### Products Source: https://aurabase.dev/en/docs/products.md # Products > Each product has its own section in the docs: an overview, then guides and reference pages when they exist. - [Database](https://aurabase.dev/en/docs/database): Dedicated Postgres per project, row-level security, NoSQL documents and GraphQL - [Auth](https://aurabase.dev/en/docs/auth): Sign-in methods, sessions, MFA and roles, carried in JWTs that your policies read - [Realtime](https://aurabase.dev/en/docs/realtime): Database changes, broadcast and presence over one WebSocket connection - [Storage](https://aurabase.dev/en/docs/storage): Files in S3-compatible buckets, with signed URLs, image transforms and path policies - [Edge Functions](https://aurabase.dev/en/docs/functions): Server-side TypeScript and WASM next to your data, with jobs, cron and secrets - [Notifications](https://aurabase.dev/en/docs/notifications): Email, SMS, push and signed webhooks from one SDK - [AI Gateway](https://aurabase.dev/en/docs/ai): One endpoint for several model providers, with embeddings and RAG - [Vault](https://aurabase.dev/en/docs/vault): Field-level encryption of secrets and sensitive data - [Cron](https://aurabase.dev/en/docs/cron): Scheduled runs of an Edge Function from a cron expression --- ### Database Source: https://aurabase.dev/en/docs/database.md # Database > What the Database product gives a project, how your code reaches it, and where to go next: first steps, concepts and task guides. ## What you get Each project has its own PostgreSQL 18 database. Your tables live in one schema of that database, named after the project, and the platform keeps its own data (users, files, settings) in separate schemas that your code does not reach. ```bash verify="version" aura db raw "select current_setting('server_version_num')::int / 10000 as postgres_major" ``` ```text expect="version" postgres_major ────────────── 18 ℹ 1 row(s). ``` - **Row level security by default.** Every table created through Aurabase (SDK table API, `aura db raw`, migrations, the Studio) gets row level security enabled. Until you add a policy, the public key reads no row. - **Plain PostgreSQL.** Views, functions, triggers, indexes and policies are standard PostgreSQL objects. Thirteen extensions are installed when a project is created on the cluster of its organization, and `pg_graphql` is installed when you [enable GraphQL](https://aurabase.dev/en/docs/graphql). - **Isolated by role.** Each kind of caller reaches PostgreSQL as a different role: `aura_anon` for the public key, `aura_authenticated` for a signed-in user, a role that bypasses RLS for the `service_role` key. Policies read the user from `auth.uid()`. - **Branches.** `aura branch create` copies a project, schema and rows, into a new project with its own URL and keys. It is a copy made at creation time, not a live replica. ## Three ways in ```text filename="request paths" Browser, server ──▶ SDK or REST ──▶ gateway ──▶ PostgREST of the project ──▶ PostgreSQL CLI, backend, CI ──▶ aura db raw ──▶ gateway ──▶ aura-db (SQL check) ──▶ PostgreSQL psql, ORM, BI ──▶ TLS :5432 ──▶ router ──▶ pooler of the cluster ──▶ PostgreSQL ``` The first path is the one your application uses. The second runs SQL with the `service_role` key, after a check that refuses a list of statements. The third is a plain PostgreSQL connection with a role of its own. [How a request reaches Postgres](https://aurabase.dev/en/docs/database/request-flow) follows each path step by step. ## Start here - [Quickstart](https://aurabase.dev/en/docs/database/quickstart): A table, a policy, and rows written and read by a signed-in user, in ten minutes. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): SDK, REST, psql or an ORM: which one fits where your code runs. - [Example schema](https://aurabase.dev/en/docs/database/example-schema): The tables, view and function every Database page uses in its examples. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): aura db raw, the /raw endpoint, db.sql(), and the statements they refuse. ## Concepts - [Project isolation](https://aurabase.dev/en/docs/database/project-isolation): One database per project, schemas, and what keeps projects apart. - [How a request reaches Postgres](https://aurabase.dev/en/docs/database/request-flow): Gateway, PostgREST, aura-db and the pooler, and where the claims come from. - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): What each key becomes inside PostgreSQL, and which roles bypass RLS. - [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling): Who pools connections, and the limits of each plan. - [Shared and dedicated clusters](https://aurabase.dev/en/docs/database/clusters): The cluster of your organization, and the dedicated cluster of Team and Enterprise. - [How extensions are installed](https://aurabase.dev/en/docs/database/extensions-model): Installed at creation, allowed on request, and why CREATE EXTENSION is refused. ## Guides and reference - [Row-level security](https://aurabase.dev/en/docs/database/rls): Owner, multi-tenant and organization policies. - [Query with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): Filters, joins, inserts and updates from JavaScript. - [Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types): Types for tables, views and functions from the live schema. - [Performance audit](https://aurabase.dev/en/docs/database/performance): Slow queries and indexes. - [Database CLI reference](https://aurabase.dev/en/docs/database/cli): Every aura db command with its options. - [NoSQL document store](https://aurabase.dev/en/docs/nosql): The MongoDB engine for projects that need it. - [REST API](https://aurabase.dev/en/docs/api-rest): The HTTP surface behind the SDK, for Database, Auth and Storage. - [Conventions](https://aurabase.dev/en/docs/conventions): Naming of schemas, columns and policies, and the auth helpers. - [Architecture](https://aurabase.dev/en/docs/architecture): How aura-db fits among the services of the platform. - [Migrate from Supabase](https://aurabase.dev/en/docs/guides/migration-supabase): Move a Supabase project, schema, data and policies. ## In the Studio The **Database** section of a project opens the table editor of a PostgreSQL project, or the collections of a MongoDB project. Its pages: ```text filename="Studio pages" //database opens the table editor (PostgreSQL) or the collections (MongoDB) //database/sql/table-editor browse and edit rows, create tables and columns //database/sql/editor SQL editor (the same endpoint as aura db raw) //database/sql/schema tables, views and functions of the project schema //database/extensions installed extensions //database/backups backups and restores ``` The direct connection card (host, role, password) is under **Settings › Connection**, and the API keys under **Settings › API keys**. --- ### Quickstart Source: https://aurabase.dev/en/docs/database/quickstart.md # Quickstart > You will create a PostgreSQL table, see that the public key cannot read it, add a policy, and read and write your own rows from Node.js. Every output on this page was captured on a real project. ## What you will build A `notes` table where each signed-in user reads and writes only their own notes. At the end you will have: - a project linked to your working folder; - a table with row level security, which Aurabase turns on for every table you create; - an owner policy written in SQL; - a Node.js script that signs a user in, inserts a note and reads it back with `@aurabase/aurabase-js`. ## Prerequisites - The `aura` CLI, signed in to your account: `aura login`. - Node.js 20 or later, and a folder with the SDK installed: `npm install @aurabase/aurabase-js`. The scripts below use top-level `await`: run them as ES modules (`"type": "module"` in `package.json`) with `npx tsx .ts`. This tutorial does not use the [example schema](https://aurabase.dev/en/docs/database/example-schema): it creates its own table and removes it at the end. ## 1. Create and link a project Create a project, then link the current folder to it. The second command writes `aurabase.toml`, which the `aura db` commands read to know which project to work on. ```bash aura projects create my-app aura link ``` Output of `aura projects create` (the id, the slug and the keys of your project differ): ```text » Creating project 'my-app'... ✔ Project created: my-app (slug: my-app-utsrqfcx) ✔ Project provisioned and ready to use! Project ID : 41fd6f07-3acf-48cf-9eb5-d665ce99a849 Slug : my-app-utsrqfcx Project URL : http://my-app-utsrqfcx.localhost:8080 ⚠ Project API keys (shown only once): • anon (front-end) : aura_anon_… • service_role (backend) : aura_sk_… ``` **Copy the two keys now: they are shown only once.** If you lose them, create new ones in the Studio under **Settings › API keys** or with `aura db api-keys create --scope anon`. Then export the project URL and the keys in your shell; the commands and scripts below read them from the environment. ```bash export AURABASE_URL=http://my-app-utsrqfcx.localhost:8080 export AURABASE_ANON_KEY=aura_anon_… export AURABASE_SERVICE_ROLE_KEY=aura_sk_… ``` - The **anon** key is public: it can go in a browser or a mobile app. Row level security decides what it can read. - The **service_role** key is secret: it bypasses row level security. Keep it on a server or in your terminal. The `aura db` commands that read or change data use it. ## 2. Create a table `aura db raw` runs SQL on the linked project. `user_id` takes the id of the signed-in user by default: `auth.uid()` reads it from the request. ```bash verify="create-table" aura db raw "create table notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null, created_at timestamptz not null default now() )" ``` ```text expect="create-table" ℹ No results (0 rows). ``` Aurabase enabled row level security on `notes` when the table was created. With RLS on and no policy, PostgreSQL returns no row to the public roles instead of an error. ## 3. Read it with the public key Save this script as `read-public.ts` and run it with `npx tsx read-public.ts`. Each SDK call returns an object with `data` (the rows), `error` (`null` on success), `meta` and `count`. ```typescript verify="public-read" needs="create-table" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const { data, error, meta } = await aura.from('notes').select('body') console.log(data, error) console.log(meta?.hint) ``` ```text expect="public-read" [] null 0 rows returned. The table "notes" may be empty, or it has row-level security and no SELECT policy lets the role "aura_anon" read its rows (PostgreSQL returns nothing instead of an error). To check what this role can see: aura db raw "select * from notes" --as anon. To open rows to it, add a policy, for example: create policy "notes_read" on notes for select to aura_anon using (true); — guide: /docs/database/rls ``` The request succeeded, but no row came back. The public key reaches PostgreSQL as the role `aura_anon`, and no policy lets that role read `notes`. ## 4. Add a policy Let signed-in users (`aura_authenticated`) read, insert, update and delete the rows whose `user_id` is their own id: ```bash verify="policy" needs="create-table" aura db raw "create policy notes_owner on notes for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)" ``` ```text expect="policy" ℹ No results (0 rows). ``` `using` filters the rows a user can read, update or delete; `with check` rejects an insert or update that would write a row for another user. ## 5. Write and read as a user A new project requires users to confirm their email address before they can sign in. For this tutorial, turn the confirmation off so that a test user can sign in at once: ```bash verify="no-confirmation" aura auth settings set email_confirmation_required=false ``` ```text expect="no-confirmation" ✔ 1 setting(s) updated. ``` Save this script as `notes.ts` and run it. It signs a new user up, signs it in, inserts a note without `user_id` (the default fills it), reads the notes back, then reads them again with a client that has no user. ```typescript verify="as-user" needs="policy,no-confirmation" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `quickstart-${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 signIn = await aura.auth.signInWithPassword({ email, password }) if (signIn.error) throw signIn.error const inserted = await aura.from('notes').insert({ body: 'My first note' }).select('body') console.log('insert:', inserted.data, inserted.error) const mine = await aura.from('notes').select('body') console.log('as the user:', mine.data, mine.error) const visitor = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const others = await visitor.from('notes').select('body') console.log('without a user:', others.data, others.error) ``` ```text expect="as-user" insert: [ { body: 'My first note' } ] null as the user: [ { body: 'My first note' } ] null without a user: [] null ``` The same anon key now returns rows, because the request carries the access token of a signed-in user: the gateway hands it to PostgreSQL as the role `aura_authenticated` with the user id in the claims that `auth.uid()` reads. ## Result You have a table that a browser can use with the public key, and that shows each user only their own rows. Check it from the CLI as the service role, which bypasses the policy and sees every row: ```bash verify="result" needs="as-user" aura db raw "select body from notes" ``` ```text expect="result" body ───────────── My first note ℹ 1 row(s). ``` ## Clean up Drop the table; its policy goes with it. ```bash verify="clean-up" needs="create-table" aura db raw "drop table notes" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` Before real users sign up, turn email confirmation back on (it is the default of every project): ```bash aura auth settings set email_confirmation_required=true ``` The test users stay in the project. Delete them in the Studio under **Auth**, or with `aura auth users list` then `aura auth users delete `. ## Next steps - [Connect to your database](https://aurabase.dev/en/docs/database/connect): SDK, REST, psql or an ORM: which connection fits where your code runs. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): aura db raw, the REST endpoint and db.sql(), and what they refuse. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Owner, multi-tenant and organization policies. - [Query with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): Filters, joins, inserts and updates from JavaScript. - [Example schema](https://aurabase.dev/en/docs/database/example-schema): The tables every Database page uses in its examples. --- ### Connect to your database Source: https://aurabase.dev/en/docs/database/connect.md # Connect to your database > Find your project URL and keys, choose between the SDK, the REST API and a direct PostgreSQL connection, and get a working connection string for psql or an ORM. Every project can be reached three ways: the JavaScript SDK, the REST API it calls, and a direct PostgreSQL connection for tools that speak the PostgreSQL protocol. This page tells you which one to use and how to set each up. ## Choose a connection | Where your code runs | Use | Why | | --- | --- | --- | | Browser, mobile app | SDK with the **anon** key | HTTPS only, no database password to ship. Row level security decides what each user sees. | | Serverless function, edge runtime | SDK or REST, anon key with the user's token, or the **service_role** key | Each call is an HTTP request: no connection to open, keep or pool on your side. | | Long-running backend (API server, worker) | SDK or REST; direct connection if you need an ORM or SQL features the REST API does not offer | The direct connection gives you plain PostgreSQL, with your own pool. | | Schema changes from a terminal or CI | `aura db raw`, or SQL migrations with `aura db migration` | Runs as the project administrator role; RLS is enabled on every table it creates. | | psql, a BI tool, a database GUI | Direct connection | Standard PostgreSQL protocol over TLS. | | Export (schema and rows) | Direct connection with a PostgreSQL 18 `pg_dump` | See [Export with pg_dump](#pg-dump): dump as the administrator role of the project. | The direct connection exists only where the deployment publishes the PostgreSQL port (5432). When it does not, `aura db connection` says so: `This deployment does not publish direct PostgreSQL access (port 5432). Use the SDK, the REST API, the Studio SQL editor, or aura db raw.` ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - For the direct connection: `psql` (any recent version connects; `pg_dump` must be version 18). ## Project URL and keys The SDK and the REST API need two values, printed by `aura projects create` and shown in the Studio under **Settings › Connection** and **Settings › API keys**: | Value | Example | Where it goes | | --- | --- | --- | | Project URL | `http://my-app-utsrqfcx.localhost:8080` on a local stack | `createClient(url, key)`, base URL of every REST call | | anon key | `aura_anon_…` | Public. Browser and mobile code. Reaches PostgreSQL as the role `aura_anon`, or `aura_authenticated` with a signed-in user. | | service_role key | `aura_sk_…` | Secret. Servers, CI, the CLI. Bypasses row level security. Refused from a browser (`401 SECRET_KEY_IN_BROWSER`). | The initial keys are shown once, when the project is created. List them, create others or revoke one with `aura db api-keys list`, `aura db api-keys create --scope anon|authenticated|service_role` and `aura db api-keys revoke `. The [roles and keys](https://aurabase.dev/en/docs/database/roles-and-keys) page explains what each key becomes inside PostgreSQL. ## Connect with the SDK Install `@aurabase/aurabase-js` and create a client with the project URL and a key. The URL is enough to target the project: there is no project id to pass. ```typescript verify="sdk" import { createClient } from '@aurabase/aurabase-js' // In a browser: the anon key. Row level security filters the rows. const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const visitor = await aura.from('todos').select('title') console.log('anon:', visitor.data, visitor.error) // On a server only: the service_role key, which bypasses row level security. const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const all = await admin.from('todos').select('title').eq('done', false).order('title') console.log('service_role:', all.data, all.error) ``` ```text expect="sdk" anon: [] null service_role: [ { title: 'Add a row level security policy' }, { title: 'Create a table' }, { title: 'Invite a teammate' } ] null ``` The anon key gets an empty list, not an error: `todos` has an owner policy and no user is signed in. Sign a user in with `aura.auth.signInWithPassword()` and the same client returns that user's rows, as in the [Quickstart](https://aurabase.dev/en/docs/database/quickstart). ## Connect over REST Any HTTP client works. Send the key in the `apikey` header (or `X-API-Key`); for a signed-in user, add `Authorization: Bearer `. Filters use the `column=operator.value` form. ```bash verify="rest" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=title&done=eq.false&order=title.asc" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" ``` ```text expect="rest" {"data":[{"title":"Add a row level security policy"}, {"title":"Create a table"}, {"title":"Invite a teammate"}],"meta":{}} ``` A read returns at most 1,000 rows, whatever `limit` you ask for. The full list of endpoints is in the [REST API reference](https://aurabase.dev/en/docs/api-rest). ## Connect with psql or an ORM Each project has its own PostgreSQL login role, `proj_` followed by eight hexadecimal characters, and a host of the form `.db.` on port 5432. Show them with: ```bash verify="show" aura db connection ``` Output (your host, database and role differ): ```text » Direct PostgreSQL access • host my-app-utsrqfcx.db.localhost • port 5432 • database project_41fd6f07_3acf_48cf_9eb5_d665ce99a849 • user proj_76c0d308 • psql "postgresql://proj_76c0d308@my-app-utsrqfcx.db.localhost:5432/project_41fd6f07_3acf_48cf_9eb5_d665ce99a849?sslmode=require" ℹ The password is shown only when issued: aura db connection --new-password (this revokes the current one). • TLS is required. Connections go through a transaction pooler: use ?pgbouncer=true with Prisma, and session-level features (LISTEN, advisory locks) do not persist across transactions. ``` The password is issued on demand and shown once: the platform does not keep it in clear, so a lost password is replaced, never recovered. `--new-password` issues one, prints the full connection string, and revokes the previous password (it asks for confirmation unless you pass `--yes`). `--json` prints `host`, `port`, `database`, `user`, `password` and `connection_uri`. Issue a password, keep the connection string in a file that your ORM or scripts load, and run a first query: ```bash verify="direct" aura db connection --new-password --yes --json \ | node -pe '"export DATABASE_URL=\x27" + JSON.parse(require("fs").readFileSync(0, "utf8")).connection_uri + "\x27"' > .env.database source .env.database psql "$DATABASE_URL" -X -A -t -c "select current_database() = current_schema() as same_name, current_setting('server_version_num')::int / 10000 as major" ``` ```text expect="direct" t|18 ``` The database and the schema of the project share the same name, and the server is PostgreSQL 18. Keep `.env.database` out of version control. - **psql, interactively.** `aura connect` opens `psql` on the linked project and lets psql ask for the password. If `DATABASE_URL` is set in your environment, `aura connect` uses it instead. - **Prisma.** Put the connection string in `DATABASE_URL` and add `&pgbouncer=true` to it. Prisma documents this flag, for Prisma ORM 6 and 7, for a PgBouncer pooler in transaction mode that does not track prepared statements. - **Other clients** (node-postgres, Drizzle, SQLx, DBeaver, Metabase): the same connection string, with TLS on (`sslmode=require`). ## Rules of the direct connection - **TLS is required.** A plaintext connection is refused: `FATAL: TLS required: this endpoint does not accept plaintext connections (use sslmode=require)`. - **`sslmode=verify-full` fails on a local stack, by design.** The local certificate is self-signed for `*.db.localhost`, so a client that verifies the chain stops with a message about the missing root certificate (`~/.postgresql/root.crt`). In production the certificate is issued for `*.db.`: if it chains to a public authority, `sslmode=verify-full&sslrootcert=system` checks it against the trust store of the system (PostgreSQL 18 documentation, `sslrootcert`). - **Confined to your project.** The router reads the role name, picks your project's database and forces it, whatever database name you ask for. Presenting your role on another project's host is refused: `FATAL: the requested host does not match this user's project`. - **Transaction pooler on Free and Pro.** On the cluster of your organization the connection goes through PgBouncer in transaction mode: session state does not survive from one transaction to the next. Use `SET LOCAL` inside a transaction, and do not rely on `LISTEN`, session-level advisory locks or named prepared statements. Run long schema migrations with `aura db migration` or `aura db raw` rather than an ORM migration tool, which expects a session connection that this endpoint does not offer. On a dedicated cluster (Team and Enterprise), the connection goes straight to the primary, without the pooler. - **Not a superuser, no RLS bypass.** The `proj_` role reads and writes the tables of your schema, under their row level security policies. It may switch, inside a transaction, to the administrator role of the project, the role `aura db raw` runs as: `BEGIN; SET LOCAL ROLE tenant__admin; …; COMMIT;`, where `` is the project id with underscores instead of dashes. That role owns the tables and bypasses row level security. - **A table created as the administrator role is public until you enable RLS.** The administrator role grants every new table to the public roles, and the hook that enables row level security runs only for SQL sent through Aurabase (`aura db raw`, migrations, the Studio, the table API), not over this connection. Enable RLS in the same transaction as the `CREATE TABLE`: `alter table enable row level security;`. ## Tables created over the direct connection A table created by the `proj_` role does not go through the hook that enables row level security on tables created by Aurabase. The platform closes it instead: the public roles get no privilege on it. The anon key and signed-in users receive `permission denied`, while the `service_role` key, the Studio and your own role read and write it. ```bash verify="private-table" needs="direct" source .env.database psql "$DATABASE_URL" -X -q \ -c "create table direct_notes (id int primary key, body text)" \ -c "insert into direct_notes values (1, 'written over psql')" \ -c "notify pgrst, 'reload schema'" sleep 3 curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/direct_notes?select=body" -H "apikey: $AURABASE_ANON_KEY"; echo curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/direct_notes?select=body" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"; echo ``` ```text expect="private-table" {"error":{"code":"INSUFFICIENT_PRIVILEGE","details":"","message":"permission denied for table direct_notes","request_id":"b58072c9-ec71-4e42-abbf-b9955072cd00","type":"auth_forbidden","upstream_code":"42501"}} {"data":[{"body":"written over psql"}],"meta":{}} ``` `notify pgrst, 'reload schema'` tells the REST API about the new table; without it, the next call answers `TABLE_NOT_FOUND` for a few seconds. To expose such a table to the SDK, turn row level security on first, then grant and add a policy. Never grant a public role on a table whose RLS is off: every holder of the anon key would read it. ```sql alter table direct_notes enable row level security; grant select on direct_notes to aura_authenticated; create policy direct_notes_read on direct_notes for select to aura_authenticated using (true); ``` ## Export with pg_dump `pg_dump` refuses a server newer than itself. With an older client you get: ```text pg_dump: error: aborting because of server version mismatch pg_dump: detail: server version: 18.7 (Debian 18.7-1.pgdg12+2); pg_dump version: 16.15 (Homebrew) ``` Use a PostgreSQL 18 client and limit the dump to your schema with `--schema`: the database also holds the internal schemas of the platform (auth, storage), which the project role cannot lock, and a plain `pg_dump` stops on them with `permission denied`. The `proj_` role does not bypass row level security: a dump of a table that has RLS on stops with `query would be affected by row-level security policy`. Dump as the administrator role of the project with `--role`; it owns the tables and reads every row. The schema, the database and the role all derive from the project id, with underscores instead of dashes: ```bash pg_dump --no-owner \ --role=tenant_41fd6f07_3acf_48cf_9eb5_d665ce99a849_admin \ --schema=project_41fd6f07_3acf_48cf_9eb5_d665ce99a849 \ "$DATABASE_URL" > my-project.sql ``` The file holds the tables, views, functions, policies and rows of your schema. Add `--schema-only` for the structure alone. ## Result One question, how many rows `todos` holds, asked through three doors. The REST API with the `service_role` key and `aura db raw` bypass row level security and count every row; the `proj_` role of the direct connection does not, and the owner policy of `todos` shows it no row because it carries no user id: ```bash verify="result" needs="direct" source .env.database curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=id" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).data.length' aura db raw --json "select count(*)::int as todos from todos" psql "$DATABASE_URL" -X -A -t -c "select count(*) as todos from todos" ``` ```text expect="result" 4 [ { "todos": 4 } ] 0 ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `FATAL: TLS required: this endpoint does not accept plaintext connections (use sslmode=require)` | `sslmode=disable`, or a client without TLS. | Keep `sslmode=require` in the connection string. | | `root certificate file "…/.postgresql/root.crt" does not exist` | `sslmode=verify-full` or `verify-ca` against the self-signed certificate of a local stack. | Use `sslmode=require` locally. | | `FATAL: the requested host does not match this user's project` | The role of one project presented on the host of another. | Take host and role from the same `aura db connection` output. | | `FATAL: SASL authentication failed` | The password was replaced by a later `--new-password`, from the CLI or the Studio. | Issue a new one and update every client that uses it. | | `aborting because of server version mismatch` | `pg_dump` older than 18. | Install a PostgreSQL 18 client. | | `permission denied for table …` (`403 INSUFFICIENT_PRIVILEGE` over the SDK) | The table was created over the direct connection. | Enable RLS, grant, add a policy (see above). | ## Clean up Drop the table created over the direct connection and delete the file that holds the password: ```bash verify="clean-up" needs="direct" source .env.database psql "$DATABASE_URL" -X -q -c "drop table if exists direct_notes" rm .env.database ``` The password stays valid until you issue a new one with `aura db connection --new-password`. ## See also - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): aura db raw, the /raw endpoint and db.sql(). - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): What each key and the proj_ role are inside PostgreSQL. - [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling): Who pools what, and how many connections your plan allows. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies for tables you expose to the SDK. - [Query with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): Filters, joins and writes from JavaScript. --- ### Example schema Source: https://aurabase.dev/en/docs/database/example-schema.md # Example schema > The example schema is a small todo and blog model with row level security. Every Database page runs its snippets against it, so you can replay them on your own project. ## Install it `aura db seed --example docs` sends the schema to the linked project as one SQL request. On a linked project the request goes through the data plane, so the command needs the `service_role` key of the project in `AURABASE_SERVICE_ROLE_KEY`. Without it the command stops with `Error: AURABASE_SERVICE_ROLE_KEY is not set.` ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… ``` ```bash verify="seed" aura db seed --example docs ``` ```text expect="seed" » Seeding example schema 'docs'... • Installing on linked project 41fd6f07-3acf-48cf-9eb5-d665ce99a849... ✔ Example schema 'docs' installed. ``` The command is idempotent: it uses `create table if not exists`, `create or replace` and inserts only the rows that are missing, so you can run it again at any time. Only `docs` is accepted as a name; any other value fails with `unknown example '' (available: docs)`. The file never uses a statement that `aura db raw` refuses (no `CREATE EXTENSION`, no `SET`, no explicit transaction), so it installs on any PostgreSQL project. Its source is `aura-cli/src/examples/docs.sql` in the Aurabase repository. ## Tables ```bash verify="tables" needs="seed" aura db table list ``` ```text expect="tables" » Project tables • org_members [RLS] org_id, user_id, role, created_at • orgs [RLS] id, slug, name, created_at • posts [RLS] id, user_id, title, body, published, created_at • profiles [RLS] id, username, display_name, created_at • todos [RLS] id, user_id, title, done, created_at ℹ 5 table(s). ``` | Table | Column | Type | Default and constraints | | --- | --- | --- | --- | | `profiles` | `id` | `uuid` | primary key | | | `username` | `text` | not null, unique | | | `display_name` | `text` | nullable | | | `created_at` | `timestamptz` | not null, default `now()` | | `orgs` | `id` | `bigint` | `generated always as identity`, primary key | | | `slug` | `text` | not null, unique | | | `name` | `text` | not null | | | `created_at` | `timestamptz` | not null, default `now()` | | `org_members` | `org_id` | `bigint` | not null, references `orgs (id)` on delete cascade | | | `user_id` | `uuid` | not null | | | `role` | `text` | not null, default `'member'` | | | `created_at` | `timestamptz` | not null, default `now()` | | | | | primary key `(org_id, user_id)` | | `posts` | `id` | `bigint` | `generated always as identity`, primary key | | | `user_id` | `uuid` | not null, index `posts_user_id_idx` | | | `title` | `text` | not null | | | `body` | `text` | nullable | | | `published` | `boolean` | not null, default `false` | | | `created_at` | `timestamptz` | not null, default `now()` | | `todos` | `id` | `bigint` | `generated always as identity`, primary key | | | `user_id` | `uuid` | not null, index `todos_user_id_idx` | | | `title` | `text` | not null | | | `done` | `boolean` | not null, default `false` | | | `created_at` | `timestamptz` | not null, default `now()` | `user_id` is a plain `uuid` column, without a foreign key to the users of the project: the demo rows belong to two made-up users. ## View and function | Object | Definition | Who can use it | | --- | --- | --- | | View `open_todos` | `select id, user_id, title, created_at from todos where not done` | Anyone who can read `todos`. A view created through Aurabase runs with `security_invoker`, so the policies of `todos` apply to the reader. | | Function `todo_count(p_user uuid) returns bigint` | `language sql stable`, `select count(*) from todos where user_id = p_user`, `SECURITY INVOKER` | Signed-in users only: `grant execute on function todo_count(uuid) to aura_authenticated`. The anon key gets `403 INSUFFICIENT_PRIVILEGE`. | Because the function is `SECURITY INVOKER`, it counts only the rows the caller is allowed to see. A signed-in user who has no todo yet gets `0`, even for the id of a demo user. ```sql verify="count-service" needs="seed" select todo_count('00000000-0000-4000-8000-0000000000a1') as alice, todo_count('00000000-0000-4000-8000-0000000000b2') as bob ``` ```text expect="count-service" alice │ bob ──────┼───── 3 │ 1 ℹ 1 row(s). ``` `aura db raw` runs with the `service_role` key, which bypasses row level security: that is why it sees the rows of both demo users. ```typescript verify="count-anon" needs="seed" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const { data, error } = await aura.rpc('todo_count', { p_user: '00000000-0000-4000-8000-0000000000a1' }) console.log(data, error?.status, error?.code) ``` ```text expect="count-anon" null 403 INSUFFICIENT_PRIVILEGE ``` ## Row level security and grants Every table of the schema has row level security enabled: `todos` and `posts` by the file itself, `profiles`, `orgs` and `org_members` because Aurabase enables it on every table created through `aura db raw`, a migration, the Studio or the table API. | Table | Policy | Rule | | --- | --- | --- | | `todos` | `todos_owner`, `for all` | `using (auth.uid() = user_id) with check (auth.uid() = user_id)` | | `posts` | `posts_owner`, `for all` | `using (auth.uid() = user_id) with check (auth.uid() = user_id)` | | `profiles`, `orgs`, `org_members` | none | RLS on and no policy: only the `service_role` key reads or writes them | ```bash verify="policies" needs="seed" aura db policy list ``` ```text expect="policies" » RLS Policies Table Policy Cmd USING Expression ------------------------------------------------------------------------------------- posts posts_owner ALL (auth.uid() = user_id) todos todos_owner ALL (auth.uid() = user_id) ℹ 2 policy(ies). ``` What each key sees, with the schema just installed: | Caller | `todos` | `profiles` | `todo_count(…)` | | --- | --- | --- | --- | | Anon key, no user | no row | no row | `403 INSUFFICIENT_PRIVILEGE` | | Signed-in user | its own rows only (none until it inserts one) | no row | the number of its own rows | | `service_role` key | every row | every row | every row of the given user | ## Demo rows | Table | Rows | | --- | --- | | `profiles` | `alice` (`00000000-0000-4000-8000-0000000000a1`, Alice Martin), `bob` (`00000000-0000-4000-8000-0000000000b2`, Bob Durand) | | `orgs` | `acme` (Acme) | | `org_members` | alice is `owner` of `acme`, bob is `member` | | `posts` | "Hello Aurabase" by alice (published), "Draft notes" by bob (not published) | | `todos` | alice: "Read the quickstart" (done), "Create a table", "Add a row level security policy"; bob: "Invite a teammate" | The two user ids are not accounts of your project: no one can sign in as alice or bob. Identity columns (`id` of `orgs`, `posts`, `todos`) get their values in an order that PostgreSQL does not guarantee, so the examples sort by title, never by id. ```sql verify="rows" needs="seed" select title, done from todos order by title ``` ```text expect="rows" done │ title ──────┼──────────────────────────────── false │ Add a row level security policy false │ Create a table false │ Invite a teammate true │ Read the quickstart ℹ 4 row(s). ``` ## Read it as a user `aura db raw --as authenticated --user ` runs a query as a signed-in user with that id, so you can watch the owner policy without creating an account. The same query as alice returns her three todos only. ```bash verify="as-alice" needs="seed" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select title, done from todos order by title" ``` ```text expect="as-alice" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). done │ title ──────┼──────────────────────────────── false │ Add a row level security policy false │ Create a table true │ Read the quickstart ℹ 3 row(s). ``` With `--as anon`, the same table returns no row, and `profiles`, which has no policy, returns no row to anyone but the `service_role` key. ```bash verify="as-anon" needs="seed" aura db raw --as anon "select count(*) as visible from profiles" ``` ```text expect="as-anon" ℹ Executed as anon. visible ─────── 0 ℹ 1 row(s). ``` With a real account, a signed-in user starts with no todo: the demo rows belong to other ids, so `todo_count` returns `0` for the user, and `0` even for alice. After the user inserts a todo of its own, the count is `1`. The script signs a new user up: on a project that requires email confirmation (the default), turn it off first with `aura auth settings set email_confirmation_required=false`, as in the [Quickstart](https://aurabase.dev/en/docs/database/quickstart). ```typescript verify="as-real-user" needs="seed" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `schema-${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 before = await aura.rpc('todo_count', { p_user: me }) console.log('before:', before.data, before.error) const inserted = await aura.from('todos').insert({ user_id: me, title: 'My first todo' }).select('title, done') console.log('insert:', inserted.data, inserted.error) const after = await aura.rpc('todo_count', { p_user: me }) console.log('after:', after.data, after.error) const alice = await aura.rpc('todo_count', { p_user: '00000000-0000-4000-8000-0000000000a1' }) console.log('alice, seen by this user:', alice.data) const open = await aura.from('open_todos').select('title') console.log('open_todos:', open.data, open.error) ``` ```text expect="as-real-user" before: 0 null insert: [ { title: 'My first todo', done: false } ] null after: 1 null alice, seen by this user: 0 open_todos: [ { title: 'My first todo' } ] null ``` ## Clean up Delete the todo inserted above (the test user stays in the project; delete it with `aura auth users delete `): ```bash verify="clean-up" needs="as-real-user" aura db raw "delete from todos where title = 'My first todo'" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## Remove it The schema only adds objects to your project schema. To remove them, drop the view and the function, then the tables: ```bash verify="remove" needs="seed" aura db raw "drop view if exists open_todos; drop function if exists todo_count(uuid); drop table if exists org_members, orgs, posts, todos, profiles cascade" ``` ```text expect="remove" ℹ No results (0 rows). ``` Run `aura db seed --example docs` again to bring it back. --- ### Run SQL from the CLI or a server Source: https://aurabase.dev/en/docs/database/run-sql.md # Run SQL from the CLI or a server > Send SQL to your project from a terminal, a script or a backend, try it without committing, run it as a given role, and know which statements the endpoint refuses and why. `aura db raw`, `POST /v1/db/{project_id}/raw` and `db.sql()` of the JavaScript SDK are three doors to the same endpoint. The Studio SQL editor (**Database › SQL editor**) uses it too. It needs the `service_role` key, runs your SQL in one transaction under the project's administrator role, and refuses a list of statements before they reach PostgreSQL. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). `aura db raw` reads `AURABASE_SERVICE_ROLE_KEY` from the environment: the CLI session of `aura login` is not accepted on the data plane. ## Run a query with the CLI ```bash verify="select" aura db raw "select title, done from todos order by title" ``` ```text expect="select" done │ title ──────┼──────────────────────────────── false │ Add a row level security policy false │ Create a table false │ Invite a teammate true │ Read the quickstart ℹ 4 row(s). ``` The columns of the table output, and the keys of the JSON output, come back in alphabetical order, not in the order of your `select`. Each row is a JSON object on the wire and its keys are sorted. A statement that returns no row prints `ℹ No results (0 rows).` A query may start with a `--` comment, and several statements separated by `;` run in the same transaction. ## Parameters, files and output | Option | Effect | | --- | --- | | `""` | The SQL to run. `-` reads it from standard input. | | `-f, --file ` | Read the SQL from a file. | | `-p, --params ...` | Values bound to `$1`, `$2`… The CLI sends them as text: cast them in SQL (`$1::uuid`, `$1::int`). | | `--json` | Print the rows as a JSON array. | | `--dry-run` | Run the SQL, return its rows, then roll the transaction back. | | `--read-only` | Run inside a read-only transaction: PostgreSQL rejects any write. | | `--as anon` / `--as authenticated --user ` | Run as the public role or as a signed-in user, to see what a policy allows. | Bind a value instead of writing it into the SQL: ```bash verify="params" aura db raw --json "select title, done from todos where user_id = \$1::uuid order by title" -p 00000000-0000-4000-8000-0000000000b2 ``` ```text expect="params" [ { "done": false, "title": "Invite a teammate" } ] ``` Read the SQL from a file, or from standard input: ```bash verify="file" cat > open-todos.sql <<'SQL' -- Todos that are not done yet select title from open_todos order by title SQL aura db raw -f open-todos.sql ``` ```text expect="file" title ─────────────────────────────── Add a row level security policy Create a table Invite a teammate ℹ 3 row(s). ``` ```bash verify="stdin" echo "select count(*) as todos from todos" | aura db raw - ``` ```text expect="stdin" todos ───── 4 ℹ 1 row(s). ``` ## Dry run and read-only mode `--dry-run` executes the statement for real, so constraint errors and returned rows show up, then rolls everything back: ```bash verify="dry-run" aura db raw --dry-run "insert into todos (user_id, title) values ('00000000-0000-4000-8000-0000000000a1', 'Try a dry run') returning title" aura db raw "select count(*) as todos from todos" ``` ```text expect="dry-run" ℹ Mode: dry-run — query is executed then transaction ROLLED BACK. title ───────────── Try a dry run ℹ 1 row(s). todos ───── 4 ℹ 1 row(s). ``` `--read-only` is for queries that must never write. A write fails with `cannot execute INSERT in a read-only transaction` and the command exits with status 1. ## Run as anon or as a user By default the query runs as the project's administrator role, which bypasses row level security. `--as` switches to a platform role for the duration of the query; it can only restrict, never give more rights. ```bash verify="as-user" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000b2 "select title from todos order by title" aura db raw --as anon "select count(*) as visible from todos" ``` ```text expect="as-user" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000b2). title ───────────────── Invite a teammate ℹ 1 row(s). ℹ Executed as anon. visible ─────── 0 ℹ 1 row(s). ``` ## Call the REST endpoint From a backend or a CI job without the CLI, send the SQL to `POST /v1/db/{project_id}/raw` with the `service_role` key in the `apikey` header. The body accepts `query`, `params` (JSON values, typed as sent), `dry_run`, `read_only`, `as_role` (`anon` or `authenticated`) and `as_user_id`; any other field is rejected with `400`. ```bash verify="http" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/raw" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H 'content-type: application/json' \ -d '{"query": "select title from todos where done = $1 order by title", "params": [true]}' ``` ```text expect="http" {"data":[{"title":"Read the quickstart"}],"meta":null} ``` The gateway refuses the `service_role` key when the request carries an `Origin` header, which every browser adds: `401 SECRET_KEY_IN_BROWSER`. Call this endpoint from a server, never from a web page. ## Call it from the SDK `db.sql(query, params, options)` posts to the same endpoint. Create the client with the `service_role` key, on a server only. `options` takes `dryRun` and `readOnly`. ```typescript verify="sdk" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const done = await admin.db.sql('select title from todos where done = $1 order by title', [true]) console.log(done.data, done.error) const count = await admin.db.sql('select count(*)::int as todos from todos', [], { readOnly: true }) console.log(count.data, count.error) const refused = await admin.db.sql('create extension postgis') console.log(refused.data, refused.error?.status, refused.error?.code) ``` ```text expect="sdk" [ { title: 'Read the quickstart' } ] null [ { todos: 4 } ] null null 400 BAD_REQUEST ``` `db.sql()` with the anon key fails with `403 FORBIDDEN` and the message ``Forbidden: `/raw` query is reserved to the service_role role``. ## Result From the terminal, a server or a script, the same endpoint answered the same data. One summary query, as JSON: ```bash verify="result" aura db raw --json "select count(*)::int as todos, (count(*) filter (where done))::int as done from todos" ``` ```text expect="result" [ { "done": 1, "todos": 4 } ] ``` The dry run above left the table unchanged: still four todos, one of them done. ## What the endpoint refuses The endpoint reads the SQL before running it and answers `400 BAD_REQUEST` when it finds one of the patterns below. The check is textual: a forbidden word inside a string literal is refused too (`select 'copy'` fails, because `copy` is on the function list). | Refused | Message (after `Invalid request:`) | What to do instead | | --- | --- | --- | | `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `SET TRANSACTION` | `Operation not allowed in a raw query: transaction control (…). The query already runs inside a transaction managed by the service.` | Send the statements together: they already share one transaction. | | `UPDATE` or `DELETE` without `WHERE` | `UPDATE without a WHERE clause is not allowed in raw queries — risk of overwriting every row. Add a WHERE condition.` and `DELETE without a WHERE clause is not allowed in raw queries — risk of deleting every row. Add a WHERE condition.` | Add a `WHERE`, even `where true` if you mean every row. | | `SET` (with or without `LOCAL`) of `search_path`, `role`, `session`, `session authorization`, `schema`, `transaction_read_only`, `standard_conforming_strings` or `backslash_quote` | `Operation not allowed in a raw query: 'SET search_path/role/session' — it could bypass tenant isolation` | Unqualified names already resolve in your project schema. Other settings, such as `SET LOCAL timezone`, are accepted. Always write `SET LOCAL`: a `SET` without `LOCAL` is accepted too, but it can outlive your request on the pooled connection and change the settings of later requests of the project. | | `RESET` | `Operation not allowed in a raw query: 'RESET' — it could bypass tenant isolation` | Nothing to reset: each request starts from the settings of the project. | | Any mention of `search_path`, even in a function call or a comment | `Referencing 'search_path' is not allowed in raw queries` | Remove the mention. | | `CREATE EXTENSION` | `Operation not allowed in a raw query: 'CREATE EXTENSION'. Enable allowed extensions from Studio › Database › Extensions or with POST /v1/db/{project_id}/schema/extensions (…)` | `aura db extensions list` and `aura db extensions enable `. | | Anonymous blocks `DO $$ … $$` | `Anonymous blocks (DO) are not allowed in raw queries` | Create a function, or write the statements out. | | `CREATE`, `ALTER` or `DROP SCHEMA`, `COPY … PROGRAM`, `CREATE RULE`, `CREATE EVENT TRIGGER`, `IMPORT FOREIGN SCHEMA` | `Operation not allowed in a raw query: 'CREATE SCHEMA'. This cluster-level or global-schema statement is reserved for declarative migrations.` | Keep your objects in the project schema. | | A function or procedure created with `SECURITY DEFINER` | `The 'SECURITY DEFINER' option is not allowed in raw queries (privilege escalation). (…)` | Create it as `SECURITY INVOKER` (the default). | | `information_schema`, `pg_catalog` | `Referencing the system schema 'pg_catalog' is not allowed in raw queries — it could enumerate other tenants` | `aura db table list`, `aura db function list`, `aura db policy list`, `aura db extensions list`, `aura db inspect`, `aura db slow-queries`. | | System views such as `pg_tables`, `pg_class`, `pg_views`, `pg_indexes`, `pg_proc`, `pg_roles`, `pg_settings`, `pg_stat_activity`, `pg_locks`, `pg_extension`, `pg_stat_statements` | `Referencing the system view 'pg_views' is not allowed in raw queries` | The same commands. | | The console schema of the platform, `aura_console` | `Referencing the 'aura_console' schema is not allowed in raw queries` | Nothing: it holds no data of your project. | | Functions that run built SQL, touch files, sleep or leave the transaction: `copy`, `dblink…`, `lo_import`, `lo_export`, `pg_read_file`, `pg_sleep`, `pg_notify`, `set_config`, `query_to_xml` and the other `*_to_xml` functions | `Calling the function 'pg_sleep' is not allowed — it can run SQL built at run time, read files or exfiltrate data, and would bypass multi-tenant isolation` | Load data with the import tools of the CLI or the SDK. | | Escape strings `E'…'`, `U&'…'` | `Escape strings (E'…', U&'…') are not allowed: they are decoded after this validation. Use a plain string literal.` | Use a plain `'…'` literal. | | A schema of another project (`project_.table`) | `Cross-schema reference not allowed: '…' — only the current project's schema is accessible` | Nothing: a project only reaches its own schema. | | A string, a quoted identifier or a block comment that is never closed | `Invalid SQL: … opened and never closed` (the middle part names the delimiter) | Close the quote or the comment. | Statements that are not in this list run, including `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, `TRUNCATE`, `CREATE INDEX`, `CREATE VIEW`, `CREATE POLICY`, `GRANT` and `CREATE FUNCTION` without `SECURITY DEFINER`. After a statement that changes the schema, the endpoint enables row level security on every new table, sets `security_invoker` on every new view and reloads the REST API cache, so the new table is reachable from the SDK on the next call. A direct PostgreSQL connection (`psql`, an ORM) does not go through this check: what the connection role is allowed to do is decided by PostgreSQL alone. See [Connect to your database](https://aurabase.dev/en/docs/database/connect). ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `Error: AURABASE_SERVICE_ROLE_KEY is not set.` | The CLI has no project key in its environment. | `export AURABASE_SERVICE_ROLE_KEY=aura_sk_…` (Studio › Settings › API keys). | | ``[403] FORBIDDEN: Forbidden: `/raw` query is reserved to the service_role role`` | The request used the anon key or a user token. | Use the `service_role` key, on a server. | | `[401] SECRET_KEY_IN_BROWSER` | The `service_role` key was sent from a browser (`Origin` header). | Move the call to a server; use the anon key and row level security in the browser. | | `operator does not exist: uuid = text` | A `-p` value is bound as text. | Cast the parameter: `$1::uuid`. | | `column "titel" does not exist (…) Hint: Perhaps you meant to reference the column "todos.title".` | A misspelled column. PostgreSQL suggests the closest name. | Fix the name; `aura db table list` prints the columns of every table. | | `cannot execute INSERT in a read-only transaction` | `--read-only` or `read_only: true` with a write. | Remove the flag for writes. | | `429` on `/raw` | The plan limit `db.raw_sql_requests` is reached: Free 60 per minute and 2,000 per month, Pro 600 per minute, Team 6,000 per minute. A second limit applies per client address: bursts of 10 requests, then one request every 2 seconds (`Rate limit exceeded. Try again in 1s`); the CLI retries these by itself, and each retry counts towards the plan limit. | Wait for the window (`Retry-After` header), batch statements in one request, or read through the SDK, which counts under `db.requests`. | By default, a query that runs longer than 10 seconds is cancelled by PostgreSQL (`statement_timeout`, set on every request of the data plane). A request can raise its own limit, but the gateway stops waiting after about 30 seconds by default and answers `408`; PostgreSQL may still be running the statement at that point. ## Clean up The dry run wrote nothing. Remove the SQL file created above: ```bash verify="clean-up" needs="file" rm open-todos.sql ``` ## See also - [Connect to your database](https://aurabase.dev/en/docs/database/connect): psql, ORMs and the direct connection, which the /raw check does not apply to. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that --as anon and --as authenticated let you test. - [Database CLI reference](https://aurabase.dev/en/docs/database/cli): Every option of aura db raw and the other aura db commands. - [Example schema](https://aurabase.dev/en/docs/database/example-schema): The tables used in the examples of this page. --- ### Project isolation Source: https://aurabase.dev/en/docs/database/project-isolation.md # Project isolation > Where your tables live, what else shares the server with them, and what stops one project from reading another, layer by layer. ## Mental model A project is a PostgreSQL **database**, not a schema in a shared database. On the Free and Pro plans that database sits on a PostgreSQL cluster that belongs to your organization: the other projects of the same organization have their own databases on it, and no other organization does. On Team and Enterprise, a project gets a cluster of its own. [Shared and dedicated clusters](https://aurabase.dev/en/docs/database/clusters) compares the two. ```text filename="where a project lives" organization (Free or Pro) └── PostgreSQL cluster of the organization ├── database project_ ← project A ├── database project_ ← project B └── … organization (Team or Enterprise) └── PostgreSQL cluster of the project ← one project, its own instances ``` ## Inside the database The database of a project holds several schemas. Yours has the same name as the database; the others belong to the platform, inside the same database. | Schema | Content | | --- | --- | | `project_` | Your tables, views, functions and policies. Unqualified names resolve here. | | `project__auth` | Users, sessions, identities and settings of Auth | | `project__storage` | Buckets, object metadata and the storage audit log | | `project__platform` | Settings of functions, notifications, realtime and AI | | `auth` | The helpers `auth.uid()`, `auth.role()`, `auth.tenant()`, `auth.jwt()`… | | `public` | The installed extensions (`vector`, `pgcrypto`…) | `` is the project id with underscores instead of dashes: project `41fd6f07-3acf-48cf-9eb5-d665ce99a849` uses the database and the schema `project_41fd6f07_3acf_48cf_9eb5_d665ce99a849`. The platform schemas are part of your project, not hidden from it. Who reaches them, and through which door: | Door | Your schema | Platform schemas of your project | | --- | --- | --- | | SDK and REST (any key) | Yes | No: the REST API serves only your schema; a table of another schema answers `TABLE_NOT_FOUND` | | `aura db raw`, `db.sql()`, Studio SQL editor (`service_role` key) | Yes | Yes: the SQL check accepts the schemas of your own project, and the administrator role owns their tables and bypasses row level security. `select count(*) from project__auth.users` counts your users. | | `aura db raw --as anon` or `--as authenticated` | Yes, under your policies | `_auth` and `_storage`: the public roles hold privileges, but the tables of `_auth` have row level security forced and no policy, so no row comes back; `storage_buckets` and `storage_objects` carry the policies of the Storage API. `_platform`: no privilege, except on `realtime_messages` (row level security forced, no policy). | | Direct connection, as the `proj_` role | Yes, under your policies | Same as the line above: `project__auth.users` returns no row, `project__platform` answers `permission denied`; the tables without row level security listed below are readable. | | Direct connection after `SET LOCAL ROLE tenant__admin` | Yes, every row | Yes, every row: the `proj_` role may switch to the administrator role, which owns the tables and bypasses row level security, exactly like the `service_role` key on `aura db raw`. | Two consequences: - **Treat the `service_role` key and the password of the direct connection as admin credentials on Auth and Storage data too.** With either, SQL reads and changes users (password hashes and MFA settings included), sessions and object metadata directly, bypassing the checks of the Auth and Storage APIs. - **A view or function you create can expose a platform table.** A few tables have no row level security and are readable by `aura_anon` and `aura_authenticated`: the migration ledgers (`_sqlx_migrations`) of `_auth` and `_storage`, `storage_audit_log` and `storage_derivatives`. The REST API does not serve them, but a view in your schema that selects from them would, to the anon key. Keep views and functions on your own tables. Check what each role reads in the users table of your project: ```bash verify="platform-schemas" AUTH_SCHEMA="project_${PROJECT_ID//-/_}_auth" aura db raw "select count(*) >= 0 as readable from $AUTH_SCHEMA.users" aura db raw --as anon "select count(*) as visible_users from $AUTH_SCHEMA.users" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select count(*) as visible_users from $AUTH_SCHEMA.users" ``` ```text expect="platform-schemas" readable ──────── true ℹ 1 row(s). ℹ Executed as anon. visible_users ───────────── 0 ℹ 1 row(s). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). visible_users ───────────── 0 ℹ 1 row(s). ``` The same table through the REST API, even with the `service_role` key: ```bash verify="platform-rest" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/users?select=id" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).error.code' ``` ```text expect="platform-rest" TABLE_NOT_FOUND ``` ## What keeps projects apart No single mechanism carries the isolation. Each path into the database goes through several of these layers: | Layer | What it does | Applies to | | --- | --- | --- | | Gateway | Resolves the project from the host and the path, and checks that the API key belongs to that project. | SDK, REST, `aura db raw` | | Signed token per project | The gateway signs the token it forwards to the project's PostgREST with a secret derived from the project id. | SDK, REST | | PostgreSQL roles | Requests run as `aura_anon`, `aura_authenticated` or an administrator role created for the project alone (`tenant__admin`). See [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys). | Every path | | Row level security | On by default for tables created through Aurabase; filters rows by `auth.uid()` and the policies you write. | SDK, REST, direct connection | | SQL check of `/raw` | Refuses references to another project's schema, to the system catalogs and to the platform's console schema, before the SQL reaches PostgreSQL. | `aura db raw`, the Studio SQL editor, `db.sql()` | | Router of the direct connection | Reads the role name, picks the database of that role's project and forces it; refuses a role presented on another project's host. | psql, ORMs | | Host rules of the cluster | A direct-connection role may only open the database of its own project, whatever the router does. | psql, ORMs | ## See it from your project The database and the schema of the project share one name, and a query that names another project's schema is refused before it runs: ```sql verify="same-name" select current_database() = current_schema() as same_name, current_schema() like 'project\_%' as project_schema ``` ```text expect="same-name" project_schema │ same_name ───────────────┼────────── true │ true ℹ 1 row(s). ``` ```typescript verify="cross-schema" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { error } = await admin.db.sql('select * from project_00000000_0000_0000_0000_000000000000.todos') console.log(error?.status, error?.message) ``` ```text expect="cross-schema" 400 Invalid request: Cross-schema reference not allowed: 'project_00000000_0000_0000_0000_000000000000' — only the current project's schema is accessible ``` ## Trade-offs - **Projects of one organization share a server.** On Free and Pro, CPU, memory, disk and the `max_connections` budget of the cluster are shared by the projects of the organization. A heavy query in one project slows the others down; it never reaches another organization. - **Some roles are shared within a cluster.** `aura_anon`, `aura_authenticated` and `aura_service_role` exist once per cluster. What isolates projects is the database each request is routed to and the roles created per project, not those three names. - **No catalog access through `/raw`.** `information_schema`, `pg_catalog` and the system views are refused on that path because a cluster-wide view could list other projects. Use the `aura db` commands (`table list`, `inspect`, `slow-queries`) or the direct connection, where PostgreSQL itself limits what your role sees. - **No extension, schema or role of your own.** A project cannot run `CREATE EXTENSION`, `CREATE SCHEMA` or `CREATE ROLE`; [How extensions are installed](https://aurabase.dev/en/docs/database/extensions-model) explains why. - **Isolation of the dedicated cluster.** The layout above is what a project on the cluster of its organization gets. The dedicated cluster of Team and Enterprise is described from the provisioning code and was not replayed for this page. ## Related pages - [How a request reaches Postgres](https://aurabase.dev/en/docs/database/request-flow): The path of each kind of request, with the role and claims it carries. - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): Every PostgreSQL role a project uses and which ones bypass RLS. - [Shared and dedicated clusters](https://aurabase.dev/en/docs/database/clusters): The two places a project database can live. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Write the policies that filter rows per user. --- ### How a request reaches Postgres Source: https://aurabase.dev/en/docs/database/request-flow.md # How a request reaches Postgres > Follow a request from your code to PostgreSQL, see which role it runs as and where auth.uid() gets its value, and know which component answers when something fails. ## Mental model There are three doors into a project database. The SDK and the REST API go to a PostgREST server that belongs to the project. SQL sent with `aura db raw`, the Studio and the schema commands goes to the `aura-db` service, which checks it and runs it. A direct PostgreSQL connection goes through a router to the connection pooler of the cluster. ```text filename="three paths" SDK / REST ─▶ gateway :8080 ─▶ PostgREST of the project ─────────────────────────▶ PostgreSQL │ key, user token, rate limit role: aura_anon | aura_authenticated | aura_service_role │ aura db raw ─▶ gateway ─▶ NATS ─▶ aura-db (SQL check) ─▶ PgBouncer ─────────────▶ PostgreSQL role: tenant__admin (service_role key), or aura_anon / aura_authenticated with --as psql, ORM ─▶ router :5432 (TLS) ─▶ PgBouncer of the organization cluster ────────▶ PostgreSQL role: proj_xxxxxxxx (no pooler on a dedicated cluster) ``` ## SDK and REST 1. **Gateway, data plane.** The request arrives on the project URL. The gateway attaches a request id, applies the rate limit of the plan (`db.requests`), and authenticates the call: the API key in `apikey` or `X-API-Key` must belong to the project, and an optional `Authorization: Bearer ` identifies a signed-in user. A `service_role` key that arrives with an `Origin` header (a browser) is refused with `401 SECRET_KEY_IN_BROWSER`. 2. **Routing.** Reads, inserts, updates (`PATCH`), deletes and `rpc()` calls go to the PostgREST server of the project over HTTP. A `PUT` and the management routes (`/raw`, `/schema`, policies, functions…) go to `aura-db` instead. 3. **Signed token.** The gateway signs a short-lived token for PostgREST with a secret derived from the project id. It carries the PostgreSQL role to use (`aura_anon` for the anon key, `aura_authenticated` for a user, `aura_service_role` for the `service_role` key) and, for a user only, the user id in `sub`. A key alone has no `sub`, so `auth.uid()` is `NULL`. 4. **PostgREST.** It switches to that role for the transaction, puts the token claims in `request.jwt.claims`, runs the pre-request hook of the platform and executes the query. It connects to the primary of the cluster directly, as `aura_authenticator`, with a small pool of its own. A read returns at most 1,000 rows. 5. **Response.** The gateway wraps the result as `{ data, meta }`. An unfiltered read that returns no row for anon or a user gets a `meta.hint` that names the likely cause: row level security without a matching policy. ## SQL through aura-db 1. **Gateway.** Same authentication. `/raw` then requires the `service_role` key; any other key gets `403 FORBIDDEN`. 2. **NATS.** The gateway forwards the request to `aura-db` over NATS (subject `aura.svc.db`). 3. **SQL check.** `aura-db` reads the SQL and refuses transaction control, `SET`, catalogs, other schemas, `CREATE EXTENSION` and the other patterns listed in [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql#refused). 4. **Transaction.** It takes a connection from its pool, logged in as `aura_authenticator` through the PgBouncer of the cluster, opens a transaction and sets, with `SET LOCAL`: the role (`tenant__admin` for the `service_role` key, `aura_anon` or `aura_authenticated` with `--as`), the search path (your schema, the storage schema of the project, `public`), a statement timeout of 10 seconds by default, and the claims of the simulated user. 5. **After a schema change.** It enables row level security on every new table, sets `security_invoker` on every new view, and asks PostgREST to reload its schema cache. ## Direct connection The router listens on port 5432, answers the TLS handshake with the `*.db.` certificate, reads the user name from the startup message, finds the project of that `proj_` role and forces its database. On the cluster of an organization it forwards the connection to PgBouncer in transaction mode; on a dedicated cluster it goes straight to the primary. Nothing checks your SQL on this path: PostgreSQL privileges and row level security decide. [Connect to your database](https://aurabase.dev/en/docs/database/connect) has the rules that follow from it. ## Claims and auth helpers Policies and functions read the caller from the setting `request.jwt.claims`, through helpers of the `auth` schema: | Helper | Returns | Value without a user | | --- | --- | --- | | `auth.uid()` | `sub` of the claims, as `uuid` | `NULL` | | `auth.role()` | `role` of the claims | depends on the path, see below | | `auth.tenant()` | `app_metadata.tenant`, if it is a UUID | `NULL` | | `auth.has_role(name)` | `true` if `app_metadata.roles` contains `name` | `false` | | `auth.jwt()` | all the claims, as `jsonb` | `{}` when no claims are set | | `auth.email()` | `email` of the claims | `NULL` | The claims are set by the server, from a token it signed or checked: a client cannot write them. `auth.role()` does not return the same value on the two paths. Through the SDK and REST it returns the PostgreSQL role name (`aura_anon`, `aura_authenticated`, `aura_service_role`); through `aura db raw --as` it returns `anon` or `authenticated`, and `anon` for the `service_role` key, which carries no claims there. Write policies with `to aura_authenticated` and `auth.uid()` rather than with a test on `auth.role()`. ## See the role of each key This function reports the role and the claims it runs with. Create it and let the three roles of the REST path call it: ```bash verify="whoami" aura db raw "create function whoami() returns json language sql stable as \$\$ select json_build_object('db_role', current_user, 'role', auth.role(), 'uid', auth.uid()) \$\$; grant execute on function whoami() to aura_anon, aura_authenticated, aura_service_role" ``` ```text expect="whoami" ℹ No results (0 rows). ``` ```typescript verify="call-whoami" needs="whoami" import { createClient } from '@aurabase/aurabase-js' const url = process.env.AURABASE_URL! const anon = createClient(url, process.env.AURABASE_ANON_KEY!) console.log('anon key:', (await anon.rpc('whoami')).data) const admin = createClient(url, process.env.AURABASE_SERVICE_ROLE_KEY!) console.log('service_role key:', (await admin.rpc('whoami')).data) const user = createClient(url, process.env.AURABASE_ANON_KEY!) const email = `flow-${Date.now()}@example.com` await user.auth.signUp({ email, password: 'correct-horse-battery-9' }) const { data: session } = await user.auth.signInWithPassword({ email, password: 'correct-horse-battery-9' }) const me = (await user.rpc('whoami')).data as { db_role: string; role: string; uid: string } console.log('signed-in user:', me.db_role, me.role, me.uid === session?.user?.id) ``` ```text expect="call-whoami" anon key: { db_role: 'aura_anon', role: 'aura_anon', uid: null } service_role key: { db_role: 'aura_service_role', role: 'aura_service_role', uid: null } signed-in user: aura_authenticated aura_authenticated true ``` The script signs a test user up: on a project that requires email confirmation (the default), turn it off first with `aura auth settings set email_confirmation_required=false`, as in the [Quickstart](https://aurabase.dev/en/docs/database/quickstart). Remove the function when you are done: ```bash verify="drop-whoami" needs="whoami" aura db raw "drop function whoami()" ``` ```text expect="drop-whoami" ℹ No results (0 rows). ``` ## Trade-offs - **Two engines behind one URL.** PostgREST serves reads and writes, `aura-db` serves `PUT`, SQL and the schema API. Errors on the first path carry an `upstream_code` from PostgREST or PostgreSQL (`42501`, `PGRST205`…); errors on the second come back as `400 BAD_REQUEST` with the PostgreSQL message. - **PostgREST pool.** Each PostgREST server keeps a small pool on the primary (by default 2 connections per replica on the cluster of an organization, 10 on a dedicated cluster; the deployment can change both). When all are busy, a request waits up to 3 seconds, then fails with `503 DB_POOL_TIMEOUT` and a `Retry-After` header. - **A table created over the direct connection** is unknown to PostgREST until the schema cache reloads: `notify pgrst, 'reload schema'` (SQL through `aura-db` triggers the reload for you). - **Waking up.** A project whose database instance is asleep answers `503` with `Retry-After: 5` while it wakes up; retry the request. - **Two statement timeouts.** On the SDK and REST path, PostgreSQL cancels a statement after 5 seconds for the anon key and after 10 seconds for a signed-in user or the `service_role` key, and the gateway answers `504 STATEMENT_TIMEOUT`. On the `aura-db` path (`aura db raw`), the limit is 10 seconds by default (a request can raise its own limit, but the gateway stops waiting after about 30 seconds by default and answers `408`) and the answer is `400` with `canceling statement due to statement timeout`. The direct connection sets no timeout. See [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling#timeouts). - **Session state** set on the direct connection does not survive the end of a transaction behind PgBouncer. See [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling). ## Related pages - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): Each role on these paths, and which ones bypass row level security. - [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling): The pools on each path and the limits of each plan. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): What the SQL check of aura-db refuses. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that use auth.uid() and the claims. --- ### Roles, keys and row level security bypass Source: https://aurabase.dev/en/docs/database/roles-and-keys.md # Roles, keys and row level security bypass > Map each key and each tool to the PostgreSQL role it runs as, understand why two of those roles bypass row level security, and tell a privilege error from a policy that hides rows. ## Mental model A key says **who calls**, a PostgreSQL role says **what the query may touch**. The gateway turns each key, and each signed-in user, into one role; PostgreSQL then applies that role's privileges (`GRANT`) and the row level security policies written for it. Two roles skip the policies on purpose: they belong to code you run on a server. ```text filename="key → role" anon key, no user ─▶ aura_anon privileges + RLS anon key + user token ─▶ aura_authenticated privileges + RLS, auth.uid() = the user service_role key (SDK) ─▶ aura_service_role bypasses RLS service_role key (/raw) ─▶ tenant__admin bypasses RLS, owns the tables direct connection ─▶ proj_xxxxxxxx privileges + RLS ``` ## Keys | Key | Prefix | Where it may live | Becomes | | --- | --- | --- | --- | | anon | `aura_anon_` | Browser, mobile app, anywhere | `aura_anon`; `aura_authenticated` when a user token is sent with it | | service_role | `aura_sk_` | Server, CI, your terminal | `aura_service_role` (SDK, REST), `tenant__admin` (`/raw`, schema API) | | authenticated | `aura_auth_`; none by default, `aura db api-keys create --scope authenticated` | Server | `aura_authenticated`, without a user (`auth.uid()` is `NULL`); see [API keys](https://aurabase.dev/en/docs/database/api-keys) | Two initial keys, anon and service_role, are created with the project and shown once. Create, list and revoke keys with `aura db api-keys` or in the Studio under **Settings › API keys**. The gateway refuses a `service_role` key sent from a browser (`401 SECRET_KEY_IN_BROWSER`) or in a URL query string. ## PostgreSQL roles of a project | Role | Login | Bypasses RLS | Used by | | --- | --- | --- | --- | | `aura_anon` | no | no | Anon key without a user; `aura db raw --as anon` | | `aura_authenticated` | no | no | Signed-in users; `aura db raw --as authenticated --user ` | | `aura_service_role` | no | **yes** | `service_role` key on the SDK and REST path | | `tenant_` | no | no | Base role of the project; the direct-connection role and the alias `service_role` inherit it | | `tenant__admin` | no | **yes** | `service_role` key on `aura-db` (`/raw`, the Studio SQL editor, schema API, migrations). Owns the tables it creates. | | `aura_authenticator` | yes | no | Connection role of `aura-db` and PostgREST, which switch to one of the roles above for each transaction | | `proj_xxxxxxxx` | yes | no | Direct connection (psql, ORMs). Inherits `tenant_` and `aura_authenticated`, may `SET ROLE tenant__admin`, and may only open its project's database. | | `anon`, `authenticated`, `service_role` | no | no | Aliases kept for SQL written for other platforms: `aura_anon`, `aura_authenticated` and `aura_service_role` are members of them, so a grant or a policy written for `anon` also applies to `aura_anon`. The alias `service_role` itself does **not** have `BYPASSRLS`. | `` is the project id with underscores instead of dashes. The three `aura_*` roles and `aura_authenticator` exist once per cluster; the `tenant_` and `proj_` roles exist per project. Tables created through Aurabase are granted to `aura_anon`, `aura_authenticated` and `aura_service_role` at creation, and protected by row level security, which Aurabase enables on them. Functions are not: PostgreSQL's default `EXECUTE` for everyone is revoked, so a function is callable only by the roles you grant it to. ## Roles that bypass row level security `aura_service_role` and `tenant__admin` have the PostgreSQL attribute `BYPASSRLS`. This is intended: they serve the `service_role` key, which is meant for code you control on a server (an admin back office, a webhook, a migration, the Studio). Such code needs to read and write every row, for every user, without a policy written for it. What keeps this safe is where the key lives, not the role: - the key never goes to a browser: the gateway refuses it when the request has an `Origin` header; - it never travels in a URL: the gateway refuses it in a query string; - a request made with the key carries no user: `auth.uid()` is `NULL`, so a policy can never mistake it for a user. If a `service_role` key leaks, revoke it (`aura db api-keys revoke `) and create another. ## See it from your project `aura db raw` runs as the administrator role, unless `--as` asks for a public role. The query below returns the same answer for each of the three: ```bash verify="roles" aura db raw "select current_user like 'tenant\_%\_admin' as admin_role, (select count(*) from todos) as todos" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select current_user, (select count(*) from todos) as todos" aura db raw --as anon "select current_user, (select count(*) from todos) as todos" ``` ```text expect="roles" admin_role │ todos ───────────┼────── true │ 4 ℹ 1 row(s). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). current_user │ todos ───────────────────┼────── aura_authenticated │ 3 ℹ 1 row(s). ℹ Executed as anon. current_user │ todos ─────────────┼────── aura_anon │ 0 ℹ 1 row(s). ``` The administrator role counts every todo of the [example schema](https://aurabase.dev/en/docs/database/example-schema); the demo user alice sees her three; anon sees none. ## Privilege or policy PostgreSQL treats a missing privilege and a missing policy differently, and the SDK shows the difference: | What you see | Cause | Fix | | --- | --- | --- | | `data: []`, no error, and a `meta.hint` | RLS is on and no policy lets the role read these rows. PostgreSQL hides rows instead of failing. | Add a `select` policy for the role. | | `403 INSUFFICIENT_PRIVILEGE`, `new row violates row-level security policy for table "todos"` | An insert or update that the `with check` of the policy rejects. | Write rows that the policy accepts (for an owner policy: your own `user_id`). | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for function todo_count` | The role has no `EXECUTE` on the function. | `grant execute on function todo_count(uuid) to aura_authenticated;` | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` | The role has no privilege on the table: typically a table created over the direct connection. | Enable RLS, then grant, then add a policy (see [Connect to your database](https://aurabase.dev/en/docs/database/connect#private-tables)). | | `403 FORBIDDEN`, ``Forbidden: `/raw` query is reserved to the service_role role`` | SQL sent with the anon key or a user token. | Run SQL from a server with the `service_role` key. | The three `INSUFFICIENT_PRIVILEGE` cases share the PostgreSQL code `42501`, so read the message: ```typescript verify="errors" import { createClient } from '@aurabase/aurabase-js' const user = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `roles-${Date.now()}@example.com` await user.auth.signUp({ email, password: 'correct-horse-battery-9' }) await user.auth.signInWithPassword({ email, password: 'correct-horse-battery-9' }) const notMine = await user.from('todos').insert({ user_id: '00000000-0000-4000-8000-0000000000a1', title: 'Not mine' }) console.log(notMine.error?.status, notMine.error?.code, notMine.error?.message) const anon = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const count = await anon.rpc('todo_count', { p_user: '00000000-0000-4000-8000-0000000000a1' }) console.log(count.error?.status, count.error?.code, count.error?.message) const hidden = await anon.from('profiles').select('username') console.log(hidden.data, hidden.error) ``` ```text expect="errors" 403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "todos" 403 INSUFFICIENT_PRIVILEGE permission denied for function todo_count [] null ``` The script signs a test user up: on a project that requires email confirmation (the default), turn it off first, as in the [Quickstart](https://aurabase.dev/en/docs/database/quickstart). ## Trade-offs - **`auth.role()` differs by path.** Through the SDK it returns `aura_anon`, `aura_authenticated` or `aura_service_role`; through `aura db raw --as` it returns `anon` or `authenticated`. Target roles with `to aura_authenticated` in a policy instead of testing `auth.role()`. - **The direct-connection role can become the administrator.** `proj_xxxxxxxx` may `SET ROLE tenant__admin`, which bypasses RLS. Treat its password like the `service_role` key. - **A table created by the administrator role over the direct connection is open to the public roles** until you enable row level security on it, because the hook that enables RLS only runs for SQL sent through Aurabase. - **No custom login role.** A project cannot `CREATE ROLE` (`permission denied to create role`); use policies on `aura_authenticated` and claims such as `auth.tenant()` or `auth.has_role()` to model your own roles. ## Related pages - [Row-level security](https://aurabase.dev/en/docs/database/rls): Write the policies these roles are filtered by. - [How a request reaches Postgres](https://aurabase.dev/en/docs/database/request-flow): Where each role is set on each path, and where the claims come from. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): Keys, the project URL, and the direct-connection role. - [Project isolation](https://aurabase.dev/en/docs/database/project-isolation): How projects are kept apart, beyond roles. - [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges): The privileges these roles hold, and how to reduce them. --- ### Connection pooling and limits Source: https://aurabase.dev/en/docs/database/connection-pooling.md # Connection pooling and limits > Know how many PostgreSQL connections your plan gives you, who holds them, what a transaction pooler breaks, and how to read the live values of your project. ## Mental model PostgreSQL gives each connection a process and caps their number with `max_connections`. Your application should not hold PostgreSQL connections when it does not need to: the SDK and the REST API never open one from your side, and the services behind them share a few pooled connections. Only the direct connection (psql, ORMs) puts connections of your own on the server, and on the cluster of an organization even those go through a pooler. ```text filename="who holds the connections" your app ─HTTP─▶ gateway ─▶ PostgREST of the project (2 pooled connections per replica) ─┐ your CLI ─HTTP─▶ gateway ─▶ aura-db ─▶ PgBouncer (transaction mode) ───────────────────┼─▶ PostgreSQL psql/ORM ─TLS──▶ router ─────────────▶ PgBouncer (transaction mode) ───────────────────┘ max_connections ``` ## The pools on each path | Path | Pool | Size | When it is full | | --- | --- | --- | --- | | SDK and REST | Pool of the project's PostgREST, connected to the primary | By default 2 connections per replica on the cluster of an organization, 10 on a dedicated cluster (settings of the deployment) | The request waits up to 3 seconds, then fails with `503 DB_POOL_TIMEOUT` and `Retry-After` | | `aura db raw`, Studio, schema API | Pool of `aura-db`, through the PgBouncer of the cluster | Created on demand, closed when idle | PgBouncer queues the transaction | | Direct connection | PgBouncer of the cluster of your organization (Free, Pro) | `default_pool_size` of the plan, see below | PgBouncer queues the transaction, up to `max_client_conn` clients | | Direct connection, dedicated cluster | None: the router connects to the primary | `max_connections` of the cluster | PostgreSQL refuses the connection | ## What transaction mode changes The PgBouncer of a cluster runs in **transaction mode**: a server connection is yours for one transaction, then goes back to the pool and may serve another client. PgBouncer's documentation puts it this way: in that mode, clients must not use session-based features, since each transaction may run on a different server connection. In practice: | Works | Does not survive the end of a transaction | | --- | --- | | Statements in one transaction (`BEGIN … COMMIT`) | `SET` without `LOCAL`: use `SET LOCAL` inside the transaction | | `SET LOCAL`, `SET LOCAL ROLE` | Named prepared statements created with `PREPARE` | | Single statements (autocommit) | `LISTEN` / `NOTIFY` subscriptions | | `NOTIFY pgrst, 'reload schema'` | Session-level advisory locks (`pg_advisory_lock`) | `aura-db` already works this way: it sets the role, the search path, the statement timeout and the claims with `SET LOCAL` at the start of each transaction. For an ORM on the direct connection, see [Connect to your database](https://aurabase.dev/en/docs/database/connect#direct): Prisma documents `pgbouncer=true` for this mode, and its migration tool expects a session connection that the endpoint of the cluster does not offer. ## Limits per plan These values come from the provisioning code and the plan table of the platform. The cluster of an organization is shared by the projects of that organization. **Cluster of the organization (new projects on Free and Pro)** | Plan of the organization | `max_connections` | Storage | PostgreSQL instances | PgBouncer `default_pool_size` | `max_client_conn` | `max_db_connections` | `max_user_connections` | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | Free | 50 | 5 Gi | 1 | 10 | 100 | 20 | 20 | | Pro | 100 | 20 Gi | 1 | 20 | 200 | 50 | 60 | `max_db_connections` caps the server connections of one database (one project); `max_user_connections` caps those of the shared login of the services across the whole cluster. The code also sizes this cluster for a Team organization (200 connections, 50 Gi, a pool of 40); new projects of a Team organization get a dedicated cluster instead. **Dedicated cluster (new projects on Team and Enterprise)** | Plan | `max_connections` | Storage | PostgreSQL instances | | --- | ---: | ---: | ---: | | Team | 300 | 50 Gi | 3 | | Enterprise | 400 | 100 Gi | 3 | The dedicated cluster has its own PgBouncer (2 instances, pool size 50 and 1,000 clients by default), used by `aura-db`. These values come from the code and were not replayed on a running dedicated cluster. **Request limits (all paths through the gateway)** | Plan | `db.requests` per minute | `db.requests` per month | `db.raw_sql_requests` per minute | `db.raw_sql_requests` per month | | --- | ---: | ---: | ---: | ---: | | Free | 600 | 1,000,000 | 60 | 2,000 | | Pro | 30,000 | 50,000,000 | 600 | 100,000 | | Team | 300,000 | 500,000,000 | 6,000 | 1,000,000 | | Enterprise | 3,000,000 | 5,000,000,000 | 60,000 | 10,000,000 | `db.requests` counts CRUD and RPC calls, `db.raw_sql_requests` counts calls to `/raw`. Above a per-minute limit the gateway answers `429`. A monthly quota blocks requests only when it is a hard limit: every monthly quota of Free is; the monthly quotas of Pro, Team and Enterprise are counted without blocking. See also [Limits](https://aurabase.dev/en/docs/limits). ## Statement timeouts Each path bounds how long one statement may run. Past the limit, PostgreSQL cancels it (`57014`, `canceling statement due to statement timeout`). | Path | Limit | Set by | Answer | | --- | --- | --- | --- | | SDK and REST, anon key | 5 s | Setting of the role `aura_anon` | `504 STATEMENT_TIMEOUT` | | SDK and REST, signed-in user or `service_role` key | 10 s | Setting of `aura_authenticator`, the login of PostgREST | `504 STATEMENT_TIMEOUT` | | `aura db raw`, Studio SQL editor, `db.sql()` | 10 s by default (500 ms to 120 s, setting of the deployment) | `SET LOCAL statement_timeout` by `aura-db`; a request can raise its own limit, but the gateway stops waiting after about 30 s by default and answers `408` | `400 BAD_REQUEST`, message containing `the query ran longer than this project's statement timeout (10 s)` | | Direct connection | none | | | `aura_authenticator` is also limited to 200 connections on a cluster (`CONNECTION LIMIT 200`). This function counts up to `n`; with a large `n` it runs longer than 5 seconds. The anon key hits its limit: ```bash verify="timeout-function" aura db raw "create function slow_count(n bigint) returns bigint language sql stable as \$\$ select count(*) from generate_series(1, n) \$\$; grant execute on function slow_count(bigint) to aura_anon" ``` ```text expect="timeout-function" ℹ No results (0 rows). ``` ```bash verify="timeout-anon" needs="timeout-function" curl -s -w '\nHTTP %{http_code}\n' -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rpc/slow_count" \ -H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' -d '{"n": 400000000}' ``` ```text expect="timeout-anon" {"error":{"code":"STATEMENT_TIMEOUT","details":"","message":"canceling statement due to statement timeout","request_id":"85871810-8838-45fd-9c40-c4a264fb23c1","type":"db_unavailable","upstream_code":"57014"}} HTTP 504 ``` ```bash verify="timeout-drop" needs="timeout-function" aura db raw "drop function slow_count(bigint)" ``` ```text expect="timeout-drop" ℹ No results (0 rows). ``` ## Read the live values `max_connections` is a setting that `aura db raw` can read: ```bash verify="max-connections" aura db raw "show max_connections" ``` ```text expect="max-connections" max_connections ─────────────── 50 ℹ 1 row(s). ``` The value above was captured on a project of a Free organization. `aura db stats` shows the connections open on the database of your project against that limit, and the size of the project: ```bash verify="stats" aura db stats ``` Output (your numbers differ): ```text » Database Statistics Active connections : 0 / 50 Project size : 224.0 KB ℹ Endpoint latencies (p50/p95/p99): Studio › Logs. ``` ## Trade-offs - **The budget is shared by the organization.** On Free and Pro, the `max_connections` of the cluster serves every project of the organization, plus each awake project's PostgREST pool. A direct connection kept open by one project's ORM uses a share of it. - **Transaction mode trades session features for capacity.** Many clients share few server connections, at the cost of the session features listed above. Keep session-dependent work on the SDK or `aura db raw`, or use a dedicated cluster, where the direct connection reaches the primary without a pooler. - **No session-mode endpoint.** The direct connection of the cluster of an organization is only offered through the transaction pooler. - **Statement timeouts.** Every path through the gateway stops waiting for a long statement, after about 30 seconds by default at the latest (see [Statement timeouts](#timeouts)); this does not guarantee that PostgreSQL has stopped it. Only the direct connection has no limit. A long migration or backfill should be split into smaller statements. ## Related pages - [Connect to your database](https://aurabase.dev/en/docs/database/connect): The direct connection, with the rules that follow from the pooler. - [Shared and dedicated clusters](https://aurabase.dev/en/docs/database/clusters): Where these limits apply, and what changes on a dedicated cluster. - [How a request reaches Postgres](https://aurabase.dev/en/docs/database/request-flow): The path behind each pool. - [Performance audit](https://aurabase.dev/en/docs/database/performance): Find the slow queries that hold connections. --- ### Shared and dedicated clusters Source: https://aurabase.dev/en/docs/database/clusters.md # Shared and dedicated clusters > Where Aurabase puts the database of a new project, what the cluster of an organization shares and what a dedicated cluster adds, and what is not offered today, such as read replicas. ## Mental model A cluster is a set of PostgreSQL instances managed together: one primary that takes writes and, on some plans, standbys that copy it. Aurabase uses two kinds: - **Cluster of the organization.** Created when the organization provisions its first PostgreSQL project. Each project of the organization gets its own database on it. It is never shared with another organization. - **Dedicated cluster.** Created for one project. Its database (`app`) holds the schemas of that project only. ```text filename="two placements" cluster of the organization dedicated cluster ┌───────────────────────────────────────┐ ┌───────────────────────────────┐ │ primary │ │ primary standby standby │ │ ├─ database project_ (project A) │ │ └─ database app (project C) │ │ ├─ database project_ (project B) │ │ PgBouncer ×2 │ │ PgBouncer (transaction mode) │ └───────────────────────────────┘ └───────────────────────────────────────┘ ``` ## Which plan gets which cluster The placement is decided once, when the project is created, from the plan of its organization: | Plan of the organization when the project is created | Placement | | --- | --- | | Free, Pro | Database on the cluster of the organization | | Team, Enterprise | Dedicated cluster | A project keeps its placement afterwards: a project created on the cluster of its organization stays there when the organization changes plan. The placement only applies to PostgreSQL projects; a MongoDB project follows the [NoSQL document store](https://aurabase.dev/en/docs/nosql) path. ## Side by side | | Cluster of the organization | Dedicated cluster | | --- | --- | --- | | Shared with | The other projects of your organization | Nobody | | PostgreSQL instances | 1 | 3 (one primary, two standbys) | | `max_connections` | Free 50, Pro 100 | Team 300, Enterprise 400 | | Storage | Free 5 Gi, Pro 20 Gi | Team 50 Gi, Enterprise 100 Gi | | Direct connection | Through the PgBouncer of the cluster, transaction mode | Straight to the primary, session semantics | | PostgREST pool per replica, by default | 2 connections | 10 connections | | Extensions installed at creation | 13 (see [How extensions are installed](https://aurabase.dev/en/docs/database/extensions-model)) | At least `vector`, `pgcrypto`, `uuid-ossp`, `pg_trgm` | | SQL accepted by `aura db raw` | Same check on both | Same check on both | The values come from the provisioning code. The behaviour of the cluster of an organization was measured on a running stack; the dedicated cluster was not replayed for this page. ## Idle projects A project that receives no traffic can be put to sleep: its PostgREST server is scaled down, and when every project of an organization sleeps, the cluster of the organization can sleep too. The first request to a sleeping project starts it again and answers `503` with `Retry-After: 5` until it is ready: retry after the delay. A project paused because its subscription was cancelled answers `403` instead, and does not wake up on a request. ## Replicas and high availability - **High availability.** On a dedicated cluster the two standbys follow the primary, ready to take over if it fails. The cluster of an organization runs a single instance. - **No read replicas.** There is no command, API or Studio page to create a read replica, and no endpoint that sends reads to a standby: the SDK, the REST API, `aura db raw` and the direct connection all reach the primary. - **No logical replication to your systems.** `create publication` fails with `permission denied for database …` for the roles a project can use. For a copy of a project to work on, create a branch: `aura branch create` copies the schema and the rows into a new project. It is a copy taken once, not a replica that follows the original. ## Trade-offs - **Organization cluster: cost against isolation of resources.** Projects of one organization share CPU, memory, disk and connections. It costs less than a cluster per project, and one busy project can slow the others. - **Dedicated cluster: resources and session connections.** A project gets its own instances, standbys, and a direct connection without a transaction pooler, at the price of the Team or Enterprise plan. - **No move between placements.** Nothing moves an existing project from the cluster of its organization to a dedicated cluster. To change placement, create a project under the new plan and copy the data across, for example with `pg_dump` (see [Connect to your database](https://aurabase.dev/en/docs/database/connect#pg-dump)). ## Related pages - [Connection pooling and limits](https://aurabase.dev/en/docs/database/connection-pooling): The connection and request limits of each plan in detail. - [Project isolation](https://aurabase.dev/en/docs/database/project-isolation): What keeps projects apart on the cluster of an organization. - [How extensions are installed](https://aurabase.dev/en/docs/database/extensions-model): Why the two placements start with different extensions. - [Database branches](https://aurabase.dev/en/docs/deployment/preview-envs): A copy of a project for each pull request. --- ### How extensions are installed Source: https://aurabase.dev/en/docs/database/extensions-model.md # How extensions are installed > Understand who installs PostgreSQL extensions in a project, check what yours has, and know what to do when an extension you need is missing. ## Mental model Installing a PostgreSQL extension needs more privileges than any role of a project has: even a trusted extension requires the right to create objects in the database. So the platform installs extensions itself, with the identity of the cluster operator, when it creates the database of a project. Your roles then use them like any other type or function. ```text filename="who installs what" project creation ──▶ cluster operator ──▶ CREATE EXTENSION × 13 (in schema public) GraphQL enabled ──▶ provisioning job ──▶ CREATE EXTENSION pg_graphql your SQL ──▶ aura db raw ──▶ CREATE EXTENSION refused (400) your SQL ──▶ direct connection ──▶ refused by PostgreSQL ``` ## Installed at creation On the cluster of an organization (Free and Pro), the database of every new project is created with these 13 extensions, in the `public` schema: | Extension | Use | | --- | --- | | `vector` (pgvector) | Vector columns and similarity search | | `pgcrypto` | Hashing, encryption, `gen_random_bytes()` | | `uuid-ossp` | UUID generators such as `uuid_generate_v4()` | | `pg_trgm` | Trigram similarity and fast `LIKE` / `ILIKE` | | `citext` | Case-insensitive text | | `hstore` | Key-value pairs in one column | | `ltree` | Hierarchical labels (paths in a tree) | | `unaccent` | Text without accents, for search | | `btree_gin`, `btree_gist` | B-tree operator classes for GIN and GiST indexes | | `fuzzystrmatch` | Soundex, Levenshtein and other fuzzy matching | | `intarray` | Functions and operators on integer arrays | | `pg_stat_statements` | Query statistics, read by `aura db slow-queries`; preloaded by the cluster | `pg_graphql` is not installed at creation: it is added when you [enable GraphQL](https://aurabase.dev/en/docs/graphql) on the project (`aura projects graphql-enable`). On a dedicated cluster (Team and Enterprise), the provisioning code installs at least `vector`, `pgcrypto`, `uuid-ossp` and `pg_trgm`; that path was not replayed for this page. ## The allowed list The database service accepts 14 names: the 13 above and `pg_graphql`. Any other extension is refused before PostgreSQL sees the request. `postgis`, `pg_cron`, `timescaledb`, `pgmq` and `pg_partman` are not in the list; for scheduled work, run an Edge Function on a schedule with [Cron](https://aurabase.dev/en/docs/cron). ## Check your project ```bash verify="list" aura db extensions list ``` ```text expect="list" » Installed extensions Name Version Schema btree_gin 1.3 public btree_gist 1.8 public citext 1.8 public fuzzystrmatch 1.2 public hstore 1.8 public intarray 1.5 public ltree 1.3 public pg_stat_statements 1.12 public pg_trgm 1.6 public pgcrypto 1.4 public plpgsql 1.0 pg_catalog unaccent 1.1 public uuid-ossp 1.1 public vector 0.8.7 public ℹ 14 extension(s). Enable another allowed one with aura db extensions enable ``` `plpgsql` is the procedural language that PostgreSQL installs in every database. The Studio shows the same list under **Database › Extensions**, and `GET /v1/db/{project_id}/schema/extensions` returns it as JSON. An extension outside the allowed list is refused by the API: ```bash verify="refused" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/schema/extensions" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H 'content-type: application/json' \ -d '{"name": "postgis"}' ``` ```text expect="refused" {"error":{"code":"BAD_REQUEST","message":"Invalid request: Extension 'postgis' is not allowed on this cluster. Allowed extensions: pgcrypto, uuid-ossp, pg_trgm, citext, hstore, ltree, unaccent, vector, pg_graphql, btree_gin, btree_gist, fuzzystrmatch, intarray, pg_stat_statements","request_id":"a215bf77-8d51-48d6-b8a7-81f600b7b23d","type":"request_invalid"}} ``` ## What enable does `aura db extensions enable ` (and `POST /v1/db/{project_id}/schema/extensions`) checks the name against the allowed list, then runs `CREATE EXTENSION IF NOT EXISTS "" CASCADE` with the administrator role of the project. For an extension already installed at creation, that is a no-op that answers with its version: ```bash verify="enable" aura db extensions enable citext ``` ```text expect="enable" ✔ Extension citext enabled (version 1.8). ``` For an allowed extension that is not installed yet, the statement needs a privilege the project role does not have, and fails. This is the case of `pg_graphql`: `aura db extensions enable pg_graphql` answers `Cannot enable extension 'pg_graphql' from the project role: Invalid request: permission denied for database …`. Install it with `aura projects graphql-enable` instead, which runs as the cluster operator. `CREATE EXTENSION` sent as SQL never reaches PostgreSQL through `aura db raw`: the endpoint refuses it with `400` and points to `aura db extensions enable`. Over the direct connection, PostgreSQL refuses it: `permission denied for database …` for an extension of the image (`pg_graphql`), `extension "postgis" is not available` for one the image does not contain. ## Trade-offs - **A fixed list.** You cannot add an extension of your own, nor one that is not in the list, on a managed project. The list is the same for every project of a deployment. - **No version choice.** Each extension comes in the version of the PostgreSQL image of the cluster (for example `vector` 0.8.7 above). `ALTER EXTENSION … UPDATE` is refused: `must be owner of extension citext`. - **Older projects.** A project created before the list grew to 13 has only the extensions installed at that time, and `enable` cannot add the others from the project role. The error message of `enable` suggests contacting support or recreating the project; there is no command to backfill them. - **Extensions live in `public`.** Their functions and types are found through the search path; you do not need to qualify them. ## Related pages - [GraphQL](https://aurabase.dev/en/docs/graphql): Enable pg_graphql on a project and query it. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): The SQL check that refuses CREATE EXTENSION, and what else it refuses. - [Shared and dedicated clusters](https://aurabase.dev/en/docs/database/clusters): Why the two placements start with different extensions. - [Performance audit](https://aurabase.dev/en/docs/database/performance): Use pg_stat_statements through aura db slow-queries. --- ### Create and change tables Source: https://aurabase.dev/en/docs/database/tables.md # Create and change tables > Create a table from the terminal, a script or Studio, add and change its columns, drop it safely, and know which defaults, rights and row level security a new table receives. A table of your project lives in the PostgreSQL schema of the project. You create and change it with `aura db table`, with the schema API (`/v1/db/{project_id}/schema/tables`), with SQL sent to `aura db raw`, or from the Studio table editor. All four need the `service_role` key, and all four give the new table the same protections: a primary key, row level security switched on, and rights for the three platform roles. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples of this page create their own tables, named `sch_tables_…`, and remove them at the end. They never change a table of the example schema. ## Four ways to change the schema | Task | `aura db table` | Schema API | SQL (`aura db raw`) | Studio | | --- | --- | --- | --- | --- | | Create a table | `create "col:type,…"` | `POST /schema/tables` | `create table …` | **New table** | | List tables and columns | `list` | `GET /schema/tables`, `GET /schema/tables/{table}` | Refused on the catalogs: use the CLI or the API | Table list, **Columns** tab | | Add, rename, retype, drop a column | No command | `POST`, `PATCH`, `DELETE /schema/tables/{table}/columns/{column}` | `alter table …` | **Columns** tab | | `NOT NULL`, `UNIQUE`, `DEFAULT`, foreign key | No (every CLI column is nullable) | Column fields | Any constraint | **Columns** tab | | Drop a table | `drop ` | `DELETE /schema/tables/{table}` | `drop table …` | **Settings** tab | | Turn row level security or Realtime on or off | `rls`, `realtime` | `PATCH …/rls`, `PUT …/realtime` | `alter table … row level security` | Table header | The schema API paths start with `/v1/db/{project_id}`. The CLI covers the common case; a column constraint, a rename or a type change needs the API, SQL or Studio. Row level security and Realtime have their own pages: [Row-level security](https://aurabase.dev/en/docs/database/rls). ## Create a table with the CLI `aura db table create` takes the table name and a comma-separated list of `name:type` pairs: ```bash verify="create" aura db table create sch_tables_books "title:text,pages:int,tags:text[],published_on:date" ``` ```text expect="create" » Creating table 'sch_tables_books' ✔ Table 'sch_tables_books' created with 6 column(s). ℹ RLS enabled by default. • Columns: id, title, pages, tags, published_on, created_at ``` The types the CLI accepts are `text`, `int`, `bigint`, `float`, `numeric`, `bool`, `uuid`, `timestamp`, `timestamptz`, `tsvector`, `date`, `time`, `json`, `jsonb` and `bytea`, plus three forms with an argument: `array()` or `[]`, `vector()` and `enum()` for an enum created beforehand. A few PostgreSQL spellings are translated: `integer` becomes `int`, `boolean` becomes `bool`, `varchar` becomes `text`, `decimal` becomes `numeric`. A column written without a type is `text`. A parameter in parentheses (`numeric(10,2)`, `varchar(80)`) is refused: use SQL for it. [Choose column types](https://aurabase.dev/en/docs/database/data-types) compares the types. The summary lists `created_at` but not `updated_at`, which the server adds too (see the next section). List the tables to see every column: ```bash verify="list" needs="create" aura db table list ``` ```text expect="list" » Project tables • org_members [RLS] org_id, user_id, role, created_at • orgs [RLS] id, slug, name, created_at • posts [RLS] id, user_id, title, body, published, created_at • profiles [RLS] id, username, display_name, created_at • sch_tables_books [RLS] id, title, pages, tags, published_on, created_at, updated_at • todos [RLS] id, user_id, title, done, created_at ℹ 6 table(s). ``` `aura db table list --json` prints the same tables with each column's type, default, nullability and foreign key, and each table's indexes, unique and check constraints. ## What every new table receives A table created by the CLI, the schema API or Studio gets, in the same transaction: | Added | Exactly | When | | --- | --- | --- | | Primary key | `id uuid primary key default gen_random_uuid()` | No primary key is declared and no column is named `id`. A declared `id` column becomes the primary key. | | Creation date | `created_at timestamptz not null default now()` | No column named `created_at`. | | Update date | `updated_at timestamptz not null default now()` | No column named `updated_at`. Nothing updates it afterwards: add the trigger of [Triggers](https://aurabase.dev/en/docs/database/triggers) if you need it. | | Row level security | `enable` and `force row level security` | Always. The `rls_enabled` field of the API body is ignored at creation. | | Rights | `select`, `insert`, `update`, `delete` and `truncate` (every table privilege) to `aura_service_role`, `aura_authenticated` and `aura_anon`. The project schema grants them by default on every relation created in it (table, partition, view, materialized view), whatever the door, and the example tables have them too. | Always. These rights do not restrict rows: row level security, forced on new tables, decides which rows each role reads and writes. Keep it on every table and every partition, and revoke what the anon key must never reach (see [Views and materialized views](https://aurabase.dev/en/docs/database/views#materialized)). | With row level security on and no policy, the anon key and signed-in users see no row and cannot write: add the policies the table needs ([Row-level security](https://aurabase.dev/en/docs/database/rls)). The `service_role` key bypasses them. A table created in SQL through `aura db raw` gets row level security too: after a statement that changes the schema, the endpoint enables and forces it on every table that did not exist before, unless the same request contains `alter table disable row level security`. It does not add `id`, `created_at` or `updated_at`: SQL creates exactly the columns you write. ## Add, change and drop columns The CLI has no column command. The schema API has three routes, all with the `service_role` key: | Route | Body | Statement it runs | | --- | --- | --- | | `POST /v1/db/{project_id}/schema/tables/{table}/columns` | A column: `name`, `col_type`, `nullable`, `unique` (all four required), optional `default_val` and `references` (`{"table", "column", "on_delete"}`) | `alter table … add column …` | | `PATCH /v1/db/{project_id}/schema/tables/{table}/columns/{column}` | Any of `new_name`, `col_type`, `nullable`, `default_val`, `drop_default` | `rename column`, `alter column … type … using col::type`, `set`/`drop not null`, `set`/`drop default`, in one transaction | | `DELETE /v1/db/{project_id}/schema/tables/{table}/columns/{column}` | None | `alter table … drop column …` | `col_type` takes the type names of the CLI as JSON: `"text"`, `"bigint"`, `{"array": "text"}`, `{"vector": 1536}`, `{"enum": "mood"}`. `on_delete` takes `CASCADE`, `SET NULL`, `SET DEFAULT`, `RESTRICT` or `NO ACTION`. Add a unique `isbn` column, turn `pages` into a `bigint` with a default, then drop `tags`: ```bash verify="columns" needs="create" key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json') curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns" "${key[@]}" \ -d '{"name": "isbn", "col_type": "text", "nullable": true, "unique": true}' echo curl -s -X PATCH "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns/pages" "${key[@]}" \ -d '{"col_type": "bigint", "default_val": "0"}' echo curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns/tags" "${key[@]}" echo ``` ```text expect="columns" {"data":null,"meta":null} {"data":null,"meta":null} {"data":null,"meta":null} ``` Read the table back with `GET /v1/db/{project_id}/schema/tables/{table}`. The JSON has the columns with their type, default and nullability; the filter below keeps the fields this example changed: ```bash verify="read-table" needs="columns" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).data for (const c of t.columns) console.log(c.name, JSON.stringify(c.col_type), c.nullable ? "null" : "not null", c.default_val ?? "") console.log("unique:", JSON.stringify(t.unique_constraints))' ``` ```text expect="read-table" id "uuid" not null gen_random_uuid() title "text" null pages "bigint" null 0 published_on "date" null created_at "timestamptz" not null now() updated_at "timestamptz" not null now() isbn "text" null unique: [["isbn"]] ``` A type change rewrites the column with `using ""::`: it fails if a value cannot be cast (a `text` value `abc` cannot become a `bigint`), and the whole change is rolled back. ## Do the same in SQL `aura db raw` accepts `create table`, `alter table` and `drop table`. SQL is the way to declare what the CLI cannot: `not null`, a check, a foreign key, an identity column, a precise `numeric(10,2)`: ```sql verify="sql" create table sch_tables_loans ( id bigint generated always as identity primary key, book_id uuid not null references sch_tables_books (id) on delete cascade, borrower uuid not null, due_on date not null, fee numeric(10,2) not null default 0 check (fee >= 0) ); alter table sch_tables_books add column summary text; alter table sch_tables_books rename column summary to blurb; ``` ```text expect="sql" ℹ No results (0 rows). ``` The endpoint enabled and forced row level security on `sch_tables_loans` (it is new) and reloaded the REST API, so the table is reachable from the SDK on the next call. `todos` and the example tables use the same `generated always as identity` key as `sch_tables_loans`: their `id` is written by PostgreSQL, never by the client. [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints) covers keys, checks and cascades. ## Create a table with the schema API `POST /v1/db/{project_id}/schema/tables` takes the table as JSON. It is what the CLI and Studio send. Besides `name` and `columns`, the body accepts `primary_key` (one column) or `primary_key_columns` (several), `unique_constraints` (lists of columns), `check_constraints` (expressions), `indexes` (`name`, `columns`, `unique`, optional `method` and `where_clause`) and `realtime_enabled`. ```bash verify="api-create" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{ "name": "sch_tables_shelves", "columns": [ {"name": "label", "col_type": "text", "nullable": false, "unique": true}, {"name": "capacity", "col_type": "int", "nullable": false, "unique": false, "default_val": "50"} ], "check_constraints": ["capacity > 0"] }' ``` ```text expect="api-create" {"data":{"name":"sch_tables_shelves"},"meta":null} ``` The answer gives the name the table really has. A name that starts with a digit gets a leading `_` (`2024_events` becomes `_2024_events`). When the primary key is not a single column named `id`, the answer adds a `warning`: the table is created, but the REST routes by id (`/v1/db/{project_id}/{table}/{id}`) do not work for it; filter by the key column instead (`?sku=eq.…`). `GET /v1/db/{project_id}/schema/tables` lists the tables in the same JSON form, `GET /v1/db/{project_id}/schema/tables/{table}` returns one table or `404 NOT_FOUND`, and `DELETE /v1/db/{project_id}/schema/tables/{table}` drops it (see [Drop a table](#drop)). ## Use the Studio table editor In Studio, **Database** opens the table editor. The left panel lists the tables of the project; **New table** opens a form with the table name, the columns (name, type, nullable, default) and the primary key, and sends it to the same `POST /schema/tables` route. A selected table has these tabs: | Tab | What it does | | --- | --- | | **Data** | Browse, insert, edit and delete rows. | | **Columns** | Add, rename, retype and drop columns, through the column routes above. | | **RLS policies**, **RLS simulator** | Policies of the table; see [Row-level security](https://aurabase.dev/en/docs/database/rls). | | **Index** | Indexes; see [Indexes](https://aurabase.dev/en/docs/database/indexes). | | **Triggers**, **Functions** | See [Triggers](https://aurabase.dev/en/docs/database/triggers) and [Database functions](https://aurabase.dev/en/docs/database/functions). | | **API** | Ready-to-copy SDK and REST snippets for this table, and whether row level security is on. | | **Settings** | Row level security, Realtime and deletion of the table. | Each tab has its own address in Studio: ```text //database/sql (opens the table editor) //database/sql/table-editor Data //database/sql/table-editor/columns Columns //database/sql/table-editor/indexes Index //database/sql/table-editor/triggers Triggers //database/sql/table-editor/functions Functions //database/sql/table-editor/api API //database/sql/table-editor/settings Settings ``` The footer of the left panel links to the **SQL Editor**, the **ERD Schema** diagram ([Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema)), **Extensions** and **Backups**. ## Drop a table `aura db table drop` asks for confirmation; `--force` skips it. The CLI, the API and Studio all run `drop table if exists "" cascade`: ```bash verify="drop" needs="sql" aura db raw "create view sch_tables_late as select id from sch_tables_loans where due_on < current_date" aura db table drop sch_tables_loans --force aura db raw "select count(*) from sch_tables_late" || echo "exit code: $?" ``` ```text expect="drop" ℹ No results (0 rows). ✔ Table 'sch_tables_loans' dropped. Error: [400] BAD_REQUEST: Invalid request: relation "sch_tables_late" does not exist (line 1, column 22) exit code: 1 ``` `cascade` removes what depends on the table without asking: the view `sch_tables_late` is gone with it, and so is a foreign key that another table had towards it (the other table and its rows stay). Look for dependent views and foreign keys before you drop a table that others use. Dropping a table that does not exist succeeds and changes nothing. ## Result The project has two new tables, both protected by row level security: ```bash verify="result" needs="columns,api-create" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'for (const t of JSON.parse(require("fs").readFileSync(0, "utf8")).data) if (t.name.startsWith("sch_tables_")) console.log(t.name, "rls:", t.rls_enabled, "columns:", t.columns.map((c) => c.name).join(","))' ``` ```text expect="result" sch_tables_books rls: true columns: id,title,pages,published_on,created_at,updated_at,isbn,blurb sch_tables_shelves rls: true columns: id,label,capacity,created_at,updated_at ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `[400] BAD_REQUEST: Invalid request: Invalid Nom de table: 'my-table' — only ASCII alphanumeric characters and '_' are allowed, and the identifier must be provided exactly as it will be created (no silent sanitizing)` | A table or column name with `-`, a space or an accent. | Use letters, digits and `_` only. | | `Unrecognized type 'numeric(10,2)': only array(), vector(), and enum() accept an argument in parentheses (…)` | A type parameter in `aura db table create`. | Create the column in SQL. | | ``Invalid JSON body — missing field `nullable` at line 1 column 33`` | A column of the API body without `nullable` or `unique`. | Send all four of `name`, `col_type`, `nullable`, `unique`. | | `No column change provided` | A `PATCH` on a column with an empty body. | Send at least one of `new_name`, `col_type`, `nullable`, `default_val`, `drop_default`. | | `[404] NOT_FOUND: Not found: Table 'nope' not found` | `GET /schema/tables/{table}` on a table that does not exist. | Check the name with `aura db table list`. | | `relation "nope" does not exist` (SQL) or `404 TABLE_NOT_FOUND` (SDK, REST) | The table does not exist, or the name differs in case. | Check the name. A quoted name created in SQL (`"Books"`) keeps its capitals. | | `cannot insert a non-DEFAULT value into column "id"` (`400 POSTGREST_ERROR` from the SDK) | A value sent for a `generated always as identity` column, including in an `upsert` with `id`. | Leave `id` out of inserts; update by filter. See [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints#identity). | | `[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role role` | The schema API called with the anon key or a user token. | Use the `service_role` key, on a server. | `aura db table create` on a name that already exists answers `✔ Table '' created`, but the server runs `create table if not exists` and leaves the existing table unchanged: the columns you passed are not added. Check with `aura db table list` before you rely on them. ## Clean up Drop the tables created on this page, one with the schema API and one with the CLI. `sch_tables_books` goes last, after `sch_tables_loans`, which referenced it and is already gone: ```bash verify="clean-up" curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_shelves" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" echo aura db table drop sch_tables_books --force ``` ```text expect="clean-up" {"data":null,"meta":null} ✔ Table 'sch_tables_books' dropped. ``` ## See also - [Choose column types](https://aurabase.dev/en/docs/database/data-types): Which PostgreSQL type to pick for text, numbers, dates, JSON, arrays, enums and vectors. - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Primary keys, identity columns, unique, check, foreign keys and cascades. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): Everything aura db raw accepts and refuses. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies for the tables you create. --- ### Choose column types Source: https://aurabase.dev/en/docs/database/data-types.md # Choose column types > Choose the type of each column from what you will store and query, declare it with the CLI or SQL, and know how the SDK and the REST API return it, including where precision can be lost. Columns of an Aurabase table are PostgreSQL 18 columns: any built-in type works, plus the types of the extensions every project has installed (`vector`, `citext`, `hstore`, `ltree`). What changes the choice in practice is how the value travels as JSON to your application. This page picks a type per use, declares them, and shows what the SDK receives. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the enum `sch_types_status` and the table `sch_types_items`, then remove them. ## Choose a type | You store | Use | Avoid, and why | | --- | --- | --- | | Names, titles, free text | `text` | `varchar(n)`: no faster than `text`; add a `check (char_length(col) <= n)` if you need a limit. | | Text compared without case (emails, usernames) | `citext` | `lower()` everywhere in queries. | | Counters, quantities | `int` (up to 2,147,483,647) or `bigint` | `float` for counts. | | Money, prices | `numeric(12,2)` | `float` or `double precision`: `0.1 + 0.2` is not `0.3`. `money` depends on the locale settings. | | Measures, scores | `double precision` | `numeric` when exactness does not matter: slower. | | A moment in time | `timestamptz` | `timestamp`: it has no time zone, so two servers may read it differently. | | A calendar day, a time of day, a duration | `date`, `time`, `interval` | Text dates. | | Yes or no | `boolean` | `int` flags. | | Row ids | `bigint generated always as identity` or `uuid default gen_random_uuid()` | `serial` (older form of identity). | | A fixed list of states | An enum, or `text` with a `check` | Free `text` with no check. | | A small list of values | `text[]`, `int[]` | A join table, when you need to query or constrain each element. | | Documents with a loose shape | `jsonb` | `json`: kept as typed, not indexable with GIN, slower to query. | | Embeddings for semantic search | `vector()` | `float[]`: no distance operators, no vector index. | | Files | Aurabase Storage, with the path in a `text` column | `bytea` for large files. | | Full-text search | `tsvector` | `like '%…%'` on large tables. | | Tree paths, key/value pairs, IP addresses | `ltree`, `hstore`, `inet` | Text you parse yourself. | `uuid-ossp` and `pgcrypto` are installed too, but `gen_random_uuid()` is built into PostgreSQL and needs neither. The list of installed extensions is on [Extensions](https://aurabase.dev/en/docs/database/extensions-model). ## CLI and API type names `aura db table create` and the schema API use short names. Each maps to one PostgreSQL type: | CLI and API | PostgreSQL | CLI and API | PostgreSQL | | --- | --- | --- | --- | | `text` | `text` | `timestamptz` | `timestamp with time zone` | | `int` | `integer` | `timestamp` | `timestamp without time zone` | | `bigint` | `bigint` | `date`, `time` | `date`, `time` | | `float` | `double precision` | `json`, `jsonb` | `json`, `jsonb` | | `numeric` | `numeric` (no precision) | `bytea`, `tsvector` | `bytea`, `tsvector` | | `bool` | `boolean` | `array()` or `[]` | `[]` | | `uuid` | `uuid` | `vector()` | `vector()` | | | | `enum()` | The enum type ``, which must exist | The schema API also accepts `inet`, `interval` and `money`. Anything else (`numeric(12,2)`, `citext`, `ltree`, `int4range`, a domain) is created in SQL with `aura db raw`. ## Create a table with every family ```sql verify="create" create type sch_types_status as enum ('draft', 'published', 'archived'); create table sch_types_items ( id bigint generated always as identity primary key, name text not null, email citext, price numeric(10,2), big_amount numeric, quantity int, views bigint, ratio double precision, in_stock boolean not null default true, status sch_types_status not null default 'draft', tags text[] not null default '{}', attributes jsonb not null default '{}', published_at timestamptz, local_time timestamp, due_on date, duration interval, embedding vector(3), raw_bytes bytea ); insert into sch_types_items (name, email, price, big_amount, quantity, views, ratio, status, tags, attributes, published_at, local_time, due_on, duration, embedding, raw_bytes) values ('Lamp', 'Ada@Example.com', 19.90, 12345678901234567890.123, 3, 9007199254740993, 0.1, 'published', '{home,light}', '{"color": "black", "watts": 40}', '2026-11-21 10:00:00+01', '2026-11-21 10:00:00', '2026-12-01', '1 day 2 hours', '[0.1,0.2,0.3]', '\x6869'); ``` ```text expect="create" ℹ No results (0 rows). ``` ## How values come back in the SDK The SDK and the REST API return rows as JSON, and JavaScript parses JSON numbers as 64-bit floats. Read the row back: ```typescript verify="sdk-read" needs="create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.db.from('sch_types_items').select('*').single() if (error) throw error for (const [column, value] of Object.entries(data as Record)) { console.log(column.padEnd(12), typeof value, JSON.stringify(value)) } ``` ```text expect="sdk-read" id number 1 name string "Lamp" email string "Ada@Example.com" price number 19.9 big_amount number 12345678901234567000 quantity number 3 views number 9007199254740992 ratio number 0.1 in_stock boolean true status string "published" tags object ["home","light"] attributes object {"color":"black","watts":40} published_at string "2026-11-21T09:00:00+00:00" local_time string "2026-11-21T10:00:00" due_on string "2026-12-01" duration string "1 day 02:00:00" embedding string "[0.1,0.2,0.3]" raw_bytes string "\\x6869" ``` What to read from this output: - **`numeric` and `bigint` arrive as JSON numbers.** `price` lost its trailing zero (`19.9`), `big_amount` lost its last digits and `views` (253 + 1) became 9007199254740992. Any integer above 9,007,199,254,740,991 and any decimal with more than about 15 significant digits is rounded by `JSON.parse`. See the next section. - **`timestamptz` comes back with a `+00:00` offset** (ISO 8601, UTC), whatever offset was written: `10:00:00+01` was returned as `09:00:00+00:00`. Sessions of the REST API run with the time zone `Etc/UTC`. `timestamp` comes back exactly as stored, without an offset. Convert to the user's time zone in your application. - **`interval` uses the PostgreSQL text form** (`1 day 02:00:00`), not ISO 8601. - **`vector` arrives as a string** (`"[0.1,0.2,0.3]"`): parse it with `JSON.parse` before using the numbers. - **`bytea` arrives as a hex string** (`\x6869`), which is why large binary data belongs in Storage. - **Arrays and `jsonb` arrive as JSON** arrays and objects, ready to use. - `citext` keeps the case you wrote (`Ada@Example.com`) and compares without it. ## Keep big numbers exact Cast the column to `text` in the select list, and convert it in your code with a decimal or `BigInt` library: ```typescript verify="sdk-text" needs="create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.db.from('sch_types_items').select('price::text, big_amount::text, views::text').single() console.log(data, error) console.log(BigInt((data as { views: string }).views) + 1n) ``` ```text expect="sdk-text" { price: '19.90', big_amount: '12345678901234567890.123', views: '9007199254740993' } null 9007199254740994n ``` An id generated by `bigint generated always as identity` stays far below 253 in practice; the risk is with values imported from elsewhere (snowflake ids, amounts in the smallest currency unit of a large total). ## Enums An enum is a type with a fixed, ordered list of labels. Create it in SQL, then use it in SQL or with the CLI (`aura db table create orders "status:enum(order_status)"`). A value outside the list is refused before the row is written: ```typescript verify="enum-refused" needs="create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const bad = await admin.db.from('sch_types_items').insert({ name: 'Desk', status: 'deleted' }) console.log(bad.error?.status, bad.error?.code, bad.error?.message) ``` ```text expect="enum-refused" 400 INVALID_INPUT invalid input value for enum sch_types_status: "deleted" ``` Add a label with `alter type`. PostgreSQL does not let a new label be used in the transaction that adds it, and each `aura db raw` call is one transaction, so add it in one call and use it in the next: ```bash verify="enum-add" needs="create" aura db raw "alter type sch_types_status add value 'deleted' after 'archived'" aura db raw "insert into sch_types_items (name, status) values ('Desk', 'deleted') returning name, status" ``` ```text expect="enum-add" ℹ No results (0 rows). name │ status ─────┼──────── Desk │ deleted ℹ 1 row(s). ``` A label cannot be removed or renamed in place by a simple statement (`alter type … rename value` renames, removing needs a new type). When the list changes often, prefer `text` with a `check` constraint, which you can replace in one statement. `GET /v1/db/{project_id}/schema` returns each enum with its labels in order ([Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema)). ## JSON and JSONB Use `jsonb`: PostgreSQL stores it parsed, so it can be indexed and queried with `->`, `->>` and `@>`. `json` keeps the text as written (key order, duplicates) and only makes sense to store a payload byte for byte. Filter on a key from the SDK with `contains`: ```typescript verify="jsonb" needs="create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const lamps = await admin.db .from('sch_types_items') .select('name, attributes->>color') .contains('attributes', { color: 'black' }) .contains('tags', ['home']) console.log(lamps.data, lamps.error) ``` ```text expect="jsonb" [ { name: 'Lamp', color: 'black' } ] null ``` To make such filters fast on a large table, add a GIN index: [Indexes](https://aurabase.dev/en/docs/database/indexes). ## Vectors `vector` comes from pgvector, installed in every project at creation. Declare the dimension of your embedding model (`vector(1536)`), then order by distance: `<->` is the Euclidean distance, `<=>` the cosine distance, `<#>` the negative inner product. ```bash verify="vector" needs="create" aura db raw "select name, round((embedding <-> '[0.1,0.2,0.4]')::numeric, 3) as distance from sch_types_items where embedding is not null order by embedding <-> '[0.1,0.2,0.4]' limit 5" ``` ```text expect="vector" distance │ name ─────────┼───── 0.1 │ Lamp ℹ 1 row(s). ``` A vector of another length is refused with `expected 3 dimensions, not 2`. For similarity search on many rows, add an `hnsw` or `ivfflat` index ([Indexes](https://aurabase.dev/en/docs/database/indexes)). ## Result The table holds two rows; one enum label was added: ```bash verify="result" needs="enum-add" aura db raw "select name, status, price from sch_types_items order by id" ``` ```text expect="result" name │ price │ status ─────┼───────┼────────── Lamp │ 19.9 │ published Desk │ NULL │ deleted ℹ 2 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400 INVALID_INPUT invalid input value for enum sch_types_status: "deleted"` (SQLSTATE `22P02`) | A label that is not in the enum. | Send one of the labels, or add it with `alter type … add value`. | | `400 INVALID_INPUT invalid input syntax for type bigint: "abc"` | Text sent to a numeric column, or a filter on an `id` with a non-number. | Send a number; check the filter value. | | `400 NUMERIC_OUT_OF_RANGE` (SQLSTATE `22003`) | A value larger than the column allows (`int` above 2,147,483,647, `numeric(10,2)` above 99,999,999.99). | Use `bigint` or a wider `numeric`. | | `unsafe use of new value "deleted" of enum type sch_types_status (…) Hint: New enum values must be committed before they can be used.` | The new label is used in the transaction that added it. | Add the label in one request, use it in the next. | | `expected 3 dimensions, not 2` | A vector of the wrong length. | Use the dimension declared on the column. | | A large number differs by a few units in your app | `JSON.parse` rounded a `bigint` or `numeric`. | Select it as `col::text`. | ## Clean up Drop the table first, then the enum type it used: ```sql verify="clean-up" needs="create" drop table sch_types_items; drop type sch_types_status; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Create and change tables](https://aurabase.dev/en/docs/database/tables): Declare columns with the CLI, the schema API, SQL or Studio. - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Keys, checks and relations between tables. - [Indexes](https://aurabase.dev/en/docs/database/indexes): GIN for JSONB and arrays, HNSW for vectors. - [Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types): Turn your schema, enums included, into types for the SDK. --- ### Constraints and foreign keys Source: https://aurabase.dev/en/docs/database/constraints.md # Constraints and foreign keys > Let PostgreSQL refuse bad data: pick a primary key, link tables with foreign keys and the right delete rule, add checks to existing tables, and handle each violation from the SDK. Constraints are rules PostgreSQL checks on every write, whatever the door: SDK, REST, `aura db raw` or a direct connection. A row that breaks one is refused and nothing is written. Declare them in SQL with `aura db raw`; the schema API and Studio cover the common ones (`not null`, `unique`, `check`, a foreign key per column). ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the tables `sch_cons_authors`, `sch_cons_books` and `sch_cons_bookings`, then remove them. In the example schema, `org_members.org_id` references `orgs (id) on delete cascade`, and `org_members` has the composite primary key `(org_id, user_id)`. ## Constraint kinds | Constraint | Guarantees | SDK error | SQLSTATE | | --- | --- | --- | --- | | `primary key` | One row per key; implies `not null` and `unique`. | `409 DUPLICATE_KEY` | `23505` | | `unique` | No two rows with the same values (several `null` are allowed unless `nulls not distinct`). | `409 DUPLICATE_KEY` | `23505` | | `not null` | A value is always present. | `400 NOT_NULL_VIOLATION` | `23502` | | `check (…)` | An expression is true for every row. | `400 CHECK_VIOLATION` | `23514` | | `references` (foreign key) | The referenced row exists. | `409 FOREIGN_KEY_VIOLATION` | `23503` | | `exclude using gist (…)` | No two rows conflict on an operator, such as overlapping time ranges. | `400 POSTGREST_ERROR` | `23P01` | The SQLSTATE is in the `upstream_code` field of the REST error body. `aura db raw` answers `400 BAD_REQUEST` with the PostgreSQL message for all of them. ## Declare constraints ```sql verify="create" create table sch_cons_authors ( id bigint generated always as identity primary key, name text not null ); create table sch_cons_books ( id bigint generated by default as identity primary key, author_id bigint not null references sch_cons_authors (id) on delete cascade, isbn text not null unique, title text not null, price numeric(10,2) not null check (price >= 0), constraint sch_cons_books_title_per_author unique (author_id, title) ); create table sch_cons_bookings ( room text not null, during tstzrange not null, exclude using gist (room with =, during with &&) ); insert into sch_cons_authors (name) values ('Ursula'), ('Octavia'); insert into sch_cons_books (author_id, isbn, title, price) values (1, '978-0441478125', 'The Left Hand of Darkness', 9.99), (2, '978-0807083697', 'Kindred', 12.50); insert into sch_cons_bookings values ('A', '[2026-12-01 09:00+00, 2026-12-01 10:00+00)'); ``` ```text expect="create" ℹ No results (0 rows). ``` The exclusion constraint compares `room` with `=` inside a GiST index, which needs the `btree_gist` extension: it is installed in every project. A constraint without a name gets one from PostgreSQL (`sch_cons_books_isbn_key`, `sch_cons_books_price_check`, `sch_cons_books_author_id_fkey`); name the ones you will look for in error messages. ## What a violation returns Each insert below breaks one constraint: ```typescript verify="violations" needs="create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const show = (label: string, r: { error: { status?: number; code?: string; message?: string } | null }) => console.log(label.padEnd(10), r.error ? `${r.error.status} ${r.error.code} ${r.error.message}` : 'ok') show('unique', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '978-0807083697', title: 'Other', price: 1 })) show('foreign', await admin.db.from('sch_cons_books').insert({ author_id: 99, isbn: '1', title: 'Ghost', price: 1 })) show('not null', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '2', price: 1 })) show('check', await admin.db.from('sch_cons_books').insert({ author_id: 1, isbn: '3', title: 'Cheap', price: -1 })) show('exclusion', await admin.db.from('sch_cons_bookings').insert({ room: 'A', during: '[2026-12-01 09:30+00, 2026-12-01 11:00+00)' })) show('identity', await admin.db.from('sch_cons_authors').insert({ id: 7, name: 'Iain' })) ``` ```text expect="violations" unique 409 DUPLICATE_KEY duplicate key value violates unique constraint "sch_cons_books_isbn_key" foreign 409 FOREIGN_KEY_VIOLATION insert or update on table "sch_cons_books" violates foreign key constraint "sch_cons_books_author_id_fkey" not null 400 NOT_NULL_VIOLATION null value in column "title" of relation "sch_cons_books" violates not-null constraint check 400 CHECK_VIOLATION new row for relation "sch_cons_books" violates check constraint "sch_cons_books_price_check" exclusion 400 POSTGREST_ERROR conflicting key value violates exclusion constraint "sch_cons_bookings_room_during_excl" identity 400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id" ``` The full error body also carries `details` (for a duplicate, `Key (isbn)=(978-0807083697) already exists.`) and the SQLSTATE in `upstream_code`. Branch on `error.code` in your application, and show `details` only to people allowed to see the other row. ## Identity columns and upserts An identity column draws its value from a sequence: - `generated always as identity` refuses any value from the client (`cannot insert a non-DEFAULT value into column "id"`), including an `id` inside an `upsert()`. `todos`, `posts` and `orgs` of the example schema use it. In SQL, `overriding system value` forces a value, for imports only. - `generated by default as identity` accepts a value from the client and uses the sequence otherwise. If you insert ids yourself, the sequence does not move: the next generated id can collide with yours (`409 DUPLICATE_KEY` on `…_pkey`). - `uuid default gen_random_uuid()`, the default of tables created by the CLI, lets the client choose the id before the insert, which suits offline writes and ids generated in the browser. `upsert()` of the SDK (and `POST` with `?on_conflict=` on the REST API) currently answers `409 DUPLICATE_KEY` when the row already exists, instead of updating it: measured with SDK 0.7.5 on a unique column and on a primary key. Until this is fixed, update an existing row by filter (`update(…).eq('isbn', …)`) or use `insert … on conflict … do update` in SQL: ```bash verify="on-conflict" needs="create" aura db raw "insert into sch_cons_books (author_id, isbn, title, price) values (2, '978-0807083697', 'Kindred', 14) on conflict (isbn) do update set price = excluded.price returning isbn, price" ``` ```text expect="on-conflict" isbn │ price ───────────────┼────── 978-0807083697 │ 14.0 ℹ 1 row(s). ``` To offer the same to signed-in users, wrap the statement in a `security invoker` function and call it with `rpc()`: [Database functions](https://aurabase.dev/en/docs/database/functions). ## Delete rules of foreign keys `on delete` decides what happens to the rows that point to a deleted row: | Rule | Effect | Use it for | | --- | --- | --- | | `no action` (default), `restrict` | The delete is refused while rows point to it (`23503`). | Data that must not disappear silently, such as invoices. | | `cascade` | The pointing rows are deleted too. | Rows that belong to the parent: members of an org, books of an author in this example. | | `set null` | The pointing column becomes `null` (it must be nullable). | Optional links, such as the last editor of a page. | | `set default` | The pointing column takes its default. | A fallback owner. | `on update` takes the same rules. Delete the first author: her book goes with her. ```bash verify="cascade" needs="create" aura db raw "delete from sch_cons_authors where name = 'Ursula'" aura db raw "select title from sch_cons_books order by title" ``` ```text expect="cascade" ℹ No results (0 rows). title ─────── Kindred ℹ 1 row(s). ``` PostgreSQL does not create an index on the referencing column. Add one (`create index on sch_cons_books (author_id)`) when the parent table is large or often deleted from: [Indexes](https://aurabase.dev/en/docs/database/indexes). ## Ids and relationships Coming from a document database, model each kind of document as a table and each reference as a foreign key column: | Relationship | Model | Example schema | | --- | --- | --- | | One to many | A foreign key on the "many" side | `posts.user_id`, `todos.user_id` | | One to one | A foreign key with `unique`, or the same primary key | `profiles.id` is the id of the user | | Many to many | A join table with two foreign keys and a composite primary key | `org_members (org_id, user_id)` | The SDK reads related rows in one request through foreign keys (`select('title, sch_cons_authors(name)')`); see [Query data with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk). A user id from Aurabase Auth is a `uuid`: store it in a `uuid` column, and compare it to `auth.uid()` in policies. ## Add a constraint to an existing table `alter table … add constraint` checks every existing row and fails if one breaks the rule. On a large table, add it `not valid` (new writes are checked at once), fix the old rows, then validate: ```sql verify="existing" needs="create" alter table sch_cons_books add constraint sch_cons_books_isbn_format check (isbn ~ '^[0-9-]+$') not valid; alter table sch_cons_books validate constraint sch_cons_books_isbn_format; ``` ```text expect="existing" ℹ No results (0 rows). ``` Remove a constraint with `alter table … drop constraint `. The schema API sets `not null`, `unique`, a default and a foreign key per column (see [Create and change tables](https://aurabase.dev/en/docs/database/tables#columns)); everything else goes through SQL. ## Result ```bash verify="result" needs="existing" aura db raw "select b.title, a.name as author, b.price from sch_cons_books b join sch_cons_authors a on a.id = b.author_id" ``` ```text expect="result" author │ price │ title ────────┼───────┼──────── Octavia │ 14.0 │ Kindred ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `409 DUPLICATE_KEY duplicate key value violates unique constraint "…"` | A value already used in a unique column or key. | Change the value, or update the existing row. | | `409 FOREIGN_KEY_VIOLATION … violates foreign key constraint "…"` | The referenced row does not exist, or a delete of a referenced row under `no action`. | Insert the parent first; choose a delete rule. | | `400 NOT_NULL_VIOLATION null value in column "…" … violates not-null constraint` | A required column is missing from the insert. | Send it, or give the column a default. | | `400 CHECK_VIOLATION new row for relation "…" violates check constraint "…"` | A value outside the rule. | Send a valid value. | | `400 POSTGREST_ERROR conflicting key value violates exclusion constraint "…"` | Two rows conflict, such as overlapping bookings. | Pick a free slot. | | `400 POSTGREST_ERROR cannot insert a non-DEFAULT value into column "id"` | A value sent to a `generated always as identity` column. | Leave `id` out. | | `check constraint "…" of relation "…" is violated by some row` | `add constraint` on a table with rows that break the rule. | Add it `not valid`, fix the rows, then `validate constraint`. | ## Clean up ```sql verify="clean-up" needs="create" drop table sch_cons_bookings; drop table sch_cons_books; drop table sch_cons_authors; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Create and change tables](https://aurabase.dev/en/docs/database/tables): Columns, defaults and the schema API. - [Choose column types](https://aurabase.dev/en/docs/database/data-types): Types for ids, money, dates and ranges. - [Database functions](https://aurabase.dev/en/docs/database/functions): Wrap an insert … on conflict in a function callable with rpc(). - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that decide which rows each user writes. --- ### Views and materialized views Source: https://aurabase.dev/en/docs/database/views.md # Views and materialized views > Save a query as a view that each caller reads through its own policies, precompute heavy aggregates in a materialized view, refresh it, and lock down what row level security cannot protect. A view is a named query: reading it runs the query. A materialized view stores the result of the query and serves it until you refresh it. You create both in SQL, with `aura db raw` or the Studio SQL editor; there is no CLI or schema API command for views. The SDK and the REST API read them like tables, by name. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the view `sch_views_open` and the materialized view `sch_views_counts`, then remove them. `open_todos` of the example schema is a view of the same kind. ## View or materialized view | | View | Materialized view | | --- | --- | --- | | Data | Read from the tables at each query | Stored when created or refreshed | | Freshness | Always current | As of the last `refresh` | | Row level security | Applies: Aurabase makes views run with the caller's rights | Does not apply: the stored rows are the same for everyone | | Who can read it by default | Anon, signed-in users and `service_role`, each limited by the policies of the tables | Anon, signed-in users and `service_role`, every row: revoke it | | Indexes | Those of the tables | Its own (`create index on …`) | | Good for | Hiding columns, joining tables, a stable shape for the API | Dashboards and costly aggregates read often and refreshed on a schedule | ## Create a view ```sql verify="create" create view sch_views_open as select id, user_id, title, created_at from todos where not done; ``` ```text expect="create" ℹ No results (0 rows). ``` The view appears in `GET /v1/db/{project_id}/schema` under `views` and in the **ERD Schema** page of Studio. `create or replace view` changes its query as long as the existing columns keep their names and types; otherwise drop it and create it again. ## Views run with the caller's rights By default PostgreSQL runs a view with the rights of its owner, which would let anyone who can read the view see every row of `todos`. After each request that changes the schema, the `aura db raw` endpoint (and the migrations endpoint used by `aura db push`) sets `security_invoker = true` on every view of the project that has no such option. The view then runs with the rights of the caller, and the policies of `todos` decide what each caller sees: ```bash verify="as-callers" needs="create" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000b2 "select title from sch_views_open" aura db raw --as anon "select count(*) as visible from sch_views_open" aura db raw "select count(*) as visible from sch_views_open" ``` ```text expect="as-callers" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000b2). title ───────────────── Invite a teammate ℹ 1 row(s). ℹ Executed as anon. visible ─────── 0 ℹ 1 row(s). visible ─────── 3 ℹ 1 row(s). ``` The signed-in user sees its own open todo, the anon key sees none, the `service_role` key sees the three open todos of the seed. The same holds through the SDK: ```typescript verify="sdk-anon" needs="create" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const { data, error } = await aura.from('sch_views_open').select('title') console.log(data, error) ``` ```text expect="sdk-anon" [] null ``` The option is only added when a view has none. A view created `with (security_invoker = false)` keeps that setting: it runs with the owner's rights and ignores the policies of its tables. Since every new relation of the project grants all table privileges to `aura_anon` and `aura_authenticated`, the anon key can then read every row through it, and, when the view is updatable (one table, no aggregate), also insert, update and delete rows of the table through the REST API: the policies of the table are not checked (measured on a view of a table with row level security and no policy). Never create such a view. If one exists, switch it with `alter view set (security_invoker = true)`, and revoke from the public roles what they must not do through it, for example `revoke all on from aura_anon, aura_authenticated` (the anon key then gets `403 INSUFFICIENT_PRIVILEGE permission denied for view …`). A view created through the direct PostgreSQL connection is not adjusted either: add `with (security_invoker = true)` yourself. ## Create a materialized view A materialized view stores rows, and PostgreSQL has no row level security on it. Like any new relation of the project, it is readable by `aura_anon` and `aura_authenticated` until you revoke it, and they would read every row. Create it and revoke in the same request: ```sql verify="materialized" create materialized view sch_views_counts as select user_id, count(*)::int as todos, count(*) filter (where done)::int as done from todos group by user_id; create unique index sch_views_counts_user on sch_views_counts (user_id); revoke select on sch_views_counts from aura_anon, aura_authenticated; ``` ```text expect="materialized" ℹ No results (0 rows). ``` The anon key is now refused, and the `service_role` key, on a server, reads it: ```typescript verify="mv-access" needs="materialized" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const anon = await aura.from('sch_views_counts').select('*') console.log('anon:', anon.error?.status, anon.error?.code, anon.error?.message) const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const server = await admin.db.from('sch_views_counts').select('todos, done').order('todos') console.log('service_role:', server.data, server.error) ``` ```text expect="mv-access" anon: 403 INSUFFICIENT_PRIVILEGE permission denied for materialized view sch_views_counts service_role: [ { todos: 1, done: 0 }, { todos: 3, done: 1 } ] null ``` To give each user its own figures from a materialized view, keep it revoked and expose a `security definer` function that filters on `auth.uid()`: [Database functions](https://aurabase.dev/en/docs/database/functions). The function is the only door, and it decides what each caller gets. ## Refresh a materialized view A new todo does not appear in the stored result until a refresh: ```bash verify="refresh" needs="materialized" aura db raw "insert into todos (user_id, title) values ('00000000-0000-4000-8000-0000000000b2', 'Plan the sprint')" aura db raw "select todos from sch_views_counts where user_id = '00000000-0000-4000-8000-0000000000b2'" aura db raw "refresh materialized view concurrently sch_views_counts" aura db raw "select todos from sch_views_counts where user_id = '00000000-0000-4000-8000-0000000000b2'" ``` ```text expect="refresh" ℹ No results (0 rows). todos ───── 1 ℹ 1 row(s). ℹ No results (0 rows). todos ───── 2 ℹ 1 row(s). ``` `concurrently` lets readers keep reading during the refresh; PostgreSQL requires a unique index on plain columns of the view for it, hence `sch_views_counts_user` above. Without `concurrently`, the refresh is faster but blocks reads of the view until it ends. Aurabase does not refresh materialized views for you, and `pg_cron` is not among the extensions of a project. Refresh from your code after the writes that matter, or from a scheduled job on your side that sends `refresh materialized view concurrently …` to `aura db raw` or `POST /v1/db/{project_id}/raw`. A refresh runs under the statement timeout of the endpoint (10 seconds by default): a view that takes longer to compute needs a smaller query, or the direct connection. ## Write through a view A view over a single table, without aggregates, `distinct` or `group by`, accepts `insert`, `update` and `delete`, which PostgreSQL applies to the table. The policies of the table still apply, since the view runs with the caller's rights (a view with `security_invoker = false` skips them: see above). Add `with check option` to refuse writes that would produce a row the view does not show: through such a view of open todos, setting `done = true` fails with `new row violates check option for view "…"`. A view with joins or aggregates is read-only: write to the tables, or through a function. ## Result ```bash verify="result" needs="create,materialized" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/schema" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8")).data.views.map((v) => v.name).sort().join("\n"))' ``` ```text expect="result" open_todos sch_views_counts sch_views_open ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `403 INSUFFICIENT_PRIVILEGE permission denied for materialized view …` | The materialized view was revoked from the caller's role. | Read it with the `service_role` key, or through a function. | | An empty array for a signed-in user or the anon key | The view runs with the caller's rights and no policy of the table lets this role read the rows. | Add a policy to the table ([Row-level security](https://aurabase.dev/en/docs/database/rls)), not to the view. | | `cannot refresh materialized view "…" concurrently` with `Hint: Create a unique index with no WHERE clause on one or more columns of the materialized view.` | `concurrently` without a unique index. | Create one on columns that identify each row. | | `"…" is not a view` with `Hint: Use DROP MATERIALIZED VIEW to remove a materialized view.` | `drop view` on a materialized view. | `drop materialized view …`. | | `cannot drop table … because other objects depend on it` with `Hint: Use DROP ... CASCADE to drop the dependent objects too.` | A plain `drop table` in SQL on a table used by a view. | Drop the view first. The CLI and the schema API drop with `cascade`, which removes the view silently. | | `cannot change name of view column "…" to "…"` with `Hint: Use ALTER VIEW ... RENAME COLUMN ... to change name of view column instead.` | `create or replace view` with a renamed column. | `alter view … rename column`, or drop and create the view. | ## Clean up Drop the two views and the todo added for the refresh: ```sql verify="clean-up" needs="create,materialized" drop materialized view sch_views_counts; drop view sch_views_open; delete from todos where title = 'Plan the sprint'; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Row-level security](https://aurabase.dev/en/docs/database/rls): The policies that views apply for each caller. - [Database functions](https://aurabase.dev/en/docs/database/functions): A controlled door to data that callers must not read directly. - [Indexes](https://aurabase.dev/en/docs/database/indexes): Indexes on tables behind a view, and on materialized views. - [Roles, keys and row level security bypass](https://aurabase.dev/en/docs/database/roles-and-keys): Which role each key uses. --- ### Indexes Source: https://aurabase.dev/en/docs/database/indexes.md # Indexes > Make the slow queries of your project fast: pick the index type for the query, create it in SQL or Studio, confirm with EXPLAIN that PostgreSQL uses it, and drop the ones that only cost writes. An index lets PostgreSQL find rows without reading the whole table. It speeds up the queries that match its columns and slows down every insert, update and delete a little, since each index is updated with the table. Create one for a query you have measured, not for every column. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the table `sch_idx_events` with 20,000 rows, then remove it. The example schema already has two indexes: `todos_user_id_idx` and `posts_user_id_idx`. ## Choose an index | Query | Index | Example | | --- | --- | --- | | `=`, `<`, `>`, `between`, `order by` on one column | B-tree (the default) | `create index on todos (user_id)` | | No duplicates allowed | Unique (or a `unique` constraint) | `create unique index on profiles (lower(username))` | | Filter on one column, sort on another | Composite, filtered column first | `(user_id, created_at desc)` | | A small, often-read part of the table | Partial | `… (created_at) where kind = 'error'` | | A function of a column | Expression | `… (lower(email))` | | `jsonb` containment (`@>`), keys (`?`) | GIN | `using gin (payload jsonb_path_ops)` | | Arrays (`@>`, `&&`), full text (`@@`) | GIN | `using gin (tags)`, `using gin (search)` | | `like '%word%'`, similarity | GIN with `pg_trgm` | `using gin (title gin_trgm_ops)` | | Ranges, overlaps, exclusion constraints | GiST | `using gist (during)` | | Very large tables in time order | BRIN | `using brin (created_at)` | | Nearest vectors | HNSW or IVFFlat (pgvector) | `using hnsw (embedding vector_cosine_ops)` | A primary key and each `unique` constraint already create a B-tree index. A foreign key does not: index the referencing column when you filter on it or delete from the parent table. `pg_trgm`, `btree_gin`, `btree_gist` and `vector` are installed in every project. ## Where to create an index | Door | What it can create | | --- | --- | | SQL with `aura db raw` or the Studio SQL editor | Any index, except `concurrently` (see [Large tables](#large)). | | Studio, **Index** tab of a table | Columns, unique, method (`btree`, `gin`, `gist`, `hash`, `brin`, `hnsw`, `ivfflat`) and an optional `where` clause; it runs the `create index` as a migration of the project. | | Schema API, `POST /v1/db/{project_id}/schema/tables` | The `indexes` of a table at its creation only (`name`, `columns`, `unique`, `method`, `where_clause`). The index is named `
_`. | | `aura db table` | No index command. | ## A table to index ```sql verify="setup" create table sch_idx_events ( id bigint generated always as identity primary key, user_id uuid not null, kind text not null, payload jsonb not null default '{}', created_at timestamptz not null default now() ); insert into sch_idx_events (user_id, kind, payload, created_at) select ('00000000-0000-4000-8000-' || lpad((i % 500)::text, 12, '0'))::uuid, case when i % 50 = 0 then 'error' else 'view' end, jsonb_build_object('page', '/p/' || (i % 40), 'ms', i % 900), timestamptz '2026-11-01' + i * interval '1 minute' from generate_series(1, 20000) as i; analyze sch_idx_events; ``` ```text expect="setup" ℹ No results (0 rows). ``` `analyze` refreshes the statistics the planner uses; PostgreSQL also does it in the background after enough writes. ## Read the plan before `explain` shows how PostgreSQL will run a query, without running it. `(costs off)` hides the estimates, which change from one run to the next: ```bash verify="before" needs="setup" aura db raw "explain (costs off) select id, kind from sch_idx_events where user_id = '00000000-0000-4000-8000-000000000042' order by created_at desc limit 10" ``` ```text expect="before" QUERY PLAN ────────────────────────────────────────────────────────────────────────────── Limit -> Sort Sort Key: created_at DESC -> Seq Scan on sch_idx_events Filter: (user_id = '00000000-0000-4000-8000-000000000042'::uuid) ℹ 5 row(s). ``` `Seq Scan` reads all 20,000 rows to keep the 40 of this user, then sorts them. `explain analyze` runs the query and adds the real times and row counts; use it on reads only, since it executes the statement. ## Create the indexes ```sql verify="create" needs="setup" create index sch_idx_events_user_created on sch_idx_events (user_id, created_at desc); create index sch_idx_events_errors on sch_idx_events (created_at) where kind = 'error'; create index sch_idx_events_payload on sch_idx_events using gin (payload jsonb_path_ops); ``` ```text expect="create" ℹ No results (0 rows). ``` - `sch_idx_events_user_created` serves "the latest events of a user": the filter column first, then the sort column in the order of the query. - `sch_idx_events_errors` only holds the 400 `error` rows: small, and used by any query that has `kind = 'error'` in its filter. - `sch_idx_events_payload` serves `payload @> '{…}'`. `jsonb_path_ops` is smaller and faster for `@>` than the default `jsonb_ops`, but does not support the key operators `?`, `?|`, `?&`. ## Read the plan after ```bash verify="after" needs="create" aura db raw "explain (costs off) select id, kind from sch_idx_events where user_id = '00000000-0000-4000-8000-000000000042' order by created_at desc limit 10" aura db raw "explain (costs off) select id from sch_idx_events where payload @> '{\"page\": \"/p/7\"}'" ``` ```text expect="after" QUERY PLAN ──────────────────────────────────────────────────────────────────────────── Limit -> Index Scan using sch_idx_events_user_created on sch_idx_events Index Cond: (user_id = '00000000-0000-4000-8000-000000000042'::uuid) ℹ 3 row(s). QUERY PLAN ────────────────────────────────────────────────────────────── Bitmap Heap Scan on sch_idx_events Recheck Cond: (payload @> '{"page": "/p/7"}'::jsonb) -> Bitmap Index Scan on sch_idx_events_payload Index Cond: (payload @> '{"page": "/p/7"}'::jsonb) ℹ 4 row(s). ``` The first query reads the index in order and stops after ten entries: no sort, no full scan. On a small table PostgreSQL may keep a `Seq Scan` even with an index, because reading a few pages is cheaper; judge an index on realistic volumes. ## Index vectors Without an index, a nearest-neighbour query compares the query vector with every row. HNSW gives fast approximate results; build it with the operator class of the distance you order by (`vector_l2_ops` for `<->`, `vector_cosine_ops` for `<=>`, `vector_ip_ops` for `<#>`): ```sql verify="vector" create table sch_idx_docs (id bigint generated always as identity primary key, embedding vector(3)); insert into sch_idx_docs (embedding) values ('[1,0,0]'), ('[0,1,0]'), ('[0.9,0.1,0]'); create index sch_idx_docs_embedding on sch_idx_docs using hnsw (embedding vector_cosine_ops); ``` ```text expect="vector" ℹ No results (0 rows). ``` Building an HNSW index on many rows takes memory and time: on a large table, build it through the direct connection (see below). [Choose column types](https://aurabase.dev/en/docs/database/data-types#vector) shows the distance operators. ## Large tables and concurrent builds `create index` blocks writes to the table while it builds. `create index concurrently` avoids that, but PostgreSQL refuses it inside a transaction, and `aura db raw` runs every request in one: ```bash verify="concurrently" needs="setup" aura db raw "create index concurrently sch_idx_events_kind on sch_idx_events (kind)" || echo "exit code: $?" ``` ```text expect="concurrently" Error: [400] BAD_REQUEST: Invalid request: CREATE INDEX CONCURRENTLY cannot run inside a transaction block exit code: 1 ``` A build also has to finish within the statement timeout of the endpoint, 10 seconds by default. For a large table, connect with the direct connection ([Connect to your database](https://aurabase.dev/en/docs/database/connect#direct)), which runs statements outside a transaction and has no statement timeout, and run `create index concurrently` there. ## Find unused indexes `/raw` refuses the catalog views (`pg_indexes`, `pg_stat_user_indexes`), so `aura db inspect indexes` reads them for you: each index with its table, size, number of scans since the statistics were last reset, and an `unused` flag for indexes never scanned that are neither unique nor primary. ```bash verify="inspect" needs="create" aura db inspect indexes | grep -c 'sch_idx_events' ``` ```text expect="inspect" 4 ``` Output of `aura db inspect indexes` (sizes and scan counts differ on your project): ```text » Inspect: indexes index_name | is_unique | scans | size_bytes | table_name | unused sch_idx_events_payload | false | 1 | 65536 | sch_idx_events | false sch_idx_events_errors | false | 0 | 16384 | sch_idx_events | true … ℹ 1 unused index(es) (never scanned, not unique/primary): consider dropping them. ``` An index that stays unused under real traffic only costs writes and storage: drop it with `drop index `. Studio shows the indexes of a table in its **Index** tab. Slow queries themselves are listed by `aura db slow-queries`; see [Performance](https://aurabase.dev/en/docs/database/performance). ## Result The table has its three new indexes, with their method and the condition of the partial one. `aura db table list --json` lists the indexes of each table except the primary key's: ```bash verify="result" needs="create" aura db table list --json | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).find((x) => x.name === "sch_idx_events") for (const i of t.indexes) console.log(i.name, i.method ?? "", i.where_clause ?? "")' ``` ```text expect="result" sch_idx_events_errors btree (kind = 'error'::text) sch_idx_events_payload gin sch_idx_events_user_created btree ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `CREATE INDEX CONCURRENTLY cannot run inside a transaction block` | `concurrently` through `aura db raw`, the SDK `db.sql()` or the Studio SQL editor. | Use the direct connection, or a plain `create index` on a small table. | | `relation "…" already exists` | An index (or table) with the same name exists in the project. | Pick another name, or `create index if not exists`. | | A message containing `the query ran longer than this project's statement timeout (10 s)` | The build took longer than the endpoint allows (10 s by default). | Build it through the direct connection. | | `could not create unique index "…"` | A unique index on a column that already has duplicates. | Remove the duplicates first. | | A `Seq Scan` remains after creating the index | Small table, stale statistics, or a filter that does not match the index (a function, another column order). | `analyze
`; match the indexed expression and column order. | ## Clean up Dropping the tables drops their indexes: ```sql verify="clean-up" drop table if exists sch_idx_events; drop table if exists sch_idx_docs; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Performance](https://aurabase.dev/en/docs/database/performance): Slow queries, pg_stat_statements and the other diagnostics of a project. - [Choose column types](https://aurabase.dev/en/docs/database/data-types): JSONB, arrays and vectors, and their operators. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): The direct connection, for long or concurrent index builds. - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Unique constraints and the indexes they create. --- ### Partitions and retention Source: https://aurabase.dev/en/docs/database/partitions.md # Partitions and retention > Partition an append-heavy table by month, keep every partition behind row level security, add the next partitions ahead of time and drop expired ones, knowing the limits of partitioned tables on Aurabase. A partitioned table is a parent that holds no rows itself and routes each row to a child table, its partition, by the value of a key such as the creation date. Queries that filter on the key only read the partitions they need, and dropping a whole month of data is one `drop table` instead of a long `delete`. You create and maintain partitions in SQL with `aura db raw`; Aurabase does not create or drop them for you. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the partitioned table `sch_part_events` and its partitions `sch_part_events_…`, then remove them. ## When to partition Partition when a table grows by time (events, logs, measurements), most queries read a recent period, and old data expires. Below a few million rows, an index on the date column ([Indexes](https://aurabase.dev/en/docs/database/indexes)) and a batched `delete` are simpler. Partitioning adds rules: the partition key must be part of every primary key and unique constraint, and each partition is a table you create, protect and drop. ## What Aurabase automates and what it does not | | Status | | --- | --- | | Creating future partitions of your tables | Not automated. Create them ahead of time (see [Add the next partitions](#next)). `pg_partman` and `pg_cron` are not among the extensions of a project. | | Dropping expired partitions of your tables | Not automated. Drop or detach them yourself (see [Drop expired data](#retention)). | | Row level security on new partitions | Not applied by `aura db raw` (measured): enable it yourself (see [Protect every partition](#rls)). | | Retention of the platform's own tables in your project | Automated, see below. These tables belong to Storage, Realtime, notifications and AI; they are not yours to change. | Aurabase runs two kinds of background jobs, and neither reads or drops your tables: - **Retention inside your project's database.** Rows of the platform's own append-only tables are deleted when they are older than a window. The values below are the defaults of the deployment. | Table (internal schemas of the project) | Kept for | How often | | --- | --- | --- | | Notification attempts | 30 days | Once a day, in batches of 5,000 rows | | Notification events | 7 days | Once a day, in batches of 5,000 rows | | AI request logs | 90 days | Once a day, in batches of 5,000 rows | | Storage audit log | 90 days | Once a day, in batches of 5,000 rows | | Realtime database changes (`postgres_changes`), kept only to replay them after a reconnection | 1 hour (10 minutes at least) | Every 10 minutes | | Realtime broadcast and presence messages, on dedicated databases | 72 hours (1 hour at least) | Every 10 minutes | - **Maintenance of the platform's console database.** Once a day, jobs create the next monthly partitions of the account audit log (three months ahead), drop its partitions older than 24 months, and delete usage events older than 90 days and platform audit events older than 90 days, by default. This database is the platform's, outside your project's database. ## Create a partitioned table Range partitions by month, plus a default partition that catches rows outside every range: ```sql verify="create" create table sch_part_events ( id bigint generated always as identity, user_id uuid not null, kind text not null, created_at timestamptz not null default now(), primary key (id, created_at) ) partition by range (created_at); create table sch_part_events_2026_11 partition of sch_part_events for values from ('2026-11-01') to ('2026-12-01'); create table sch_part_events_2026_12 partition of sch_part_events for values from ('2026-12-01') to ('2027-01-01'); create table sch_part_events_default partition of sch_part_events default; create index sch_part_events_user on sch_part_events (user_id, created_at); ``` ```text expect="create" ℹ No results (0 rows). ``` The primary key includes `created_at` because PostgreSQL requires the partition key in every unique constraint of a partitioned table. The index created on the parent is created on every partition, present and future. Other strategies exist: `partition by list (region)` for a fixed set of values, `partition by hash (user_id)` to spread rows evenly. ## Write and read through the parent Always write to and read from the parent; PostgreSQL routes each row: ```bash verify="routing" needs="create" aura db raw "insert into sch_part_events (user_id, kind, created_at) values ('00000000-0000-4000-8000-0000000000a1', 'login', '2026-11-21'), ('00000000-0000-4000-8000-0000000000a1', 'login', '2026-12-02'), ('00000000-0000-4000-8000-0000000000b2', 'login', '2027-03-15') returning tableoid::regclass::text as partition, created_at::date as day" ``` ```text expect="routing" day │ partition ───────────┼──────────────────────── 2026-11-21 │ sch_part_events_2026_11 2026-12-02 │ sch_part_events_2026_12 2027-03-15 │ sch_part_events_default ℹ 3 row(s). ``` The March row had no monthly partition and went to the default one. A query that filters on `created_at` skips the partitions that cannot match: ```bash verify="pruning" needs="create" aura db raw "explain (costs off) select count(*) from sch_part_events where created_at >= '2026-12-01' and created_at < '2027-01-01'" ``` ```text expect="pruning" QUERY PLAN ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Aggregate -> Seq Scan on sch_part_events_2026_12 sch_part_events Filter: ((created_at >= '2026-12-01 00:00:00+00'::timestamp with time zone) AND (created_at < '2027-01-01 00:00:00+00'::timestamp with time zone)) ℹ 3 row(s). ``` The SDK and the REST API reach the parent like any table (`from('sch_part_events')`). They do not expose the partitions themselves: `from('sch_part_events_2026_11')` answers `404 TABLE_NOT_FOUND`. ## Protect every partition `aura db raw` enables and forces row level security on new tables after a schema change, but not on partitions. The parent is protected; the partitions are not, and they carry the default rights of the project's relations, so the anon role could read or write a partition by its name in SQL (for example inside a function or a view you expose). `aura db table list` shows it: ```bash verify="rls-before" needs="create" aura db table list --json | node -e 'for (const t of JSON.parse(require("fs").readFileSync(0, "utf8"))) if (t.name.startsWith("sch_part_")) console.log(t.name, "rls:", t.rls_enabled)' ``` ```text expect="rls-before" sch_part_events_2026_11 rls: false sch_part_events_2026_12 rls: false sch_part_events_default rls: false ``` The list shows the partitions but not the parent `sch_part_events`. Enable row level security on each partition when you create it. With no policy on the partition, direct access is refused to every role except `service_role`, while reads and writes through the parent keep following the parent's policies: ```bash verify="rls-on" needs="create" for p in sch_part_events_2026_11 sch_part_events_2026_12 sch_part_events_default; do aura db table rls "$p" on done aura db raw --as anon "select count(*) as visible from sch_part_events_2026_11" ``` ```text expect="rls-on" ✔ RLS enabled on 'sch_part_events_2026_11'. ✔ RLS enabled on 'sch_part_events_2026_12'. ✔ RLS enabled on 'sch_part_events_default'. ℹ Executed as anon. visible ─────── 0 ℹ 1 row(s). ``` In SQL, the same is `alter table enable row level security; alter table force row level security;` in the request that creates the partition. Add the policies your callers need on the parent: [Row-level security](https://aurabase.dev/en/docs/database/rls). ## Add the next partitions A row whose date falls in no range goes to the default partition, which grows without limit and blocks the creation of a partition whose range overlaps rows it already holds. Create the partitions of the coming months in advance, for example once a month from a scheduled job of yours that calls `aura db raw` or `POST /v1/db/{project_id}/raw`: ```sql verify="next" needs="create" create table if not exists sch_part_events_2027_01 partition of sch_part_events for values from ('2027-01-01') to ('2027-02-01'); alter table sch_part_events_2027_01 enable row level security; alter table sch_part_events_2027_01 force row level security; ``` ```text expect="next" ℹ No results (0 rows). ``` ## Drop expired data Dropping a partition removes its rows at once, without scanning them and without leaving dead rows to vacuum: ```bash verify="retention" needs="routing" aura db raw "drop table sch_part_events_2026_11" aura db raw "select count(*) as events from sch_part_events" ``` ```text expect="retention" ℹ No results (0 rows). events ────── 2 ℹ 1 row(s). ``` To keep the data outside the live table (archive, export), detach the partition instead: `alter table sch_part_events detach partition sch_part_events_2026_12` turns it into a standalone table. The `concurrently` form, which avoids blocking the parent, is refused by `aura db raw` because it cannot run inside a transaction: ```bash verify="detach" needs="create" aura db raw "alter table sch_part_events detach partition sch_part_events_2026_12 concurrently" || echo "exit code: $?" ``` ```text expect="detach" Error: [400] BAD_REQUEST: Invalid request: ALTER TABLE ... DETACH CONCURRENTLY cannot run inside a transaction block exit code: 1 ``` On a table that is not partitioned, expire rows with a `delete … where created_at < …` limited in size (a few thousand rows per request), since each request must finish within the statement timeout of the endpoint (10 seconds by default). ## Limits of partitioned tables | Feature | Behavior with a partitioned table | | --- | --- | | `aura db table list`, `GET /v1/db/{project_id}/schema` | List the partitions, not the parent. | | `GET /v1/db/{project_id}/schema/dump`, `aura db pull` | Omit the parent and its partitions: the exported schema does not recreate them. Keep their `create table` statements in your migrations. | | Preview branches | A project with a partitioned table cannot be branched: the clone refuses partitioned and inherited tables. | | SDK and REST API | Reach the parent only. | | Realtime | Not tested with partitioned tables. | ## Result ```bash verify="result" needs="next,retention" aura db raw "select tableoid::regclass::text as partition, count(*) as events from sch_part_events group by 1 order by 1" ``` ```text expect="result" events │ partition ───────┼──────────────────────── 1 │ sch_part_events_2026_12 1 │ sch_part_events_default ℹ 2 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `unique constraint on partitioned table must include all partitioning columns` | A primary key or unique constraint without the partition key. | Add the key column (`primary key (id, created_at)`). | | `no partition of relation "…" found for row` | No partition covers the value and there is no default partition. | Create the partition, or a default one. | | `updated partition constraint for default partition "…" would be violated by some row` | A new partition overlaps rows already in the default partition. | Move those rows out of the default partition first, then create the partition. | | `ALTER TABLE ... DETACH CONCURRENTLY cannot run inside a transaction block` | `concurrently` through `aura db raw`. | Detach without `concurrently`, or use the direct connection. | | `404 TABLE_NOT_FOUND` on a partition from the SDK | The REST API does not expose partitions. | Query the parent. | ## Clean up Dropping the parent drops every partition attached to it: ```sql verify="clean-up" needs="create" drop table sch_part_events; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Indexes](https://aurabase.dev/en/docs/database/indexes): BRIN and B-tree indexes on dates, an alternative for moderate volumes. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies on the parent table. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): The direct connection, for operations that cannot run in a transaction. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): The endpoint used for partition maintenance. --- ### Database functions Source: https://aurabase.dev/en/docs/database/functions.md # Database functions > Put logic next to your data: create a SQL or PL/pgSQL function, decide who may call it, call it from the SDK, and know when a security definer function is the right door and how to keep it safe. A database function is SQL or PL/pgSQL stored in your project's schema. Your application calls it with `rpc()` of the SDK or `POST /v1/db/rpc/{name}`, a trigger runs it on writes, and SQL calls it like any function. Database functions are not Edge Functions: `aura db function` manages the first, `aura functions` the second. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create functions named `sch_fn_…`, then remove them. `todo_count(p_user uuid)` of the example schema is a function of the same kind, granted to signed-in users. ## Where to create a function | Door | Command | Notes | | --- | --- | --- | | CLI | `aura db function create`, `list`, `drop` | Sends the function API calls below. | | Function API | `POST /v1/db/{project_id}/functions`, `GET /v1/db/{project_id}/functions`, `DELETE /v1/db/{project_id}/functions/{name}` | `service_role` key for all three. | | SDK | `db.createFunction()`, `db.listFunctions()`, `db.dropFunction()` | Same API, from a server with the `service_role` key. | | SQL | `create function …` with `aura db raw` | Any argument mode, `returns table (…)`, dynamic `execute`. `security definer` is refused. | | Studio | **Functions** tab of the table editor | Lists, creates (name, arguments, return type, language, security, `GRANT EXECUTE TO`, body) and drops functions, through the function API. | The function API takes a `name`, `args` (each `name`, `data_type`, `mode`), `returns`, `language` (`sql` or `plpgsql`), `body` (without the enclosing `$$`), and optional `security` (`invoker` or `definer`) and `grant_execute_to` (a list of roles). ## Create a function with the CLI A SQL function that counts the open todos of a user, callable by signed-in users: ```bash verify="create" aura db function create sch_fn_open_count \ --language sql --returns bigint --args "p_user:uuid" \ --body 'select count(*) from todos where user_id = p_user and not done' \ --grant-execute-to authenticated ``` ```text expect="create" ✔ Function 'sch_fn_open_count' created (sql → bigint). • EXECUTE granted to: authenticated ``` `--args` takes `name:type` pairs separated by commas, `--body-file` reads the body from a file, `--language` defaults to `plpgsql` and `--returns` to `void`. ## What the server enforces | Rule | Detail | | --- | --- | | `security invoker` by default | The function runs with the rights of its caller, so the policies of the tables it reads apply. `--security definer` must be asked for. | | A fixed `search_path` | Every function is created with `set search_path = `: names in the body resolve in your schema, whoever calls it. | | Nobody can call a new function | `EXECUTE` is revoked from `PUBLIC` and from every platform role, then granted to the roles of `--grant-execute-to` only. Re-creating a function resets its grants the same way. | | Allowed grantees | `anon`, `authenticated`, `service_role` (or their PostgreSQL names `aura_anon`, `aura_authenticated`, `aura_service_role`). | | Arguments | `in` mode only. Other modes, `returns table (…)` and default values need SQL. | | Body | Checked like an `aura db raw` query, and stricter: no dynamic `execute`, no change to row level security. | | One signature per name | Re-creating a function with other argument types is refused, since PostgreSQL would add a second function next to the first. Drop it first. | A function created in SQL through `aura db raw` gets no `EXECUTE` for the platform roles either (measured: the anon key gets `403 INSUFFICIENT_PRIVILEGE` on it): grant it yourself with `grant execute on function () to aura_authenticated`. It has no fixed `search_path` unless you write `set search_path = …` in its definition. ## Call it with rpc() The SDK calls a function with `rpc(name, args)`. A signed-in user creates a todo, then counts its open todos; the anon key is refused, since the function was granted to `authenticated` only: ```typescript verify="call" needs="create" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const anon = await aura.rpc('sch_fn_open_count', { p_user: '00000000-0000-4000-8000-0000000000a1' }) console.log('anon:', anon.error?.status, anon.error?.code) const email = `functions-${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 await aura.from('todos').insert({ user_id: me, title: 'Call a database function' }) const mine = await aura.rpc('sch_fn_open_count', { p_user: me }) console.log('mine:', mine.data, mine.error) const alice = await aura.rpc('sch_fn_open_count', { p_user: '00000000-0000-4000-8000-0000000000a1' }) console.log('alice, seen by this user:', alice.data) ``` ```text expect="call" anon: 403 INSUFFICIENT_PRIVILEGE mine: 1 null alice, seen by this user: 0 ``` The function is `security invoker`: for this user, the owner policy of `todos` hides Alice's rows, so her count is `0`. Arguments are sent by name, as JSON. Over REST, the same call is `POST /v1/db/rpc/sch_fn_open_count` with the body `{"p_user": "…"}` and the user's token or a key in the headers. The sign-up above works because email confirmation is turned off on the test project; a project requires it by default. ## A PL/pgSQL function from the SDK PL/pgSQL adds variables, conditions and error messages. This function adds a todo for the signed-in user and refuses an empty title; `auth.uid()` reads the user from the request: ```typescript verify="plpgsql" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const created = await admin.db.createFunction({ name: 'sch_fn_add_todo', args: [{ name: 'p_title', data_type: 'text', mode: 'IN' }], returns: 'bigint', language: 'plpgsql', body: ` declare new_id bigint; begin if coalesce(trim(p_title), '') = '' then raise exception 'title is required'; end if; insert into todos (user_id, title) values (auth.uid(), p_title) returning id into new_id; return new_id; end`, grant_execute_to: ['authenticated'], }) console.log('created:', created.error) const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `plpgsql-${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 { error } = await aura.auth.signInWithPassword({ email, password }) if (error) throw error const ok = await aura.rpc('sch_fn_add_todo', { p_title: 'Write a PL/pgSQL function' }) console.log('ok:', typeof ok.data, ok.error) const empty = await aura.rpc('sch_fn_add_todo', { p_title: ' ' }) console.log('empty:', empty.error?.status, empty.error?.message) ``` ```text expect="plpgsql" created: null ok: number null empty: 400 title is required ``` `raise exception` ends the function, rolls back what it wrote, and reaches the client as a `400` with your message. Since the function is `security invoker`, the insert still goes through the `with check` of the owner policy of `todos`. ## Security invoker or definer | | `security invoker` (default) | `security definer` | | --- | --- | --- | | Runs with the rights of | The caller | The owner of the function, the project's administrator role | | Row level security | Applies to the caller | Bypassed: the function reads and writes every row | | Created by | The CLI, the API, the SDK, SQL | The CLI, the API and the SDK only: `aura db raw` refuses `security definer` | | Use it for | Almost everything | A controlled exception: a count across all users, a write the caller may not do directly | A definer function decides on its own what each caller gets. Filter with `auth.uid()` inside it, grant it to `authenticated` only, and validate every argument. Granted to `anon`, a definer function that reads `todos` returns data of every user to anyone with the anon key. Here is a narrow one, which tells a signed-in user how many todos exist in the project without showing any of them: ```bash verify="definer" aura db function create sch_fn_total_todos \ --language sql --returns bigint \ --body 'select count(*) from todos' \ --security definer --grant-execute-to authenticated ``` ```text expect="definer" ✔ Function 'sch_fn_total_todos' created (sql → bigint). • EXECUTE granted to: authenticated ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's. ``` `aura db function list` shows `SECURITY DEFINER` for such functions; review them when you audit the project. ## List and drop functions `aura db function list` prints each function with its arguments, return type, language, security mode and the roles that hold `EXECUTE`. The administrator role of the project (`tenant__admin`) always holds it; `--json` returns the same as `GET /v1/db/{project_id}/functions`: ```bash verify="list" needs="create,definer" aura db function list --json | node -e 'for (const f of JSON.parse(require("fs").readFileSync(0, "utf8"))) console.log(f.name, f.security, f.grant_execute_to.filter((r) => !r.startsWith("tenant_")).join(",") || "(nobody)")' ``` ```text expect="list" sch_fn_add_todo INVOKER aura_authenticated sch_fn_open_count INVOKER aura_authenticated sch_fn_total_todos DEFINER aura_authenticated todo_count INVOKER aura_authenticated ``` Drop a function by name. The server resolves its signature; a name shared by several functions (overloads created in SQL) is refused rather than guessed: ```bash verify="drop" needs="create" aura db function drop sch_fn_open_count --force ``` ```text expect="drop" ✔ Function 'sch_fn_open_count' dropped (or already absent). ``` Dropping a function that a trigger uses fails: drop the trigger first ([Triggers](https://aurabase.dev/en/docs/database/triggers)). The same three operations over HTTP, from any language, with the `service_role` key: ```bash verify="http" key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json') curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/functions" "${key[@]}" -d '{ "name": "sch_fn_greet", "args": [{"name": "p_name", "data_type": "text", "mode": "IN"}], "returns": "text", "language": "sql", "body": "select '"'"'Hello, '"'"' || p_name", "grant_execute_to": ["authenticated"]}' echo curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/functions" "${key[@]}" \ | node -e 'const f = JSON.parse(require("fs").readFileSync(0, "utf8")).data.find((x) => x.name === "sch_fn_greet") console.log(f.name, f.language, f.return_type, f.security, JSON.stringify(f.args))' curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/functions/sch_fn_greet" "${key[@]}" echo ``` ```text expect="http" {"data":null,"meta":null} sch_fn_greet SQL text INVOKER [{"name":"p_name","data_type":"text","mode":"IN"}] {"data":null,"meta":null} ``` And from a server with the SDK, `db.listFunctions()` and `db.dropFunction()` (with `db.createFunction()` shown above): ```typescript verify="sdk-manage" needs="plpgsql" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const listed = await admin.db.listFunctions() const mine = listed.data?.find((f) => f.name === 'sch_fn_add_todo') console.log(mine?.language, mine?.security, mine?.grant_execute_to.filter((r) => !r.startsWith('tenant_'))) const dropped = await admin.db.dropFunction('sch_fn_add_todo') console.log('dropped:', dropped.error) ``` ```text expect="sdk-manage" PLPGSQL INVOKER [ 'aura_authenticated' ] dropped: null ``` ## Result ```bash verify="result" needs="definer" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000b2 "select sch_fn_total_todos() as total, todo_count('00000000-0000-4000-8000-0000000000a1') as alices_seen" ``` ```text expect="result" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000b2). alices_seen │ total ────────────┼────── 0 │ 6 ℹ 1 row(s). ``` The definer function counts every todo of the project; the invoker function `todo_count` sees none of Alice's for this user. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `403 INSUFFICIENT_PRIVILEGE permission denied for function …` | The caller's role has no `EXECUTE`. | `--grant-execute-to authenticated` (CLI) or `grant execute on function … to aura_authenticated` (SQL). | | `404 FUNCTION_NOT_FOUND`, with a hint such as `Perhaps you meant to call the function todo_count(p_user)` | No function with this name and these argument names. | Send the arguments by their exact names. | | ``Invalid request: A function '…' already exists in this project with a DIFFERENT signature (…)`` | Re-creating a function with other argument types. | `aura db function drop --force`, then create it. | | ``'EXECUTE' is not allowed in a function body: SQL built at run time escapes any textual validation by nature.`` | Dynamic SQL in a body sent to the function API. | Write the statement out. | | `The 'SECURITY DEFINER' option is not allowed in raw queries (privilege escalation).` | `security definer` in `aura db raw`. | Create it with `aura db function create --security definer`. | | `Invalid GRANT EXECUTE role: 'public'. Accepted values: anon, authenticated, service_role, aura_anon, aura_authenticated, aura_service_role` | A role the CLI does not accept. | Use one of the listed roles. | | `Invalid Language: 'js'. Accepted values: plpgsql, sql` | Another language. | Use `sql` or `plpgsql`. | | `[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role role` | The function API, including `GET /functions`, called with the anon key or a user token. | Use the `service_role` key, on a server. | ## Clean up Remove the remaining functions and the todos added by the examples: ```bash verify="clean-up" needs="definer,plpgsql" aura db function drop sch_fn_total_todos --force aura db function drop sch_fn_add_todo --force aura db raw "delete from todos where title in ('Call a database function', 'Write a PL/pgSQL function')" ``` ```text expect="clean-up" ✔ Function 'sch_fn_total_todos' dropped (or already absent). ✔ Function 'sch_fn_add_todo' dropped (or already absent). ℹ No results (0 rows). ``` The test users created by the examples stay in the project; delete them with `aura auth users delete `. ## See also - [Triggers](https://aurabase.dev/en/docs/database/triggers): Run a function automatically on insert, update or delete. - [Row-level security](https://aurabase.dev/en/docs/database/rls): The policies that a security invoker function applies. - [Roles, keys and row level security bypass](https://aurabase.dev/en/docs/database/roles-and-keys): Which role each key uses, and what a definer function runs as. - [Query data with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): rpc() and the other read and write methods. --- ### Triggers Source: https://aurabase.dev/en/docs/database/triggers.md # Triggers > Attach a function to the writes of a table: maintain updated_at, record who changed what in an audit table, fire only when a column changes, and list or remove the triggers of a table. A trigger runs a function each time a table is written, in the same transaction as the write. It runs whatever the door (SDK, REST, `aura db raw`, a direct connection), so a rule enforced by a trigger cannot be bypassed by a client. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the tables `sch_trg_notes` and `sch_trg_audit` and functions named `sch_trg_…`, then remove them. ## How a trigger runs | Choice | Values | Effect | | --- | --- | --- | | Timing | `before`, `after`, `instead_of` (views only; the CLI and the API take `instead_of`, SQL writes `instead of`) | `before` can change or cancel the row; `after` sees the final row and cannot change it. | | Events | `insert`, `update`, `delete`, `truncate` | Any combination. | | Granularity | `for each row`, `for each statement` | Once per row, or once per statement whatever the number of rows. `truncate` is statement only. | The function returns `trigger` and reads the row through `NEW` (insert, update) and `OLD` (update, delete), and the operation through `TG_OP`. A `before` row trigger returns `NEW`, possibly modified, to write it, or `NULL` to skip the row. The return value of an `after` trigger is ignored; return `NULL`. An error raised in the function cancels the whole write. A trigger function needs no `EXECUTE` grant: PostgreSQL checks it when the trigger is created, not when it fires. The CLI warning "the function cannot be called by ANYONE" concerns direct calls only; the trigger fires for every caller (measured with a signed-in user). ## Where to create a trigger | Door | Command | Covers | | --- | --- | --- | | CLI | `aura db trigger create
--function --timing … --events … --for-each …`, `list
`, `drop
` | Timing, events, granularity. | | Trigger API | `POST /v1/db/{project_id}/{table}/triggers` (`name`, `timing`, `events`, `function_name`, `for_each`), `GET` the same path, `DELETE /v1/db/{project_id}/{table}/triggers/{name}` | Same as the CLI. `service_role` key. | | SDK | `db.createTrigger(table, …)`, `db.listTriggers(table)`, `db.dropTrigger(table, name)` | Same as the CLI, from a server. | | SQL | `create trigger …` with `aura db raw` | Everything: `when (…)` conditions, `update of `, arguments, transition tables. | | Studio | **Triggers** tab of the table editor | Lists, creates and drops the triggers of a table. | The function must exist first, in the project schema, with no arguments and `returns trigger`: create it with [Database functions](https://aurabase.dev/en/docs/database/functions) (`--returns trigger`). ## Keep updated_at current Tables created by the CLI, the schema API and Studio have an `updated_at` column, set at insert and never updated afterwards. A `before update` trigger fixes that: ```bash verify="updated-at" aura db table create sch_trg_notes "body:text" aura db function create sch_trg_touch --returns trigger \ --body 'begin new.updated_at := now(); return new; end' aura db trigger create sch_trg_notes sch_trg_notes_touch \ --function sch_trg_touch --timing before --events update ``` ```text expect="updated-at" » Creating table 'sch_trg_notes' ✔ Table 'sch_trg_notes' created with 3 column(s). ℹ RLS enabled by default. • Columns: id, body, created_at ✔ Function 'sch_trg_touch' created (plpgsql → trigger). ⚠ No GRANT EXECUTE: the server revoked EXECUTE from PUBLIC and all known roles — the function cannot be called by ANYONE. • Add --grant-execute-to authenticated to expose it. ✔ Trigger 'sch_trg_notes_touch' created on 'sch_trg_notes' (BEFORE UPDATE FOR EACH ROW). • Executes function 'sch_trg_touch'. ``` Write a note with an old date, then update it. `now()` is the start time of the current transaction, so `updated_at = now()` is true only if the trigger set it in this request: ```bash verify="touch" needs="updated-at" aura db raw "insert into sch_trg_notes (body, created_at, updated_at) values ('first draft', '2026-01-01', '2026-01-01')" aura db raw "update sch_trg_notes set body = 'second draft' where body = 'first draft' returning body, updated_at = now() as touched" ``` ```text expect="touch" ℹ No results (0 rows). body │ touched ─────────────┼──────── second draft │ true ℹ 1 row(s). ``` The same function serves every table that has an `updated_at` column: create one trigger per table. ## Write an audit log An `after` trigger can record each change in another table. The audit table must not be writable by your users, otherwise they could forge or erase entries. Keep it closed (row level security with no policy) and make the trigger function `security definer`, so that it, and only it, writes there: ```bash verify="audit" needs="updated-at" aura db raw "create table sch_trg_audit ( id bigint generated always as identity primary key, table_name text not null, op text not null, row_id uuid, changed_by uuid, old_row jsonb, new_row jsonb, at timestamptz not null default now())" aura db function create sch_trg_audit_row --returns trigger --security definer --body " begin insert into sch_trg_audit (table_name, op, row_id, changed_by, old_row, new_row) values (TG_TABLE_NAME, TG_OP, coalesce(new.id, old.id), auth.uid(), case when TG_OP <> 'INSERT' then to_jsonb(old) end, case when TG_OP <> 'DELETE' then to_jsonb(new) end); return null; end" aura db trigger create sch_trg_notes sch_trg_notes_audit \ --function sch_trg_audit_row --timing after --events insert,update,delete ``` ```text expect="audit" ℹ No results (0 rows). ✔ Function 'sch_trg_audit_row' created (plpgsql → trigger). ⚠ No GRANT EXECUTE: the server revoked EXECUTE from PUBLIC and all known roles — the function cannot be called by ANYONE. • Add --grant-execute-to authenticated to expose it. ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's. ✔ Trigger 'sch_trg_notes_audit' created on 'sch_trg_notes' (AFTER INSERT OR UPDATE OR DELETE FOR EACH ROW). • Executes function 'sch_trg_audit_row'. ``` A signed-in user who may edit notes (the policy below lets every signed-in user do so, for the example) updates one; the audit row records who did it, before and after: ```bash verify="audit-run" needs="audit,touch" aura db raw "create policy sch_trg_notes_edit on sch_trg_notes for all to aura_authenticated using (true) with check (true)" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "update sch_trg_notes set body = 'final' where body = 'second draft'" aura db raw "select op, changed_by, old_row->>'body' as before, new_row->>'body' as after from sch_trg_audit" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select count(*) as visible from sch_trg_audit" ``` ```text expect="audit-run" ℹ No results (0 rows). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). ℹ No results (0 rows). after │ before │ changed_by │ op ──────┼──────────────┼──────────────────────────────────────┼─────── final │ second draft │ 00000000-0000-4000-8000-0000000000a1 │ UPDATE ℹ 1 row(s). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). visible ─────── 0 ℹ 1 row(s). ``` `auth.uid()` returns the user of the request, or `null` for the `service_role` key and for SQL without `--as`. The user cannot read the audit table: it has no policy. ## Fire only when a column changes The CLI and the API create triggers without conditions. A condition (`when`), a column list (`update of body`) or arguments need SQL. This version of the `updated_at` trigger only fires when `body` really changes: ```sql verify="when" needs="updated-at" drop trigger sch_trg_notes_touch on sch_trg_notes; create trigger sch_trg_notes_touch before update of body on sch_trg_notes for each row when (old.body is distinct from new.body) execute function sch_trg_touch(); ``` ```text expect="when" ℹ No results (0 rows). ``` A `when` condition is checked before the function is called, which is cheaper than testing inside the function. ## List and drop triggers `aura db trigger list
--json` returns one entry per trigger, with its events in an array (the same as `GET /v1/db/{project_id}/{table}/triggers`): ```bash verify="list" needs="audit,when" aura db trigger list sch_trg_notes --json ``` ```text expect="list" [ { "events": [ "DELETE", "INSERT", "UPDATE" ], "function_name": "EXECUTE FUNCTION sch_trg_audit_row()", "name": "sch_trg_notes_audit", "table_name": "sch_trg_notes", "timing": "AFTER" }, { "events": [ "UPDATE" ], "function_name": "EXECUTE FUNCTION sch_trg_touch()", "name": "sch_trg_notes_touch", "table_name": "sch_trg_notes", "timing": "BEFORE" } ] ``` The trigger API and the SDK do the same from a server. Here they make the audit table append-only: a function that refuses the write, attached `before update or delete` at statement level through HTTP, then listed and dropped with the SDK: ```bash verify="http" needs="audit" key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json') curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/functions" "${key[@]}" \ -d '{"name": "sch_trg_refuse", "args": [], "returns": "trigger", "language": "plpgsql", "body": "begin raise exception '"'"'% is append-only'"'"', TG_TABLE_NAME; end"}' echo curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers" "${key[@]}" \ -d '{"name": "sch_trg_audit_lock", "timing": "before", "events": ["update", "delete"], "function_name": "sch_trg_refuse", "for_each": "statement"}' echo curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers" "${key[@]}" echo aura db raw "delete from sch_trg_audit where true" || echo "exit code: $?" ``` ```text expect="http" {"data":null,"meta":null} {"data":null,"meta":null} {"data":[{"name":"sch_trg_audit_lock","table_name":"sch_trg_audit","timing":"BEFORE","events":["DELETE","UPDATE"],"function_name":"EXECUTE FUNCTION sch_trg_refuse()"}],"meta":null} Error: [400] BAD_REQUEST: Invalid request: sch_trg_audit is append-only exit code: 1 ``` Even the `service_role` key is refused now: a trigger applies to every role. A statement-level trigger fires once per statement, with `NEW` and `OLD` set to `NULL`. ```typescript verify="sdk" needs="http" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const listed = await admin.db.listTriggers('sch_trg_audit') console.log(listed.data?.map((t) => `${t.name} ${t.timing}`)) console.log('dropped:', (await admin.db.dropTrigger('sch_trg_audit', 'sch_trg_audit_lock')).error) const truncate = await admin.db.createTrigger('sch_trg_audit', { name: 'sch_trg_audit_no_truncate', timing: 'before', events: ['truncate'], function_name: 'sch_trg_refuse', for_each: 'statement' }) console.log('truncate lock:', truncate.error) console.log('dropped:', (await admin.db.dropTrigger('sch_trg_audit', 'sch_trg_audit_no_truncate')).error) ``` ```text expect="sdk" [ 'sch_trg_audit_lock BEFORE' ] dropped: null truncate lock: null dropped: null ``` Without `--json`, the CLI prints `?` in place of the events of each trigger (`sch_trg_notes_touch — BEFORE ?`): use `--json` to read them. `aura db trigger drop
` removes a trigger; dropping one that does not exist succeeds. ## Result ```bash verify="result" needs="audit-run" aura db raw "select body, updated_at = created_at as untouched from sch_trg_notes" ``` ```text expect="result" body │ untouched ──────┼────────── final │ false ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `function project_.nope() does not exist` | `--function` names a function that is not in the project, or that takes arguments. | Create it first with `--returns trigger` and no arguments. | | `trigger "…" for relation "…" already exists` | A trigger of that name is already on the table. | Drop it, or pick another name. | | `cannot drop function …() because other objects depend on it` | `aura db function drop` on a function a trigger uses. | Drop the trigger first. | | `TRUNCATE exige for_each = 'statement' (aucun trigger TRUNCATE au niveau ROW en Postgres)` | `--events truncate` with the default `--for-each row` (the message is in French). | Add `--for-each statement`. | | `Duplicate event: 'UPDATE' appears several times in events (…)` | The same event twice in `--events`. | List each event once. | | `new row violates row-level security policy for table "…"` from a trigger | A `security invoker` trigger function writes to a table the caller cannot write. | Make that function `security definer`, as for the audit log, or add a policy. | | `record "new" has no field "updated_at"` | The function sets a column the table does not have. | Attach it only to tables with that column. | ## Clean up Drop the triggers before their functions (one of them through `DELETE /v1/db/{project_id}/{table}/triggers/{name}`, which succeeds even if the trigger is already gone), then the tables: ```bash verify="clean-up" needs="updated-at" aura db trigger drop sch_trg_notes sch_trg_notes_audit --force aura db trigger drop sch_trg_notes sch_trg_notes_touch --force curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers/sch_trg_audit_lock" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"; echo aura db function drop sch_trg_audit_row --force aura db function drop sch_trg_touch --force aura db function drop sch_trg_refuse --force aura db table drop sch_trg_notes --force aura db table drop sch_trg_audit --force ``` ```text expect="clean-up" ✔ Trigger 'sch_trg_notes_audit' dropped from 'sch_trg_notes'. ✔ Trigger 'sch_trg_notes_touch' dropped from 'sch_trg_notes'. {"data":null,"meta":null} ✔ Function 'sch_trg_audit_row' dropped (or already absent). ✔ Function 'sch_trg_touch' dropped (or already absent). ✔ Function 'sch_trg_refuse' dropped (or already absent). ✔ Table 'sch_trg_notes' dropped. ✔ Table 'sch_trg_audit' dropped. ``` ## See also - [Database functions](https://aurabase.dev/en/docs/database/functions): Write the function a trigger runs, and choose invoker or definer. - [Create and change tables](https://aurabase.dev/en/docs/database/tables): The updated_at column that new tables receive. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that triggers and their functions meet. - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Rules that need no trigger: check, unique and foreign keys. --- ### Read and export your schema Source: https://aurabase.dev/en/docs/database/inspect-schema.md # Read and export your schema > Find out what your project's schema contains without querying the system catalogs, follow its relationships, and export it as a replayable SQL file, knowing what the export leaves out. `aura db raw` refuses the PostgreSQL catalogs (`information_schema`, `pg_catalog`, `pg_tables`…), since on a shared cluster they would describe other projects. Aurabase reads them for you, filtered to your project, through the CLI, the schema API, the SDK and Studio. This page lists what each one returns and how to export the schema as SQL. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). This page only reads; the export example writes a local file that the last step removes. ## Where to read the schema | You want | CLI | API (`service_role` key) | SDK | Studio | | --- | --- | --- | --- | --- | | Tables, columns, keys, indexes, constraints | `aura db table list [--json]` | `GET /v1/db/{project_id}/schema/tables`, `…/schema/tables/{table}` | `db.schema()` | Table editor, **ERD Schema** | | Views, functions, enums too | | `GET /v1/db/{project_id}/schema` | `db.schema()` | **ERD Schema** | | Policies | `aura db policy list [--json]` | `GET /v1/db/{project_id}/policies` | | **RLS policies** tab | | Functions with security and grants | `aura db function list [--json]` | `GET /v1/db/{project_id}/functions` | `db.listFunctions()` | **Functions** tab | | Triggers of a table | `aura db trigger list
--json` | `GET /v1/db/{project_id}/{table}/triggers` | `db.listTriggers()` | **Triggers** tab | | Extensions | `aura db extensions list` | `GET /v1/db/{project_id}/schema/extensions` | | **Extensions** | | Index usage, table sizes, locks | `aura db inspect indexes\|tables\|locks` | | | | | The schema as SQL | `aura db pull` | `GET /v1/db/{project_id}/schema/dump` | | **ERD Schema** › **Export schema** | Every route needs the `service_role` key: the schema is administration data, refused to the anon key and to user tokens. ## Tables, columns and relationships `aura db table list --json` returns each table with its columns (type, nullability, default, identity, foreign key), primary key, indexes, unique and check constraints, and its row level security and Realtime flags. The foreign keys are on the columns, under `references`. List the relationships of the example schema: ```bash verify="relations" aura db table list --json | node -e 'for (const t of JSON.parse(require("fs").readFileSync(0, "utf8"))) for (const c of t.columns) if (c.references) console.log(`${t.name}.${c.name} -> ${c.references.table}.${c.references.column}`, c.references.on_delete ?? "NO ACTION")' ``` ```text expect="relations" org_members.org_id -> orgs.id CASCADE ``` `todos.user_id` and `posts.user_id` hold user ids but declare no foreign key: the users live in the Auth schema of the project, which your tables do not reference. The keys and identity columns of one table: ```bash verify="one-table" aura db table list --json | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).find((x) => x.name === "org_members") console.log("primary key:", t.primary_key_columns.join(", ")) for (const c of t.columns) console.log(c.name, JSON.stringify(c.col_type), c.nullable ? "null" : "not null", c.default_val ?? "")' ``` ```text expect="one-table" primary key: org_id, user_id org_id "bigint" not null user_id "uuid" not null role "text" not null 'member'::text created_at "timestamptz" not null now() ``` A composite primary key leaves `primary_key` empty (`null`) and fills `primary_key_columns`; a single-column key fills both. ## The whole schema in one call `GET /v1/db/{project_id}/schema` returns `tables`, `views` (views and materialized views), `functions` (those the REST API can call, with their arguments) and `enums` (each with its labels in order). It is what Studio and the type generators read: ```bash verify="api" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const s = JSON.parse(require("fs").readFileSync(0, "utf8")).data console.log("engine:", s.engine) console.log("tables:", s.tables.map((t) => t.name).join(", ")) console.log("views:", s.views.map((v) => v.name).join(", ")) console.log("functions:", s.functions.map((f) => `${f.name}(${f.args.map((a) => a.name + " " + a.data_type).join(", ")}) -> ${f.returns}`).join(", ")) console.log("enums:", s.enums.length)' ``` ```text expect="api" engine: postgres tables: org_members, orgs, posts, profiles, todos views: open_todos functions: todo_count(p_user uuid) -> bigint enums: 0 ``` ## Read it from the SDK `db.schema()` calls the same route. Use it from a server or a script, with the `service_role` key: ```typescript verify="sdk" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.db.schema() if (error) throw error const todos = data.tables.find((t) => t.name === 'todos')! console.log(todos.columns.map((c) => c.name)) console.log(data.views.map((v) => v.name), data.functions.map((f) => f.name)) const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const refused = await aura.db.schema() console.log(refused.error?.status, refused.error?.code) ``` ```text expect="sdk" [ 'id', 'user_id', 'title', 'done', 'created_at' ] [ 'open_todos' ] [ 'todo_count' ] 403 FORBIDDEN ``` ## Policies, functions, triggers, extensions ```bash verify="other" aura db policy list aura db trigger list todos --json ``` ```text expect="other" » RLS Policies Table Policy Cmd USING Expression ------------------------------------------------------------------------------------- posts posts_owner ALL (auth.uid() = user_id) todos todos_owner ALL (auth.uid() = user_id) ℹ 2 policy(ies). [] ``` `aura db function list` adds each function's security mode and the roles that hold `EXECUTE` ([Database functions](https://aurabase.dev/en/docs/database/functions)); `aura db extensions list` gives the installed extensions and their versions ([Extensions](https://aurabase.dev/en/docs/database/extensions-model)). ## Export the schema as SQL `aura db pull` writes the schema of the linked project to `aurabase/schema.sql`. It prints `✔ Schema exported to aurabase/schema.sql ( bytes)`. It calls `GET /v1/db/{project_id}/schema/dump`, which returns plain SQL; the **Export schema** button of the **ERD Schema** page in Studio downloads the same file. ```bash verify="pull" aura db pull > /dev/null head -n 9 aurabase/schema.sql ``` ```text expect="pull" -- Aurabase DDL dump — project: 11111111-2222-4333-8444-555555555555 -- Table: org_members CREATE TABLE IF NOT EXISTS "org_members" ( "org_id" bigint NOT NULL, "user_id" uuid NOT NULL, "role" text NOT NULL DEFAULT 'member'::text, "created_at" timestamp with time zone NOT NULL DEFAULT now() ); ``` The file is portable: names are not qualified by the project's internal schema, and the objects Aurabase adds itself (the Realtime trigger, the GraphQL wrapper) are left out. Statements use `if not exists` and `drop policy if exists`, so the file can be replayed on another project with `aura db raw -f`. ## What the export contains | Included | Not included | | --- | --- | | Enum types | Views and materialized views | | Tables, with types, defaults and identity columns | Partitioned tables and their partitions | | Primary keys, unique, check and foreign key constraints | `grant` and `revoke` (on tables, views and functions) | | Indexes | Comments | | Row level security (`enable` and `force`) and policies | Data | | Functions and triggers | Extensions (installed in every project) | Check it on the example schema: the view `open_todos` and the `grant` on `todo_count` are missing from the file: ```bash verify="coverage" needs="pull" grep -c 'open_todos' aurabase/schema.sql || true grep -ci '^grant' aurabase/schema.sql || true grep -c 'CREATE POLICY' aurabase/schema.sql ``` ```text expect="coverage" 0 0 2 ``` The route itself returns the same text, for a script or a backup job: ```bash verify="dump" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/dump" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -c '^CREATE TABLE' ``` ```text expect="dump" 5 ``` Keep views, materialized views, partitioned tables and grants in your own migration files, next to the export. ## Export data The schema export contains no rows. To export data: - a table or a query as JSON, from the SDK or `aura db raw --json "select …"` (each request is limited by the statement timeout of the endpoint); - the whole project, schema and data, with `pg_dump` on the direct connection: [Connect to your database](https://aurabase.dev/en/docs/database/connect); - managed backups of the project, with `aura db backup` and the **Backups** page of Studio. ## Result The schema of the example project, read four ways, gives the same five tables: ```bash verify="result" aura db table list --json | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8")).map((t) => t.name).join(" "))' ``` ```text expect="result" org_members orgs posts profiles todos ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | ``Referencing the system schema 'information_schema' is not allowed in raw queries — it could enumerate other tenants`` | A catalog query through `aura db raw`. | Use the commands and routes of this page. | | ``Referencing the system view 'pg_type' is not allowed in raw queries`` | A function or view whose name contains a catalog name, such as `pg_typeof()`. | Avoid the function in `aura db raw`. | | `[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role role` | A schema route called with the anon key or a user token. | Use the `service_role` key. | | `[404] NOT_FOUND: Not found: Table '…' not found` | `GET /schema/tables/{table}` on an unknown table. | Check the name with `aura db table list`. | | A table missing from `aura db table list` | It is a partitioned table: only its partitions are listed. | Query it by name; see [Partitions](https://aurabase.dev/en/docs/database/partitions). | ## Clean up Remove the exported file: ```bash verify="clean-up" needs="pull" rm -r aurabase ``` ## See also - [Create and change tables](https://aurabase.dev/en/docs/database/tables): The schema API that also creates and changes tables. - [Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types): Types for the SDK, built from the same schema. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): pg_dump and psql on the direct connection. - [Database CLI reference](https://aurabase.dev/en/docs/database/cli): Every aura db command and option. --- ### Multi-tenant schema design Source: https://aurabase.dev/en/docs/database/multi-tenancy.md # Multi-tenant schema design > Pick how your customers' data is separated: one project per customer, or shared tables filtered by row level security, from a tenant claim in the user's token or from a membership table, and test that no tenant reads another's rows. A multi-tenant application serves several customers (tenants) and must never show one customer's rows to another. On Aurabase, the separation is either structural (a project per customer) or done by row level security on shared tables. A schema per customer inside one project is not available: a project has one schema, and `create schema` is refused. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the tables `sch_mt_notes` and `sch_mt_projects` and the function `sch_mt_is_member`, sign up test users, then remove what they created. The sign-ups work because email confirmation is turned off on the test project; a project requires it by default. ## Choose a pattern | Pattern | Separation | Fits | Limits | | --- | --- | --- | --- | | Tenant claim: a `tenant_id` column and the claim `app_metadata.tenant` of the user's token, read by `auth.tenant()` | Row level security | One user belongs to one tenant; many small tenants | A user changing tenant needs a new token; one tenant per user | | Membership table: a table of `(org, user, role)` and a function that checks it | Row level security | Users in several organizations, roles per organization | One more lookup per policy check; index the membership table | | One project per customer | Separate database schema, keys, quotas and backups per customer | Few large customers, data residency, contractual isolation | Each project is created, migrated and paid for separately; no query across customers | | A schema per customer in one project | | | Not available: `create schema` is refused by `aura db raw` and reserved to the platform | The first two can be combined: the claim for the default tenant, the membership table for users invited elsewhere. ## Shared tables with a tenant claim `auth.tenant()` returns the `tenant` key of the user's `app_metadata` claim as a `uuid`, or `null` when it is absent or not a uuid. Only the `service_role` key can set `app_metadata` (users can edit their `user_metadata`, never `app_metadata`), so a user cannot choose its tenant. Give the table a `tenant_id` filled by default from the claim, and a policy that compares both: ```sql verify="claim-table" create table sch_mt_notes ( id bigint generated always as identity primary key, tenant_id uuid not null default auth.tenant(), body text not null ); create index sch_mt_notes_tenant on sch_mt_notes (tenant_id); create policy sch_mt_notes_tenant on sch_mt_notes for all to aura_authenticated using (tenant_id = auth.tenant()) with check (tenant_id = auth.tenant()); insert into sch_mt_notes (tenant_id, body) values ('22222222-2222-4222-8222-222222222222', 'Note of another tenant'); ``` ```text expect="claim-table" ℹ No results (0 rows). ``` Set the claim from a server with the admin API, then sign the user in again: the claim is read from the token, and a token issued before the change does not carry it. ```typescript verify="claim-flow" needs="claim-table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `tenant-${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 first = await aura.auth.signInWithPassword({ email, password }) if (first.error) throw first.error const before = await aura.from('sch_mt_notes').insert({ body: 'No tenant yet' }) console.log('before the claim:', before.error?.status, before.error?.code) const updated = await admin.authAdmin.updateUser(first.data!.user.id, { app_metadata: { tenant: '11111111-1111-4111-8111-111111111111' }, }) console.log('claim set:', updated.error) const again = await aura.auth.signInWithPassword({ email, password }) if (again.error) throw again.error const inserted = await aura.from('sch_mt_notes').insert({ body: 'Note of my tenant' }).select('tenant_id, body') console.log('insert:', inserted.data, inserted.error) const visible = await aura.from('sch_mt_notes').select('body') console.log('visible:', visible.data, visible.error) const forged = await aura.from('sch_mt_notes').insert({ tenant_id: '22222222-2222-4222-8222-222222222222', body: 'Forged' }) console.log('forged:', forged.error?.status, forged.error?.code) ``` ```text expect="claim-flow" before the claim: 403 INSUFFICIENT_PRIVILEGE claim set: null insert: [ { tenant_id: '11111111-1111-4111-8111-111111111111', body: 'Note of my tenant' } ] null visible: [ { body: 'Note of my tenant' } ] null forged: 403 INSUFFICIENT_PRIVILEGE ``` Without the claim, `auth.tenant()` is `null` and the policy refuses the write. With it, the row takes the tenant of the token, the other tenant's note stays invisible, and a row sent with another `tenant_id` is refused by `with check`. In your own sign-up flow, set `app_metadata.tenant` from a server right after creating the user (invitation, admin action), or from the custom access token hook of Auth. ## Shared tables with a membership table When a user can belong to several organizations, keep the memberships in a table, like `org_members (org_id, user_id, role)` of the example schema, and check membership in the policy. Put the check in a `security definer` function: the policy then works even though users cannot read `org_members` themselves, and the membership table is not queried through its own policies at each row. ```bash verify="membership-setup" aura db raw "create table sch_mt_projects ( id bigint generated always as identity primary key, org_id bigint not null references orgs (id) on delete cascade, name text not null)" aura db raw "create index sch_mt_projects_org on sch_mt_projects (org_id)" aura db function create sch_mt_is_member --language sql --returns boolean \ --args "p_org:bigint" \ --body 'select exists (select 1 from org_members where org_id = p_org and user_id = auth.uid())' \ --security definer --grant-execute-to authenticated aura db raw "create policy sch_mt_projects_members on sch_mt_projects for select to aura_authenticated using (sch_mt_is_member(org_id))" aura db raw "insert into orgs (slug, name) values ('sch-mt-globex', 'Globex')" aura db raw "insert into sch_mt_projects (org_id, name) select id, slug || ' roadmap' from orgs where slug in ('acme', 'sch-mt-globex')" ``` ```text expect="membership-setup" ℹ No results (0 rows). ℹ No results (0 rows). ✔ Function 'sch_mt_is_member' created (sql → boolean). • EXECUTE granted to: authenticated ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's. ℹ No results (0 rows). ℹ No results (0 rows). ℹ No results (0 rows). ``` The function only answers "is the caller a member of this org": it reveals nothing else, filters on `auth.uid()`, and is granted to signed-in users only. A new user sees no project until a server adds it to an organization: ```typescript verify="membership-flow" needs="membership-setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `member-${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 none = await aura.from('sch_mt_projects').select('name') console.log('before:', none.data, none.error) const acme = await admin.db.from('orgs').select('id').eq('slug', 'acme').single() const joined = await admin.db.from('org_members').insert({ org_id: (acme.data as { id: number }).id, user_id: session!.user.id, role: 'member' }) console.log('joined:', joined.error) const mine = await aura.from('sch_mt_projects').select('name') console.log('after:', mine.data, mine.error) ``` ```text expect="membership-flow" before: [] null joined: null after: [ { name: 'acme roadmap' } ] null ``` Roles per organization follow the same idea: a function such as `has_org_role(p_org, 'admin')` reads `org_members.role`, and the write policies call it. For roles that hold across the whole project, `auth.has_role('')` reads the `roles` array of `app_metadata`. ## One project per customer Each project has its own schema in its own database, its own API keys, its own users and its own quotas: a key of one project cannot reach another ([Project isolation](https://aurabase.dev/en/docs/database/project-isolation)). Create a project per customer with `aura projects create`, apply the same migrations to each, and route each customer to its project URL and keys. You give up queries across customers and take on one migration run per project; in exchange, a policy mistake cannot leak data between customers, and each customer can be backed up, restored or deleted alone. ## Checklist for shared tables | Check | Why | | --- | --- | | Every tenant table has a `tenant_id` (or `org_id`) column, `not null`, indexed | Policies filter on it at each query; without an index, each read scans the table. | | Every tenant table has row level security and policies for each command it serves | Tables created by Aurabase have row level security on; a table without a policy is closed, a policy with `using (true)` is open to every tenant. | | `with check` repeats the tenant condition on insert and update policies | Otherwise a user writes rows into another tenant. | | Foreign keys between tenant tables stay inside the tenant | A row of tenant A must not point to a row of tenant B; check it in the policy or with a composite key `(tenant_id, id)`. | | Views are `security invoker`, materialized views are revoked from `aura_anon` and `aura_authenticated` | A materialized view or a `security_invoker = false` view ignores row level security ([Views and materialized views](https://aurabase.dev/en/docs/database/views)). | | `security definer` functions filter on `auth.uid()` or `auth.tenant()` themselves | They bypass row level security. | | Tests sign in as users of two tenants and check that each sees only its rows | The only proof that the policies do what you think. `aura db raw --as authenticated --user ` helps for membership checks; the tenant claim needs a real token, as in the example above. | ## Result The service role sees the rows of every tenant; each user saw only its own: ```bash verify="result" needs="claim-flow,membership-flow" aura db raw "select tenant_id, body from sch_mt_notes order by id" aura db raw "select name from sch_mt_projects order by name" ``` ```text expect="result" body │ tenant_id ───────────────────────┼───────────────────────────────────── Note of another tenant │ 22222222-2222-4222-8222-222222222222 Note of my tenant │ 11111111-1111-4111-8111-111111111111 ℹ 2 row(s). name ───────────────────── acme roadmap sch-mt-globex roadmap ℹ 2 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "…"` | The user's token has no tenant claim, or the row's `tenant_id` differs from it. | Set `app_metadata.tenant`, sign in again, and let the default fill `tenant_id`. | | An empty array for a user who should see rows | No membership row, an old token without the claim, or no `select` policy. | Check `org_members`, sign in again, add the policy. | | `403 INSUFFICIENT_PRIVILEGE permission denied for function …` | The membership function is not granted to `authenticated`. | `--grant-execute-to authenticated`. | | `Operation not allowed in a raw query: 'CREATE SCHEMA'. (…)` | A schema per tenant attempted with `aura db raw`. | Use a tenant column or a project per customer. | | `infinite recursion detected in policy for relation "…"` (`400 RECURSIVE_POLICY`) | A policy on the membership table queries the membership table. | Check membership in a `security definer` function, as above. | ## Clean up ```bash verify="clean-up" needs="claim-table,membership-setup" aura db table drop sch_mt_projects --force aura db table drop sch_mt_notes --force aura db function drop sch_mt_is_member --force aura db raw "delete from orgs where slug = 'sch-mt-globex'" aura db raw "delete from org_members where user_id not in ('00000000-0000-4000-8000-0000000000a1', '00000000-0000-4000-8000-0000000000b2')" ``` ```text expect="clean-up" ✔ Table 'sch_mt_projects' dropped. ✔ Table 'sch_mt_notes' dropped. ✔ Function 'sch_mt_is_member' dropped (or already absent). ℹ No results (0 rows). ℹ No results (0 rows). ``` `org_members.user_id` has no foreign key to the users of Auth, so deleting a user leaves its memberships: the last command removes the one added for the test user. Delete the test users themselves with `aura auth users delete `. ## See also - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies, auth.uid(), auth.tenant() and auth.has_role(). - [Project isolation](https://aurabase.dev/en/docs/database/project-isolation): What separates two projects, for the project-per-customer pattern. - [Database functions](https://aurabase.dev/en/docs/database/functions): Security definer functions for membership checks. - [Views and materialized views](https://aurabase.dev/en/docs/database/views): Views that respect the tenant policies. --- ### Query your database with the JavaScript SDK Source: https://aurabase.dev/en/docs/database/query-with-sdk.md # Query your database with the JavaScript SDK > The everyday flows of `aura.db`, the rules that refuse unsafe calls, and how to protect a table with row-level security. `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](#errors)). 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](#rls)). Each section links to the page that covers its topic in depth. ## Read rows ```typescript filename="read.ts" verify="read" 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) ``` ```text expect="read" [ { title: 'Add a row level security policy', done: false }, { title: 'Create a table', done: false }, { title: 'Invite a teammate', done: false } ] null ``` Filters chain: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `in`, `is`, and the others listed in [Filter operators](https://aurabase.dev/en/docs/database/filter-operators). Related tables nest in `select()` through foreign keys: [Join tables and nest rows](https://aurabase.dev/en/docs/database/joins). More on reads: [Read rows](https://aurabase.dev/en/docs/database/select). ## Insert, update and delete ```typescript filename="write.ts" verify="write" 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) ``` ```text expect="write" insert: [ { title: 'Write the docs', done: false } ] null update: [ { title: 'Write the docs', done: true } ] null delete: [ { title: 'Write the docs' } ] null ``` Name 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_BODY` with `All object keys must match`. Fill the missing keys with `null`. - **`update()` and `delete()` without a filter are refused by the client** with the error code `UNFILTERED_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 answers `409 DUPLICATE_KEY` instead of updating the row (it inserts new keys normally). Use `insert … on conflict … do update` in SQL or in a function called with `rpc()`: [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert#on-conflict). More: [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert), [Update and delete rows](https://aurabase.dev/en/docs/database/update-and-delete). ## One row, many rows, counts ```typescript filename="count.ts" verify="count" 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) ``` ```text expect="count" single: { username: 'alice' } null single, no row: 406 PGRST116 maybeSingle: null null page: 2 of 4 count: 4 ``` `count: '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](https://aurabase.dev/en/docs/database/pagination). ## Protect a table > **RLS is enabled by default through Aurabase, add policies to grant access** > > 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: > > ```sql filename="SQL" > 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](https://aurabase.dev/en/docs/database/rls). 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()`: ```typescript filename="server/setup.ts" 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'], }) ``` ```typescript filename="client.ts" const { data } = await aura.rpc('add', { a: 1, b: 2 }) // → 3 ``` - **`grant_execute_to` is required to call it.** Without it, only the `service_role` key can execute the function. Another role that is not listed gets `403 permission denied for function`. Both `authenticated` and `aura_authenticated` are accepted. This also holds for functions you create with `db.sql()` or a migration on projects created after this change (the default `EXECUTE` privilege of `PUBLIC` is revoked): add `grant 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()` returns `404 Could not find the function`. - **Functions via SQL (`db.sql()`):** `CREATE FUNCTION` / `CREATE OR REPLACE FUNCTION` is allowed in `SECURITY INVOKER` mode (default); `SECURITY DEFINER` is rejected on `/raw` and must be created through `createFunction` (`POST /v1/db/{project_id}/functions`) or CLI/migrations with explicit `grant_execute_to`. Arguments, results, filters on returned rows and errors: [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc). ## Run SQL from a server ```typescript filename="server/migrate.ts" 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](https://aurabase.dev/en/docs/database/transactions). ## 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: ```typescript filename="errors.ts" verify="errors" 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()) ``` ```text expect="errors" 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=2 ``` A 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()` or `range()` you ask for. `meta.has_more` is `true` when more rows match; ask for `count: 'exact'` to also get `meta.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; `offset` gets slower the deeper you go. - **Numbers beyond JavaScript's 2^53.** A `bigint` above 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. A `numeric` is returned as a JSON number when it is exactly representable, and as an exact decimal string otherwise (long values such as `12345678901234567890.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). Use `count: 'exact'` when the number matters. A count is lost on inserts and updates for now (`count: null`): count with a separate read. - **A `vector` column comes back as a string** such as `"[0.1,0.2,0.3]"`: parse it with `JSON.parse` to get a `number[]`. - **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 write `with (security_invoker = false)`: such a view ignores those policies, and the anon key could read and even write the table through it ([Views](https://aurabase.dev/en/docs/database/views)). - **`db.sql()` retries a `429` after the `Retry-After` delay** (a refused request never ran). `/raw` is limited per project; for bulk loads use the typed `insert()` with an array. --- ### Read rows Source: https://aurabase.dev/en/docs/database/select.md # Read rows > Read the rows your application needs, in the order it needs them, and understand why a read returns fewer rows than the table holds. A read is a `select`: `from('todos').select(…)` in the SDK, `GET /v1/db/todos` over REST, `select … from todos` in SQL. The SDK builds the REST request, and the REST API runs one SQL query under the role of the key or user that calls it, so the same row level security policies apply to every door. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. Most examples read the demo rows with the `service_role` key, which bypasses row level security: run that key on a server only. [Which rows each key reads](#who) shows the same reads with the anon key and a signed-in user. ## Read rows ```typescript verify="sdk-read" 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').order('title') console.log(data, error) ``` ```text expect="sdk-read" [ { title: 'Add a row level security policy', done: false }, { title: 'Create a table', done: false }, { title: 'Invite a teammate', done: false }, { title: 'Read the quickstart', done: true } ] null ``` `data` is always an array for a read, `[]` when nothing matches; the call never throws unless you add `.throwOnError()`. The same read over REST: the query string carries `select`, the filters and `order`. `curl --get --data-urlencode` encodes the values for you: ```bash verify="rest-read" curl -s --get "$AURABASE_URL/v1/db/todos" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ --data-urlencode 'select=title,done' \ --data-urlencode 'order=title' echo ``` ```text expect="rest-read" {"data":[{"title":"Add a row level security policy","done":false}, {"title":"Create a table","done":false}, {"title":"Invite a teammate","done":false}, {"title":"Read the quickstart","done":true}],"meta":{}} ``` And in SQL, with `aura db raw` (or `db.sql()` from a server): ```sql verify="sql-read" select title, done from todos order by title ``` ```text expect="sql-read" done │ title ──────┼──────────────────────────────── false │ Add a row level security policy false │ Create a table false │ Invite a teammate true │ Read the quickstart ℹ 4 row(s). ``` A view reads like a table: `from('open_todos').select('title')`. ## Choose columns `select()` takes a comma-separated list. `*` (or no argument) returns every column. Rename a column with `alias:column` and convert it with `column::type`: ```typescript verify="columns" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data } = await admin.from('posts').select('heading:title, published, id::text').order('title') console.log(data) ``` ```text expect="columns" [ { heading: 'Draft notes', published: false, id: '2' }, { heading: 'Hello Aurabase', published: true, id: '1' } ] ``` Rows of related tables go in the same list (`select('slug, org_members(role)')`): [Join tables and nest rows](https://aurabase.dev/en/docs/database/joins). Keys inside a `jsonb` column use `->` and `->>`: [Query JSON columns](https://aurabase.dev/en/docs/database/json). Ask only for the columns you use: it keeps responses small and lets [generated types](https://aurabase.dev/en/docs/database/generate-types) infer the shape of `data`. ## Filter rows Each filter method adds a condition; several filters must all be true. `eq`, `in` and `ilike` cover most reads: ```typescript verify="filter" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const open = await admin.from('todos').select('title').eq('done', false).ilike('title', '%a%').order('title') console.log(open.data) const two = await admin.from('profiles').select('username').in('username', ['alice', 'carol']).order('username') console.log(two.data) ``` ```text expect="filter" [ { title: 'Add a row level security policy' }, { title: 'Create a table' }, { title: 'Invite a teammate' } ] [ { username: 'alice' } ] ``` Over REST, a filter is `column=operator.value`: `?done=eq.false&title=ilike.*a*` (`*` stands for `%`, which would need escaping in a URL). Every operator, with `or`, `not` and null checks: [Filter operators](https://aurabase.dev/en/docs/database/filter-operators). ## Sort and limit Without `order()`, rows come back in no guaranteed order. Call `order()` once per column, in the order of priority: ```typescript verify="order" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data } = await admin .from('todos') .select('title, done') .order('done', { ascending: false }) .order('title') .limit(2) console.log(data) ``` ```text expect="order" [ { title: 'Read the quickstart', done: true }, { title: 'Add a row level security policy', done: false } ] ``` `order(column, { ascending: false })` (or `order(column, 'desc')`) sorts in descending order; `nullsFirst: true` or `false` places `null` values. In REST, `?order=done.desc,title.asc&limit=2`. `limit(n)` caps the number of rows; **a read never returns more than 1,000 rows**, whatever the limit: page through larger results as shown in [Paginate and count rows](https://aurabase.dev/en/docs/database/pagination). ## Read exactly one row `single()` returns the row as an object instead of an array, and fails when zero or several rows match. `maybeSingle()` accepts zero rows and returns `null`: ```typescript verify="one" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const one = await admin.from('profiles').select('username, display_name').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, none.error?.message) const many = await admin.from('profiles').select('username').single() console.log('single, two rows:', many.error?.status, many.error?.code, many.error?.message) const maybe = await admin.from('profiles').select('username').eq('username', 'nobody').maybeSingle() console.log('maybeSingle, no row:', maybe.data, maybe.error) ``` ```text expect="one" single: { username: 'alice', display_name: 'Alice Martin' } null single, no row: 406 PGRST116 JSON object requested, 0 rows returned single, two rows: 406 PGRST116 JSON object requested, multiple rows returned maybeSingle, no row: null null ``` Use `single()` when the row must exist (a lookup by key), `maybeSingle()` when it may not (find a profile by username). Over REST, `single()` is the header `Accept: application/vnd.pgrst.object+json`. ## Read one row by id `GET /v1/db/{table}/{id}` reads the row whose `id` column equals the value, and returns it as an object: ```bash verify="by-id" id=$(aura db raw --json "select id from posts where title = 'Hello Aurabase'" | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8"))[0].id)') curl -s -X GET "$AURABASE_URL/v1/db/posts/$id?select=title,published" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" echo curl -s -X GET "$AURABASE_URL/v1/db/posts/999999" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)' ``` ```text expect="by-id" {"data":{"title":"Hello Aurabase","published":true},"meta":{}} RECORD_NOT_FOUND Cannot coerce the result to a single JSON object ``` The route only works on a table whose key column is named `id`. In the SDK, write `.eq('id', id).single()`. ## Which rows each key reads Row level security filters every read before your filters apply. The same query returns all rows with the `service_role` key, none with the anon key alone, and only the user's rows once a user is signed in: ```typescript verify="who" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const anon = await aura.from('todos').select('title') console.log('anon:', anon.data, anon.meta?.hint?.split('. ')[0]) const email = `select-${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 await aura.from('todos').insert({ user_id: session!.user.id, title: 'Read my rows' }) const mine = await aura.from('todos').select('title') console.log('signed in:', mine.data) ``` ```text expect="who" anon: [] 0 rows returned signed in: [ { title: 'Read my rows' } ] ``` An empty result is not an error: when a read without filters returns no row to the anon key or a user, `meta.hint` says that the table may be empty or that no policy lets the role read it, and how to check with `aura db raw --as anon`. Policies are written in [Row-level security](https://aurabase.dev/en/docs/database/rls). The sign-up works because email confirmation is turned off on the test project; a project requires it by default. ## Result ```sql verify="result" needs="who" select title, done from todos order by title ``` ```text expect="result" done │ title ──────┼──────────────────────────────── false │ Add a row level security policy false │ Create a table false │ Invite a teammate false │ Read my rows true │ Read the quickstart ℹ 5 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400 COLUMN_NOT_FOUND column todos.titel does not exist` | A column name that does not exist; the `hint` often suggests the right one. | Fix the name. | | `404 TABLE_NOT_FOUND …` | The table does not exist, or the API has not reloaded its schema after a change. | Check the name; retry after a second. | | `406 PGRST116 JSON object requested, 0 rows returned` | `single()` and no row matches (or a policy hides it). | Use `maybeSingle()`, or check the filter. | | `406 PGRST116 JSON object requested, multiple rows returned` | `single()` or `maybeSingle()` and several rows match. | Filter on a unique column. | | `404 RECORD_NOT_FOUND Cannot coerce the result to a single JSON object` | `GET /v1/db/{table}/{id}` on an id that does not exist or is hidden. | Check the id and the policies. | | `data: []` and a `meta.hint` | No policy lets this role read the table, or the table is empty. | Sign the user in, or add a `select` policy. | | `400 POSTGREST_ERROR "failed to parse select parameter …"` | A syntax error in the column list. | Check commas, parentheses and `::` casts. | ## Clean up Delete the todo inserted by the `who` example (the test user stays in the project; delete it with `aura auth users delete `): ```bash verify="clean-up" needs="who" aura db raw "delete from todos where title = 'Read my rows'" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Filter operators](https://aurabase.dev/en/docs/database/filter-operators): Every filter of the SDK and of the REST API. - [Join tables and nest rows](https://aurabase.dev/en/docs/database/joins): Read related rows in one request. - [Paginate and count rows](https://aurabase.dev/en/docs/database/pagination): Pages, totals and the 1,000-row cap. - [Query with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): A tour of the SDK calls on one page. --- ### Join tables and nest rows Source: https://aurabase.dev/en/docs/database/joins.md # Join tables and nest rows > Fetch a row with its related rows nested inside it, in one request from the SDK or the REST API, and know when to write the join in SQL instead. The SDK and the REST API do not take a `join` keyword: you name a related table inside `select()`, and its rows come back nested in each row. The relation comes from a foreign key, which the API reads from your schema. Anything a foreign key cannot express (a join on another condition, a `group by`) goes in a view or a function. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` in the environment, for the SDK and `curl` examples. In the example schema, `org_members.org_id` references `orgs (id)`: an org has many members, and each member row points to one org. The examples read them with the `service_role` key, since `orgs` and `org_members` have no policy (only that key reads them). The many-to-many section creates `qd_joins_students`, `qd_joins_courses` and `qd_joins_enrollments`, then removes them. ## How nesting works | You write | Relation | Nested value | | --- | --- | --- | | `orgs.select('slug, org_members(role)')` | one-to-many: `org_members` points to `orgs` | an array of rows (`[]` when there is none) | | `org_members.select('role, orgs(slug)')` | many-to-one: the row points to `orgs` | one object, or `null` | | `students.select('name, courses(title)')` | many-to-many through a join table with two foreign keys | an array | The name inside the parentheses is the related table (or an alias, see below). The API looks up foreign keys between the two tables; with none, the request fails with `Could not find a relationship`. After a schema change, the new relation is visible once the API has reloaded its schema, which Aurabase triggers after each change through `aura db raw`, migrations and the schema API. ## One to many ```typescript verify="one-to-many" 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('orgs').select('slug, name, org_members(user_id, role)') console.log(JSON.stringify(data, null, 2), error) ``` ```text expect="one-to-many" [ { "slug": "acme", "name": "Acme", "org_members": [ { "role": "owner", "user_id": "00000000-0000-4000-8000-0000000000a1" }, { "role": "member", "user_id": "00000000-0000-4000-8000-0000000000b2" } ] } ] null ``` Over REST, the same `select` goes in the query string: ```bash verify="rest" curl -s --get "$AURABASE_URL/v1/db/orgs" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ --data-urlencode 'select=slug,org_members(role)' echo ``` ```text expect="rest" {"data":[{"slug":"acme","org_members":[{"role": "owner"}, {"role": "member"}]}],"meta":{}} ``` ## Many to one From the side that holds the foreign key, the related row is an object: ```typescript verify="many-to-one" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data } = await admin.from('org_members').select('role, orgs(slug, name)').order('role') console.log(data) ``` ```text expect="many-to-one" [ { role: 'member', orgs: { name: 'Acme', slug: 'acme' } }, { role: 'owner', orgs: { name: 'Acme', slug: 'acme' } } ] ``` When two foreign keys link the same two tables (a `billing_address_id` and a `shipping_address_id`, say), name the one to follow after `!`: `orgs!org_members_org_id_fkey(slug)` uses the constraint `org_members_org_id_fkey`. A foreign key declared without a name is named `
__fkey` by PostgreSQL; the name also appears in the errors it raises. ## Many to many A join table with a foreign key to each side, both part of its primary key, links two tables. The API detects it and lets you nest one side directly in the other: ```sql verify="m2m-create" create table qd_joins_students (id bigint generated always as identity primary key, name text not null); create table qd_joins_courses (id bigint generated always as identity primary key, title text not null); create table qd_joins_enrollments ( student_id bigint references qd_joins_students (id) on delete cascade, course_id bigint references qd_joins_courses (id) on delete cascade, primary key (student_id, course_id) ); insert into qd_joins_students (name) values ('Ada'), ('Grace'); insert into qd_joins_courses (title) values ('Algebra'), ('Compilers'); insert into qd_joins_enrollments select s.id, c.id from qd_joins_students s, qd_joins_courses c where (s.name, c.title) in (('Ada', 'Algebra'), ('Ada', 'Compilers'), ('Grace', 'Compilers')); ``` ```text expect="m2m-create" ℹ No results (0 rows). ``` ```typescript verify="m2m" needs="m2m-create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const students = await admin.from('qd_joins_students').select('name, qd_joins_courses(title)').order('name') console.log(JSON.stringify(students.data)) const courses = await admin.from('qd_joins_courses').select('title, qd_joins_students(name)').order('title') console.log(JSON.stringify(courses.data), courses.error) ``` ```text expect="m2m" [{"name":"Ada","qd_joins_courses":[{"title":"Algebra"},{"title":"Compilers"}]},{"name":"Grace","qd_joins_courses":[{"title":"Compilers"}]}] [{"title":"Algebra","qd_joins_students":[{"name":"Ada"}]},{"title":"Compilers","qd_joins_students":[{"name":"Ada"},{"name":"Grace"}]}] null ``` To read columns of the join table itself (an enrollment date, a role), nest through it: `select('name, qd_joins_enrollments(course_id, qd_joins_courses(title))')`. ## Filter on related rows A filter on a nested column is written `table.column`. It has two meanings: - without `!inner`, it filters the **nested** rows only: every parent row stays, with fewer (or no) nested rows; - with `!inner` on the nested table, it also drops the **parent** rows that have no matching nested row, like an SQL inner join. ```typescript verify="filter" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const nestedOnly = await admin.from('orgs').select('slug, org_members(role)').eq('org_members.role', 'owner') console.log('nested filter:', JSON.stringify(nestedOnly.data)) const noOwner = await admin.from('orgs').select('slug, org_members(role)').eq('org_members.role', 'guest') console.log('nested filter, no match:', JSON.stringify(noOwner.data)) const inner = await admin.from('orgs').select('slug, org_members!inner(role)').eq('org_members.role', 'guest') console.log('inner join, no match:', JSON.stringify(inner.data)) ``` ```text expect="filter" nested filter: [{"slug":"acme","org_members":[{"role":"owner"}]}] nested filter, no match: [{"slug":"acme","org_members":[]}] inner join, no match: [] ``` Use `!inner` to answer "which orgs have an owner" or "which posts have a comment by this user". Over REST: `?select=slug,org_members!inner(role)&org_members.role=eq.owner`. ## Rename, flatten and count ```typescript verify="shape" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const alias = await admin.from('orgs').select('slug, members:org_members(role)') console.log('alias:', JSON.stringify(alias.data)) const flat = await admin.from('org_members').select('role, ...orgs(org_slug:slug)').order('role') console.log('spread:', JSON.stringify(flat.data)) const counted = await admin.from('orgs').select('slug, org_members(count)') console.log('count:', JSON.stringify(counted.data)) ``` ```text expect="shape" alias: [{"slug":"acme","members":[{"role":"owner"},{"role":"member"}]}] spread: [{"role":"member","org_slug":"acme"},{"role":"owner","org_slug":"acme"}] count: [{"slug":"acme","org_members":[{"count":2}]}] ``` - `alias:table(…)` renames the nested key. - `...table(…)` (spread) copies the columns of a many-to-one row into the parent row instead of nesting an object. - `table(count)` returns the number of related rows. It is the only aggregate the API accepts: `sum()`, `avg()` and the others are turned off ([Aggregate rows](https://aurabase.dev/en/docs/database/aggregates)). ## Sort and limit nested rows Over REST, prefix `order` and `limit` with the nested table: `org_members.order=role.desc` sorts the members of each org, `org_members.limit=1` keeps one per org. ```bash verify="order" curl -s --get "$AURABASE_URL/v1/db/orgs" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ --data-urlencode 'select=slug,org_members(role)' \ --data-urlencode 'org_members.order=role.desc' \ --data-urlencode 'org_members.limit=1' echo ``` ```text expect="order" {"data":[{"slug":"acme","org_members":[{"role": "owner"}]}],"meta":{}} ``` The SDK option `order(column, { referencedTable })` is meant for this, but it currently builds a parameter the API rejects (`400 POSTGREST_ERROR "failed to parse order (org_members.role.desc)"`). Until it is fixed, sort nested rows in your code, or use the REST form above. ## The same join in SQL A view or a function holds joins that foreign keys do not express, and returns a flat result you read like a table: ```sql verify="sql" select o.slug, m.role, p.username from orgs o join org_members m on m.org_id = o.id join profiles p on p.id = m.user_id order by m.role desc ``` ```text expect="sql" role │ slug │ username ───────┼──────┼───────── owner │ acme │ alice member │ acme │ bob ℹ 2 row(s). ``` `org_members.user_id` has no foreign key to `profiles` in the example schema, so the API cannot nest `profiles` in `org_members`; the SQL join does not need one. Wrap such a query in a view (`create view … as select …`) and read it with `from('')`, or in a function called with [rpc()](https://aurabase.dev/en/docs/database/rpc). ## Policies on related tables Each nested table is read under the caller's role, with its own policies: a user sees a parent row and, inside it, only the related rows the policies of the related table let it read. A nested table without a `select` policy for that role comes back as `[]` (or `null` for many-to-one), not as an error. With `!inner`, hidden related rows also hide the parent row. ## Result ```typescript verify="result" needs="m2m-create" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data } = await admin .from('qd_joins_courses') .select('title, qd_joins_students!inner(name)') .eq('qd_joins_students.name', 'Grace') console.log(JSON.stringify(data)) ``` ```text expect="result" [{"title":"Compilers","qd_joins_students":[{"name":"Grace"}]}] ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400 POSTGREST_ERROR Could not find a relationship between 'todos' and 'profiles' in the schema cache` | No foreign key between the two tables (`upstream_code` `PGRST200`). | Add a foreign key, or join in a view or function. | | `400 POSTGREST_ERROR "failed to parse order (…)"` | `order(…, { referencedTable })` of the SDK. | Use `
.order=` over REST, or sort in your code. | | `400 POSTGREST_ERROR Use of aggregate functions is not allowed` | An aggregate other than `table(count)` in `select`. | Use a view or a function. | | Nested value `[]` or `null` while rows exist | The caller's policies hide the related rows. | Add a `select` policy on the related table. | ## Clean up ```bash verify="clean-up" needs="m2m-create" aura db raw "drop table qd_joins_enrollments, qd_joins_courses, qd_joins_students" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Declare the foreign keys that nesting follows. - [Read rows](https://aurabase.dev/en/docs/database/select): Columns, filters, order and single rows. - [Views and materialized views](https://aurabase.dev/en/docs/database/views): Save a join as a view you read like a table. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies on each table of a nested read. --- ### Paginate and count rows Source: https://aurabase.dev/en/docs/database/pagination.md # Paginate and count rows > Read a large table page by page without missing rows, get the total for your page numbers, and pick the pagination that stays fast on the last page. A read returns at most 1,000 rows. To go further, ask for one page at a time: by position (`range()`, `offset()`) or after the last row you read (`after()`). The total number of matching rows comes from `count`, exact or estimated. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` in the environment, for the SDK and `curl` examples. The examples create the table `qd_page_events` with 2,500 rows, read it with the `service_role` key, then remove it. ```sql verify="table" create table qd_page_events ( id bigint primary key, label text not null ); insert into qd_page_events select g, 'event ' || g from generate_series(1, 2500) g; ``` ```text expect="table" ℹ No results (0 rows). ``` ## The 1,000-row cap Every read returns 1,000 rows at most: it is the default when you set no limit, and the ceiling when you ask for more. The SDK tells you when rows were left out with `meta.has_more`: ```typescript verify="cap" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const all = await admin.from('qd_page_events').select('id') console.log('no limit:', all.data!.length, all.meta) const more = await admin.from('qd_page_events').select('id').limit(5000) console.log('limit 5000:', more.data!.length, more.meta) ``` ```text expect="cap" no limit: 1000 { has_more: true } limit 5000: 1000 { has_more: true } ``` `has_more` is computed by the SDK from the response; over REST, compare the number of rows to the total given by `count` ([Pages over REST](#rest)). The cap applies to reads of tables and views and to functions that return rows; it does not apply to SQL through `aura db raw`. ## Offset pagination `range(from, to)` reads the rows at positions `from` to `to`, both included, counting from 0. Always sort on a unique column first, or the same row can appear on two pages: ```typescript verify="range" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const pageSize = 10 const page = 3 const { data, count, meta } = await admin .from('qd_page_events') .select('id, label', { count: 'exact' }) .order('id') .range((page - 1) * pageSize, page * pageSize - 1) console.log(data!.map((r) => r.id).join(','), count, meta?.has_more) const same = await admin.from('qd_page_events').select('id').order('id').offset(20).limit(10) console.log(same.data!.map((r) => r.id).join(',')) ``` ```text expect="range" 21,22,23,24,25,26,27,28,29,30 2500 true 21,22,23,24,25,26,27,28,29,30 ``` `range(20, 29)` is `offset(20).limit(10)`. On the last page, `has_more` is `false`. Each page costs more than the previous one: PostgreSQL still reads and skips the `offset` rows before the page. ## Count rows `count` returns the number of rows that match the filters, whatever the range or the cap: | Mode | How it is computed | Use it for | | --- | --- | --- | | `'exact'` | `count(*)` of the matching rows. | Totals you show to users, small and medium tables. | | `'planned'` | The row estimate of PostgreSQL's query planner. | Very large tables where a rough total is enough. | | `'estimated'` | `exact` for small results, `planned` above a threshold (measured: the exact `500` for 500 rows, the planner's `1200` for 1,500 rows). | Same as `planned`, with an exact value on small results. | ```typescript verify="count" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const total = await admin.from('qd_page_events').select('*', { count: 'exact', head: true }) console.log('rows:', total.count, 'data:', total.data) const filtered = await admin.from('qd_page_events').select('id', { count: 'exact', head: true }).like('label', 'event 1%') console.log('matching "event 1%":', filtered.count) const withRows = await admin.from('qd_page_events').select('id').gt('id', 2495).count() console.log('count() method:', withRows.count, withRows.data!.map((r) => r.id).join(',')) const planned = await admin.from('qd_page_events').select('id', { count: 'planned', head: true }) console.log('planned is a number:', typeof planned.count === 'number') ``` ```text expect="count" rows: 2500 data: null matching "event 1%": 1111 count() method: 5 2496,2497,2498,2499,2500 planned is a number: true ``` - `head: true` sends a `HEAD` request: you get `count` and no rows. - `.count()` (or `.count('planned')`) is the same as the `count` option of `select()`. - `planned` and `estimated` come from table statistics, which can be far from the truth on a table that was just loaded (measured: `1200` for 1,500 fresh rows). Use `exact` when the number matters. - A count is lost on inserts and updates for now: `insert(…).select().count('exact')` returns `count: null`. Count with a separate read. ## Pages over REST Over REST, `limit` and `offset` go in the query string and `count=exact` adds the total. The response carries a `Content-Range` header, `-/`, and the status `206 Partial Content` when the page is not the whole result: ```bash verify="rest" needs="table" body=$(mktemp) curl -s -D - -o "$body" \ "$AURABASE_URL/v1/db/qd_page_events?select=id&order=id&limit=3&offset=10&count=exact" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -iE '^(HTTP|content-range)' cat "$body" echo rm -f "$body" ``` ```text expect="rest" HTTP/1.1 206 Partial Content content-range: 10-12/2500 {"data":[{"id":11}, {"id":12}, {"id":13}],"meta":{"total":2500}} ``` The total is also in `meta.total`. Without `count`, the header ends with `/*` (total unknown). `Content-Range` is exposed to browser code by CORS. ## Keyset pagination Keyset pagination asks for the rows after the last one you read: `after(column, lastValue)` sorts on the column and adds `column > lastValue`. Each page costs the same, and rows inserted meanwhile never shift a page: ```typescript verify="keyset" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) let last: number | undefined let pages = 0 let rows = 0 for (;;) { const q = admin.from('qd_page_events').select('id, label').limit(1000) const { data, error } = await (last === undefined ? q.order('id') : q.after('id', last)) if (error) throw error if (!data.length) break pages += 1 rows += data.length last = data[data.length - 1].id } console.log({ pages, rows, last }) console.log(admin.from('qd_page_events').select('id').after('id', 1000).limit(3).buildQueryString()) const cursor = await admin.from('qd_page_events').select('id').cursor('abc') console.log('cursor():', cursor.error?.status, cursor.error?.code) ``` ```text expect="keyset" { pages: 3, rows: 2500, last: 2500 } select=id&id=gt.1000&order=id.asc&limit=3 cursor(): 400 BAD_REQUEST ``` The column must be unique and sorted (a primary key, or `created_at` plus `id` for a feed). `after(column, value, { ascending: false })` walks backwards with `lt`. Over REST, it is `?order=id.asc&id=gt.1000&limit=1000`. `cursor()` of the SDK is for MongoDB projects only; on PostgreSQL it is refused with a message that points to `after()`. ## Pages in SQL From a server, the same pages are `limit` and `offset`, or a `where` on the last value read, with `aura db raw` or `db.sql()`. SQL through this endpoint is not capped at 1,000 rows, so always write the `limit`: ```bash verify="sql" needs="table" aura db raw "select id, label from qd_page_events order by id limit 3 offset 20" aura db raw "select id, label from qd_page_events where id > 1000 order by id limit 3" aura db raw "select count(*) as total from qd_page_events" ``` ```text expect="sql" id │ label ─────┼───────── 21 │ event 21 22 │ event 22 23 │ event 23 ℹ 3 row(s). id │ label ─────┼─────────── 1001 │ event 1001 1002 │ event 1002 1003 │ event 1003 ℹ 3 row(s). total ───── 2500 ℹ 1 row(s). ``` ## Choose a pagination | Need | Use | Why | | --- | --- | --- | | Page numbers in a table view | `range()` with `count: 'exact'` | Jump to any page and show "page 3 of 250". | | Infinite scroll, feeds, exports | `after()` | Constant cost, no duplicate or missing rows when data changes. | | Read a whole table in a script | `after()` in a loop | Every row exactly once, 1,000 at a time. | | A total for a very large table | `count: 'planned'` | No full scan; the value is approximate. | ## Result ```bash verify="result" needs="table" aura db raw "select count(*) as rows, min(id) as first, max(id) as last from qd_page_events" ``` ```text expect="result" first │ last │ rows ──────┼──────┼───── 1 │ 2500 │ 2500 ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `data.length` is 1,000 and `meta.has_more` is `true` | The 1,000-row cap. | Read the next page with `range()` or `after()`. | | `416 POSTGREST_ERROR Requested range not satisfiable` | `range()` or `offset` beyond the last row, with `count`. | Stop when a page is shorter than the page size, or compare to `count`. | | `400 BAD_REQUEST Invalid request: Cursor pagination … is not available on PostgreSQL projects (it is MongoDB-only)` | `cursor()` on a PostgreSQL project. | Use `after()` or `range()`. | | `count` is `null` after an insert or update | The count of a write is lost by the gateway today. | Count with a separate `select(…, { count: 'exact', head: true })`. | | The same row on two pages | Offset pagination without `order()`, or on a column that is not unique. | Sort on a unique column, or add `id` as a second sort key. | ## Clean up ```bash verify="clean-up" needs="table" aura db raw "drop table qd_page_events" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Read rows](https://aurabase.dev/en/docs/database/select): Columns, filters, order and single rows. - [Indexes](https://aurabase.dev/en/docs/database/indexes): Index the columns you sort and page on. - [Aggregate rows](https://aurabase.dev/en/docs/database/aggregates): Counts per group, sums and averages. - [Query with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): A tour of the SDK calls on one page. --- ### Insert and upsert rows Source: https://aurabase.dev/en/docs/database/insert.md # 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 `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` (the URL of your project) and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. 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 ```sql verify="table" 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() ); ``` ```text expect="table" ℹ 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): ```typescript verify="sdk-one" needs="table" 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) ``` ```text expect="sdk-one" [ { sku: 'LAMP-1', name: 'Desk lamp', qty: 4 } ] null ``` Over REST, `POST /v1/db/{table}` with a JSON body. A single inserted row comes back as an object in `data`, with the status `201`: ```bash verify="rest-one" needs="table" 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' ``` ```text expect="rest-one" {"data":{"sku":"DESK-1","name":"Standing desk","qty":1},"meta":{}} HTTP 201 ``` In SQL, `returning` gives back the columns you name: ```bash verify="sql-one" needs="table" aura db raw "insert into qd_insert_items (sku, name, qty) values ('CHAIR-1', 'Office chair', 2) returning sku, qty" ``` ```text expect="sql-one" 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. ```typescript verify="sdk-many" needs="sdk-one" 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) ``` ```text expect="sdk-many" 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 match ``` Every 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: ```typescript verify="bulk" needs="table" 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) ``` ```text expect="bulk" 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](https://aurabase.dev/en/docs/database/connect). ## 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: ```typescript verify="user" needs="table" 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) ``` ```text expect="user" 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_PRIVILEGE ``` `user_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=` 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"` | ```typescript verify="upsert-today" needs="sdk-one" 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) ``` ```text expect="upsert-today" existing sku: 409 DUPLICATE_KEY duplicate key value violates unique constraint "qd_insert_items_sku_key" new sku: [ { sku: 'LAMP-2', qty: 1 } ] null ``` The 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 () do update` inserts the row or updates the existing one, in one statement. `excluded` is the row you tried to insert: ```sql verify="sql-upsert" needs="sdk-one" 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; ``` ```text expect="sql-upsert" 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: ```sql verify="fn" needs="table" 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 *; $$; ``` ```text expect="fn" ℹ No results (0 rows). ``` ```typescript verify="rpc-upsert" needs="fn,sdk-one" 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) ``` ```text expect="rpc-upsert" [ { sku: 'LAMP-1', qty: 12 } ] null [ { sku: 'LAMP-4', qty: 6 } ] null ``` A 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()](https://aurabase.dev/en/docs/database/rpc) and [Database functions](https://aurabase.dev/en/docs/database/functions). ## Result ```bash verify="result" needs="rpc-upsert,sql-upsert" aura db raw "select sku, name, qty from qd_insert_items where sku not like 'BULK-%' order by sku" ``` ```text expect="result" 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 `. ```bash verify="clean-up" needs="table" 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'" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Update and delete rows](https://aurabase.dev/en/docs/database/update-and-delete): Change or remove the rows that match a filter. - [Constraints and foreign keys](https://aurabase.dev/en/docs/database/constraints): Keys, unique columns and the errors they return. - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Arguments, results and errors of a function call. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that decide which rows each user writes. --- ### Update and delete rows Source: https://aurabase.dev/en/docs/database/update-and-delete.md # Update and delete rows > Update and delete exactly the rows you mean, know which doors refuse a call without a filter and which do not, and read why a write touched no row. An update or a delete applies to every row that matches its filter and that the caller's policies let it see. The SDK (`update()`, `delete()`), the REST API (`PATCH` and `DELETE /v1/db/{table}`) and SQL (`update`, `delete`) all work this way; they differ in what they return and in how they treat a call without a filter. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. The examples create the tables `qd_upd_tasks` and `qd_upd_notes` and the view `qd_upd_live_tasks`, then remove them. ## A table to change ```sql verify="table" create table qd_upd_tasks ( id bigint generated always as identity primary key, title text not null, status text not null default 'open', deleted_at timestamptz ); insert into qd_upd_tasks (title) values ('Write specs'), ('Review specs'), ('Ship'), ('Celebrate'); create table qd_upd_notes (id uuid primary key default gen_random_uuid(), title text not null, body text); ``` ```text expect="table" ℹ No results (0 rows). ``` The table has row level security and no policy: the examples use the `service_role` key, on a server, except in [As a signed-in user](#users). ## Update rows that match a filter Chain the filters before or after `update()`; every matching row gets the new values: ```typescript verify="sdk-update" needs="table" 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_upd_tasks').update({ status: 'done' }).ilike('title', '%specs').select('title, status') console.log(data, error) const none = await admin.from('qd_upd_tasks').update({ status: 'done' }).eq('title', 'Nothing like this').select('title') console.log(none.data, none.meta?.rows_affected) ``` ```text expect="sdk-update" [ { title: 'Write specs', status: 'done' }, { title: 'Review specs', status: 'done' } ] null [] 0 ``` An update that matches no row is not an error: `data` is `[]`, and `meta` carries `rows_affected: 0` and a `hint` that names the two usual causes (no row matches the filter, or a policy hides the rows). The same update over REST is a `PATCH` with the filter in the query string: ```bash verify="rest-update" needs="table" curl -s -X PATCH "$AURABASE_URL/v1/db/qd_upd_tasks?title=eq.Ship&select=title,status" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"status": "in progress"}' echo ``` ```text expect="rest-update" {"data":[{"title":"Ship","status":"in progress"}],"meta":{}} ``` And in SQL: ```bash verify="sql-update" needs="table" aura db raw "update qd_upd_tasks set status = 'blocked' where title = 'Celebrate' returning title, status" ``` ```text expect="sql-update" status │ title ────────┼────────── blocked │ Celebrate ℹ 1 row(s). ``` `update()` returns the updated rows even without `.select()`: the gateway currently answers every `PATCH` with `return=representation`. Name the columns you need with `.select('a, b')` to keep the response small. The filters are those of reads: [Filter operators](https://aurabase.dev/en/docs/database/filter-operators). ## Update or delete one row by id `update(id, values)` and `delete(id)` target the row whose `id` column equals the value; the REST routes are `PATCH` and `DELETE /v1/db/{table}/{id}`. They return the row as an object, and a missing id is an error, not an empty result: ```typescript verify="by-id" needs="table" 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_upd_tasks').select('id').eq('title', 'Ship').single() const updated = await admin.from('qd_upd_tasks').update(String(row!.id), { status: 'done' }).select('title, status') console.log(updated.data, updated.error) const missing = await admin.from('qd_upd_tasks').delete('999999') console.log(missing.error?.status, missing.error?.code) ``` ```text expect="by-id" { title: 'Ship', status: 'done' } null 404 RECORD_NOT_FOUND ``` These routes only work on a table whose key column is named `id`. For any other key, filter on it: `update({ … }).eq('sku', 'LAMP-1')`. Over REST, on a table whose `id` is a `uuid`: ```bash verify="rest-by-id" needs="table" id=$(aura db raw --json "insert into qd_upd_notes (title, body) values ('Draft', 'v1') returning id" | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8"))[0].id)') key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json') curl -s -X PATCH "$AURABASE_URL/v1/db/qd_upd_notes/$id?select=title,body" "${key[@]}" -d '{"body": "v2"}' echo curl -s -X PUT "$AURABASE_URL/v1/db/qd_upd_notes/$id?select=title,body" "${key[@]}" -d '{"title": "Final", "body": "v3"}' echo curl -s -X DELETE "$AURABASE_URL/v1/db/qd_upd_notes/$id" "${key[@]}" -w 'DELETE %{http_code}\n' curl -s -X DELETE "$AURABASE_URL/v1/db/qd_upd_tasks?title=eq.Nothing" "${key[@]}" -w 'DELETE with filter %{http_code}\n' ``` ```text expect="rest-by-id" {"data":{"title":"Draft","body":"v2"},"meta":{}} {"data":{"title":"Final","body":"v3"},"meta":null} DELETE 204 DELETE with filter 204 ``` ## Delete rows that match a filter `delete()` returns nothing unless you chain `.select()`, which returns the deleted rows: ```typescript verify="sdk-delete" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const quiet = await admin.from('qd_upd_tasks').delete().eq('title', 'Celebrate') console.log(quiet.data, quiet.error) await admin.from('qd_upd_tasks').insert({ title: 'Temporary' }) const loud = await admin.from('qd_upd_tasks').delete().eq('title', 'Temporary').select('title') console.log(loud.data, loud.error) ``` ```text expect="sdk-delete" null null [ { title: 'Temporary' } ] null ``` Over REST, a `DELETE` answers `204` with no body. The header `Prefer: return=representation` returns the deleted rows, and `?select=` then chooses their columns; `?select=` alone still answers `204`: ```bash verify="rest-delete" needs="table" aura db raw "insert into qd_upd_tasks (title) values ('Old 1'), ('Old 2')" > /dev/null key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY") curl -s -X DELETE "$AURABASE_URL/v1/db/qd_upd_tasks?title=eq.Old%201&select=title" "${key[@]}" -w 'select only: %{http_code}\n' curl -s -X DELETE "$AURABASE_URL/v1/db/qd_upd_tasks?title=eq.Old%202&select=title" "${key[@]}" -H 'Prefer: return=representation' -w ' %{http_code}\n' ``` ```text expect="rest-delete" select only: 204 {"data":[{"title":"Old 2"}],"meta":{}} 200 ``` In SQL, `delete from qd_upd_tasks where title = 'Celebrate'`. ## Calls without a filter A mutation without a filter applies to every row the caller can see. Each door treats it differently: | Door | `update` without a filter | `delete` without a filter | | --- | --- | --- | | SDK | Refused before any request: `UNFILTERED_MUTATION` | Refused before any request: `UNFILTERED_MUTATION` | | REST `PATCH` / `DELETE /v1/db/{table}` | **Accepted**: every visible row is updated | **Accepted**: every visible row is deleted | | `aura db raw`, `db.sql()` | Refused: `UPDATE without a WHERE clause is not allowed in raw queries` | Refused: `DELETE without a WHERE clause is not allowed in raw queries` | ```typescript verify="guard" needs="table" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const r = await admin.from('qd_upd_tasks').delete() console.log(r.error?.code, '-', r.error?.message) ``` ```text expect="guard" UNFILTERED_MUTATION - update()/delete() without a filter rejected (anti-wipe protection): add an .eq()/... filter or use an id-based mutation ``` The SQL endpoint refuses both, with these exact messages: ```bash verify="raw-guard" needs="table" aura db raw "update qd_upd_tasks set status = 'open'" || true aura db raw "delete from qd_upd_tasks" || true ``` ```text expect="raw-guard" Error: [400] BAD_REQUEST: Invalid request: UPDATE without a WHERE clause is not allowed in raw queries — risk of overwriting every row. Add a WHERE condition. Error: [400] BAD_REQUEST: Invalid request: DELETE without a WHERE clause is not allowed in raw queries — risk of deleting every row. Add a WHERE condition. ``` The SDK refuses on the client, so a raw HTTP call or another client gets no such protection: with the `service_role` key, `curl -X DELETE "$AURABASE_URL/v1/db/qd_upd_tasks"` empties the table, and a `PATCH` without a filter changes every row. Always send a filter over REST, and keep the `service_role` key on servers. To change every row on purpose, say so in SQL with an explicit condition, which the endpoint accepts: `update qd_upd_tasks set status = 'open' where true`. `.or([])` and other empty filters count as no filter for the SDK. A filter on a column named like a directive of the same call (`limit`, `offset`, `cursor`, `order`, `count` or `select`, such as `.eq('limit', 1).limit(1)`) is refused with `RESERVED_FILTER_CONFLICT`. ## As a signed-in user With the anon key and a signed-in user, the policies of the table decide which rows an update or delete can reach. `todos` lets each user change its own rows only: the same call that changes the user's todo touches nothing of Alice's. ```typescript verify="user" needs="table" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `update-${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 await aura.from('todos').insert({ user_id: me, title: 'Update me' }) const mine = await aura.from('todos').update({ done: true }).eq('title', 'Update me').select('title, done') console.log('own row:', mine.data) const alice = await aura.from('todos').update({ done: true }).eq('title', 'Create a table').select('title') console.log('alice row:', alice.data, alice.meta?.rows_affected) const removed = await aura.from('todos').delete().eq('title', 'Update me').select('title') console.log('deleted:', removed.data) ``` ```text expect="user" own row: [ { title: 'Update me', done: true } ] alice row: [] 0 deleted: [ { title: 'Update me' } ] ``` PostgreSQL does not raise an error for rows a policy hides: the update finds none. A policy that lets a user see a row but not change it gives the same `[]`. The sign-up works because email confirmation is turned off on the test project; a project requires it by default. ## Soft delete A soft delete keeps the row and marks it as deleted, so it can be restored and audited. Add a nullable `deleted_at` column (the table above has one), set it instead of deleting, and read through a view or a filter that hides marked rows: ```sql verify="soft-view" needs="table" create view qd_upd_live_tasks as select id, title, status from qd_upd_tasks where deleted_at is null; create index qd_upd_tasks_live on qd_upd_tasks (status) where deleted_at is null; ``` ```text expect="soft-view" ℹ No results (0 rows). ``` ```typescript verify="soft" needs="soft-view" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) await admin.from('qd_upd_tasks').update({ deleted_at: new Date().toISOString() }).eq('title', 'Review specs') const live = await admin.from('qd_upd_live_tasks').select('title').order('title') console.log('live:', live.data) await admin.from('qd_upd_tasks').update({ deleted_at: null }).eq('title', 'Review specs') const restored = await admin.from('qd_upd_tasks').select('title').is('deleted_at', 'null').order('title') console.log('restored:', restored.data) ``` ```text expect="soft" live: [ { title: 'Ship' }, { title: 'Write specs' } ] restored: [ { title: 'Review specs' }, { title: 'Ship' }, { title: 'Write specs' } ] ``` The view runs with the caller's rights, so the policies of the table still apply to it ([Views](https://aurabase.dev/en/docs/database/views)). To hide marked rows from users everywhere, put the condition in the policy itself, for example `using (auth.uid() = user_id and deleted_at is null)`, and give the `update` policy a `with check` that allows setting `deleted_at`. The partial index keeps queries on live rows fast when marked rows pile up. A foreign key with `on delete cascade` does not fire on a soft delete: mark the child rows yourself, in the same function or trigger. ## Replace a row with PUT `PUT /v1/db/{table}/{id}` replaces a whole row: columns missing from the body are set to `null`. The SDK has no method for it, and it is served by a different path than `PATCH`, with these limits measured today: | Case | Response | | --- | --- | | Key column `id` of type `uuid`, body with every `not null` column | `200` and the new row | | Key column of another type (such as `bigint` identity, like `todos`) | `500 INTERNAL_ERROR` | | Body without a `not null` column | `500 INTERNAL_ERROR` (the column is set to `null`) | | Unknown id, or a row hidden by a policy | `404 NOT_FOUND Record '…' not found` | Use `PATCH` (`update()`) to change rows; it sends only the columns you change. ## Result ```bash verify="result" needs="soft" aura db raw "select title, status, deleted_at is not null as deleted from qd_upd_tasks order by title" ``` ```text expect="result" deleted │ status │ title ────────┼────────┼───────────── false │ done │ Review specs false │ done │ Ship false │ done │ Write specs ℹ 3 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `UNFILTERED_MUTATION update()/delete() without a filter rejected …` | SDK call without a filter (`status` is `0`: no request was sent). | Add a filter, or use `update(id, …)` / `delete(id)`. | | `RESERVED_FILTER_CONFLICT Filter collides with a directive …` | A filter on a column named `limit`, `offset`, `cursor`, `order`, `count` or `select`, with the same directive in the chain. | Remove the directive from the mutation. | | `data: []`, `meta.rows_affected: 0` and a `hint` | No row matches, or a policy hides the rows from this role. | Check the filter; check the `update` / `delete` policies. | | `404 RECORD_NOT_FOUND Cannot coerce the result to a single JSON object` | `update(id, …)` or `delete(id)` on an id that does not exist or is hidden. | Check the id and the policies. | | `UPDATE without a WHERE clause is not allowed in raw queries …` or `DELETE without a WHERE clause …` | `aura db raw` or `db.sql()` with an `update` or a `delete` without `where`. | Add a `where`; `where true` changes or deletes every row on purpose. | | `403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy …` | The new values fail the `with check` of the `update` policy. | Change values the policy allows. | | `500 INTERNAL_ERROR` on `PUT` | Key that is not a `uuid` named `id`, or a `not null` column missing from the body. | Use `PATCH`. | ## Clean up The test user created by the `user` example stays in the project; delete it with `aura auth users delete `. ```bash verify="clean-up" needs="table" aura db raw "drop view if exists qd_upd_live_tasks" aura db raw "drop table qd_upd_tasks, qd_upd_notes" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert): Add rows, and insert or update with on conflict. - [Filter operators](https://aurabase.dev/en/docs/database/filter-operators): Every filter of the SDK and of the REST API. - [Transactions and consistency](https://aurabase.dev/en/docs/database/transactions): Several writes at once, and conflicts between writers. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Policies that decide which rows each user changes. --- ### Aggregate rows Source: https://aurabase.dev/en/docs/database/aggregates.md # Aggregate rows > Get totals and per-group figures from your data, with the method that works today for each need, and know which aggregate doors are closed. The SDK and the REST API count rows, but they do not compute sums, averages or groups on a PostgreSQL project: write the aggregate in SQL, in a view you read like a table or a function you call with `rpc()`. The policies of the tables still apply when the view or function runs with the caller's rights. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. The examples create the table `qd_agg_orders`, the view `qd_agg_by_status` and the function `qd_agg_totals`, read them with the `service_role` key, then remove them. ## What works today | Need | Use | Available | | --- | --- | --- | | Number of rows matching a filter | `select('*', { count: 'exact', head: true })` | Yes | | Number of related rows per row | `select('name, child_table(count)')` | Yes | | `sum`, `avg`, `min`, `max`, `group by` | A view, or a function called with `rpc()` | Yes | | Aggregates in `select()` (`amount.sum()`, `count()`) | | No: refused with `Use of aggregate functions is not allowed` | | `POST /v1/db/{table}/aggregate` | | MongoDB projects only | | Ad hoc SQL from a server | `aura db raw`, `db.sql()` | Yes, `service_role` key | ## Example data ```sql verify="setup" create table qd_agg_orders ( id int primary key, customer text not null, status text not null, amount numeric(10,2) not null, ordered_on date not null ); insert into qd_agg_orders values (1, 'ada', 'paid', 120.00, '2026-11-01'), (2, 'ada', 'paid', 35.50, '2026-11-03'), (3, 'bob', 'refunded', 80.00, '2026-11-03'), (4, 'cy', 'paid', 15.25, '2026-11-10'), (5, 'bob', 'pending', 60.00, '2026-11-12'); ``` ```text expect="setup" ℹ No results (0 rows). ``` ## Count rows `count` counts the rows that match the filters; `head: true` skips the rows themselves: ```typescript verify="count" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const all = await admin.from('qd_agg_orders').select('*', { count: 'exact', head: true }) const paid = await admin.from('qd_agg_orders').select('*', { count: 'exact', head: true }).eq('status', 'paid') console.log('orders:', all.count, 'paid:', paid.count) const members = await admin.from('orgs').select('slug, org_members(count)') console.log('members per org:', JSON.stringify(members.data)) ``` ```text expect="count" orders: 5 paid: 3 members per org: [{"slug":"acme","org_members":[{"count":2}]}] ``` `table(count)` inside `select()` counts the related rows of each row through a foreign key ([Join tables and nest rows](https://aurabase.dev/en/docs/database/joins)). To count per value of a column (orders per status), group in SQL. ## Group in a view A view saves the `group by` query; you read it with `from()` and filter or sort it like a table: ```sql verify="view" needs="setup" create view qd_agg_by_status as select status, count(*)::int as orders, sum(amount) as total, round(avg(amount), 2) as average from qd_agg_orders group by status; ``` ```text expect="view" ℹ No results (0 rows). ``` ```typescript verify="view-read" needs="view" 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_agg_by_status').select('status, orders, total, average').order('total', { ascending: false }) console.log(data, error) const paid = await admin.from('qd_agg_by_status').select('total').eq('status', 'paid').single() console.log('paid total:', paid.data) ``` ```text expect="view-read" [ { status: 'paid', orders: 3, total: 170.75, average: 56.92 }, { status: 'refunded', orders: 1, total: 80, average: 80 }, { status: 'pending', orders: 1, total: 60, average: 60 } ] null paid total: { total: 170.75 } ``` Aurabase creates views with `security_invoker = true` unless you set the option explicitly ([Views and materialized views](https://aurabase.dev/en/docs/database/views#invoker)): a signed-in user who reads the view gets figures computed on the rows its policies let it see, such as its own orders only. A filter on the view (`eq('status', 'paid')`) applies to the grouped rows, like `having`. ## Aggregate in a function When the aggregate takes parameters (a date range, a customer), write a function that returns a table, and call it with `rpc()`: ```sql verify="function" needs="setup" create function qd_agg_totals(p_since date) returns table (customer text, orders int, total numeric) language sql stable as $$ select customer, count(*)::int, sum(amount) from qd_agg_orders where ordered_on >= p_since and status = 'paid' group by customer order by sum(amount) desc $$; ``` ```text expect="function" ℹ No results (0 rows). ``` ```typescript verify="function-call" needs="function" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.rpc('qd_agg_totals', { p_since: '2026-11-02' }) console.log(data, error) ``` ```text expect="function-call" [ { customer: 'ada', orders: 1, total: 35.5 }, { customer: 'cy', orders: 1, total: 15.25 } ] null ``` To let signed-in users call it, `grant execute on function qd_agg_totals(date) to aura_authenticated`; the function runs with their rights, so their policies filter the rows it aggregates. See [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc). ## Refused requests Aggregate functions in `select()` are turned off on the REST API of every project: ```typescript verify="refused-select" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const r = await admin.from('qd_agg_orders').select('status, amount.sum()') console.log(r.error?.status, r.error?.code, r.error?.message) ``` ```text expect="refused-select" 400 POSTGREST_ERROR Use of aggregate functions is not allowed ``` `POST /v1/db/{table}/aggregate` takes a MongoDB aggregation pipeline. It requires the `service_role` key on every project, and a PostgreSQL project refuses it: ```bash verify="refused-endpoint" needs="setup" for key in "$AURABASE_ANON_KEY" "$AURABASE_SERVICE_ROLE_KEY"; do curl -s -X POST "$AURABASE_URL/v1/db/qd_agg_orders/aggregate" \ -H "apikey: $key" -H 'content-type: application/json' -d '[{"$match": {}}]' \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' done ``` ```text expect="refused-endpoint" FORBIDDEN - Forbidden: Aggregation is reserved to the service_role role BAD_REQUEST - Invalid request: Pipeline aggregation is specific to MongoDB: it is not available on a 'postgres' project. Use `?select=` with aggregate functions (count/sum/avg/min/max) or `POST /v1/db/{project_id}/raw` for SQL. ``` The second message suggests `?select=` aggregates, which are turned off as shown above: use a view, a function, or SQL from a server. ## Large tables An aggregate reads every row it groups. On a large table: - index the columns of `where` and `group by` ([Indexes](https://aurabase.dev/en/docs/database/indexes)); - for figures that may be a few minutes old (dashboards), store them in a materialized view and refresh it from your code ([Views and materialized views](https://aurabase.dev/en/docs/database/views)); revoke it from the anon key, since a materialized view has no row level security; - for a total shown next to a list, `count: 'planned'` avoids a full count ([Paginate and count rows](https://aurabase.dev/en/docs/database/pagination)). ## Result ```sql verify="result" needs="view" select status, orders, total from qd_agg_by_status order by status ``` ```text expect="result" orders │ status │ total ───────┼──────────┼─────── 3 │ paid │ 170.75 1 │ pending │ 60.0 1 │ refunded │ 80.0 ℹ 3 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400 POSTGREST_ERROR Use of aggregate functions is not allowed` | `sum()`, `avg()`, `count()`… in `select()`. | Use a view or a function. | | `403 FORBIDDEN Forbidden: Aggregation is reserved to the service_role role` | `/aggregate` with the anon key or a user token. | Not available for apps; use a view or a function. | | `400 BAD_REQUEST … Pipeline aggregation is specific to MongoDB …` | `/aggregate` on a PostgreSQL project. | Use a view, a function or SQL. | | `column "…" must appear in the GROUP BY clause or be used in an aggregate function` | A selected column is neither grouped nor aggregated. | Add it to `group by`, or aggregate it. | ## Clean up ```bash verify="clean-up" needs="setup" aura db raw "drop function if exists qd_agg_totals(date); drop view if exists qd_agg_by_status" aura db raw "drop table qd_agg_orders" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Views and materialized views](https://aurabase.dev/en/docs/database/views): Save a group by as a view, or store its result. - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Aggregates that take parameters. - [Paginate and count rows](https://aurabase.dev/en/docs/database/pagination): Exact and estimated counts. - [Run SQL](https://aurabase.dev/en/docs/database/run-sql): Ad hoc queries from a server. --- ### Full-text search Source: https://aurabase.dev/en/docs/database/full-text-search.md # Full-text search > Find rows by the words they contain, in the right language, sorted by relevance, fast on large tables, and tolerant of typos. PostgreSQL full-text search turns text into a list of normalized words (a `tsvector`) and matches it against a query (a `tsquery`): `reading` and `reads` both match `read`, and common words such as `the` are ignored. Aurabase exposes it through the SDK filter `textSearch()`, the REST operators `fts`, `plfts`, `phfts` and `wfts`, the endpoint `POST /v1/db/{table}/search`, and SQL. The examples follow PostgreSQL 18. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. The examples create the table `qd_fts_articles` and the functions `qd_fts_search` and `qd_fts_fuzzy`, read them with the `service_role` key, then remove them. ## Choose a method | Method | Language | Ranking | Speed on large tables | Typos | | --- | --- | --- | --- | --- | | `textSearch()` on a `tsvector` column with a GIN index | Fixed in the column definition | No (sort by another column) | Fast | No | | `textSearch()` on a `text` column | `config` option, `english` by default | No | Scans every row | No | | A function with `ts_rank`, called with `rpc()` | Yours | Yes, with highlights | Fast with the index | No | | `POST /v1/db/{table}/search` | French, fixed | Yes (`_rank`) | Scans every row | No | | Trigrams (`pg_trgm`) in a function | Any | By similarity | Fast with a GIN trigram index | Yes | | `ilike('%word%')` | None | No | Fast with a trigram index | No | ## A searchable table Store the `tsvector` in a generated column, so PostgreSQL keeps it up to date, and index it with GIN: ```sql verify="setup" create table qd_fts_articles ( id int primary key, title text not null, body text not null, search tsvector generated always as ( setweight(to_tsvector('english', title), 'A') || setweight(to_tsvector('english', body), 'B') ) stored ); create index qd_fts_articles_search on qd_fts_articles using gin (search); insert into qd_fts_articles (id, title, body) values (1, 'Getting started with Postgres', 'Create a table, insert rows and read them back.'), (2, 'Row level security', 'Policies decide which rows each user reads and writes.'), (3, 'Search your data', 'Full-text search ranks documents by the words they contain.'), (4, 'Indexes for faster reads', 'A GIN index makes text search fast on large tables.'); ``` ```text expect="setup" ℹ No results (0 rows). ``` `setweight` marks title words as more important (`A`) than body words (`B`), which ranking uses below. The generated column is read-only: you insert `title` and `body`, never `search`. ## Search with textSearch() `textSearch(column, query, options)` adds a full-text filter. On the `tsvector` column, it uses the index: ```typescript verify="text-search" needs="setup" 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_fts_articles') .select('title') .textSearch('search', 'reading', { type: 'plain', config: 'english' }) .order('id') console.log(data, error) ``` ```text expect="text-search" [ { title: 'Getting started with Postgres' }, { title: 'Row level security' }, { title: 'Indexes for faster reads' } ] null ``` `reading` matched `read` and `reads` in three articles: all three are reduced to the word `read`. Over REST: ```bash verify="rest" needs="setup" curl -s --get "$AURABASE_URL/v1/db/qd_fts_articles" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ --data-urlencode 'select=title' --data-urlencode 'search=wfts(english).search -security' echo ``` ```text expect="rest" {"data":[{"title":"Search your data"}, {"title":"Indexes for faster reads"}],"meta":{}} ``` On a plain `text` column, `textSearch('body', 'policies')` also works: PostgreSQL converts the text on the fly for every row, with the `english` configuration unless you pass `config`. That is fine for small tables; add a `tsvector` column and an index before the table grows. ## Query syntaxes | `type` | REST operator | PostgreSQL function | Input | | --- | --- | --- | --- | | (none) | `fts` | `to_tsquery` | Operators written by you: `postgres & !mysql`, `search <-> data`, `read:*` (prefix). | | `'plain'` | `plfts` | `plainto_tsquery` | Plain words, all required. | | `'phrase'` | `phfts` | `phraseto_tsquery` | Words in this order. | | `'websearch'` | `wfts` | `websearch_to_tsquery` | What users type: `"exact phrase"`, `or`, `-excluded`. | ```typescript verify="query-types" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const titles = async (q: any) => { const { data, error } = await q return error ? `${error.status} ${error.code} ${error.message}` : data.map((r: any) => r.id).join(',') } const q = () => admin.from('qd_fts_articles').select('id').order('id') console.log('fts prefix: ', await titles(q().textSearch('search', 'index:*', { config: 'english' }))) console.log('fts and/not: ', await titles(q().textSearch('search', 'rows & !policies', { config: 'english' }))) console.log('plain: ', await titles(q().textSearch('search', 'text search', { type: 'plain', config: 'english' }))) console.log('phrase: ', await titles(q().textSearch('search', 'row level', { type: 'phrase', config: 'english' }))) console.log('websearch: ', await titles(q().textSearch('search', '"text search" or policies', { type: 'websearch', config: 'english' }))) console.log('bad syntax: ', await titles(q().textSearch('search', 'rows &', { config: 'english' }))) ``` ```text expect="query-types" fts prefix: 4 fts and/not: 1 plain: 3,4 phrase: 2 websearch: 2,3,4 bad syntax: 400 POSTGREST_ERROR no operand in tsquery: "rows &" ``` Pass user input with `'websearch'` or `'plain'`: they never fail on syntax. Use the default `to_tsquery` syntax only for queries your code writes. Always pass the same `config` as the one used to build the `tsvector`, or words may be normalized differently. ## Rank and highlight results A filter only keeps or drops rows. To sort by relevance and show the matching words, write a function with `ts_rank` and `ts_headline`, and call it with `rpc()`: ```sql verify="rank-fn" needs="setup" create function qd_fts_search(p_query text) returns table (id int, title text, rank real, snippet text) language sql stable as $$ select a.id, a.title, ts_rank(a.search, q) as rank, ts_headline('english', a.body, q, 'StartSel=[, StopSel=]') as snippet from qd_fts_articles a, websearch_to_tsquery('english', p_query) q where a.search @@ q order by rank desc, a.id limit 20 $$; ``` ```text expect="rank-fn" ℹ No results (0 rows). ``` ```typescript verify="rank" needs="rank-fn" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.rpc('qd_fts_search', { p_query: 'search' }) if (error) throw error for (const r of data) console.log(r.rank.toFixed(3), r.title, '|', r.snippet) ``` ```text expect="rank" 0.669 Search your data | Full-text [search] ranks documents by the words they contain. 0.243 Indexes for faster reads | A GIN index makes text [search] fast on large tables. ``` The title match counts more because of weight `A`. Grant `EXECUTE` and add a `select` policy on the table to let the anon key or users call it ([Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc)); the function runs with the caller's rights, so users only find rows they may read. ## The /search endpoint `POST /v1/db/{table}/search` takes `query`, `columns` (required), and optional `limit` and `offset`. It searches the given columns with the **French** configuration, whatever the language of your text, and adds a `_rank` field: ```bash verify="search-endpoint" needs="setup" curl -s -X POST "$AURABASE_URL/v1/db/qd_fts_articles/search" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"query": "policies", "columns": ["title", "body"], "limit": 5}' \ | node -e 'for (const r of JSON.parse(require("fs").readFileSync(0, "utf8")).data) console.log(r.title, Number(r._rank).toFixed(3))' curl -s -X POST "$AURABASE_URL/v1/db/qd_fts_articles/search" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"query": "reading", "columns": ["title", "body"]}' echo ``` ```text expect="search-endpoint" Row level security 0.061 {"data":[],"meta":null} ``` `reading` finds nothing here, while the English configuration matched three articles: the French rules do not reduce `reading` to `read`. The endpoint has no SDK method, returns every column plus `_rank`, cannot use your index, and applies the caller's policies (the anon key gets `[]` on a table without a `select` policy). Prefer `textSearch()` or a function for English or any other language. ## Fuzzy search with trigrams Full-text search matches words, not spellings: `postgers` finds nothing. The `pg_trgm` extension, installed in every project, compares strings by their groups of three letters, which tolerates typos. A GIN trigram index serves `%` (similar to), `ilike '%…%'` and `similarity()` ordering: ```sql verify="trgm-fn" needs="setup" create index qd_fts_articles_title_trgm on qd_fts_articles using gin (title gin_trgm_ops); create function qd_fts_fuzzy(p_text text) returns table (title text, score real) language sql stable as $$ select title, similarity(title, p_text) from qd_fts_articles where title % p_text order by similarity(title, p_text) desc limit 10 $$; ``` ```text expect="trgm-fn" ℹ No results (0 rows). ``` ```typescript verify="trgm" needs="trgm-fn" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const fuzzy = await admin.rpc('qd_fts_fuzzy', { p_text: 'serch yuor data' }) console.log(fuzzy.data?.map((r: any) => `${r.title} ${r.score.toFixed(2)}`), fuzzy.error) const fts = await admin.from('qd_fts_articles').select('title').textSearch('search', 'postgers', { type: 'plain', config: 'english' }) console.log('full-text, typo:', fts.data) const contains = await admin.from('qd_fts_articles').select('title').ilike('title', '%level%') console.log('ilike:', contains.data) ``` ```text expect="trgm" [ 'Search your data 0.43' ] null full-text, typo: [] ilike: [ { title: 'Row level security' } ] ``` `%` keeps rows whose similarity is above `pg_trgm.similarity_threshold` (0.3 by default). Combine both methods in one function when you need words and typos: full-text first, trigrams when it finds nothing. `unaccent`, also installed, removes accents before comparing, so that a search without accents finds words written with them. ## Result ```bash verify="result" needs="setup" aura db raw "select id, title from qd_fts_articles where search @@ websearch_to_tsquery('english', 'fast index') order by id" ``` ```text expect="result" id │ title ─────┼───────────────────────── 4 │ Indexes for faster reads ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400 POSTGREST_ERROR no operand in tsquery: "…"` (or another `tsquery` syntax error) | User input passed to `textSearch()` without `type`. | Use `type: 'websearch'` or `'plain'`. | | No result for a word that is in the text | Different `config` for the column and the query, or the French `/search` endpoint on English text. | Use the same configuration on both sides. | | `400 BAD_REQUEST Invalid request: search: …`, a message in French saying that at least one column is required | `/search` without `columns`. | Send `"columns": ["title"]`. | | `cannot insert a non-DEFAULT value into column "search"` | A value sent to the generated `tsvector` column. | Leave it out; PostgreSQL computes it. | | A slow search on a large table | No GIN index, or a search on a `text` column converted for every row. | Search a `tsvector` column with a GIN index. | ## Clean up ```bash verify="clean-up" needs="setup" aura db raw "drop function if exists qd_fts_search(text); drop function if exists qd_fts_fuzzy(text)" aura db raw "drop table qd_fts_articles" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Indexes](https://aurabase.dev/en/docs/database/indexes): GIN indexes for tsvector and trigrams. - [Filter operators](https://aurabase.dev/en/docs/database/filter-operators): textSearch and every other filter. - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Ranking and fuzzy search in functions. - [Extensions](https://aurabase.dev/en/docs/database/extensions-model): pg_trgm, unaccent and the other installed extensions. --- ### Query JSON columns Source: https://aurabase.dev/en/docs/database/json.md # Query JSON columns > Store flexible attributes in jsonb, query them like columns, change one key without rewriting the document, and keep these queries fast. A `jsonb` column holds a JSON document per row. PostgreSQL stores it parsed, so you can read a key, filter on it and index it. In the SDK and the REST API, a path such as `attrs->>color` takes the place of a column name. Prefer `jsonb` to `json`: `json` keeps the text as written and cannot be indexed the same way ([Choose column types](https://aurabase.dev/en/docs/database/data-types#json)). ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` in the environment, for the SDK and `curl` examples. The examples create the table `qd_json_products` and the function `qd_json_similar`, read them with the `service_role` key, then remove them. The paths and operators follow PostgreSQL 18. ## A table with JSON ```sql verify="setup" create table qd_json_products ( id int primary key, name text not null, attrs jsonb not null default '{}', tags text[] not null default '{}', embedding vector(3) ); insert into qd_json_products values (1, 'Lamp', '{"color": "black", "watts": 40, "dims": {"h": 45, "w": 20}}', '{home,light}', '[0.9,0.1,0.0]'), (2, 'Desk', '{"color": "oak", "watts": 0, "dims": {"h": 75, "w": 140}, "adjustable": true}', '{home,office}', '[0.1,0.9,0.1]'), (3, 'Monitor', '{"color": "black", "watts": 120, "panel": "ips"}', '{office}', '[0.2,0.8,0.3]'), (4, 'Cable', '{}', '{}', null); ``` ```text expect="setup" ℹ No results (0 rows). ``` ## Read keys | Path | Returns | Example | | --- | --- | --- | | `col->key` | The value as JSON (number, object, `true`…) | `attrs->watts` → `40` | | `col->>key` | The value as text | `attrs->>color` → `"black"` | | `col->a->b`, `col->a->>b` | A nested value | `attrs->dims->>w` → `"20"` | | `col->0` | An element of an array (JSON or PostgreSQL array) | `tags->0` → `"home"` | ```typescript verify="read" needs="setup" 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_json_products') .select('name, color:attrs->>color, watts:attrs->watts, width:attrs->dims->>w, first_tag:tags->0') .order('id') if (error) throw error for (const row of data) console.log(JSON.stringify(row)) ``` ```text expect="read" {"name":"Lamp","color":"black","watts":40,"width":"20","first_tag":"home"} {"name":"Desk","color":"oak","watts":0,"width":"140","first_tag":"home"} {"name":"Monitor","color":"black","watts":120,"width":null,"first_tag":"office"} {"name":"Cable","color":null,"watts":null,"width":null,"first_tag":null} ``` A missing key gives `null`. Without an alias, the key name becomes the field name (`attrs->>color` returns `color`). Over REST, encode the `>` signs: `curl --get --data-urlencode 'select=name,color:attrs->>color' …`; a raw `>` in the URL is refused with `400`. ## Filter on keys Any filter works on a path. Two things change the result: - `->>` compares **text**: `'120' > '40'` is false in text order. Compare numbers with `->`, which keeps the JSON number. - `contains` (`@>`) tests that the document includes a fragment, nested keys included. ```typescript verify="filter" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const names = async (q: any) => (await q).data.map((r: any) => r.name).join(', ') const q = () => admin.from('qd_json_products').select('name').order('id') console.log('color is black: ', await names(q().eq('attrs->>color', 'black'))) console.log('watts > 50 (json):', await names(q().gt('attrs->watts', 50))) console.log('watts > 50 (text):', await names(q().gt('attrs->>watts', '50'))) console.log('contains fragment:', await names(q().contains('attrs', { color: 'black', panel: 'ips' }))) console.log('nested key: ', await names(q().gte('attrs->dims->h', 50))) console.log('has key "dims": ', await names(q().not('attrs->dims', 'is', null))) console.log('one of colors: ', await names(q().in('attrs->>color', ['oak', 'black']))) ``` ```text expect="filter" color is black: Lamp, Monitor watts > 50 (json): Monitor watts > 50 (text): contains fragment: Monitor nested key: Desk has key "dims": Lamp, Desk one of colors: Lamp, Desk, Monitor ``` The text comparison found nothing: as text, `'120'` and `'40'` both sort before `'50'`. Never compare numbers with `->>`. Over REST, `?attrs->>color=eq.black` and `?attrs=cs.{"color":"black"}`, URL-encoded. ## Sort by a key ```typescript verify="order" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const desc = await admin.from('qd_json_products').select('name, watts:attrs->watts').order('attrs->watts', { ascending: false }) console.log(desc.data!.map((r) => `${r.name}:${r.watts}`).join(' ')) const nullsLast = await admin.from('qd_json_products').select('name').order('attrs->watts', { ascending: false, nullsFirst: false }) console.log(nullsLast.data!.map((r) => r.name).join(' ')) ``` ```text expect="order" Cable:null Monitor:120 Lamp:40 Desk:0 Monitor Lamp Desk Cable ``` In descending order, PostgreSQL puts `null` first: add `nullsFirst: false` when some rows lack the key. ## Arrays A PostgreSQL array column (`text[]`, `int[]`) and a JSON array inside `jsonb` take the same filters: `contains` (has all these elements), `containedBy` (only elements from this list) and `overlaps` (at least one in common): ```typescript verify="arrays" needs="setup" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const names = async (q: any) => (await q).data.map((r: any) => r.name).join(', ') const q = () => admin.from('qd_json_products').select('name').order('id') console.log('contains home: ', await names(q().contains('tags', ['home']))) console.log('contains home+office:', await names(q().contains('tags', ['home', 'office']))) console.log('overlaps light|office:', await names(q().overlaps('tags', ['light', 'office']))) console.log('only office tags: ', await names(q().containedBy('tags', ['office']))) ``` ```text expect="arrays" contains home: Lamp, Desk contains home+office: Desk overlaps light|office: Lamp, Desk, Monitor only office tags: Monitor, Cable ``` `containedBy` also matches the empty array of `Cable`. To insert or update an array from the SDK, send a JavaScript array (`tags: ['home', 'sale']`). ## Update one key `update({ attrs: {…} })` replaces the whole document. To change one key and keep the others, use `jsonb_set` or the `||` operator in SQL, from a server or inside a function called with `rpc()`: ```bash verify="update" needs="setup" aura db raw "update qd_json_products set attrs = attrs || '{\"color\": \"white\"}' where id = 1 returning attrs->>'color' as color, attrs->>'watts' as watts" aura db raw "update qd_json_products set attrs = jsonb_set(attrs, '{dims,w}', '25') where id = 1 returning attrs->'dims' as dims" aura db raw "update qd_json_products set attrs = attrs - 'adjustable' where id = 2 returning attrs ? 'adjustable' as still_there" ``` ```text expect="update" color │ watts ──────┼────── white │ 40 ℹ 1 row(s). dims ─────────────── {"h":45,"w":25} ℹ 1 row(s). still_there ─────────── false ℹ 1 row(s). ``` `||` merges top-level keys, `jsonb_set(doc, path, value)` replaces the value at a path, and `-` removes a key. In SQL, `?` tests that a key exists; the REST API has no such operator, so use `not.is.null` on the key as shown above. ## Index JSON A GIN index on the column speeds up `contains` (`@>`) and key tests on large tables; a B-tree index on an expression speeds up `eq` and sorting on one key: ```sql verify="index" needs="setup" create index qd_json_products_attrs on qd_json_products using gin (attrs jsonb_path_ops); create index qd_json_products_color on qd_json_products ((attrs->>'color')); create index qd_json_products_tags on qd_json_products using gin (tags); ``` ```text expect="index" ℹ No results (0 rows). ``` `jsonb_path_ops` makes a smaller index that serves `@>` only; the default `jsonb_ops` also serves the key-exists operators. See [Indexes](https://aurabase.dev/en/docs/database/indexes) to check with `explain` that a query uses them. ## Vector similarity A `vector` column (pgvector, installed in every project) stores embeddings. The REST API has no distance operator, so search through a function that orders by distance, and call it with `rpc()`: ```sql verify="vector-fn" needs="setup" create function qd_json_similar(p_query vector(3), p_limit int default 3) returns table (name text, distance float8) language sql stable as $$ select name, round((embedding <=> p_query)::numeric, 3)::float8 from qd_json_products where embedding is not null order by embedding <=> p_query limit p_limit $$; ``` ```text expect="vector-fn" ℹ No results (0 rows). ``` ```typescript verify="vector" needs="vector-fn" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data, error } = await admin.rpc('qd_json_similar', { p_query: '[0.15,0.85,0.2]', p_limit: 2 }) console.log(data, error) ``` ```text expect="vector" [ { name: 'Desk', distance: 0.009 }, { name: 'Monitor', distance: 0.01 } ] null ``` `<=>` is the cosine distance (smaller is closer), `<->` the Euclidean distance, `<#>` the negative inner product. Pass the vector as a string `'[…]'`. A `vector` column read through the API comes back as a string: `JSON.parse` it to get numbers. For many rows, add an `hnsw` index ([Indexes](https://aurabase.dev/en/docs/database/indexes)). The function is `security invoker`: grant `EXECUTE` and add policies before calling it with the anon key ([Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc)). ## When to use JSON | Data | Store it as | | --- | --- | | Attributes that differ per row (product options, settings, webhook payloads) | `jsonb` | | Values you filter, join, constrain or reference often | Regular columns, with types and constraints | | A list of short labels | A `text[]` array, or a join table if the labels have their own data | | Data you only store and return as is | `jsonb` (or `json` to keep the exact text) | A key you query in every request is a column waiting to be promoted: move it out of the document, give it a type and a constraint, and index it. ## Result ```sql verify="result" needs="update" select name, attrs->>'color' as color, tags from qd_json_products order by id ``` ```text expect="result" color │ name │ tags ──────┼─────────┼────────────────── white │ Lamp │ ["home","light"] oak │ Desk │ ["home","office"] black │ Monitor │ ["office"] NULL │ Cable │ [] ℹ 4 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `400` on a `curl` with `->>` in the URL | A raw `>` in the query string. | URL-encode it (`--data-urlencode`). | | A numeric filter on `->>` returns the wrong rows | `->>` compares text. | Use `->` for numbers and booleans. | | `400 INVALID_INPUT invalid input syntax for type json` | A value that is not valid JSON in an insert or update. | Send an object or a valid JSON string. | | `400 POSTGREST_ERROR … failed to parse …` | A malformed path, such as a missing key after `->`. | Check the path. | | `expected 3 dimensions, not 2` | A vector of the wrong length. | Use the dimension declared on the column. | ## Clean up ```bash verify="clean-up" needs="setup" aura db raw "drop function if exists qd_json_similar(vector, int)" aura db raw "drop table qd_json_products" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Choose column types](https://aurabase.dev/en/docs/database/data-types): jsonb, json, arrays and vector columns. - [Filter operators](https://aurabase.dev/en/docs/database/filter-operators): contains, containedBy, overlaps and the others. - [Indexes](https://aurabase.dev/en/docs/database/indexes): GIN for JSON and arrays, HNSW for vectors. - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Search vectors and update keys through functions. --- ### Call functions with rpc() Source: https://aurabase.dev/en/docs/database/rpc.md # Call functions with rpc() > Run logic that lives in the database with one call, shape what it returns with the usual filters, and turn its exceptions into errors your app can read. `rpc(name, args)` calls a PostgreSQL function of your project and returns its result. It is the door for anything a single read or write cannot express: several statements in one transaction, a computed value, a search with your own SQL. Over REST, the same call is `POST /v1/db/rpc/{name}` with the arguments as a JSON object. Creating functions is covered in [Database functions](https://aurabase.dev/en/docs/database/functions); this page calls them. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` and `AURABASE_ANON_KEY` in the environment, for the SDK and `curl` examples. The examples create the table `qd_rpc_scores` and four functions named `qd_rpc_…`, then remove them. ## Functions to call ```sql verify="setup" create table qd_rpc_scores (id int primary key, player text not null, points int not null); insert into qd_rpc_scores values (1, 'ada', 30), (2, 'bob', 12), (3, 'cy', 25), (4, 'ada', 5); create policy qd_rpc_scores_read on qd_rpc_scores for select to aura_anon, aura_authenticated using (true); create function qd_rpc_top(p_min int default 0) returns setof qd_rpc_scores language sql stable as $$ select * from qd_rpc_scores where points >= p_min order by points desc $$; create function qd_rpc_totals() returns table (player text, total bigint) language sql stable as $$ select player, sum(points) from qd_rpc_scores group by player order by 2 desc $$; create function qd_rpc_check(p_points int) returns int language plpgsql as $$ begin if p_points < 0 then raise exception 'points must be positive' using errcode = '22023'; end if; if p_points > 100 then raise exception 'too many points: %', p_points; end if; return p_points; end $$; create function qd_rpc_noop() returns void language sql as $$ select $$; grant execute on function qd_rpc_top(int), qd_rpc_totals(), qd_rpc_check(int), qd_rpc_noop() to aura_anon, aura_authenticated; ``` ```text expect="setup" ℹ No results (0 rows). ``` The policy lets anyone read the scores; the functions are `security invoker` (the default), so they read the table with the caller's rights. A function created in SQL gets no `EXECUTE` for the public roles until you grant it, as above. ## Call a function ```typescript verify="call" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const { data, error } = await aura.rpc('qd_rpc_check', { p_points: 42 }) console.log(data, error) ``` ```text expect="call" 42 null ``` Over REST: ```bash verify="rest" needs="setup" curl -s -X POST "$AURABASE_URL/v1/db/rpc/qd_rpc_top" \ -H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' \ -d '{"p_min": 20}' echo ``` ```text expect="rest" {"data":[{"id":1,"player":"ada","points":30}, {"id":3,"player":"cy","points":25}],"meta":{}} ``` From SQL, call it like any function: `aura db raw "select qd_rpc_check(42)"`. ## What comes back | The function returns | `data` | | --- | --- | | A scalar (`int`, `text`, `jsonb`…) | The value: `42`, `"text"`, an object. | | `setof
` | An array of rows of that table. | | `table (col type, …)` | An array of objects with those columns. | | `void` | `null`. | ```typescript verify="results" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) console.log('setof:', (await aura.rpc('qd_rpc_top', { p_min: 20 })).data) console.log('table:', (await aura.rpc('qd_rpc_totals')).data) console.log('void:', (await aura.rpc('qd_rpc_noop')).data) ``` ```text expect="results" setof: [ { id: 1, player: 'ada', points: 30 }, { id: 3, player: 'cy', points: 25 } ] table: [ { player: 'ada', total: 35 }, { player: 'cy', total: 25 }, { player: 'bob', total: 12 } ] void: null ``` Rows returned by a function are capped at 1,000 per call, like reads. ## Filter and sort returned rows When a function returns rows, chain the methods of a read: `select()`, filters, `order()`, `limit()`, `single()`. They apply to the rows the function returns: ```typescript verify="rows" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const ada = await aura.rpc('qd_rpc_top').eq('player', 'ada').select('points') console.log('filter:', ada.data) const lowest = await aura.rpc('qd_rpc_top').order('points').limit(2).select('player, points') console.log('order:', lowest.data) const best = await aura.rpc('qd_rpc_top', { p_min: 26 }).single() console.log('single:', best.data, best.error) ``` ```text expect="rows" filter: [ { points: 30 }, { points: 5 } ] order: [ { player: 'ada', points: 5 }, { player: 'bob', points: 12 } ] single: { id: 1, player: 'ada', points: 30 } null ``` ## GET, HEAD and counts `rpc()` sends a `POST` by default. A function that does not write (declared `stable` or `immutable`) can be called with `GET`, which puts the arguments in the query string and can be cached by HTTP caches; `head: true` returns only the count: ```typescript verify="verbs" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const get = await aura.rpc('qd_rpc_top', { p_min: 20 }, { get: true }).select('player') console.log('get:', get.data) const head = await aura.rpc('qd_rpc_top', { p_min: 10 }, { head: true, count: 'exact' }) console.log('head:', head.data, head.count) const post = await aura.rpc('qd_rpc_top', { p_min: 10 }, { count: 'exact' }).limit(1) console.log('post with count:', post.data?.length, post.count) ``` ```text expect="verbs" get: [ { player: 'ada' }, { player: 'cy' } ] head: null 3 post with count: 1 null ``` The count is lost on a `POST` call for now (`count: null`): ask for it with `head: true`, or with `get: true` for a read-only function. Over REST, `GET /v1/db/rpc/qd_rpc_top?p_min=20`. ## Arguments - Arguments are passed **by name**, as a JSON object whose keys are the parameter names (`{ p_min: 20 }`). Their order does not matter. - A parameter with a default (`p_min int default 0`) can be left out. - The function is found by its name **and** the names of the arguments you send: a wrong or missing argument name gives `404 FUNCTION_NOT_FOUND`, not a type error. - Two functions with the same name are told apart by their parameter names only. Give each function its own name. - A function created or replaced a moment ago may answer `404 FUNCTION_NOT_FOUND` until the API reloads its schema; the gateway retries for about a second. ```typescript verify="args" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const wrongName = await aura.rpc('qd_rpc_check', { points: 5 }) console.log(wrongName.error?.status, wrongName.error?.code, wrongName.error?.message) const missing = await aura.rpc('qd_rpc_nope') console.log(missing.error?.status, missing.error?.code, missing.error?.message) ``` ```text expect="args" 404 FUNCTION_NOT_FOUND Could not find the function qd_rpc_check(points) in the schema cache 404 FUNCTION_NOT_FOUND Could not find the function qd_rpc_nope without parameters in the schema cache ``` ## Errors raised by a function `raise exception` in PL/pgSQL stops the function, rolls back everything it did, and becomes the error of the call. The message is yours; the `code` depends on the SQLSTATE: ```typescript verify="raise" needs="setup" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const invalid = await aura.rpc('qd_rpc_check', { p_points: -1 }) console.log(invalid.error?.status, invalid.error?.code, invalid.error?.message) const plain = await aura.rpc('qd_rpc_check', { p_points: 500 }) console.log(plain.error?.status, plain.error?.code, plain.error?.message) ``` ```text expect="raise" 400 INVALID_INPUT points must be positive 400 POSTGREST_ERROR too many points: 500 ``` A plain `raise exception` (SQLSTATE `P0001`) arrives as `400 POSTGREST_ERROR`, with the SQLSTATE in `upstream_code` of the REST body. To let your app branch on the error, choose an SQLSTATE that the API maps to a code (`22023` → `INVALID_INPUT`, `23505` → `DUPLICATE_KEY`, `42501` → `INSUFFICIENT_PRIVILEGE`), or put a stable prefix in the message. ## Who can call a function | Question | Rule | | --- | --- | | Who can call it | The roles with `EXECUTE`: `grant execute on function f(int) to aura_authenticated`. Others get `403 INSUFFICIENT_PRIVILEGE permission denied for function f`. The `service_role` key can call every function. | | With whose rights does it run | `security invoker` (default): the caller's, so the policies of the tables apply to the caller. `security definer`: the owner's, which bypasses row level security. | | Who is the caller inside | `auth.uid()` is the signed-in user, `null` for the anon key. | `security definer` functions cannot be created through `aura db raw`; use the function API with `--security definer` and read the precautions in [Database functions](https://aurabase.dev/en/docs/database/functions#definer). The example function `todo_count` is granted to `aura_authenticated` only: the anon key gets `403`, as shown in [Example schema](https://aurabase.dev/en/docs/database/example-schema). ## Result ```bash verify="result" needs="setup" aura db raw "select qd_rpc_check(7) as checked, (select count(*) from qd_rpc_top(10)) as top_rows" ``` ```text expect="result" checked │ top_rows ────────┼───────── 7 │ 3 ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `404 FUNCTION_NOT_FOUND Could not find the function f(a) in the schema cache` | No function with that name and those argument names, or it was created a moment ago. | Check the names of the arguments; retry after a second. | | `403 INSUFFICIENT_PRIVILEGE permission denied for function f` | The caller's role has no `EXECUTE`. | `grant execute on function f() to aura_authenticated`. | | `400 POSTGREST_ERROR ` | The function raised an exception (SQLSTATE `P0001`). | Handle it in the app; use a mapped SQLSTATE to branch on `code`. | | `data: []` while the table has rows | The function is `security invoker` and the caller's policies hide the rows. | Add a policy, or sign the user in. | | `count: null` | `count` on a `POST` call. | Use `head: true` or `get: true`. | | `400 BAD_REQUEST … The 'SECURITY DEFINER' option is not allowed in raw queries` | Creating a definer function through `aura db raw`. | Use the function API ([Database functions](https://aurabase.dev/en/docs/database/functions)). | ## Clean up ```bash verify="clean-up" needs="setup" aura db raw "drop function qd_rpc_top(int); drop function qd_rpc_totals(); drop function qd_rpc_check(int); drop function qd_rpc_noop()" aura db raw "drop table qd_rpc_scores" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Database functions](https://aurabase.dev/en/docs/database/functions): Create functions, grant EXECUTE, invoker or definer. - [Transactions and consistency](https://aurabase.dev/en/docs/database/transactions): Several writes that succeed or fail together. - [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert): An insert-or-update wrapped in a function. - [Filter operators](https://aurabase.dev/en/docs/database/filter-operators): Filters you can chain on returned rows. --- ### Transactions and consistency Source: https://aurabase.dev/en/docs/database/transactions.md # 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 `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `AURABASE_URL` in 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. ```sql verify="setup" 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); ``` ```text expect="setup" ℹ 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: ```sql verify="fn" needs="setup" 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; ``` ```text expect="fn" ℹ No results (0 rows). ``` ```typescript verify="transfer" needs="fn" 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()) ``` ```text expect="transfer" 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=80 ``` In 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](https://aurabase.dev/en/docs/database/functions#definer). ## 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: ```bash verify="sql" needs="transfer" 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" ``` ```text expect="sql" 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](https://aurabase.dev/en/docs/database/run-sql). ## Isolation level Requests run at PostgreSQL's default level, `read committed`: each statement sees the rows committed before it started. ```sql verify="iso-fn" needs="setup" create function qd_tx_isolation() returns text language sql stable as $$ select current_setting('transaction_isolation') $$; ``` ```text expect="iso-fn" ℹ No results (0 rows). ``` ```typescript verify="isolation" needs="iso-fn" 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) ``` ```text expect="isolation" read committed ``` `set 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](https://aurabase.dev/en/docs/database/connect)), 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: ```typescript verify="optimistic" needs="transfer" 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) ``` ```text expect="optimistic" first save: [ { balance: 75, version: 3 } ] second save, stale version: [] 0 ``` When `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: ```sql 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 ```bash verify="result" needs="optimistic" aura db raw "select owner, balance, version from qd_tx_accounts order by id" ``` ```text expect="result" 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 ` 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 ```bash verify="clean-up" needs="setup" 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" ``` ```text expect="clean-up" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## See also - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Arguments, results and errors of a function call. - [Database functions](https://aurabase.dev/en/docs/database/functions): Create functions, grant EXECUTE, invoker or definer. - [Run SQL](https://aurabase.dev/en/docs/database/run-sql): What aura db raw accepts and refuses. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): A direct connection for begin and commit. --- ### SQL editor Source: https://aurabase.dev/en/docs/database/sql-editor.md # SQL editor > Run SQL on your project from the browser, without a terminal: what the editor sends, what it keeps, and the rules it shares with aura db raw. The SQL editor of the Studio runs SQL on your project's database from the browser. It sends your query to the same endpoint as `aura db raw`, so it accepts and refuses the same statements, and it runs with administrator rights: row level security does not filter what it returns. ## Prerequisites - A project, and access to it in the Studio as a member of its organization. - For the CLI examples at the end: a linked project (`aura link `) and the example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The Studio screens are described from the Studio code; the replayed examples on this page are the CLI ones, which call the same endpoint. ## Open the editor In the Studio, open your project, then **Database** and **SQL Editor** in the database sidebar, or press the command palette shortcut and type `SQL Editor`. The page address is: ```text https:////database/sql/editor ``` The page has three areas: a sidebar with the **History** and **Ask AI** tabs, the editor, and the results below it. ## Run a query 1. Type your SQL in the editor. A new query starts with the comment `-- Write your SQL here`. 2. Click **Run**, or press `⌘ + Enter` (`Ctrl + Enter` on Windows and Linux). 3. Read the rows in the results table, with the row count and the time the request took. Several statements separated by `;` run in one request and one transaction: if one fails, none is applied. The results table shows the rows of the request; a statement that returns no row shows `Query executed successfully — no records returned.` After a statement that changes the schema (`create`, `alter`, `drop`…), the other Studio pages of the project reload the schema, so a new table appears in the table editor without a page refresh. ## What the editor runs | Rule | Detail | | --- | --- | | Endpoint | `POST /v1/db/{project_id}/raw`, the endpoint of `aura db raw` and `db.sql()`. | | Rights | The project's administrator role: every row of every table, policies not applied. | | Refused statements | The same list as `aura db raw`: `begin`/`commit`, `create extension`, system catalogs, `security definer` functions, `update` or `delete` without `where`, and the others listed in [Run SQL](https://aurabase.dev/en/docs/database/run-sql#refused). | | Time limit | The statement timeout of the endpoint, and the gateway stops waiting after 30 seconds by default. | | Rate limit | The `/raw` limit of the project's plan applies to the editor as to the CLI. | To see what a user or a visitor would get, run the query with `aura db raw --as authenticated --user ` or `--as anon` ([Run SQL](https://aurabase.dev/en/docs/database/run-sql#as-role)); the editor has no such option. ## Dry run and read only Two check boxes above the editor restrict the next run: - **Dry run**: the query is executed, then its transaction is rolled back. You see the rows and the errors it would produce, and nothing is kept. A banner above the results says that the transaction was canceled. - **Read only**: the transaction is opened read-only; PostgreSQL refuses any write. The banner describes the mode of the run whose results are shown, even if you change the boxes afterwards. Use **Dry run** before an `update` or a migration you are not sure of. ## Results and export - Columns are shown in alphabetical order, not in the order of your `select`: each row arrives as a JSON object with sorted keys. - `null` values are marked as such; JSON values are shown as JSON text. - **JSON** copies the rows to the clipboard as a JSON array; **CSV** downloads them as `query_.csv`. - **Copy** copies the SQL; **Export** downloads it as a `.sql` file. The results table shows every row the request returns. For large exports, prefer `aura db raw --json` or a direct connection with `COPY` ([Connect to your database](https://aurabase.dev/en/docs/database/connect)). ## History The **History** tab lists your last 50 queries, each marked as succeeded or failed; click one to load it in the editor. The history is kept in your browser's local storage, per project: it is not shared with teammates or other devices, it is cleared with the browser's site data, and entries older than 30 days or longer than 10 KB are not kept. The trash icon clears it; the plus icon starts a new query. Saved, shared or named queries are not available. Keep the queries you reuse in files of your repository, or as migrations ([Run SQL](https://aurabase.dev/en/docs/database/run-sql)). ## Ask AI The **Ask AI** tab turns a question in plain language into SQL. Type the question and click **Generate**: the answer shows the SQL, the tables it uses, a confidence score and an explanation. If the model wrote no `LIMIT`, the server adds one and the panel says so (`LIMIT automatically added`). **Insert into editor** copies the SQL into the editor; nothing runs until you click **Run**. - The server reads the schema of your project itself; it is not sent from the browser. - Ask AI needs an AI provider key: one saved for the project (`POST /v1/ai/{project_id}/providers/openai`), or one set on the server. Without it, the panel shows an `AI_PROVIDER_NOT_CONFIGURED` error saying that the provider `openai` is configured neither for the project nor on the server. - The last 20 questions and their SQL are kept in your browser, per project, for 30 days. Read the generated SQL before running it: it runs with administrator rights like any query of the editor. ## The same from the CLI The editor's modes are the `--dry-run` and `--read-only` options of `aura db raw`, which needs the project's `service_role` key in `AURABASE_SERVICE_ROLE_KEY`: ```bash verify="dry-run" aura db raw --dry-run "update todos set done = true where title = 'Create a table' returning title, done" aura db raw "select done from todos where title = 'Create a table'" ``` ```text expect="dry-run" ℹ Mode: dry-run — query is executed then transaction ROLLED BACK. done │ title ─────┼─────────────── true │ Create a table ℹ 1 row(s). done ───── false ℹ 1 row(s). ``` ```bash verify="read-only" aura db raw --read-only "delete from todos where title = 'Create a table'" || true ``` ```text expect="read-only" ℹ Mode: read-only — PostgreSQL will reject any write. Error: [400] BAD_REQUEST: Invalid request: cannot execute DELETE in a read-only transaction ``` ## Result After the dry run and the refused read-only delete, the row is unchanged: ```bash verify="result" needs="dry-run" aura db raw "select title, done from todos where title = 'Create a table'" ``` ```text expect="result" done │ title ──────┼─────────────── false │ Create a table ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `Operation not allowed in a raw query: transaction control …` | `begin`, `commit` or `rollback` in the query. | Remove them: each run is already one transaction. | | `UPDATE without a WHERE clause is not allowed in raw queries …` or `DELETE without a WHERE clause …` | An `update` or a `delete` without `where`. | Add a `where` (`where true` to change or delete every row on purpose). | | `cannot execute … in a read-only transaction` | **Read only** is checked. | Uncheck it to write. | | `The 'SECURITY DEFINER' option is not allowed in raw queries …` | Creating a definer function. | Use the function API ([Database functions](https://aurabase.dev/en/docs/database/functions)). | | `AI_PROVIDER_NOT_CONFIGURED` in Ask AI | No AI provider key for the project or the server. | Save a provider key for the project. | | `429` | The `/raw` rate limit of the plan. | Wait for the next minute; batch statements in one run. | ## See also - [Run SQL](https://aurabase.dev/en/docs/database/run-sql): aura db raw, POST /raw and db.sql(): options and refused statements. - [Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema): Tables, views and functions of the project. - [Transactions and consistency](https://aurabase.dev/en/docs/database/transactions): What runs in one transaction. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): psql and GUI clients on a direct connection. --- ### Row-level security Source: https://aurabase.dev/en/docs/database/rls.md # Row-level security > Enable row level security on a table, give each user its own rows with one policy, understand why a hidden row comes back as an empty array, and check the parts of the database that policies do not cover. Row level security (RLS) is the PostgreSQL feature that decides, row by row, what a role may read and write. On a table with RLS on, a query only sees the rows that a policy lets its role see, and a write is accepted only if a policy allows it. With no policy at all, nothing is visible and nothing can be written, except by the roles that bypass RLS. ## How it works Each request reaches PostgreSQL as a role: the anon key becomes `aura_anon`, a signed-in user becomes `aura_authenticated` with its id in `auth.uid()`, and the `service_role` key becomes a role that bypasses RLS ([Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys) lists them). PostgreSQL then adds the policies written for that role to the query: ```text filename="what a policy does to a query" select * from todos ← the query sent by the SDK for alice policy todos_owner: using (auth.uid() = user_id) select * from todos where auth.uid() = user_id ← what PostgreSQL runs ``` Three facts shape everything on this page: - **Tables created through Aurabase have RLS on.** `aura db table create`, the schema API, the Studio and `aura db raw` (so `aura db push` too) enable and force RLS on every new table. Until you add a policy, the anon key and signed-in users get no row. - **A hidden row is not an error.** A read that no policy allows returns an empty array; an update or delete that reaches no row succeeds and changes nothing. Only a written row that a policy refuses fails. - **RLS filters rows, not privileges.** The public roles hold every table privilege on the tables of your schema by default, `truncate` included, and several kinds of objects have no RLS at all. [What row level security does not protect](#limits) lists them; [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges) shows how to reduce those privileges. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the table `sec_rls_notes`, then remove it. The SDK example signs a test user up: on a project that requires email confirmation (the default), turn it off first, as in the [Quickstart](https://aurabase.dev/en/docs/database/quickstart). ## Turn it on and off Create a table in SQL. Its `user_id` column defaults to the id of the signed-in user, so the application never has to send it: ```bash verify="create" aura db raw "create table sec_rls_notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null)" aura db table list | grep sec_rls_notes ``` ```text expect="create" ℹ No results (0 rows). • sec_rls_notes [RLS] ``` `[RLS]` marks a table whose RLS is on. `aura db table rls
on|off` switches it, as do `PATCH /v1/db/{project_id}/schema/tables/{table}/rls` with `{"enabled": true}` (the `service_role` key is required) and the **RLS policies** tab of a table in the Studio (`//database/sql/table-editor/rls`). Turning it on runs `enable` and `force row level security` together; turning it off runs `no force` and `disable` together, and says what it means. The block below switches it off with the CLI and back on over HTTP: ```bash verify="toggle" needs="create" aura db table rls sec_rls_notes off curl -s -X PATCH "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sec_rls_notes/rls" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d '{"enabled": true}' echo ``` ```text expect="toggle" ✔ RLS disabled on 'sec_rls_notes'. ⚠ Row Level Security is now OFF on 'sec_rls_notes': anyone holding the public (anon) key can read and write every row of this table. Re-enable it with `aura db table rls sec_rls_notes on` and add policies before exposing the table. {"data":{"table":"sec_rls_notes","rls_enabled":true},"meta":null} ``` In SQL, `alter table … enable row level security` and `alter table … force row level security` do the same. A table that you create with `disable row level security` in the same request keeps it off: Aurabase only turns RLS on for tables that appear during a request and that the request did not explicitly leave open. Two kinds of tables are never switched on for you: tables created over the direct PostgreSQL connection, and partitions. See [What row level security does not protect](#limits). ## Give each user its own rows One policy covers the four commands for signed-in users: `using` filters the rows a user reads, updates and deletes, `with check` validates the rows it inserts or updates. ```sql verify="policy" needs="create" create policy sec_rls_notes_owner on sec_rls_notes for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id); ``` ```text expect="policy" ℹ No results (0 rows). ``` `to aura_authenticated` keeps the anon key out of the policy entirely: a visitor has no `auth.uid()`, so an owner policy would not match anyway, but the role clause says it plainly and saves the evaluation. Check the result as two demo users and as a visitor before writing any application code: ```bash verify="as-users" needs="policy" aura db raw "insert into sec_rls_notes (user_id, body) values ('00000000-0000-4000-8000-0000000000a1', 'Alice: call the bank'), ('00000000-0000-4000-8000-0000000000b2', 'Bob: book the room')" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select body from sec_rls_notes" aura db raw --as anon "select count(*) as visible from sec_rls_notes" ``` ```text expect="as-users" ℹ No results (0 rows). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). body ──────────────────── Alice: call the bank ℹ 1 row(s). ℹ Executed as anon. visible ─────── 0 ℹ 1 row(s). ``` From an application, a signed-in user reads its own notes, writes new ones without sending `user_id`, and cannot write a note for someone else: ```typescript verify="sdk" needs="as-users" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const email = `rls-${Date.now()}@example.com` const password = 'correct-horse-battery-9' await aura.auth.signUp({ email, password }) const { error: signInError } = await aura.auth.signInWithPassword({ email, password }) if (signInError) throw signInError const before = await aura.from('sec_rls_notes').select('body') console.log('before:', before.data, before.error) const mine = await aura.from('sec_rls_notes').insert({ body: 'My first note' }).select('body') console.log('insert:', mine.data, mine.error) const forAlice = await aura.from('sec_rls_notes').insert({ user_id: '00000000-0000-4000-8000-0000000000a1', body: 'Not mine' }) console.log('insert for alice:', forAlice.error?.status, forAlice.error?.code, forAlice.error?.message) const touched = await aura.from('sec_rls_notes').update({ body: 'Edited' }).eq('body', 'Alice: call the bank').select('body') console.log('update alice:', touched.data, touched.error) const after = await aura.from('sec_rls_notes').select('body') console.log('after:', after.data) ``` ```text expect="sdk" before: [] null insert: [ { body: 'My first note' } ] null insert for alice: 403 INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "sec_rls_notes" update alice: [] null after: [ { body: 'My first note' } ] ``` The other common shapes (public read of published rows, signed-in read, membership of an organization, a role claim, a restrictive policy) are on [Policies](https://aurabase.dev/en/docs/database/policies). ## Empty answers and refusals PostgreSQL hides rows instead of failing, so most RLS mistakes look like missing data. What each path returns when no policy allows the operation: | Operation | SDK and REST API | `aura db raw --as …`, `db.sql()` | | --- | --- | --- | | Read | `200`, `data: []`. An unfiltered read adds `meta.hint`, which names the role and suggests a policy. | `ℹ No results (0 rows).` | | Insert, or an update whose new row fails `with check` | `403 INSUFFICIENT_PRIVILEGE`, `new row violates row-level security policy for table "…"`, `upstream_code: "42501"` | `400 BAD_REQUEST`, `Invalid request: new row violates row-level security policy for table "…"` | | Update of rows the role cannot see | `200`, `data: []`, `meta.hint` starting `No row was updated.` and `rows_affected: 0` | Success, no row changed | | Delete of rows the role cannot see | `204`, nothing deleted | Success, no row deleted | | Table without the privilege (not a policy matter) | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` | `400 BAD_REQUEST`, `Invalid request: permission denied for table …` | The two paths do not use the same status for the same refusal: write your error handling on the code (`INSUFFICIENT_PRIVILEGE`, or the PostgreSQL code `42501`) and the message, not on the status alone. To see the rows a role can reach, run the query with `aura db raw --as anon` or `--as authenticated --user `, or ask the simulator, which also tries writes inside a transaction it rolls back: [Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy). ## Auth helpers in policies Policies read the caller from the claims of its token. The schema `auth` of the database provides these functions. None of them raises an error when the request carries no token or lacks a claim: the last column gives what each one returns then, so a policy that compares them to a user value denies instead of failing. One exception: if SQL of your own sets the claims to an empty string (`set local request.jwt.claims = ''`), `auth.jwt()` fails with `invalid input syntax for type json`, while the other functions still return the values of the last column. | Function | Returns | Without a token or claim | Notes | | --- | --- | --- | --- | | `auth.uid()` | `uuid` of the signed-in user (claim `sub`) | `NULL` | `NULL` for the anon key, for a `service_role` key and for a key of scope `authenticated` sent without a user token | | `auth.role()` | `text`, claim `role` | `'anon'` | Differs by path: `aura_anon`, `aura_authenticated`, `aura_service_role` through the SDK and REST; `anon`, `authenticated` through `aura db raw --as` and the simulator. Do not compare it in a policy: use `to aura_authenticated` instead. | | `auth.jwt()` | `jsonb`, all claims | `{}` | | | `auth.email()` | `text`, claim `email` | `NULL` | | | `auth.claim(key)` | `jsonb`, one top-level claim | `NULL` | | | `auth.tenant()` | `uuid` from `app_metadata.tenant` | `NULL` | Also `NULL` when the value is not a uuid. See [Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy). | | `auth.has_role(name)` | `boolean`, true if `app_metadata.roles` contains `name` | `false` | Roles you set from a server, never from `user_metadata`, which users can change themselves | | `auth.is_anonymous()` | `boolean`, true for a user signed in anonymously | `false` | Such a user has the role `aura_authenticated` and an id | The same values seen from each path, through a function that returns them: ```bash verify="whoami" needs="create" aura db raw "create function sec_rls_whoami() returns json language sql stable as \$\$ select json_build_object('uid', auth.uid(), 'role', auth.role()) \$\$; grant execute on function sec_rls_whoami() to aura_anon" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rpc/sec_rls_whoami" \ -H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' -d '{}' echo aura db raw --as anon "select sec_rls_whoami() as caller" ``` ```text expect="whoami" ℹ No results (0 rows). {"data":{"uid" : null, "role" : "aura_anon"},"meta":{}} ℹ Executed as anon. caller ────────────────────────── {"role":"anon","uid":null} ℹ 1 row(s). ``` ## Point rows at users There is no `auth.users` table to reference: `references auth.users (id)` fails with `relation "auth.users" does not exist`. The users of a project live in the schema `project__auth`, which the REST API does not serve and which Auth manages. Store the owner in a plain `uuid` column, as `todos.user_id` does, and fill it with `default auth.uid()` or from the session (`session.user.id` in the SDK). A foreign key to `project__auth.users` is accepted by PostgreSQL, but how it interacts with the deletion of a user by Auth was not tested: keep the column without a foreign key, and remove a deleted user's rows from a server. ## What row level security does not protect Row level security only filters the rows of tables that have it on, for the roles that do not bypass it. The rest depends on privileges and on how objects were created. These are the gaps measured on a project, with the safe practice for each: | Gap | What happens | Safe practice | | --- | --- | --- | | Broad default privileges | Every table, view, materialized view and partition of your schema grants all privileges to `aura_anon` and `aura_authenticated`: `select`, `insert`, `update`, `delete`, `truncate`, `references`, `trigger` and `maintain`. | Revoke what the public roles never need: [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges). | | `truncate` | PostgreSQL does not apply policies to `truncate`: a role that holds the privilege empties the table, whatever the policies say. The REST API never sends `truncate`; SQL run as a public role (a function you expose, for example) can. | Revoke `truncate` from `aura_anon` and `aura_authenticated`. | | Views with `security_invoker = false` | A view created with this option reads with its owner's rights: the anon key reads every row through it, and writes through it when it is updatable. | Never set it; Aurabase sets `security_invoker = true` on views without the option. See [Views](https://aurabase.dev/en/docs/database/views#invoker). | | Materialized views | PostgreSQL has no RLS on them: the public roles read every stored row. | Revoke them from the public roles. See [Views](https://aurabase.dev/en/docs/database/views#materialized). | | Partitions | A partition created in SQL has RLS off; reading the parent applies the parent's policies, but SQL that names the partition reads it unfiltered. | Turn RLS on for each partition. See [Partitions](https://aurabase.dev/en/docs/database/partitions#rls). | | Objects created over the direct connection | A table created after switching to the administrator role over `psql` or an ORM gets the broad privileges and no RLS: the anon key reads it. | Enable RLS in the same migration. See [Connect](https://aurabase.dev/en/docs/database/connect#private-tables). | | Tables created by a public role | The public roles may create tables in your schema; such a table belongs to them and has no RLS. | Revoke `create` on your schema from them ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)). | | Realtime and hidden columns | A table enabled for `postgres_changes` sends whole rows to every subscriber allowed to see the row: column privileges do not apply to the events. | Do not enable Realtime on a table with hidden columns. See [Column-level security](https://aurabase.dev/en/docs/database/column-security#realtime). | | Platform tables | A few tables of the Auth and Storage schemas of your project have no RLS and are readable by the public roles; the REST API does not serve them, but a view in your schema would. | Keep views and functions on your own tables. See [Project isolation](https://aurabase.dev/en/docs/database/project-isolation). | | Roles that bypass RLS | The `service_role` key, `aura db raw` without `--as`, and the password of the direct connection act as administrator: they read every row, including Auth data. | Keep them on servers; never in a browser or a mobile app. See [API keys](https://aurabase.dev/en/docs/database/api-keys). | ## Checklist before you ship 1. `aura db table list`: every table you expose shows `[RLS]`. Partitions are listed too; turn RLS on for each. 2. Every table the application reads has a policy per role and command it needs, written with `to aura_authenticated` or `to aura_anon` and `auth.uid()`, never with `auth.role()`. 3. Every view has `security_invoker = true`; no view was created with `security_invoker = false`. 4. Materialized views are revoked from `aura_anon` and `aura_authenticated`. 5. `truncate`, `references`, `trigger` and `maintain` are revoked from the public roles on your tables, `create` on your schema, and the defaults changed for future tables ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)). Re-check after platform upgrades. 6. Functions are granted only to the roles that call them; a `security definer` function filters on `auth.uid()` itself ([Database functions](https://aurabase.dev/en/docs/database/functions#definer)). 7. The `service_role` key and the direct-connection password stay on servers ([API keys](https://aurabase.dev/en/docs/database/api-keys)). 8. A test proves that a second user and a visitor cannot read or change the first user's rows, and it runs in CI ([Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls)). 9. SQL sent through `aura db raw`, `db.sql()` or the SQL editor uses `set local`, never `set` alone: a setting without `local` is accepted, but it can outlive the request on the pooled connection and apply to later requests of the project ([Run SQL](https://aurabase.dev/en/docs/database/run-sql#refused)). The security advisor (`GET /v1/db/{project_id}/schema/advisors/security` with the `service_role` key) flags tables and partitions with RLS off and policies whose `using` is `true`. It does not inspect privileges, views or materialized views. ## Policies and query speed A policy is added to every query on the table, so it costs what a `where` clause costs. Index the columns a policy compares, as the example schema does with `todos_user_id_idx`; PostgreSQL then uses the index for the policy: ```bash verify="explain" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "explain select * from todos" ``` ```text expect="explain" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). QUERY PLAN ────────────────────────────────────────────────────────────────────────────── Bitmap Heap Scan on todos (cost=4.43..13.89 rows=4 width=65) Filter: (auth.uid() = user_id) -> Bitmap Index Scan on todos_user_id_idx (cost=0.00..4.43 rows=4 width=0) Index Cond: (user_id = auth.uid()) ℹ 4 row(s). ``` Also filter in the query itself (`.eq('user_id', userId)`): the planner then knows the condition before it reads the policy. A policy that queries another table for each row (a membership check) is the usual slow case; put that check in a `security definer` function, as [Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy#membership) does. Aurabase did not benchmark other rewrites of policies for this page. ## Result The table has RLS on, one owner policy for signed-in users, and no policy for visitors: ```bash verify="result" needs="policy" aura db policy list --table sec_rls_notes --json ``` ```text expect="result" [ { "check_expr": "(auth.uid() = user_id)", "command": "ALL", "policy_name": "sec_rls_notes_owner", "roles": [ "aura_authenticated" ], "table_name": "sec_rls_notes", "using_expr": "(auth.uid() = user_id)" } ] ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `data: []` with a `meta.hint` starting `0 rows returned.` | RLS is on and no `select` policy lets this role read these rows; or the table is empty. | Add a policy for the role ([Policies](https://aurabase.dev/en/docs/database/policies)); check with `aura db raw "select …" --as …`. | | `403 INSUFFICIENT_PRIVILEGE`, `new row violates row-level security policy for table "…"` | The row written does not satisfy `with check`, often a `user_id` that is not the caller's, or no insert policy for the role. | Write rows the policy accepts; use `default auth.uid()` for the owner column. | | An update returns `[]` and `meta.hint` starting `No row was updated.` | No `update` policy reaches these rows for the role, or the filter matches nothing. | Add an `update` policy with `using`; check the filter. | | A policy works with `aura db raw --as` but not from the SDK, or the reverse | It compares `auth.role()`, which returns different names on the two paths. | Replace it by `to aura_authenticated` or `to aura_anon`. | | Every signed-in user sees nothing | `auth.uid()` is `NULL`: the request carries no user token (anon key alone, or a key of scope `authenticated`). | Sign the user in with the SDK, which sends its token. | | `relation "auth.users" does not exist` | The Auth users are not in a schema named `auth`. | Store the user id in a `uuid` column ([Point rows at users](#users)). | | `infinite recursion detected in policy for relation "…"` | A policy queries its own table. | Move the check into a `security definer` function ([Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy) shows the error). | | `permission denied for table …` | The role lacks the privilege, before any policy is read: a revoked privilege or a table created over the direct connection with the project's own login role. | Grant the privilege ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)). | ## Clean up ```sql verify="clean-up" needs="create" drop function if exists sec_rls_whoami(); drop table sec_rls_notes; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Policies](https://aurabase.dev/en/docs/database/policies): Create, change and drop policies in SQL, with the CLI or over HTTP. - [Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy): Try reads and writes as anon or as a user, rolled back. - [Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls): A script that fails when a user can read someone else's rows. - [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges): The privileges behind the policies, and how to reduce them. - [Column-level security](https://aurabase.dev/en/docs/database/column-security): Hide columns that every reader of a row must not see. - [Public read access](https://aurabase.dev/en/docs/database/public-read): Open a table, or some of its rows, to the anon key. - [API keys](https://aurabase.dev/en/docs/database/api-keys): Which key bypasses RLS and where each one may live. - [Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy): Policies for organizations and tenants. --- ### Policies: create, change and drop Source: https://aurabase.dev/en/docs/database/policies.md # Policies: create, change and drop > Create the policies that decide which rows each role reads and writes, change their expressions without a gap, drop them, and pick the door that supports what your policy needs. A policy is a rule attached to one table: for one command (or all), for some roles, it says which rows are visible (`using`) and which new rows are acceptable (`with check`). This page writes the policies of a small articles table: everyone reads published articles, signed-in users manage their own, and anonymous sign-ins cannot write. [Row-level security](https://aurabase.dev/en/docs/database/rls) explains what policies do and do not protect. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the table `sec_pol_articles` and its policies, then remove them. All the doors below require the `service_role` key (or a Studio session); the anon key gets `403 FORBIDDEN`, `DDL operation is reserved to the service_role role`. ```bash verify="table" aura db raw "create table sec_pol_articles ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), title text not null, published boolean not null default false)" aura db raw "insert into sec_pol_articles (user_id, title, published) values ('00000000-0000-4000-8000-0000000000a1', 'Alice, published', true), ('00000000-0000-4000-8000-0000000000a1', 'Alice, draft', false), ('00000000-0000-4000-8000-0000000000b2', 'Bob, draft', false)" ``` ```text expect="table" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## Where to write a policy | | SQL (`aura db raw`, SQL editor, migrations) | `aura db policy` | HTTP `/v1/db/{project_id}/policies` | Studio, **RLS policies** tab | | --- | --- | --- | --- | --- | | Target roles (`to …`) | Any role | None: the policy applies to every role (`public`) | `target_roles`: `anon`, `authenticated`, `service_role` or their `aura_` names | Check boxes: `authenticated`, `anon`, `service_role`; none checked means every role | | Subqueries (`exists (select …)`) | Yes | Refused | Refused | Refused (it calls the HTTP API) | | `as restrictive` | Yes | No | No | No | | Change expressions in place | `alter policy` | `aura db policy update` | `PUT …/policies/{name}/{table}` | No (drop and create) | Use SQL in migrations: it is the only door that has every option, and the file replays the same way on every environment. The CLI and the HTTP API suit quick rules that need no subquery; call a function for anything that reads another table (see [Common policies](#patterns)). ## Parts of a policy ```text filename="create policy" create policy on
[as permissive | as restrictive] -- permissive by default for all | select | insert | update | delete to , … -- every role (public) if omitted using () with check () ``` Which expression each command evaluates: | Command | `using` | `with check` | | --- | --- | --- | | `select` | Rows the role reads | Not allowed | | `insert` | Not allowed | Rows the role may insert | | `update` | Rows the role may update (the row before the change) | The row after the change; `using` is reused when omitted | | `delete` | Rows the role may delete | Not allowed | | `all` | All of the above | Inserts and updates; `using` is reused when omitted | A policy only names a role; the role still needs the privilege on the table. Tables created through Aurabase grant all table privileges to `aura_anon` and `aura_authenticated`, so in practice the policies decide. See [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges). ## With the CLI `aura db policy add
` creates a policy, with `--using-expr` and `--check-expr`. It has no option for roles: the policy applies to every role. That fits a public read rule: ```bash verify="cli-add" needs="table" aura db policy add sec_pol_articles sec_pol_articles_published SELECT --using-expr "published" aura db policy list --table sec_pol_articles --json ``` ```text expect="cli-add" ✔ Policy 'sec_pol_articles_published' created on 'sec_pol_articles' (SELECT). • USING: published [ { "check_expr": null, "command": "SELECT", "policy_name": "sec_pol_articles_published", "roles": [ "public" ], "table_name": "sec_pol_articles", "using_expr": "published" } ] ``` `roles: ["public"]` means every role, anon included. The table output of `aura db policy list` does not show the roles; use `--json` to see them. `--table` filters one table; without it, the list hides the internal Storage policies, which `--all` adds. ## Over HTTP `POST /v1/db/{project_id}/policies` takes the table, the name, the command, the two expressions and the roles. This policy lets signed-in users manage their own articles: ```bash verify="http-add" needs="table" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/policies" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_pol_articles", "name": "sec_pol_articles_owner", "command": "ALL", "using_expr": "auth.uid() = user_id", "check_expr": "auth.uid() = user_id", "target_roles": ["authenticated"]}' echo curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/policies" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data for (const p of d.filter((p) => p.table_name === "sec_pol_articles")) console.log(p.policy_name, p.command, p.roles.join(","))' ``` ```text expect="http-add" {"data":null,"meta":null} sec_pol_articles_owner ALL aura_authenticated sec_pol_articles_published SELECT public ``` | Field | Required | Values | | --- | --- | --- | | `table` | Yes | A table of your schema; the five Storage tables (`storage_buckets`, `storage_objects`…) target the Storage schema of the project | | `name` | Yes | A plain identifier: letters, digits and `_` | | `command` | Yes | `SELECT`, `INSERT`, `UPDATE`, `DELETE` or `ALL`, any case | | `using_expr`, `check_expr` | No | An SQL expression; an empty string is ignored | | `target_roles` | No | `anon`, `authenticated`, `service_role`, `aura_anon`, `aura_authenticated`, `aura_service_role`; the short names are translated to the `aura_` roles. Omitted or empty: every role. | The CLI, the HTTP API and the Studio check each expression before running it, and refuse: - `;`, comments (`--`, `/*`) and dollar quoting (`$$`, `$tag$`); - the words `select`, `insert`, `update`, `delete`, `with`, `create`, `drop`, `alter`, `truncate`, `grant`, `revoke`, `execute`, `copy`, `import`, `export` and `load`, so no subquery; - a list of functions: file and large-object access, `dblink`, `pg_sleep`, `set_config`, `pg_notify`, the `*_to_xml` family, and string builders such as `format`, `concat`, `replace` or `encode`; - any qualified name other than `auth.`, so no `public.my_function()` and no `other_schema.table`. A policy that must read another table calls a function of your schema instead, unqualified: `is_member(org_id)`. ## In SQL SQL has no such checks beyond those of `aura db raw` and accepts every option. A restrictive policy is combined with `and` with the others: this one keeps users who signed in anonymously from writing, whatever the other policies allow: ```sql verify="sql-restrictive" needs="table" create policy sec_pol_articles_no_anonymous_writes on sec_pol_articles as restrictive for insert to aura_authenticated with check (not auth.is_anonymous()); ``` ```text expect="sql-restrictive" ℹ No results (0 rows). ``` ## How policies combine For a given table, command and role, PostgreSQL 18 combines the policies this way: at least one permissive policy must let the row through (they are joined with `or`), and every restrictive policy must also let it through (joined with `and`). With no permissive policy, nothing is allowed. Policies for other roles or other commands do not apply. The articles table now has a public `select` policy and an owner `all` policy for signed-in users. Alice reads the published article of everyone, plus her own draft; a visitor reads published articles only: ```bash verify="combine" needs="cli-add,http-add" aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select title from sec_pol_articles order by title" aura db raw --as anon "select title from sec_pol_articles order by title" ``` ```text expect="combine" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). title ──────────────── Alice, draft Alice, published ℹ 2 row(s). ℹ Executed as anon. title ──────────────── Alice, published ℹ 1 row(s). ``` Bob's draft stays hidden from both: no permissive policy matches it. ## Common policies | Need | Policy | | --- | --- | | Each user its own rows | `for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)` | | Everyone reads some rows | `for select to aura_anon, aura_authenticated using (published)`. See [Public read access](https://aurabase.dev/en/docs/database/public-read). | | Signed-in users read everything | `for select to aura_authenticated using (true)` | | Members of an organization | `for select to aura_authenticated using (is_member(org_id))`, with `is_member` a `security definer` function that reads the membership table. See [Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy#membership). | | One tenant per user | `using (tenant_id = auth.tenant())`, the tenant set in `app_metadata` from a server. See [Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy#claim). | | A role you assign | `using (auth.has_role('editor'))`, the roles set in `app_metadata.roles` from a server | | Block a kind of user everywhere | A restrictive policy, as above | Avoid `auth.role()` in expressions: it returns `aura_authenticated` through the SDK and `authenticated` through `aura db raw --as` and the simulator, so the same policy behaves differently depending on who calls. The `to` clause is the reliable way to target a role. ## Change and drop a policy `aura db policy update` runs `alter policy`: the table keeps its rule while the expression changes, unlike a drop followed by a create. Omitted clauses stay as they are. ```bash verify="change" needs="cli-add" aura db policy update sec_pol_articles sec_pol_articles_published --using-expr "published and title <> ''" aura db policy delete sec_pol_articles sec_pol_articles_no_anonymous_writes --force ``` ```text expect="change" ✔ Policy 'sec_pol_articles_published' updated on 'sec_pol_articles'. • USING: published and title <> '' ℹ Omitted clauses are left AS IS (ALTER POLICY only rewrites what is provided). ✔ Policy 'sec_pol_articles_no_anonymous_writes' deleted from 'sec_pol_articles'. ``` Over HTTP, `PUT /v1/db/{project_id}/policies/{policy_name}/{table}` takes `using_expr` and `check_expr` (at least one), and `DELETE` on the same path drops the policy. The drop uses `if exists`: an unknown name returns `200` and changes nothing, so check the name, then list the policies: ```bash verify="http-change" needs="http-add" curl -s -X PUT "$AURABASE_URL/v1/db/$PROJECT_ID/policies/sec_pol_articles_owner/sec_pol_articles" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"check_expr": "auth.uid() = user_id and title <> '"''"'"}' echo curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/policies/sec_pol_no_such_policy/sec_pol_articles" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" echo ``` ```text expect="http-change" {"data":null,"meta":null} {"data":null,"meta":null} ``` In SQL: `alter policy … using (…)` and `drop policy … on …`. Without `--force`, `aura db policy delete` asks for confirmation and stops when it has no terminal. ## Result ```bash verify="result" needs="change" aura db policy list --table sec_pol_articles ``` ```text expect="result" » RLS Policies Table Policy Cmd USING Expression ------------------------------------------------------------------------------------- sec_pol_articles sec_pol_articles_owner ALL (auth.uid() = user_id) sec_pol_articles sec_pol_articles_published SELECT (published AND (title <> ''::text)) ℹ 2 policy(ies). ``` PostgreSQL stores the expressions in its own normalized form, which is what the list shows. ## Common errors The refusals of the CLI and the HTTP API, measured: ```bash verify="refused" needs="cli-add" aura db policy add sec_pol_articles sec_pol_x SELECT --using-expr "user_id in (select user_id from org_members)" || true aura db policy add sec_pol_articles sec_pol_articles_published SELECT --using-expr "true" || true aura db policy add sec_pol_articles sec_pol_x READ --using-expr "true" || true ``` ```text expect="refused" Error: [400] BAD_REQUEST: Invalid request: Invalid USING expression: the SQL keyword 'SELECT' is not allowed in policy expressions — subqueries are not permitted Error: [400] BAD_REQUEST: Invalid request: policy "sec_pol_articles_published" for table "sec_pol_articles" already exists Error: Invalid command 'READ'. Valid: SELECT, INSERT, UPDATE, DELETE, ALL ``` | Message | Cause | Fix | | --- | --- | --- | | `Invalid USING expression: the SQL keyword 'SELECT' is not allowed in policy expressions — subqueries are not permitted` | A subquery through the CLI, the HTTP API or the Studio. | Call a function, or create the policy in SQL. | | `Invalid USING expression: cross-schema references are not allowed ('…') — only the 'auth.' prefix is permitted` | A qualified name such as `public.f()`. | Drop the schema prefix. | | `policy "…" for table "…" already exists` | The name is taken on that table. | `update` it, or choose another name. | | `relation "project_….…" does not exist` | Unknown table. | Check the name with `aura db table list`. | | `Role 'admin' non autorise. Valeurs acceptees : …` | `target_roles` outside the six accepted names (the message is partly in French). | Use `anon`, `authenticated` or `service_role`. | | `At least one expression (USING or WITH CHECK) is required` | `PUT` without expression. | Send `using_expr` or `check_expr`. | | `policy "…" for table "…" does not exist` | `PUT` on an unknown policy. | List the policies; names are case-sensitive. | | `only WITH CHECK expression allowed for INSERT` | `using` on an insert policy (PostgreSQL). | Use `with check`. | | `infinite recursion detected in policy for relation "…"` | A policy that queries its own table, written in SQL. | Move the check into a `security definer` function. | ## Clean up Dropping the table drops its policies: ```sql verify="clean-up" needs="table" drop table sec_pol_articles; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Row-level security](https://aurabase.dev/en/docs/database/rls): What policies protect, and what they do not. - [Policy templates](https://aurabase.dev/en/docs/database/policy-templates): The ready-made policies of the API and the Studio. - [Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy): Check a policy as anon or as a user before shipping it. - [Database functions](https://aurabase.dev/en/docs/database/functions): Security definer functions for membership checks. --- ### Policy templates Source: https://aurabase.dev/en/docs/database/policy-templates.md # Policy templates > See exactly which policies the template catalog and the Studio offer, apply one through the policies API, and know which templates need a role or a different expression to do what their name says. A policy template is a prepared set of fields for the policies API: a command, the target roles and the `using` and `with check` expressions. Aurabase has two sets: the catalog served by `GET /v1/db/policy-templates`, and the list built into the **RLS policies** tab of the Studio. Neither creates anything by itself; applying one creates an ordinary policy, which you can change or drop like any other ([Policies](https://aurabase.dev/en/docs/database/policies)). ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the table `sec_tpl_notes`, then remove it: ```bash verify="table" aura db raw "create table sec_tpl_notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null)" aura db raw "insert into sec_tpl_notes (user_id, body) values ('00000000-0000-4000-8000-0000000000a1', 'Alice note'), ('00000000-0000-4000-8000-0000000000b2', 'Bob note')" ``` ```text expect="table" ℹ No results (0 rows). ℹ No results (0 rows). ``` ## The template catalog The catalog is static: it does not depend on a project, so its path has no project id, and it is served on the management API only, with the session token of a console account (`Authorization: Bearer …`), not with a project key. Request (excerpt, not replayed by the documentation checks: it needs a console session): ```bash curl -s "$AURA_GATEWAY_URL/v1/db/policy-templates" -H "Authorization: Bearer $AURA_CONSOLE_TOKEN" ``` Response captured on a local stack (the `name` and `description` fields are in French in this version): ```json verify="catalog" {"data":[ {"id":"public_read","name":"Lecture publique","description":"Tous les utilisateurs (anon + authenticated) peuvent lire","command":"SELECT","using_expr":"true","check_expr":null,"target_roles":[]}, {"id":"auth_read","name":"Lecture authentifiee","description":"Seuls les utilisateurs connectes peuvent lire","command":"SELECT","using_expr":"true","check_expr":null,"target_roles":["authenticated"]}, {"id":"owner_all","name":"Acces proprietaire (CRUD complet)","description":"Chaque utilisateur ne voit et modifie que ses propres lignes","command":"ALL","using_expr":"auth.uid() = user_id","check_expr":"auth.uid() = user_id","target_roles":[]}, {"id":"owner_read","name":"Lecture proprietaire","description":"Chaque utilisateur ne voit que ses propres lignes","command":"SELECT","using_expr":"auth.uid() = user_id","check_expr":null,"target_roles":[]}, {"id":"owner_insert","name":"Insertion authentifiee","description":"Les utilisateurs connectes peuvent inserer leurs propres lignes","command":"INSERT","using_expr":null,"check_expr":"auth.uid() = user_id","target_roles":[]}, {"id":"admin_all","name":"Acces admin complet","description":"Seuls les admins ont acces total","command":"ALL","using_expr":"auth.role() = 'admin'","check_expr":"auth.role() = 'admin'","target_roles":[]} ],"meta":null} ``` Sent to a project URL with a project key, the same path is read as a table named `policy-templates` and answers `404 TABLE_NOT_FOUND`. ## What each template creates An empty `target_roles` creates the policy for every role (`public`), anon included. | `id` | SQL created on `
` | What it really does | | --- | --- | --- | | `public_read` | `for select using (true)` | Every role reads every row, the anon key included. See [Public read access](https://aurabase.dev/en/docs/database/public-read). | | `auth_read` | `for select to aura_authenticated using (true)` | Every signed-in user reads every row; visitors read none. | | `owner_all` | `for all using (auth.uid() = user_id) with check (auth.uid() = user_id)` | Each signed-in user reads and writes its own rows. Visitors match nothing, since `auth.uid()` is `NULL` for them. | | `owner_read` | `for select using (auth.uid() = user_id)` | Each signed-in user reads its own rows. | | `owner_insert` | `for insert with check (auth.uid() = user_id)` | Each signed-in user inserts rows in its own name. | | `admin_all` | `for all using (auth.role() = 'admin') with check (auth.role() = 'admin')` | Nobody: `auth.role()` returns `aura_authenticated` or `aura_anon` through the SDK and `authenticated` or `anon` through SQL, never `admin`. Only the `service_role` key, which bypasses policies, reaches the rows. | The `owner_*` templates need a `uuid` column named `user_id`; on another column name, edit the expressions before applying. ## Apply a template Copy the fields of the template into `POST /v1/db/{project_id}/policies`, with a name of your choice. Adding `target_roles: ["authenticated"]` to `owner_all` keeps the anon key out of the policy explicitly: ```bash verify="apply" needs="table" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/policies" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_tpl_notes", "name": "sec_tpl_notes_owner_all", "command": "ALL", "using_expr": "auth.uid() = user_id", "check_expr": "auth.uid() = user_id", "target_roles": ["authenticated"]}' echo aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select body from sec_tpl_notes" ``` ```text expect="apply" {"data":null,"meta":null} ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). body ────────── Alice note ℹ 1 row(s). ``` The same fields work with `aura db policy add
--using-expr … --check-expr …`, which has no option for roles (the policy then applies to every role). ## Replace admin_all Applied as is, `admin_all` lets nobody in, even a user whose token says it is an administrator. Give administrators a role in `app_metadata.roles` from a server, and test it with `auth.has_role()`. The simulator compares both, for a user that carries the role: ```bash verify="admin" needs="table" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/policies" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_tpl_notes", "name": "sec_tpl_notes_admin_all", "command": "ALL", "using_expr": "auth.role() = '"'admin'"'", "check_expr": "auth.role() = '"'admin'"'"}' echo simulate() { curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_tpl_notes", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000c3", "claims": {"app_metadata": {"roles": ["admin"]}}}' \ | node -e 'console.log("admin user reads", JSON.parse(require("fs").readFileSync(0, "utf8")).data.row_count, "notes")' } simulate aura db policy update sec_tpl_notes sec_tpl_notes_admin_all --using-expr "auth.has_role('admin')" --check-expr "auth.has_role('admin')" simulate ``` ```text expect="admin" {"data":null,"meta":null} admin user reads 0 notes ✔ Policy 'sec_tpl_notes_admin_all' updated on 'sec_tpl_notes'. • USING: auth.has_role('admin') • WITH CHECK: auth.has_role('admin') admin user reads 2 notes ``` `app_metadata` is written by your server, never by the user, so a user cannot give itself the role. `user_metadata`, which the user can change, must never grant access. ## Templates of the Studio The **RLS policies** tab of a table (Database › a table) has its own list, built into the page; it does not read the catalog. Choosing one fills the form, which then calls the same policies API: | Studio template | Fields filled | Result | | --- | --- | --- | | Strict owner | `ALL`, `auth.uid() = user_id` for both expressions | Same as `owner_all`. Check **authenticated** in Target roles to keep visitors out explicitly. | | Public read for all | `SELECT`, `true` | Same as `public_read`. | | Team members | `SELECT`, `team_id IN (SELECT get_user_team_ids(auth.uid()))` | Refused: the policies API does not accept subqueries. Write it in SQL, with a function you created. | | Team administrators only | `ALL`, `is_team_admin(team_id, auth.uid())` | Refused unless your schema has an `is_team_admin(…)` function: neither function is provided. | The two team templates show a pattern, not a ready policy: create the `security definer` function first ([Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy#membership)), then a policy that calls it without a subquery (`using (is_member(org_id))`). ## Result ```bash verify="result" needs="apply,admin" aura db policy list --table sec_tpl_notes --json | node -e 'for (const p of JSON.parse(require("fs").readFileSync(0, "utf8"))) console.log(p.policy_name, p.roles.join(","), p.using_expr)' ``` ```text expect="result" sec_tpl_notes_admin_all public auth.has_role('admin'::text) sec_tpl_notes_owner_all aura_authenticated (auth.uid() = user_id) ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `404 TABLE_NOT_FOUND`, `Could not find the table 'policy-templates' …` | The catalog was requested on a project URL with a project key. | Request it on the management API with a console session, or use the table on this page. | | `401 UNAUTHORIZED`, `A console token is required (Authorization header or token query parameter)` | No console session on the management API. | Sign in with `aura login` or the Studio. | | `the SQL keyword 'SELECT' is not allowed in policy expressions — subqueries are not permitted` | The Team members template of the Studio. | Create the policy in SQL, or call a function without `select`. | | `function is_team_admin(integer, uuid) does not exist` | The Team administrators template, without the function. | Create the function first. | | Every user sees nothing after `admin_all` | `auth.role()` never equals `admin`. | Use `auth.has_role('admin')` ([Replace admin_all](#admin)). | | `policy "…" for table "…" already exists` | A template applied twice with the same name. | Choose another name, or update the policy. | ## Clean up ```sql verify="clean-up" needs="table" drop table sec_tpl_notes; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Policies](https://aurabase.dev/en/docs/database/policies): Create, change and drop policies by any door. - [Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy): Check a template on your table before relying on it. - [Row-level security](https://aurabase.dev/en/docs/database/rls): What policies protect, and what they do not. - [Public read access](https://aurabase.dev/en/docs/database/public-read): When a public_read policy is the right choice. --- ### Simulate a policy Source: https://aurabase.dev/en/docs/database/simulate-policy.md # Simulate a policy > Ask PostgreSQL what a visitor or a given user can read, insert, update or delete in a table, without changing any row, and use the answer to find the policy that hides a row or refuses a write. `POST /v1/db/{project_id}/rls/simulate` runs one operation on one table as the role and user you name, inside a transaction that is always rolled back. The answer says whether rows came back, how many, a sample of them, and the PostgreSQL error when the operation failed. It requires the `service_role` key. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the tables `sec_sim_notes` and `sec_sim_members` and the function `sec_sim_my_teams`, then remove them: ```bash verify="setup" aura db raw "create table sec_sim_notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null)" aura db raw "create policy sec_sim_notes_owner on sec_sim_notes for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)" aura db raw "insert into sec_sim_notes (user_id, body) values ('00000000-0000-4000-8000-0000000000a1', 'Alice note'), ('00000000-0000-4000-8000-0000000000b2', 'Bob note')" ``` ```text expect="setup" ℹ No results (0 rows). ℹ No results (0 rows). ℹ No results (0 rows). ``` ## What the simulator runs In one transaction, rolled back at the end whatever happens: 1. It sets the claims of a token: `role` (`anon` or `authenticated`), `sub` from `user_id`, `email`, and the extra `claims` you send. 2. It switches to `aura_anon` or `aura_authenticated`. For `service_role`, it stays on the administrator role of the project, which bypasses row level security. 3. It runs the operation on the table of your schema: | `operation` | SQL run | | --- | --- | | `SELECT` | `select * from
limit ` | | `INSERT` | `insert into
() values () returning *` | | `UPDATE` | `update
set returning *`, on every row the role can reach (no filter) | | `DELETE` | `delete from
returning *`, on every row the role can reach (no filter) | Because it is real SQL in PostgreSQL, the policies, privileges, constraints, defaults and triggers of the table all apply, exactly as for a request of that role. Two things are not undone by the rollback: values taken from an identity column or a sequence (an `INSERT` simulation leaves a gap in the ids), and work done outside the database. ## Request | Field | Required | Values | | --- | --- | --- | | `table` | Yes | A table of your schema, plain identifier | | `operation` | Yes | `SELECT`, `INSERT`, `UPDATE` or `DELETE`, any case. `ALL` is refused. | | `role` | Yes | `anon`, `authenticated`, `service_role`, or their `aura_` names | | `user_id` | No | The `uuid` returned by `auth.uid()` | | `email` | No | The value of `auth.email()` | | `claims` | No | A JSON object merged into the claims, for `auth.jwt()`, `auth.tenant()`, `auth.has_role()` (`{"app_metadata": {"roles": ["editor"]}}`). Its `role` is always replaced by the role above; its `sub` and `email` are replaced only when `user_id` or `email` is sent and not empty. | | `payload` | `INSERT`, `UPDATE` | A non-empty JSON object, column → value. Strings, numbers, booleans and `null` are sent as SQL literals; arrays and objects as `jsonb`. | | `limit` | No | Rows of a `SELECT`, from 1 to 50; 25 by default | ## Response Always `200` once the request is valid, with these fields in `data`: | Field | Meaning | | --- | --- | | `allowed` | `SELECT`: at least one row came back, or the table has row level security off. Other operations: at least one row was written. | | `rls_enabled` | Row level security is on for the table. | | `row_count` | Rows returned by the operation (at most `limit` for a `SELECT`). | | `sample_rows` | The rows themselves, up to `limit`. | | `error_code` | `null`, or `RLS_DENIED` (a policy refused a written row, or a privilege is missing), `RECURSIVE_POLICY` (a policy queries its own table), `SQL_ERROR` (anything else: unknown column, constraint, unknown table). | | `error_message` | The PostgreSQL message, prefixed `Invalid request: `. | | `evaluated_by` | Always `postgresql`. | | `execution_time_ms` | Time spent, in milliseconds. | `allowed: false` with no error means "no row": a `SELECT` on an empty table, or on rows no policy shows, gives the same answer. Look at `row_count` against what you expected, not at `allowed` alone. ## Simulate a read Alice reads her own note; a visitor reads none. The command prints the fields that matter and the bodies of the rows: ```bash verify="read" needs="setup" for who in '"role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"' '"role": "anon"'; do curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d "{\"table\": \"sec_sim_notes\", \"operation\": \"SELECT\", $who}" \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data console.log(d.allowed, d.rls_enabled, d.row_count, d.error_code, d.sample_rows.map((r) => r.body))' done ``` ```text expect="read" true true 1 null [ 'Alice note' ] false true 0 null [] ``` ## Simulate writes Bob tries to insert a note in Alice's name, then in his own, then deletes what he can reach; a visitor tries to update. Nothing is kept: ```bash verify="write" needs="setup" simulate() { curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d "$1" \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data console.log(d.allowed, d.row_count, d.error_code, d.error_message ?? "")' } BOB=00000000-0000-4000-8000-0000000000b2 simulate '{"table": "sec_sim_notes", "operation": "INSERT", "role": "authenticated", "user_id": "'$BOB'", "payload": {"user_id": "00000000-0000-4000-8000-0000000000a1", "body": "Not mine"}}' simulate '{"table": "sec_sim_notes", "operation": "INSERT", "role": "authenticated", "user_id": "'$BOB'", "payload": {"body": "Mine"}}' simulate '{"table": "sec_sim_notes", "operation": "DELETE", "role": "authenticated", "user_id": "'$BOB'"}' simulate '{"table": "sec_sim_notes", "operation": "UPDATE", "role": "anon", "payload": {"body": "Defaced"}}' aura db raw "select body from sec_sim_notes order by body" ``` ```text expect="write" false 0 RLS_DENIED Invalid request: new row violates row-level security policy for table "sec_sim_notes" true 1 null true 1 null false 0 null body ────────── Alice note Bob note ℹ 2 row(s). ``` The `DELETE` simulation reached one row, Bob's own: a real `delete` sent by Bob without filter would remove exactly that. The table still holds both notes. ## Simulate claims `claims` lets you test policies that read the token: a role set in `app_metadata.roles`, a tenant, an email. Add a policy that lets auditors read every note, then compare Bob with and without the role: ```bash verify="claims" needs="setup" aura db raw "create policy sec_sim_notes_auditors on sec_sim_notes for select to aura_authenticated using (auth.has_role('auditor'))" for claims in '{}' '{"app_metadata": {"roles": ["auditor"]}}'; do curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_sim_notes", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000b2", "claims": '"$claims"'}' \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.row_count)' done ``` ```text expect="claims" ℹ No results (0 rows). 1 2 ``` The simulator sets the claim `role` to `anon` or `authenticated`, as `aura db raw --as` does, while the SDK and the REST API see `aura_anon` and `aura_authenticated` in `auth.role()`. A policy that compares `auth.role()` is therefore not simulated faithfully; target roles with `to …` instead. ## Find a recursive policy A policy that reads its own table to decide (here: "members see the rows of their teams") makes PostgreSQL loop. The simulator names the problem: ```bash verify="recursive" needs="setup" aura db raw "create table sec_sim_members (team_id int not null, user_id uuid not null, primary key (team_id, user_id))" aura db raw "create policy sec_sim_members_team on sec_sim_members for select to aura_authenticated using (team_id in (select m.team_id from sec_sim_members m where m.user_id = auth.uid()))" aura db raw "insert into sec_sim_members values (1, '00000000-0000-4000-8000-0000000000a1'), (1, '00000000-0000-4000-8000-0000000000b2')" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_sim_members", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"}' \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.error_code, d.error_message)' ``` ```text expect="recursive" ℹ No results (0 rows). ℹ No results (0 rows). ℹ No results (0 rows). RECURSIVE_POLICY Invalid request: infinite recursion detected in policy for relation "sec_sim_members" ``` Move the lookup into a `security definer` function, which reads the table with its owner's rights and therefore without going through the policy again, and use it in the policy: ```bash verify="fix" needs="recursive" aura db function create sec_sim_my_teams --language sql --returns 'setof int' \ --body 'select team_id from sec_sim_members where user_id = auth.uid()' \ --security definer --grant-execute-to authenticated aura db raw "drop policy sec_sim_members_team on sec_sim_members; create policy sec_sim_members_team on sec_sim_members for select to aura_authenticated using (team_id in (select sec_sim_my_teams()))" curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \ -d '{"table": "sec_sim_members", "operation": "SELECT", "role": "authenticated", "user_id": "00000000-0000-4000-8000-0000000000a1"}' \ | node -e 'const d = JSON.parse(require("fs").readFileSync(0, "utf8")).data; console.log(d.allowed, d.row_count, d.error_code)' ``` ```text expect="fix" ✔ Function 'sec_sim_my_teams' created (sql → setof int). • EXECUTE granted to: authenticated ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's. ℹ No results (0 rows). true 2 null ``` Alice now sees both members of her team. The function returns only the teams of the caller and is granted to signed-in users only. ## In the Studio **Database › a table › RLS simulator** (`//database/sql/table-editor/rls/simulate`) sends the same request. When the server answers, the verdict comes from PostgreSQL; when it does not, the Studio falls back to an estimate computed in the browser and labels it as such: trust only the PostgreSQL verdict. ## Result The simulations changed no row: the table holds the two notes of the setup. ```bash verify="result" needs="write" aura db raw "select count(*) as notes from sec_sim_notes" ``` ```text expect="result" notes ───── 2 ℹ 1 row(s). ``` ## Common errors ```bash verify="refused" needs="setup" for body in '{"table": "sec_sim_notes", "operation": "ALL", "role": "anon"}' \ '{"table": "sec_sim_notes", "operation": "SELECT", "role": "admin"}' \ '{"table": "sec_sim_notes", "operation": "UPDATE", "role": "anon"}' \ '{"table": "sec_sim_notes", "operation": "INSERT", "role": "service_role", "payload": {"owner": "x"}}'; do curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/rls/simulate" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d "$body" \ | node -e 'const r = JSON.parse(require("fs").readFileSync(0, "utf8")); console.log(r.error ? r.error.message : r.data.error_code + " " + r.data.error_message)' done ``` ```text expect="refused" Invalid request: Specify SELECT, INSERT, UPDATE or DELETE to simulate an operation Invalid request: Invalid simulation role: 'admin' Invalid request: A non-empty JSON payload is required to simulate UPDATE SQL_ERROR Invalid request: column "owner" of relation "sec_sim_notes" does not exist (line 4, column 77) ``` | Message | Cause | Fix | | --- | --- | --- | | `Specify SELECT, INSERT, UPDATE or DELETE to simulate an operation` (400) | `operation` is `ALL`. | Simulate each command. | | `Invalid simulation role: '…'` (400) | A role other than anon, authenticated or service_role. | Use one of the three; express other roles as `claims`. | | `A non-empty JSON payload is required to simulate UPDATE` (400) | `INSERT` or `UPDATE` without `payload`. | Send the columns to write. | | `Invalid RLS command: '…'` (400) | Unknown operation. | `SELECT`, `INSERT`, `UPDATE` or `DELETE`. | | `403 FORBIDDEN`, `DDL operation is reserved to the service_role role` | Called with the anon key. | Call it from a server with the `service_role` key. | | `error_code: "SQL_ERROR"`, `relation "project_….…" does not exist` | Unknown table. | Check the name with `aura db table list`. | | `error_code: "RLS_DENIED"`, `permission denied for table …` | A privilege is missing, which is not a policy. | Grant it ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)). | | `allowed: false`, `row_count: 0`, no error | No row came back: an empty table, or no policy shows the rows. | Compare with `service_role`, which bypasses the policies. | ## Clean up ```sql verify="clean-up" needs="setup" drop table if exists sec_sim_members; drop function if exists sec_sim_my_teams(); drop table sec_sim_notes; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Row-level security](https://aurabase.dev/en/docs/database/rls): What policies protect, and the empty answers they give. - [Policies](https://aurabase.dev/en/docs/database/policies): Create and change the policies you simulate. - [Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls): Turn these checks into a test that runs on every change. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql#as-role): aura db raw --as, the other way to read as a role. --- ### Test row level security in CI Source: https://aurabase.dev/en/docs/database/test-rls.md # Test row level security in CI > Turn your policies into checks that fail the build when a visitor or another user can read, change or write rows they should not, and know which tool fits which check. Policies are code, and a policy that is too open fails silently: the application keeps working, and shows more than it should. A test that reads and writes as a visitor and as two different users catches that, before deployment and after every schema change. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples test a table `sec_test_notes` with an owner policy, and save the script in `tests/rls.sh`; the [Clean up](#clean-up) block removes both. Run the tests against a project made for it (a preview branch or a test project), never against production data: the checks insert rows. ```bash verify="table" aura db raw "create table sec_test_notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null)" aura db raw "create policy sec_test_notes_owner on sec_test_notes for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id)" aura db raw "insert into sec_test_notes (user_id, body) values ('00000000-0000-4000-8000-0000000000a1', 'Alice note')" ``` ```text expect="table" ℹ No results (0 rows). ℹ No results (0 rows). ℹ No results (0 rows). ``` ## What to prove For each table the application exposes: | Check | Expected | | --- | --- | | A visitor reads | Nothing, or only the public rows | | A user reads | Its own rows, and the shared rows it is entitled to | | A second user reads the first one's rows | Nothing | | A second user updates or deletes the first one's rows | Zero rows changed | | A user inserts a row in someone else's name | Refused | | Row level security | On for every table and partition | | Privileges of the public roles | Only what you decided ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)) | Test with users that differ: a check run only as the owner of the rows proves nothing about the others. ## Three ways to run the checks | Tool | Runs as | Needs | Writes | Fits | | --- | --- | --- | --- | --- | | `aura db raw --as anon` / `--as authenticated --user ` | The public role, with the user id you choose | The `service_role` key and the project URL | Rolled back with `--dry-run` | Most checks: fast, no real user needed | | `POST /v1/db/{project_id}/rls/simulate` | The same | The `service_role` key, `curl` | Always rolled back | Checks from any language; one operation per call ([Simulate a policy](https://aurabase.dev/en/docs/database/simulate-policy)) | | The SDK with a signed-in user | Exactly what the application runs | The anon key, real sign-ups | Real | A final end-to-end check of the real path | `aura db raw --as` and the simulator set `auth.role()` to `anon` or `authenticated`, while the SDK path sees `aura_anon` and `aura_authenticated`. Policies written with `to …` and `auth.uid()` behave the same on all three; a policy that compares `auth.role()` does not, which an SDK test reveals. ## A test script The block below saves a script in `tests/rls.sh` and runs it. `count` compares the result of a query with the expected number, `refused` expects a write to fail; writes run with `--dry-run`, so the test leaves no row behind. Adapt the table names and ids to your schema; the two ids are the demo users of the example schema. ```bash verify="script" needs="table" mkdir -p tests cat > tests/rls.sh <<'SCRIPT' #!/usr/bin/env bash # Row level security checks. Needs AURABASE_SERVICE_ROLE_KEY and a linked project. set -uo pipefail ALICE=00000000-0000-4000-8000-0000000000a1 BOB=00000000-0000-4000-8000-0000000000b2 failed=0 fail() { # a failed check sets the exit code to 1, unless a check could not run (2 is kept) echo "FAIL $1"; [ "$failed" -eq 2 ] || failed=1 } reason() { # the status and code of an error printed by aura, such as "[401] API_KEY_INVALID", or its first line grep -oE '\[[0-9]{3}\] [A-Z_]+' <<< "$1" | head -n 1 | grep . || grep -m 1 -v 'Executed as' <<< "$1" } count() { # count
off`. Keep such columns in a second table, joined by the same id, that is never enabled for Realtime, and enable Realtime on the table of public columns only. The example signs up a user and signs them in at once. A new project requires email confirmation by default, so on your project the sign-in fails until the user confirms the address; the test project of this page has confirmation turned off (`aura auth settings set email_confirmation_required=false`). ## Restrict the columns a user can change The same applies to writes. Here each member may change its own display name, but not its email, and nobody may insert through the API: ```sql verify="write" needs="read" revoke insert, update on sec_col_members from aura_anon, aura_authenticated; grant update (display_name) on sec_col_members to aura_authenticated; create policy sec_col_members_own_update on sec_col_members for update to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id); ``` ```text expect="write" ℹ No results (0 rows). ``` ```bash verify="write-check" needs="write" ALICE=00000000-0000-4000-8000-0000000000a1 aura db raw --as authenticated --user $ALICE "update sec_col_members set display_name = 'Alice M.' where user_id = '$ALICE' returning display_name" aura db raw --as authenticated --user $ALICE "update sec_col_members set email = 'new@example.com' where user_id = '$ALICE'" || true ``` ```text expect="write-check" ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). display_name ──────────── Alice M. ℹ 1 row(s). ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1). Error: [400] BAD_REQUEST: Invalid request: permission denied for table sec_col_members ``` Change protected columns from a server with the `service_role` key, or through a `security definer` function that checks what it writes ([Database functions](https://aurabase.dev/en/docs/database/functions#definer)). ## Check the privileges `has_column_privilege` and `has_table_privilege` answer for any role, and `aura db raw` accepts them: ```bash verify="check" needs="write" aura db raw "select c.col, has_column_privilege('aura_anon', 'sec_col_members', c.col, 'select') as anon_reads, has_column_privilege('aura_authenticated', 'sec_col_members', c.col, 'update') as user_updates from (values ('display_name'), ('email')) c(col)" ``` ```text expect="check" anon_reads │ col │ user_updates ───────────┼──────────────┼───────────── true │ display_name │ true false │ email │ false ℹ 2 row(s). ``` Keep the `revoke` and `grant` statements in a migration or a script that you run again: according to the code of the provisioner, Aurabase re-applies its default grants to your schema when it upgrades the internal schemas of a project, which would grant the table-level privileges again and make hidden columns readable (read in the code, not reproduced for this page). Run this check after each platform upgrade, or in CI ([Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls)). [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges) explains the default grants. ## Other ways to hide columns | Option | Behavior on Aurabase | | --- | --- | | Column privileges | The columns are refused to the role over REST, the SDK, SQL run as that role and views read by that role. Not over Realtime: a table enabled for `postgres_changes` sends whole rows. | | Realtime | Sends every column of a changed row to each subscriber allowed to see the row. Never enable it on a table with hidden columns. | | A view of the allowed columns | Views run with the caller's rights (`security_invoker = true` is set on them), so the caller still needs the privileges on the columns of the table: a view gives a name to the allowed columns but does not replace the privileges. A view with `security_invoker = false` would bypass the policies of the table: never use one for this ([Views](https://aurabase.dev/en/docs/database/views#invoker)). | | A `security definer` function | Returns exactly the columns it selects, for the rows it filters with `auth.uid()`. Suits a computed or partial answer ("my profile", "public card of a member"). | | Two tables | Move private columns to a second table with its own policies, joined by the same id. Often the clearest design for data such as emails or phone numbers. Keep the private table out of Realtime: then its columns never appear in change events, while the public table can stay enabled. | ## Result ```bash verify="result" needs="write-check,realtime" aura db raw "select display_name, email from sec_col_members order by id" ``` ```text expect="result" display_name │ email ─────────────┼────────────────── Alice M. │ alice@example.com Bob │ bob@example.com Carol │ carol@example.com ℹ 3 row(s). ``` The `service_role` key reads both columns, including the row added for the Realtime example; the public roles read the name only, and Alice changed her name but not her email. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` on a read | The request asks for a column the role may not read, often `select=*` or `select()` without arguments. | List the allowed columns. | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` on an update | The update sets a column without `update` privilege for the role. | Send allowed columns only; change the others from a server. | | The hidden column is still readable | The table-level privilege was not revoked first, a platform upgrade granted it again, or the reader receives it in a Realtime `postgres_changes` event, which carries every column. | Revoke at table level, then grant the columns; check with `has_column_privilege`. Turn Realtime off on the table (`aura db table realtime
off`). | | A view of the allowed columns fails with `permission denied` | The view runs with the caller's rights and reads a revoked column. | Select only allowed columns in the view. | ## Clean up ```bash verify="clean-up" needs="table" aura db table realtime sec_col_members off aura db raw "drop table sec_col_members" ``` ```text expect="clean-up" ✔ Realtime disabled on 'sec_col_members'. ℹ No results (0 rows). ``` ## See also - [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges): The default grants and how to reduce them. - [Public read access](https://aurabase.dev/en/docs/database/public-read): Open rows to the anon key. - [Row-level security](https://aurabase.dev/en/docs/database/rls): Which rows each role sees. - [Database functions](https://aurabase.dev/en/docs/database/functions): Security definer functions for partial answers. --- ### Public read access Source: https://aurabase.dev/en/docs/database/public-read.md # Public read access > Open some rows of a table to visitors and to signed-in users without opening writes, check what the anon key can and cannot do afterwards, and understand why the per-table public-read switch only applies to MongoDB projects. On a PostgreSQL project, a table is public when a `select` policy lets the role of the anon key, `aura_anon`, read its rows. There is no separate switch: the policy is the switch, and it can open every row or only some of them. Writes stay closed until another policy opens them. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create the table `sec_pub_articles`, then remove it: ```bash verify="table" aura db raw "create table sec_pub_articles ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), title text not null, published boolean not null default false)" aura db raw "insert into sec_pub_articles (user_id, title, published) values ('00000000-0000-4000-8000-0000000000a1', 'Release notes', true), ('00000000-0000-4000-8000-0000000000a1', 'Unannounced feature', false)" ``` ```text expect="table" ℹ No results (0 rows). ℹ No results (0 rows). ``` Like every table created through Aurabase, it has row level security on and no policy: nobody but the `service_role` key reads it yet. ## Open rows to everyone Name both public roles: the anon key alone is `aura_anon`, but as soon as a user signs in, its requests run as `aura_authenticated`, which a policy for `aura_anon` does not cover. ```sql verify="policy" needs="table" create policy sec_pub_articles_read on sec_pub_articles for select to aura_anon, aura_authenticated using (published); ``` ```text expect="policy" ℹ No results (0 rows). ``` ## Check what the anon key can do The anon key now reads the published article, and only that one; writing is still refused: ```bash verify="check" needs="policy" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/sec_pub_articles?select=title" -H "apikey: $AURABASE_ANON_KEY" echo curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/sec_pub_articles" \ -H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' \ -d '{"user_id": "00000000-0000-4000-8000-0000000000a1", "title": "Spam", "published": true}' \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)' ``` ```text expect="check" {"data":[{"title":"Release notes"}],"meta":{}} INSUFFICIENT_PRIVILEGE new row violates row-level security policy for table "sec_pub_articles" ``` From the SDK, the same read needs no sign-in: ```typescript verify="sdk" needs="policy" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!) const { data, error } = await aura.from('sec_pub_articles').select('title, published') console.log(data, error) ``` ```text expect="sdk" [ { title: 'Release notes', published: true } ] null ``` ## Open a whole table `using (true)` opens every row: ```sql create policy
_read on
for select to aura_anon, aura_authenticated using (true); ``` Do it only for data that is public by nature (a catalog, a list of countries). The security advisor (`GET /v1/db/{project_id}/schema/advisors/security`) reports every policy whose `using` is `true` as a warning, so that an open table is a decision you can find again. A policy that leaves out `to …` applies to every role, which for a `select` policy means the same as naming the two public roles. Do not publish a table through a view created with `security_invoker = false` or through a materialized view: both ignore the policies of the table and show every row ([Views](https://aurabase.dev/en/docs/database/views#invoker)). ## Keep some columns private A policy opens whole rows. If a public row has a column visitors must not read (an email, an internal note), restrict the columns with privileges, not with the policy: [Column-level security](https://aurabase.dev/en/docs/database/column-security). Column privileges do not filter Realtime events: do not enable `postgres_changes` on such a table. ## The public-read endpoint `GET` and `PUT /v1/db/{project_id}/schema/tables/{table}/public-read` exist for MongoDB projects, which have no row level security: there, `PUT` with `{"public_read": true}` lets anyone holding the anon key read the documents of one collection, writes stay limited to the owner of each document, and every change is recorded in an audit log. Collections are private until this call. On a PostgreSQL project, both methods refuse and point to a policy: ```bash verify="switch" needs="table" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sec_pub_articles/public-read" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)' curl -s -X PUT "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sec_pub_articles/public-read" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d '{"public_read": true}' \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)' ``` ```text expect="switch" BAD_REQUEST Invalid request: per-collection public access is not managed by this engine (on PostgreSQL, use an RLS policy) BAD_REQUEST Invalid request: per-collection public access is not managed by this engine (on PostgreSQL, use an RLS policy) ``` Both methods require the `service_role` key (the anon key gets `403 FORBIDDEN`), and only `GET` and `PUT` exist (`PATCH` answers `405`). The CLI has no command for this endpoint. The MongoDB behavior above is described from the code and was not replayed for this page. ## Result ```bash verify="result" needs="policy" aura db raw --as anon "select title from sec_pub_articles" aura db raw "select count(*) as all_rows from sec_pub_articles" ``` ```text expect="result" ℹ Executed as anon. title ───────────── Release notes ℹ 1 row(s). all_rows ──────── 2 ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `data: []` for the anon key, with a `meta.hint` | No `select` policy for `aura_anon`, or no row matches it. | Add the policy above; check the condition (`published`). | | A visitor sees the rows, a signed-in user does not | The policy names `aura_anon` only. | Add `aura_authenticated` to `to …`. | | `403 INSUFFICIENT_PRIVILEGE`, `new row violates row-level security policy …` on a write with the anon key | Expected: a `select` policy opens reads only. | Add an `insert` policy only if visitors must write. | | `400 BAD_REQUEST`, `per-collection public access is not managed by this engine (on PostgreSQL, use an RLS policy)` | The public-read endpoint on a PostgreSQL project. | Write a policy. | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` | The privilege was revoked from the role (or the table was created over the direct connection with the project's login role). | Grant `select` ([Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges)). | ## Clean up ```sql verify="clean-up" needs="table" drop table sec_pub_articles; ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Policies](https://aurabase.dev/en/docs/database/policies): Other policies, for writes and for signed-in users. - [Column-level security](https://aurabase.dev/en/docs/database/column-security): Public rows with private columns. - [Row-level security](https://aurabase.dev/en/docs/database/rls): What policies protect, and what they do not. - [Policy templates](https://aurabase.dev/en/docs/database/policy-templates): The public_read template and what it creates. --- ### API keys Source: https://aurabase.dev/en/docs/database/api-keys.md # API keys > Choose the right key for each place your code runs, create and revoke keys from the CLI or the management API, rotate a leaked key without downtime, and recognize the errors that protect the service_role key. Every call to the data plane of a project (`https://./v1/db/…`, the SDK, the REST API) carries a project key in the `apikey` or `X-API-Key` header. The key tells the gateway which project is called and which PostgreSQL role the request runs as. Keys are created per project, shown once, stored as a SHA-256 hash, and revoked one by one. ## Prerequisites - A linked project: `aura link `, and a console session (`aura login`) of an **owner** or **admin** of the organization: managing keys is refused to other members. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create keys named `sec-keys-…`, then revoke them. They never print a key: the commands pass each new key through `sed` to replace it with `…` on this page; in your terminal, the key is printed in full, once. ## Three scopes | Scope | Prefix | Runs as | `auth.uid()` | Where it may live | | --- | --- | --- | --- | --- | | `anon` | `aura_anon_` | `aura_anon`; `aura_authenticated` when a user token is sent with it | `NULL`, or the signed-in user | Browser, mobile app, anywhere. It reaches the rows that policies open to visitors, plus what row level security does not cover, such as materialized views: see [What row level security does not protect](https://aurabase.dev/en/docs/database/rls#limits) | | `authenticated` | `aura_auth_` | `aura_authenticated`, without a user | `NULL` | Server code that must read what policies open to every signed-in user. It is not refused in a browser, but anyone holding it gets that access: do not publish it. | | `service_role` | `aura_sk_` | `aura_service_role` (SDK, REST), the administrator role of the project (`aura db raw`, schema API) | `NULL` | Servers, CI, your terminal only. It bypasses row level security and can read the Auth data of the project. | A key is the prefix followed by 43 characters (32 random bytes). The first 16 characters are stored in clear as `key_prefix`, so you can recognize a key in a list. Two keys are created with each project, `Default anon key` and `Default service_role key`; `aura projects create --json` prints them once. ## List the keys `aura db api-keys list` shows the active keys of the linked project, newest first, with their scope, creation date and last use; revoked keys are not listed. `--json` gives the full id: ```bash verify="list" aura db api-keys list --json | node -e ' for (const k of JSON.parse(require("fs").readFileSync(0, "utf8"))) console.log(k.name, "|", k.scope, "|", k.key_prefix.replace(/^(aura_[a-z]+_).*/, "$1…"))' ``` ```text expect="list" Default service_role key | service_role | aura_sk_… Default anon key | anon | aura_anon_… ``` `last_used_at` is updated in the background on each validation that is not served from the gateway cache. ## Create a key `aura db api-keys create --scope anon|authenticated|service_role` creates a key (scope `anon` by default) and prints it once. Store it in your secret manager right away: only its hash is kept. ```bash verify="create" aura db api-keys create sec-keys-backend --scope service_role \ | sed -E 's/aura_(anon|auth|sk)_[A-Za-z0-9_-]+/aura_\1_…/; s/ID: [0-9a-f]{8}/ID: …/' ``` ```text expect="create" » Creating API key 'sec-keys-backend' ✔ Key created: sec-keys-backend [service_role] ⚠ API Key (save it now — it will only be shown once): aura_sk_… • ID: … ``` The CLI sends a new `Idempotency-Key` header with each creation. The server remembers it: a request replayed with the same header and the same body returns the key already created (without its value, which is no longer available) instead of creating a second one, and the same header with another body is refused. ## Rotate and revoke a key To replace a key, create the new one, deploy it everywhere the old one is used, then revoke the old one. Revocation takes effect at once on every replica of the gateway, which drops the key from its cache: ```bash verify="rotate" NEW_KEY=$(aura db api-keys create sec-keys-rotation --scope anon | grep -oE 'aura_anon_[A-Za-z0-9_-]+') curl -s -o /dev/null -w 'before revoke: %{http_code}\n' "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=id" -H "apikey: $NEW_KEY" aura db api-keys revoke sec-keys-rotation --force curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?select=id" -H "apikey: $NEW_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log("after revoke:", e.code, "-", e.message)' ``` ```text expect="rotate" before revoke: 200 ✔ API key sec-keys-rotation revoked. after revoke: API_KEY_INVALID - The API key is invalid, expired or revoked. Send your project's key in the `apikey` header (Studio › Settings › Connection). ``` `aura db api-keys revoke` accepts the full id, the first characters of the id (the 8 shown by `list`), or the name; when several active keys match, it refuses with `AMBIGUOUS_API_KEY`. Revocation cannot be undone; the key stays in the audit trail with its revocation date. Without `--force`, the command asks for confirmation and stops when it has no terminal. There is no expiry date to set on a key: rotate on a schedule of your own, and right away when a key may have leaked. A `service_role` key that leaked must be treated like a database password: revoke it, then check what it could have reached (every row, and the Auth data of the project). ## What the gateway refuses ```bash verify="guards" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'Origin: https://app.example.com' \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' curl -s -o /dev/null -w 'anon key with Origin: %{http_code}\n' "$AURABASE_URL/v1/db/$PROJECT_ID/todos" -H "apikey: $AURABASE_ANON_KEY" -H 'Origin: https://app.example.com' curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/todos?apikey=$AURABASE_ANON_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' ``` ```text expect="guards" SECRET_KEY_IN_BROWSER - A secret key (service_role) was used from a browser: it bypasses RLS and must never be sent client-side. Use the anon (public) key in the browser and keep the service_role key on the server. anon key with Origin: 200 UNAUTHORIZED - Unauthorized: An API key in the query string is reserved for real-time streams (WS/SSE); use the apikey or X-API-Key header. ``` | Guard | Where | What it checks | | --- | --- | --- | | `401 SECRET_KEY_IN_BROWSER` | Gateway | A `service_role` key on a request that has an `Origin` header. Browsers always send `Origin` on cross-origin requests and a page cannot remove it; servers, `curl` and the SDK on a server do not send it. | | Key in the URL | Gateway | `?apikey=` is accepted only on real-time streams (WebSocket, SSE), and never for a `service_role` key (`403`, `A service_role key must never travel in a URL.`). | | `createClient()` in a browser | SDK | Throws when given an `aura_sk_` key in a browser or a browser worker (option `refuseServiceRoleInBrowser`, `true` by default; `false` only logs a warning). | | `createAdminClient()` in a browser | SDK | Always throws. | An `aura_auth_` key is not refused in a browser: the guards only protect the `service_role` scope. ## Use the service_role key on a server - Read it from the environment (`AURABASE_SERVICE_ROLE_KEY`), never from code committed to a repository; never prefix it with `NEXT_PUBLIC_` or any variable a bundler exposes to the browser. - Create a separate key per server or service, named after it, so you can revoke one without touching the others. - On a server that acts for a user, prefer the anon key with the user's token: the policies then apply. Keep the `service_role` key for work that must see every row (webhooks, back office, migrations). - A request made with the `service_role` key and a user token runs as that user: the token wins. ## Management API The CLI calls the management API with the console session (`Authorization: Bearer `); the Studio (**Settings › API keys**) does the same: | Method and path | Body | Answer | | --- | --- | --- | | `GET /v1/control/projects/{project_id}/api-keys` | — | Active keys: `id`, `name`, `key_prefix`, `scope`, `created_at`, `last_used_at` | | `POST /v1/control/projects/{project_id}/api-keys` | `{"name": "…", "scope": "anon"}`, optional header `Idempotency-Key` (255 characters at most) | The key, with `key` (shown once) and `key_available` | | `DELETE /v1/control/projects/{project_id}/api-keys/{id-or-name}` | — | Revocation | The routes `GET`, `POST /v1/db/{project_id}/api-keys` and `DELETE /v1/db/{project_id}/api-keys/{id}` serve the same keys on the management API with the same session. A project key cannot manage keys, not even the `service_role` key: ```bash verify="project-key" curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/api-keys" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/api-keys" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H 'content-type: application/json' -d '{"name": "sec-keys-from-project-key", "scope": "anon"}' \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/api-keys/00000000-0000-0000-0000-000000000000" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, "-", e.message)' ``` ```text expect="project-key" FORBIDDEN - Forbidden: The owner or admin role is required to manage API keys FORBIDDEN - Forbidden: The owner or admin role is required to manage API keys FORBIDDEN - Forbidden: The owner or admin role is required to manage API keys ``` A leaked `service_role` key therefore cannot create other keys. Every creation and revocation is written to the audit trail of the platform, without the key. ## Result ```bash verify="result" needs="create,rotate" aura db api-keys list --json | node -e ' for (const k of JSON.parse(require("fs").readFileSync(0, "utf8"))) console.log(k.name, "|", k.scope)' ``` ```text expect="result" sec-keys-backend | service_role Default service_role key | service_role Default anon key | anon ``` The revoked rotation key no longer appears. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `401 API_KEY_INVALID`, `The API key is invalid, expired or revoked. …` | Revoked key, a key of another project, or a typing error. | Check the key and the project URL; `aura db api-keys list` shows the active prefixes. | | `401 UNAUTHORIZED`, `An API key is required: add the apikey or X-API-Key header` | No key in the request. | Send `apikey: `. | | `401 SECRET_KEY_IN_BROWSER` | A `service_role` key from a browser. | Use the anon key in the browser; move the call to a server. | | `401 UNAUTHORIZED`, `An API key in the query string is reserved for real-time streams (WS/SSE); …` | Key in `?apikey=` on a REST call. | Send it as a header. | | `403 FORBIDDEN`, `The owner or admin role is required to manage API keys` | A project key, or a console account that is not owner or admin. | Use the console session of an owner or admin. | | `[404] API_KEY_NOT_FOUND`, with a message in French in this version | Unknown or already revoked key. | List the keys and use the id or the name shown. | | `AMBIGUOUS_API_KEY` | Several active keys match the prefix or name. | Give the full id from `list --json`. | | `Error: Revoke API key …? This action is irreversible.` then `Not a terminal: cannot ask for confirmation.` | `revoke` in a script without `--force`. | Add `--force`. | ## Clean up ```bash verify="clean-up" needs="create" aura db api-keys revoke sec-keys-backend --force ``` ```text expect="clean-up" ✔ API key sec-keys-backend revoked. ``` ## See also - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): The PostgreSQL role behind each key. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): The project URL and where to find the keys. - [Row-level security](https://aurabase.dev/en/docs/database/rls): What the anon key can reach is decided by policies. - [Roles and privileges](https://aurabase.dev/en/docs/database/roles-and-privileges): The privileges each role holds. --- ### Privileges: grant, revoke and reduce Source: https://aurabase.dev/en/docs/database/roles-and-privileges.md # Privileges: grant, revoke and reduce > Read the real privilege matrix of a project, grant or revoke a privilege with aura db raw, change the defaults for future tables, and keep a least-privilege setup in place over time. A request reaches a table only if its role holds the privilege for the operation (`select`, `insert`…), and only then do the policies filter the rows. Aurabase grants broad privileges to the public roles on everything in your schema and relies on row level security to limit rows. This page shows those privileges as they are, and how to narrow them. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The examples create objects prefixed `sec_priv_` and change the default privileges of the project schema; the [Clean up](#clean-up) block drops the objects and restores the defaults. ## Privileges come before policies ```text filename="order of the checks for one request" 1. role of the request anon key → aura_anon, user → aura_authenticated, service_role → bypass 2. privilege on the object missing → 403 permission denied for table … (whatever the policies) 3. policies of the table no match → empty answer, or 403 new row violates row-level security policy ``` Which key becomes which role, and which roles bypass row level security, is on [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys). This page is about step 2 for `aura_anon` and `aura_authenticated`. ## What the public roles hold by default When it provisions a project, Aurabase runs, as the administrator role of the project, `grant all` on the schema, its tables and its sequences to `aura_anon`, `aura_authenticated` and `aura_service_role`, and `alter default privileges … grant all on tables` (and sequences) for every relation created later. It also removes PostgreSQL's default `execute` for everyone on new functions. Measured on a project: | Object in your schema | `aura_anon` and `aura_authenticated` hold | Rows limited by | | --- | --- | --- | | Table created with the CLI, the schema API, `aura db raw` or a migration | All table privileges: `select`, `insert`, `update`, `delete`, `truncate`, `references`, `trigger`, `maintain` | Policies (RLS on) | | Partition | The same | Nothing when the partition is read by name: RLS is off on new partitions | | View | The same | The policies of its tables, when `security_invoker = true` | | Materialized view | The same | Nothing: no RLS on materialized views | | Sequence | All sequence privileges | — | | Function | No `execute` until you grant it | — | | The schema itself | `usage` and `create` | — | What these privileges allow beyond the policies: - `truncate` empties a table; policies do not apply to it. - `trigger` lets the role create triggers on the table, `references` lets it reference the table from a foreign key, `maintain` lets it run `vacuum`, `analyze`, `reindex`, `refresh materialized view` and `lock table` on it. - `create` on the schema lets the role create its own tables, which then belong to it and have no row level security. The REST API and the SDK never send these statements: they only matter for SQL that runs as a public role, such as a `security invoker` function you expose with `rpc()`, or a future path you did not plan for. They are defense in depth, and removing them costs nothing to an application. ## Read the matrix of your project `has_table_privilege` answers for any role and object, and `aura db raw` accepts it. Create one object of each kind, then list what `aura_anon` holds on each: ```bash verify="objects" aura db raw "create table sec_priv_items (id bigint generated always as identity primary key, name text not null)" aura db table create sec_priv_cli "name:text" aura db raw "create view sec_priv_view as select id, name from sec_priv_items; create materialized view sec_priv_counts as select count(*) as n from sec_priv_items; create table sec_priv_events (at date not null) partition by range (at); create table sec_priv_events_2026 partition of sec_priv_events for values from ('2026-01-01') to ('2027-01-01')" ``` ```text expect="objects" ℹ No results (0 rows). » Creating table 'sec_priv_cli' ✔ Table 'sec_priv_cli' created with 3 column(s). ℹ RLS enabled by default. • Columns: id, name, created_at ℹ No results (0 rows). ``` ```sql verify="matrix" needs="objects" select o.obj as object, string_agg(p.priv, ',' order by p.n) filter (where has_table_privilege('aura_anon', o.obj, p.priv)) as anon_privileges from (values ('sec_priv_items'), ('sec_priv_cli'), ('sec_priv_view'), ('sec_priv_counts'), ('sec_priv_events'), ('sec_priv_events_2026'), ('todos')) o(obj) cross join (values (1, 'select'), (2, 'insert'), (3, 'update'), (4, 'delete'), (5, 'truncate'), (6, 'references'), (7, 'trigger'), (8, 'maintain')) p(n, priv) group by o.obj order by o.obj; ``` ```text expect="matrix" anon_privileges │ object ─────────────────────────────────────────────────────────────────┼───────────────────── select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_cli select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_counts select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_events select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_events_2026 select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_items select,insert,update,delete,truncate,references,trigger,maintain │ sec_priv_view select,insert,update,delete,truncate,references,trigger,maintain │ todos ℹ 7 row(s). ``` `aura_authenticated` holds the same; replace the role in the query to check it. `has_column_privilege`, `has_function_privilege` and `has_schema_privilege` work the same way. ## Grant and revoke `grant` and `revoke` run through `aura db raw`, the SQL editor of the Studio, migrations and the direct connection. Revoking a privilege from a public role gives `403 INSUFFICIENT_PRIVILEGE`, `permission denied for …` to the requests of that role: ```bash verify="revoke" needs="objects" aura db raw "revoke all on sec_priv_counts from aura_anon, aura_authenticated" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/sec_priv_counts" -H "apikey: $AURABASE_ANON_KEY" \ | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)' ``` ```text expect="revoke" ℹ No results (0 rows). INSUFFICIENT_PRIVILEGE permission denied for materialized view sec_priv_counts ``` Typical uses: | Goal | SQL | | --- | --- | | Keep a materialized view for servers only | `revoke all on from aura_anon, aura_authenticated;` | | Read-only table for the public roles | `revoke insert, update, delete on
from aura_anon, aura_authenticated;` | | Hide a column | Revoke `select` on the table, then `grant select () …`; Realtime events still carry every column ([Column-level security](https://aurabase.dev/en/docs/database/column-security)) | | Let signed-in users call a function | `grant execute on function () to aura_authenticated;` ([Database functions](https://aurabase.dev/en/docs/database/functions)) | | Expose a table created over the direct connection with the project's login role | `grant select, insert, update, delete on
to aura_authenticated;` after enabling RLS and writing policies ([Connect](https://aurabase.dev/en/docs/database/connect#private-tables)) | ## Reduce the defaults The privileges below are never needed by the REST API or the SDK. Revoke them on what exists, and change the defaults so future tables are created without them. On your project, the first statement covers every table, view, materialized view and partition of your schema at once (excerpt; your schema is `project_` followed by the project id with underscores): ```sql filename="on your project" revoke truncate, references, trigger, maintain on all tables in schema project_ from aura_anon, aura_authenticated; ``` The example below does the same on the objects of this page only, so that the tables of the example schema stay as they are, then removes `create` on the schema and changes the defaults. `alter default privileges` applies to objects created later by the role that runs it, which for `aura db raw`, the CLI and the schema API is the administrator role of the project, the one that set the defaults: ```bash verify="least" needs="objects" SCHEMA="project_${PROJECT_ID//-/_}" aura db raw "revoke truncate, references, trigger, maintain on sec_priv_items, sec_priv_cli, sec_priv_view, sec_priv_counts, sec_priv_events, sec_priv_events_2026 from aura_anon, aura_authenticated; revoke create on schema $SCHEMA from aura_anon, aura_authenticated; alter default privileges in schema $SCHEMA revoke truncate, references, trigger, maintain on tables from aura_anon, aura_authenticated" aura db raw "create table sec_priv_after (id int)" aura db raw "select string_agg(p.priv, ',' order by p.n) filter (where has_table_privilege('aura_anon', 'sec_priv_after', p.priv)) as anon_on_new_table, has_schema_privilege('aura_anon', current_schema(), 'create') as anon_creates from (values (1, 'select'), (2, 'insert'), (3, 'update'), (4, 'delete'), (5, 'truncate'), (6, 'references'), (7, 'trigger'), (8, 'maintain')) p(n, priv)" ``` ```text expect="least" ℹ No results (0 rows). ℹ No results (0 rows). anon_creates │ anon_on_new_table ─────────────┼──────────────────────────── false │ select,insert,update,delete ℹ 1 row(s). ``` A partition has its own privileges: revoking on the parent does not change its partitions, which `all tables in schema` covers. Keep `select`, `insert`, `update` and `delete`: the policies decide which rows they reach, and removing them breaks the API for that role. Two things are not covered by this script: objects created over the direct connection by another role than the administrator (the defaults are those of the role that creates), and the platform schemas of the project, which Aurabase manages. ## Keep it in place Aurabase re-applies its grants to the schemas of a project, your schema included, when it upgrades their internal migrations: the same `grant all` on every table and sequence, and the same default privileges. Such an upgrade restores what your `revoke` statements removed, including the revocations of [Column-level security](https://aurabase.dev/en/docs/database/column-security) and of materialized views. This re-application is described from the code of the provisioner and was not triggered for this page. Therefore: - keep your `revoke` and `grant` statements in a migration or a script that you can run again at any time; - check the result with the matrix query above, in CI or after each platform upgrade ([Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls)); - for data that must never reach a public role whatever its privileges, rely on row level security (a policy that does not match) or keep it in a table without any policy for the public roles. ## Roles you cannot create A project cannot create PostgreSQL roles (`permission denied to create role`). Model your own roles with claims instead: set `app_metadata.roles` from a server and test `auth.has_role('')` in policies, or keep memberships in a table read by a `security definer` function ([Multi-tenant schema design](https://aurabase.dev/en/docs/database/multi-tenancy)). The `service_role` key and the password of the direct connection both act as administrator; they never go to a browser or an app ([API keys](https://aurabase.dev/en/docs/database/api-keys)). ## Result After the reduction, the public roles keep the four privileges that policies filter, on the objects revoked above and on new tables: ```sql verify="result" needs="least" select o.obj as object, string_agg(p.priv, ',' order by p.n) filter (where has_table_privilege('aura_authenticated', o.obj, p.priv)) as user_privileges from (values ('sec_priv_items'), ('sec_priv_after'), ('sec_priv_events_2026')) o(obj) cross join (values (1, 'select'), (2, 'insert'), (3, 'update'), (4, 'delete'), (5, 'truncate'), (6, 'references'), (7, 'trigger'), (8, 'maintain')) p(n, priv) group by o.obj order by o.obj; ``` ```text expect="result" object │ user_privileges ─────────────────────┼──────────────────────────── sec_priv_after │ select,insert,update,delete sec_priv_events_2026 │ select,insert,update,delete sec_priv_items │ select,insert,update,delete ℹ 3 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `403 INSUFFICIENT_PRIVILEGE`, `permission denied for table …` | The role lacks the privilege: revoked, or a table created over the direct connection with the project's login role. | Grant what the role needs, then let policies filter. | | `permission denied for materialized view …` / `… for view …` | The view was revoked from the role. | Read it with the `service_role` key, or through a function. | | `permission denied for function …` | No `execute` for the role: the default for new functions. | `grant execute on function … to aura_authenticated;` | | `permission denied for schema project_…` | `create` was revoked on the schema and SQL running as a public role tried to create an object. | Expected after the reduction: create objects as administrator. | | `permission denied to create role` | Projects cannot create roles. | Use claims and policies. | | A revoked privilege is back | A platform upgrade re-applied the default grants. | Run your script again ([Keep it in place](#durable)). | ## Clean up Drop the objects, and give the defaults back as the project had them: ```bash verify="clean-up" needs="objects" SCHEMA="project_${PROJECT_ID//-/_}" aura db raw "drop table if exists sec_priv_after; drop materialized view sec_priv_counts; drop view sec_priv_view; drop table sec_priv_events; drop table sec_priv_items; drop table sec_priv_cli; grant create on schema $SCHEMA to aura_anon, aura_authenticated; alter default privileges in schema $SCHEMA grant all on tables to aura_anon, aura_authenticated" ``` ```text expect="clean-up" ℹ No results (0 rows). ``` Keep the reduction on your own project; this block only restores the state that the rest of the documentation assumes. ## See also - [Roles, keys and RLS bypass](https://aurabase.dev/en/docs/database/roles-and-keys): Which role each key becomes. - [Row-level security](https://aurabase.dev/en/docs/database/rls): The policies that filter rows after the privileges. - [Column-level security](https://aurabase.dev/en/docs/database/column-security): Privileges on a list of columns. - [Views and materialized views](https://aurabase.dev/en/docs/database/views): Objects that the policies of a table do not protect. --- ### SQL migrations: write, apply and track Source: https://aurabase.dev/en/docs/database/migrations.md # SQL migrations: write, apply and track > Write each schema change as a SQL file in aurabase/migrations, apply the files in order to your project, see which ones ran, and know what happens when one of them fails or changes after it ran. A migration is a SQL file that changes the schema of your project. You keep the files in your repository, next to your code, and `aura db push` applies the ones the project has not run yet, in order. The project keeps a ledger of what ran, so the same file never runs twice. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - No `DATABASE_URL` in your environment, `.env` or `.env.local`. The CLI reads those files, and when `DATABASE_URL` is set, `aura db push` applies the files to that database instead of the linked project ([Local development](https://aurabase.dev/en/docs/database/local-development)). The examples create migrations named `wf_mig_…` and the tables `wf_mig_notes` and `wf_mig_labels`; the [Clean up](#clean-up) block removes them. File names start with the time they were created, so the commands of this page pipe their output through `sed` to replace that timestamp with `YYYYMMDDHHMMSS`: you do not need it. ## How migrations run | Step | What happens | | --- | --- | | Files | `aurabase/migrations/*.sql`, applied in the order of their names. `aura db migration new ` prefixes the name with the current UTC time (`YYYYMMDDHHMMSS_.sql`), so the order is the order of creation. Files ending in `.down.sql` are never applied by `push` ([Roll back and repair migrations](https://aurabase.dev/en/docs/database/rollback-migrations)). | | Sending | `aura db push` strips the SQL comments of each file and sends it to `POST /v1/db/{project_id}/migrations/run`, with the file name as `version`. Empty files are skipped. It needs the `service_role` key, not `aura login`. | | Running | The server runs the whole file in **one transaction**: if a statement fails, nothing of the file stays. Tables the file creates get row level security turned on and forced, as with every other path ([Row-level security](https://aurabase.dev/en/docs/database/rls)), and views get `security_invoker = true`. | | Time limits | By default a statement waits at most 5 seconds for a lock and runs at most 5 minutes. | | Ledger | After success, the project records the version, a description and the SHA-256 checksum of the SQL that ran. A version already in the ledger with the same checksum is skipped. The ledger belongs to the project: you cannot edit it with SQL. | | Order of failure | `push` stops at the first file that fails. The files before it stay applied, the files after it are not sent. | Aurabase also upgrades its own internal schemas when the platform is updated. Those upgrades never run your files and never appear in your ledger. ## Create a migration ```bash verify="new" aura db migration new wf_mig_notes | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="new" ✔ aurabase/migrations/YYYYMMDDHHMMSS_wf_mig_notes.sql ``` The command creates the folder if needed and an empty file. `aura migration new` is the same command. Write the change in it: ```bash verify="write" needs="new" file=$(ls aurabase/migrations/*_wf_mig_notes.sql) cat > "$file" <<'SQL' -- Notes owned by their author create table wf_mig_notes ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid(), body text not null, created_at timestamptz not null default now() ); create policy wf_mig_notes_owner on wf_mig_notes for all to aura_authenticated using (auth.uid() = user_id) with check (auth.uid() = user_id); SQL ``` Use unqualified names: the server runs the file in the schema of your project. ## Apply it ```bash verify="push" needs="write" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="push" » Applying migrations... • Applying to linked project 11111111-2222-4333-8444-555555555555 via API... ✔ YYYYMMDDHHMMSS_wf_mig_notes.sql applied ✔ 1 migration(s) applied successfully! ``` Run it again: nothing is sent twice. ```bash verify="push-again" needs="push" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="push-again" » Applying migrations... • Applying to linked project 11111111-2222-4333-8444-555555555555 via API... ℹ YYYYMMDDHHMMSS_wf_mig_notes.sql (already applied) ℹ Schema up to date (no new migrations). ``` ## See what ran `aura db status` lists the local files, applied or pending, then the versions the ledger holds without a local file. `aura db migration list` and `aura migration list` print the same thing. ```bash verify="status" needs="push" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' aura db migration list --json | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="status" » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_mig_notes.sql APPLIED 2026-11-23 10:00:00.000000+00 [ { "applied": true, "applied_at": "2026-11-23 10:00:00.000000+00", "name": "YYYYMMDDHHMMSS_wf_mig_notes.sql" } ] ``` ## The migrations API The CLI calls two routes that you can call from any language, with the `service_role` key. The anon key gets `403 FORBIDDEN` (`DDL operation is reserved to the service_role role`). | Route | Body | Answer | | --- | --- | --- | | `GET /v1/db/{project_id}/migrations` | | The ledger, newest first: `version`, `description`, `checksum`, `applied_at`, `project_id` | | `POST /v1/db/{project_id}/migrations/run` | `{"version", "description", "sql"}`, all three required, no other field | `applied: true` once, then `applied: false` with `Version already applied` | `version` is 1 to 100 characters and `description` 1 to 500, without `$`, quotes, backslashes or control characters. A migration sent over HTTP is recorded like a file: ```bash verify="http" needs="push" run() { node -e 'console.log(JSON.stringify({ version: process.argv[1], description: process.argv[2], sql: process.argv[3] }))' "$@" \ | curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/migrations/run" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d @- echo } run wf_mig_http_index "index on created_at" "create index wf_mig_notes_created_at on wf_mig_notes (created_at)" run wf_mig_http_index "index on created_at" "create index wf_mig_notes_created_at on wf_mig_notes (created_at)" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/migrations" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ | node -e 'for (const m of JSON.parse(require("fs").readFileSync(0, "utf8")).data) console.log(`${m.version} | ${m.description}`.replace(/\d{14}_/g, "YYYYMMDDHHMMSS_"))' ``` ```text expect="http" {"data":{"version":"wf_mig_http_index","applied":true,"message":"Migration applied successfully"},"meta":null} {"data":{"version":"wf_mig_http_index","applied":false,"message":"Version already applied"},"meta":null} wf_mig_http_index | index on created_at YYYYMMDDHHMMSS_wf_mig_notes.sql | Migration YYYYMMDDHHMMSS_wf_mig_notes.sql ``` ## What a migration may contain The server checks the SQL of a migration before running it, with the same isolation rules as `aura db raw` plus a few of its own. Measured on a project: | Statement | In a migration | | --- | --- | | `create table`, `alter table`, `drop table`, `create index`, `create view`, `create policy`, `grant`, `revoke` | Accepted | | `create function … language sql` or `plpgsql`, with a dollar-quoted body | Accepted, `security invoker` only | | `create trigger … execute function …` | Accepted | | `begin`, `commit`, `rollback`, `savepoint` | Refused: `Transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT) is not allowed in migrations` | | `security definer` | Refused: create such a function with `aura db function create` ([Database functions](https://aurabase.dev/en/docs/database/functions)) | | `do $$ … $$` blocks | Refused: `Anonymous blocks (DO) are not allowed in raw queries` | | `create extension` | Refused: enable the extension with `aura db extensions enable ` | | `set search_path`, `set role` | Refused | | `create index concurrently` | Fails when it runs: `CREATE INDEX CONCURRENTLY cannot run inside a transaction block`, since the file runs in a transaction (PostgreSQL 18) | | Another project's schema, `information_schema`, `pg_catalog` | Refused | ```bash verify="refused" needs="push" run() { node -e 'console.log(JSON.stringify({ version: process.argv[1], description: "refused", sql: process.argv[2] }))' "$@" \ | curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/migrations/run" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d @- \ | node -e 'const r = JSON.parse(require("fs").readFileSync(0, "utf8")); console.log(r.error ? r.error.message : r.data.message)' } run wf_mig_tx "begin; create table wf_mig_tx (id int); commit;" run wf_mig_definer "create function wf_mig_definer() returns int language sql security definer as \$\$ select 1 \$\$" run wf_mig_concurrently "create index concurrently wf_mig_notes_body on wf_mig_notes (body)" ``` ```text expect="refused" Invalid request: Transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT) is not allowed in migrations Invalid request: The 'SECURITY DEFINER' option is not allowed in raw queries (privilege escalation). Create your function as 'SECURITY INVOKER' (the default) or use the dedicated API 'POST /v1/db/:pid/functions'. Invalid request: Migration failed: Invalid request: CREATE INDEX CONCURRENTLY cannot run inside a transaction block ``` A refused migration is not recorded: fix the file and push again. ## When a migration fails halfway Three new files, where the second one inserts a row that breaks a constraint: ```bash verify="halfway" needs="push" aura db migration new wf_mig_step1_tags > /dev/null aura db migration new wf_mig_step2_labels > /dev/null aura db migration new wf_mig_step3_index > /dev/null echo "alter table wf_mig_notes add column tags text[] not null default '{}';" > $(ls aurabase/migrations/*_wf_mig_step1_tags.sql) cat > $(ls aurabase/migrations/*_wf_mig_step2_labels.sql) <<'SQL' create table wf_mig_labels (id bigint generated always as identity primary key, name text not null); insert into wf_mig_labels (name) values ('urgent'), (null); SQL echo "create index wf_mig_notes_user on wf_mig_notes (user_id);" > $(ls aurabase/migrations/*_wf_mig_step3_index.sql) aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' || echo "exit code $?" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' aura db table list | grep -c wf_mig_labels || true ``` ```text expect="halfway" » Applying migrations... • Applying to linked project 11111111-2222-4333-8444-555555555555 via API... ℹ YYYYMMDDHHMMSS_wf_mig_notes.sql (already applied) ✔ YYYYMMDDHHMMSS_wf_mig_step1_tags.sql applied Error: Migration 'YYYYMMDDHHMMSS_wf_mig_step2_labels.sql' failed: [400] BAD_REQUEST: Invalid request: Migration failed: Invalid request: null value in column "name" of relation "wf_mig_labels" violates not-null constraint exit code 1 » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_mig_notes.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_mig_step1_tags.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_mig_step2_labels.sql PENDING - YYYYMMDDHHMMSS_wf_mig_step3_index.sql PENDING - wf_mig_http_index APPLIED 2026-11-23 10:00:00.000000+00 0 ``` The state is clean at the level of files: `step1` is applied, `step2` left nothing behind (its table was not created, since the file ran in one transaction), and `step3` was never sent. Fix the failing file and push again; the push resumes where it stopped: ```bash verify="resume" needs="halfway" sed -i.bak "s/('urgent'), (null)/('urgent'), ('later')/" aurabase/migrations/*_wf_mig_step2_labels.sql && rm aurabase/migrations/*.bak aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="resume" » Applying migrations... • Applying to linked project 11111111-2222-4333-8444-555555555555 via API... ℹ YYYYMMDDHHMMSS_wf_mig_notes.sql (already applied) ℹ YYYYMMDDHHMMSS_wf_mig_step1_tags.sql (already applied) ✔ YYYYMMDDHHMMSS_wf_mig_step2_labels.sql applied ✔ YYYYMMDDHHMMSS_wf_mig_step3_index.sql applied ✔ 2 migration(s) applied successfully! ``` One file is atomic, a push is not. Group statements that must succeed together in one file. If you need to undo the files that did apply, see [Roll back and repair migrations](https://aurabase.dev/en/docs/database/rollback-migrations). ## Changing a migration that already ran The ledger stores the checksum of each file. The server refuses a version it already ran with different SQL, but `aura db push` reports that refusal as `(already applied)` and goes on: **the change is not applied**, and nothing tells you so. ```bash verify="edit" needs="resume" echo "alter table wf_mig_notes add column archived boolean not null default false;" >> $(ls aurabase/migrations/*_wf_mig_step1_tags.sql) aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep step1 aura db table list --json | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).find((t) => t.name === "wf_mig_notes"); console.log(t.columns.map((c) => c.name).join(", "))' ``` ```text expect="edit" ℹ YYYYMMDDHHMMSS_wf_mig_step1_tags.sql (already applied) id, user_id, body, created_at, tags ``` The column `archived` does not exist. The server's own answer, when the same version is sent with the new SQL: ```bash verify="edit-http" needs="edit" file=$(ls aurabase/migrations/*_wf_mig_step1_tags.sql) node -e 'const fs = require("fs"); const f = process.argv[1]; console.log(JSON.stringify({ version: f.split("/").pop(), description: "edited", sql: fs.readFileSync(f, "utf8").trim() }))' "$file" \ | curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/migrations/run" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d @- \ | node -e 'const r = JSON.parse(require("fs").readFileSync(0, "utf8")); console.log(r.error.code, r.error.message.replace(/\d{14}_/, "YYYYMMDDHHMMSS_"))' ``` ```text expect="edit-http" CONFLICT Conflict: Version 'YYYYMMDDHHMMSS_wf_mig_step1_tags.sql' was already applied with different SQL (checksum mismatch) — use a new migration version ``` Never edit a migration once it ran on a project: put the change in a new file. Changing only comments is harmless, since the CLI strips them before computing what it sends. If a file was edited by mistake, restore its content from your version control; to record its new content as applied without running it, use `aura db migration repair --applied` ([Roll back and repair migrations](https://aurabase.dev/en/docs/database/rollback-migrations#repair)). Revert the edit of the example before going on: ```bash verify="edit-revert" needs="edit" file=$(ls aurabase/migrations/*_wf_mig_step1_tags.sql) echo "alter table wf_mig_notes add column tags text[] not null default '{}';" > "$file" aura db push 2>&1 | grep -c 'already applied' ``` ```text expect="edit-revert" 4 ``` ## Change a busy table Most `alter table` forms take an `ACCESS EXCLUSIVE` lock, which waits for the queries running on the table and blocks the new ones while it waits (PostgreSQL 18). A migration waits at most 5 seconds by default for its locks; past that, it fails with `409 CONFLICT` (`Migration hit a lock conflict (concurrent DDL operation or locked table) — retry in a moment`) and nothing of the file stays. Push again when the table is quieter. To remove or rename a column that your application reads, split the change so that each deployed version of the application works with the schema it meets (expand, then contract): | Step | Migration or action | The application | | --- | --- | --- | | 1. Expand | Add the new column, nullable or with a default. | Still reads and writes the old column. | | 2. Backfill | Copy the values (`update … set new = old where new is null`), in batches on a large table. | Writes both columns. | | 3. Switch | | Reads and writes the new column only. | | 4. Contract | Drop the old column in a later migration. | Already ignores it. | `drop column` cannot be undone with its data: a `.down.sql` can add the column back, not its values. Take a [branch](https://aurabase.dev/en/docs/database/branches) to try the sequence on a copy first. ## Apply migrations from CI `aura db push` only talks to the data plane of the project with the `service_role` key: no `aura login` is needed. It reads the project from `aurabase.toml` (written by `aura link`, commit it) or from `AURABASE_PROJECT_ID` and `NEXT_PUBLIC_AURABASE_URL`. Excerpt of a GitHub Actions workflow (not replayed here): ```yaml filename=".github/workflows/migrate.yml" name: migrate on: push: branches: [main] jobs: migrate: runs-on: ubuntu-latest env: AURABASE_PROJECT_ID: ${{ vars.PROJECT_ID }} NEXT_PUBLIC_AURABASE_URL: ${{ vars.PROJECT_URL }} AURABASE_SERVICE_ROLE_KEY: ${{ secrets.SERVICE_ROLE_KEY }} steps: - uses: actions/checkout@v4 - run: npm install -g @aurabase/cli - run: aura db push ``` Two pushes at the same time do not run the same file twice: the server takes a lock per project, and the second one fails with `409 CONFLICT` (`Migration lock conflict (concurrent DDL operation) — retry`) if it waits more than 5 seconds. Run the migration job once per deployment, before the new code goes live. To try the migrations of a pull request first, push them to a [branch](https://aurabase.dev/en/docs/database/branches). ## Result ```bash verify="result" needs="edit-revert" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' aura db table list | grep -A1 wf_mig_ ``` ```text expect="result" » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_mig_notes.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_mig_step1_tags.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_mig_step2_labels.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_mig_step3_index.sql APPLIED 2026-11-23 10:00:00.000000+00 wf_mig_http_index APPLIED 2026-11-23 10:00:00.000000+00 • wf_mig_labels [RLS] id, name • wf_mig_notes [RLS] id, user_id, body, created_at, tags ``` Both tables have row level security on, without any `enable row level security` in the files. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `Migration '' failed: [400] BAD_REQUEST: Invalid request: Migration failed: …` | A statement of the file failed; the PostgreSQL message follows. Nothing of that file stayed. | Fix the file, then `aura db push` again. | | `Migration failed: Invalid request: relation "…" already exists` | The object exists but the ledger does not list the file, for example after `aura db migration down` without a `.down.sql`, or on a [branch](https://aurabase.dev/en/docs/database/branches). | Mark the file as applied: `aura db migration repair --applied`. | | `(already applied)` after editing a file | The file changed after it ran; the change is skipped. | Restore the file; put the change in a new migration. | | `409 CONFLICT`, `Migration hit a lock conflict (concurrent DDL operation or locked table) — retry in a moment` | A lock was not obtained within 5 seconds. | Push again later. | | `Transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT) is not allowed in migrations` | The file has `begin` or `commit`. | Remove them: the file already runs in a transaction. | | `Empty migration SQL: nothing to apply` | `POST …/migrations/run` with an empty `sql`. (`push` skips empty files.) | Send the SQL. | | `Invalid JSON body — missing field `description`` | `POST …/migrations/run` without `description`. | Send `version`, `description` and `sql`. | | `AURABASE_SERVICE_ROLE_KEY is not set.` | The key is missing in the shell or the CI job. | Export the `service_role` key of the project. | | `PostgreSQL unreachable at postgresql://…` | `DATABASE_URL` is set, so `push` targets that database. | Unset `DATABASE_URL` or remove it from `.env`. | ## Clean up Drop the tables, remove the versions from the ledger, then delete the files. `repair --reverted` only edits the ledger; it runs no SQL. ```bash verify="clean-up" needs="push" aura db raw "drop table if exists wf_mig_labels; drop table if exists wf_mig_notes" for f in aurabase/migrations/*_wf_mig_*.sql; do aura db migration repair "$(basename "$f")" --reverted > /dev/null; done aura db migration repair wf_mig_http_index --reverted > /dev/null rm -rf aurabase/migrations aura db status ``` ```text expect="clean-up" ℹ No results (0 rows). » Migration Status - Project 11111111-2222-4333-8444-555555555555 ℹ No migrations found, local or applied. Create one with aura db migration new . ``` ## See also - [Roll back and repair migrations](https://aurabase.dev/en/docs/database/rollback-migrations): Down files, the rollback route and the ledger repair. - [Push, pull, diff and watch](https://aurabase.dev/en/docs/database/sync-schema): Keep the folder and the project in sync. - [Database branches](https://aurabase.dev/en/docs/database/branches): Try migrations on a copy of the project. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): The isolation rules that migrations share with aura db raw. --- ### Roll back and repair migrations Source: https://aurabase.dev/en/docs/database/rollback-migrations.md # Roll back and repair migrations > Write the SQL that undoes a migration, run it so that the schema and the ledger change together, and put the ledger back in line with the schema when they disagree. Aurabase never guesses how to undo a migration: you write the reverse SQL. This page runs it so that the schema and the ledger of the project change together, and shows how to edit the ledger alone when it no longer matches the schema. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - How migrations are applied: [SQL migrations](https://aurabase.dev/en/docs/database/migrations). The examples create two migrations, `wf_rb_1_tags` and `wf_rb_2_labels`, each with a down file, and the tables `wf_rb_tags` and `wf_rb_labels`; the [Clean up](#clean-up) block removes them. As on the migrations page, `sed` replaces the timestamp of the file names with `YYYYMMDDHHMMSS`. ```bash verify="setup" aura db migration new wf_rb_1_tags > /dev/null aura db migration new wf_rb_2_labels > /dev/null one=$(ls aurabase/migrations/*_wf_rb_1_tags.sql) two=$(ls aurabase/migrations/*_wf_rb_2_labels.sql) echo "create table wf_rb_tags (id bigint generated always as identity primary key, name text not null);" > "$one" echo "drop table wf_rb_tags;" > "${one%.sql}.down.sql" echo "create table wf_rb_labels (id bigint generated always as identity primary key, name text not null);" > "$two" echo "drop table wf_rb_labels;" > "${two%.sql}.down.sql" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="setup" » Applying migrations... • Applying to linked project 11111111-2222-4333-8444-555555555555 via API... ✔ YYYYMMDDHHMMSS_wf_rb_1_tags.sql applied ✔ YYYYMMDDHHMMSS_wf_rb_2_labels.sql applied ✔ 2 migration(s) applied successfully! ``` ## Three tools | Tool | Runs SQL | Changes the ledger | Use it to | | --- | --- | --- | --- | | `aura db migration down [N]` with `.down.sql` files | The down file, if it exists | Removes the version | Undo migrations from the CLI. Read [the defect below](#down) first. | | `POST /v1/db/{project_id}/migrations/rollback` with `{"version", "sql"}` | `sql`, if given | Removes the version | Undo one named migration. | | `aura db migration repair --applied` or `--reverted`, `POST …/migrations/repair` | Never | Adds or removes the version | Put the ledger in line with a schema that is already right. | When SQL runs, it runs in one transaction with the removal from the ledger: either both happen or neither does. The same isolation rules as for migrations apply to it ([What a migration may contain](https://aurabase.dev/en/docs/database/migrations#rules)). `aura migration …` is the same command as `aura db migration …`. ## Write a down file A down file has the name of its migration with `.down.sql` instead of `.sql`, in the same folder: `20261123100000_wf_rb_1_tags.down.sql` undoes `20261123100000_wf_rb_1_tags.sql`. `aura db push`, `aura db status` and `aura db diff` ignore down files. Write the down file when you write the migration, and undo the statements in reverse order: drop what the migration created, add back what it dropped. ## aura db migration down picks the oldest migration `aura db migration down` says it reverts the last N applied migrations (1 by default). On a linked project it reverts the **oldest** N of the ledger instead (measured with CLI 0.3.4). With the two migrations above, it undoes `wf_rb_1_tags`, applied first, and leaves `wf_rb_2_labels`: ```bash verify="down-oldest" needs="setup" aura db migration down 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/g' aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="down-oldest" » Reverting last 1 migration(s)... • Reverting on linked project 11111111-2222-4333-8444-555555555555 via API... • Reverting YYYYMMDDHHMMSS_wf_rb_1_tags.sql via aurabase/migrations/YYYYMMDDHHMMSS_wf_rb_1_tags.down.sql... ✔ 1 migration(s) reverted. » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_rb_1_tags.sql PENDING - YYYYMMDDHHMMSS_wf_rb_2_labels.sql APPLIED 2026-11-23 10:00:00.000000+00 ``` Until this is fixed, use `aura db migration down` only when the ledger holds a single migration, and revert a named migration with the route of the next section. When it already ran on the wrong migration, as here, the down file did its work (the table `wf_rb_tags` is gone) and the version is pending again: `aura db push` applies it again. ```bash verify="push-back" needs="down-oldest" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_rb ``` ```text expect="push-back" ✔ YYYYMMDDHHMMSS_wf_rb_1_tags.sql applied ℹ YYYYMMDDHHMMSS_wf_rb_2_labels.sql (already applied) ``` Without a down file, `down` prints `has no .down.sql — removing from migration history only.`: the schema stays, the ledger forgets the version, and the next `aura db push` fails with `relation "…" already exists`. Mark the version applied again with `repair --applied` ([Repair the ledger](#repair)). ## Revert one migration by name `POST /v1/db/{project_id}/migrations/rollback` takes the version to revert and the SQL that undoes it, with the `service_role` key. Here it reverts `wf_rb_2_labels` with the content of its down file: ```bash verify="rollback" needs="push-back" down=$(ls aurabase/migrations/*_wf_rb_2_labels.down.sql) rollback() { node -e 'const fs = require("fs"); const f = process.argv[1]; console.log(JSON.stringify({ version: f.split("/").pop().replace(".down.sql", ".sql"), sql: fs.readFileSync(f, "utf8") }))' "$down" \ | curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/migrations/rollback" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d @- \ | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' echo } rollback rollback aura db table list | grep -c wf_rb_labels || true ``` ```text expect="rollback" {"data":{"version":"YYYYMMDDHHMMSS_wf_rb_2_labels.sql","reverted":true,"message":"Migration reverted and removed from the ledger"},"meta":null} {"data":{"version":"YYYYMMDDHHMMSS_wf_rb_2_labels.sql","reverted":false,"message":"Version not in the ledger (already reverted or never applied)"},"meta":null} 0 ``` The second call changes nothing: the version is no longer in the ledger. The body accepts `version` and `sql` only (any other field is refused with `400`); without `sql`, the route removes the version from the ledger and runs nothing. If the SQL fails, the answer is `400 BAD_REQUEST` with the PostgreSQL message, and neither the schema nor the ledger changes. ## Repair the ledger `repair` writes to the ledger and runs no SQL. Use it when the schema is right and the ledger is not: a change made by hand, a migration recorded under another name, the ledger of a [branch](https://aurabase.dev/en/docs/database/branches), or a version removed by `down` without its down file. Here the ledger forgets `wf_rb_1_tags` while its table stays, so `push` fails, then `repair --applied` records the file again: ```bash verify="repair" needs="rollback" one=$(basename "$(ls aurabase/migrations/*_wf_rb_1_tags.sql)") aura db migration repair "$one" --reverted | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep Error || true aura db migration repair "$one" --applied | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="repair" • Repairing migration on linked project 11111111-2222-4333-8444-555555555555 via API... ✔ Migration 'YYYYMMDDHHMMSS_wf_rb_1_tags.sql' marked as REVERTED (no SQL was executed). Error: Migration 'YYYYMMDDHHMMSS_wf_rb_1_tags.sql' failed: [400] BAD_REQUEST: Invalid request: Migration failed: Invalid request: relation "wf_rb_tags" already exists • Repairing migration on linked project 11111111-2222-4333-8444-555555555555 via API... ✔ Migration 'YYYYMMDDHHMMSS_wf_rb_1_tags.sql' marked as APPLIED (no SQL was executed). ``` - `--applied` is the default when you give neither flag. It needs the file in `aurabase/migrations`: the ledger stores the checksum of its SQL, so a later `push` recognizes it. Without the file: `cannot mark '' as applied: file aurabase/migrations/ not found (the ledger stores the checksum of its SQL)`. - `--reverted` removes the version and answers `marked as REVERTED` even for a version the ledger never held. - The route is `POST /v1/db/{project_id}/migrations/repair` with `{"version", "status": "applied" | "reverted", "sql", "description"}`; `sql` is required for `applied`. ```bash verify="repair-http" needs="setup" repair() { curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/migrations/repair" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' -d "$1" echo } repair '{"version": "wf_rb_by_hand", "status": "applied", "sql": "create table wf_rb_by_hand (id int)"}' repair '{"version": "wf_rb_by_hand", "status": "reverted"}' repair '{"version": "wf_rb_by_hand", "status": "applied"}' | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8")).error.message)' ``` ```text expect="repair-http" {"data":{"version":"wf_rb_by_hand","status":"applied","message":"Ledger updated; no SQL was executed"},"meta":null} {"data":{"version":"wf_rb_by_hand","status":"reverted","message":"Ledger updated; no SQL was executed"},"meta":null} Invalid request: Reparing a migration as 'applied' requires its `sql` (the ledger stores its checksum) ``` The first call recorded a table that does not exist: `repair` trusts you. Check the schema (`aura db table list`) before repairing. ## What a rollback cannot undo - **Data.** A down file that adds back a dropped column or table restores the structure, not the rows. Before a destructive migration, export what you may need, or try the change on a [branch](https://aurabase.dev/en/docs/database/branches) first. - **Several migrations at once.** Each version is reverted in its own transaction. With `down N` (or several route calls), a failure stops there: the versions reverted before it stay reverted. - **What the platform did around the migration.** Row level security turned on for new tables, and `security_invoker` on new views, are part of the objects: dropping the object removes them too. - **Transaction control and `security definer`.** A down file follows the rules of a migration: no `begin`/`commit`, no `security definer`. Prefer changes that need no rollback: add before you remove, and remove in a later migration ([Change a busy table](https://aurabase.dev/en/docs/database/migrations#zero-downtime)). ## Result ```bash verify="result" needs="repair" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' aura db table list | grep wf_rb ``` ```text expect="result" » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_rb_1_tags.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_rb_2_labels.sql PENDING - • wf_rb_tags [RLS] ``` `wf_rb_1_tags` is applied and its table exists; `wf_rb_2_labels` was reverted by the route and its table is gone. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | ` was NOT reverted: Version not in the ledger (already reverted or never applied)` | `down` asked the server to revert a version the ledger no longer holds. | Read the ledger with `aura db status`. | | `has no .down.sql — removing from migration history only.` | No down file next to the migration. | Undo the schema by hand or with a new migration, or record it again with `repair --applied`. | | `relation "…" already exists` on the next `push` | The ledger forgot a version whose objects still exist. | `aura db migration repair --applied`. | | `cannot mark '' as applied: file aurabase/migrations/ not found` | `repair --applied` (or `repair` without a flag) on a name with no local file. | Use the exact file name, or `--reverted`. | | `Invalid JSON body — down_sql: unknown field` | The rollback route only accepts `version` and `sql`. | Rename the field to `sql`. | | `400 BAD_REQUEST`, `Migration failed: …` on a rollback | The down SQL failed; nothing changed. | Fix the down SQL and call the route again. | ## Clean up ```bash verify="clean-up" needs="setup" aura db raw "drop table if exists wf_rb_tags; drop table if exists wf_rb_labels" for f in aurabase/migrations/*_wf_rb_*.sql; do case "$f" in *.down.sql) continue ;; esac aura db migration repair "$(basename "$f")" --reverted > /dev/null done rm -rf aurabase/migrations aura db status ``` ```text expect="clean-up" ℹ No results (0 rows). » Migration Status - Project 11111111-2222-4333-8444-555555555555 ℹ No migrations found, local or applied. Create one with aura db migration new . ``` ## See also - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): Files, order, transactions and the ledger. - [Database branches](https://aurabase.dev/en/docs/database/branches): Try a migration and its rollback on a copy. - [Push, pull, diff and watch](https://aurabase.dev/en/docs/database/sync-schema): Record changes made outside the files. - [Database CLI reference](https://aurabase.dev/en/docs/database/cli): Every option of aura db migration. --- ### Push, pull, diff and watch Source: https://aurabase.dev/en/docs/database/sync-schema.md # Push, pull, diff and watch > Know which way each schema command copies, what it reads and writes, and how to bring changes made in Studio or with SQL back into your migration files. Your schema lives in two places: the migration files of your repository and the database of your project. Four commands of the CLI copy between them, each in one direction. None of them merges: knowing which way each one goes is what keeps the two in line. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - No `DATABASE_URL` in your environment, `.env` or `.env.local`: with it, `push` and the migration commands work on that database instead of the project ([Local development](https://aurabase.dev/en/docs/database/local-development)). The examples create the tables `wf_sync_events` and `wf_sync_watch`, files under `aurabase/` and `types.ts`; the [Clean up](#clean-up) block removes them. `sed` replaces the timestamp of migration file names with `YYYYMMDDHHMMSS`. ## Four commands, four directions | Command | Reads | Writes | Route | | --- | --- | --- | --- | | `aura db push` | `aurabase/migrations/*.sql` | The project: runs the files the ledger does not hold | `POST /v1/db/{project_id}/migrations/run` | | `aura db pull` | The project | `aurabase/schema.sql` (overwritten) | `GET /v1/db/{project_id}/schema/dump` | | `aura db diff [--name ]` | The project and your migration files | A new file `aurabase/migrations/_.sql` (`schema_diff` by default) | `GET …/schema` and `GET …/schema/dump` | | `aura db watch` | `aurabase/migrations` | Runs `push`, then `aura db generate` (`types.ts`), at start and on each change | Both of the above | All four use the `service_role` key of the project and the project of `aurabase.toml`. ## push: files to the project `aura db push` sends each migration file the ledger does not hold, in the order of the file names, and stops at the first failure. Everything about files, order, transactions and failures is in [SQL migrations](https://aurabase.dev/en/docs/database/migrations). Two points matter for syncing: - `push` never reads the project's schema: it trusts the ledger. A table created in Studio is unknown to your files until you capture it with `diff`. - A file edited after it ran is reported `(already applied)` and its change is not applied ([Changing a migration that already ran](https://aurabase.dev/en/docs/database/migrations#edit)). ## pull: the project to one file ```bash verify="pull" aura db pull | tail -n 1 | sed -E 's/\([0-9]+ bytes\)/( bytes)/' grep -E '^(-- Table|CREATE OR REPLACE FUNCTION)' aurabase/schema.sql ``` ```text expect="pull" ✔ Schema exported to aurabase/schema.sql ( bytes) -- Table: org_members -- Table: orgs -- Table: posts -- Table: profiles -- Table: todos CREATE OR REPLACE FUNCTION todo_count(p_user uuid) ``` The file holds enum types, tables, constraints, indexes, row level security, policies, functions and triggers. It leaves out views and materialized views, partitioned tables, `grant` and `revoke`: the view `open_todos` and the `grant execute` on `todo_count` are not in it. [Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema#coverage) lists what the export contains. Use the file as a snapshot to read, review or diff in your repository, not as a migration: `pull` overwrites it each time and `push` does not read it. Without a linked project, `pull` runs `pg_dump --schema-only` on `DATABASE_URL` instead. Your `pg_dump` must match the major version of the server (PostgreSQL 18 on Aurabase); otherwise it prints `pg_dump failed.` with the error of `pg_dump`, and still exits with code 0. ## diff: capture changes made outside the files A table created in Studio, with `aura db raw` or over the direct connection is in the project but in no file. `aura db diff` writes the SQL of what the project has and your files do not: ```bash verify="diff" aura db raw "create table wf_sync_events (id bigint generated always as identity primary key, kind text not null)" aura db diff --name wf_sync_capture | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' grep '^-- TABLE' aurabase/migrations/*_wf_sync_capture.sql ``` ```text expect="diff" ℹ No results (0 rows). » Schema diff (remote → local) • Fetching remote schema... ✔ Migration generated: aurabase/migrations/YYYYMMDDHHMMSS_wf_sync_capture.sql ℹ Review the file, then apply with aura db push -- TABLE: org_members -- TABLE: orgs -- TABLE: posts -- TABLE: profiles -- TABLE: todos -- TABLE: wf_sync_events ``` This project had no migration files yet, so every table is in the file, with its constraints, indexes, row level security and policies. What `diff` detects: | Detected | Not detected | | --- | --- | | A table that no local file creates (its whole DDL) | Functions, triggers and views | | A column of the project that no local file mentions (`add column if not exists`) | Tables and columns dropped in the project | | An index, constraint or policy whose name no local file mentions | A changed type, default or policy body | | An enum type that no local file creates | Grants | The detection reads names in your files as text: a name mentioned anywhere, even in a comment, counts as known. The message says to apply the file with `aura db push`, but on the project it came from, the file re-creates what already exists and fails: ```bash verify="diff-push" needs="diff" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep Error || true ``` ```text expect="diff-push" Error: Migration 'YYYYMMDDHHMMSS_wf_sync_capture.sql' failed: [400] BAD_REQUEST: Invalid request: Migration failed: Invalid request: multiple primary keys for table "org_members" are not allowed ``` Record it as applied instead, without running it: the project already has its content, and a new project will run it from your files. ```bash verify="diff-record" needs="diff" aura db migration repair "$(basename "$(ls aurabase/migrations/*_wf_sync_capture.sql)")" --applied > /dev/null aura db diff ``` ```text expect="diff-record" » Schema diff (remote → local) • Fetching remote schema... ✔ No differences detected — local schema is up to date. ``` A column added later gives a statement that can run on any project, the source included, since it only adds what is missing: ```bash verify="diff-column" needs="diff-record" aura db raw "alter table wf_sync_events add column source text" aura db diff --name wf_sync_source > /dev/null grep -v '^--' aurabase/migrations/*_wf_sync_source.sql | grep . aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_sync_source ``` ```text expect="diff-column" ℹ No results (0 rows). ALTER TABLE "wf_sync_events" ADD COLUMN IF NOT EXISTS "source" TEXT; ✔ YYYYMMDDHHMMSS_wf_sync_source.sql applied ``` Read every generated file before you keep it: it is a starting point, not a verified migration. ## watch: apply on save `aura db watch` runs `aura db push` and `aura db generate` once, then again each time a file is created or changed in `aurabase/migrations`, until you stop it with Ctrl+C. An error is printed and the watch goes on. Here it runs in the background while a new migration is written: ```bash verify="watch" needs="diff-record" aura db watch > watch.log 2>&1 & watcher=$! for i in $(seq 1 60); do grep -q 'Waiting for changes' watch.log && break; sleep 1; done aura db migration new wf_sync_watch > /dev/null echo "create table wf_sync_watch (id bigint generated always as identity primary key);" > "$(ls aurabase/migrations/*_wf_sync_watch.sql)" for i in $(seq 1 60); do grep -q 'wf_sync_watch.sql applied' watch.log && break; sleep 1; done { kill "$watcher" && wait "$watcher"; } 2>/dev/null || true grep -E 'Watcher mode|types.ts generated|Waiting for changes|Change detected|wf_sync_watch.sql applied' watch.log \ | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | awk '!seen[$0]++' ``` ```text expect="watch" » Watcher mode enabled: watching migrations... ✔ types.ts generated from API! ℹ Waiting for changes in 'aurabase/migrations' (Ctrl+C to stop)... Change detected, updating... ✔ YYYYMMDDHHMMSS_wf_sync_watch.sql applied ``` Each save is a push. A file saved half written is applied as it is; if you then complete it, the new content is skipped as `(already applied)` ([Changing a migration that already ran](https://aurabase.dev/en/docs/database/migrations#edit)). Write the whole file before saving it, or keep `watch` for a test project or a [branch](https://aurabase.dev/en/docs/database/branches). A single save often triggers several pushes; the ones after the first find nothing new. `watch` writes `types.ts` in the current folder; [Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types) writes it where you choose. ## A workflow that keeps them in line 1. Make schema changes in migration files, and apply them with `aura db push` (or `watch` on a test project). 2. When someone changes the schema in Studio or with SQL, run `aura db diff --name `, read the file, keep it, and record it with `aura db migration repair --applied`. 3. Commit the files. In CI, `aura db push` applies them to each environment ([Apply migrations from CI](https://aurabase.dev/en/docs/database/migrations#ci)). 4. Run `aura db pull` when you want a readable snapshot of the whole schema, then regenerate types. ## Result ```bash verify="result" needs="diff-column" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' ``` ```text expect="result" » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ YYYYMMDDHHMMSS_wf_sync_capture.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_sync_source.sql APPLIED 2026-11-23 10:00:00.000000+00 YYYYMMDDHHMMSS_wf_sync_watch.sql APPLIED 2026-11-23 10:00:00.000000+00 ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `multiple primary keys for table "…" are not allowed` after `diff` | The generated file was pushed to the project it was generated from. | `aura db migration repair --applied`, then delete what you do not want to keep. | | `No remote tables found.` | `diff` on a project without tables. | Nothing to capture. | | `pg_dump failed.` with a version mismatch | `pull` without a linked project, with an older `pg_dump`. | Install the client of the server's major version, or link the project. | | `API failed to export schema (…)` | `pull` was refused by the project, for example with an anon key. | Use the `service_role` key. | | `Push error: …` in the watch output | A file failed while watching; the watch goes on. | Fix the file and save it again. | | `No project linked. Run 'aura link' first (or 'aura init').` | `diff` outside a linked folder. | `aura link `. | ## Clean up ```bash verify="clean-up" needs="diff" aura db raw "drop table if exists wf_sync_events; drop table if exists wf_sync_watch" for f in aurabase/migrations/*_wf_sync_*.sql; do aura db migration repair "$(basename "$f")" --reverted > /dev/null; done rm -rf aurabase watch.log types.ts aura db status ``` ```text expect="clean-up" ℹ No results (0 rows). » Migration Status - Project 11111111-2222-4333-8444-555555555555 ℹ No migrations found, local or applied. Create one with aura db migration new . ``` ## See also - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): Files, order, transactions and the ledger. - [Roll back and repair migrations](https://aurabase.dev/en/docs/database/rollback-migrations): Undo a migration, fix the ledger. - [Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema): What the schema export contains and leaves out. - [Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types): Types that follow the schema. --- ### Seed a project with test data Source: https://aurabase.dev/en/docs/database/seed.md # Seed a project with test data > Fill a test project, a branch or a local database with the same data every time, from a file in your repository, without duplicates and without half-loaded data. A seed is the data a fresh project needs to be usable: reference rows, demo content, test users. Keep it in `aurabase/seed.sql` next to your migrations and load it after them. This page is about your own data; the example schema used across this documentation has its own command, `aura db seed --example docs` ([Example schema](https://aurabase.dev/en/docs/database/example-schema)). ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). Seed a test project or a [branch](https://aurabase.dev/en/docs/database/branches), never production. The examples create the table `wf_seed_projects`, the file `aurabase/seed.sql` and two users of the project; the [Clean up](#clean-up) block removes them. ```bash verify="table" aura db raw "create table wf_seed_projects ( id bigint generated always as identity primary key, slug text not null unique, name text not null, owner uuid)" ``` ```text expect="table" ℹ No results (0 rows). ``` ## Which command loads the file | Command | Runs `aurabase/seed.sql` on | Works on a linked project | | --- | --- | --- | | `aura db raw -f aurabase/seed.sql` | The linked project, through the SQL API, in one transaction | Yes, with the `service_role` key | | `aura db seed` | The database of `DATABASE_URL` only | No: it fails with `No database configured`, even when a project is linked | | `aura db seed --example docs` | The linked project (or `DATABASE_URL` without a link) | Yes; it installs the example schema, not your file | `aura db seed` ignores the linked project and looks for `DATABASE_URL`: ```bash verify="seed-linked" needs="table" mkdir -p aurabase echo "select 1;" > aurabase/seed.sql aura db seed 2>&1 || echo "exit code $?" ``` ```text expect="seed-linked" » Seeding database... Error: No database configured. Link a project with 'aura link' (commands will use the API), or set DATABASE_URL (environment variable or .env) for a local database. exit code 1 ``` On a linked project, use `aura db raw -f`. `aura db seed` remains the command for a local database ([Local development](https://aurabase.dev/en/docs/database/local-development)). ## Write a seed file you can run twice A seed runs again on every new branch, on every reset of a test project, and by mistake. Make each statement a no-op when its rows are already there: give the rows a natural key with a unique constraint and use `on conflict do nothing`, or insert with `where not exists`. Do not insert values into an identity column: let it number the rows. ```bash verify="write" needs="table" cat > aurabase/seed.sql <<'SQL' -- Reference data: safe to run again insert into wf_seed_projects (slug, name) values ('website', 'Website'), ('mobile-app', 'Mobile app'), ('internal', 'Internal tools') on conflict (slug) do nothing; SQL ``` ## Load it ```bash verify="load" needs="write" aura db raw -f aurabase/seed.sql aura db raw -f aurabase/seed.sql aura db raw "select slug, name from wf_seed_projects order by id" ``` ```text expect="load" ℹ No results (0 rows). ℹ No results (0 rows). name │ slug ───────────────┼─────────── Website │ website Mobile app │ mobile-app Internal tools │ internal ℹ 3 row(s). ``` Twice the file, three rows. (`aura db raw` prints columns in alphabetical order.) `aura db raw -f` sends the whole file as one request: it counts once against the SQL quota of the project (60 requests per minute on the Free plan by default) and follows the rules of [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): no `copy`, no `do` blocks, no `set_config`. ## A failing seed leaves nothing The file runs in one transaction. If a statement fails, the statements before it are rolled back too: ```bash verify="atomic" needs="load" cat > aurabase/seed-broken.sql <<'SQL' insert into wf_seed_projects (slug, name) values ('billing', 'Billing'); insert into wf_seed_projects (slug, name) values ('no-name', null); SQL aura db raw -f aurabase/seed-broken.sql 2>&1 || echo "exit code $?" aura db raw "select count(*) as projects from wf_seed_projects" ``` ```text expect="atomic" Error: [400] BAD_REQUEST: Invalid request: null value in column "name" of relation "wf_seed_projects" violates not-null constraint exit code 1 projects ──────── 3 ℹ 1 row(s). ``` `billing` was not kept. Fix the file and run it again: there is no partial state to clean. ## Rows that belong to users Rows owned by a user need a real user id: the users of a project live in its Auth schema, which SQL cannot write. Create the users with the CLI first, then use their ids in the seed. `--json` prints the user, id included; `-p` passes it to `aura db raw` as a text parameter, hence the cast `$1::uuid`: ```bash verify="users" needs="load" for name in alice bob; do aura auth users create --email "wf-seed-$name@example.com" --password 'correct-horse-battery-9' --json \ | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).id' > "aurabase/.user-$name" done aura db raw "update wf_seed_projects set owner = \$1::uuid where slug in ('website', 'internal')" -p "$(cat aurabase/.user-alice)" aura db raw "update wf_seed_projects set owner = \$1::uuid where slug = 'mobile-app'" -p "$(cat aurabase/.user-bob)" aura db raw "select slug, owner is not null as owned from wf_seed_projects order by id" ``` ```text expect="users" ℹ No results (0 rows). ℹ No results (0 rows). owned │ slug ──────┼─────────── true │ website true │ mobile-app true │ internal ℹ 3 row(s). ``` - Creating a user twice fails with `[409] CONFLICT: Conflict: This email is already in use.`: look the user up with `aura auth users list` instead. - Users created this way are not confirmed (`email_verified: false`). With email confirmation required, the default of a project, they cannot sign in: `signInWithPassword` answers `EMAIL_NOT_CONFIRMED`. On a test project, turn confirmation off with `aura auth settings set email_confirmation_required=false`. - A [branch](https://aurabase.dev/en/docs/database/branches) copies the rows of its source but not its users: the owner ids of the copied rows point to no user of the branch. Create the users on the branch and seed again. ## Order and size - **After the migrations.** The seed needs the tables: run `aura db push`, then `aura db raw -f aurabase/seed.sql`. Keep the seed out of `aurabase/migrations`: a migration runs once per project, a seed whenever you need fresh data. - **Several files.** Split a large seed into files that you load in a fixed order, one `aura db raw -f` each; each file is its own transaction. - **Large volumes.** Every request through the gateway is limited by a statement timeout ([Statement timeouts](https://aurabase.dev/en/docs/database/connection-pooling#timeouts)). For more than a few thousand rows, split the inserts into several files, or load the data with `psql` over the direct connection ([Connect to your database](https://aurabase.dev/en/docs/database/connect)). - **Generated data.** `insert … select … from generate_series(1, 1000)` builds many rows in one statement. ## Result ```bash verify="result" needs="users" aura db raw "select count(*) as projects, count(distinct owner) as owners from wf_seed_projects" ``` ```text expect="result" owners │ projects ───────┼───────── 2 │ 3 ℹ 1 row(s). ``` ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `No database configured. Link a project with 'aura link' (commands will use the API), or set DATABASE_URL …` | `aura db seed` on a linked project: it only uses `DATABASE_URL`. | `aura db raw -f aurabase/seed.sql`. | | `Seed file 'aurabase/seed.sql' not found. Create 'aurabase/seed.sql' first.` | `aura db seed` without the file. | Create the file, or pass `--example docs` for the example schema. | | `duplicate key value violates unique constraint …` | The seed ran twice without `on conflict do nothing`. | Make each insert a no-op when the row exists. | | `cannot insert a non-DEFAULT value into column "id"` | The seed sets a `generated always` identity column. | Leave the column out. | | `AURABASE_SERVICE_ROLE_KEY is not set.` | `aura db raw` or `aura db seed --example docs` without the key. | Export the `service_role` key of the project. | | `[409] CONFLICT: Conflict: This email is already in use.` | The test user exists. | Reuse it: `aura auth users list`. | ## Clean up ```bash verify="clean-up" needs="table" for name in alice bob; do if [ -f "aurabase/.user-$name" ]; then aura auth users delete "$(cat "aurabase/.user-$name")" --force > /dev/null; fi done aura db raw "drop table wf_seed_projects" rm -rf aurabase ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Example schema](https://aurabase.dev/en/docs/database/example-schema): The schema and rows used across this documentation. - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): Create the tables before you seed them. - [Database branches](https://aurabase.dev/en/docs/database/branches): A copy of a project, rows included. - [Run SQL from the CLI or a server](https://aurabase.dev/en/docs/database/run-sql): The rules of aura db raw -f. --- ### Generate TypeScript types from your database Source: https://aurabase.dev/en/docs/database/generate-types.md # Generate TypeScript types from your database > One command turns your tables into types. Your editor then rejects a wrong column or a wrong value before you run anything. Your tables, views, functions and enums become one TypeScript type, `Database`. Passed to `createClient`, it lets the compiler reject a wrong table, column or value before you run anything. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - Node.js 20 or later for `@aurabase/gen`. Reading the schema requires the `service_role` key: run the generators on your machine or in CI, never in a browser. The examples write `types.ts`, `models.rs` and `src/types/`; the [Clean up](#clean-up) block removes them. ## Generate the file `@aurabase/gen` is the generator to use in an application. With version 0.7.5, create the output folder first: the published package does not create it and fails with `ENOENT: no such file or directory`. ```bash filename="terminal" mkdir -p src/types npx @aurabase/gen --url "$NEXT_PUBLIC_AURABASE_URL" --key "$AURABASE_SERVICE_ROLE_KEY" --out src/types/database.types.ts ``` On the example schema it prints (measured with `@aurabase/gen` 0.7.5, not replayed by this page): ```text [aurabase-gen] ✓ Types written to src/types/database.types.ts (5 table(s), 1 function(s), 0 enum(s), 1 view(s)). ``` Run it again whenever the schema changes, for example after each `aura db push`. ## Options | Option | Environment variable | Default | Effect | | --- | --- | --- | --- | | `--url ` | `NEXT_PUBLIC_AURABASE_URL` | | URL of the project | | `--key ` | `AURABASE_SERVICE_ROLE_KEY` | | `service_role` key. An `aura_anon_` or `aura_auth_` key is refused before any request. | | `-o`, `--out ` | `AURABASE_TYPES_OUT` | Standard output | File to write | | `-s`, `--schema ` | `AURABASE_SCHEMA` | `public` | Name of the schema key inside `Database` (`Database['public']`) | | `-t`, `--type-name ` | | `Database` | Name of the main type | | `--numeric-as-string` | | Off | `numeric` and `decimal` become `string` instead of `number`, to keep their precision | | `--allow-empty` | | Off | Write the file even if a table has no column (a MongoDB project); without it, the command fails | | `--check` | | Off | Compare with the `--out` file instead of writing it ([Check the types in CI](#ci)) | | `-h`, `--help`, `-v`, `--version` | | | Help and version | Without `--url` and `--key`, the variables are read from the environment, then from `.env.local`, `.env.development.local`, `.env.development` and `.env` in the current folder, in this order; a variable already set wins. ## With the CLI or the API `aura db generate` asks the project for its types (`GET /v1/db/{project_id}/types.ts`) and writes them to `types.ts` in the current folder: ```bash verify="cli" aura db generate > /dev/null sed -n '/^ todos: {/,/^ Relationships/p' types.ts ``` ```text expect="cli" todos: { Row: { id: number; user_id: string; title: string; done: boolean; created_at: string; }; Insert: { id?: number; user_id: string; title: string; done?: boolean; created_at?: string; }; Update: { id?: number; user_id?: string; title?: string; done?: boolean; created_at?: string; }; Relationships: []; ``` The route can be called directly with the `service_role` key; the anon key is refused: ```bash verify="api" curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -c '^export' curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/types.ts" -H "apikey: $AURABASE_ANON_KEY" | node -pe 'JSON.parse(require("fs").readFileSync(0, "utf8")).error.message' ``` ```text expect="api" 26 Forbidden: DDL operation is reserved to the service_role role ``` `aura db generate --lang rust` writes `models.rs`, one struct per table, from the same schema; nullable columns become `Option<…>` and enums become Rust enums: ```bash verify="rust" aura db generate --lang rust > /dev/null sed -n '/^pub struct Todos/,/^}/p' models.rs ``` ```text expect="rust" pub struct Todos { pub id: i64, pub user_id: String, pub title: String, pub done: bool, pub created_at: String, } ``` | | `@aurabase/gen` | `aura db generate` | | --- | --- | --- | | Output | The file you choose, or standard output | `types.ts` in the current folder | | `Database` type | Same tables, views, functions and enums | Same | | Helpers | `Tables`, `TablesInsert`, `TablesUpdate`, `Enums` | `Tables`, `TablesInsert`, `TablesUpdate`, an interface per table (`Todos`, `TodosInsert`…), `TableName` | | Options | All the options above | `--lang ts` (default) or `rust` | | Drift check | `--check` | None | Without a linked project, `aura db generate` reads the database of `DATABASE_URL` with a simpler generator ([Local development](https://aurabase.dev/en/docs/database/local-development#local)). `aura db watch` regenerates `types.ts` after each push ([Push, pull, diff and watch](https://aurabase.dev/en/docs/database/sync-schema#watch)). ## What the file contains | Part of `Database['public']` | From | Contents | | --- | --- | --- | | `Tables` | Each table | `Row` (a read row), `Insert` (optional when the column has a default, is nullable or is an identity), `Update` (all optional), `Relationships` (foreign keys) | | `Views` | Each view | `Row` only, every column nullable | | `Functions` | Each function | `Args` (argument names and types) and `Returns`; a `returns table (…)` function gives an array of rows | | `Enums` | Each enum type | The union of its values, such as `'todo' \| 'doing' \| 'done'` | | `CompositeTypes` | | Always empty | Types follow the JSON the API returns: integers and `float` give `number`, `numeric` gives `number` (or `string` with `--numeric-as-string`), `uuid`, dates and timestamps give `string`, `json` and `jsonb` give `Json`, arrays give arrays, `bigint` gives `number`. ## Use it with the client Excerpt of `src/lib/aurabase.ts`: ```typescript filename="src/lib/aurabase.ts" import { createClient } from '@aurabase/aurabase-js' import type { Database } from '../types/database.types' export const aura = createClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!) ``` ## Row types for your components ```typescript filename="Todo.tsx" import type { Tables, TablesInsert, TablesUpdate, Enums } from '../types/database.types' type Todo = Tables<'todos'> // a row, as read type NewTodo = TablesInsert<'todos'> // what insert() accepts type TodoPatch = TablesUpdate<'todos'> // what update() accepts ``` `Tables<'open_todos'>` gives the row of a view, and `Enums<'name'>` the values of an enum. ## What is checked Checked with TypeScript 5.9.3, `@aurabase/aurabase-js` 0.7.5 and a file generated from the example schema (not replayed by this page): ```typescript filename="checked.ts" const { data } = await aura.from('todos').select('id, title, done') const title: string | undefined = data?.[0]?.title // ok const wrong: number | undefined = data?.[0]?.title // error: string is not assignable to number await aura.from('todos').insert({ title: 1 }) // error: number is not assignable to string await aura.from('todos').insert({ title: 'ok', user_id: userId }) // ok: the other columns have defaults await aura.from('todos').update({ done: 'yes' }) // error: string is not assignable to boolean await aura.from('todos').select('id').eq('done', 'no') // error: string is not assignable to boolean await aura.from('anything').select('id') // error: no overload matches this call await aura.from('open_todos').insert({ title: 'x' }) // error: a view has no Insert type const typo = await aura.from('todos').select('id, titel') typo.data?.[0]?.id // error: column 'titel' does not exist on 'todos' ``` - **Tables and views.** A name that is not in the file is rejected. A view can be read, not written. - **Columns in `select('…')`.** The string is parsed: a misspelled column turns the row type into an error that names the column, as soon as you use the row. - **Values.** `insert()`, `update()` and filters such as `eq()` are checked against the column types. In `Insert`, a column without a default that is not nullable is required: `todos.user_id` here. - **Relationships.** An embed such as `select('role, orgs(name)')` is typed from `Relationships`. - **Functions.** `aura.rpc()` does not use the `Functions` part of the file: its arguments are not checked and its `data` is `unknown`. Type the result yourself. - **Freshness.** The file describes the schema at the time you generated it: regenerate it after each migration, and check it in CI. ## Check the types in CI `--check` regenerates the file in memory and compares it with `--out`. It exits with `0` and `[aurabase-gen] ✓ src/types/database.types.ts is up to date.` when they match, and with `1` and `[aurabase-gen] Types in src/types/database.types.ts are out of date. Re-run aurabase-gen without --check.` when the schema changed and the committed file was not regenerated. Excerpt of a CI step (not replayed here): ```yaml filename=".github/workflows/types.yml" - run: npx @aurabase/gen@0.7.5 --check --out src/types/database.types.ts env: NEXT_PUBLIC_AURABASE_URL: ${{ vars.PROJECT_URL }} AURABASE_SERVICE_ROLE_KEY: ${{ secrets.SERVICE_ROLE_KEY }} ``` Run it after `aura db push` in the same job, so that the types are compared with the migrated schema. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `[aurabase-gen] ENOENT: no such file or directory, open '…'` | The folder of `--out` does not exist (`@aurabase/gen` 0.7.5). | `mkdir -p` the folder first. | | `[aurabase-gen] Error: the project URL and/or service_role key is missing.` | Neither the options nor the variables are set. | Pass `--url` and `--key`, or set the variables. | | `[aurabase-gen] Error: schema introspection requires a service_role key (aura_sk_...), not an anon/auth key.` | An anon or authenticated key was passed. | Use the `service_role` key. | | `[aurabase-gen] Types in … are out of date. Re-run aurabase-gen without --check.` | The schema changed since the file was generated. | Regenerate and commit the file. | | `[aurabase-gen] Tables without any column: … Use --allow-empty to generate anyway.` | A MongoDB project, whose collections have no declared columns. | Add `--allow-empty`, knowing these types check nothing. | | `API failed to generate types (403 Forbidden): …` | `aura db generate` with a key that is not `service_role`. | Export the `service_role` key. | ## Clean up ```bash verify="clean-up" rm -f types.ts models.rs rm -rf src/types ``` ## See also - [Query data with the SDK](https://aurabase.dev/en/docs/database/query-with-sdk): The queries these types check. - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): Regenerate the types after each migration. - [Read and export your schema](https://aurabase.dev/en/docs/database/inspect-schema): The schema the generators read. - [Call functions with rpc()](https://aurabase.dev/en/docs/database/rpc): Functions, whose results you type yourself. --- ### Database branches Source: https://aurabase.dev/en/docs/database/branches.md # Database branches > Create a copy of a project for a pull request or a risky change, run your migrations there first, and understand what a branch copies, what it costs and when it disappears. A branch is a new project made from a copy of an existing PostgreSQL project. It has its own URL, API keys and database, so a migration, a policy or a preview deployment can be tried on it without touching the source. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). - `aura login`: the `aura branch` commands use your account, not a project key. Creating or deleting a branch takes the `developer` role in the organization; listing takes `viewer`. The examples apply a migration `wf_br_base` to the project, create the branch `wf-br-review` and the tables `wf_br_items` and `wf_br_notes`, and write `branch.json` and a folder `branch-work`; the [Clean up](#clean-up) block removes them. `sed` replaces the timestamp of migration file names with `YYYYMMDDHHMMSS`. ```bash verify="setup" aura db migration new wf_br_base > /dev/null echo "create table wf_br_items (id bigint generated always as identity primary key, name text not null);" > "$(ls aurabase/migrations/*_wf_br_base.sql)" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_br aura db raw "insert into wf_br_items (name) values ('first'), ('second')" ``` ```text expect="setup" ✔ YYYYMMDDHHMMSS_wf_br_base.sql applied ℹ No results (0 rows). ``` ## What a branch is | Question | Answer | | --- | --- | | Copy or replica? | A **copy made at creation**. The source is read in one consistent snapshot and copied; nothing flows between them afterwards. | | What is copied? | Schema (tables, constraints, indexes, enum types, sequences and their values), row level security and policies, functions, triggers, views and materialized views, the privileges of tables and functions, and the rows unless you ask for the schema only (`--no-data`). | | What is not? | Auth users, sessions and settings; storage buckets and objects; edge functions, secrets, environment variables and cron jobs; Realtime settings of tables; comments; column privileges; GraphQL activation. The ledger of migrations starts empty ([see below](#migrate)). | | How long does it live? | 72 hours by default, from 1 hour to 30 days (`--ttl 1h` to `--ttl 30d`). An expired branch and a failed one are deleted automatically, checked every 30 seconds. | | What does it cost? | The copy takes time in proportion to the data: on the local test stack, 14 rows took under a second. A branch counts against the active branches of your organization (`max_branches`: 1 on Free, 10 on Pro, 25 on Team, 2,147,483,647 on Enterprise), not against its projects. | | Size limit | A branch with rows is refused above 2 GiB of data by default, and a copy stops after 30 minutes. `--no-data` has no size limit. | | Which projects? | PostgreSQL projects that are active and not hibernated. A branch cannot be branched. | A branch is not a backup and not a staging environment kept in sync: create it when you need it, and delete it when the change is merged. ## Create a branch `aura branch create ` copies the linked project (or `--from `) and waits until the branch is ready, 15 minutes at most by default (`--timeout`). `--json` prints what a script needs, keys included; this example stores it in a file and prints everything but the keys: ```bash verify="create" needs="setup" aura branch create wf-br-review --ttl 2h --json > branch.json node -e 'const b = JSON.parse(require("fs").readFileSync("branch.json", "utf8")) console.log(b.branch, b.state, b.status, b.parent_project_id === process.env.PROJECT_ID ? "(copy of this project)" : "") console.log(Object.keys(b).sort().join(", "))' ``` ```text expect="create" wf-br-review ready active (copy of this project) anon_key, branch, expires_at, id, parent_project_id, service_role_key, slug, state, status, url ``` The keys are shown once, as for a new project: keep `branch.json` out of version control, and store the keys as secrets of your CI or preview deployment. Without `--json`, the command prints a summary, the URL and the keys. `--no-wait` returns at once with the state `provisioning`; follow it with `aura branch list` (`provisioning`, then `cloning`, then `ready` or `failed`). Names use letters, digits, `.`, `_`, `-` and `/`, up to 63 characters, start with a letter or a digit, and are unique among the live branches of a project, whatever the case. The branch project is named `/`. ## What was copied `aura branch list` shows the branches of the linked project (`--all` for every branch of the organization, `--json` for scripts). The JSON holds the report of the copy: ```bash verify="contents" needs="create" aura branch list --json | node -e 'for (const b of JSON.parse(require("fs").readFileSync(0, "utf8"))) { const r = b.report console.log(b.name, b.state, b.with_data ? "with rows" : "schema only") console.log(`${r.tables} tables, ${r.rows} rows, ${r.views} view, ${r.functions} function, ${r.policies} policies, ${r.triggers} triggers`) for (const x of r.not_cloned) console.log("not cloned:", x) }' ``` ```text expect="contents" wf-br-review ready with rows 6 tables, 13 rows, 1 view, 1 function, 2 policies, 0 triggers not cloned: auth users, sessions and auth settings not cloned: storage buckets and objects not cloned: edge functions, secrets, environment variables, cron jobs not cloned: realtime table settings not cloned: table and column comments (including pg_graphql directives) not cloned: column-level privileges not cloned: pg_graphql activation (run `aura projects graphql-enable` on the branch) ``` The rows are the source's, personal data included: there is no anonymization. Branch a staging project rather than production when the copy must not hold real data. Rows owned by users point to no user of the branch, since users are not copied: create test users on the branch ([Seed a project with test data](https://aurabase.dev/en/docs/database/seed#users)). ## Try a migration on the branch A branch is a project: link a folder to it and use the usual commands with its `service_role` key. This example writes the `aurabase.toml` of the branch from `branch.json` in a separate folder, with a copy of the migrations: ```bash verify="ledger" needs="create" mkdir -p branch-work && cp -r aurabase branch-work/ node -e 'const b = JSON.parse(require("fs").readFileSync("branch.json", "utf8")) console.log(`[project]\nname = "branch"\nproject_id = "${b.id}"\nproject_url = "${b.url}"`)' > branch-work/aurabase.toml cd branch-work export AURABASE_SERVICE_ROLE_KEY=$(node -pe 'JSON.parse(require("fs").readFileSync("../branch.json", "utf8")).service_role_key') aura db raw "select count(*) as items from wf_br_items" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_br ``` ```text expect="ledger" items ───── 2 ℹ 1 row(s). YYYYMMDDHHMMSS_wf_br_base.sql PENDING - ``` The table and its rows were copied, but the **ledger of migrations is empty**: the branch does not know that `wf_br_base` ran. A plain `aura db push` would run it again and fail with `relation "wf_br_items" already exists`. Record the migrations the source already ran, then push the new one: ```bash verify="try" needs="ledger" cd branch-work export AURABASE_SERVICE_ROLE_KEY=$(node -pe 'JSON.parse(require("fs").readFileSync("../branch.json", "utf8")).service_role_key') for f in aurabase/migrations/*.sql; do aura db migration repair "$(basename "$f")" --applied > /dev/null; done aura db migration new wf_br_notes > /dev/null echo "create table wf_br_notes (id bigint generated always as identity primary key, item_id bigint references wf_br_items (id));" > "$(ls aurabase/migrations/*_wf_br_notes.sql)" aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_br ``` ```text expect="try" ℹ YYYYMMDDHHMMSS_wf_br_base.sql (already applied) ✔ YYYYMMDDHHMMSS_wf_br_notes.sql applied ``` The source project did not change: ```bash verify="parent" needs="try" aura db table list | grep -c 'wf_br_notes' || true ``` ```text expect="parent" 0 ``` When the migration works on the branch, add it to your migrations and apply it to the source with `aura db push`, from your usual folder. To run this in CI for each pull request, see [Preview databases per pull request](https://aurabase.dev/en/docs/deployment/preview-envs). ## Limits and refusals The limit counts the live branches of the organization; a branch whose creation failed does not count. Past it, and from a branch, creation is refused at once: ```bash verify="limits" needs="create" aura branch create wf-br-second --no-wait 2>&1 | grep Error || true branch_id=$(node -pe 'JSON.parse(require("fs").readFileSync("branch.json", "utf8")).id') aura branch create wf-br-nested --from "$branch_id" --no-wait 2>&1 | grep Error || true ``` ```text expect="limits" Error: [403] BRANCH_LIMIT_REACHED: Your plan free allows 1 active branch(es) per organization. You already have 1. Delete one with `aura branch delete`, or wait for its TTL. Error: [400] BRANCH_OF_BRANCH: A branch cannot be branched: create the branch from its parent project ``` The copy also refuses a source that it cannot reproduce in full, within seconds of the creation, and deletes the branch project. Measured with a partitioned table in the source: ```text Error: The branch could not be created: This project uses objects that a branch cannot reproduce yet: partitioned table "wf_br_events", partitioned table "wf_br_events_2026". A branch would be incomplete, so it is refused. Nothing was left behind: the branch project is removed automatically. ``` | Refused | Message starts with | | --- | --- | | Partitioned and inherited tables, foreign tables, domains, composite and range types, aggregate and window functions, rewrite rules, foreign keys to another schema | `This project uses objects that a branch cannot reproduce yet: …` | | Extensions other than those every project has | `The source project uses extension(s) the branch database does not have: …` | | More than 2 GiB of data with rows | `This project holds about … MB of data, the limit for a branch with data is … MB. Create the branch with --no-data (schema only), or reduce the large tables.` | | A source that is paused, provisioning or hibernated | `[409] SOURCE_NOT_ACTIVE` | | A MongoDB project | `[400] BRANCH_SOURCE_UNSUPPORTED` | A failed branch stays in `aura branch list` for 24 hours with its message, then disappears. The schema of the source is read just before the copy: do not change it while a branch is being created. ## Delete a branch ```bash verify="delete" needs="create" aura branch delete wf-br-review --force aura branch list ``` ```text expect="delete" ✔ Branch 'wf-br-review' deleted (its database is being removed). » Branches ℹ No branches. • Create one with aura branch create ``` Without `--force`, the command asks for confirmation, and fails in a script (`Cannot ask for confirmation: not a terminal. Pass --force instead.`). Deleting a branch deletes its database; it cannot be undone. A branch you forget is deleted at the end of its time to live. ## In Studio The **Branches** page of a project creates a branch (name, time to live in hours, schema only), lists the branches with their state, expiry and project id, deletes them, and shows the recent failures. On a branch, the page says that it cannot be branched again. ## Result ```bash verify="result" needs="delete" aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/' | grep wf_br aura db table list | grep wf_br ``` ```text expect="result" YYYYMMDDHHMMSS_wf_br_base.sql APPLIED 2026-11-23 10:00:00.000000+00 • wf_br_items [RLS] ``` The project kept its own migration and table; `wf_br_notes` existed on the branch only. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `[403] BRANCH_LIMIT_REACHED: Your plan … allows N active branch(es) per organization.` | The organization has as many live branches as its plan allows. | Delete one, or wait for its time to live. | | `[400] BRANCH_OF_BRANCH` | `--from` names a branch. | Branch its parent project. | | `[400] INVALID_BRANCH_NAME: invalid branch name: …` | Spaces or other characters, more than 63 characters, `//`, `..`, or a final `/` or `.`. | Use letters, digits, `.`, `_`, `-`, `/`. | | `[409] BRANCH_NAME_TAKEN` | A live branch of the project has that name. | Pick another name or delete the old branch. | | `Invalid --ttl '…': a branch lives between 1h and 720h (30d)` | The time to live is out of bounds. | Use `1h` to `30d`. | | `Invalid --ttl '…': the unit must be h, d or w (e.g. 72h, 3d, 2w)` | Minutes or another unit. | Use hours, days or weeks. | | `relation "…" already exists` on `aura db push` to a branch | The branch's ledger is empty. | `aura db migration repair --applied` for the migrations the source already ran. | | A `400 BAD_REQUEST` in French saying that the third segment of the path does not match the project served by the host | `NEXT_PUBLIC_AURABASE_URL` (environment or `.env`) still points to the source while `aurabase.toml` names the branch; the variable wins. | Set it to the branch URL, or unset it. | | `Timed out after 900s: the branch is still being created.` | The copy takes longer than `--timeout`. | Follow it with `aura branch list`; raise `--timeout`. | | `No active branch named '…' for project …` | `aura branch delete` with a wrong name, or a branch already deleted. | `aura branch list`. | ## Clean up ```bash verify="clean-up" needs="setup" aura branch delete wf-br-review --force > /dev/null 2>&1 || true aura db raw "drop table if exists wf_br_items" for f in aurabase/migrations/*_wf_br_*.sql; do aura db migration repair "$(basename "$f")" --reverted > /dev/null; done rm -rf aurabase/migrations branch-work branch.json ``` ```text expect="clean-up" ℹ No results (0 rows). ``` ## See also - [Preview databases per pull request](https://aurabase.dev/en/docs/deployment/preview-envs): A branch per pull request, from CI. - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): Apply the migration to the source once it works. - [Local development and test databases](https://aurabase.dev/en/docs/database/local-development): Branches, test projects and local PostgreSQL compared. - [Deployment](https://aurabase.dev/en/docs/deployment#branches): Environments, CI and database branches. --- ### Local development and test databases Source: https://aurabase.dev/en/docs/database/local-development.md # Local development and test databases > Pick where you develop and test your schema, see what changes when the CLI works on a local PostgreSQL instead of a project, and start over from a clean database. Aurabase does not ship a local emulator of a project. You develop against a project (a test project, or a branch of your main one), or against a PostgreSQL on your machine for quick SQL iterations, knowing what it lacks. This page helps you choose, and shows what the CLI does in each case. ## Prerequisites - A linked project: `aura link `. - The example schema, installed with the service role key of the project: ```bash export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docs ``` It creates `profiles`, `orgs`, `org_members`, `posts`, `todos`, the view `open_todos` and the function `todo_count(p_user uuid)`. See [Example schema](https://aurabase.dev/en/docs/database/example-schema). The replayed examples write a migration file `wf_local_probe` and remove it in [Clean up](#clean-up); the local PostgreSQL examples are outputs measured on a PostgreSQL 18 container and are not replayed by this page. ## Where to develop | | A test project | A branch | A local PostgreSQL (`DATABASE_URL`) | | --- | --- | --- | --- | | Same behavior as production (RLS by default, `auth.uid()`, roles, API, Realtime) | Yes | Yes | No ([what it lacks](#differences)) | | SDK, REST API and Auth work | Yes | Yes | No: only SQL | | Starts from | Empty; push migrations and seed | A copy of the source, rows included unless `--no-data` | Empty | | Lifetime | Until you delete it | 1 hour to 30 days (72 hours by default) | Yours | | Counts against | Projects of your plan | Branches of your plan (1 on Free) | Nothing | | Start over | Drop your objects, or delete and create the project | Delete it, create a new one | Drop and create the database | Use a test project or a branch for anything that involves policies, users or the SDK. A local PostgreSQL suits plain SQL work: writing a migration, checking a query plan, running a seed. ## A test project per developer Each developer, and each CI pipeline, can have its own project. Excerpt of the commands (not replayed here): ```bash aura projects create my-app-alice --json > project.json # prints the keys once: keep them aura link export AURABASE_SERVICE_ROLE_KEY=aura_sk_… # the service_role key from project.json aura auth settings set email_confirmation_required=false # test project only aura db push # your migrations aura db raw -f aurabase/seed.sql # your seed ``` On a test project, email confirmation can be turned off so that test users sign in at once; a project requires it by default. For a copy of real data, or a short-lived database per pull request, create a [branch](https://aurabase.dev/en/docs/database/branches) instead. ## How DATABASE_URL changes the CLI The CLI loads `.env.local` and `.env` from the current folder at start. When `DATABASE_URL` is set, in the environment or in one of these files, the migration commands work on that database, **even when a project is linked**: | Command | Linked project, no `DATABASE_URL` | `DATABASE_URL` set | | --- | --- | --- | | `aura db push` | The project, through the API | That database, then each file is also sent to the project if one is linked | | `aura db migration down`, `aura db migration repair` | The project's ledger | A table `_aura_cli_migrations` in that database | | `aura db status` | The project's ledger | The project's ledger if one is linked, `_aura_cli_migrations` otherwise | | `aura db seed` (your `seed.sql`) | Fails: `No database configured` | That database | | `aura db reset` | Fails ([see below](#reset)) | Fails | | `aura db generate` | The project (`types.ts`) | The project; `DATABASE_URL` is only used without a link | | `aura db pull` | The project | The project; `pg_dump` on `DATABASE_URL` only without a link | Many applications keep a `DATABASE_URL` in `.env` for their ORM. In such a folder, `aura db push` leaves your project alone and tries that database: ```bash verify="database-url" mkdir -p aurabase/migrations echo "select 1;" > aurabase/migrations/20261201000000_wf_local_probe.sql DATABASE_URL=postgresql://dev@127.0.0.1:1/app aura db push 2>&1 || echo "exit code $?" ``` ```text expect="database-url" » Applying migrations... Error: PostgreSQL unreachable at postgresql://dev@127.0.0.1:1/app. Run aura start first. exit code 1 ``` Rename the variable of your ORM, or run the CLI from a folder without it, when you mean the project. Without a linked project, the local database is used in its `public` schema; with one, in a schema named `project_`, which a plain PostgreSQL does not have (`schema "project_…" does not exist`). ## A local PostgreSQL Any PostgreSQL works; use the major version of Aurabase (18) so that `pg_dump` and SQL behave the same. In a folder that is not linked (`aura init` writes an `aurabase.toml` without a project), set `DATABASE_URL` and use the usual commands. Output measured on a PostgreSQL 18 container (not replayed by this page): ```bash export DATABASE_URL=postgresql://postgres:…@127.0.0.1:55432/postgres aura db push ``` ```text » Applying migrations... ⚠ No linked project — operations targeting schema 'public'. Use aura link • Applying 20261201000000_wf_local_notes.sql... • Applying 20261201000100_wf_local_owner.sql... Error: error returned from database: schema "auth" does not exist Caused by: schema "auth" does not exist ``` The second migration used `default auth.uid()`, which exists on a project and not on a plain PostgreSQL. The first file was applied and recorded; locally, too, each file runs in its own transaction. `aura db status`, `aura db migration down` (it reads the `.down.sql` files and reverts the latest migrations, as its help says) and `aura db seed` then work on that database: ```text » Migration Status - Database Migration Status Date ------------------------------------------------------------------------ 20261201000000_wf_local_notes.sql APPLIED 2026-11-22 23:32 20261201000100_wf_local_owner.sql PENDING - ``` To run migrations that call `auth.uid()` locally, create a stand-in once in the local database (with `psql`, not part of your migrations). It reads the same setting as on a project, so `set local request.jwt.claims = '{"sub": "…"}'` lets you test a policy by hand: ```sql create schema if not exists auth; create or replace function auth.uid() returns uuid language sql stable as $$ select nullif(nullif(current_setting('request.jwt.claims', true), '')::json->>'sub', '')::uuid $$; ``` With it, the second migration applied. Policies `to aura_authenticated` also need the roles: `create role aura_anon nologin; create role aura_authenticated nologin;`. `aura db generate` without a link reads the local database and writes `types.ts` and `AuraClient.js`. That generator is simpler than the project's: identity columns are required in `Insert`, and views, functions and enums are not described. Generate the types you ship from a project ([Generate TypeScript types](https://aurabase.dev/en/docs/database/generate-types)). ## What a local database does not have | On a project | On a local PostgreSQL | | --- | --- | | `auth.uid()`, `auth.jwt()` and the other `auth.*` helpers | Missing unless you create stand-ins | | Roles `aura_anon`, `aura_authenticated`, `aura_service_role` | Missing | | Row level security turned on and forced on every new table | Off unless your migration turns it on: a migration that relies on the default gives a table without RLS locally | | Migration SQL checked before it runs (no `do` blocks, no `security definer`, no `begin`/`commit`…) | Not checked: a migration can pass locally and be refused by the project | | A ledger with checksums: an edited file is detected | A ledger of names only, in `_aura_cli_migrations` | | The REST API, the SDK, Auth, Realtime, the extensions the platform installs | None | Before merging, push your migrations to a test project or a branch: that is where they must pass. ## Start over: aura db reset does not work `aura db reset` is meant to drop the schema, recreate it and push the migrations again. With CLI 0.3.4 it fails in every case. On a linked project, without `DATABASE_URL`, it does not use the API: ```bash verify="reset" needs="database-url" aura db reset --force 2>&1 || echo "exit code $?" ``` ```text expect="reset" » Resetting local database... Error: No database configured. Link a project with 'aura link' (commands will use the API), or set DATABASE_URL (environment variable or .env) for a local database. exit code 1 ``` With `DATABASE_URL`, measured on the local PostgreSQL 18 container (not replayed here), it fails before changing anything: ```text » Resetting local database... Error: error returned from database: cannot insert multiple commands into a prepared statement ``` Start over this way instead: - **Local PostgreSQL:** drop and create the database (`dropdb` and `createdb`, or a new container), then `aura db push` and `aura db seed`. - **Test project:** drop the objects your migrations created (`aura db table drop
--force`, `aura db raw "drop view …"`), remove their versions from the ledger (`aura db migration repair --reverted`), then push and seed again. Or delete the project (`aura projects delete --force`) and create a new one. - **Branch:** delete it and create a new one, with `--no-data` for an empty schema. ## aura start runs the Aurabase stack `aura start`, `aura stop`, `aura restart` and `aura dev` start the services of Aurabase itself, from a checkout of the Aurabase repository (they run its `start.sh`); they are for self-hosting and for contributors. In an application folder they stop at once: ```bash verify="start" aura start 2>&1 || echo "exit code $?" ``` ```text expect="start" » Starting Aurabase stack... Error: Error: Unable to find Aurabase repository root. Please run this command from the project directory OR set the environment variable: export AURABASE_PATH=/path/to/aurabase exit code 1 ``` The hint `Run aura start first.` printed when a `DATABASE_URL` is unreachable refers to that stack, not to your local PostgreSQL. ## Result The linked project was never touched by the commands above: ```bash verify="result" needs="reset" aura db status ``` ```text expect="result" » Migration Status - Project 11111111-2222-4333-8444-555555555555 Migration Status Date ------------------------------------------------------------------------ 20261201000000_wf_local_probe.sql PENDING - ``` The probe file is pending: neither the push redirected to `DATABASE_URL` nor the reset reached the project. ## Common errors | Message | Cause | Fix | | --- | --- | --- | | `PostgreSQL unreachable at postgresql://…` | `DATABASE_URL` is set (environment, `.env` or `.env.local`) and its database does not answer. | Start that database, or unset `DATABASE_URL` to work on the linked project. | | `schema "project_…" does not exist` | `DATABASE_URL` points to a plain PostgreSQL while a project is linked. | Unset `DATABASE_URL`, or work in a folder that is not linked. | | `schema "auth" does not exist` | A migration uses `auth.uid()` on a local database. | Create the stand-in above, or push to a test project. | | `No database configured. Link a project with 'aura link' …` | `aura db seed` or `aura db reset` on a linked project without `DATABASE_URL`. | Seed with `aura db raw -f aurabase/seed.sql`; start over as described above. | | `cannot insert multiple commands into a prepared statement` | `aura db reset` with `DATABASE_URL`. | Drop and create the database yourself. | | `No linked project. Reset the 'public' schema? (DESTRUCTIVE)` then `Not a terminal` | `aura db reset` without `--force` in a script. | It would fail anyway: see [Start over](#reset). | | `Unable to find Aurabase repository root.` | `aura start` or `aura dev` outside the Aurabase repository. | Use a project, a branch or your own PostgreSQL. | ## Clean up ```bash verify="clean-up" needs="database-url" rm -rf aurabase/migrations aura db status ``` ```text expect="clean-up" » Migration Status - Project 11111111-2222-4333-8444-555555555555 ℹ No migrations found, local or applied. Create one with aura db migration new . ``` ## See also - [Database branches](https://aurabase.dev/en/docs/database/branches): A copy of a project for each change. - [SQL migrations](https://aurabase.dev/en/docs/database/migrations): What a migration may contain on a project. - [Seed a project with test data](https://aurabase.dev/en/docs/database/seed): Load the same data into any database. - [Connect to your database](https://aurabase.dev/en/docs/database/connect): psql and pg_dump on the direct connection of a project. --- ### Performance audit p99 Source: https://aurabase.dev/en/docs/database/performance.md # Performance audit p99 > Identify slow queries, understand EXPLAIN ANALYZE, indexing strategies, and the 5 anti-patterns that kill Postgres in production. ## Measure before optimizing An audit starts with numbers. The Studio exposes p50/p95/p99 by endpoint and by query. Capture a 7-day baseline before any change. > **Note:** > > The `aura db slow-queries` and `aura db stats` CLI commands query `pg_stat_statements` and database pool/size metrics on your linked project, scoped to your project (also available in **Studio › Database** and **Logs**). `aura db inspect indexes|tables|locks` lists index usage (with the unused ones flagged), table sizes and dead rows, and blocking locks — the diagnostics that `/raw` cannot run because it refuses system catalogs. ```bash filename="cli" # The 10 most expensive queries (total time) aura db slow-queries --limit 10 # Connections and database size (endpoint latencies: Studio › Logs) aura db stats ``` ## pg_stat_statements in real time `pg_stat_statements` is installed and preloaded on every new project. It aggregates each normalized query (no literal values are stored) with `mean_exec_time`, `calls` and `rows`. `/raw` does not read it directly — the view is cluster-wide — so use the commands above, which return only your project's queries, or **Studio › Database**. ```bash filename="top-10" aura db slow-queries --limit 10 --json aura db inspect indexes # idx_scan = 0 and not unique/primary → unused ``` ## Read the plan like a pro A query that runs longer than the project's statement timeout (10 s) is cancelled with `STATEMENT_TIMEOUT` (HTTP 504) / « canceling statement due to statement timeout » in `aura db raw`: reduce the work or split it. The plan tells you **why** the query is slow. The 4 signals to look for: - `Seq Scan` on table > 10k rows → missing index - `rows (estimated) ≠ rows (actual)` by ±10× → obsolete stats, `analyze table_name` - `Nested Loop` on 100k+ lines → hash join preferred, maybe a missing WHERE - `Materialize` or `Sort Method: external merge` → RAM exhausted, `work_mem` to increase ```sql filename="debug" explain (analyze, buffers, format json) select * from orders where customer_id = 'abc' and created_at > now() - interval '30 days'; ``` ## When, what, how - **B-tree** (default): equality, range, order by. 80% of cases. - **GIN**: full-text search, JSONB, tables. `using gin (to_tsvector('french', body))`. - **GiST**: range types, exclusion constraints, similarity search (`pg_trgm`). - **HNSW** (pgvector): vector search, > 100k vectors. - **Partial**: common conditions, `where deleted_at is null` for soft delete. - **Covering**: `include (...)` to avoid the lookup on the table. > **Warning:** > > Each index slows down INSERT/UPDATE/DELETE (~5-15% per index). Drop unused indexes — `aura db inspect indexes` lists them (never scanned, not unique, not primary). ## What kills Postgres in production 1. **N+1 queries** — do a join or use `!inner` in the SDK rather than a loop 2. **Pagination by OFFSET** — beyond 1000, use cursor-based (`where id > last_seen`) 3. **SELECT \* on large tables** — request only the necessary columns 4. **Long transactions** — these block VACUUM and cause bloat. Keep < 1 second 5. **Non-indexed RLS Policies** — if your policy uses `tenant_id = auth.tenant()`, index `tenant_id` ## To go further - [Database](https://aurabase.dev/en/docs/database): Extensions, CRUD, migrations. - [Multi-region deployment](https://aurabase.dev/en/docs/deployment/multi-region): Read replicas for scale-out reading. - [Database branches](https://aurabase.dev/en/docs/deployment/preview-envs): Test on a copy of your project, away from production. - [RLS](https://aurabase.dev/en/docs/database/rls): Indexed policies, avoid full-scans. --- ### GraphQL Source: https://aurabase.dev/en/docs/graphql.md # GraphQL > Postgres extension pg_graphql, opt-in per project and disabled by default. Once enabled, it exposes the same schema as your REST API — inheriting RLS and roles with no separate GraphQL authentication — via dedicated `/graphql` routes or the generic RPC proxy. ## A second way to query the same schema, not a separate service GraphQL is powered directly by the Postgres `pg_graphql` extension inside your tenant database, generating a GraphQL schema from your SQL tables, views, and relationships. Enabling it adds a **second query surface over the same Postgres schema** as your REST API — inheriting the exact same RLS policies and roles, without a separate GraphQL server or auth layer. > **Note:** > > Disabled by default for all projects. Aurabase activates `pg_graphql` **only** on explicit opt-in per project. See the official [pg\_graphql](https://supabase.github.io/pg_graphql/) docs for full query, filter, cursor pagination, and mutation syntax. ## An SQL resolver exposed on /graphql and /rpc/graphql Enabling GraphQL on a project installs `pg_graphql` and creates `"".graphql(query, variables, operationName, extensions)` in a single transaction. On a project subdomain, requests to `POST /graphql`, `POST /graphql/v1`, `POST /v1/graphql`, `POST /v1/graphql/v1`, and `POST /v1/db/{project_id}/graphql` (as well as `POST /v1/db/{project_id}/rpc/graphql`) are routed to `pg_graphql` and return the standard `{ "data": ..., "errors": ... }` GraphQL JSON payload directly without the REST `{ data, meta }` wrapper. ```text filename="cycle of an activation" ACTIVATION ────▶ POST .../graphql/enable or aura projects graphql-enable ENQUEUE ────▶ job "graphql_enable" queued (idempotent, no-op if already enabled) DDL ────▶ CREATE EXTENSION pg_graphql + wrapper function + GRANTs, 1 single transaction FLAG ────▶ projects.graphql_enabled = true, set only after full transaction commit QUERY ────▶ POST /graphql or /v1/db/{project_id}/graphql (returns raw GraphQL JSON) ``` > **Tip:** > > The activation transaction is atomic: if any step (extension, wrapper function, or GRANTs) fails, everything rolls back and `graphql_enabled` stays `false`. ## What activation sets up - **Automatically generated schema.** pg\_graphql introspects your Postgres schema and exposes each table as a Relay GraphQL type (`<table>Collection`, `edges`, `node`) with SQL `snake_case` columns inflected to `camelCase` by default — no SDL to write by hand. - **SECURITY INVOKER — Inherited RLS.** The wrapper function runs with the privileges of the caller (`aura_anon` / `aura_authenticated` / `aura_service_role`), enforcing the exact same RLS policies as REST requests. - **Three settings you can change, applied atomically.** `introspection` (off by default: `{ __schema { ... } }` is refused with `Unknown field "__schema"`, so GraphiQL and Apollo codegen cannot discover the schema until you turn it on), `max_rows` (rows returned per collection, 1 to 10000, default 1000) and `inflect_names` (`created_at` → `createdAt`, on by default). The pg\_graphql `COMMENT ON SCHEMA … @graphql(...)` recipe does not work from a project (your role does not own the schema, and `/raw` refuses `E'…'` literals): use `aura projects graphql-config` or `PATCH …/graphql/config` instead, see [Tune the settings](#settings). - **Opt-in activation, idempotent.** `POST .../graphql/enable` (console JWT) or `aura projects graphql-enable --wait` (CLI) dispatches the provisioning job and, with `--wait`, returns once GraphQL is actually enabled; never turned on automatically. - **Available on all Postgres tiers.** Works whether your project runs on an organization Postgres cluster or a dedicated Enterprise cluster; validated end-to-end (extension, RLS wrapper, real query). - **Postgres projects only.** A MongoDB project refuses activation (`GRAPHQL_UNSUPPORTED_ENGINE`). ## Activate, then query **CLI** ```bash tab="CLI" filename="graphql-enable.sh" # Idempotent: a repeated call on an already enabled project is a no-op. # --wait returns once GraphQL is actually enabled (the activation is a background job). aura projects graphql-enable --wait ``` **REST (activation)** ```bash tab="REST (activation)" filename="graphql-enable.sh" # Management plane (Studio/admin) — Console JWT, not a project apikey. curl -X POST "$AURA_CONTROL_URL/v1/control/projects/$PROJECT_ID/graphql/enable" \ -H "Authorization: Bearer $CONSOLE_JWT" # 200 if already enabled (no-op) — 202 when queued as an async provisioning job. ``` **GraphQL Query** ```bash tab="GraphQL Query" filename="query.sh" # Dedicated GraphQL route (on subdomain: POST /graphql; or POST /v1/db/$PROJECT_ID/graphql) # Columns are inflected to camelCase by pg_graphql (`created_at` -> `createdAt`). curl -X POST "$NEXT_PUBLIC_AURABASE_URL/graphql" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"query":"query { postsCollection(first: 10, filter: { published: { eq: true } }) { edges { node { id title createdAt } } } }"}' ``` > **Tip:** > > Activation responds with the updated project (`graphql_enabled: true`). Notice column inflection (`created_at` → `createdAt`): see the [official pg\_graphql API reference](https://supabase.github.io/pg_graphql/api/) for filters, `orderBy`, cursor pagination (`first`/`after`), and mutations (`insertInto
Collection`). ## Tune the settings: introspection, max rows, name inflection pg\_graphql reads its settings from a comment on your project's schema. Only the schema owner can write it, so the platform does it for you, in one transaction, when you ask. A change is idempotent (asking for what is already applied does nothing) and bounded (`max_rows` outside 1–10000 is refused before anything is queued). **CLI** ```bash tab="CLI" filename="graphql-config.sh" # Show the settings in effect aura projects graphql-config # Turn introspection on (GraphiQL, graphql-codegen, Apollo), wait until it is applied aura projects graphql-config --introspection on --wait # Cap collections at 100 rows and keep SQL names as they are aura projects graphql-config --max-rows 100 --inflect-names off --wait ``` **REST** ```bash tab="REST" filename="graphql-config.sh" # Console JWT. Partial body: only the fields you send change. 202 = queued, 200 = already applied. curl -X PATCH "$AURA_CONTROL_URL/v1/control/projects/$PROJECT_ID/graphql/config" \ -H "Authorization: Bearer $CONSOLE_JWT" -H "Content-Type: application/json" \ -d '{"introspection": true, "max_rows": 100}' # Read: `config` is what the project database really uses, `state` is applied | pending | failed. curl "$AURA_CONTROL_URL/v1/control/projects/$PROJECT_ID/graphql/config" \ -H "Authorization: Bearer $CONSOLE_JWT" ``` `state` tells the truth about the change: `pending` while it is being applied (with `pending_config`), `failed` if it could not be (the settings in `config` are then still the ones in effect), `applied` otherwise. GraphQL must be enabled first (`GRAPHQL_NOT_ENABLED` otherwise), and a second change while one is pending answers `GRAPHQL_CONFIG_PENDING`: retry in a few seconds. > **Introspection exposes your schema** > > With `introspection` on, anyone who holds the project's public key can list every table and column that GraphQL exposes (RLS still protects the rows). Turn it on for development, and off again for production if the shape of your schema is sensitive. ## Points of attention > **Naming inflection and schema reloads** > > By default, `pg_graphql` inflects SQL `snake_case` names to GraphQL `camelCase` (`created_at` becomes `createdAt`, table `blog_posts` becomes `blogPostsCollection`). After DDL changes, PostgREST reloads its schema cache within seconds so both `/graphql` and `/rpc/graphql` expose updated fields. ## To go further - [Database](https://aurabase.dev/en/docs/database): Postgres managed, extensions enabled, RLS — the schema that pg_graphql exposes. - [Call a Postgres function](https://aurabase.dev/en/docs/api/database/rpc): The generic RPC proxy (/rpc/{function}) used by GraphQL queries. - [Security & RBAC](https://aurabase.dev/en/docs/security): RLS, roles anon/authenticated/service_role — the model inherited as is by GraphQL. - [CLI](https://aurabase.dev/en/docs/cli): aura projects graphql-enable and the rest of the projects commands. --- ### NoSQL & Document Store Source: https://aurabase.dev/en/docs/nosql.md # NoSQL & Document Store > MongoDB compatible document-oriented database engine. Store flexible JSON data structures, index your collections, and run complex aggregation pipelines. ## The Aurabase document store In addition to the PostgreSQL relational engine, Aurabase allows you to activate a **NoSQL Document Store** engine isolated by project. It offers the flexibility of semi-structured documents with the robustness of the Aurabase infrastructure (backups, access control, observability). > **Recommended use cases** > > Choose the NoSQL engine for tracking/analytics events, product catalogs with heterogeneous attributes, real-time telemetry and user sessions. > **A MongoDB project is required** > > The `/v1/nosql` routes only exist on a project created with the MongoDB engine. On a Postgres project they answer `400` « NoSQL routes (/v1/nosql) are only available on MongoDB projects ». Create one with `aura projects create my-events --engine mongodb`, or choose the engine in the console, then use that project's URL and keys for the examples below. ## Collection operations **Insert** ```typescript tab="Insert" filename="nosql-insert.ts" const { data, error } = await aura.nosql .collection('events') .insertOne({ type: 'user_signup', userId: 'usr_9482', metadata: { country: 'FR', plan: 'pro' }, timestamp: new Date(), }) ``` **Find & Filter** ```typescript tab="Find & Filter" filename="nosql-find.ts" // Query with filters ($gte, $in, $regex); sort / limit / skip chain on the query const { data: events } = await aura.nosql .collection('events') .find({ 'metadata.country': 'FR', type: { $in: ['user_signup', 'payment_success'] }, }) .sort({ timestamp: -1 }) .limit(50) ``` **Update & Delete** ```typescript tab="Update & Delete" filename="nosql-write.ts" await aura.nosql.collection('events').insertMany([{ type: 'a' }, { type: 'b' }]) await aura.nosql.collection('events').updateMany({ type: 'a' }, { $set: { seen: true } }) await aura.nosql.collection('events').updateOne({ type: 'b' }, { $set: { seen: true } }) const { data: n } = await aura.nosql.collection('events').countDocuments({ seen: true }) await aura.nosql.collection('events').deleteMany({ seen: true }) ``` **Aggregation** ```typescript tab="Aggregation" filename="nosql-aggregate.ts" // Aggregation pipeline ($match -> $group -> $sort) const { data: stats } = await aura.nosql .collection('orders') .aggregate([ { $match: { status: 'completed' } }, { $group: { _id: '$customer_id', totalSpent: { $sum: '$amount' } } }, { $sort: { totalSpent: -1 } }, { $limit: 10 }, ]) ``` **Indexes** ```typescript tab="Indexes" filename="nosql-index.ts" // Compound index & TTL index (auto session expiration) await aura.nosql.collection('sessions').createIndex({ keys: { userId: 1, createdAt: -1 }, options: { unique: false, expireAfterSeconds: 86400 }, // 24h }) ``` ## Who can read and write a collection Access is **private by default and isolated per owner**. Every document is stamped with the user who wrote it, and a signed-in user only reads and writes their own documents. A request with no user (the `anon` key alone) is refused with `403` — « Read refused: no user identity to apply per-owner isolation » — unless the collection is explicitly made publicly readable. A `service_role` key bypasses the isolation. To make a collection readable by everyone, open it in **Studio › Database** and click **Make public** (writes stay isolated per owner, and the owner field is never returned). The same switch is available on the management plane, with a console token: `PUT /v1/db/{project_id}/schema/tables/{collection}/public-read` with `{"public_read": true}`. ## Engine optimized for production - **Flexible schema.** Dynamic JSON/BSON documents. Ideal for logs, e-commerce catalogs, IoT telemetry and non-standardized profiles. - **Query operators.** `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$regex` (simple patterns) and `$exists`, on top-level fields and nested paths such as `'metadata.country'`. An operator the engine does not support is **rejected with an explicit error**, never ignored, so a filter never silently returns more than you asked for. - **Aggregation pipelines.** Multi-step transformations with $match, $project, $group, $sort, $unwind and streaming metric calculations. - **Indexing.** Simple, compound, text indexes for full-text search and TTL indexes with automatic purge of expired documents. - **Explain and profiling.** Detailed execution plan for each query (COLLSCAN vs IXSCAN, execution time, indexes used). - **REST API and SDK.** Direct access via REST endpoints `/v1/nosql/{collection}` (on your project's URL, with your `apikey`) or the `@aurabase/aurabase-js` SDK. ## Query Optimization (Explain) Call `aura.nosql.collection('events').explain({ type: 'user_signup' })` to get the plan of a filter. Each query can be analyzed to inspect the execution steps, identify if an index was requested (`IXSCAN`) or if a full scan took place (`COLLSCAN`): ```json filename="explain-plan.json" { "queryPlanner": { "winningPlan": { "stage": "IXSCAN", "indexName": "metadata.country_1_timestamp_-1", "keysExamined": 42, "docsExamined": 42 }, "executionTimeMillis": 1.2 } } ``` ## PostgreSQL vs NoSQL: Which engine to choose? | Criterion | PostgreSQL (relational) | Document store (NoSQL) | | --- | --- | --- | | Structure | Strict schema, versioned migrations | Dynamic schema without rigid constraints | | Relations and joins | SQL joins and foreign keys | Nested or denormalized documents | | Access control | Declarative row-level security (RLS) in SQL | Permissions by collection and role token | | Vector search | Native pgvector with HNSW | Filtering by attributes and text indexes | | Best for | Core banking, B2B SaaS, rights management | Logs, dynamic catalogs, IoT, events | ## To go further - [PostgreSQL Database](https://aurabase.dev/en/docs/database): Complete guide to PostgreSQL, RLS and extensions. - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): Collection manipulation methods. - [REST API](https://aurabase.dev/en/docs/api-rest): REST endpoints for NoSQL collections. --- ### Database CLI reference Source: https://aurabase.dev/en/docs/database/cli.md # Database CLI reference > Usage, arguments and options of each `aura` command that works on your database, read from the help of the binary itself This page is generated from the `aura` binary (`npm run docs:cli` in `studio/`): every usage line, argument and option below is the output of `aura --help`. Square brackets mark optional items, angle brackets mark values you provide. Every command also accepts `--help` and `--gateway-url `: Management plane URL (default: https://api.aurabase.dev). Local: http://localhost:8090. Equivalent to the AURA_GATEWAY_URL environment variable. ## aura db Manage the database (migrations, SDK, schema) ```text aura db [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db migration`](#db-migration) | Manage migrations | | [`aura db table`](#db-table) | Manage tables (schema) | | [`aura db push`](#db-push) | Apply local migrations (+ remote sync if a project is linked) | | [`aura db pull`](#db-pull) | Pull remote schema | | [`aura db watch`](#db-watch) | Watch for changes and sync | | [`aura db reset`](#db-reset) | Reset the database (purge and recreate) — DESTRUCTIVE, asks for confirmation | | [`aura db seed`](#db-seed) | Insert test data (seed.sql), or an example schema with --example | | [`aura db generate`](#db-generate) | Generate types (TypeScript/JS or Rust) | | [`aura db status`](#db-status) | Show migration status | | [`aura db slow-queries`](#db-slow-queries) | Most expensive SQL queries in the project (pg_stat_statements) | | [`aura db stats`](#db-stats) | Connections and database size for the project | | [`aura db diff`](#db-diff) | Compare remote schema and generate a diff migration | | [`aura db raw`](#db-raw) | Execute raw SQL directly | | [`aura db policy`](#db-policy) | Manage RLS policies | | [`aura db function`](#db-function) | Manage project Postgres SQL functions (PL/pgSQL, SQL) | | [`aura db trigger`](#db-trigger) | Manage Postgres triggers on a table | | [`aura db backup`](#db-backup) | Manage database backups | | [`aura db inspect`](#db-inspect) | Diagnostics the SQL guard does not allow in raw queries: index usage, table sizes, blocking locks | | [`aura db connection`](#db-connection) | Direct PostgreSQL access (psql, Prisma, Drizzle, pg_dump): host, role and a one-time password | | [`aura db extensions`](#db-extensions) | List or enable PostgreSQL extensions of the linked project | | [`aura db api-keys`](#db-api-keys) | Manage project API keys | | [`aura db restore`](#db-restore) | Restore a plain-SQL pg_dump file (statements, $$ bodies, COPY blocks) into the project | ### aura db migration Manage migrations ```text aura db migration [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db migration new`](#db-migration-new) | Create a new migration | | [`aura db migration list`](#db-migration-list) | List all migrations and their status | | [`aura db migration down`](#db-migration-down) | Revert the last N applied migrations (default: 1) | | [`aura db migration repair`](#db-migration-repair) | Manually mark a migration as applied or reverted | ### aura db migration new Create a new migration ```text aura db migration new [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | | ### aura db migration list List all migrations and their status ```text aura db migration list [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db migration down Revert the last N applied migrations (default: 1) ```text aura db migration down [OPTIONS] [N] ``` | Argument | Description | | --- | --- | | `[N]` | [default: 1] | ### aura db migration repair Manually mark a migration as applied or reverted ```text aura db migration repair [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | Migration file name (e.g. 20240101_create_users.sql) | | Option | Description | | --- | --- | | `--applied` | Mark as applied | | `--reverted` | Mark as reverted | ### aura db table Manage tables (schema) ```text aura db table [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db table list`](#db-table-list) | List tables and their columns | | [`aura db table create`](#db-table-create) | Create a table e.g. aura db table create users "name:text,email:text,age:int" | | [`aura db table drop`](#db-table-drop) | Drop a table | | [`aura db table rls`](#db-table-rls) | Enable or disable Row Level Security | | [`aura db table realtime`](#db-table-realtime) | Enable or disable Realtime CDC | ### aura db table list List tables and their columns ```text aura db table list [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db table create Create a table e.g. aura db table create users "name:text,email:text,age:int" ```text aura db table create [OPTIONS] [COLUMNS] ``` | Argument | Description | | --- | --- | | `` | Table name | | `[COLUMNS]` | Columns in "name:type,..." format (see --help for all 16 supported types) | ### aura db table drop Drop a table ```text aura db table drop [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | Table name | | Option | Description | | --- | --- | | `-f, --force` | Drop without asking for confirmation | ### aura db table rls Enable or disable Row Level Security ```text aura db table rls [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | Table name | | `` | on \| off | ### aura db table realtime Enable or disable Realtime CDC ```text aura db table realtime [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | Table name | | `` | on \| off | ### aura db push Apply local migrations (+ remote sync if a project is linked) ```text aura db push [OPTIONS] ``` ### aura db pull Pull remote schema ```text aura db pull [OPTIONS] ``` ### aura db watch Watch for changes and sync ```text aura db watch [OPTIONS] ``` ### aura db reset Reset the database (purge and recreate) — DESTRUCTIVE, asks for confirmation ```text aura db reset [OPTIONS] ``` | Option | Description | | --- | --- | | `-f, --force` | Skip the confirmation prompt | ### aura db seed Insert test data (seed.sql), or an example schema with --example ```text aura db seed [OPTIONS] ``` | Option | Description | | --- | --- | | `--example ` | Install an embedded example schema instead of seed.sql (available: docs) | ### aura db generate Generate types (TypeScript/JS or Rust) ```text aura db generate [OPTIONS] ``` | Option | Description | | --- | --- | | `--lang ` | Output language: ts (default) \| rust [default: ts] [possible values: ts, rust] | ### aura db status Show migration status ```text aura db status [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db slow-queries Most expensive SQL queries in the project (pg_stat_statements) ```text aura db slow-queries [OPTIONS] ``` | Option | Description | | --- | --- | | `--limit ` | Number of queries to display [default: 10] | | `--json` | | ### aura db stats Connections and database size for the project ```text aura db stats [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db diff Compare remote schema and generate a diff migration ```text aura db diff [OPTIONS] ``` | Option | Description | | --- | --- | | `--name ` | Name of the generated migration (default: schema_diff) | ### aura db raw Execute raw SQL directly ```text aura db raw [OPTIONS] [SQL] ``` | Argument | Description | | --- | --- | | `[SQL]` | SQL query to execute (use `-` to read it from stdin). May start with a `--` comment | | Option | Description | | --- | --- | | `-f, --file ` | Read the SQL from a file instead of the command line | | `-p, --params [...]` | Positional parameters ($1, $2...) to bind | | `--json` | Raw JSON output | | `--dry-run` | Actually run the query then ROLL BACK the transaction (dry run). Constraint errors still surface and rows are returned, but nothing is committed | | `--read-only` | Execute inside a READ-ONLY transaction — PostgreSQL rejects any write at the engine level (this flag can only restrict) | | `--as ` | Execute the query as an anonymous visitor (`anon`) or application user (`authenticated`, with --user) instead of admin: verifies an RLS policy as the application would see it. Can only restrict [possible values: anon, authenticated] | | `--user ` | UUID of the impersonated user (`auth.uid()`), required with `--as authenticated` | ### aura db policy Manage RLS policies ```text aura db policy [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db policy list`](#db-policy-list) | List RLS policies | | [`aura db policy add`](#db-policy-add) | Create an RLS policy | | [`aura db policy update`](#db-policy-update) | Update expressions on an existing RLS policy (ALTER POLICY) | | [`aura db policy delete`](#db-policy-delete) | Delete an RLS policy | ### aura db policy list List RLS policies ```text aura db policy list [OPTIONS] ``` | Option | Description | | --- | --- | | `--table
` | | | `--all` | Include system/storage internal policies | | `--json` | | ### aura db policy add Create an RLS policy ```text aura db policy add [OPTIONS]
``` | Argument | Description | | --- | --- | | `
` | | | `` | | | `` | | | Option | Description | | --- | --- | | `--using-expr ` | | | `--check-expr ` | | ### aura db policy update Update expressions on an existing RLS policy (ALTER POLICY) ```text aura db policy update [OPTIONS]
``` | Argument | Description | | --- | --- | | `
` | | | `` | | | Option | Description | | --- | --- | | `--using-expr ` | | | `--check-expr ` | | ### aura db policy delete Delete an RLS policy ```text aura db policy delete [OPTIONS]
``` | Argument | Description | | --- | --- | | `
` | | | `` | | | Option | Description | | --- | --- | | `-f, --force` | | ### aura db function Manage project Postgres SQL functions (PL/pgSQL, SQL) ```text aura db function [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db function list`](#db-function-list) | List Postgres functions in the project schema (name, arguments, security, GRANT) | | [`aura db function create`](#db-function-create) | Create or replace a Postgres function | | [`aura db function drop`](#db-function-drop) | Drop a Postgres function | ### aura db function list List Postgres functions in the project schema (name, arguments, security, GRANT) ```text aura db function list [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db function create Create or replace a Postgres function ```text aura db function create [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | Function name (ASCII alphanumeric and '_' — no silent sanitization) | | Option | Description | | --- | --- | | `-b, --body ` | Function body (SQL or PL/pgSQL, without enclosing `$$`) | | `--body-file ` | File containing the function body (alternative to --body) | | `--returns ` | Postgres return type (e.g. void, text, trigger, setof uuid, numeric(10,2)) [default: void] | | `--language ` | Language: plpgsql \| sql [default: plpgsql] | | `--args ` | Arguments in "name:type,name2:type2" format (IN mode only) | | `--security ` | Security mode: invoker (server default) \| definer | | `--grant-execute-to ` | Roles allowed to EXECUTE (repeatable, or comma-separated) | ### aura db function drop Drop a Postgres function ```text aura db function drop [OPTIONS] ``` | Argument | Description | | --- | --- | | `` | | | Option | Description | | --- | --- | | `-f, --force` | | ### aura db trigger Manage Postgres triggers on a table ```text aura db trigger [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db trigger list`](#db-trigger-list) | List triggers on a table | | [`aura db trigger create`](#db-trigger-create) | Create a trigger on a table | | [`aura db trigger drop`](#db-trigger-drop) | Drop a trigger from a table | ### aura db trigger list List triggers on a table ```text aura db trigger list [OPTIONS]
``` | Argument | Description | | --- | --- | | `
` | Table name | | Option | Description | | --- | --- | | `--json` | | ### aura db trigger create Create a trigger on a table ```text aura db trigger create [OPTIONS] --function --events
``` | Argument | Description | | --- | --- | | `
` | Table name owning the trigger | | `` | Trigger name | | Option | Description | | --- | --- | | `--function ` | Postgres function to execute (created via `aura db function create`, RETURNS trigger) | | `--timing ` | Timing: before \| after \| instead_of [default: before] | | `--events ` | Events: insert \| update \| delete \| truncate (repeatable or comma-separated) | | `--for-each ` | Granularity: row \| statement (truncate requires statement) [default: row] | ### aura db trigger drop Drop a trigger from a table ```text aura db trigger drop [OPTIONS]
``` | Argument | Description | | --- | --- | | `
` | Table name | | `` | Trigger name | | Option | Description | | --- | --- | | `-f, --force` | | ### aura db backup Manage database backups ```text aura db backup [OPTIONS] ``` | Command | Description | | --- | --- | | [`aura db backup list`](#db-backup-list) | List backups | | [`aura db backup create`](#db-backup-create) | Create a backup | | [`aura db backup restore`](#db-backup-restore) | Restore from a backup (overwrites current data; --verify-only replays it in a rolled-back transaction) | | [`aura db backup download`](#db-backup-download) | Download a backup's SQL dump | | [`aura db backup delete`](#db-backup-delete) | Delete a backup | | [`aura db backup schedule`](#db-backup-schedule) | View or configure the AUTOMATIC backup schedule | ### aura db backup list List backups ```text aura db backup list [OPTIONS] ``` | Option | Description | | --- | --- | | `--json` | | ### aura db backup create Create a backup ```text aura db backup create [OPTIONS] ``` | Option | Description | | --- | --- | | `--label
on`) with the body `{"enabled": true}` and a `service_role` key. Listening starts when the first client subscribes and stops a few minutes after the last one leaves. Delivery is at least once: after a server restart a change can arrive twice, so make your handler idempotent, for example by keying on the row's primary key. A busy cluster can refuse a new listener with a capacity error; retry shortly. Any channel name works: each filter's `table` selects the table to listen to, and one channel can listen to several tables. On a channel that is not named `db:.
`, every filter needs a `table`. The first subscriber can receive up to 5 seconds of changes made just before it subscribed. Changes are kept one hour for recovery, then deleted. When the cluster is full, the subscription fails with `capacité d'écoute postgres_changes atteinte pour la base de ce projet, réessayez`. If listening stays down for more than a minute, the channel moves to `CHANNEL_ERROR`, then back to `SUBSCRIBED` once listening is restored; you do not need to subscribe again. If an outage outlasts the one-hour retention, the channel also receives `CHANNEL_ERROR` with `changements postgres_changes perdus pendant l'interruption, resynchronisez`: reload the data from the database. A change keeps the same `id` each time it is delivered, so you can also skip an `id` you have already handled. The row of a delete no longer exists, so row level security cannot be evaluated on it. On a table with row level security, a `DELETE` is therefore delivered only to subscribers whose role has a `SELECT` policy on the table (or bypasses RLS, like `service_role`): a visitor (`anon`) without a read policy does not receive it. On a table without row level security every subscriber receives it. `payload.old` of a `DELETE` holds only the primary key columns (nothing if the table has no primary key), and a filter on any other column never matches a delete. For an `UPDATE`, `payload.old` also holds only the primary key columns of the previous row (their previous values if the key changed), never its other values: row level security is checked on the new row only. The filter of an `UPDATE` applies to the new row. Keep sensitive information out of primary keys. ```typescript filename="changes.ts" const changes = aura.realtime .channel('todos') .on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (payload) => { console.log(payload.eventType, payload.new) }) .subscribe((status) => { if (status === 'CHANNEL_ERROR') console.warn('database changes are not available for this project') }) ``` ## Clean up ```typescript filename="cleanup.ts" room.unsubscribe() // leave one channel aura.realtime.removeChannel(room) // leave and forget it aura.realtime.removeAllChannels() // leave every channel aura.realtime.disconnect() // close the connection ``` Watch the connection with `aura.realtime.onStateChange(callback)` and `onError(callback)`. After a drop, the client reconnects by itself unless you call `setAutoReconnect(false)`. --- ### Storage Source: https://aurabase.dev/en/docs/storage.md # Storage > REST API per project on S3 storage (SeaweedFS S3), on-the-fly image transformations with derivative cache, HMAC signed URLs, public or private buckets, trash and restore. ## One bucket, one origin, one CDN The `aura-storage` service manages your binary files: upload, download, image transformations, signed URLs, trash. It exposes its own **REST API** under `/v1/storage/{project_id}` and relies on S3 storage (SeaweedFS S3) internally — the S3 tools (rclone, boto3) do not connect to it directly. Objects are organized into **buckets**. Each bucket has a policy (public or private), size limits, an optional TTL, and a set of RLS policies that control who can read/write each path. > **Note:** > > The metadata lives in the project schema: `storage_buckets`, `storage_objects`, `storage_derivatives`, `storage_project_settings`, `storage_audit_log`. The bytes are in S3 storage. ## Path → RLS → CDN → origin During a read, the service checks for access to the requested path and then serves the bytes from storage. If the query carries transformation parameters, the corresponding derivative is reused if it already exists, otherwise calculated and then cached. In upload, the flow is reversed: client → service → storage, after writing control and bucket limits. ```text filename="schema" ┌──── derivative cache ────┐ GET /v1/storage/{pid}/… ─▶ │ derivative cached? │ │ no ⇢ origin │ └──────────┬───────────────┘ │ ┌──────────▼───────────────┐ │ aura-storage │ │ ─ access control │ │ ─ transforms │ │ ─ derivative cache │ └──────────┬───────────────┘ │ S3 storage (SeaweedFS S3) ``` ## Six native abilities - **REST API per project.** Routes /v1/storage/\{project\_id\}/… on S3 storage (SeaweedFS S3) — this is not an S3 API: S3 SDKs do not plug into it. - **Transforms on the fly.** width, height, fit, format (jpeg/png/webp/gif), quality, rotate, flip. Each combination is cached as a derivative. - **Signed URLs.** HMAC signature on method + bucket + key + expiration. TTL 3600 s by default, secret rotation per project. - **Multipart upload.** Simple upload in multipart/form-data, or init / part / complete for large files. - **Trash and restoration.** Soft deletion: /trash lists deleted objects, /restore/\{key\} restores them. - **Public or private buckets.** The bucket carries the access policy, size limits and the list of authorized MIME types. ## Four basic operations **Upload** ```typescript tab="Upload" filename="avatar.ts" const { data, error } = await aura.storage.upload('avatars', `${user.id}/${file.name}`, file, { contentType: file.type, upsert: true, }) // Without upsert, a path already occupied fails in 409 (CONFLICT code) ``` **Public URL** ```typescript tab="Public URL" filename="avatar.ts" const url = aura.storage.getPublicUrl('avatars', path, { transform: { width: 240, height: 240, resize: 'cover', format: 'webp', // origin | jpeg | png | webp | gif — no auto, no AVIF quality: 80, // applied to JPEG encoding only }, }) ``` **Signed URL** ```typescript tab="Signed URL" filename="invoice.ts" const { data } = await aura.storage.createSignedUrl('invoices', path, 300) // data.url valid 300 s; the signature is on method + bucket + key + expiration ``` **Delete** ```typescript tab="Delete" filename="cleanup.ts" // Deletes multiple objects — permission is checked on each await aura.storage.remove('avatars', [ 'u_9k2/avatar-old.jpg', 'u_9k2/avatar-backup.jpg', ]) ``` > **Tip:** > > Transformation URLs are immutable by parameters. `?width=240&format=png` and `?width=240&format=webp` are two distinct URLs, therefore two distinct derivatives: each combination is only calculated once, then reread from the derivative cache. ## RLS on object paths Object metadata lives in the `storage_objects` table of the project schema (columns `bucket_name`, `key`, `owner_id`, `metadata`, `deleted_at`), with RLS enabled. There is no `storage` schema nor `storage.foldername()` function: policies are written on the columns. ```sql filename="policies delivered by default" -- Read: own object, or any object from a public bucket create policy storage_objects_select on storage_objects for select using ( owner_id = auth.uid() or exists (select 1 from storage_buckets b where b.name = storage_objects.bucket_name and b.public) ); -- Writing: only your own objects create policy storage_objects_insert on storage_objects for insert with check (owner_id = auth.uid()); ``` ## To go further - [Row-Level Security](https://aurabase.dev/en/docs/database/rls): Policies on storage_objects, path-based patterns. - [Conventions](https://aurabase.dev/en/docs/conventions): Naming buckets, paths, ACLs. - [REST API](https://aurabase.dev/en/docs/api-rest): HTTP endpoints for /v1/storage/. - [Performance](https://aurabase.dev/en/docs/database/performance): Optimize CDN hit rate, purge tags. --- ### Store and serve files with the JavaScript SDK Source: https://aurabase.dev/en/docs/storage/files-with-sdk.md # Store and serve files with the JavaScript SDK > Everyday storage flows with client.storage: bucket management, single and multipart uploads, streaming downloads, HMAC signed URLs, and trash restoration. ## Bucket management A **bucket** groups files and decides whether they are public. Creating and deleting buckets requires a `service_role` key. Listing buckets requires a signed-in user or a `service_role` key (the anonymous key receives `403 FORBIDDEN`). ```typescript filename="server/buckets.ts" // Create a public bucket (anyone can read objects without API keys) await admin.storage.createBucket('avatars', { public: true }) // Create a private bucket (only object owners or service_role can read) await admin.storage.createBucket('invoices', { public: false, fileSizeLimit: 10 * 1024 * 1024, // 10 MiB limit per file allowedMimeTypes: ['application/pdf'], }) // List accessible buckets const { data: buckets, error } = await admin.storage.listBuckets() ``` A bucket also accepts `fileSizeLimit` (in bytes) and `allowedMimeTypes`. An upload that is too large returns `413 PAYLOAD_TOO_LARGE`, and a type that is not allowed returns `400 BAD_REQUEST`. ## Upload, download, list, remove ```typescript filename="files.ts" const bucket = aura.storage.from('invoices') // Upload: a File, Blob, Buffer, or Uint8Array // Files > 5 MiB are automatically split into multipart parts const { data, error } = await bucket.upload(`${user.id}/2026-10.pdf`, file, { contentType: 'application/pdf', onUploadProgress: (progress) => { console.log(`Upload progress: ${progress.percentage}%`) }, }) // → { key, bucket, url, size, content_type, etag } // Replace an existing file owned by the current user await bucket.upload(`${user.id}/2026-10.pdf`, newFile, { upsert: true }) // List files under a prefix / folder const { data: files } = await bucket.list({ prefix: `${user.id}/` }) // Download file as a Blob const { data: blob, error: downloadError } = await bucket.download(`${user.id}/2026-10.pdf`) // Stream download without loading entire file into memory const { data: stream } = await bucket.download(`${user.id}/2026-10.pdf`).asStream() // Remove a file (moved to trash by default with 30-day retention) await bucket.remove([`${user.id}/2026-10.pdf`]) // Permanent deletion (bypasses trash and immediately frees disk quota) await bucket.remove([`${user.id}/2026-10.pdf`], { permanent: true }) ``` Key runtime behaviors: - **Uploading an existing path returns `409 CONFLICT`** unless `upsert: true` is provided. - **Anonymous uploads are rejected** with `403 FORBIDDEN` on both private and public buckets (writing requires an authenticated JWT or service key). - **Path traversal protection**: paths containing `..` or illegal characters return `400 INVALID_PATH` without throwing unhandled exceptions. - **User isolation**: one user cannot overwrite or delete files owned by another user (`owner_id = auth.uid()`). Structure paths using user-scoped folders like `${user.id}/...`. ## Share a file (public & signed URLs) ```typescript filename="share.ts" // 1. Public bucket: direct permanent URL (served without API keys) const { data: { publicUrl } } = aura.storage.from('avatars').getPublicUrl('ada.png') // → https://.localhost:8080/v1/storage/avatars/ada.png // Force download as attachment with custom filename const downloadUrl = aura.storage.from('avatars').getPublicUrl('ada.png', { download: 'avatar-ada.png', }) // 2. Private bucket: HMAC signed URL with configurable TTL const { data, error } = await aura.storage.from('invoices').createSignedUrl( `${user.id}/2026-10.pdf`, 300, // Valid for 300 seconds (5 minutes) { download: true } ) // data.signedUrl and data.url contain the HMAC signed URL // 3. Direct browser upload without exposing secret keys // Server-side (service_role): const { data: uploadInfo } = await admin.storage.from('invoices').createSignedUploadUrl( `${user.id}/document.pdf`, 600 ) // Browser client (no API key required): await aura.storage.uploadToSignedUrl(uploadInfo.signedUrl, file, { contentType: 'application/pdf', }) ``` Signed URLs seal the HTTP method (`GET` or `PUT`), bucket, key, and expiration timestamp. Once expired or if the object is deleted, requests receive `403 FORBIDDEN`. ## Who can do what (Access matrix) | Action | Anonymous key (`anon`) | Signed-in user (`authenticated`) | Service role (`service_role`) | | --- | --- | --- | --- | | **Read file in a public bucket** | Yes | Yes | Yes | | **Read file in a private bucket** | No (`403`) | Owner only (`owner_id = auth.uid()`) | Yes | | **Upload a new file** | No (`403`) | Yes (becomes owner) | Yes | | **Replace (`upsert`) or delete** | No (`403`) | Owner only | Yes | | **List files in a public bucket** | Yes | Yes | Yes | | **List files in a private bucket** | No (`403`) | Owner only (RLS filter) | Yes | | **Create, update, or delete buckets** | No (`403`) | No (`403`) | Yes | | **Mint signed upload URLs** | No (`403`) | No (`403`) | Yes | The owner is identified by the JWT subject (`auth.uid()`). On both public and private buckets, users cannot overwrite or destroy other users' objects. ## Move, copy, metadata & trash ```typescript filename="server/organise.ts" // Copy a file (preserves original Content-Type and custom metadata) await admin.storage.copy('invoices', '2026/draft.pdf', '2026/archive.pdf') // Move or rename a file await admin.storage.move('invoices', '2026/draft.pdf', '2026/final.pdf') // Inspect object metadata (size, MIME type, ETag, custom metadata) const { data: meta } = await admin.storage.getMetadata('invoices', '2026/final.pdf') // List items currently in the trash (30-day retention) const { data: trashItems } = await admin.storage.from('invoices').listTrash() // Restore an object from trash await admin.storage.from('invoices').restore('2026/final.pdf') ``` For real-time image transformations (resizing, format conversion, rotation), see the [Storage SDK Reference](https://aurabase.dev/en/docs/sdk/storage). --- ### Edge Functions Source: https://aurabase.dev/en/docs/functions.md # Edge Functions > Write a function in TypeScript, deploy it with one command, and call it from your app with the public key. ## One function, three ways to trigger it An Edge Function is a piece of server code that Aurabase stores for your project and runs on demand. You trigger the same function in three ways: - **A call**: your app calls `aura.functions.invoke('name')`, or sends an HTTP request, and gets the answer. - **A job**: you enqueue a call to run in the background, with a delay and automatic retries. - **A schedule**: a cron entry enqueues a job at the times you choose. There are two runtimes: **Deno** (TypeScript or JavaScript, the default) and **WASM** (a compiled Rust binary). Each call runs in its own isolated worker with a memory limit and a timeout. ## The contract of a function A Deno function is one file that calls `Deno.serve`. It receives the request you described and returns a `Response`. ```typescript filename="aurabase/functions/hello/index.ts" Deno.serve(async (req) => { const { name = 'world' } = await req.json().catch(() => ({})) return Response.json({ greeting: `Hello, ${name}!` }) }) ``` An `export default` is never called. A function is a **single file**: relative imports are not shipped, so use `npm:` or `https://esm.sh/` imports. ## Find what you need | I want to… | Read | | --- | --- | | Deploy and call my first function | [Your first Edge Function](https://aurabase.dev/en/docs/functions/quickstart) | | Call a function and know who is calling | [Invoke a function](https://aurabase.dev/en/docs/functions/invoke) | | Handle failures, timeouts and retries | [Errors, timeouts and retries](https://aurabase.dev/en/docs/functions/errors) | | Return text, an image or HTML | [Return text, binary and HTML](https://aurabase.dev/en/docs/functions/responses) | | Give a function an API key | [Secrets and environment variables](https://aurabase.dev/en/docs/functions/secrets) | | Run work in the background or on a schedule | [Jobs, cron and the dead-letter queue](https://aurabase.dev/en/docs/functions/jobs) | | Be warned when something goes wrong | [Alerts](https://aurabase.dev/en/docs/functions/alerts) | | Test locally and deploy from CI | [Test and deploy from CI](https://aurabase.dev/en/docs/functions/testing) | | Look up a command | [aura functions and aura secrets](https://aurabase.dev/en/docs/functions/cli) | | Look up a route | [HTTP API reference](https://aurabase.dev/en/docs/functions/api) | | Look up an SDK method | [JavaScript SDK: functions](https://aurabase.dev/en/docs/functions/sdk) | | Know the sizes, durations and quotas | [Limits and quotas](https://aurabase.dev/en/docs/functions/limits) | | Understand what happens during a call | [How an invocation works](https://aurabase.dev/en/docs/functions/how-it-works) | | Understand who can do what | [Security model](https://aurabase.dev/en/docs/functions/security) | | Move to SDK 0.6 | [Upgrade to SDK 0.6](https://aurabase.dev/en/docs/guides/sdk-0-6-upgrade) | ## Facts to know first - Only **invoking** a function works with the public key. Everything else needs a `service_role` key and belongs on your server. - Requests and responses must stay below about **256 KiB**. Use Storage for larger data. - Every call is stateless. Do not keep data in memory between calls. - Secrets are variables of the function, set with `aura secrets set` or `PUT /env`. Encryption at rest applies only on the `PUT` path and only when the deployment has a key. - What a function writes with `console.log` is not available to you yet. See [limits](https://aurabase.dev/en/docs/functions/limits) for the current gaps. - There is one region and no version history: keep your functions in Git. --- ### Your first Edge Function Source: https://aurabase.dev/en/docs/functions/quickstart.md # Your first Edge Function > You will write a function, deploy it to your project, call it from Node.js and read its result. Every command below was run for real. ## Before you start You need: - Node.js 20 or later. - The `aura` CLI. Install it with `npm install -g @aurabase/cli` (see the [CLI reference](https://aurabase.dev/en/docs/cli) for other platforms). - An Aurabase account. ## 1. Create and link a project Sign in, create a project, and link your working folder to it. Replace `` with the slug shown by `aura orgs list`. ```bash filename="terminal" aura login --email you@example.com --password '' aura orgs list aura projects create my-app --org ``` The last command prints the project URL and your first API keys. **Copy them now: the initial keys are shown only once.** If you miss them, create new ones in the Studio under Settings, API keys. ```text filename="output" ✔ Project created: my-app (e99f2c4f-43e2-4d08-b023-b4f9e687d17c) import { createClient } from '@aurabase/aurabase-js' const client = createClient('http://my-app-ajap5iw2.localhost:8080', 'aura_anon_…') ``` Link the current folder to the project: ```bash filename="terminal" aura link --project-id e99f2c4f-43e2-4d08-b023-b4f9e687d17c ``` ```text filename="output" ✔ Project e99f2c4f-43e2-4d08-b023-b4f9e687d17c linked in aurabase.toml. • Project URL: http://my-app-ajap5iw2.localhost:8080 ``` Then tell the CLI where the data plane is and which key to use. A `service_role` key is required to deploy, because deploying code is an administrative action. ```bash filename=".env" NEXT_PUBLIC_AURABASE_URL=http://my-app-ajap5iw2.localhost:8080 AURABASE_SERVICE_ROLE_KEY= ``` > **Keep the service_role key on your machine** > > A `service_role` key bypasses row-level security and can deploy code. Never put it in a browser bundle or commit `.env`. ## 2. Write the function ```bash filename="terminal" aura functions new hello ``` ```text filename="output" ✔ New function created in aurabase/functions/hello (TypeScript Deno template) ``` Open `aurabase/functions/hello/index.ts` and replace its content: ```typescript filename="aurabase/functions/hello/index.ts" Deno.serve(async (req: Request) => { const { name = 'world' } = await req.json().catch(() => ({})) return new Response(JSON.stringify({ greeting: `Hello, ${name}!` }), { headers: { 'content-type': 'application/json' }, }) }) ``` A function must call `Deno.serve`. An `export default` is never called. ## 3. Deploy it ```bash filename="terminal" aura functions deploy hello ``` ```text filename="output" ✔ Detected TypeScript script (runtime: deno)... • Uploading to service (runtime: deno)... ✔ Function 'hello' deployed successfully! ``` Call it once from the CLI to check that it answers: ```bash filename="terminal" aura functions invoke hello --data '{"name":"Ada"}' ``` ```text filename="output" ✔ Response (200): { "data": { "body": { "greeting": "Hello, Ada!" }, "duration_ms": 74, … ``` ## 4. Call it from the SDK ```bash filename="terminal" mkdir hello-client && cd hello-client npm init -y npm install @aurabase/aurabase-js ``` ```typescript filename="hello.mjs" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.NEXT_PUBLIC_AURABASE_URL, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY) const { data, error } = await aura.functions.invoke('hello', { body: { name: 'Ada' } }) if (error) throw error console.log(data.greeting) ``` ```bash filename="terminal" NEXT_PUBLIC_AURABASE_URL=http://my-app-ajap5iw2.localhost:8080 NEXT_PUBLIC_AURABASE_ANON_KEY=aura_anon_… node hello.mjs ``` ```text filename="output" Hello, Ada! ``` You called a function with the public `anon` key. That is the only call a public key can make: see [who can call what](https://aurabase.dev/en/docs/functions/security). ## Where to go next - [Invoke a function](https://aurabase.dev/en/docs/functions/invoke): browsers, servers, headers and the identity of the caller. - [Errors, timeouts and retries](https://aurabase.dev/en/docs/functions/errors): what to do when a call fails. - [Secrets and environment](https://aurabase.dev/en/docs/functions/secrets): give your function a Stripe key without hard-coding it. - [How an invocation works](https://aurabase.dev/en/docs/functions/how-it-works): what happened between your `invoke` and the response. --- ### How an invocation works Source: https://aurabase.dev/en/docs/functions/how-it-works.md # How an invocation works > A walk through one call, to explain the limits, the error codes and the timing you observe. ## The path of a call ```text filename="one invocation" your code ── invoke('hello') ──▶ gateway (data plane) • checks the key and the user's token • finds the project from the host • adds x-aura-role, x-aura-user-id, x-aura-project-id │ message bus (request / reply) ▼ functions service • access policy: only invoke is public • reads the function, reserves one invocation of the plan quota │ HTTP ▼ edge runtime • loads code, limits and variables • starts an isolated V8 worker • rebuilds the request you described ▼ your function ── Response ──▶ back along the same path ``` The gateway and the functions service talk over a message bus. A message on that bus has a size limit, which is why a request or a response above about 256 KiB does not go through: see [limits](https://aurabase.dev/en/docs/functions/limits). ## Inside the runtime - **One worker per call.** The edge runtime starts a new isolated V8 worker for each invocation, with the memory limit and the timeout of the function. Nothing in memory survives from one call to the next: do not keep state in a variable. Use your database or Storage. - **Code is cached for a few seconds.** The runtime keeps the code and the limits of a function for 5 seconds and drops them when you deploy. Variables are read on every call. - **Your request is rebuilt.** The runtime creates the request you described (`method`, `path`, `headers`, `body`) and hands it to your `Deno.serve` handler. A function therefore behaves like any HTTP server. - **The runtime enforces the timeout.** When `timeout_secs` elapses, it cancels the worker; the caller sees an error after about that delay. - **WASM functions** run inside the service itself, with limits on memory, time and instructions. A WASM function can report log lines, which appear in the `logs` field of the response; a Deno function cannot. ## The envelope and raw mode The service has two ways to return your function's answer, chosen by the `X-Aurabase-Invoke-Mode` request header. | | Envelope (default) | Raw (`raw`) | | --- | --- | --- | | HTTP status | Always `200` | The function's own status | | Body | `{ data: { status, headers, body, logs, duration_ms }, meta }` | The function's bytes | | Content | JSON or UTF-8 text | Anything, including binary | | Used by | `responseType: 'json'`, the Studio | `'text'`, `'blob'`, `'arrayBuffer'`, direct HTTP | The envelope exists so that one JSON response can carry the status, headers and duration of the call. Its limit is that bytes cannot travel in JSON: this is why a binary response needs raw mode. The SDK chooses the mode from `responseType`. In raw mode the service adds `x-aurabase-invoke-origin: function` to the answers of your function. An error that comes from the gateway or the runtime does not carry it. This is how the SDK separates `FunctionsHttpError` (your function answered) from `FunctionsRelayError` (the platform failed). ## Time, metering and failures Three timeouts are nested so that none ends before the one inside it: ```text filename="timeouts, outside to inside" gateway 380 s ⊃ message bus 370 s ⊃ function timeout_secs (≤ 300 s) + margin ``` The service waits for the runtime for `timeout_secs` plus a margin. Because the runtime cancels the worker at `timeout_secs`, you normally see an error from the function at that moment, and a `504 TIMEOUT` only if the runtime itself stops answering. A `504` therefore means that the function **was started** and may have had effects: do not repeat a non-idempotent call blindly. Metering and quota: 1. Before the call, the service reserves one invocation from the plan quota. If the quota is exhausted, the call stops here with `403`. 2. After the call, it records the invocation and its duration in milliseconds. 3. If the call fails before your function answers, the reservation is released and nothing is counted. ## What follows for your code - Keep each call short and stateless. For long work, [enqueue a job](https://aurabase.dev/en/docs/functions/jobs). - Keep requests and responses small; put files in Storage and pass a reference. - Make functions idempotent: a retried job, a client retry after a network error or a duplicated cron delivery can run your code twice. - Authorise on the platform's identity headers, because they are the only values the caller cannot forge. See [security](https://aurabase.dev/en/docs/functions/security). - Measure your own latency: each call pays for the start of a worker. A minimal function reported `duration_ms: 74` on a local stack. --- ### Edge Functions security model Source: https://aurabase.dev/en/docs/functions/security.md # Edge Functions security model > The rules that keep your functions, their code and their secrets private, and the places where you remain responsible. ## Keys and roles | Role | Key | Can do | | --- | --- | --- | | `anon` | Public key, safe in a browser | Invoke a function | | `authenticated` | Public key plus a signed-in user's JWT | Invoke a function, with the user's identity | | `service_role` | Secret key, **server only** | Everything: deploy, read code and secrets, jobs, cron, alerts | | `admin` | A console session in the Studio | Everything, from the Studio | The role comes from the key and the token, which the platform validates. A client cannot choose it: a call with the public key and a header `x-aura-role: service_role` still reaches your function as `anon`. Every route and its role is listed in the [HTTP API reference](https://aurabase.dev/en/docs/functions/api). ## Why only invocation is public A public key is published in your web or mobile app, so anyone can read it. Whatever it allows, everyone is allowed. Invoking a function is the one operation designed for that: your code decides what a caller may do. Reading the **definition** of a function is different. It contains the source code and the environment variables, which often hold secrets. Listing jobs and alerts shows your data. Enqueuing a job runs your code on your quota. None of these can be public, and the platform refuses them with `403` for any key that is not `service_role`. The same split exists elsewhere. Supabase validates a user's JWT before an Edge Function runs by default (`verify_jwt = true`) and deploys functions through its CLI and platform ([docs](https://supabase.com/docs/guides/functions/auth.md)). Firebase enqueues tasks from a trusted server environment through the Admin SDK, with an IAM permission ([docs](https://firebase.google.com/docs/functions/task-functions)). Cloudflare lets only a Worker send to a queue, through a binding ([docs](https://developers.cloudflare.com/queues/configuration/javascript-apis/)). > **Before the fix, a public key could read definitions** > > Earlier versions of the service answered `GET /v1/functions` and `GET /v1/functions/{name}` to any key. If your project ran on a deployment that predates this fix, treat the code and variables of your functions as exposed and rotate the secrets they contain. See [upgrade to 0.6](https://aurabase.dev/en/docs/guides/sdk-0-6-upgrade). ## Identity cannot be forged Your function reads the caller from `x-aura-role`, `x-aura-user-id` and `x-aura-project-id`. The platform sets them after it validates the key and the token. - A caller cannot supply them. The platform discards `authorization`, `apikey`, `x-request-id` and any `x-aura-*` header sent in the `headers` of an invocation, whatever their case. In a real test, a call with `x-aura-role: service_role` and a forged `authorization` reached the function as `role: "anon"` with no `authorization`. - Other custom headers pass through untouched. Treat them as user input. - Jobs and cron firings reach your function **without** identity headers. They are triggered by the platform, not by a user. So authorise on `x-aura-role` and `x-aura-user-id`, never on a value from the body: ```typescript filename="aurabase/functions/delete-account/index.ts" Deno.serve((req) => { const userId = req.headers.get('x-aura-user-id') if (req.headers.get('x-aura-role') !== 'authenticated' || !userId) { return new Response('Forbidden', { status: 403 }) } // delete the account of `userId`, never of an id taken from the body return new Response('ok') }) ``` ## The sandbox What the platform gives you: - Each call runs in its own V8 isolate, with its own memory limit and wall-clock timeout. A crash or an infinite loop in one call does not affect another. - The host's environment variables are invisible: `Deno.env.get('PATH')` returned `undefined` in a real run. Only your function's variables and the platform's `AURABASE_*` variables are present. - The code of one project cannot be read by another: the service that serves it requires an internal token. - Responses that can run scripts are served with a sandboxing content security policy, and `Set-Cookie` and CORS headers from a function are dropped. See [responses](https://aurabase.dev/en/docs/functions/responses). What it does **not** give you: - **Outbound network is open unless you restrict it.** When `permissions.allow_net` lists at least one host, the runtime refuses a `fetch` to any other host (`Requires net access to "host:443"`). An empty list, the default, restricts nothing. List every host the function needs, including your project URL if it calls the platform. Even with a list, validate any URL taken from user input. - **No protection of your own secrets in logs.** Anything your function writes with `console.log` goes to the runtime's logs. - **No limit per user.** The invocation rate limit is per client IP. Add your own check if one user must not call a function more than a few times. ## Checklist - The `service_role` key exists only on your servers and in your CI secrets. - The browser bundle contains the public key only. The SDK refuses a `service_role` key in a browser by default. - Every function checks `x-aura-role` before it does anything sensitive. - Secrets are variables of the function, never in `index.ts`. - Functions that call external URLs validate the destination. - You rotate a key by creating a new one in the Studio, deploying it as a secret, then revoking the old one. --- ### Invoke a function Source: https://aurabase.dev/en/docs/functions/invoke.md # Invoke a function > How to call a deployed function with the JavaScript SDK or over HTTP, and how your function knows who is calling. ## Call from the SDK `invoke` is the only call a public key can make. It works the same in a browser and on a server. ```typescript tab="Browser or server" filename="src/lib/call.ts" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!) const { data, error } = await aura.functions.invoke<{ greeting: string }>('hello', { body: { name: 'Ada' }, }) if (error) throw error console.log(data?.greeting) ``` ```typescript tab="Signed-in user" filename="src/lib/call-as-user.ts" // After sign-in, the SDK adds the user's JWT to every call: no extra code. await aura.auth.signInWithPassword({ email, password }) const { data } = await aura.functions.invoke('whoami') // The function sees x-aura-role: authenticated and the user's id. ``` The generic `invoke` only types the response. The name and the body are not checked at compile time. > **A public key can only invoke** > > `list`, `get`, `listJobs`, `enqueueJob` and the other management methods need a `service_role` key and belong on your server. A public key receives `403`. See [who can call what](https://aurabase.dev/en/docs/functions/security). ## Describe the request Your function receives **exactly** the request you describe, not a wrapper around it. | Option | Default | What the function sees | | --- | --- | --- | | `method` | `POST` | `req.method` | | `path` | `/` | `new URL(req.url).pathname` | | `headers` | none | `req.headers`, except the platform headers listed below | | `body` | none | `await req.json()` (or `req.text()` for a string) | | `timeout` | client default (30 s) | not visible: cancels your call | | `signal` | none | not visible: cancels your call | | `responseType` | `'json'` | not visible: how the SDK decodes the response, see [non-JSON responses](https://aurabase.dev/en/docs/functions/responses) | ```typescript filename="request.ts" await aura.functions.invoke('items', { method: 'PUT', path: '/items/1', headers: { 'x-source': 'dashboard' }, body: { qty: 2 }, }) ``` ```typescript filename="aurabase/functions/items/index.ts" Deno.serve(async (req) => { const url = new URL(req.url) // pathname: '/items/1' const source = req.headers.get('x-source') // 'dashboard' const body = await req.json() // { qty: 2 } return Response.json({ method: req.method, id: url.pathname.split('/').pop(), source, body }) }) ``` Rules worth knowing: - `GET` and `HEAD` are sent without a body. - A body that is not a string is sent as JSON, with `content-type: application/json` unless you set one. A **string** body is sent as-is and also gets `content-type: application/json`, so read it with `req.text()`. - With no `body`, the function receives a request with no body. A bare `await req.json()` throws, so write `await req.json().catch(() => ({}))` when the call can be made without a payload. - The body must be JSON: an object, array, string, number or boolean. A `Blob`, `ArrayBuffer`, typed array, `FormData`, `URLSearchParams` or `ReadableStream` is refused with the error code `invalid_body` before any request is sent. - Framing headers (`content-length`, `transfer-encoding`, `connection`, `host`, …) are ignored. ## Read the caller's identity The platform validates the key and the user's token before your function runs, then adds these headers: | Header | Value | | --- | --- | | `x-aura-role` | `anon`, `authenticated` or `service_role` | | `x-aura-user-id` | The user's id when `x-aura-role` is `authenticated`, otherwise absent | | `x-aura-project-id` | The project id | | `authorization` | The user's JWT, only for a signed-in user | | `apikey` | The key used for the call | ```typescript filename="aurabase/functions/whoami/index.ts" Deno.serve((req) => { if (req.headers.get('x-aura-role') !== 'authenticated') { return new Response('Sign in first', { status: 401 }) } return Response.json({ userId: req.headers.get('x-aura-user-id') }) }) ``` Real results of this call with three different keys: ```json filename="results.json" { "role": "anon", "userId": null } { "role": "authenticated", "userId": "b125f8cd-ddc8-4042-9d9d-2e0aa3cebe51" } { "role": "service_role", "userId": null } ``` > **A caller cannot forge these headers** > > The platform discards `authorization`, `apikey`, `x-request-id` and every `x-aura-*` header that a caller puts in `headers`, whatever their case. Only the values it verified itself reach your function. Other custom headers pass through unchanged. > **No request id inside the function** > > The `x-request-id` of the call is not forwarded to your function. To correlate a call with a log line, generate your own id, send it in `headers` and log it in the function. ## Call over HTTP Without the SDK, send a JSON object that describes the request. The `body` field is what your function receives. ```bash filename="terminal" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/hello/invoke" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -d '{"body":{"name":"Ada"}}' ``` Both `apikey` and `Content-Type: application/json` are required. Add `Authorization: Bearer ` to call as a signed-in user. The default response is an envelope; the `X-Aurabase-Invoke-Mode: raw` header returns your function's own response instead, see [non-JSON responses](https://aurabase.dev/en/docs/functions/responses). ## Read the result `invoke` never throws. It returns `{ data, error }`: ```typescript filename="result.ts" const { data, error } = await aura.functions.invoke('hello', { body: { name: 'Ada' } }) if (error) { // error.status: HTTP status of the failure // error.message: the text your function returned, or the platform's explanation return } // data is null when the function returned no content (for example a 204) if (data === null) return console.log(data) ``` Test `data` rather than `error` when you need the value: TypeScript then knows it is not `null`. To handle failures precisely, read [errors, timeouts and retries](https://aurabase.dev/en/docs/functions/errors). --- ### Errors, timeouts and retries Source: https://aurabase.dev/en/docs/functions/errors.md # Errors, timeouts and retries > How to read what `invoke` returns when something goes wrong, and when you can safely call again. ## The error object `invoke` returns `{ data, error }` and never throws. `error` is an `AuraError`, so `isAuraError(error)` is true. Two subclasses tell you **who failed**: ```typescript filename="classify.ts" import { FunctionsHttpError, FunctionsRelayError } from '@aurabase/aurabase-js' const { data, error } = await aura.functions.invoke('checkout', { body }) if (error instanceof FunctionsHttpError) { // Your function answered, with an error status. Debug your code. } else if (error instanceof FunctionsRelayError) { // The platform failed: the answer of your function never came back. } else if (error) { // The call was cancelled or refused on the client (TIMEOUT, INVALID_BODY, NO_SESSION). } ``` | Field | Meaning | | --- | --- | | `error.status` | HTTP status. `0` means the failure happened on the client (no response). | | `error.code` | Stable identifier, for example `NOT_FOUND`, `QUOTA_EXCEEDED`, `TIMEOUT`, `INVALID_BODY`. | | `error.message` | The text your function returned, or the platform's explanation. | | `error.context` | On a `FunctionsHttpError`: the body your function returned (parsed JSON or text). | | `error.details` | The raw error body. For a platform error it contains `error.request_id`. | ## Which error is it? Behaviours observed against a running stack. The quota row follows the backend's error mapping and was not triggered in our tests. | What happened | Class | `status` | `code` | `message` | | --- | --- | --- | --- | --- | | The function does not exist | `FunctionsHttpError` | 404 | `NOT_FOUND` | "…Fonction 'nope' introuvable" | | Your function returns `500` with text | `FunctionsHttpError` | 500 | `http_500` | that text | | Your function returns `503` itself | `FunctionsHttpError` | 503 | `http_503` | what you returned | | Your function throws | `FunctionsHttpError` | 500 | `http_500` | "Internal Server Error" | | Your function exceeds its `timeout_secs` | `FunctionsHttpError` | 500 or 503 | `http_500` / `http_503` | "Function execution failed" or "Function returned HTTP 503" | | The runtime is unreachable | `FunctionsRelayError` | 503 | `SERVICE_UNAVAILABLE` | explains that the function was **not** run | | The network fails before any response | `FunctionsRelayError` | 0 | `NETWORK_ERROR` | the network error | | Plan quota exhausted | `FunctionsHttpError` | 403 | `QUOTA_EXCEEDED` | the quota message | | Too many calls from one client | `FunctionsHttpError` | 429 | `RATE_LIMITED` | wait message | | Request body too large | `FunctionsRelayError` | 503 | `SERVICE_UNAVAILABLE` | "max payload size exceeded" | | You cancelled, or your `timeout` elapsed | `AuraError` | 0 | `TIMEOUT` | "Function invocation aborted or timed out" | | The body cannot be sent as JSON | `AuraError` | 0 | `invalid_body` | names the type to avoid | > **A 503 from your function is not a platform failure** > > If your own code returns `502`, `503` or `504`, you get a `FunctionsHttpError`: the class tells you who answered, not what the status number is. > **Two failures look like something else** > > A request body above about 256 KiB is rejected with `503 SERVICE_UNAVAILABLE`, and a **response** of about 300 KB or more did not return within our 50-second test. See [limits](https://aurabase.dev/en/docs/functions/limits). Retrying does not help; send less data, or use Storage. ## Decide whether to retry The SDK never retries an invocation for you: your function may have side effects, and a repeated `POST` is not safe by default. You decide, using the table below. | Failure | Did the function run? | Safe to retry? | | --- | --- | --- | | `503` from the platform (`FunctionsRelayError`) | No, the runtime was unreachable | Yes, with a short back-off | | `429` | No | Yes, after the delay in `error.retryAfter` | | `403` `QUOTA_EXCEEDED` | No | No, until the quota resets or you change plan | | `status 0` (`NETWORK_ERROR`) | Unknown | Only if your function is idempotent | | `TIMEOUT` on the client | Unknown | Only if your function is idempotent | | `FunctionsHttpError` 5xx | Yes, partially or fully | Only if your function is idempotent | | `FunctionsHttpError` 4xx | Yes | No: fix the request | ```typescript filename="retry.ts" import { FunctionsRelayError } from '@aurabase/aurabase-js' async function invokeWithRetry(name: string, body: unknown, attempts = 3) { for (let i = 0; i < attempts; i++) { const res = await aura.functions.invoke(name, { body }) const safe = res.error instanceof FunctionsRelayError && res.error.status === 503 if (!res.error || !safe) return res await new Promise((r) => setTimeout(r, 2 ** i * 500)) } return aura.functions.invoke(name, { body }) } ``` > **Make the function idempotent instead** > > The platform does not deduplicate calls and ignores `Idempotency-Key`. For payments or e-mail, store a key that you pass in `body` and check it at the start of the function. ## Timeouts Three clocks run at once: | Clock | Default | Where to change it | | --- | --- | --- | | Your client | 30 s for every `responseType` | `invoke(…, { timeout })`, `{ signal }`, or `requestTimeoutMs` in the client options | | The function | 30 s, between 1 and 300 | `permissions.timeout_secs` on the function | | The gateway | 380 s | not configurable by projects | When the function exceeds `timeout_secs`, the runtime cancels it and your call fails after about that delay, with the 500 or 503 shown above. The cause appears in `error.context.detail` (`WorkerRequestCancelled: request has been cancelled by supervisor`) in raw mode. Set your client `timeout` slightly above the function's `timeout_secs` to see this error instead of a client `timeout`. ```typescript filename="timeout.ts" const { error } = await aura.functions.invoke('report', { timeout: 35_000 }) if (error?.code === 'TIMEOUT') { // Cancelled by your client. The function may still be running. } ``` For work longer than a few seconds, [enqueue a job](https://aurabase.dev/en/docs/functions/jobs) instead of holding a connection open. ## Find the cause - Platform errors carry a request id: `error.details.error.request_id`. Quote it when you contact support. - `aura functions logs ` lists recent HTTP requests with method, path, status, duration and request id. It does **not** show what your function wrote with `console.log` or `console.error`: that output stays in the runtime's own logs, which only the platform operator can read. See [limits](https://aurabase.dev/en/docs/functions/limits) for this and the other current gaps. - The identifier of the call is not forwarded to your function. Pass your own id in `headers` and log it. --- ### Return text, binary and HTML Source: https://aurabase.dev/en/docs/functions/responses.md # Return text, binary and HTML > How to send text, images, files or HTML from a function and read them back with the SDK or plain HTTP. ## Choose a response type | Your function returns | Use `responseType` | `data` is | | --- | --- | --- | | JSON | `'json'` (default) | the parsed value | | Plain text, CSV, HTML | `'text'` (or `'json'`, which also returns the string) | a `string` | | An image, a PDF, any bytes | `'blob'` or `'arrayBuffer'` | a `Blob` or an `ArrayBuffer` | The default `'json'` mode can carry JSON and text. It **cannot** carry bytes: if a function answers with a binary content type, the SDK returns the error `invalid_response` and tells you to pick `'blob'` or `'arrayBuffer'`, so nothing is lost silently. ## Read it with the SDK ```typescript filename="aurabase/functions/export/index.ts" Deno.serve((req) => { const { pathname } = new URL(req.url) if (pathname === '/csv') { return new Response('id,name\n1,Ada\n', { headers: { 'content-type': 'text/csv' } }) } // The 8-byte PNG signature, enough to show bytes round-trip const bytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]) return new Response(bytes, { headers: { 'content-type': 'image/png' } }) }) ``` ```typescript filename="client.ts" const csv = await aura.functions.invoke('export', { path: '/csv', responseType: 'text' }) console.log(csv.data) // "id,name\n1,Ada\n" const img = await aura.functions.invoke('export', { responseType: 'blob' }) console.log(img.data?.type, img.data?.size) // "image/png" 8 ``` In a real run with a function returning the bytes `137,80,78,71,13,10,26,10,255,0,1`, `arrayBuffer` returned exactly those 11 bytes and `blob` returned `type=image/png size=11`. With `'text'`, `'blob'` or `'arrayBuffer'`, the SDK skips the JSON envelope and returns the body of your function as it is. If your function answers with an error status, `error.status` is that status and `error.message` is the text your function returned. ## Raw mode over HTTP Add the header `X-Aurabase-Invoke-Mode: raw` and the platform returns your function's own response: its status, `content-type` and bytes. ```bash filename="terminal" curl -i -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/export/invoke" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -H "X-Aurabase-Invoke-Mode: raw" \ -d '{"path":"/csv"}' --output export.csv ``` Without that header, the response is always `200` with an envelope: ```json filename="envelope.json" { "data": { "status": 200, "headers": { "content-type": "application/json" }, "body": { "greeting": "Hello, Ada!" }, "logs": [], "duration_ms": 74 }, "meta": null } ``` In the envelope, `body` is the parsed JSON, the text of your response when it is UTF-8 and not JSON, or `null` when the body is empty or binary. In raw mode every response from your function carries `x-aurabase-invoke-origin: function`. A response without it comes from the gateway or the runtime. This is how the SDK tells a `503` returned by your code from a platform outage. ## Which headers survive In raw mode your response headers are filtered, because they are served from the platform's own origin. | Header | Result | | --- | --- | | `content-type` | Kept. Defaults to `application/octet-stream` if you set none. | | Custom headers (`x-custom-out`, `cache-control`, …) | Kept. | | `set-cookie` | Removed. A function cannot set cookies. | | `access-control-*` | Removed. CORS is decided by the gateway. | | `x-aura-*`, `x-internal-token` | Removed. | | `content-security-policy`, `strict-transport-security`, `x-content-type-options` | Set by the platform, whatever you send. | | `content-length`, `transfer-encoding`, `connection` | Recomputed. | A response that can run scripts (`text/html`, `application/xhtml+xml`, `image/svg+xml`, `application/xml`, `text/xml`) is served with a sandboxing content security policy. Real response for a function returning `text/html`: ```text filename="response headers" content-type: text/html content-security-policy: default-src 'none'; frame-ancestors 'none'; sandbox x-content-type-options: nosniff ``` Your HTML is served, but without cookie, storage or script access to your project's origin. Use Storage or your own domain to host a real web page. --- ### Secrets and environment variables Source: https://aurabase.dev/en/docs/functions/secrets.md # Secrets and environment variables > How to pass a Stripe key or any setting to a function without writing it in the code, and what the platform actually protects. ## Set a variable Every variable belongs to one function. Setting variables needs a `service_role` key. ```bash tab="CLI" filename="terminal" aura secrets set --function checkout STRIPE_SECRET_KEY=sk_live_… WEBHOOK_SECRET=whsec_… aura secrets list --function checkout # values are masked: STRIPE_SECRET_KEY sk_l*** aura secrets unset --function checkout WEBHOOK_SECRET ``` ```bash tab="HTTP (PUT /env)" filename="terminal" curl -X PUT "$NEXT_PUBLIC_AURABASE_URL/v1/functions/checkout/env" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ -d '{"vars":[{"key":"STRIPE_SECRET_KEY","value":"sk_live_…"}]}' ``` `PUT /env` **replaces** the whole set of variables with the list you send. `aura secrets set` and `unset` read the current values, change the keys you name and write the result back. > **Redeploying keeps your secrets** > > Deploying new code with `aura functions deploy` leaves the variables untouched. ## Read it in the function ```typescript filename="aurabase/functions/checkout/index.ts" Deno.serve(async (req) => { const key = Deno.env.get('STRIPE_SECRET_KEY') if (!key) return new Response('STRIPE_SECRET_KEY is not set', { status: 500 }) // …call Stripe with `key` return Response.json({ ok: true }) }) ``` Variables are read at every invocation: a change applies to the next call. ## Variables the platform adds | Variable | Value | | --- | --- | | `AURABASE_PROJECT_ID` | The project id. Always set. | | `AURABASE_FUNCTION_NAME` | The function's name. Always set. | | `AURABASE_URL` | The platform URL, when the platform operator defines it. | | `AURABASE_ANON_KEY` | A platform key, when the operator defines it. | These `AURABASE_*` names belong to functions: you read them with `Deno.env.get(...)` inside a function. They are not the variables of your application, which are `NEXT_PUBLIC_AURABASE_URL` and `NEXT_PUBLIC_AURABASE_ANON_KEY` (browser) or `AURABASE_SERVICE_ROLE_KEY` (server): use those in your Next.js, Vite or Node code, and these only in the code of a function. `AURABASE_URL` is the platform's address, not your project's `https://.` URL. You cannot override these names. The host's environment is not visible to your function: in a real run `Deno.env.get('PATH')` returned `undefined`. To call your own project from a function, store a `service_role` key as a secret of that function and send it in the `apikey` header of an HTTP request. Never forward the key of a user, and never put a `service_role` key in a browser. ## What is encrypted | Path | Encrypted at rest | | --- | --- | | `PUT /v1/functions/{name}/env` | Yes, **if** the service has an encryption key configured (`FN_ENV_ENCRYPTION_KEY`, AES-256-GCM). Without it, values are stored as sent and the service logs a warning at start. | | `aura secrets set` / `unset` | No: the CLI writes through `PATCH`, which stores the values as sent. | | `env_vars` in a deploy request | No, same reason. | In our local test, a value written by `PUT /env` was returned unchanged by the function's definition, because no key was configured. > **Ask your platform operator before relying on encryption** > > Whether secrets are encrypted depends on the deployment, and only the `PUT /env` path can encrypt them. The CLI path stores them as given. Until the CLI uses `PUT /env`, use the HTTP call above for production secrets. Reading secrets back is restricted too. `GET /v1/functions/{name}/env` returns the decrypted values and, like `GET /v1/functions/{name}`, requires a `service_role` key. A public key receives `403`. ## Rules to follow - Never hard-code a secret in `index.ts`. The source code of a function is stored in your project and returned to any `service_role` caller. - Never log a secret. The output of `console.log` ends up in the runtime's logs. - Use one variable per function, with the narrowest key that works (a restricted key from your provider, not the master key). - Rotate a key by setting the new value and redeploying nothing: the next call uses it. --- ### Jobs, cron and the dead-letter queue Source: https://aurabase.dev/en/docs/functions/jobs.md # Jobs, cron and the dead-letter queue > How to run work outside a request: what a job is, how it is retried, how cron creates jobs, and what to do with the jobs that end up dead. ## Enqueue a job A job is one background call to a function. Enqueue it from a server with a `service_role` key. ```typescript filename="server/enqueue.ts" import { createClient } from '@aurabase/aurabase-js' const admin = createClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) const { data: job, error } = await admin.functions.enqueueJob('send-report', { payload: { month: '2026-10' }, delaySecs: 60, // wait 60 seconds before the first attempt maxAttempts: 3, // the default }) ``` | Option | Default | Meaning | | --- | --- | --- | | `payload` | `null` | JSON given to the function as the request body | | `delaySecs` | `0` | Seconds to wait before the first attempt. The job stays `pending` until then. | | `maxAttempts` | `3` | Total number of attempts, the first included | You read a job back with `getJob(id)` or `listJobs({ status, limit })` (`limit` is between 1 and 500, default 50). The job has a `status`, `attempts`, `max_attempts`, `error` and the dates `scheduled_at`, `started_at`, `completed_at`. > **Jobs are a server-side tool** > > `enqueueJob`, `getJob` and `listJobs` need a `service_role` key. A public key receives `403`. ## What your function receives A job calls your function like any other request, with three differences you must handle: | Part | Value | | --- | --- | | Method | `JOB` (not `POST`) | | Path | `/jobs/` | | Body | The job's `payload`, as JSON | | Identity headers | None: `x-aura-role` and `x-aura-user-id` are absent | ```typescript filename="aurabase/functions/send-report/index.ts" Deno.serve(async (req) => { const jobId = new URL(req.url).pathname.split('/').pop() const { month } = await req.json() // …build and send the report, using jobId as an idempotency key return new Response('ok') }) ``` A real call logged `{"method":"JOB","path":"/jobs/d443d541-…","role":null,"userId":null,"body":"{\"items\":[\"a\",\"b\"],\"order\":42}"}`. A job runs without a user: do not rely on `x-aura-user-id`. If the work belongs to a user, put the user's id in the payload. ## Lifecycle and retries ```text filename="statuses" pending ──claimed──▶ running ──▶ completed ▲ │ └── after 5 s ◀── failed (attempts left) └──▶ dead (no attempts left) ``` - A job runs **at least once**. It can run twice if a worker stops while it is running, so make the function idempotent. - A failed attempt is retried after a fixed delay of 5 seconds, until `maxAttempts` is reached. The job is then `dead`. The delay and the default attempt count are service settings (`JOB_RETRY_DELAY_SECS`, `JOB_MAX_RETRIES`). - A job that is still `running` after its lease (450 seconds by default) is reclaimed by the service. - Finished jobs are kept for 14 days by default. > **An HTTP error from your function is not a failure** > > A job is `completed` as soon as your function **answers**, whatever the status code. In a real run, a function that returned `500` produced a `completed` job after one attempt and was never retried. > > A job fails and is retried only when the call itself fails: the function does not exist or is inactive, the runtime is unreachable, or the call times out. If you want a retry when your own code detects an error, enqueue a new job from the handler (with `delaySecs` for a back-off) instead of relying on the status code. In the same real run, a job for a function that does not exist went through this sequence: attempt 1 failed at 3 s with `Fonction 'ghost' introuvable`, attempt 2 failed at about 9 s, and the job became `dead` with `attempts` equal to `max_attempts`. ## The dead-letter queue Dead jobs stay in the queue and can be listed and retried. These routes have no SDK method yet: use HTTP with a `service_role` key. ```bash filename="terminal" # list dead jobs curl "$NEXT_PUBLIC_AURABASE_URL/v1/functions/jobs/dlq" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" # retry one job curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/jobs/$JOB_ID/retry" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" # retry every dead job (up to 1000) curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/jobs/dlq/requeue" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" # → {"data":{"requeued":1},"meta":null} ``` A retry puts the job back to `pending` **without resetting its attempt counter**, so it gets exactly one more attempt and returns to `dead` if it fails again. Fix the cause (deploy the missing function, for example) before you retry. ## Schedule with cron A cron entry does not call the function itself: each time it fires, it enqueues a job. ```typescript filename="server/cron.ts" await admin.functions.createCronJob('nightly-cleanup', '0 3 * * *', 'cleanup', { payload: { dryRun: false }, }) const { data: crons } = await admin.functions.listCronJobs() await admin.functions.deleteCronJob('nightly-cleanup') // by NAME, not by id ``` - The schedule has **5 fields** (`min hour day month weekday`) or **6 fields** (`sec min hour day month weekday`). A 5-field schedule gets `0` seconds in front: `*/1 * * * *` is stored as `0 */1 * * * *`. - Aliases such as `@daily` are refused with a `400` that states the expected format. - Times are in UTC. - `last_run` and `next_run` are `null` until the first firing. In a real run, a schedule created at 15:40 fired at 15:41:00 and then showed `next_run` 15:42:00. - The payload is frozen when you create the entry. - Deleting an unknown name returns `404`. Deleting a cron entry also stops it from firing. - The SDK has no `getCronJob` or `updateCronJob`: delete the entry and create it again. For recurring scheduled workloads, configure a cron schedule targeting an Edge Function on the [Cron](https://aurabase.dev/en/docs/cron) page. --- ### Alerts Source: https://aurabase.dev/en/docs/functions/alerts.md # Alerts > How to be told when your functions misbehave: the metrics you can watch, how rules are checked, and how to manage them over HTTP. ## Create a rule Alert rules are managed over HTTP with a `service_role` key. The SDK has no method for them. ```bash filename="terminal" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/alerts" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "High error rate", "metric": "error_rate", "condition": "gt", "threshold": 5, "channel": "email", "destination": "oncall@example.com" }' ``` ```json filename="response" { "data": { "id": "3356d54a-ed32-49df-84bf-94ee64790c78", "name": "High error rate", "metric": "error_rate", "condition": "gt", "threshold": 5.0, "channel": "email", "destination": "oncall@example.com", "enabled": true, "last_triggered_at": null, "created_at": "2026-10-12T15:42:34.721256Z" }, "meta": null } ``` ## Metrics, conditions and channels | Field | Allowed values | | --- | --- | | `metric` | `error_rate`, `latency_p95`, `job_failures`, `low_disk`, `ai_quota`, `anomaly_detection`, or `log_pattern::` | | `condition` | `gt`, `lt`, `eq`, `match`, `auto` | | `channel` | `email`, `webhook`, `slack` | | `threshold` | A number | | `destination` | An e-mail address, or the URL of the webhook or Slack hook | `log_pattern` watches the logs of one service for a regular expression: `log_pattern:functions:timeout`. An unknown value returns `400` and lists the accepted ones. Real answer for `metric: "cpu"`: ```text filename="error" Requête invalide : Métrique inconnue: 'cpu'. Valeurs: error_rate, latency_p95, job_failures, low_disk, ai_quota, anomaly_detection, log_pattern:: ``` ## How rules are checked - The service checks every enabled rule **once per minute**. - Numeric metrics are read from Prometheus; `log_pattern` rules query Loki. Each query has a 5-second limit. If one project fails, the others are still checked. - When a rule fires, the service sets `last_triggered_at`, records an event and publishes it for delivery on the chosen channel. - A rule you disable is kept but not checked. > **Delivery depends on your deployment** > > Alerts need Prometheus and Loki to be reachable from the functions service, and the e-mail channel needs an e-mail provider. On a development stack without them, a rule is stored but cannot fire. ## Manage rules and history | Action | Request | | --- | --- | | List rules | `GET /v1/functions/alerts` | | Enable or disable | `PATCH /v1/functions/alerts/{id}` with `{"enabled": false}` | | Delete | `DELETE /v1/functions/alerts/{id}` | | History of one rule | `GET /v1/functions/alerts/{id}/events` | | History of all rules | `GET /v1/functions/alerts/events` | An event has `alert_rule_id`, `event_type`, `triggered_value`, `message` and `created_at`; the history routes accept `limit` and `offset`. Every route needs a `service_role` key. --- ### Outgoing Webhooks & HMAC Signatures Source: https://aurabase.dev/en/docs/functions/webhooks.md # Outgoing Webhooks & HMAC Signatures > Receive real-time events from your Aurabase project on your own servers securely using HMAC-SHA256 cryptographic signatures. ## Webhooks architecture Aurabase outgoing webhooks broadcast system events to your callback URLs (e.g. new user registration, successful payment, table row update). > **At-Least-Once Delivery Guarantee** > > Each webhook sent contains a unique event identifier `event_id` allowing you to implement idempotent processing on your servers. ## Structure of the X-Aurabase-Signature header Each HTTP POST request issued by Aurabase includes the following security header: ```text filename="http-headers" POST /webhook HTTP/1.1 Host: api.votre-domaine.com Content-Type: application/json X-Aurabase-Event-Id: evt_01J8Y6Q9K3M7Z... X-Aurabase-Signature: t=1724060000,v1=9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 ``` ## Verify HMAC-SHA256 signature **Node.js / TypeScript** ```typescript tab="Node.js / TypeScript" filename="verify-webhook.ts" import crypto from 'node:crypto' export function verifyAurabaseWebhook( rawBody: string, signatureHeader: string, secret: string ): boolean { const parts = Object.fromEntries( signatureHeader.split(',').map(p => p.split('=')), ) const { t: timestamp, v1: signature } = parts // 1. Protection against replay attacks (5 min max) if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) { return false } // 2. Calculation of HMAC-SHA256 on timestamp.rawBody const expected = crypto .createHmac('sha256', secret) .update(timestamp + '.' + rawBody) .digest('hex') // 3. Secure comparison in constant time return crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expected) ) } ``` **Python** ```python tab="Python" filename="verify_webhook.py" import hmac, hashlib, time def verify_aurabase_webhook(raw_body: bytes, sig_header: str, secret: str) -> bool: parts = dict(x.split("=") for x in sig_header.split(",")) timestamp = int(parts.get("t", 0)) signature = parts.get("v1", "") # Replay protection (5 minutes max) if abs(time.time() - timestamp) > 300: return False payload_to_sign = f"{timestamp}.".encode("utf-8") + raw_body expected = hmac.new(secret.encode("utf-8"), payload_to_sign, hashlib.sha256).hexdigest() return hmac.compare_digest(signature, expected) ``` **Go** ```go tab="Go" filename="verify_webhook.go" package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "strings" "time" ) func VerifyAurabaseWebhook(rawBody []byte, sigHeader string, secret string) bool { var t, v1 string for _, part := range strings.Split(sigHeader, ",") { kv := strings.Split(part, "=") if len(kv) == 2 && kv[0] == "t" { t = kv[1] } if len(kv) == 2 && kv[0] == "v1" { v1 = kv[1] } } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(fmt.Sprintf("%s.", t))) mac.Write(rawBody) expected := hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(v1), []byte(expected)) } ``` ## Fault management and dead-letter queue If your server responds with an HTTP error code (4xx, 5xx) or experiences a timeout (time limit of 10 seconds), Aurabase automatically retries the sending according to an exponential **backoff**: - Attempt 1: Immediate - Attempt 2: After 15 seconds - Attempt 3: After 1 minute - Attempt 4: After 5 minutes - Attempt 5: After 30 minutes After 5 consecutive failures, the event is placed in the Studio's **Dead-Letter Queue (DLQ)** for inspection and manual replay. ## To go further - [Notifications & Channels](https://aurabase.dev/en/docs/notifications): Email, SMS, mobile push and webhooks. - [Edge Functions](https://aurabase.dev/en/docs/functions): Create custom receivers and handlers. - [Realtime CDC](https://aurabase.dev/en/docs/realtime): Real-time broadcast via WebSocket and NATS. --- ### Test and deploy from CI Source: https://aurabase.dev/en/docs/functions/testing.md # Test and deploy from CI > A workable loop from the first edit to an automatic deployment, with the limits of local emulation stated up front. ## Run it locally `aura functions serve` runs your file with Deno and restarts it when you save. ```bash filename="terminal" aura functions serve hello --port 54321 curl -X POST http://127.0.0.1:54321/ -H 'Content-Type: application/json' -d '{"name":"Ada"}' ``` It is a plain Deno server. Compared with the platform, it has: - **No platform headers.** `x-aura-role` and `x-aura-user-id` are absent: send them yourself with `curl -H` to test authorisation branches. - **No secrets.** Pass them in your shell: `STRIPE_SECRET_KEY=sk_test_… aura functions serve checkout`. - **No limits.** Memory, timeout, body size and rate limits are not applied. - **Plain requests.** You call the function directly, so `path` and `method` are those of your `curl`, not the SDK's `invoke` options. The SDK cannot target this server, because `invoke` calls the platform route. Test the SDK path against a real project, as below. ## Test it for real Create a project for development (see [your first function](https://aurabase.dev/en/docs/functions/quickstart)), deploy the function there, and test through the SDK. This covers the platform's identity headers, limits and error classes. ```typescript filename="tests/hello.test.ts" import { createClient, FunctionsHttpError } from '@aurabase/aurabase-js' import { describe, expect, it } from 'vitest' const aura = createClient(process.env.AURA_TEST_URL!, process.env.AURA_TEST_ANON_KEY!) describe('hello', () => { it('greets', async () => { const { data, error } = await aura.functions.invoke<{ greeting: string }>('hello', { body: { name: 'Ada' } }) expect(error).toBeNull() expect(data?.greeting).toBe('Hello, Ada!') }) it('reports a missing function as a FunctionsHttpError 404', async () => { const { error } = await aura.functions.invoke('does-not-exist') expect(error).toBeInstanceOf(FunctionsHttpError) expect(error?.status).toBe(404) }) it('refuses to list functions with a public key', async () => { const { data, error } = await aura.functions.list() expect(data).toBeNull() expect(error?.status).toBe(403) }) }) ``` Tips: - Use a dedicated project, never production, and keep its keys in your CI secrets. - The invocation rate limit is 15 calls then 1 per second per IP. Space your tests, or run them serially. ## Deploy from CI The `aura` CLI installs from npm on macOS Apple Silicon and from source elsewhere, so a Linux CI job is simpler with the HTTP API. Deploying is one `POST` per function, authenticated with a `service_role` key. This exact loop was run against a real project and the function answered afterwards. ```yaml filename=".github/workflows/deploy-functions.yml" name: Deploy functions on: push: branches: [main] paths: ['aurabase/functions/**'] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Deploy every function env: NEXT_PUBLIC_AURABASE_URL: ${{ secrets.NEXT_PUBLIC_AURABASE_URL }} AURABASE_SERVICE_ROLE_KEY: ${{ secrets.AURABASE_SERVICE_ROLE_KEY }} run: | set -euo pipefail for dir in aurabase/functions/*/; do name=$(basename "$dir") file="${dir}index.ts" [ -f "$file" ] || continue jq -n --arg name "$name" --rawfile code "$file" \ '{name: $name, runtime: "deno", code: $code}' | curl -sS --fail-with-body -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ --data-binary @- echo " deployed $name" done ``` Facts that make this safe to run on every push: - The `POST` replaces the code of an existing function and **keeps its secrets**, because the body has no `env_vars`. - A function is single-file: relative imports are not shipped. Bundle first if you use local modules. - There is no version history on the server. Your Git history is the rollback: to go back, revert the commit and let CI deploy again. Then run your integration tests against the project you just deployed, in a following job. ## Development, staging and production One project is one environment. Create one project per environment, each with its own URL and keys, and let CI choose the target: | Environment | Project | Deployed when | | --- | --- | --- | | Development | one per developer or shared | on demand, from a branch | | Staging | `my-app-staging` | every push to `main` | | Production | `my-app` | a release tag, after the staging tests pass | Store `NEXT_PUBLIC_AURABASE_URL` and `AURABASE_SERVICE_ROLE_KEY` per GitHub environment, and set each function's secrets separately in each project. Nothing is shared between projects. --- ### Edge Functions HTTP API reference Source: https://aurabase.dev/en/docs/functions/api.md # Edge Functions HTTP API reference > The complete HTTP surface of the functions service, with the role each route requires. ## Conventions **Base URL.** The URL of your project, for example `https://my-app.aurabase.dev`. The project is identified by the host, so the paths below carry no project id. The long form `/v1/functions/{project_id}/…` is accepted as well. **Authentication.** Send your key in the `apikey` header. Add `Authorization: Bearer ` to call as a signed-in user. The Studio calls the same routes with a console session token, which gives it the `admin` role. | Role | How you get it | May call | | --- | --- | --- | | `anon` | The public key of the project | `POST …/invoke` | | `authenticated` | The public key plus a user's JWT | `POST …/invoke` | | `service_role` | The `service_role` key (server only) | Every route below | | `admin` | A console session (the Studio) | Every route below | Any other route answers `403` to `anon` and `authenticated`: ```json filename="403" { "error": { "code": "FORBIDDEN", "type": "forbidden", "request_id": "…", "message": "Accès interdit : Opération réservée au rôle service_role : seule l'invocation d'une fonction est ouverte aux clés publiques" } } ``` **Format.** Bodies are JSON and need `Content-Type: application/json`. A success is `{ "data": …, "meta": null }`. A failure is `{ "error": { "code", "message", "type", "request_id" } }`. **Function object.** | Field | Type | | | --- | --- | --- | | `id`, `project_id`, `name` | string | | | `runtime` | `"deno"` or `"wasm"` | | | `code` | string | Source for `deno`; base64 of the compiled binary for `wasm` | | `code_hash` | string | SHA-256 of `code` | | `env_vars` | object | Key to value | | `permissions` | object | `allow_net` (string array), `memory_mb`, `timeout_secs` | | `is_active` | boolean | | | `created_at`, `updated_at` | ISO 8601 | | ## Functions | Method and path | Role | Body | Response | | --- | --- | --- | --- | | `GET /v1/functions` | service_role | none | array of function objects | | `POST /v1/functions` | service_role | `{ name, runtime, code, env_vars? }` | the function object | | `GET /v1/functions/{name}` | service_role | none | the function object. `{name}` is the name, or the id when no function has that name. | | `PATCH /v1/functions/{name}` | service_role | `{ code?, env_vars?, is_active?, permissions? }` | the function object | | `DELETE /v1/functions/{name}` | service_role | none | `{ "data": null }` | | `GET /v1/functions/{name}/code` | service_role | none | `{ "data": { "code": "…" } }` | | `GET /v1/functions/{name}/env` | service_role | none | `{ "data": [ { "key", "value" } ] }`, values decrypted | | `PUT /v1/functions/{name}/env` | service_role | `{ "vars": [ { "key", "value" } ] }` | `{ "data": null }` | Notes: - `POST` is an upsert on `name`: posting an existing name replaces its code. An `env_vars` field in that body replaces the existing variables; omit it to keep them. - In `PATCH`, `permissions` is merged field by field: `{ "permissions": { "timeout_secs": 60 } }` keeps `allow_net` and `memory_mb`. A field outside its bounds returns `400`. - `PUT …/env` replaces the whole set of variables and is the only route that encrypts them. See [secrets](https://aurabase.dev/en/docs/functions/secrets). - A function with `is_active: false` is not found by `invoke` or by jobs. ```bash filename="deploy.sh" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H "Content-Type: application/json" \ -d '{"name":"hello","runtime":"deno","code":"Deno.serve(() => new Response(\"ok\"))"}' ``` ## Invoke `POST /v1/functions/{name}/invoke`. Role: `anon`, `authenticated` or `service_role`. | Field | Type | Default | | | --- | --- | --- | --- | | `method` | string | `POST` | HTTP method seen by the function | | `path` | string | `/` | Path seen by the function | | `headers` | object | none | Headers given to the function. Reserved headers are dropped. | | `body` | any JSON | none | Body given to the function | | Request header | | | --- | --- | | `apikey` | Required | | `Content-Type: application/json` | Required | | `Authorization: Bearer ` | Optional: call as that user | | `X-Aurabase-Invoke-Mode: raw` | Optional: return the function's own response | Default response, always `200`: ```json filename="200" { "data": { "status": 200, "headers": { "content-type": "application/json" }, "body": { "greeting": "Hello, Ada!" }, "logs": [], "duration_ms": 74 }, "meta": null } ``` `status` is the status of **your function**. `logs` is empty for `deno`. In raw mode the response is your function's own: status, `content-type`, bytes, plus `x-aurabase-invoke-origin: function`. | Failure | Status | `error.code` | | --- | --- | --- | | Function not found or inactive | 404 | `NOT_FOUND` | | Runtime unreachable | 503 | `SERVICE_UNAVAILABLE` | | The platform stopped waiting for the runtime (after `timeout_secs` plus a margin) | 504 | `TIMEOUT` | | Plan quota exhausted | 403 | `QUOTA_EXCEEDED` | | Too many calls from one client | 429 | `rate_limit_exceeded` | | Body above about 256 KiB | 503 | `SERVICE_UNAVAILABLE` | ## Jobs and dead-letter queue | Method and path | Role | Body or query | Response | | --- | --- | --- | --- | | `POST /v1/functions/jobs` | service_role | `{ function_name, payload?, delay_secs?, max_attempts? }` | the job | | `GET /v1/functions/jobs` | service_role | `?status=&limit=` (1 to 500, default 50) | array of jobs | | `GET /v1/functions/jobs/{id}` | service_role | none | the job | | `POST /v1/functions/jobs/{id}/retry` | service_role | none | the job, back to `pending` | | `GET /v1/functions/jobs/dlq` | service_role | `?limit=` | array of dead jobs | | `POST /v1/functions/jobs/dlq/requeue` | service_role | none | `{ "data": { "requeued": 1 } }` | Job object: `id`, `project_id`, `function_name`, `payload`, `status` (`pending`, `running`, `completed`, `failed`, `dead`), `attempts`, `max_attempts`, `error`, `scheduled_at`, `started_at`, `completed_at`, `created_at`. Behaviour: [Jobs, cron and the dead-letter queue](https://aurabase.dev/en/docs/functions/jobs). ## Cron | Method and path | Role | Body | Response | | --- | --- | --- | --- | | `POST /v1/functions/cron` | service_role | `{ name, schedule, function_name, payload? }` | the cron entry | | `GET /v1/functions/cron` | service_role | none | array of entries | | `DELETE /v1/functions/cron/{name}` | service_role | none | `{ "data": null }`, or `404` for an unknown **name** | Entry: `id`, `project_id`, `name`, `schedule` (stored with 6 fields), `function_name`, `payload`, `is_active`, `last_run`, `next_run`, `created_at`. ## Alerts | Method and path | Role | Body or query | | --- | --- | --- | | `POST /v1/functions/alerts` | service_role | `{ name, metric, condition, threshold, channel, destination }` | | `GET /v1/functions/alerts` | service_role | none | | `PATCH /v1/functions/alerts/{id}` | service_role | `{ "enabled": true }` | | `DELETE /v1/functions/alerts/{id}` | service_role | none | | `GET /v1/functions/alerts/{id}/events` | service_role | `?limit=&offset=` | | `GET /v1/functions/alerts/events` | service_role | `?limit=&offset=` | Values and behaviour: [Alerts](https://aurabase.dev/en/docs/functions/alerts). --- ### JavaScript SDK: functions Source: https://aurabase.dev/en/docs/functions/sdk.md # JavaScript SDK: functions > Every method of `aura.functions`, its signature, the role it needs and what it returns. ## Get the client `aura.functions` is a `FunctionsService`. You almost never build it yourself. ```typescript filename="client.ts" import { createClient } from '@aurabase/aurabase-js' const aura = createClient('https://my-app.aurabase.dev', 'aura_anon_…') aura.functions.invoke('hello') ``` The package `@aurabase/functions` is installed with `@aurabase/aurabase-js`. Install it alone only if you compose your own client from `@aurabase/core`. It requires Node.js 20 or later and ships ES modules and CommonJS with type declarations. Every method returns `Promise>`, an object `{ data, error }` that never throws: | Case | `data` | `error` | | --- | --- | --- | | Success | the value | `null` | | Success without content (204, empty body) | `null` | `null` | | Failure | `null` | an `AuraError` | Test `data` rather than `error` when you need the value: only then does TypeScript know it is not `null`. | Method | Role needed | | --- | --- | | `invoke` | public key (`anon`), user, or `service_role` | | every other method | `service_role` (server only) | ## invoke ```typescript filename="signature" invoke( name: string, options?: { body?: unknown method?: string path?: string headers?: Record signal?: AbortSignal timeout?: number responseType?: 'json' | 'text' | 'blob' | 'arrayBuffer' }, ): Promise> ``` | Option | Default | | | --- | --- | --- | | `body` | none | JSON-serialisable. A `Blob`, `ArrayBuffer`, typed array, `FormData`, `URLSearchParams` or `ReadableStream` returns the error `invalid_body` without any request. | | `method` | `'POST'` | The method the function sees | | `path` | `'/'` | The path the function sees | | `headers` | none | Headers given to the function. `authorization`, `apikey`, `x-request-id` and `x-aura-*` are discarded by the platform. | | `timeout` | client default, 30 s | Milliseconds. Cancels the call and returns the code `timeout`. | | `signal` | none | Your own `AbortSignal`. A cancelled call returns the code `timeout`. | | `responseType` | `'json'` | How `data` is decoded: a parsed value, a string, a `Blob` or an `ArrayBuffer` | `name` is encoded in the URL, so a value containing `/`, `?` or `#` cannot leave its position. A name that contains such characters is not found. `invoke` refreshes an expired user session first, sends the user's JWT when there is one, and never retries a call. How to use it: [Invoke a function](https://aurabase.dev/en/docs/functions/invoke). How it fails: [Errors, timeouts and retries](https://aurabase.dev/en/docs/functions/errors). ## list and get ```typescript filename="signatures" list(): Promise> get(nameOrId: string): Promise> ``` Both need a `service_role` key. `get` accepts the **name** or the **id**; if a function is named like an id, the name wins. A `FunctionDef` contains the source code and the variables of the function, which is why a public key receives `403`. There is no method to deploy, update or delete a function, or to write secrets: use the [HTTP API](https://aurabase.dev/en/docs/functions/api) or the [CLI](https://aurabase.dev/en/docs/functions/cli). ## Jobs ```typescript filename="signatures" enqueueJob( functionName: string, options?: { payload?: unknown; delaySecs?: number; maxAttempts?: number }, ): Promise> listJobs(options?: { status?: string; limit?: number }): Promise> getJob(jobId: string): Promise> ``` - `enqueueJob` returns `{ code: 'bad_request', status: 400 }` without any request when `functionName` is empty or only spaces, and trims the name otherwise. - `listJobs` filters on `status` (`pending`, `running`, `completed`, `failed`, `dead`) and returns between 1 and 500 jobs, 50 by default. - Retrying dead jobs has no method: see the [dead-letter queue](https://aurabase.dev/en/docs/functions/jobs). ## Cron ```typescript filename="signatures" listCronJobs(): Promise> createCronJob( name: string, schedule: string, functionName: string, options?: { payload?: unknown }, ): Promise> deleteCronJob(name: string): Promise> ``` `schedule` has 5 or 6 fields, in UTC; an alias such as `@daily` is refused with `400`. `deleteCronJob` takes the **name**, and returns `404` for an unknown name. There is no `getCronJob` or `updateCronJob`. ## Types and errors Exported by `@aurabase/aurabase-js` and `@aurabase/functions`: ```typescript filename="imports" import { FunctionsHttpError, FunctionsRelayError, isRelayStatus, type FunctionsResponseType, } from '@aurabase/aurabase-js' ``` | Export | What it is | | --- | --- | | `FunctionsHttpError` | Your function (or a management route) answered with an error. `error.context` holds the body it returned. | | `FunctionsRelayError` | The platform failed: network (`status` 0) or `502`, `503`, `504` produced by the gateway or the runtime. | | `isRelayStatus(status)` | `true` for `0`, `502`, `503`, `504`. | | `FunctionsResponseType` | `'json' \| 'text' \| 'blob' \| 'arrayBuffer'` | Both error classes extend `AuraError`, so `isAuraError(error)` is true. `AuraError` has `status`, `code`, `message`, `details`, `retryAfter`, and the getters `isNotFound`, `isUnauthorized`, `isForbidden` and `isRateLimited`. Data types, exported by `@aurabase/aurabase-js`: | Type | Fields | | --- | --- | | `FunctionDef` | `id`, `project_id`, `name`, `runtime`, `code`, `code_hash`, `env_vars`, `permissions`, `is_active`, `created_at`, `updated_at` | | `FunctionPermissions` | `allow_net: string[]`, `memory_mb: number`, `timeout_secs: number` | | `Job` | `id`, `project_id`, `function_name`, `status`, `payload`, `attempts`, `max_attempts`, `error?`, `scheduled_at`, `started_at?`, `created_at`, `completed_at?` | | `CronJob` | `id`, `project_id`, `name`, `schedule`, `function_name`, `payload`, `is_active`, `last_run?`, `next_run?`, `created_at` | | `AuraResponse` | `{ data, error, meta? }` | > **Backward-compatible properties** > > When a function returns a JSON object, `data` also carries two non-enumerable properties, `body` and `status`, kept for code written against older versions. Do not rely on them in new code. --- ### aura functions and aura secrets Source: https://aurabase.dev/en/docs/functions/cli.md # aura functions and aura secrets > Every `aura functions` and `aura secrets` command, with its options, the files it reads and the environment it needs. ## Setup Commands that talk to your project need three things: | Need | How | | --- | --- | | A session | `aura login`, then `aura link --project-id `, which writes `aurabase.toml` | | The project URL | `NEXT_PUBLIC_AURABASE_URL`, or `project_url` in `aurabase.toml` | | A `service_role` key | `AURABASE_SERVICE_ROLE_KEY`, in the environment or in a `.env` file | | Variable | Default | Role | | --- | --- | --- | | `AURA_GATEWAY_URL` | `https://api.aurabase.dev` | Management API used by `login`, `orgs` and `projects`. **Set it explicitly when you work against another stack**: the default is the hosted cloud. | | `NEXT_PUBLIC_AURABASE_URL` | `project_url` of `aurabase.toml` | Data plane of your project | | `AURA_STUDIO_URL` | `http://localhost:3000` | Studio opened by `aura studio` | > **The default target is the hosted cloud** > > Without `AURA_GATEWAY_URL`, `aura login` and `aura projects create` talk to `https://api.aurabase.dev`. Export the URL of your own stack before you test against it. ## aura functions ### `aura functions new [--runtime deno|wasm]` Creates `aurabase/functions//`. The default runtime is `deno` (TypeScript template with `index.ts` and `deno.json`). With `--runtime wasm` it creates a Rust crate (`Cargo.toml`, `src/lib.rs`). It refuses an existing name. ### `aura functions serve [name] [--port 54321]` Runs `index.ts` or `index.js` with `deno run --allow-net --allow-env --allow-read --watch`, so the function restarts when you save. It needs [Deno](https://deno.com) installed; without it, the command explains how to install it. With no name, it lists local functions. The server listens on `http://127.0.0.1:` and the function receives the request as it would in production (method, path, headers, body), **without** the platform: no `x-aura-*` identity headers, no secrets, no limits. `PORT` and `DENO_SERVE_ADDRESS` are set for you, so a plain `Deno.serve(handler)` uses the chosen port. ```bash filename="terminal" aura functions serve hello --port 54321 curl -X POST http://127.0.0.1:54321/ -d '{"name":"Ada"}' ``` A WASM function cannot be served locally: the command prints how to deploy it. ### `aura functions deploy ` Reads `index.ts` (or `index.js`) and sends it to the project, creating or replacing the function. Existing secrets are kept. For a function without `index.ts` or `index.js`, it runs `cargo build --target wasm32-unknown-unknown --release` and sends the compiled binary. A Deno function is a **single file**: the command refuses relative imports (`./helper.ts`, `../lib.ts`). Use remote imports (`npm:` or `https://esm.sh/`) or inline the code. ### `aura functions invoke [--data '']` Calls the deployed function and prints the response envelope. `--data` is the request body. A `--data` that is not valid JSON is an error: it is not replaced by `{}`. ```bash filename="terminal" aura functions invoke hello --data '{"name":"Ada"}' ``` ### `aura functions list [--json]` Lists local functions with their runtime (`Deno / TypeScript` or `Rust / WASM`) and, when a project is linked, the deployed ones with `actif` or `inactif`. ### `aura functions logs [--limit 50]` Lists recent HTTP requests for the function: time, method, path, status, duration and request id. It does **not** show the output of your code (`console.log`). See [limits](https://aurabase.dev/en/docs/functions/limits). ### `aura functions download ` Writes the deployed code to `aurabase/functions//`: `index.ts` for a Deno function, `.wasm` for a WASM one. The Rust source of a WASM function is not stored on the server. ### `aura functions delete [--force]` Deletes the deployed function after a confirmation. `--force` (or `-f`) skips the confirmation, which you need in scripts. ## aura secrets | Command | Effect | | --- | --- | | `aura secrets list --function [--json]` | Lists the keys; values are masked (`sk_l***`) | | `aura secrets set --function KEY=VALUE …` | Adds or updates keys, keeps the others | | `aura secrets unset --function KEY …` | Removes keys | `--function` can be written `-f`. These commands store values as given and do not encrypt them: see [secrets and environment](https://aurabase.dev/en/docs/functions/secrets) for the encrypted path. ## Folder layout ```text filename="project" aurabase.toml # project_id and project_url, written by aura link .env # NEXT_PUBLIC_AURABASE_URL, AURABASE_SERVICE_ROLE_KEY (do not commit) aurabase/ functions/ hello/ index.ts # the whole function deno.json ``` --- ### Edge Functions Limits and Quotas Source: https://aurabase.dev/en/docs/functions/limits.md # Edge Functions Limits and Quotas > The numbers you need before you design a function, and the known gaps of the current platform. ## A function | Limit | Value | Where it comes from | | --- | --- | --- | | Name | 1 to 64 characters among `a-z`, `A-Z`, `0-9`, `_`, `-` | Enforced at deploy | | Source size | 20 MB | Enforced at deploy | | Runtimes | `deno` (TypeScript or JavaScript) and `wasm` | | | Memory | 16 to 1024 MB, default 128 | `permissions.memory_mb` | | Duration | 1 to 300 s, default 30 | `permissions.timeout_secs` | | Outbound network | Open by default | `permissions.allow_net`: when not empty, only the listed hosts are reachable | A value outside the bounds is refused with `400`; it is never clamped silently. Real answer for `timeout_secs: 0`: `permissions.timeout_secs doit être compris entre 1 et 300 secondes`. Change permissions without redeploying: ```bash filename="terminal" curl -X PATCH "$NEXT_PUBLIC_AURABASE_URL/v1/functions/report" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H "Content-Type: application/json" \ -d '{"permissions":{"timeout_secs":120}}' ``` Only the fields you send change. ## A call | Limit | Value | Source | | --- | --- | --- | | Request body | About **256 KiB** | Measured: 260 KB passed; above 256 KiB the call is refused with `413 PAYLOAD_TOO_LARGE` | | Response body | About **256 KiB** | Measured: 250 KB passed; 300 KB returned nothing within 50 s | | State between calls | None | Every call runs in a new isolated V8 worker | | Regions | One | No region selection | A request body above 256 KiB is refused before the function runs, with `413 PAYLOAD_TOO_LARGE` and a message that points to Storage; nothing is counted against your quota. A response above the same size did not come back at all in our test. **Keep requests and responses below 250 KB and send larger data through Storage.** ## Rate and plan quotas Invocation rate, per client IP: | Profile | Value | | --- | --- | | Burst | 15 calls | | Sustained | 1 call per second | In a real run of 30 quick calls, 15 returned `200` and 15 returned `429`. A `429` carries `x-ratelimit-*` and `retry-after` headers, and the SDK exposes the delay as `error.retryAfter`. Monthly quotas per plan, from the platform's plan table: | Plan | Invocations | Total duration | | --- | --- | --- | | Free | 100,000 | 6,000,000 ms (100 min) | | Pro | 1,000,000 | 60,000,000 ms (1,000 min) | | Team | 10,000,000 | 600,000,000 ms (10,000 min) | | Enterprise | 100,000,000 | 6,000,000,000 ms (100,000 min) | On the Free plan the limit is hard: a call beyond it is refused with `403 QUOTA_EXCEEDED`. On paid plans the table is the monthly allowance, and usage beyond it is not blocked: the unit rates of the cost calculator apply. A call is counted once your function has answered, whatever its status. A call that fails before the function answers is not counted. Jobs and cron firings count as invocations too. ## Jobs, cron and alerts | Limit | Value | | --- | --- | | Job attempts | 3 by default, set per job with `maxAttempts` | | Delay between attempts | 5 s, fixed | | Parallel jobs per service instance | 8 by default | | Running lease | 450 s, then the job is reclaimed | | Finished jobs kept | 14 days by default | | `listJobs` page | 1 to 500, default 50 | | Cron schedule | 5 or 6 fields, UTC, no aliases | | Alert check | Every 60 s | The values in this table are those of the managed service and are the same for every project. A self-hosted deployment sets them with the service settings `JOB_MAX_RETRIES`, `JOB_RETRY_DELAY_SECS`, `WORKER_CONCURRENCY`, `JOB_RUNNING_LEASE_SECS` and `JOB_RETENTION_DAYS`. ## Known gaps - **No access to a function's own logs.** What a function writes with `console.log` or `console.error` stays in the runtime's logs, which only the platform operator can read. `aura functions logs` shows requests (method, path, status, duration, request id), not that output. Return the information you need in the response, or send it to your own logging service. - **No request id inside the function.** The identifier of a call is not forwarded to the function. - **No versions or rollback.** Deploying replaces the code. Keep the previous version in your repository. - **No streaming.** The whole response is buffered before it reaches the SDK. - **An empty `allow_net` restricts nothing.** The network is open by default; list your hosts to restrict it. - **Local emulation is partial.** `aura functions serve` runs your file with Deno but does not reproduce the platform route, headers or limits. --- ### Notifications Source: https://aurabase.dev/en/docs/notifications.md # Notifications > SMTP email, SMS, mobile push, outgoing webhooks. i18n templates, rate-limit per channel, bounce management, HMAC signatures. Everything from a job edge. ## Four channels, one unified SDK The `aura-notifications` service exposes a single `aura.notifications.*` surface (service_role key, server side) which manages email, SMS, push and webhooks. Calls go through a NATS queue with retry, backoff, and DLQ — you send, we guarantee delivery (or refund the credit). > **Note:** > > Templates, logs and quotas live in `project_{uuid}_platform.notifications_*`. 30-day retention of delivery logs (2 years on Enterprise). ## What each channel guarantees - **Email (SMTP).** MJML/HTML templates with Liquid, DKIM/SPF/DMARC, rate-limit by domain, bounces managed automatically. - **SMS.** Multiple providers (Twilio, Vonage, OVH), routing by country, automatic fallback. - **Push.** APNs (iOS), FCM (Android), Web Push (VAPID). Self-validated device tokens, purging invalid ones. - **Outgoing webhooks.** HMAC-SHA256 signing, exponential retry (5 attempts), DLQ, rotating signatures. ## MJML + Liquid, native i18n Create templates from the Studio or via CLI. MJML syntax for email (responsive out-of-the-box), Liquid for templating. Locales managed by file `welcome.fr.mjml`, `welcome.en.mjml`. - **Email templates:** ~12 per project (on average) - **Local supported:** 38 (Liquid + auto fallback) - **Delivery p99:** < 8s (queue → recipient) - **Inbox rate:** 97\.8% (DKIM + dedicated IP) ## Four channels in code **Email** ```typescript tab="Email" filename="functions/send-welcome.ts" await aura.notifications.sendEmail({ to: user.email, templateId: 'welcome', // a template created in Studio › Notifications variables: { name: user.name, plan: 'Pro' }, }) ``` **SMS** ```typescript tab="SMS" filename="functions/send-otp.ts" await aura.notifications.sendSms({ to: '+33612345678', body: `Your code: ${code}`, }) ``` **Push** ```typescript tab="Push" filename="functions/push.ts" await aura.notifications.sendPush({ to: deviceToken, // one device token per call title: 'New message', body: msg.preview, metadata: { messageId: msg.id }, }) ``` **Webhook** ```typescript tab="Webhook" filename="functions/webhook.ts" await aura.notifications.sendWebhook( integration.callback_url, 'order.created', { orderId, amount, currency }, // signed HMAC-SHA256 (project secret) ) ``` Each call returns `{ data, error }`: check `error` (a channel that is not configured is refused at once with a 503). See the [notifications reference](https://aurabase.dev/en/docs/sdk/notifications) for every option. > **Tip:** > > Continue with a `edge.job()` to decouple: the transmitter pushes into the `notifications`queue, the worker sends asynchronously with automatic retry. > **Note:** > > Signed webhook: configure a secret in Notifications → Settings → Webhook (or `WEBHOOK_SIGNING_SECRET` on the service side). Each send then carries the `X-Aurabase-Signature: t={timestamp},v1={hmac-sha256}` header — verification on the receiver side documented in the README of the `@aurabase/notifications`package. ## To go further - [Edge Functions](https://aurabase.dev/en/docs/functions): Asynchronous jobs + DLQ for sending. - [REST API](https://aurabase.dev/en/docs/api-rest): Endpoints /v1/notify/ for external integrations. - [Compliance](https://aurabase.dev/en/docs/compliance): GDPR, opt-in, unsubscribe, retention logs. --- ### AI Gateway Source: https://aurabase.dev/en/docs/ai.md # AI Gateway > Sovereign European AI gateway in Rust: OpenAI, Anthropic, Gemini, sub-10ms pgvector search, ephemeral capability tickets, and NL2SQL. ## One endpoint, N providers The Aurabase AI Gateway is a unified HTTP and SDK surface for major LLM providers. The same code runs against OpenAI, Anthropic, and Google Gemini — you only change `provider` or rely on the project default. The gateway incorporates four native pillars: 1. **Automated Fallback**: Automatically falls back to a secondary provider when the primary suffers upstream outages or timeouts (5xx/408). 2. **Ephemeral Sessions**: Issues short-lived capability tickets (300s TTL) with bounded token budgets, eliminating API key exposure in client frontends. 3. **Multi-Dimension pgvector**: Dedicated dimensional column routing (`embedding_768`, `embedding_1536`, `embedding_3072`) with sub-5ms HNSW similarity search. 4. **AST-Verified NL2SQL**: Synthesizes PostgreSQL queries validated by an Abstract Syntax Tree parser that forbids mutations and enforces row limits. ## Supported LLM and embedding models | Provider | Chat & Completion Models | Supported Embeddings | | --- | --- | --- | | **Anthropic** | `claude-3-5-sonnet`, `claude-3-5-haiku`, `claude-3-opus` | — | | **OpenAI** | `gpt-4o`, `gpt-4o-mini`, `o1`, `o3-mini` | `text-embedding-3-small` (1536), `text-embedding-3-large` (3072) | | **Google Gemini** | `gemini-1.5-pro`, `gemini-1.5-flash`, `gemini-2.0-flash` | `text-embedding-004` (768) | | **Custom / Ollama** | Any OpenAI-compatible endpoint | Custom OpenAI-compatible embeddings | ## Ephemeral sessions (Zero secret exposure) Frontend single-page applications and mobile apps should never embed backend API keys (`aura_anon_...` or `aura_sk_...`) for open-ended LLM endpoints. Aurabase solves this with ephemeral capability sessions: ```typescript filename="functions/mint-session.ts" // In your backend, Next.js Server Component, or Edge Function: const session = await aura.ai.session() // The session instance holds a 300s capability ticket signed with JWT HMAC: const { content, budget_remaining } = await session.chat([ { role: 'user', content: 'Summarize my dashboard statistics.' } ]) console.log('Tokens remaining in session:', budget_remaining) ``` > **Tip:** > > The ticket is bounded by the project's remaining monthly token quota. When the allocated session budget is depleted, the gateway rejects requests with `HTTP 429 Too Many Requests` (`code: "session_budget_exceeded"`), shielding your organization from client-side denial-of-wallet attacks. ## Chat, streaming, pgvector & RAG **Chat streaming** ```typescript tab="Chat streaming" filename="chat-stream.ts" for await (const chunk of aura.ai.chatStream([ { role: 'user', content: 'Draft a Data Processing Agreement clause under GDPR.' } ], { provider: 'anthropic', model: 'claude-3-5-sonnet', temperature: 0.1 })) { process.stdout.write(chunk.delta) } ``` **Embeddings** ```typescript tab="Embeddings" filename="embed.ts" // Calculate and persist vector directly into PostgreSQL pgvector const { data: record } = await aura.ai.embed({ text: 'European cloud infrastructure hosted strictly in EU jurisdictions.', namespace: 'legal-docs', metadata: { tag: 'compliance' } }) console.log('Indexed document ID:', record?.id, 'Dimensions:', record?.dimensions) ``` **Semantic search** ```typescript tab="Semantic search" filename="search.ts" // Sub-10ms Cosine similarity query on namespace const { data: matches } = await aura.ai.semanticSearch( 'What are the encryption standards for backups?', 'legal-docs', { threshold: 0.82, top_k: 5 } ) ``` **RAG synthesis** ```typescript tab="RAG synthesis" filename="rag.ts" // Grounded retrieval-augmented generation in a single call const { data: answer } = await aura.ai.rag({ question: 'Where are project backups stored?', namespace: 'legal-docs', system: 'Answer strictly using the provided context.', }) console.log(answer?.answer, answer?.sources) ``` **NL to SQL** ```typescript tab="NL to SQL" filename="nl2sql.ts" // Translates natural language to PostgreSQL with AST mutation guards const { data: query } = await aura.ai.nl2sql( 'Which 5 organizations have the highest storage usage?', { dialect: 'postgresql', limit: 5 } ) console.log('Safe SQL:', query?.sql) ``` ## Audit logs & quotas Every AI call is logged with prompt/completion tokens, reasoning tokens (Gemini thoughts included), provider, upstream model, duration, and status. ### Real-Time Logs API Inspect audit logs via `GET /v1/ai/{project_id}/logs`: ```bash filename="curl" curl "https://.aurabase.dev/v1/ai/$PROJECT_ID/logs?limit=10" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" ``` > **Note:** > > Rate limits are enforced on a per-project token bucket (10 req/min with burst 5 by default). Monthly plan limits apply across `ai.requests`, `ai.input_tokens`, and `ai.output_tokens`. Exceeding monthly plan limits returns `HTTP 403 Forbidden` (`QUOTA_EXCEEDED`). ## To go further - [Edge Functions](https://aurabase.dev/en/docs/functions): ctx.ai in your handlers/crons/jobs. - [Database + pgvector](https://aurabase.dev/en/docs/database): Store embeddings, match via HNSW index. - [REST API](https://aurabase.dev/en/docs/api-rest): Endpoints /v1/ai/chat, /embed, /rag. - [Performance](https://aurabase.dev/en/docs/database/performance): Streaming, retry, fallback providers. --- ### RAG & Vector Search Guide Source: https://aurabase.dev/en/docs/ai/rag-pgvector.md # RAG & Vector Search Guide > Build semantic search and a Retrieval-Augmented Generation (RAG) pipeline with pgvector and the Aurabase AI Gateway. ## RAG on Aurabase in 3 steps RAG allows your AI models to respond accurately on your own private data without retraining: - **Vectorization**: Your textual documents are transformed into digital vectors using `aura.ai.embed()`. - **Storage & Indexing**: Vectors are stored in PostgreSQL with the native extension `pgvector`. - **Augmentation & Answer**: The question is compared to the stored vectors, and the relevant snippets are provided to the LLM via `aura.ai.chat()`. ## Full RAG pipeline code **1. SQL Schema & HNSW Index** ```sql tab="1. SQL Schema & HNSW Index" filename="migrations/001_pgvector_rag.sql" -- 1. pgvector is installed with the project: no CREATE EXTENSION (refused in a raw query). -- Check with `aura db extensions list`, or enable it with `aura db extensions enable vector`. -- 2. Create the documents table with column vector(1536) create table documents ( id uuid primary key default gen_random_uuid(), content text not null, metadata jsonb default '{}'::jsonb, embedding vector(1536) not null ); -- 3. HNSW index for ultra-fast cosine searches (p99 < 5ms) create index idx_documents_embedding on documents using hnsw (embedding vector_cosine_ops) with (m = 16, ef_construction = 64); -- 4. RPC function for cosine similarity search create or replace function match_documents ( query_embedding vector(1536), match_threshold float, match_count int ) returns table (id uuid, content text, metadata jsonb, similarity float) language sql stable security invoker as $$ select id, content, metadata, 1 - (embedding <=> query_embedding) as similarity from documents where 1 - (embedding <=> query_embedding) > match_threshold order by embedding <=> query_embedding limit match_count; $$; ``` **2. Generation of Embeddings** ```typescript tab="2. Generation of Embeddings" filename="src/lib/index-doc.ts" import { aura } from '@/lib/aurabase' export async function indexDocument(content: string, metadata: Record) { // Calculation of vector embedding via the AI Gateway Aurabase const { vectors } = await aura.ai.embed({ provider: 'openai', model: 'text-embedding-3-small', input: [content], }) // Saving in PostgreSQL table const { data, error } = await aura.from('documents').insert({ content, metadata, embedding: vectors[0], }) return { data, error } } ``` **3. Search & RAG Streaming** ```typescript tab="3. Search & RAG Streaming" filename="src/app/api/chat/route.ts" import { aura } from '@/lib/aurabase' export async function POST(req: Request) { const { question } = await req.json() // 1. Calculation of the user question vector const { vectors } = await aura.ai.embed({ provider: 'openai', model: 'text-embedding-3-small', input: [question], }) // 2. Search for the 5 most relevant snippets via RPC const { data: matches } = await aura.rpc('match_documents', { query_embedding: vectors[0], match_threshold: 0.75, match_count: 5, }) const context = matches?.map((m: any) => m.content).join('\n\n') || '' // 3. Generation of the response with injected context (Streaming LLM) const stream = await aura.ai.chat({ provider: 'anthropic', model: 'claude-3-5-sonnet', stream: true, messages: [ { role: 'system', content: 'Answer questions grounded in the provided context.' }, { role: 'user', content: question }, ], }) return new Response(stream.toReadableStream()) } ``` ## HNSW indexing for sub-10ms queries For databases containing hundreds of thousands of vectors, **HNSW (Hierarchical Navigable Small World) indexing** provides significantly better search performance than `ivfflat`: ### HNSW Index (Recommended) Zero pre-training time, recall > 99% and constant latency even with continuous insertions of new documents. ### Cosine Distance (<=>) Use the `<=>` operator to calculate the normalized cosine distance between the embedding vectors. ## Semantic cache and token savings Aurabase's AI Gateway integrates an automatic **semantic cache**: if two users ask a similar question (cosine similarity greater than 0.95), the answer is served from the in-memory cache in **less than 2 ms**, saving 100% of the LLM call cost. ## To go further - [AI Gateway](https://aurabase.dev/en/docs/ai): Unified LLM proxy and token streaming. - [PostgreSQL Database](https://aurabase.dev/en/docs/database): PostgreSQL 18 and advanced extensions. - [Edge Functions](https://aurabase.dev/en/docs/functions): Deployment of Deno and WASM workers. --- ### Vault Source: https://aurabase.dev/en/docs/vault.md # Vault > Field-level encryption for sensitive Aurabase data. AES-256-GCM with record-derived key (HKDF-SHA256), or HashiCorp Vault transit backend in production — the same primitive protects your Edge Functions secrets and internal platform secrets. ## An encryption service, not a separate product “Vault” is not a separate HTTP service on the gateway: it is a field-level encryption engine that automatically protects your sensitive data before writing to the database — MFA secrets, OAuth provider tokens, project connection strings, and the secrets of your Edge Functions. What you actually manipulate, as a developer, are the **secrets per function**: key/value pairs defined via the CLI or the REST API, injected as environment variables into the worker that executes your function. > **Note:** > > The name “Vault” also refers to the HashiCorp Vault infrastructure product, deployed in production as an optional *backend* of this service (management of the root encryption key, rotation, Postgres credentials with a limited lifespan). The two meanings coexist: the application primitive documented here, and the infrastructure tool that can support it. ## Two backends, one reading format On write, the service chooses a backend: **Vault transit** if configured (preferred — the root encryption key never leaves Vault), otherwise a fallback **AES-256-GCM local** with a key derived by registration via HKDF-SHA256. When read, the format of the ciphertext indicates which backend produced it — no forced migration is needed to switch from one to the other. ```text filename="ciphertext format" vault:v1:AbCdEf... # backend transit — decrypted via Vault (KEK never exposed) {"key_id":"v1", # local AES-256-GCM backend (fallback/dev) "nonce":"…","data":"…"} sk_live_51J2x... # unencrypted historical value (before encryption activation) ``` > **Tip:** > > The derivation context (functions side) is `project_id:function_name` — the same secret encrypted twice for two functions produces two different ciphertexts, and removing/renaming the function makes the old ciphertext unreadable by construction. ## What the service provides - **AES-256-GCM.** 32-byte key derived by registration via HKDF-SHA256 (context = project\_id:function\_name). 96-bit nonce per write. - **Backend Vault transit.** In production, the KEK never leaves Vault: encryption/decryption delegated to transit/encrypt|decrypt, versioned ciphertext vault:vN:.... - **Reading older formats.** Decryption detects stored format (vault: → transit, \{...\} → local AES, plain text → unencrypted history): backend failover without forced rewriting. - **Scope by function.** The application secrets documented here are scoped to a function (project\_id + name), injected to the Deno worker via `Deno.env.get('KEY')`. - **Dedicated CLI.** `aura secrets list`, `set` and `unset` take `--function `. `list` never shows values in plain text. - **Reused by the platform.** The same encryption service also protects, on the server side, MFA secrets, OAuth tokens and connection strings (db\_url\_encrypted, anon\_key\_encrypted). ## Three ways of writing, one way of reading **CLI** ```bash tab="CLI" filename="secrets.sh" # Define secrets (KEY=VALUE pairs) for a function aura secrets set --function echo STRIPE_SECRET_KEY=sk_live_... # List the secrets of a function (values hidden on display) aura secrets list --function echo # Delete secrets aura secrets unset --function echo STRIPE_SECRET_KEY ``` **REST (encrypted)** ```bash tab="REST (encrypted)" filename="env-endpoint.sh" # Write — the value is encrypted before writing to base. curl -X PUT "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/echo/env" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H "content-type: application/json" \ -d '{"vars":[{"key":"STRIPE_SECRET_KEY","value":"sk_live_..."}]}' # Read — the response is decrypted on the server side. curl "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/echo/env" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" ``` **Reading (Deno)** ```typescript tab="Reading (Deno)" filename="functions/echo.ts" // Once written (CLI or REST), the secret is injected as a variable // environment of the worker who executes the function. Deno.serve(async (req) => { const cle = Deno.env.get('STRIPE_SECRET_KEY') // ... }) ``` > **Tip:** > > The CLI (`aura secrets`) and the dedicated REST endpoint (`/env`) manipulate the same data — the secrets of a function — but not necessarily through the same write path. See point of attention below. ## Encryption depends on the write path taken `aura-functions` exposes two ways to modify the environment variables of a function: the dedicated `PUT /v1/functions/:projectId/:nom/env` endpoint (which systematically encrypts via `EncryptionService` before writing), and the generic `PATCH /v1/functions/:projectId/:nom` endpoint used to update an entire function — code, runtime, `env_vars` included — without going through this encryption. > **Encrypting environment variables** > > Environment variables configured via `/env` are encrypted at rest via AES-256-GCM before being stored. In local development as well as in managed production, this encryption is performed transparently for the developer. ## To go further - [Edge Functions](https://aurabase.dev/en/docs/functions): Runtimes, invocation, permissions — where your functions and their secrets live. - [Cron](https://aurabase.dev/en/docs/cron): Trigger a function (and therefore its secrets) on a schedule. - [Security & RBAC](https://aurabase.dev/en/docs/security): Roles, RLS policies, auditing — the rest of the Aurabase security model. - [REST API](https://aurabase.dev/en/docs/api-rest): Raw HTTP surface, service key authentication. --- ### Cron Source: https://aurabase.dev/en/docs/cron.md # Cron > Schedule the invocation of an Edge Function on a cron expression. Each scheduled run puts a job in the same queue as the asynchronous invocations, consumed by the pool of workers — without retrying in case of failure. ## One more trigger for your functions The `aura-functions` service can invoke an Edge Function on a schedule, in addition to synchronous HTTP invocations and manually queued asynchronous jobs — see `/docs/functions`. There is no separate “cron” function: any deployed function can be targeted by a schedule. > **Note:** > > Cron schedules **Edge Functions** (`aura-functions`), not in-database SQL jobs (`pg_cron` is not installed in the managed Postgres image). For database maintenance (materialized views, periodic cleanups), schedule an Edge Function that connects to your database via `@aurabase/aurabase-js` or `DATABASE_URL`. ## Cron enqueues a job, it does not run the function A cron run does not launch the function directly: it creates a **job** in the queue (the same tables and the same worker pool as `POST /v1/functions/:projectId/jobs`), with a payload frozen at the time of cron creation. The job is then consumed by a worker like any other job. ```text filename="cycle of a scheduled run" TRIGGER ────▶ the in-process scheduler triggers at the scheduled time ENQUEUE ────▶ a job is created (function_name + cron payload) WORKER ────▶ the worker pool consumes the job, invokes the function FAILURE ────▶ max_attempts=1 → dead (DLQ) immediately, no retry SUCCESS ────▶ last_run + next_run updated on cron line ``` > **Tip:** > > When the service is restarted, all active crons of all provisioned projects are reloaded from the database and rescheduled — the task list is not persisted in memory alone. ## What the scheduler provides - **In-process scheduler.** tokio-cron-scheduler + the cron crate in aura-functions: no external service, in-memory scheduling rescheduled on startup. - **Each run is a job.** The cron does not execute anything itself: it enqueues a job (like functions.invoke in asynchronous mode), consumed by the same pool of workers. - **Without retry.** A job created by the cron has max\_attempts=1: a failure switches it directly to DLQ (dead), unlike classic asynchronous jobs (3 attempts by default). - **Last\_run/next\_run tracking.** Each trigger timestamps last\_run and pre-calculates next\_run from the stored expression — visible via listCronJobs(). ## Create, list, delete **SDK** ```typescript tab="SDK" filename="app/cron.ts" import { createClient } from '@aurabase/aurabase-js' const aura = createClient(url, serviceRoleKey) // 5-field expression (min hour day month dsem) — seconds are // implicitly 0. A 6-field expression (with seconds) is also accepted. await aura.functions.createCronJob( 'rollup-15min', // name, unique per project '*/15 * * * *', // planning 'rollup', // function invoked at each run { payload: { minutes: 15 } }, ) const { data: crons } = await aura.functions.listCronJobs() await aura.functions.deleteCronJob('rollup-15min') ``` **REST** ```bash tab="REST" filename="cron.sh" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/cron" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H "content-type: application/json" \ -d '{"name":"rollup-15min","schedule":"*/15 * * * *","function_name":"rollup","payload":{"minutes":15}}' curl "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/cron" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" curl -X DELETE "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/cron/rollup-15min" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" ``` **Expressions** ```text tab="Expressions" filename="cheatsheet" 5 champs : min heure jour mois jour-semaine (secondes = 0 implicite) 6 champs : sec min heure jour mois jour-semaine '0 * * * *' # 5 fields → normalized to '0 0 * * * *' (every hour) '*/15 * * * *' # every 15 minutes '0 9 * * MON' # every Monday at 9:00 a.m. # Shortcuts @daily / @every are NOT accepted — full expression required. ``` > **Tip:** > > The name of a cron is unique per project and serves as an identifier for deletion (`DELETE /v1/functions/:projectId/cron/:nom`) — there is no UUID to remember on the client side. ## What cron doesn't do (yet) > **No dedicated CLI command** > > Unlike function secrets (`aura secrets`), there is no `aura functions cron` command today: management of scheduled tasks goes through the SDK or the REST API, not through the CLI. > **No automatic retry** > > A job from the cron fails directly in `dead` (DLQ) on the first attempt — `max_attempts` is worth `1`, compared to 3 by default for a classic asynchronous job. A cron-invoked function must therefore handle its own replays if the underlying operation is to be guaranteed, or you must monitor the DLQ (`GET /v1/functions/:projectId/jobs/dlq`) and replay manually. ## To go further - [Edge Functions](https://aurabase.dev/en/docs/functions): Runtimes, invocation, jobs, DLQ, secrets — the service that the cron triggers. - [Vault](https://aurabase.dev/en/docs/vault): Encryption of secrets injected into the function invoked by cron. - [Database](https://aurabase.dev/en/docs/database): Postgres 18 allowlisted extensions, RLS, and migrations. - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): createCronJob, listCronJobs, deleteCronJob — the exact surface of the client. --- ### Platform Source: https://aurabase.dev/en/docs/platform.md # Platform > How projects, plans, quotas, security and deployments work across every product. - [Projects](https://aurabase.dev/en/docs/projects): Create a project, choose its region, manage roles and API keys - [Plans and billing](https://aurabase.dev/en/docs/billing): The plan of the organization, payment, invoices and cancellation - [Limits and quotas](https://aurabase.dev/en/docs/limits): Every quota and rate limit of each plan, and what happens when one is reached - [Security](https://aurabase.dev/en/docs/security): Postgres roles, policy patterns and audit logs - [Compliance](https://aurabase.dev/en/docs/compliance): Certification status, GDPR DPA, data residency and incident commitments - [Deployment](https://aurabase.dev/en/docs/deployment): Environments, SQL migrations, rollback and CI integrations - [Database branches](https://aurabase.dev/en/docs/deployment/preview-envs): A copy of a project with its own URL and keys, deleted by its TTL - [Multi-region deployment](https://aurabase.dev/en/docs/deployment/multi-region): Replication, failover and data residency; the aura commands it shows are planned - [Support](https://aurabase.dev/en/docs/support): Help channels by plan and how to report a security issue --- ### Project management Source: https://aurabase.dev/en/docs/projects.md # Project management > Everything surrounding an Aurabase project: creation, regions, team, roles, API keys, monitoring, invoicing. A project = a dedicated Postgres database on your organization's cluster + a complete namespace. ## One project, one complete namespace An Aurabase project provisions: a dedicated PostgreSQL database with four sub-schemas (hosted on your organization's CNPG cluster, or on a cluster entirely dedicated to the project on the enterprise offer), a pair of API keys (`anon` + `service_role`), a UUID identifier which serves as a prefix to all its routes (`/v1//{project_id}` — there is no domain per project), a default storage bucket, a scope for edge functions and a budget. Billing is per consumption on the Pro plan, flat rate on Enterprise. A project can be paused (resources remain allocated, not billed) or deleted (data deleted within 30 days). ## Create a project From the console (`console.aurabase.dev`): a name and a database engine. The region is the one your deployment declares for its database cluster — the only one available, shown in the form — and the plan is your organization's. Provisioning takes 45 seconds to 1.5 minutes (measured: about 45 s when the organization's cluster is created, about 90 s with the CLI, which waits for the project to be active) — base created on your organization's PostgreSQL cluster (or dedicated cluster provisioned on the fly on the enterprise offer), schemas initialized, keys generated, TypeScript types pre-generated. When you delete the last project of an organization, its cluster is deleted immediately; the next project creates a new one. ```bash filename="cli" # CLI alternative (non-interactive) aura projects create my-saas --org # API keys of the project (linked in aurabase.toml, or --project-id) aura projects api-keys --project-id ``` > **Tip:** > > Keys are displayed only once upon creation. They can be regenerated (old invalidated immediately) from the Studio or via `Settings › Connection`. ## EU regions · Paris by default Your project is pinned to its creation region. Data, backups and replicas remain in this region, inside the European Union. Changing region involves a migration assisted by our team (contact `migrate@aurabase.cloud`). - `fr-par` — **Paris** · Scaleway (`FR`) - `de-fsn` — **Falkenstein and Nuremberg** · Hetzner (`DE`) - `fi-hel` — **Helsinki** · Hetzner (`FI`) > **Note:** > > **Enterprise only**: pinning at country level, contractual commitment. No third-party certification (SecNumCloud FR, C5 DE) is yet committed — public roadmap on our Trust Center. ## Four default roles, custom RBAC available Each project has a unique `owner` (the default creator, transferable). Beyond that, you invite members with a predefined role or a custom role defined via policy. | Role | Permissions | Max per project | | --- | --- | --- | | `owner` | Full management, invoicing, project deletion | 1 | | `admin` | Team management, policies, deployments; no invoicing | Unlimited | | `developer` | Read and write tables, functions and migrations | Unlimited | | `viewer` | Read-only access to data and logs; no secrets | Unlimited | > **Warning:** > > A `viewer` never sees the secrets or values of `service_role_key`. Audit logs record each access to sensitive resources for 30 days (2 years on Enterprise). ## Anon, service_role, JWT custom Three types of keys. Use the right one for the right surface. | Key | Visibility | Use | | --- | --- | --- | | `anon_key` | Public | Client bundles and mobile apps. RLS applies and the claims are `anon`. | | `service_role_key` | Secret | Backend only. Bypasses RLS. Never ship it in client code. | | `user_jwt` | Session | Issued by `aura-auth` after sign-in. Expires after 15 minutes and rotates automatically. | ## Live metrics + quotas The Studio exposes real-time metrics on each service: requests/sec, p50/p99 latency, active connections, error rate, storage usage/egress. Export to Datadog, Grafana Cloud, Honeycomb via webhook or Prometheus endpoint. - **DB REQ/S:** 1 240 (average 5 min) - **P99 READ:** 8ms (select last 100) - **STORAGE:** 4\.2 GB (100 GB · Pro plan) - **EDGE INV:** 48k (this month · 5M quota) ## To go further - [Security & RBAC](https://aurabase.dev/en/docs/security): Custom roles, fine policies, audit logs. - [Deployment](https://aurabase.dev/en/docs/deployment): Branches, preview envs, CI/CD. - [Prices](https://aurabase.dev/en/pricing): Free / Pro plans €25 / Enterprise. - [REST API](https://aurabase.dev/en/docs/api-rest): Endpoints /v1/projects/. --- ### Plans and billing Source: https://aurabase.dev/en/docs/billing.md # Plans and billing > What you pay, when, how to get your invoices, and the gaps that exist today. ## The plan The subscription belongs to the organization, not to a project. Free is €0, Pro is €25 per month and Team is €99 per month, excluding VAT. Quotas are counted for each project: see [Limits and quotas](https://aurabase.dev/en/docs/limits). Usage above the included monthly quota is not blocked on paid plans; the unit rates of the [cost calculator](https://aurabase.dev/en/pricing/calculator) apply. Automatic metering of this overage on the invoice is not available yet. On the Free plan a reached quota blocks further use until the next month and nothing is billed. ## Paying Payments go through Mollie, a European payment provider. The first payment is made in a checkout opened from the billing page of the organization in the Studio. You can pay by card (Visa, Mastercard) or by SEPA direct debit. The platform stores the customer reference, never the card number or the bank details. ## Invoices The billing page of the organization lists every invoice with its status (paid, open, void, refunded), its period and a link to the document. A management link opens the payment provider's portal to update the payment method and download receipts. ## Cancelling Cancel from the billing page. The cancellation takes effect at the end of the paid period: the plan stays active until then. You can export your databases with `pg_dump` and download your files before deleting a project. ## Not available yet - A spend cap and alerts at a usage threshold. - Proration rules for changing between paid plans are not documented because they are not defined yet. Contact support before switching plans mid-period. - An annual price on the pricing page. --- ### Limits and quotas Source: https://aurabase.dev/en/docs/limits.md # Limits and quotas > The numbers enforced by the platform for each plan, and what you get when you reach one. ## When a limit is reached There are four kinds of limit, and each one fails differently. | Kind | Examples | What you get | | --- | --- | --- | | Per-minute rate limit | `http.requests`, `db.requests`, `ai.requests` per minute | `429 Too Many Requests` with `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `Retry-After`. Retry after the delay. | | Monthly quota, Free plan | any monthly metric | Hard limit: further calls are refused with `403` and `error.code = QUOTA_EXCEEDED` until the next month (`error.isQuotaExceeded` in the SDK). The message names the metric, the usage, the limit and the reset date. Nothing is billed. | | Monthly quota, paid plans | any monthly metric | The service keeps running. The unit rates of the [cost calculator](https://aurabase.dev/en/pricing/calculator) apply to the usage above the included quota; automatic metering of this overage on the invoice is not available yet. | | Instant limit | projects, concurrent realtime connections | Hard limit on every plan: the project or the connection is refused, there is no overage billing. | A spend cap and usage alerts are not available yet. Until they are, watch the usage page of your project. ## Limits per plan | Limit | Metric | Free | Pro | Team | Enterprise | | --- | --- | --- | --- | --- | --- | | Projects | `max_projects` | 3 | 10 | 50 | Unlimited | | Active branches | `max_branches` | 1 | 10 | 25 | Unlimited | | Database requests | `db.requests` | 1,000,000 / month | 50,000,000 / month | 500,000,000 / month | 5,000,000,000 / month | | Database requests per minute | `db.requests` | 600 | 30,000 | 300,000 | 3,000,000 | | Raw SQL requests | `db.raw_sql_requests` | 2,000 / month | 100,000 / month | 1,000,000 / month | 10,000,000 / month | | Raw SQL requests per minute | `db.raw_sql_requests` | 60 | 600 | 6,000 | 60,000 | | Backup storage | `db.backup_storage` | 100 MiB | 5 GiB | 50 GiB | 500 GiB | | Gateway requests | `http.requests` | 1,000,000 / month | 50,000,000 / month | 500,000,000 / month | 5,000,000,000 / month | | Gateway requests per minute | `http.requests` | 1,200 | 60,000 | 600,000 | 6,000,000 | | Auth requests per minute | `auth.requests` | 240 | 6,000 | 60,000 | 600,000 | | Auth e-mails | `auth.email_sends` | 100 / month | 5,000 / month | 50,000 / month | 500,000 / month | | Auth SMS | `auth.sms_sends` | 25 / month | 1,000 / month | 10,000 / month | 100,000 / month | | Realtime concurrent connections | `realtime.peak_connections` | 200 | 1,000 | 10,000 | 100,000 | | Realtime messages | `realtime.messages` | 1,000,000 / month | 10,000,000 / month | 100,000,000 / month | 1,000,000,000 / month | | Realtime messages per minute | `realtime.messages` | 300 | 3,000 | 30,000 | 300,000 | | Realtime traffic | `realtime.bytes` | 1 GiB / month | 10 GiB / month | 100 GiB / month | 1,000 GiB / month | | Storage uploads | `storage.upload_bytes` | 5 GiB / month | 50 GiB / month | 500 GiB / month | 5,000 GiB / month | | Storage downloads | `storage.download_bytes` | 10 GiB / month | 100 GiB / month | 1,000 GiB / month | 10,000 GiB / month | | Storage objects | `storage.objects` | 10,000 / month | 1,000,000 / month | 10,000,000 / month | 100,000,000 / month | | Storage requests per minute | `storage.requests` | 600 | 6,000 | 60,000 | 600,000 | | Function invocations | `functions.invocations` | 100,000 / month | 1,000,000 / month | 10,000,000 / month | 100,000,000 / month | | Function duration | `functions.duration_ms` | 100 min / month | 1,000 min / month | 10,000 min / month | 100,000 min / month | | AI requests | `ai.requests` | 1,000 / month | 50,000 / month | 500,000 / month | 5,000,000 / month | | AI requests per minute | `ai.requests` | 30 | 120 | 1,200 | 12,000 | | AI tokens (input, output) | `ai.input_tokens`, `ai.output_tokens` | 500,000 each / month | 10,000,000 each / month | 100,000,000 each / month | 1,000,000,000 each / month | The numbers are the ones stored in the platform's plan table. The pricing page and the calculator display the same values. ## What applies to what The subscription belongs to the organization. Quotas are counted for each project: a Pro organization with three projects has three times the monthly quota of one project, and one project cannot use the quota of another. Limits that are not in this table: the Edge Function limits (memory, duration, body size, invocation rate per IP) are on [Limits and quotas of Edge Functions](https://aurabase.dev/en/docs/functions/limits), and the gateway limit per IP is described in the [REST API reference](https://aurabase.dev/en/docs/api-rest). --- ### Security & RBAC Source: https://aurabase.dev/en/docs/security.md # Security & RBAC > Row-Level Security native Postgres, predefined roles, multi-tenant RBAC, audit logs. Your rules live in the database — testable, versioned, impossible to circumvent on the client side. ## Security lives in the base Aurabase uses PostgreSQL's native **Row-Level Security (RLS)**. This means that your access rules are written in SQL, stored in the database, applied to each request — including those made by the SDK, PostgREST, or direct psql. **On a MongoDB project, there is no RLS.** Isolation is ensured by a reserved field `_owner_id`: any reading of a non-privileged role is filtered on the `sub` of the JWT, and any writing stamps this field. Three consequences to be aware of before debugging an empty list: a document created with a `service_role` key has *no* `_owner_id` and therefore becomes invisible to all authenticated users (`[]` response in HTTP 200, without error); a `anon` caller without a JWT receives an `403` on a non-public collection; and `_owner_id`, reserved, can never be modified by the client. A collection is opened for reading to all by the explicit opt-in `public_read`. Circumventing a policy is impossible on the client side. The gateway validates each JWT before opening a Postgres connection with the appropriate role. The claims (`auth.uid()`, `auth.role()`, `auth.tenant()`) are injected via `request.jwt.claims` — cannot be modified from an SQL query. > **Note:** > > Tables created through Aurabase (Studio, table API, migrations, or `/raw`) get `ENABLE` and `FORCE ROW LEVEL SECURITY` automatically by default (unless explicitly disabled in DDL). Always verify RLS on tables created over a direct `psql` connection with `alter table ... enable row level security` before adding policies. ## JWT → claims → policy → line Each query follows the same path. The gateway decodes the JWT, verifies its signature (`ES256` with the project-derived secret by default; `RS256` with a JWKS only when an RSA key is configured), extracts the claims, opens a Postgres connection with `SET LOCAL role` + `SET LOCAL request.jwt.claims`. All policies that reference `auth.*()` use these claims. ```text filename="flux" Client → Gateway verify JWT (ES256 via JWKS, project key) ↓ extract { sub, role, tenant, exp } Postgres SET LOCAL role = authenticated SET LOCAL request.jwt.claims = {...} ↓ SELECT ... FROM posts WHERE ... ↓ (RLS injecte la policy USING) SELECT ... FROM posts WHERE author_id = auth.uid() ``` ## Three Postgres roles, clear hierarchy | Role | Claims | Description | | --- | --- | --- | | `anon` | No `user_id` | Requests made with the anon key and no signed user JWT | | `authenticated` | `auth.uid()` is the user | A signed-in user with a valid JWT, from any Aurabase session | | `service_role` | Bypasses RLS | Backend key that passes every policy. Server only. | ## Five essential patterns Policies are attached to a table + an operation (SELECT/INSERT/UPDATE/DELETE) + a role. Multiple policies on the same pair are combined in OR. Use `using` to filter existing rows, `with check` to validate new values. **SELECT** ```sql tab="SELECT" filename="migrations/posts_rls.sql" alter table posts enable row level security; -- Reading: author only create policy "posts_own_read" on posts for select to aura_authenticated using (auth.uid() = author_id); ``` **INSERT** ```sql tab="INSERT" filename="migrations/posts_rls.sql" -- Insertion: the author_id must match the logged in user create policy "posts_own_insert" on posts for insert to aura_authenticated with check (auth.uid() = author_id); ``` **UPDATE** ```sql tab="UPDATE" filename="migrations/posts_rls.sql" -- Update: author only, and author_id does not change create policy "posts_own_update" on posts for update to aura_authenticated using (auth.uid() = author_id) with check (auth.uid() = author_id); ``` **DELETE** ```sql tab="DELETE" filename="migrations/posts_rls.sql" -- Deletion: author or admin create policy "posts_delete" on posts for delete to aura_authenticated using ( auth.uid() = author_id or auth.has_role('admin') ); ``` **Multi-tenant** ```sql tab="Multi-tenant" filename="migrations/tenant_rls.sql" -- Tenant-scoped — an organism only sees its lines create policy "posts_tenant_scope" on posts for all to aura_authenticated using (tenant_id = auth.tenant()) with check (tenant_id = auth.tenant()); ``` > **Tip:** > > **Test your policies in CI**: `aura db raw --as` and the RLS simulator read and write as a visitor or as a given user, and pgTAP is not available on Aurabase. See [Test RLS in CI](https://aurabase.dev/en/docs/database/test-rls). ## Beyond anon/authenticated The application roles (admin, editor, viewer, billing, etc.) live in the `roles` array of the user's `app_metadata`, which only the server can write (the admin API `PUT /admin/users/{id}` with a `service_role` key, or the access-token hook). Each user can have N roles. They travel in the token under `app_metadata.roles`, and `auth.has_role('admin')` reads them in your policies. `user_metadata` never grants a role: users can edit it themselves. Do not confuse them with the token's `role` claim (`anon` or `authenticated`: the Postgres tier, read by `auth.role()`) nor with the user's `role` field (a free label shown in the Studio, such as `user` or `editor`): neither of these grants an application role. Inside PostgreSQL, `auth.role()` returns `aura_anon`, `aura_authenticated` or `aura_service_role` for requests made through the SDK and the REST API, and `anon` or `authenticated` for SQL run with `aura db raw --as`: in a policy, target roles with `to aura_authenticated` rather than comparing `auth.role()` ([Row-level security](https://aurabase.dev/en/docs/database/rls#helpers)). ```sql filename="policies/admin.sql" -- Admin sees everything create policy "posts_admin_read" on posts for select to aura_authenticated using (auth.has_role('admin')); -- Billing sees sensitive columns in dedicated view create view posts_billing as select id, author_id, revenue_cents from posts where auth.has_role('billing'); ``` ## Complete trace, SIEM export Each security event is logged in `project_{uuid}_auth.auth_audit_log`: signin, signout, password\_change, mfa\_enroll, role\_granted, service\_role\_access, failed\_auth. 30-day retention on Pro, 2 years on Enterprise. > **Note:** > > Automatic export to your SIEM (Splunk, Datadog, Elastic) via webhook or Kafka stream. See `/docs/compliance` for detailed event schemas. ## To go further - [RLS guide](https://aurabase.dev/en/docs/database/rls): Policies, empty answers, and what RLS does not protect. - [Multi-tenant RBAC](https://aurabase.dev/en/docs/auth/rbac): Custom roles, org hierarchies, scopes. - [Auth](https://aurabase.dev/en/docs/auth): How claims are generated and signed. - [Compliance](https://aurabase.dev/en/docs/compliance): SOC2, ISO, GDPR, HIPAA, DPA. --- ### Compliance Source: https://aurabase.dev/en/docs/compliance.md # Compliance > Honest inventory: no third-party certification (SOC 2, ISO 27001, HIPAA, PCI DSS, FedRAMP) has yet been undertaken. Standard GDPR DPA included from the Pro plan (customizable on Enterprise), EU-only hosting, audit logs exportable to your SIEM. ## Trust Center at a glance No third-party certification (SOC 2 Type II, ISO 27001, HIPAA BAA, PCI DSS SAQ-D, etc.) has yet been undertaken to date — see the standard by standard details below. The standard GDPR DPA is included from the Pro plan and customizable on Enterprise. For a precise inventory and your compliance requirements, write to our team. > **Note:** > > An urgent security question? `security@aurabase.cloud` (response within 48 working hours). To report a vulnerability, write to the same address (coordinated disclosure, no paid bug bounty at this time). ## Inventory of 8 standards | Standard | Status | Details | | --- | --- | --- | | SOC 2 Type II | Not committed | No third-party audits in progress to date | | ISO 27001 | Not committed | No certification in progress to date | | GDPR · DPA | Included | Standard Art. 28 DPA from Pro, customizable on Enterprise | | HIPAA BAA | Not committed | No standard BAA available to date | | PCI DSS SAQ-D | Not committed | No certification in progress to date | | FedRAMP Moderate | Not committed | No audits planned to date | | SecNumCloud | Not committed | No ANSSI process in progress to date | | C5 Germany | Not committed | No BSI process in progress to date | ## Your data stays in the EU Databases, files, backups and logs of every project are hosted in the European Union only, on infrastructure operated by EU-headquartered providers: Scaleway (Paris) as primary provider and Hetzner (Germany, Finland) as secondary provider. Free and Pro projects cannot be placed outside the EU. - **Free / Pro**: EU hosting (France, Germany, Finland) - **Enterprise**: pinning by country, contractual commitment - **Enterprise + dedicated FR cluster**: data residency France, SecNumCloud approach not initiated to date - **Dedicated Private VPC (Isolated)**: complete network isolation, zero traffic outgoing from the VPC > **Note:** > > Aurabase telemetry logs (aggregated metrics, anonymized system errors) are stored in the EU. Some technical request data, such as IP addresses, transits through US-parent sub-processors that protect request traffic (Cloudflare). They are listed in the DPA with their safeguards. ## Contractual transparency Our GDPR DPA (Data Processing Agreement) is included from the Pro plan and customizable on Enterprise. The complete and current list of sub-processors, with their role, country and safeguards, is published on `/dpa`: - **Scaleway SAS** — Kapsule K8s, PostgreSQL HA, S3, Redis (France, Paris) - **Hetzner Online GmbH** — Secondary compute, edge nodes, block storage, backup object storage (Germany, Finland) - **Mollie B.V.** — Payments and subscriptions, cards and SEPA (Netherlands) - **Cloudflare, Inc.** — DNS, TLS, DDoS protection and WAF (global edge, US parent) - **Microsoft Ireland / Clarity** — Anonymized audience measurement and usability analytics - **Better Stack / Mihari** — Status page and uptime monitoring, no customer content - **Let’s Encrypt (ISRG)** — TLS certificates - Optional, only when you enable them: **Apple (APNs) and Google (FCM)** for mobile push, **Twilio** for SMS ## Backups and recovery Project databases get a daily base-backup and a continuous archive of the write-ahead log, stored in the EU. Backups are kept for 30 days on a rolling basis, and point-in-time recovery is available within that window. Restore from the CLI with `aura db backup restore `. Longer retention is available on Enterprise on request. ## Complete trace, SIEM export Each auth, sensitive data access, policy change event is logged. Retention 30 days (Pro), 2 years (Enterprise). Export via webhook to your SIEM (Splunk, Datadog, Elastic) or dedicated Kafka stream. ## RTO 15 min, post-mortem 5 days Severity 1 (prod down): Slack + PagerDuty notification within 15 min, bridge call operated until resolution. Public post-mortem within 5 working days, shared action plan. RTO 4h, RPO 15 min for the Enterprise plan. > **Tip:** > > Real-time status on the `aurabase.dev/en/status` — 90-day history, subscription by email/webhook/RSS. ## To go further - [Security & RBAC](https://aurabase.dev/en/docs/security): Native RLS, roles, policies, auth helpers. - [Trust Center](https://aurabase.dev/en/enterprise/trust-center): Security architecture, compliance inventory, DPA. - [Data residency](https://aurabase.dev/en/docs/projects): Regions available, pinning by country. - [Incident response](https://aurabase.dev/en/status): Escalation policy, RTO/RPO. --- ### Deployment Source: https://aurabase.dev/en/docs/deployment.md # Deployment > Zero-downtime migrations, atomic rollback, CI/CD via GitHub Actions / GitLab / CLI, and database branches: a copy of a project to test a migration or a policy before production. ## Three deployment surfaces An Aurabase project exposes three surfaces to deploy: **Postgres schema** (versioned SQL migrations), **edge functions** (WASM + cron + jobs), **policies and secrets** (RLS, env vars, OAuth apps). Each pushes itself independently via `aura` CLI. The CLI (`aura`) is a single binary, also installable with `npm install -g @aurabase/cli`, and supports dry-run, confirm prompts and diff preview. Linux / macOS / Windows compatible. ## Dev, preview, production By default, a project has two environments: `dev` (local, Kubernetes) and `prod` (cloud). To try a change on a copy of your data before production, create a [database branch](#branches). ```text filename="flux" LOCAL DEV $ ./start.sh → full local stack (k3d) $ aura dev → watch mode + types gen BRANCH (copy of a project, deleted by its TTL) $ aura branch create pr-142 --from my-app --ttl 3d $ aura db push → on the branch project, to try the migration $ aura branch delete pr-142 PRODUCTION merge to main → CI run: aura db push → aura deploy functions ``` ## Versioned SQL, atomic rollback Migrations live in `aurabase/migrations`. One file per change, timestamp in prefix. The CLI applies the missing migrations to the linked project; regenerate your TypeScript types with `npx @aurabase/gen` after a change. ```bash filename="terminal" # Create a new migration aura db migration new add_devices_table # → aurabase/migrations/20260415120000_add_devices_table.sql # See which migrations are applied or pending, then apply them to the linked project aura db status aura db push # Regenerate TypeScript types npx @aurabase/gen --out src/aurabase.types.ts # List applied migrations aura db migration list ``` > **Warning:** > > **Zero-downtime migrations**. Follow the rules: add nullable column first, separate backfill, constraint NOT NULL last. The CLI does not check backward compatibility for you: review destructive statements (`drop column`, `alter column … type`) before `aura db push`. ## Database branches A branch is a **new project** cloned from an existing PostgreSQL project: its schema, row level security policies, functions, triggers, views and (unless you ask for the schema only) its rows. It has its own URL, API keys and database, so you can run a migration, test a policy or point a preview deployment at it without touching the source. Branches are deleted automatically when their time to live ends. ```bash filename="cli" # From the linked project (aura link), 72 hours by default aura branch create feat/new-checkout # From another project, kept 7 days aura branch create pr-142 --from my-app --ttl 7d # Schema only: no row is copied, sequences start over aura branch create schema-test --no-data aura branch list # the branches of the linked project aura branch list --all # every branch of the organization aura branch delete feat/new-checkout ``` `aura branch create` waits until the branch is ready, then prints its URL and its API keys, **shown only once** like those of `aura projects create` (`--json` prints them for scripts). Use `--no-wait` to return at once and follow it with `aura branch list`. A branch is a project: link a folder to it with `aura link --project-id ` and run `aura db push` there to try a migration. > **What a branch is, exactly** > > A branch is a **copy made at creation time**, not a live replica and not a copy-on-write clone: nothing flows back to the source or from it afterwards. The platform reads the source in one consistent snapshot and copies the rows into the branch database, so the time is proportional to the data. On the local test stack, a 333 MB table of 350,000 rows was cloned in 14 seconds. A migration that works on the branch is then applied to production with the usual `aura db push`. ### Limits, in full | | | | --- | --- | | **Who can create** | Members with the `developer` role or more, from a PostgreSQL project that is active and not hibernated. A MongoDB project is refused. | | **Branching a branch** | Refused: create the branch from its parent project. | | **Name** | Letters, digits, `.`, `_`, `-` and `/`, up to 63 characters, unique per project among the live branches (case insensitive). | | **Time to live** | 72 hours by default, from 1 hour to 30 days (`--ttl 1h` to `--ttl 30d`). The expired branch and its database are deleted automatically, within about a minute of the deadline. You can delete it earlier. | | **Plan limit** | A branch does **not** count against your project limit (`max_projects`); it has its own limit of active branches per organization (`max_branches`): 1 on Free, 10 on Pro, 25 on Team. Past it, creation is refused with `BRANCH_LIMIT_REACHED`. A failed branch does not count. See [limits](https://aurabase.dev/en/docs/limits). | | **Data size** | The rows are streamed, not held in memory, so there is no 32 MiB ceiling. Cloning is refused, in a few seconds, when the tables hold more than the limit of the deployment (2 GiB by default, `BRANCH_CLONE_MAX_BYTES` when you host Aurabase): the message gives the size and suggests `--no-data`. A clone also stops after 30 minutes. | ### What is not cloned - **Cloned**: tables and their rows, column types, defaults, identity columns, sequences and their current value, constraints, indexes, row level security (enabled, forced, policies), SQL functions and procedures, triggers, views and materialized views, enum types, and the privileges on all of them. - **Not cloned**: auth users, sessions and auth settings; storage buckets and objects; edge functions, secrets, environment variables and cron jobs; realtime table settings (re-enable them on the branch); table and column comments, including `@graphql` directives; column-level privileges; the pg_graphql activation (`aura projects graphql-enable` on the branch). Objects are owned by the branch's admin role. - **Refused** (the branch would be incomplete): partitioned and inherited tables, foreign tables, domains, composite and range types, aggregate functions, rewrite rules, foreign keys that point to another schema, and extensions other than those the platform installs in every project. A branch is created from the schema as it is read just before the copy. Do not change the schema of the source (`aura db push`, DDL) while a branch is being created. ### When creation fails Nothing is left behind. The copy runs in a single transaction on the branch database; on any failure it is rolled back, the branch project is deleted, and `aura branch create` prints the reason (for example the object that cannot be cloned). The failed branch stays visible in `aura branch list` for 24 hours with its message, and its name is free again. If the database service restarts in the middle of a copy, the branch is declared failed and deleted after 45 minutes. ## Three integrations ready The CLI works with any CI. Here are the recipes for the three most common. **GitHub Actions** ```yaml tab="GitHub Actions" filename=".github/workflows/deploy.yml" name: Deploy to Aurabase on: push: { branches: [main] } jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: npm install -g @aurabase/cli # or download the binary from the release page - run: aura login --token ${{ secrets.AURA_PAT }} # Personal Access Token aura_pat_* - run: aura link ${{ vars.AURA_PROJECT_ID }} - run: aura db push - run: aura deploy functions ``` **GitLab CI** ```yaml tab="GitLab CI" filename=".gitlab-ci.yml" deploy: image: node:22 script: - npm install -g @aurabase/cli - aura login --token $AURA_PAT - aura link $AURA_PROJECT_ID - aura db push - aura deploy functions only: - main ``` **Makefile** ```makefile tab="Makefile" filename="Makefile" deploy-prod: aura login --token $(AURA_PAT) aura link $(AURA_PROJECT_ID) aura db push aura deploy functions npx @aurabase/gen --out src/aurabase.types.ts ``` Link one project per environment (a staging project and a production project) and run the same pipeline against each. There is no `--env` flag: the target is the project the folder is linked to. ## Atomic, via down migration Each `20260415_xxx.sql` migration can have a `20260415_xxx.down.sql` file next to it. `aura db migration down [n]` runs the `.down.sql` of the last `n` applied migrations, newest first, and removes them from the history; the command checks the server's answer and fails if nothing was reverted. A migration without a `.down.sql` is only removed from the history, and the CLI says so. ```bash filename="rollback" # Revert the last applied migration (runs its .down.sql) aura db migration down # Revert the last three aura db migration down 3 # Fix the history without touching the schema (a migration applied by hand, a failed one) aura db migration repair 20260415120000_add_devices_table.sql --applied # A failed migration is cancelled in its own transaction: nothing to revert. # Point-in-time recovery of a whole database goes through backups (aura db backup restore --yes) ``` > **Warning:** > > **Point-in-time recovery** has no self-service command yet. For a restore you drive yourself, use the snapshots of `aura db backup create` / `aura db backup restore --yes`; the restore overwrites the database, so take a fresh backup first. ## To go further - [Preview databases per pull request](https://aurabase.dev/en/docs/deployment/preview-envs): A branch per pull request in CI, and its cleanup. - [Multi-region deployment](https://aurabase.dev/en/docs/deployment/multi-region): Replication, failover, data residency. - [Performance audit](https://aurabase.dev/en/docs/database/performance): EXPLAIN ANALYZE, indexes, slow queries. - [CLI reference](https://aurabase.dev/en/docs/cli): All commands, flags, env vars. --- ### Preview databases per pull request Source: https://aurabase.dev/en/docs/deployment/preview-envs.md # Preview databases per pull request > A branch is a copy of a project with its own URL and API keys. Create one per pull request in CI, point the preview at it, and let it expire or delete it at merge. ## One pull request = one database `aura branch create` clones a PostgreSQL project (schema, row level security policies, functions, triggers, views and rows) into a **new project** with its own URL and API keys. A pull request can run its migration there, and reviewers can try the result, without any contention on the source project. The full list of what is and is not cloned, and the limits, are in [database branches](https://aurabase.dev/en/docs/deployment#branches). > **Note:** > > A branch is a copy made when you create it, in time proportional to the data (14 seconds for 333 MB on the local test stack). It is not a copy-on-write clone, and it does not follow the source afterwards. ## In CI There is no GitHub Action to install: the CLI does the work. Authenticate with a Personal Access Token (`aura login --token`), then create the branch from the project you test against and keep what the preview needs. Save each snippet as a script of your pipeline: ```bash filename="open-preview.sh" aura login --token "$AURA_PAT" aura branch create "pr-$PR_NUMBER" --from "$AURA_PROJECT_ID" --ttl 3d --json > branch.json # branch.json: id, slug, url, anon_key, service_role_key, expires_at ``` ```bash filename="close-preview.sh" aura login --token "$AURA_PAT" aura branch delete "pr-$PR_NUMBER" --from "$AURA_PROJECT_ID" --force ``` The keys are printed only once, when the branch is created: store them in the job (or as secrets of the preview deployment) right then. To run the pull request's migrations on the branch, link the folder to it and push: `aura link --project-id ` then `aura db push`. The `aura branch` commands were run against a local stack; `aura login --token` is the login of the CI recipes in [deployment](https://aurabase.dev/en/docs/deployment#ci). The GitHub or GitLab workflow around them is yours to write. ## What the branch contains The branch has the **rows of the source** (add `--no-data` for the schema only), including any personal data they hold: there is no anonymization. Create the branch from a staging project, not from production, if the preview must not see real data. Auth users, storage objects, edge functions and secrets are not cloned; seed them in your preview setup. ## TTL and quotas A branch lives 72 hours by default, up to 30 days (`--ttl`). Expired branches are deleted automatically, and so is a branch whose creation fails. A branch does not count against your project limit; it counts against the limit of active branches of your plan (1 on Free, 10 on Pro, 25 on Team), see [limits](https://aurabase.dev/en/docs/limits). Past the limit, `aura branch create` fails with `BRANCH_LIMIT_REACHED`: delete a branch or wait for its TTL. ## To go further - [Deployment](https://aurabase.dev/en/docs/deployment): CI/CD, migrations, rollback, database branches. - [Project management](https://aurabase.dev/en/docs/projects): Projects, environments, regions. - [Performance audit](https://aurabase.dev/en/docs/database/performance): Load testing on a branch. - [Limits](https://aurabase.dev/en/docs/limits): Plan limits, including active branches. --- ### Multi-region deployment Source: https://aurabase.dev/en/docs/deployment/multi-region.md # Multi-region deployment > Cross-region logical replication, automatic failover, data residency by country. Patterns for global SaaS with local latency without sacrificing consistency. ## Three common patterns - **Single region** (default) — everything in `fr-par` (Scaleway, Paris): Postgres, Storage, Functions. Minimum intra-region latency, single point of failure at the region level. - **Primary + read replicas** — primary in one region, read replicas in other EU regions (fr-par → Germany, Finland). Centralized writes, distributed reads. - **Active-active multi-region** (Enterprise) — Postgres with BDR (bi-directional replication), logical decoding per table, custom conflict resolution. ## Table by table, filtered Enable logical replication from the Studio or CLI. Choose the tables to replicate (fine granularity: exclude heavy, non-critical tables). > **Warning:** > > **Roadmap — not available.** The `aura` commands shown below are planned and not delivered yet: the CLI does not have them today. ```bash filename="cli" # Create a read-only replica in Germany aura replica create \ --region de-fsn \ --tables orders,products,customers \ --mode logical # Lag monitoring aura replica status --region de-fsn # → lag: 120ms · last_lsn: 7/3F2A12E8 · healthy ``` ## Automatic within 30 seconds Our agent monitors each primary with multi-AZ health checks. On confirmed failure (3 consecutive checks), a replica is promoted in ~30s. The gateway switches connections automatically. > **Warning:** > > During failover, writes are queued on the SDK client side (automatic retry with backoff). Readings continue on surviving replicas. ## Pinning by country on Enterprise Free and Pro projects are hosted in the EU only. Plan Enterprise: pins each project to a country. Data, backups and replicas never leave the territory — contractual commitment, without third-party certification to date. - **`FR` — France** (GDPR) - **`DE` — Germany** (GDPR) - **`FI` — Finland** (GDPR) ## To go further - [Deployment](https://aurabase.dev/en/docs/deployment): Dev/preview/prod, migrations, rollback. - [Preview databases per pull request](https://aurabase.dev/en/docs/deployment/preview-envs): Test on a copy of your data before production. - [Compliance](https://aurabase.dev/en/docs/compliance): SOC2, ISO, data residency — state of play. - [Performance](https://aurabase.dev/en/docs/database/performance): Read from the nearest replica. --- ### Troubleshooting Source: https://aurabase.dev/en/docs/troubleshooting.md # Troubleshooting > Start from the message or the code in the response. Each entry says what it means and what to do. ## Read an error Every error from the API has the same shape. Program on `code`, which is stable; `message` is for a human and follows the `Accept-Language` header (English by default). ```json filename="error.json" { "error": { "code": "EMAIL_NOT_CONFIRMED", "type": "auth_email_not_confirmed", "message": "Confirm your email address before signing in. …", "request_id": "cc36bc27-5b73-4e92-b7d5-413f59baf263" } } ``` Keep the `request_id` when you ask for help: it finds the request in the logs. The SDK returns the same object as `error` (`{ data, error }`), with `error.code` and `error.status`; it does not throw. Always read `error` before using `data`. ## Common situations ### Sign-up works, sign-in answers EMAIL_NOT_CONFIRMED A new project requires users to confirm their email. On the local stack the message goes to Mailpit: `kubectl -n aurabase-dev port-forward svc/aurabase-mailpit 8025:8025`, then open http://localhost:8025. To skip the step while you develop: `aura auth settings set email_confirmation_required=false`. See the [quick start](https://aurabase.dev/en/docs/getting-started). ### 401 SECRET_KEY_IN_BROWSER A `service_role` key (`aura_sk_…`) reached a browser. Use the anon key (`NEXT_PUBLIC_AURABASE_ANON_KEY`) in client code and keep `AURABASE_SERVICE_ROLE_KEY` on the server. ### 403 « new row violates row-level security policy » Row-level security is on and no policy allows the operation for the caller's role (`aura_anon` for a visitor, `aura_authenticated` for a signed-in user). Check that the user is signed in (a sign-in that failed silently sends the request as a visitor), then add a policy. See [row-level security](https://aurabase.dev/en/docs/database/rls). ### An empty result where you expect rows Without a policy that lets the caller read, a select returns `[]`, not an error. Test the policy as the user with `aura db raw "select …" --as authenticated --user `. ### TABLE_NOT_FOUND The table does not exist in this project, or the schema cache has not reloaded after a change. Create it with `aura db raw "create table …"` or in the SQL editor, then retry. ### Realtime receives nothing Check, in this order: realtime is enabled on the table (`aura db table realtime
on`); the channel reached `SUBSCRIBED` (a `CHANNEL_ERROR` carries the reason); the signed-in user can read the rows (events follow row-level security). A `postgres_changes capacity reached` error means the organization's database has too few free connections: stop idle projects or upgrade the plan. ### A CORS error in the browser The data plane answers with `access-control-allow-origin: *`, so a CORS message in the console usually hides a 4xx or 5xx response. Open the network tab, read the status and the `code`, and fix that. For functions, see [responses and CORS](https://aurabase.dev/en/docs/functions/responses). ### RATE_LIMITED « Try again in N seconds » Too many sign-in attempts for the project: the error carries `retry_after` in seconds. The per-hour limits are project settings (`aura auth settings get`: `rate_limit_login_per_hour`, `rate_limit_signup_per_hour`). ### A function answers 401 or 404 `404 FUNCTION_NOT_FOUND`: the function is not deployed under that name (`aura functions list`). A function call with the public key is the only call a public key can make: see [who can call what](https://aurabase.dev/en/docs/functions/security). ### AI calls answer 400 « provider … not configured » The project has no key for the provider. Save one with the route named in the message (`POST /v1/ai/{project_id}/providers/`), or set the provider key in the service environment. ## Error codes These codes are stable. A code not listed here keeps its own text, and its `code` is still stable. | Code | HTTP | Meaning and what to do | | --- | --- | --- | | `INVALID_TOKEN` | 401 | The access token is unreadable: it is not a valid JWT. Send `Authorization: Bearer <access_token>` obtained by signing in to your project. | | `PROJECT_NOT_FOUND` | 404 | No active project at `<host>`: the project was deleted or the address is wrong. Check NEXT_PUBLIC_AURABASE_URL in Studio › Settings › Connection. | | `PROJECT_URL_REQUIRED` | 400 | This URL does not point to a project: call your project's URL (<form>), shown in Studio › Settings › Connection and expected in NEXT_PUBLIC_AURABASE_URL. | | `SECRET_KEY_IN_BROWSER` | 401 | A secret key (service_role) was used from a browser: it bypasses RLS and must never be sent client-side. Use the anon (public) key in the browser and keep the service_role key on the server. | | `API_KEY_INVALID` | 401 | The API key is invalid, expired or revoked. Send your project's key in the `apikey` header (Studio › Settings › Connection). | | `AUTHORIZATION_MISSING` | 401 | The `Authorization` header is missing. Send `Authorization: Bearer <access_token>`. | | `AUTHORIZATION_BEARER_REQUIRED` | 401 | The `Authorization` header must use the Bearer scheme: `Authorization: Bearer <access_token>`. | | `TOKEN_EXPIRED` | 401 | The access token has expired. Refresh the session (the SDK does it for you) or sign in again. | | `TOKEN_SIGNATURE_INVALID` | 401 | The access token signature is invalid: it was not issued by this project, or it was altered. | | `TOKEN_AUDIENCE_INVALID` | 401 | The access token was issued for another project. Use a token obtained by signing in to this project. | | `RATE_LIMITED` | 429 | Too many attempts. Try again in <retry_after> seconds. | | `INVALID_CREDENTIALS` | 401 | Invalid email or password. | | `EMAIL_ALREADY_IN_USE` | 409 | This email is already in use. | | `BUCKET_NOT_FOUND` | 404 | Bucket "<bucket>" does not exist in this project. Existing buckets: <existing>. Create it with `aura.storage.createBucket('<bucket>')` or in Studio › Storage. | | `FUNCTION_NOT_FOUND` | 404 | Function `<name>` not found: no active function of this project has this name or identifier. List them with `aura functions list`. | | `BUCKET_ALREADY_EXISTS` | 400 | Bucket "<bucket>" already exists in this project. Choose another name, or use the existing bucket. | | `CURRENT_PASSWORD_INCORRECT` | 401 | The current password is incorrect. | | `AI_PROVIDER_NOT_CONFIGURED` | 400 | The AI provider `<provider>` is configured neither for this project nor in the service environment. Save a key with <route> (JSON body with `api_key`), or set <env_var> on the server. | | `CHAT_PROVIDER_NOT_CONFIGURED` | 400 | No chat provider is configured and enabled for this project. Configure one with <route> (JSON body with `api_key` and `enabled: true`) using one of <providers>, or set the matching key in the service environment (ANTHROPIC_API_KEY / OPENAI_API_KEY / GOOGLE_API_KEY). | | `QUOTA_EXCEEDED` | 403 | Monthly quota reached for `<metric>`: <used> of <limit> used. It resets on <resets_at> (UTC). Change plan in Studio › Billing, or see the limits of each plan at https://aurabase.dev/en/docs/limits | | `EMAIL_NOT_CONFIRMED` | 403 | Confirm your email address before signing in. Send a new confirmation link with `auth.resendVerificationEmail(email)`. | | `USER_BANNED` | 403 | This account is suspended. Contact the application's support. | | `MFA_CODE_INVALID` | 401 | The verification code is incorrect. Check the code in your authenticator app and try again. | | `MFA_CHALLENGE_EXPIRED` | 401 | The sign-in challenge has expired. Sign in again with your password. | | `TOTP_CODE_REUSED` | 401 | This code was already used. Wait for the next code from your authenticator app. | | `ANONYMOUS_SIGNINS_DISABLED` | 403 | Anonymous sign-ins are disabled for this project. Enable them in Studio › Authentication › Configuration. | | `PROVIDER_NOT_CONFIGURED` | 400 | <provider> sign-in is not configured for this project. Add a client ID and secret in Studio › Authentication › Providers. | | `REDIRECT_URL_NOT_ALLOWED` | 400 | The redirect URL <redirect_to> is not in this project's allow list. Add it in Studio › Authentication › Configuration › Redirect URLs. | | `SESSION_REVOKED` | 401 | This session was revoked (sign-out, device revoked, password change or ban). Sign in again. | | `REFRESH_TOKEN_REJECTED` | 401 | The refresh token is no longer valid (<reason>). Sign in again. | | `HOOK_FAILED` | 502 | The `<hook>` hook of this project failed: <reason>. Fix the hook in Studio › Authentication › Hooks (or remove its URL); sign-in is refused until it answers correctly. | | `UPSTREAM_UNAVAILABLE` | 503 | A dependency of the platform (<service>) is temporarily unavailable. Retry in <retry_after> seconds; no data was changed. | --- ### Support Source: https://aurabase.dev/en/docs/support.md # Support > Which channel to use, what each plan includes, and what to send so we can answer on the first reply. ## Channels by plan | Plan | Channel | Availability commitment | | --- | --- | --- | | Free | Community on [Discord](https://discord.gg/62HY9GprNc) | Best effort (99.0%) | | Pro | E-mail to `support@aurabase.cloud` | Reply within 24 business hours, 99.95% | | Team | Priority support by e-mail | See your contract | | Enterprise | 24/7 on-call, 15-minute response for a blocking incident (Sev-1) | 99.99% (Multi-AZ) | There is no published response time for the community channel. ## What to send - The `request_id` of the failing call: it is in the body of every error (`error.request_id`). - The error `code` (for example `QUOTA_EXCEEDED`) and the HTTP status. - The project URL (`https://.aurabase.dev`), never the keys. - The version of the SDK (`npm ls @aurabase/aurabase-js`) and of the CLI (`aura --version`). ## Security issues Do not open a public message for a vulnerability. Follow the contact and the encryption key published in [`/security.txt`](https://aurabase.dev/en/security.txt). ## Status The state of each service is on the [status page](https://aurabase.dev/en/status). --- ### Reference Source: https://aurabase.dev/en/docs/reference.md # Reference > Signatures, endpoints, options and errors of every interface to Aurabase. - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): Install, create the client, and every service of @aurabase/aurabase-js - [Client options and errors](https://aurabase.dev/en/docs/sdk/client-options): Client options, error shape, retries and timeouts - [Rust SDK](https://aurabase.dev/en/docs/sdk-rust): The aurabase crate: installation, client and typed queries - [REST API](https://aurabase.dev/en/docs/api-rest): Base URL, API keys, headers, pagination, errors and rate limits - [API endpoints](https://aurabase.dev/en/docs/api): Each endpoint with its parameters, responses and examples - [CLI](https://aurabase.dev/en/docs/cli): Every command of the aura CLI - [MCP server](https://aurabase.dev/en/docs/mcp): Configuration per client, transports, flags and tools --- ### JavaScript SDK Source: https://aurabase.dev/en/docs/sdk-js.md # JavaScript SDK > @aurabase/aurabase-js — typed client for Node, Bun, Deno, Next.js, React, SvelteKit, Vue. Covers Database, Auth, Realtime, Storage, Functions. ## One package, four managers **pnpm** ```bash tab="pnpm" filename="terminal" pnpm add @aurabase/aurabase-js ``` **npm** ```bash tab="npm" filename="terminal" npm install @aurabase/aurabase-js ``` **yarn** ```bash tab="yarn" filename="terminal" yarn add @aurabase/aurabase-js ``` **bun** ```bash tab="bun" filename="terminal" bun add @aurabase/aurabase-js ``` > **Tip:** > > The SDK directly includes `@aurabase/aurabase-js/ssr` export for Next.js (App Router, Server Actions, Middleware), Remix, Nuxt and SvelteKit with automatic management of session cookies and anti-truncation chunking. ## Create the client ```typescript filename="src/lib/aurabase.ts" import { createClient } from '@aurabase/aurabase-js' import type { Database } from './aurabase.types' export const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, { auth: { persistSession: true } } ) ``` ## Native Server-Side Rendering support For SSR architectures (Next.js App Router, Middleware, Server Actions, SvelteKit), import `createServerClient` from `@aurabase/aurabase-js/ssr`. The user session is automatically stored in secure `httpOnly` cookies, with multi-chunk support for large tokens: ```typescript filename="src/middleware.ts" import { createServerClient } from '@aurabase/aurabase-js/ssr' import { NextResponse, type NextRequest } from 'next/server' export async function middleware(request: NextRequest) { let response = NextResponse.next({ request }) const aura = createServerClient( process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, { cookies: { getAll() { return request.cookies.getAll() }, setAll(cookies) { cookies.forEach(({ name, value, options }) => { request.cookies.set(name, value) response.cookies.set(name, value, options) }) }, }, }) await aura.auth.getSession() return response } ``` ## Codegen from your schema `npx @aurabase/gen --out lib/aurabase.types.ts` (or `aura db generate`, which writes `types.ts` in the current folder) generates the types file from your complete schema (tables, views, enums, RPC functions). To plug into `createClient` to type all of your queries. ```json filename="package.json" { "scripts": { "types:gen": "npx @aurabase/gen --out src/aurabase.types.ts", "migrate": "aura db push && pnpm types:gen" } } ``` ## By service ### Database - `.from(table).select(cols?)` → `SelectBuilder` - `.from(table).insert(row)` → `Promise<{ data, error }>` - `.from(table).update(patch)` → `UpdateBuilder` - `.from(table).delete()` → `DeleteBuilder` - `.rpc(fn, args)` → `Promise<{ data, error }>` - `.nosql.collection(name)` → `NoSqlCollectionClient` (`find()`, `insertOne()`, `aggregate()`, `createIndex()`) ### Auth - `.auth.signUp({ email, password, options? })` → `Promise>` - `.auth.signInWithPassword({ email, password })` → `Promise>` - `.auth.signInWithOAuth(provider, opts?) | ({ provider, ... })` → `Promise>` - `.auth.getSession()` → `Promise<{ data: { session }, error }>` - `.auth.signOut()` → `Promise>` - `.auth.mfa.enroll() | .auth.mfaEnroll()` → `Promise>` ### Realtime - `.channel(name, config?)` → `Channel` - `channel.on(event, filter, cb)` → `Channel` - `channel.subscribe()` → `Channel` - `channel.send({ type, event, payload })` → `Promise` - `channel.unsubscribe()` → `Promise` ### Storage - `.storage.from(bucket).upload(path, file, opts?)` → `Promise<{ data, error }>` - `.storage.from(bucket).download(path)` → `Promise` - `.storage.from(bucket).getPublicUrl(path, opts?)` → `{ publicUrl }` - `.storage.from(bucket).createSignedUrl(path, expiresIn)` → `Promise<{ signedUrl }>` - `.storage.from(bucket).remove(paths[])` → `Promise<{ data, error }>` ### Functions - `.functions.invoke(name, { body?, method?, path?, headers?, responseType?, signal?, timeout? })` → `Promise<{ data, error }>` - `.functions.list()` → `Promise<{ data: FunctionDef[], error }>` - `.functions.get(nameOrId)` → `Promise<{ data: FunctionDef, error }>` - `.functions.listJobs({ status?, limit? })` → `Promise<{ data: Job[], error }>` - `.functions.getJob(jobId)` → `Promise<{ data: Job, error }>` - `.functions.enqueueJob(functionName, { payload?, delaySecs?, maxAttempts? })` → `Promise<{ data: Job, error }>` - `.functions.listCronJobs()` → `Promise<{ data: CronJob[], error }>` - `.functions.createCronJob(name, schedule, functionName, { payload? })` → `Promise<{ data: CronJob, error }>` - `.functions.deleteCronJob(name)` → `Promise<{ data, error }>` Only `invoke` is open to the public (`anon`) key. `list`, `get`, `listJobs`, `getJob`, `enqueueJob`, `listCronJobs`, `createCronJob` and `deleteCronJob` require a `service_role` key and belong on your server: a `FunctionDef` carries the function's source code and environment variables, so these calls answer `403` to a public key. `invoke` reports errors as `FunctionsHttpError` (the function answered with an error, any status) or `FunctionsRelayError` (the platform failed: network, 502, 503, 504), both exported by `@aurabase/aurabase-js`. ## Uniform shape \{ data, error \} Each async method returns `{ data, error }`. `error` is `null` on success, otherwise an `AuraError` instance (also exported under the alias `AurabaseError`) with `code`, `message`, `status`, and `details`. Pass `{ parseBigIntAsString: true }` in `createClient` options if your schema uses 64-bit `bigint` values beyond `Number.MAX_SAFE_INTEGER`. ```typescript filename="errors.ts" import { AurabaseError } from '@aurabase/aurabase-js' const { data, error } = await aura.from('users').select('*').single() if (error) { if (error.code === 'PGRST116') notFound() throw error // instanceof AuraError / AurabaseError } ``` ## To go further - [Rust SDK](https://aurabase.dev/en/docs/sdk-rust): Rust-typed client, stable public API. - [CLI](https://aurabase.dev/en/docs/cli): aura CLI — provisioning, migrations, types. - [REST API](https://aurabase.dev/en/docs/api-rest): Without SDK, direct HTTP calls. --- ### Client and services Source: https://aurabase.dev/en/docs/sdk/client.md # Client and services > The entry point of the SDK: how to create the client and which services it exposes. ## Exported functions | Function | Description | | --- | --- | | `function createClient(baseUrl: string, apiKey: string, options?: AuraClientOptions): AuraClient` | Create a new Aurabase client instance. | | `function createAdminClient(baseUrl: string, serviceRoleKey: string, options?: AuraClientOptions): AuraClient` | Creates a client for **SERVER use only** for administration operations (`client.authAdmin`: list/create/ban users, read audit). | ## AuraClient | Property | Description | | --- | --- | | `readonly baseUrl: string` | Project URL (`https://.aurabase.dev`), without trailing bar. | | `readonly apiKey: string \| null` | Project API key (`anon` or `service_role`) sent in the `apikey` header; `null` if none was provided. | | `readonly fetchFn: typeof globalThis.fetch` | Function `fetch` used for all queries (that of `options.fetch`, otherwise `globalThis.fetch`). | | `readonly authStore: BaseAuthStore` | Session store (access token, refresh token, user): memory, `localStorage` or cookies depending on context. | | `readonly retryConfig: { enabled: boolean; maxRetries: number; }` | Read request resumption policy (`GET`, `HEAD`) on transient error: enabled or not, and maximum number of resumptions. | | `readonly requestTimeoutMs?: number` | Default timeout (ms) for JSON requests without signal. `undefined` → core fault (30s). | | `readonly onEvent?: (event: AuraObservabilityEvent) => void` | Observability hook — see `AuraClientOptions.onEvent`. | | `readonly debug?: boolean` | Journalise chaque `AuraObservabilityEvent` via `console.debug` — voir `AuraClientOptions.debug`. | | `readonly parseBigIntAsString?: boolean` | Preserves PostgreSQL 64-bit `bigint` values as strings instead of JSON numbers when enabled. | | `get auth(): AuthService` | Authentication service: registration, connection, session, MFA, OAuth, identities. | | `get authAdmin(): AuthAdminService` | Authentication administration API (users, sessions, audit log, email templates). | | `get db(): DatabaseService` | Database service: queries on tables and views, SQL function calls (`rpc`), raw SQL. | | `get nosql(): NoSqlService` | NoSQL service (MongoDB): collections, document queries and aggregation pipelines (`aggregate`). | | `get storage(): StorageService` | Storage service: buckets, sending, downloading, signed and public URLs, image transformations. | | `get realtime(): RealtimeService` | Real-time service: channels, Postgres changes, broadcast (`broadcast`) and presence. | | `get functions(): FunctionsService` | Edge Functions service: invocation, and management of jobs and cron with a `service_role` key. | | `get ai(): AiService` | AI service: conversation (`chat`), embeddings, RAG (ingest, queries, namespaces), semantic search and sessions. | | `get notifications(): NotificationsService` | Notifications service: sending (email, SMS, push, webhook), history, templates and administration. | | Method | Description | | --- | --- | | `dispose(): void` | Dismounts the client: stops proactive refresh (ticker + visibility + BroadcastChannel), disconnects realtime, empties auth listeners. | | `from, Table extends Schema['Tables'][TableName]>(table: TableName): AuraQueryBuilder`
`from, View extends Schema['Views'][ViewName]>(view: ViewName): AuraQueryBuilder` | Shortcut: query a database table or view (Supabase-compatible API). | | `rpc = Record>(fn: FnName, args?: Args, options?: Parameters['rpc']>[2]): ReturnType['rpc']>` | Shortcut: call a stored procedure / PostgreSQL function via RPC (Supabase-compatible API). | | `channel(name: string, options?: ChannelConfig): AuraChannel` | Shortcut: create a realtime channel with Supabase-compatible API. | | `removeChannel(channel: string \| AuraChannel): void` | Shortcut: remove a realtime channel by name or AuraChannel instance. | | `removeAllChannels(): void` | Shortcut: remove all realtime channels and unsubscribe. | | `getChannels(): AuraChannel[]` | Shortcut: list all active realtime channels. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### Client options, errors, retries and timeouts Source: https://aurabase.dev/en/docs/sdk/client-options.md # Client options, errors, retries and timeouts > The behaviour shared by every service of the SDK, and the options that change it. ## Create the client ```typescript filename="src/lib/aurabase.ts" import { createClient } from '@aurabase/aurabase-js' export const aura = createClient( process.env.NEXT_PUBLIC_AURABASE_URL!, // https://my-app.aurabase.dev process.env.NEXT_PUBLIC_AURABASE_ANON_KEY!, // the public key ) ``` `createClient(url, key, options?)` takes the **project URL** and one key. The project is identified by the host of the URL, so there is no project id to pass. In a local stack, use a URL with the project subdomain, such as `http://my-app-ab12.localhost:8080`; with a bare `http://localhost:8080` the client prints a warning, because the gateway cannot tell which project you mean. Use the public key (`aura_anon_…`) in browsers and apps. A `service_role` key (`aura_sk_…`) belongs on your server only, and the client enforces it: ```typescript filename="server/admin.ts" import { createAdminClient } from '@aurabase/aurabase-js' // Server only: bypasses row-level security. export const admin = createAdminClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!) ``` In a browser, `createClient` **throws** when it receives a `service_role` key, so a leaked key cannot ship by accident. Set `refuseServiceRoleInBrowser: false` to downgrade the error to a warning; do not do this in production. Every service hangs off the client: `aura.auth`, `aura.db`, `aura.storage`, `aura.realtime`, `aura.functions`, `aura.ai`, `aura.notifications`, and `aura.from('table')` as a shortcut for `aura.from('table')`. See [the client reference](https://aurabase.dev/en/docs/sdk/client). ## Options | Option | Default | Effect | | --- | --- | --- | | `auth.persistSession` | `true` in a browser | Keep the session between page loads | | `auth.storage` | `localStorage` in a browser, memory elsewhere | Where the session lives: pass your own store (cookies for SSR) | | `auth.autoRefresh` | `true` | Refresh the access token before it expires, and keep tabs in sync | | `auth.detectSessionInUrl` | `true` in a browser | Read a session from the URL after an OAuth redirect, then clean the URL | | `fetch` | `globalThis.fetch` | Your own `fetch`, for tests or proxies | | `retry` | `true` | Retry reads on transient errors. `false` disables, or `{ enabled, maxRetries }` | | `requestTimeoutMs` | `30000` | Time limit of a request. `0` disables it. | | `onEvent` | none | Receives observability events, see below | | `debug` | `false` | Also print each event with `console.debug('[aurabase]', event)` | | `refuseServiceRoleInBrowser` | `true` | Throw when a `service_role` key reaches a browser | For server-side rendering, use the cookie-based clients described in [Next.js App Router and SSR](https://aurabase.dev/en/docs/guides/nextjs-ssr). ## The error object Every call returns `{ data, error }` and never throws. When it fails, `error` is an `AuraError`: ```typescript filename="errors.ts" import { isAuraError } from '@aurabase/aurabase-js' const { data, error } = await aura.from('posts').select('*') if (error) { console.log(error.status) // 500, or 0 when the failure is on the client console.log(error.code) // 'INTERNAL_ERROR', 'TIMEOUT', 'NETWORK_ERROR', … console.log(error.message) // human-readable console.log(error.details) // the raw body, including error.request_id from the server isAuraError(error) // true } ``` A real failing call returned: ```json filename="error.details" { "error": { "code": "INTERNAL", "message": "boom", "request_id": "req-123" } } ``` | Field | Meaning | | --- | --- | | `status` | The HTTP status. **`0`** means the failure happened before any response: network, timeout, or a refusal by the client. | | `code` | A stable identifier. Server codes keep their value; the client adds the codes below. | | `message` | A readable explanation | | `details` | The raw response body | | `retryAfter` | Seconds to wait, from a `Retry-After` header, on a `429` | | `isNotFound`, `isUnauthorized`, `isForbidden`, `isRateLimited` | Shortcuts on `status` | All error codes are in SCREAMING_SNAKE (`^[A-Z][A-Z0-9_]+$`), whether the server or the client produced them (`error.legacyCode` returns the former lowercase form and is deprecated). Codes produced by the client itself (status `0`): `TIMEOUT`, `NETWORK_ERROR`, `INVALID_RESPONSE` (a success whose body is not JSON), `NO_SESSION`, `REFRESH_DISCARDED`, `INVALID_PATH`, `INVALID_BODY`. Authentication adds codes such as `INVALID_CREDENTIALS`, `WEAK_PASSWORD`, `EMAIL_ALREADY_IN_USE`, `USER_NOT_FOUND`, `INVALID_OTP`, `SESSION_EXPIRED`, `SESSION_REVOKED` and `RATE_LIMITED`. A `429` always carries `RATE_LIMITED`, and `error.retryAfter` holds the `Retry-After` delay in seconds when the server sent one. Test `data` rather than `error` when you need the value. Some calls succeed without content (`204`), and then both `data` and `error` are `null`. ## Retries and timeouts **Retries.** The client retries a request automatically only when all of these hold: - the method is `GET` or `HEAD` (a `POST`, `PUT`, `PATCH` or `DELETE` is never replayed, so nothing runs twice); - the response status is `408`, `429`, `502`, `503` or `504`, or the network failed; - fewer than 3 retries have happened. The delay is random between 0 and `min(500 ms × 2^attempt, 10 s)`. A `Retry-After` header wins over it, capped at 60 seconds. Retried requests carry an `X-Retry-Count` header. A timeout is not retried. Measured against a server that answered `503` twice, then `200`: ```text GET /flaky 590 ms { data: [...] } events: retry#1:503, retry#2:503 POST /flaky 5 ms { error: SERVICE_UNAVAILABLE } (not retried) GET /flaky 1 ms { error: SERVICE_UNAVAILABLE } with retry: false ``` **Timeouts.** A request that gets no answer within `requestTimeoutMs` (30 s by default) ends with `status: 0` and `code: 'TIMEOUT'`. Reading the body is bounded by the same limit, so a server that sends headers and then stalls cannot hang the call. A request to a server that never answered, with a 400 ms limit, returned the error after 405 ms. Two cases do not use this limit because they manage their own: a call where you pass an `AbortSignal`, and uploads. Functions use their own `timeout` option, see [Errors, timeouts and retries](https://aurabase.dev/en/docs/functions/errors). ## Observe the client `onEvent` receives one event per notable thing the client does. It never makes a request fail: an exception thrown by your hook is ignored. | `kind` | Fields | When | | --- | --- | --- | | `retry` | `attempt`, `status?`, `url` | Before a retry | | `timeout` | `url` | A request hit `requestTimeoutMs` | | `refresh-success` | none | A session refresh succeeded | | `refresh-discarded` | `reason` | A refresh was dropped because the session changed meanwhile | | `jwks-fetch-failed` | `baseUrl` | The signing keys could not be fetched (local token checks) | | `storage-blocked` | `op` | The browser refused storage access | ```typescript filename="observe.ts" const aura = createClient(url, key, { onEvent: (e) => metrics.increment(`aurabase.${e.kind}`), }) ``` URLs in events have their query string and fragment removed, because they can carry secrets (`?apikey=`, signed links). ## Sessions and tokens - The client sends `apikey` on every request, and `Authorization: Bearer ` once a user is signed in. - It refreshes the access token when fewer than 30 seconds remain. Concurrent refreshes are merged into one, so a rotating refresh token is used once. - A `401` triggers one refresh and one replay of the request, then stops. - In a browser, refreshes are coordinated across tabs. - `aura.auth.onAuthStateChange(callback)` tells you about `SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`, `USER_UPDATED` and `MFA_CHALLENGE`. See [the auth guide](https://aurabase.dev/en/docs/auth/authenticate-users). --- ### JavaScript SDK: auth reference Source: https://aurabase.dev/en/docs/sdk/auth.md # JavaScript SDK: auth reference > Every authentication and user-administration method, with its signature. ## Exported functions | Function | Description | | --- | --- | | `function isMfaChallenge(v: unknown): v is MfaChallenge` | Discriminant type guard `LoginResponse = TokenPair \| MfaChallenge`. | ## AuthService | Property | Description | | --- | --- | | `get mfa(): { enroll: (params?: { factor_type?: 'totp'; factorType?: 'totp'; }) => Promise>; verifySetup: (codeOrParams: string \| { code: string; }) => Promise>; verify: (req: MfaVerifyRequest) => Promise>; unenroll: (passwordOrParams: string \| { password: string; }) => Promise>; regenerateRecoveryCodes: (codeOrParams: string \| { code: string; }) => Promise>; factors: (mfaToken: string) => Promise>; sms: { setup: (phone: string) => Promise>; verifySetup: (code: string) => Promise>; send: (mfaToken: string) => Promise>; remove: (password: string) => Promise>; }; webauthn: { register: (params?: WebAuthnRegisterParams) => Promise>; verify: (params: WebAuthnVerifyParams) => Promise>; list: () => Promise>; remove: (id: string, password: string) => Promise>; }; }` | Unified facade for MFA (TOTP) operations. | | `get admin(): AuthAdminService` | Authentication administration API (aliased to `client.authAdmin`). | | Method | Description | | --- | --- | | `dispose(): void` | Dismantles the proactive lifecycle: ticker, visibility, BroadcastChannel, listeners. | | `onAuthStateChange(callback: AuthStateCallback): { unsubscribe: () => void; data: { subscription: { unsubscribe: () => void; }; }; }` | Listens for session state changes (`SIGNED_IN`, `SIGNED_OUT`, `TOKEN_REFRESHED`, `USER_UPDATED`, `MFA_CHALLENGE`…). | | `signUp(req: SignUpRequest): Promise>` | Create an account with email and password. | | `signInWithPassword(req: SignInRequest): Promise>` | Logs in a user by email and password. | | `signInWithOAuth(provider: string, options?: OAuthSignInOptions): Promise>`
`signInWithOAuth(options: OAuthSignInObjectOptions): Promise>` | Starts a OAuth flow: always returns `{ url }` (and additionally redirects the browser if an `window` exists). | | `signInWithMagicLink(req: MagicLinkRequest): Promise>` | Sends a connection link by email (“magic link”). | | `signInAnonymously(): Promise>` | Creates an anonymous session (user without email), recorded and reported by `SIGNED_IN`. | | `signOut(): Promise>` | Disconnect: revokes the server-side refresh token if it exists, flushes the local session, and issues `SIGNED_OUT`. | | `refreshSession(): Promise>` | Refreshes the session with the refresh token and issues `TOKEN_REFRESHED`. | | `getSession(): Promise<{ data: { session: Session \| null; }; error: null; }>` | Current session read from the store (no network call). | | `setSession(tokenOrSession: string \| { access_token: string; refresh_token: string; }, possibleRefreshToken?: string): Promise>` | Installs a session from an existing access token and refresh token (e.g. received from a server). | | `exchangeCodeForSession(authCode: string, codeVerifier?: string): Promise>` | Exchanges the PKCE authorization code for a session. | | `listSessions(): Promise>` | Lists the logged in user's sessions (device, IP address, dates); `is_current` locates the current session. | | `revokeSession(sessionId: string): Promise>` | Revokes a session of the user connected by their identifier. | | `revokeAllSessions(): Promise>` | Logs out the user everywhere: revokes all their sessions, flushes the local session, and issues `SIGNED_OUT`. | | `getUser(jwt?: string): Promise>` | Retrieves the validated user on the server side. | | `getClaims(jwt?: string, options?: { allowExpired?: boolean; issuer?: string; audience?: string; }): Promise>` | Verifies and decodes the claims of a JWT. | | `deleteUser(password: string): Promise>` | Deletes the connected user's account after confirmation with their password, then clears the local session. | | `updateUser(req: UpdateUserRequest): Promise>` | Updates the logged in user (metadata, password, etc.) and issues `USER_UPDATED`. | | `resetPasswordForEmail(emailOrReq: string \| PasswordResetRequest): Promise>` | Sends a password reset email (accepts a string email or PasswordResetRequest object). | | `updatePassword(newPassword: string, currentPassword?: string): Promise>` | Changes the password of the logged in user. | | `mfaEnroll(): Promise>` | MFA: starts TOTP enrollment and returns the `secret` and the URL `otpauth_url` to display as a QR code. | | `mfaVerifySetup(code: string): Promise>` | MFA: confirms the enrollment with a first code and returns the recovery codes. | | `mfaVerify(req: MfaVerifyRequest): Promise>` | MFA: terminates a connection that returned a challenge (`mfa_token` and TOTP code). | | `mfaUnenroll(password: string): Promise>` | MFA: deactivates MFA after confirmation with the password. | | `verifyOtp(params: VerifyEmailChangeOtpParams): Promise>`
`verifyOtp(params: Exclude): Promise>` | SINGLE entry point of OTP verification (parity `verifyOtp` of `@supabase/auth-js`). | | `resendVerificationEmail(email?: string): Promise>` | Resends the verification email, to `email` or to the logged in user's address. | | `signInWithEmailOtp(email: string): Promise>` | Sends a one-time use code by email; to be confirmed by `verifyOtp({ type: 'email' })`. | | `signInWithSmsOtp(phone: string): Promise>` | Sends a one-time code by SMS; to be confirmed by `verifyOtp({ type: 'sms' })`. | | `listIdentities(): Promise>` | Lists the identities (providers) linked to the logged in user. | | `linkIdentity(provider: string): Promise>` | Starts binding a provider OAuth to the connected account and returns the authorization URL to open. | | `unlinkIdentity(identityId: string): Promise>` | Detaches an identity from the account connected by its identifier. | | `regenerateRecoveryCodes(code: string): Promise>` | MFA: regenerates the recovery codes after confirmation with a TOTP code. | | `signInWithIdToken(provider: string, idToken: string, accessToken?: string): Promise>` | Exchanges a provider token ID (Google/Apple, native mobile) for a session. | | `getSettings(): Promise; mailer_autoconfirm: boolean; mfa_enabled: boolean; }>>` | GoTrue parity: GET /settings — public project config (no auth required). | | `resetPassword(token: string, newPassword: string): Promise>` | Consumes the password recovery token and applies the new password. | | `promoteAnonymous(credentials: { email: string; password: string; }): Promise>` | Converts the current anonymous user (JWT required) to a regular email+password account. | | `verifyMagicLink(token: string): Promise>` | Consumes the magic link token and returns a TokenPair. | ## AuthAdminService | Method | Description | | --- | --- | | `listUsers(params?: { limit?: number; offset?: number; search?: string; }): Promise>` | Lists project users, with search (`search`) and pagination (`limit`, `offset`). | | `getUser(userId: string): Promise>` | Reads a user by their ID. | | `createUser(data: AdminCreateUserRequest): Promise>` | Creates a user without going through public registration (email, password, metadata, role). | | `updateUser(userId: string, data: AdminUpdateUserRequest): Promise>` | Updates a user: only the provided fields change. | | `deleteUser(userId: string): Promise>` | Delete a user. | | `banUser(userId: string): Promise>` | Bans a user: he can no longer log in. | | `unbanUser(userId: string): Promise>` | Lift a user's ban. | | `generateLink(userIdOrParams: string \| { userId?: string; user_id?: string; email?: string; type: GenerateLinkType; redirectTo?: string; redirect_to?: string; }, type?: GenerateLinkType): Promise>` | Generates a one-time link for a user (`'magic'`, `'recovery'`, or `'invite'`) and returns `{ link, token }`. | | `impersonate(userId: string, options?: { reason?: string; ttlSeconds?: number; allowPrivileged?: boolean; }): Promise>` | Impersonation (AUTH-037): SHORT token (10 minutes at most) to act as the user, with the claim `act: { sub }`. | | `importUsers(users: ImportUserInput[]): Promise>` | Bulk import (AUTH-037): up to 1000 users per call, with bcrypt or argon2id hash. | | `listSigningKeys(): Promise>` | Project signature keys (active + previous), JWKS URL and issuer (`iss`). | | `rotateSigningKey(): Promise>` | Rotation: a new key signs the new tokens, the old one remains published for 24 hours. | | `revokeSigningKey(kid: string): Promise>` | Revokes an old compromised key (removed from JWKS, tokens refused). | | `getUserStats(): Promise>` | User statistics: total, verified, banned, with MFA and new over 7 days. | | `listUserIdentities(userId: string): Promise>` | Lists identities linked to a user (OAuth providers, email). | | `listSessions(params?: { userId?: string; limit?: number; offset?: number; }): Promise>` | Lists active sessions of all users, filterable by `userId`, with pagination. | | `revokeSession(sessionId: string): Promise>` | Revokes a session by its identifier. | | `getAuditLog(params?: { userId?: string; limit?: number; offset?: number; }): Promise>` | Reads the audit log (action, IP address, user agent, date), filterable by `userId`, with paging. | | `getSettings(): Promise>` | Reads the project's authentication settings. | | `updateSettings(data: AuthSettingsUpdate): Promise>` | Updates the auth settings of the project (partial merge: only the provided fields are written, `COALESCE` on the backend side). | | `listEmailTemplates(): Promise[]>>` | Lists project authentication email templates. | | `getEmailTemplate(type: string): Promise>>` | Reads the email template of a given type (e.g. confirmation, recovery). | | `updateEmailTemplate(type: string, data: EmailTemplateUpdate): Promise>>` | Replaces email template content of a given type. | | `deleteEmailTemplate(type: string): Promise>` | Removes the custom template from an email type. | | `testEmailTemplate(type: string, body: { to_email: string; }): Promise>` | Sends a test email with a type's template to the address `to_email`. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: database reference Source: https://aurabase.dev/en/docs/sdk/db.md # JavaScript SDK: database reference > Every method of `aura.db` and of the chainable query builder, with its signature. ## DatabaseService | Method | Description | | --- | --- | | `from, Table extends Schema['Tables'][TableName]>(table: TableName): AuraQueryBuilder`
`from, View extends Schema['Views'][ViewName]>(view: ViewName): AuraQueryBuilder` | Start a query on a table. | | `sql(query: string, params?: unknown[], options?: RawSqlOptions): Promise>` | Executes a raw SQL query (`POST /v1/db/raw`). | | `rpc = RpcArgsFor, Fn extends { Row: Record; Result: unknown; RelationName: unknown; Relationships: unknown; } = RpcResultFor>(fn: FnName, args?: Args, options?: RpcOptions): AuraFilterBuilder` | Calls a function Postgres exposed by PostgREST (`POST\|GET\|HEAD /rpc/{fn}`). | | `schema(): Promise>` | Fetch the schema (tables & columns, Postgres functions exposed via PostgREST, enum types and views) for the current project. | | `enableRealtime(table: string): Promise>` | Enables realtime (`postgres_changes`) on a table: its INSERT/UPDATE/DELETE are then broadcast to subscribers, filtered by their RLS policies. | | `disableRealtime(table: string): Promise>` | Disables realtime on a table (the reverse of `enableRealtime`). | | `listFunctions(): Promise>` | Lists the functions of the project schema (`GET /v1/db/functions`). | | `createFunction(definition: CreatePgFunctionRequest): Promise>` | Creates or replaces a Postgres (`POST /v1/db/functions`) function. **Requires a `service_role` key.** PostgreSQL projects only. | | `dropFunction(name: string): Promise>` | Removes a feature from the project schema (`DELETE /v1/db/functions/{name}`). **Requires a `service_role` key.** | | `listTriggers(table: PgRelationName): Promise>` | Lists the triggers of a table (`GET /v1/db/{table}/triggers`). | | `createTrigger(table: PgRelationName, definition: CreatePgTriggerRequest): Promise>` | Creates a trigger on a table (`POST /v1/db/{table}/triggers`). **Requires a `service_role` key.** PostgreSQL projects only. | | `dropTrigger(table: PgRelationName, name: string): Promise>` | Removes a trigger from a table (`DELETE /v1/db/{table}/triggers/{name}`). **Requires `service_role`.** | ## AuraQueryBuilder Chainable query builder that compiles to URL query parameters matching the backend's QueryOptions / FilterOp format. | Method | Description | | --- | --- | | `insert(body: Relation extends { Insert: infer I; } ? I \| I[] : never): this` | Inserts a row or an array of rows. | | `update(id: string, body: Relation extends { Update: infer U; } ? U : never): AuraFilterBuilder`
`update(body: Relation extends { Update: infer U; } ? U : never): AuraFilterBuilder` | Updates rows: `update(body)` targeted by filters, or `update(id, body)` for one row per identifier. | | `delete(id?: string): AuraFilterBuilder` | Deletes rows: targeted by filters, or one row by identifier with `delete(id)`. | | `upsert(body: Relation extends { Insert: infer I; } ? I \| I[] : never, options?: { onConflict?: string; }): AuraFilterBuilder` | Inserts or updates (upsert) a row or an array of rows. `options.onConflict` names the conflict column (`id` by default). | ## AuraFilterBuilder All PostgREST filters (`eq`, `neq`, ... `ilikeAnyOf`). | Method | Description | | --- | --- | | `eq(column: C, value: Row[C]): this` | Filters rows where `column` equals `value`. | | `neq(column: C, value: Row[C]): this` | Filters rows where `column` is different from `value`. | | `after(column: C, lastValue: Row[C], options?: { ascending?: boolean; }): this` | PostgreSQL keyset pagination: the page that FOLLOWS the last value read from a unique, sorted column (stable, no duplicates or skips, constant cost — unlike `offset`). | | `gt(column: C, value: Row[C]): this` | Filters rows where `column` is strictly greater than `value`. | | `gte(column: C, value: Row[C]): this` | Filters rows where `column` is greater than or equal to `value`. | | `lt(column: C, value: Row[C]): this` | Filters rows where `column` is strictly less than `value`. | | `lte(column: C, value: Row[C]): this` | Filters rows where `column` is less than or equal to `value`. | | `like(column: keyof Row & string, pattern: string): this` | Filter by pattern `LIKE`, case sensitive (`%` replaces a sequence of characters). | | `ilike(column: keyof Row & string, pattern: string): this` | Filter by pattern `ILIKE`, case insensitive. | | `is(column: keyof Row & string, value: 'null' \| 'true' \| 'false' \| 'unknown' \| 'not.null'): this` | IS NULL or IS NOT NULL filter. | | `in(column: C, values: Row[C][]): this` | Filters rows whose `column` is one of `values`. | | `or(filters: Array<{ column: string; op: string; value: unknown; }>): this` | Add an OR group: `or=(col1.eq.val1,col2.gt.val2)` | | `notIn(column: C, values: Row[C][]): this` | Filters rows where `column` is not equal to any of `values`. | | `contains(column: keyof Row & string, value: unknown): this` | Filters rows whose column (table, JSON or range) contains `value` (operator `@>`). | | `containedBy(column: keyof Row & string, value: unknown): this` | Filters rows whose column (array, JSON or range) is contained in `value` (operator `<@`). | | `overlaps(column: keyof Row & string, value: unknown): this` | Filters rows whose column (array or range) has at least one element in common with `value` (operator `&&`). | | `rangeGt(column: keyof Row & string, range: string): this` | Interval: filters the ranges located strictly to the right of `range` (operator `>>`). | | `rangeGte(column: keyof Row & string, range: string): this` | Range: Filters ranges that do not extend to the left of `range` (operator `&>`). | | `rangeLt(column: keyof Row & string, range: string): this` | Interval: filters ranges located strictly to the left of `range` (operator `<<`). | | `rangeLte(column: keyof Row & string, range: string): this` | Range: Filters ranges that do not extend to the right of `range` (operator `&<`). | | `rangeAdjacent(column: keyof Row & string, range: string): this` | Range: filters ranges adjacent to `range` (operator `-\|-`). | | `isDistinct(column: keyof Row & string, value: unknown): this` | Filters rows where `column` is distinct from `value`, treating `NULL` as a value (`IS DISTINCT FROM`). | | `not(column: string, op: string, value: unknown): this` | Negates a filter: `not('status', 'eq', 'done')` is equivalent to `status` different from `done`. | | `filter(column: string, op: string, value: unknown): this` | Adds a filter with a raw PostgREST operator (`eq`, `gt`, `cs`…), for cases not covered by a dedicated method. | | `match(query: Record): this` | Filter by equality on several columns at the same time: `match({ a: 1, b: 2 })`. | | `textSearch(column: keyof Row & string, query: string, options?: { type?: 'plain' \| 'phrase' \| 'websearch'; config?: string; }): this` | Full text search. `options.type` chooses the query: `'plain'`, `'phrase'` or `'websearch'` (otherwise native `tsquery` syntax); `options.config` sets the language configuration. | | `likeAllOf(column: keyof Row & string, patterns: string[]): this` | Filter `LIKE`: the column must match ALL patterns. | | `likeAnyOf(column: keyof Row & string, patterns: string[]): this` | Filter `LIKE`: the column must match AT LEAST ONE of the patterns. | | `ilikeAllOf(column: keyof Row & string, patterns: string[]): this` | Filter `ILIKE` (case insensitive): the column must match ALL patterns. | | `ilikeAnyOf(column: keyof Row & string, patterns: string[]): this` | Filter `ILIKE` (case insensitive): the column must match AT LEAST ONE of the patterns. | ## AuraTransformBuilder Column selection, sorting, pagination and cardinality modifiers (`single`/`maybeSingle`/`count`). | Method | Description | | --- | --- | | `select>(columns?: Query, options?: SelectOptions): AuraFilterBuilder` | Select columns and optionally embed related resources (PostgREST parity). | | `order(column: string, directionOrOptions?: 'asc' \| 'desc' \| OrderOptions): this` | Sort on a column. | | `limit(n: number): this` | Limits the number of rows returned. | | `offset(n: number): this` | Ignores the first `n` rows (shift paging). | | `range(from: number, to: number): this` | Pages by index interval \[from, to\] (inclusive, base 0). | | `cursor(cursor: string): this` | Opaque cursor pagination — **MongoDB only**. | | `count(mode?: CountMode): this` | Requests the total number of matching rows (default `'exact'`, `'planned'` or `'estimated'`), returned in `count`. | | `single(): AuraPostgrestBuilder` | Waits for exactly one row and returns the object itself; 0 or several rows give the error `PGRST116`. | | `maybeSingle(): AuraPostgrestBuilder` | Like `single()`, but 0 rows are not an error: `data` is then `null`. | ## AuraPostgrestBuilder Base class: shared state, constructor, HTTP execution (`then`/`_execute`), `throwOnError` and `buildQueryString`. | Method | Description | | --- | --- | | `throwOnError(): this` | Throws an exception (instead of returning `{ error }`) when the request fails. | | `toJSON(): { notExecuted: string; query: string; }` | `JSON.stringify(builder)` / `console.log(builder)`: a builder you did not `await` has sent NOTHING. | | `buildQueryString(): string` | Constructs the query string PostgREST (select, filters, sort, pagination) without running the query; useful for debugging. | | `then, TResult2 = never>(onfulfilled?: ((value: AuraResponse) => TResult1 \| PromiseLike) \| null, onrejected?: ((reason: unknown) => TResult2 \| PromiseLike) \| null): Promise` | Executes the query: the builder is “thenable”, a simple `await` is enough. | > **Measured behavior that differs from the descriptions above** > > - `upsert()` does not update an existing row: on a key that already exists it answers `409 DUPLICATE_KEY`. Use `insert … on conflict … do update` in SQL or in a function called with `rpc()`: [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert#upsert). > - `insert()` and `update()` return the written rows even without `.select()`, and `count` is `null` on an insert or an update: count with a separate read ([Paginate and count rows](https://aurabase.dev/en/docs/database/pagination#count)). > - `order(column, { referencedTable })` is rejected with `400` by the API: sort nested rows over REST or in your code ([Join tables and nest rows](https://aurabase.dev/en/docs/database/joins#order)). > - For `IS NOT NULL`, use `is(column, 'not.null')`. `neq(column, null)`, suggested by the code comment of `is()`, sends `neq.null`: on a number column it fails with `400 INVALID_INPUT`, on a text column it compares with the text `'null'` ([Filter operators](https://aurabase.dev/en/docs/database/filter-operators#lists-null)). > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: storage reference Source: https://aurabase.dev/en/docs/sdk/storage.md # JavaScript SDK: storage reference > Every method that manages buckets and objects, with its signature. ## StorageService | Method | Description | | --- | --- | | `from(bucketId: string): StorageBucketClient` | Returns a client scoped to a specific bucket (DX parity Supabase). | | `listBuckets(): Promise>` | List the project buckets. | | `getBucket(id: string): Promise>` | Reads a bucket by its identifier. | | `createBucket(name: string, options?: { public?: boolean; fileSizeLimit?: number; allowedMimeTypes?: string[]; }): Promise>` | Create a bucket. `public` (default `false`) makes its objects readable without authentication; `fileSizeLimit` (in bytes) and `allowedMimeTypes` limit the accepted files. | | `updateBucket(id: string, options?: { public?: boolean; fileSizeLimit?: number; allowedMimeTypes?: string[]; }): Promise>` | Updates an existing bucket (PARTIAL update: only the provided fields are sent). | | `deleteBucket(id: string): Promise>` | Deletes a bucket by its identifier. | | `upload(bucketId: string, path: string, file: Blob \| File \| ArrayBuffer \| Uint8Array, options?: { contentType?: string; upsert?: boolean; metadata?: Record; authToken?: string; signal?: AbortSignal; onUploadProgress?: (progress: UploadProgressEvent) => void; }): Promise>` | Upload a file to a bucket. | | `uploadToSignedUrl(signedUrl: string, file: Blob \| File \| ArrayBuffer \| Uint8Array, options?: { contentType?: string; signal?: AbortSignal; onUploadProgress?: (progress: UploadProgressEvent) => void; }): Promise>` | Direct upload to a pre-signed URL (`createSignedUploadUrl`). | | `download(bucketId: string, path: string, options?: { transform?: ImageTransform; download?: boolean \| string; }): BlobDownloadBuilder` | Lazy download of a file. | | `list(bucketId: string, pathOrOptions?: string \| { prefix?: string; limit?: number; offset?: number; cursor?: string; authToken?: string; }, maybeOptions?: { prefix?: string; limit?: number; offset?: number; cursor?: string; authToken?: string; }): Promise>` | List files in a bucket. | | `remove(bucketId: string, paths: string[], options?: { permanent?: boolean; authToken?: string; }): Promise>` | Delete one or more files from a bucket. | | `listTrash(bucketId: string, options?: { prefix?: string; authToken?: string; }): Promise>>` | Lists objects placed in the trash (soft-delete) of a bucket. | | `restore(bucketId: string, path: string, options?: { authToken?: string; }): Promise>` | Restores an object placed in the trash (soft-delete). | | `copy(bucketId: string, fromPath: string, toPath: string, options?: { destinationBucket?: string; authToken?: string; }): Promise>` | Copy a file within a bucket. | | `move(bucketId: string, fromPath: string, toPath: string, options?: { destinationBucket?: string; authToken?: string; }): Promise>` | Move/rename a file within a bucket or to another bucket. | | `getMetadata(bucketId: string, path: string, options?: { authToken?: string; }): Promise>` | Get file metadata. | | `createSignedUrl(bucketId: string, path: string, expiresInSeconds?: number, options?: { transform?: ImageTransform; download?: boolean \| string; authToken?: string; }): Promise>` | Generate a signed (temporary) download URL. | | `createSignedUrls(bucketId: string, paths: string[], expiresInSeconds?: number, options?: { transform?: ImageTransform; download?: boolean \| string; authToken?: string; }): Promise>>` | Generates several signed URLs in one pass (batch). | | `createSignedUploadUrl(bucketId: string, path: string, expiresInSeconds?: number, options?: { upsert?: boolean; authToken?: string; }): Promise>` | Generate a signed upload URL (presigned PUT). | | `getPublicUrl(bucketId: string, path: string, options?: { transform?: ImageTransform; download?: boolean \| string; }): string` | Constructs a URL to a file in a bucket. | ## StorageBucketClient Access client scoped to a specific bucket (DX parity Supabase). | Property | Description | | --- | --- | | `readonly bucketId: string` | Identifier of the bucket to which this client is linked: all its methods act on this bucket. | | Method | Description | | --- | --- | | `upload(path: string, file: Blob \| File \| ArrayBuffer \| Uint8Array, options?: { contentType?: string; upsert?: boolean; metadata?: Record; authToken?: string; signal?: AbortSignal; onUploadProgress?: (progress: UploadProgressEvent) => void; }): Promise>` | Upload a file to this bucket. | | `uploadToSignedUrl(signedUrl: string, file: Blob \| File \| ArrayBuffer \| Uint8Array, options?: { contentType?: string; signal?: AbortSignal; onUploadProgress?: (progress: UploadProgressEvent) => void; }): Promise>` | Direct upload to a signed URL. | | `download(path: string, options?: { transform?: ImageTransform; download?: boolean \| string; }): BlobDownloadBuilder` | Download a file from this bucket. | | `list(pathOrOptions?: string \| { prefix?: string; limit?: number; offset?: number; cursor?: string; authToken?: string; }, options?: { prefix?: string; limit?: number; offset?: number; cursor?: string; authToken?: string; }): Promise>` | List the files in this bucket. | | `remove(paths: string[], options?: { permanent?: boolean; authToken?: string; }): Promise>` | Deletes one or more files from this bucket. | | `listTrash(options?: { prefix?: string; authToken?: string; }): Promise>>` | Lists the files in the trash of this bucket (soft-delete). | | `restore(path: string, options?: { authToken?: string; }): Promise>` | Restores a file from the Recycle Bin. | | `copy(fromPath: string, toPath: string, options?: { destinationBucket?: string; authToken?: string; }): Promise>` | Copies a file within this bucket or to another bucket. | | `move(fromPath: string, toPath: string, options?: { destinationBucket?: string; authToken?: string; }): Promise>` | Moves or renames a file within this bucket or to another bucket. | | `createSignedUrl(path: string, expiresInSeconds?: number, options?: { transform?: ImageTransform; download?: boolean \| string; authToken?: string; }): Promise>` | Creates a temporary signed URL for a file in this bucket. | | `getMetadata(path: string, options?: { authToken?: string; }): Promise>` | Reads metadata from a file in this bucket. | | `createSignedUrls(paths: string[], expiresInSeconds?: number, options?: { transform?: ImageTransform; download?: boolean \| string; authToken?: string; }): Promise>>` | Creates multiple signed URLs in one pass for this bucket. | | `createSignedUploadUrl(path: string, expiresInSeconds?: number, options?: { upsert?: boolean; authToken?: string; }): Promise>` | Creates a presigned upload URL (direct PUT). | | `getPublicUrl(path: string, options?: { transform?: ImageTransform; download?: boolean \| string; }): { data: { publicUrl: string; }; }` | Returns the public URL of a file in this bucket. | ## BlobDownloadBuilder Lazy download (Blob by default). | Method | Description | | --- | --- | | `asStream(): StreamDownloadBuilder` | Switches to streaming reading: the result becomes a `ReadableStream` instead of a `Blob` loaded into memory. | | `then, TR2 = never>(onfulfilled?: ((v: AuraResponse) => TR1 \| PromiseLike) \| null, onrejected?: ((e: unknown) => TR2 \| PromiseLike) \| null): Promise` | Triggers the download (lazy: the request only starts at `await`); the result is memorized. | ## StreamDownloadBuilder Variante flux — `res.body` (ReadableStream). | Method | Description | | --- | --- | | `then>, TR2 = never>(onfulfilled?: ((v: AuraResponse>) => TR1 \| PromiseLike) \| null, onrejected?: ((e: unknown) => TR2 \| PromiseLike) \| null): Promise` | Triggers streaming (lazy) download; the result is memorized. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: realtime reference Source: https://aurabase.dev/en/docs/sdk/realtime.md # JavaScript SDK: realtime reference > Every method of the realtime service and of channels, with its signature. ## RealtimeService | Property | Description | | --- | --- | | `get connectionState(): ConnectionState` | Current connection state. | | `get isConnected(): boolean` | Whether the WebSocket is currently connected. | | Method | Description | | --- | --- | | `onStateChange(callback: (state: ConnectionState) => void): () => void` | Listen for connection state changes. | | `onError(callback: (err: RealtimeConnectionError) => void): () => void` | Listen for realtime connection transport errors. | | `connect(): void` | Ensure the WebSocket connection is open. | | `refreshToken(token: string): void` | Refresh the JWT token on an existing connection (no disconnect). | | `setAuth(token?: string): void` | Explicitly defines/refreshes the token used for authorization of private and broadcast channels (parity `@supabase/realtime-js` `setAuth`). | | `httpBroadcast(channel: string, event: string, payload?: Record, options?: HttpBroadcastOptions): Promise>` | Sends a broadcast via HTTP (REST), without an open WebSocket connection (parity `@supabase/realtime-js`). | | `setAutoReconnect(enabled: boolean, maxAttempts?: number): void` | Enable/disable auto-reconnect (enabled by default). | | `disconnect(): void` | Disconnect the WebSocket and clean up all channels. | | `channel(name: string, options?: ChannelConfig): AuraChannel` | Create or retrieve a channel by name. | | `removeChannel(channel: string \| AuraChannel): void` | Remove a channel by name or by AuraChannel instance. | | `getChannels(): AuraChannel[]` | List active channels. | | `removeAllChannels(): void` | Remove all channels and subscriptions. | ## AuraChannel A realtime channel with Supabase-compatible chainable API. | Property | Description | | --- | --- | | `readonly name: string` | Channel name as passed to `realtime.channel(name)`. | | `get fullName(): string` | Full channel name with project prefix (for server protocol) | | `get isSubscribed(): boolean` | Whether this channel has been subscribed. | | Method | Description | | --- | --- | | `on>(type: 'postgres_changes', filter: PostgresChangesFilter & { event: 'INSERT'; }, callback: (payload: RealtimePostgresInsertPayload) => void): AuraChannelSubscription`
`on>(type: 'postgres_changes', filter: PostgresChangesFilter & { event: 'UPDATE'; }, callback: (payload: RealtimePostgresUpdatePayload) => void): AuraChannelSubscription`
`on>(type: 'postgres_changes', filter: PostgresChangesFilter & { event: 'DELETE'; }, callback: (payload: RealtimePostgresDeletePayload) => void): AuraChannelSubscription`
`on>(type: 'postgres_changes', filter: PostgresChangesFilter, callback: (payload: RealtimePostgresChangesPayload) => void): AuraChannelSubscription`
`on>(type: 'broadcast', filter: BroadcastFilter, callback: (payload: RealtimeBroadcastEvent) => void): AuraChannelSubscription`
`on(type: 'presence', filter: PresenceFilter, callback: (payload: PresenceState \| RealtimeEvent \| Record) => void): AuraChannelSubscription` | Registers a listener for PostgreSQL (CDC) events with INSERT filtering. | | `off(type?: RealtimeListenType, filter?: PostgresChangesFilter \| BroadcastFilter \| PresenceFilter, callback?: (payload: unknown) => void): this` | Removes one or more listeners from the channel without closing the channel or cutting the WebSocket. | | `subscribe(callback?: SubscribeCallback, timeoutMs?: number): this` | Subscribe to the channel. | | `unsubscribe(): Promise<'ok'>` | Unsubscribe from the channel. | | `send(message: BroadcastPayload): Promise` | Sends a broadcast message on the channel. | | `track(state: Record): Promise<'ok' \| 'error'>` | Track presence state for this client. | | `untrack(): Promise<'ok' \| 'error'>` | Stop tracking presence. | | `presenceState(): PresenceState` | Get the current presence state for this channel. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: AI reference Source: https://aurabase.dev/en/docs/sdk/ai.md # JavaScript SDK: AI reference > Every method of the AI service and of sessions, with its signature. ## AiService | Method | Description | | --- | --- | | `session(): Promise` | Mints an ephemeral ticket AI session (`POST /v1/ai/{project_id}/session`) and returns a ready-made `AiSession` for `chat`/`chatStream`/`embed`. | | `chat(messages: ChatMessage[], options?: { model?: string; temperature?: number; max_tokens?: number; system?: string; provider?: string; }): Promise>` | Chat completion (not streamed). | | `chatStream(messages: ChatMessage[], options?: { model?: string; temperature?: number; max_tokens?: number; system?: string; signal?: AbortSignal; }): AsyncGenerator` | Streamed chat completion (SSE). | | `embed(req: EmbedRequest): Promise>` | Generate embeddings for the given input(s). | | `rag(req: RagRequest): Promise>` | Retrieval-Augmented Generation: query a collection and get an answer. | | `ragIngest(req: RagIngestRequest): Promise>` | Ingest a document into a RAG namespace. | | `listNamespaces(): Promise>` | Lists the RAG namespaces of the project. | | `deleteNamespace(namespace: string): Promise>` | Deletes a RAG namespace (and its corpus). | | `reindexNamespace(namespace: string): Promise>` | Re-indexes a RAG namespace with the current embedding model (remediation after a model/dimension change). | | `semanticSearch(query: string, namespace: string, options?: { top_k?: number; threshold?: number; }): Promise>` | Semantic search over an embedding namespace. | | `nl2sql(question: string, options?: { dialect?: 'postgresql' \| 'postgres'; examples?: Array<{ question: string; sql: string; }>; limit?: number; }): Promise>` | Translates a question into SQL. | ## AiSession Ephemeral ticket AI session: mint a short-lived capability (`POST /v1/ai/{project_id}/session`, classic `apikey` auth) then use it for `chat`/`chatStream`/`embed` (`Authorization: Bearer ` ALONE — never `apikey`). | Property | Description | | --- | --- | | `get budgetRemaining(): number` | Remaining token budget, known at the last call (or at mint if no call has yet been made). | | Method | Description | | --- | --- | | `static create(client: AuraClientLike): Promise` | Mint a new AI session. | | `chat(messages: ChatMessage[], options?: AiSessionChatOptions): Promise` | Chat not streamed on this session. | | `chatStream(messages: ChatMessage[], options?: AiSessionChatStreamOptions): AsyncGenerator` | Streamed chat (SSE) on this session. | | `embed(input: string): Promise` | Embedding on this session (`{input}` → `{embedding, budget_remaining}`). | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: notifications reference Source: https://aurabase.dev/en/docs/sdk/notifications.md # JavaScript SDK: notifications reference > Every method for sending and administering notifications, with its signature. ## NotificationsService | Property | Description | | --- | --- | | `readonly admin: NotificationsAdminService` | Administration subclient: statistics, queue, scrap (DLQ), supplier logs, events, rules and settings. | | Method | Description | | --- | --- | | `send(options: SendNotificationOptions): Promise>`
`send(channel: NotificationChannel, recipient: string, body: string, options?: { subject?: string; templateId?: string; variables?: Record; metadata?: Record; idempotencyKey?: string; }): Promise>` | Queues a notification to be sent (Modern Object API). | | `sendBatch(items: Array): Promise>` | Sends a batch of notifications (`POST /send/batch`). | | `sendEmail(options: SendEmailPayload): Promise>`
`sendEmail(recipient: string, subject: string, body: string, options?: SendEmailOptions): Promise>` | Sends a transactional email (`channel: 'email'`). | | `sendSms(options: SendSmsPayload): Promise>`
`sendSms(recipient: string, body: string, options?: SendSmsOptions): Promise>` | Sends a transactional SMS (`channel: 'sms'`). | | `sendPush(options: SendPushPayload): Promise>`
`sendPush(recipient: string, title: string, body: string, options?: SendPushOptions): Promise>` | Sends a mobile push notification (`channel: 'push'`, FCM or APNs). | | `sendWebhook(targetUrl: string, event: string, payload: string \| Record, options?: SendWebhookOptions): Promise>` | Issues an outgoing HTTP POST webhook (`channel: 'webhook'`). | | `retry(id: string): Promise>` | Retry a failed notification (`status: 'failed'` or `'dead_lettered'`). | | `list(options?: { channel?: NotificationChannel; status?: NotificationStatus; search?: string; sort?: 'created_at' \| 'updated_at' \| 'status'; order?: 'asc' \| 'desc'; limit?: number; offset?: number; }): Promise>` | Lists the project's notification history, filterable by `channel`, `status` and `search`, sorted by `created_at`, `updated_at` or `status`, with `limit` / `offset` pagination. | | `get(id: string): Promise>` | Reads a notification by its identifier. | | `listTemplates(): Promise>` | Lists the project message templates. | | `getTemplate(id: string): Promise>` | Reads a message template by its identifier. | | `createTemplate(template: Omit): Promise>` | Creates a template — `name`, `channel`, `subject`, `body`, and nothing else. | | `updateTemplate(id: string, updates: Partial>): Promise>` | Updates a template: `name`, `subject` and/or `body`. | | `deleteTemplate(id: string): Promise>` | Deletes a message template. | ## NotificationsAdminService | Method | Description | | --- | --- | | `getSettings(): Promise>` | Retrieves the project's public supplier and quota settings (`GET /settings`). | | `updateSettings(settings: NotificationSettingsPatch \| Partial): Promise>` | Updates the project's supplier or quota settings (`PATCH /settings`). | | `getStats(options?: { window?: NotificationStatsWindow; channel?: NotificationChannel; }): Promise>` | Aggregated sending statistics (`GET /stats`). | | `getQueue(): Promise>` | Reads the status of the sending queue: depth and distribution of pending notifications. | | `listAttempts(notificationId: string): Promise>` | Lists attempts to send a notification, with the provider's response to each. | | `listDeadLetters(options?: { channel?: NotificationChannel; search?: string; limit?: number; offset?: number; }): Promise>` | Lists notifications placed in the garbage queue (DLQ), filterable by `channel` and `search`. | | `retryDeadLetter(id: string): Promise>` | Resends a specific notification from the scrap queue (DLQ). | | `listEvents(options?: { status?: 'received' \| 'matched' \| 'ignored' \| 'failed' \| 'enqueued'; limit?: number; offset?: number; }): Promise>` | Lists events received by the rules engine, filterable by `status`. | | `listProviderLogs(options?: { channel?: NotificationChannel; status?: NotificationAttemptStatus; limit?: number; offset?: number; }): Promise>` | Third-party vendor execution logs (`GET /providers/logs`). | | `previewTemplate(id: string, variables: Record): Promise>` | Renders a model with the given `variables` for preview, without sending a message. | | `listRules(): Promise>` | Lists the project notification rules (automatic triggering of a sending). | | `createRule(rule: CreateNotificationRuleRequest): Promise>` | Creates a notification rule: for each event of type `trigger_type` which checks `condition`, a message is sent on `channel` to the recipient given by `recipient_expr`, with an optional delay. | | `getRule(id: string): Promise>` | Reads a notification rule by its identifier. | | `updateRule(id: string, updates: UpdateNotificationRuleRequest): Promise>` | Updates a notification rule: only the provided fields change (for example `enabled`). | | `deleteRule(id: string): Promise>` | Deletes a notification rule. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: React reference Source: https://aurabase.dev/en/docs/sdk/react.md # JavaScript SDK: React reference > Reactive authentication state for React: a context provider, hooks and conditional wrappers. ## Exported functions | Function | Description | | --- | --- | | `function AuthProvider({ client, children, initialSession, }: AuthProviderProps): unknown` | Wraps your application to provide reactive Aurabase authentication context. | | `function useAuth(): AuthContextValue` | Access the core Aurabase authentication state and actions. | | `function useUser(): User \| null` | Returns the currently authenticated user, or null if unauthenticated. | | `function useSession(): Session \| null` | Returns the current active session. | | `function SignedIn({ children }: { children: ReactNode; }): unknown` | Conditional component rendering children only when a user is signed in. | | `function SignedOut({ children }: { children: ReactNode; }): unknown` | Conditional component rendering children only when NO user is signed in. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: Next.js reference Source: https://aurabase.dev/en/docs/sdk/nextjs.md # JavaScript SDK: Next.js reference > Protect Next.js routes and read the signed-in user on the server (App Router). ## Exported functions | Function | Description | | --- | --- | | `function createAuthMiddleware(options?: AuthMiddlewareOptions): (request: NextRequestLike) => Promise` | Creates a standard Next.js middleware that validates sessions and protects private routes. | | `function auth(options?: { projectUrl?: string; apiKey?: string; }): Promise<{ userId: string \| null; user: User \| null; session: Session \| null; }>` | Server Component helper (Clerk-like API) to get the current authentication state. | | `function currentUser(options?: { projectUrl?: string; apiKey?: string; }): Promise` | Server Component helper to get the currently logged-in user profile. | | `function createClientForServerComponent(cookieStore: ReadonlyRequestCookiesLike, projectUrl?: string, apiKey?: string): AuraClient` | Creates an Aurabase client optimized for React Server Components (RSC). | | `function createClientForServerAction(cookieStore: ReadonlyRequestCookiesLike, projectUrl?: string, apiKey?: string): AuraClient` | Creates an Aurabase client for Server Actions and Route Handlers. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### JavaScript SDK: SSR reference Source: https://aurabase.dev/en/docs/sdk/ssr.md # JavaScript SDK: SSR reference > Server-side rendering helpers: a client that reads and writes the session in HTTP cookies. ## Exported functions | Function | Description | | --- | --- | | `function createServerClient(baseUrl: string, apiKey: string, options: ServerClientOptions): AuraClient` | — | | `function createBrowserClient(baseUrl: string, apiKey: string, options?: AuraClientOptions): AuraClient` | Create an Aurabase client for browser usage. | ## Exported functions | Function | Description | | --- | --- | | `function parseCookieHeader(header: string): Record` | Parse a raw Cookie header string into key-value pairs. | | `function serializeCookieHeader(name: string, value: string, options?: SerializeCookieOptions): string` | Serialize a cookie name + value + options into a Set-Cookie header value. | > **Generated page** > > This page is generated from the type declarations and comments of the SDK, so it cannot drift from the published code. For worked examples, read the guides. --- ### Rust SDK Source: https://aurabase.dev/en/docs/sdk-rust.md # Rust SDK > aurabase crate — typed async client for Tokio/axum/actix. ## Cargo ```toml filename="Cargo.toml" [dependencies] aurabase = "0.1" tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } ``` > **Warning:** > > Breaking changes are announced in the changelog with a period of 30 days before release. ## Default client ```rust filename="src/aurabase.rs" use aurabase::AuraClient; use std::env; pub fn client() -> AuraClient { AuraClient::new( &env::var("NEXT_PUBLIC_AURABASE_URL").expect("NEXT_PUBLIC_AURABASE_URL"), &env::var("AURABASE_SERVICE_ROLE_KEY").expect("AURABASE_SERVICE_ROLE_KEY"), None, // AuraClientOptions (auth store) ) } ``` ## Typed select The row type is given to `from::()`; `order(column, direction)` takes the direction as a second argument; `execute()` returns an `AuraResponse` whose `data` is the list of rows. Like the JavaScript SDK, an HTTP error is reported in `AuraResponse.error`, not as `Err`: call `into_result()?` to turn it into an `Err`, otherwise `unwrap_or_default()` on `data` hides a rejected key behind an empty list. ```rust filename="src/handlers.rs" use aurabase::{AuraClient, AuraError}; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct Todo { pub id: i64, pub title: String, pub done: bool, } pub async fn recent(aura: &AuraClient) -> Result, AuraError> { let res = aura .from::("todos") .select("id,title,done") .order("created_at", "desc") .limit(5) .execute() .await? .into_result()?; // an HTTP error (invalid key, RLS, missing table…) becomes `Err` Ok(res.unwrap_or_default()) } ``` ## aura db generate --lang rust ```bash filename="terminal" # Generates Deserialize/Serialize structs and enums from your project schema aura db generate --lang rust > src/aurabase_types.rs ``` ## API still evolving These surfaces are still subject to change. Conditional compilation behind the `unstable` feature in Cargo.toml. - `aura.channel()` — WebSocket/SSE client - `aura.functions.invoke()` — edge function call - `aura.storage.upload_resumable()` — tus-style chunks ## To go further - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): Complete Node/Bun/Deno reference. - [REST API](https://aurabase.dev/en/docs/api-rest): Raw HTTP surface if no SDK. - [CLI](https://aurabase.dev/en/docs/cli): CLI for provisioning, migrations, and Rust/TypeScript types. --- ### REST API — Overview Source: https://aurabase.dev/en/docs/api-rest.md # REST API — Overview > Aurabase raw HTTP surface. Compatible with all languages. Base URL, authentication, response format, error codes — then details by endpoint in /docs/api/. ## An origin, the project on the way The URL **is** the project. Each project is served on its own sub-domain, `https://.` (locally `http://.localhost:8080`), and the gateway resolves the project from the host: no project identifier is written in the paths. Studio › Settings › Connection shows this URL, and `NEXT_PUBLIC_AURABASE_URL` holds it. The gateway exposes two plans: the data plan (SDK and applications, `:8080` locally) and the management plan (Studio and administration, `:8090`). The data plan surfaces are prefixed `/v1/db`, `/v1/auth`, `/v1/storage`, `/v1/realtime`, `/v1/functions`, `/v1/notifications`, `/v1/ai`. ```bash filename="examples" # NEXT_PUBLIC_AURABASE_URL = project URL (e.g. http://my-app-x1y2z3.localhost:8080) GET $NEXT_PUBLIC_AURABASE_URL/v1/db/sensors POST $NEXT_PUBLIC_AURABASE_URL/v1/auth/login GET $NEXT_PUBLIC_AURABASE_URL/v1/storage/avatars/u_xx/file.png POST $NEXT_PUBLIC_AURABASE_URL/v1/functions/ocr/invoke ``` > **Note:** > > The forms that carry the project UUID in the path (`/v1/db/{project_id}/sensors`, `/v1/auth/{project_id}/login`, as in the endpoint reference pages) are still accepted on the project URL, and also on the bare gateway origin. They are kept for compatibility: prefer the forms above, which do not depend on the identifier. > **Warning:** > > The streaming routes `/v1/realtime/ws` and `/v1/realtime/sse` are served as they are on the project host. A URL that does not identify a project (for example the bare gateway origin without a project identifier) is rejected as `400`. ## Two keys, one JWT - `anon_key` — publishable. Serves as the API key for any request. Header `apikey`, `X-API-Key`, or parameter `?apikey=` — the latter is only accepted on real-time streams (`/ws`, `/sse`, `/chat/stream`); elsewhere it is explicitly refused. - `service_role_key` — secret, RLS bypass. Reserved for the backend. - `user_jwt` — issued by `POST /v1/auth/login` after authentication. Header `Authorization: Bearer`. ```bash filename="headers.sh" # Anonymous customer (guest) -H "apikey: " # Authenticated client (claims user) -H "apikey: " -H "Authorization: Bearer " # Backend (RLS bypass) -H "apikey: " -H "Authorization: Bearer " ``` ## Standards applied - `Content-Type: application/json` — required on POST/PATCH/PUT (except upload storage, in `multipart/form-data`) - `Prefer: return=representation` — returns the rows created or modified; `return=minimal` for a response without a body (204). `Prefer: count=exact` is read on aura-db mutations (headers `Content-Range` + `Preference-Applied`); To rely on a *reading*, use the `?count=exact` parameter - `Range: 0-49` — **only** on a Postgres project served by PostgREST, which interprets it itself. The aura-db path (MongoDB project, or Postgres with PostgREST disabled) **ignores this** header: it only reads `limit` and `offset`. Prefer `limit`/`offset`, which work on both engines - `Idempotency-Key` — **is NOT read on Database** (`POST /v1/db/…`) writes: two identical POSTs create two rows. It is only honored by `POST /v1/notifications/{project_id}/send` (and `/send/batch`), and by the creation of the management plan API key (`POST /v1/db/{project_id}/api-keys`, 24-hour window) ## Limit + offset ```bash filename="pagination.sh" # Only portable form — works on both engines GET $NEXT_PUBLIC_AURABASE_URL/v1/db/sensors?order=id.asc&limit=50&offset=100 # Keyset “by hand”: filter on the last key read GET $NEXT_PUBLIC_AURABASE_URL/v1/db/sensors?id=gt.{last_id}&order=id.asc&limit=50 # ?cursor=: aura-db ONLY (MongoDB, or Postgres without PostgREST). # On PostgREST the request is refused in 400. GET $NEXT_PUBLIC_AURABASE_URL/v1/db/sensors?cursor={meta.next_cursor}&limit=50 ``` > **Tip:** > > Without `limit`, a read returns at most **1000 rows** — this is both the default and the hard ceiling. When a query actually has more matching rows beyond the returned slice, `meta.has_more` is `true` (and `false` when no additional rows exist or the final slice has been reached); ask for `count=exact` to also get `meta.total`. > **Warning:** > > The total is not read in the same place depending on the engine: on the aura-db path, the response carries the header `Content-Range: items 100-149/1247` (the total is worth `*` if no count was requested); on the PostgREST path, the gateway does not relay this header and places the total in `meta.total` of the JSON envelope. Counting is never done by default: request it with the parameter `?count=exact` (portable form, translated into `Prefer` by the gateway on the PostgREST path), `?count=planned`, or `?count=estimated`. The OpenAPI description of your project is served at `GET /v1/db/{project_id}/openapi.json` (with your `apikey`); it is generated from the live schema, so a table you just created appears in it. ## Uniform format `error` is always an object, never a string. Two variants, depending on the issuer - the fields `code` and `message` are common to both, and it is on `code` (never on `message`, free text) that we discriminate. ```json filename="error emitted by an Aurabase service" { "error": { "type": "auth_unauthorized", // machine type, prefixed by domain "code": "UNAUTHORIZED", // stable code "message": "Unauthorized: Invalid or revoked API key", "request_id": "dc20e246-d8e0-412c-b9d7-ce675af6edd5" } } ``` ```json filename="PostgREST error translated by the gateway" { "error": { "code": "COLUMN_NOT_FOUND", // never the raw PGRST code "message": "Column unknown_col not found in table sensors", "details": "" } } ``` > **Warning:** > > PostgREST/PostgreSQL codes (`PGRST116`, `23505`…) are **never** returned as is by the REST API: the gateway translates them into Aurabase codes (`RECORD_NOT_FOUND`, `NOT_SINGULAR`, `COLUMN_NOT_FOUND`, `NO_RELATIONSHIP`, `SCHEMA_NOT_FOUND`, `DUPLICATE_KEY`, `FOREIGN_KEY_VIOLATION`, `CHECK_VIOLATION`, `INVALID_INPUT`, `NUMERIC_OUT_OF_RANGE`, `INVALID_BODY`, `TABLE_NOT_FOUND`, `FUNCTION_NOT_FOUND`, `INSUFFICIENT_PRIVILEGE`, `STATEMENT_TIMEOUT`, `DB_POOL_TIMEOUT`, otherwise `POSTGREST_ERROR`). This variant carries no `type`; errors that can be fixed by the caller add a `hint` (a missing column or function suggests the closest name, an RLS refusal gives the `create policy` to add). The JavaScript SDK keeps `PGRST116` for `.single()` / `.maybeSingle()` on purpose, for compatibility with `supabase-js`: on raw HTTP the same situation is `NOT_SINGULAR`. | Code | Name | Description | | --- | --- | --- | | `400` | Bad Request | Malformed payload or query. `error.code` is `BAD_REQUEST`. | | `401` | Unauthorized | Missing or revoked `apikey`, or invalid JWT. `error.code` is `UNAUTHORIZED`, or `REFRESH_TOKEN_REJECTED` on `/refresh`. | | `403` | Forbidden | RLS or the authorization service refuses the operation. `error.code` is `FORBIDDEN`, `QUOTA_EXCEEDED` or `INSUFFICIENT_PRIVILEGE` (PostgREST path). | | `404` | Not Found | The resource does not exist or RLS hides it. `error.code` is `NOT_FOUND`, `RECORD_NOT_FOUND` or `TABLE_NOT_FOUND`. | | `406` | Not Acceptable | One row expected, several returned. `error.code` is `NOT_SINGULAR`. | | `409` | Conflict | Unique or foreign key violation. `error.code` is `CONFLICT`, `DUPLICATE_KEY` or `FOREIGN_KEY_VIOLATION`. An upsert (`?on_conflict=`) currently answers `409` on an existing key instead of updating the row: see [Insert and upsert rows](https://aurabase.dev/en/docs/database/insert#upsert). | | `413` | Payload Too Large | Request larger than `MAX_BODY_SIZE` (50 MB by default on the gateway). Use a multipart storage upload. | | `429` | Too Many Requests | Rate limit reached. `error.code` is `RATE_LIMITED`; `message` names the limit that was hit (IP, project or API key) and `hint` says when to retry. `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers are set, and `Retry-After` on gateway refusals. | | `500` | Internal Server Error | Server error. Give `error.request_id` to support. | | `503` | Service Unavailable | `SERVER_BUSY` when the gateway is shedding load (too many requests in flight, `Retry-After: 1`), `DB_POOL_TIMEOUT` when the project's connection pool stayed saturated, circuit breaker open, instance missing, or project hibernated (`Retry-After: 5` in that case). The breaker retries after 30 seconds. | | `504` | Gateway Timeout | Upstream timeout. `error.code` is `TIMEOUT`, or `STATEMENT_TIMEOUT` when a SQL statement ran longer than the project's 10-second statement timeout. | ## By IP at the gateway, plus limits per route - **Per project and API key**: the limit of the project's plan (Studio › Settings › Usage). A `429` names the scope that was hit, so you know whether to slow down or upgrade. - **Gateway, all routes**: per IP, `100` req/s with a burst of `1000` by default (adjustable via `RATE_LIMIT_RPS` / `RATE_LIMIT_BURST`). There is no separate tier per role. - **Auth sensitive** (`login`, `register`, `forgot-password`, `magic-link`, `email-otp/send`, `sms/send`, `refresh`, `mfa/verify-login`): 5 req/min per IP, burst 3. In addition, a quota per project: 30 connection attempts/hour per IP by default, adjustable in the project settings. In development (`AURA_ENV=development`, the local stack), the router limit is relaxed (burst 100) so you can iterate; the project quotas shown in Studio › Authentication › Configuration › Rate limiting always apply. - **Raw SQL** (`/raw`): 30 req/min, burst 10. **IA**: 10 req/min, burst 5. > **Warning:** > > Overflow → `429 Too Many Requests` with the headers `X-RateLimit-Limit` and `X-RateLimit-Remaining` (present on any response from the gateway), plus `X-RateLimit-Reset` and `Retry-After` on the refusal. ## Complete tree per service Each endpoint has its dedicated page with parameters, response codes, examples in 5 languages and live rail code. [Database](https://aurabase.dev/en/docs/api#database-rest)[Auth](https://aurabase.dev/en/docs/api#auth)[Storage](https://aurabase.dev/en/docs/api#storage)[Realtime](https://aurabase.dev/en/docs/api#realtime)[Functions](https://aurabase.dev/en/docs/api#functions) ## No SDK for your language yet There is no published Python or Dart package yet (the Studio says so too). The REST API above is complete, so a client is a few lines. The Python version uses only the standard library; it reads the same variables as the other examples and turns an API error into an exception that carries the stable `code` and the `request_id`: ```python filename="aurabase_rest.py" import json, os, urllib.error, urllib.request URL = os.environ["NEXT_PUBLIC_AURABASE_URL"] KEY = os.environ["NEXT_PUBLIC_AURABASE_ANON_KEY"] # or AURABASE_SERVICE_ROLE_KEY on a server def get(path): request = urllib.request.Request(URL + path, headers={"apikey": KEY}) try: with urllib.request.urlopen(request, timeout=15) as response: return json.load(response) except urllib.error.HTTPError as e: error = json.load(e)["error"] raise RuntimeError(f'{error["code"]}: {error["message"]} (request_id {error.get("request_id")})') print(get("/v1/db/todos?limit=2")) ``` The Dart version (Flutter or server) needs no package either; run it with `dart run aurabase_rest.dart`: ```dart filename="aurabase_rest.dart" import 'dart:convert'; import 'dart:io'; final url = Platform.environment['NEXT_PUBLIC_AURABASE_URL']!; final key = Platform.environment['NEXT_PUBLIC_AURABASE_ANON_KEY']!; // or AURABASE_SERVICE_ROLE_KEY on a server Future get(String path) async { final client = HttpClient(); try { final request = await client.getUrl(Uri.parse(url + path)); request.headers.set('apikey', key); final response = await request.close(); final body = jsonDecode(await response.transform(utf8.decoder).join()); if (response.statusCode >= 400) { final error = body['error']; throw Exception('${error['code']}: ${error['message']} (request_id ${error['request_id']})'); } return body; } finally { client.close(); } } Future main() async { print(await get('/v1/db/todos?limit=2')); } ``` ## To go further - [Complete endpoints](https://aurabase.dev/en/docs/api): Tree /docs/api/ Stripe-style. - [JavaScript SDK](https://aurabase.dev/en/docs/sdk-js): Alternative to raw REST. - [Security](https://aurabase.dev/en/docs/security): RLS, JWT claims, service_role_key. - [Compliance](https://aurabase.dev/en/docs/compliance): SOC2, GDPR, HIPAA, data residency. --- ### REST API reference Source: https://aurabase.dev/en/docs/api.md # REST API reference > Complete Aurabase REST surface: Database, Auth, Storage, Realtime, Functions. Every endpoint documented with parameters, headers, response codes, request/response examples in 5 languages. | Element | Value | | --- | --- | | Base URL | `{NEXT_PUBLIC_AURABASE_URL}/v1//{project_id}` | | Authentication | `apikey: (+ Bearer )` | | Content-Type | `application/json` | ## Database · REST - [Overview](https://aurabase.dev/en/docs/api) - `GET` [Rows · select](https://aurabase.dev/en/docs/api/database/select) - `POST` [Rows · insert](https://aurabase.dev/en/docs/api/database/insert) - `PATCH` [Rows · update](https://aurabase.dev/en/docs/api/database/update) - `DELETE` [Rows · delete](https://aurabase.dev/en/docs/api/database/delete) - `POST` [RPC](https://aurabase.dev/en/docs/api/database/rpc) ## Auth - `POST` [Sign up](https://aurabase.dev/en/docs/api/auth/signup) - `POST` [Sign in](https://aurabase.dev/en/docs/api/auth/signin) - `POST` [Refresh](https://aurabase.dev/en/docs/api/auth/refresh) - `GET` [Sessions](https://aurabase.dev/en/docs/api/auth/sessions) - `POST` [MFA enroll](https://aurabase.dev/en/docs/api/auth/mfa-enroll) ## Storage - `POST` [Upload object](https://aurabase.dev/en/docs/api/storage/upload) - `GET` [Signed URL](https://aurabase.dev/en/docs/api/storage/signed-url) - `GET` [Download](https://aurabase.dev/en/docs/api/storage/download) ## Realtime - `GET` [Channel subscribe](https://aurabase.dev/en/docs/api/realtime/channel) - `POST` [Broadcast](https://aurabase.dev/en/docs/api/realtime/broadcast) ## Functions - `POST` [Invoke](https://aurabase.dev/en/docs/api/functions/invoke) ## AI Gateway - `POST` [Chat completion](https://aurabase.dev/en/docs/api/ai/chat) - `POST` [Ephemeral session](https://aurabase.dev/en/docs/api/ai/session) - `POST` [Embeddings](https://aurabase.dev/en/docs/api/ai/embed) - `GET` [Semantic search](https://aurabase.dev/en/docs/api/ai/search) - `POST` [RAG query & ingest](https://aurabase.dev/en/docs/api/ai/rag) - `POST` [NL to SQL](https://aurabase.dev/en/docs/api/ai/nl2sql) --- ### CLI aura — Full reference Source: https://aurabase.dev/en/docs/cli.md # CLI aura — Full reference > The official aura binary allows you to control the entire Aurabase platform: local dev, Kubernetes, SQL migrations, stored functions, Edge Functions WASM, RLS, Storage and Auth. ## A standalone binary, available everywhere The CLI is a standalone Rust binary. It is installed today by NPM on **macOS Apple Silicon**, and by compilation from sources everywhere else. The precompiled binary packages for Linux, macOS Intel and Windows are not yet released: `npm install -g @aurabase/cli` fails there, this is not an error on your part. ```bash filename="terminal" # 1. NPM — macOS Apple Silicon only as of today npm install -g @aurabase/cli aura --help # 2. From source — all platforms (Rust 1.7x+) git clone https://github.com/Aurabase-cloud/Aurabase.git cargo install --path Aurabase/aura-cli # install the `aurabase` binary in ~/.cargo/bin aurabase --help ``` ## Authenticate the CLI You can log in with your console account or using a Personal Access Token for your CI/CD pipelines: ```bash filename="terminal" # Interactive login (opens browser) aura login # Non-interactive connection (email / password) aura login --email dev@example.com --password "secret" # Connection via Personal Access Token (ideal for GitHub Actions / GitLab CI) aura login --token aura_pat_9a8b7c6d5e4f... # Check account and active project aura whoami ``` ## Exhaustive reference per module Find all the commands and subcommands supported by the `aura` binary: ### Project setup & management Initialization, connection and diagnosis of the project - `aura init` — Initializes a new Aurabase project (structure, config, docker) - `aura login [--email ] [--password ] [--token ]` — Logs in to the console account or with a Personal Access Token - `aura register [--email ] [--password ]` — Creates a new Aurabase Console developer account - `aura logout` — Disconnects the active local session - `aura whoami` — Shows the logged in user, their organization, and the active project - `aura link --project-id ` — Links the current directory to an existing cloud project - `aura status` — Shows project status, connection and service status - `aura doctor` — Diagnoses the local environment (Docker, ports, system tools) ### Local development Local stack management (Kubernetes / k3d) and logs - `aura start` — Starts all Aurabase local microservices on k3d - `aura stop` — Stops k3d cluster and local services - `aura restart` — Restarts local services - `aura dev` — Continuous dev mode: monitors migrations and synchronizes types - `aura studio` — Opens the local Studio interface in your browser (localhost:3000) - `aura logs [-s ] [--since 1h] [--tail 100]` — Displays logs unified or filtered by service (aura-auth, aura-db, gateway...) - `aura connect` — Opens an interactive psql terminal on the project's direct PostgreSQL endpoint (psql asks for the password issued by `aura db connection --new-password`) ### Organizations & cloud projects Multi-tenant management of organizations and projects - `aura orgs list [--json]` — Lists the organizations of which you are a member - `aura orgs create --name --slug ` — Creates a new Cloud organization - `aura orgs use ` — Sets the default organization for orders - `aura projects list [--org ] [--json]` — Lists an organization's projects - `aura projects create [--engine postgres|mongodb] [--org ]` — Provisions a new project - `aura projects delete ` — Permanently deletes a project and its data - `aura projects api-keys [--project-id ]` — Shows the project's API keys (anon, service\_role) - `aura projects rename ` — Renames an existing project - `aura projects retry ` — Re-runs the provisioning of a project in `error` and prints its URL and keys once it is ready - `aura projects graphql-enable [--wait]` — Enables the GraphQL extension (pg\_graphql) on the project - `aura projects graphql-config [--introspection on|off] [--max-rows N] [--inflect-names on|off] [--wait]` — Shows or changes the pg\_graphql settings (without a flag, prints the settings in effect) ### Database branches (aura branch) A branch is a new project cloned from a PostgreSQL project, with its own URL and keys, deleted when its TTL ends. See [database branches](https://aurabase.dev/en/docs/deployment#branches) for the limits and what is cloned. - `aura branch create [--from ] [--org ] [--ttl 72h|3d|2w] [--no-data] [--no-wait] [--json] [--timeout ]` — Creates a branch of the linked project (or of `--from`), waits until it is ready, then prints its URL and its API keys once. `--ttl` goes from 1h to 30d (default 72h). `--no-data` copies the schema only - `aura branch list [--from ] [--all] [--json]` — Lists the branches of a project, or of the whole organization with `--all`; failed branches stay listed for 24 hours with their reason - `aura branch delete [--from ] [--force]` — Deletes a branch and its database ### Database & migrations (aura db) Schema management, synchronization, push/pull and SQL queries - `aura db push` — Applies pending local SQL migrations (+ cloud sync if linked) - `aura db pull` — Retrieves remote schema and updates local schema - `aura db diff [--name ]` — Compares remote schema with local and generates SQL migration - `aura db status [--json]` — Shows detailed status of applied and pending migrations - `aura db watch` — Monitors schema changes and syncs live - `aura db reset [--force]` — Purge and recreate local database from scratch (asks for confirmation; `--force` for scripts) - `aura db seed` — Runs seed.sql script to load test data - `aura db generate [--lang ts|rust]` — Generates TypeScript (default) or Rust Database type definitions - `aura db extensions list [--json]` / `aura db extensions enable ` — Lists the installed extensions, or enables an allowed one - `aura db inspect [--json]` — Index usage (unused ones flagged), table sizes and dead rows, blocking locks - `aura db slow-queries [--limit ] [--json]` — Lists the slowest SQL queries via `pg_stat_statements` - `aura db stats [--json]` — Shows connection stats and database disk usage - `aura db connection [--new-password] [--yes] [--json]` — Direct PostgreSQL access (psql, Prisma, Drizzle, `pg_dump`): host, port, database and role; with `--new-password`, issues a password (shown once, never stored in clear, revokes the previous one) and prints the full connection string - `aura db raw "" [--params ] [--dry-run] [--read-only] [--json]` — Runs a direct SQL query with simulation and read-only options - `aura db migration new ` — Creates a new timestamped SQL migration file - `aura db migration list [--json]` — Lists all project migrations and their status - `aura db migration down [n]` — Cancels the last n migrations applied (default: 1) - `aura db migration repair [--applied|--reverted]` — Manually marks a migration as applied or canceled in the project's migration history (the same history `aura db status` and `migration list` read) ### RLS tables & policies (aura db table / policy) Declarative creation, RLS, real-time CDC and permissions - `aura db table list [--json]` — Lists the public schema tables with their columns and types - `aura db table create ""` — Creates a table (ex: "title:text,tags:text\[\],embedding:vector(1536)") - `aura db table drop [-f]` — Deletes a table and its constraints - `aura db table rls ` — Enables or disables Row Level Security protection on a table - `aura db table realtime ` — Enables or disables Realtime CDC publishing on a table - `aura db policy list [--table ] [--all] [--json]` — Lists RLS security policies defined on tables (`--all` includes internal storage rules) - `aura db policy add
[--using-expr ] [--check-expr ]` — Creates a new RLS policy (SELECT, INSERT, UPDATE, DELETE or ALL) - `aura db policy update
[--using-expr ] [--check-expr ]` — Modifies the USING / WITH CHECK expressions of a rule without breaking - `aura db policy delete
[-f]` — Deletes an RLS security rule ### Postgres SQL functions & triggers (aura db function / trigger) PL/pgSQL stored procedures and table triggers - `aura db function list [--json]` — Lists Postgres functions in the schema (name, arguments, security, rights) - `aura db function create [--body |--body-file ] [--returns ] [--language plpgsql|sql] [--args ] [--security invoker|definer] [--grant-execute-to ]` — Creates or replaces a stored SQL function with strict access control - `aura db function drop [-f]` — Delete a Postgres SQL function - `aura db trigger list
[--json]` — Lists all triggers in a table - `aura db trigger create
--function [--timing before|after|instead_of] --events insert,update [--for-each row|statement]` — Binds a trigger function to table events - `aura db trigger drop
[-f]` — Delete a trigger on a table ### Backups & API keys (aura db backup / api-keys) Snapshots, restoration and management of access tokens - `aura db backup list [--json]` — Lists manual and automated backups of the database - `aura db backup create [--label
`, each filter needs a `table`. | | `config.postgres_changes[].filter` | `string` | no | Syntax `column=op.value`. Operators: `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in`, `like`, optionally prefixed with `not.`. | | `config.broadcast` | `object` | no | `self_broadcast` (receive its own broadcasts, default false) and `ack` (acknowledgement of receipt, default false). | | `config.presence` | `object` | no | `key` — presence key allowing you to follow the same user on several tabs. | | `config.private` | `boolean` | no | Private channel: an authorization check is made before joining. | ## Protocol messages > **Note:** > > Client → server: `subscribe`, `unsubscribe`, `broadcast`, `presence_update`, `ping`, `access_token`. Server → client: `subscribed`, `event`, `pong`, `error`, `token_refreshed`, `broadcast_ack`, `presence_state`, `channel_recovered`. ## HSE Alternative > **Tip:** > > `GET /v1/realtime/sse` provides unidirectional flow. Unlike WebSocket, **requires an API key** and infers the project from `?project_id=` or the prefix of `?channel=`. ## RLS > **Note:** > > CDC events inherit RLS policies: a client is only notified of changes on rows it can read. The JWT is re-validated periodically (every 5 minutes at most) — send `access_token` to renew it without breaking the connection. --- ### Send a broadcast Source: https://aurabase.dev/en/docs/api/realtime/broadcast.md # Send a broadcast > Sends an event to all clients subscribed to a channel. Independent of Postgres — fan-out via NATS, then best-effort persistence. **Node (client)** ```typescript tab="Node (client)" filename="broadcast.ts" await aura.channel('chat:general').send({ type: 'broadcast', event: 'typing', payload: { userId }, }) ``` **cURL (server)** ```bash tab="cURL (server)" filename="curl.sh" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/realtime/$PROJECT_ID/broadcast" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"channel":"$PROJECT_ID:chat:general","payload":{"event":"typing","userId":"u_1"}}' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" // No recipient count: fan-out is asynchronous { "data": null, "meta": null } ``` **Response 403** ```json response="403" tone="error" filename="403.json" { "error": { "type": "auth_forbidden", "code": "FORBIDDEN", "message": "Accès interdit : Le canal n'appartient pas à ce projet", "request_id": "…" } } ``` **Response 429** ```json response="429" tone="warn" filename="429.json" { "error": { "code": "RATE_LIMITED", "message": "Payload trop volumineux (… octets, max …)", … } } ``` ## Headers | Header | Required | Value | | --- | --- | --- | | `apikey` | yes | `Project API key` | | `Authorization` | yes | `Bearer . Its project_id must match the URL, otherwise 403` | | `Content-Type` | yes | `application/json` | ## Bodysuit | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `channel` | `string` | yes | Target channel, necessarily prefixed with the project: `{project_id}:{topic}`. A channel that does not belong to the project is refused in 403. | | `payload` | `object` | yes | Event body, serializable JSON. Its size is limited by the configuration of the project. | ## Body shape > **Warning:** > > The body has only two fields: `channel` and `payload`. There is no `event` field at the top level — if your application wants one, put it in `payload`. ## Access control and limits > **Warning:** > > Authorization is based on the JWT: its `project_id` must match that of the URL, and the channel must have this same prefix. There is no policy table `allow_broadcast`. Three counters per project can respond `429`: payload size, number of events, byte volume. --- ### Invoke an edge function Source: https://aurabase.dev/en/docs/api/functions/invoke.md # Invoke an edge function > Triggers a deployed handler. The body of the request is NOT transmitted as is: it describes the request to be replayed (method, path, headers, body). **Node** ```typescript tab="Node" filename="invoke.ts" const { data } = await aura.functions.invoke('ocr', { body: { fileUrl }, }) ``` **cURL** ```bash tab="cURL" filename="curl.sh" curl -X POST "$NEXT_PUBLIC_AURABASE_URL/v1/functions/$PROJECT_ID/ocr/invoke" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"body":{"fileUrl":"https://…"}}' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" // Default mode: function output is wrapped { "data": { "status": 200, "headers": { … }, "body": { "text": "Lorem ipsum…" }, "logs": ["…"], "duration_ms": 42 }, "meta": null } ``` **Response 403** ```json response="403" tone="warn" filename="403.json" // Summon quota exceeded — 403, NOT 429 { "error": { "type": "quota_exceeded", "code": "QUOTA_EXCEEDED", "message": "Quota dépassé : …", … } } ``` **Response 503** ```json response="503" tone="error" filename="503.json" // PLATFORM failure: edge-runtime unreachable. The function did NOT work, // a retry is safe. The SDK makes this a FunctionsRelayError (not HttpError). { "error": { "type": "service_unavailable", "code": "SERVICE_UNAVAILABLE", … } } ``` **Response 504** ```json response="504" tone="error" filename="504.json" // Budget exceeded: the function was LAUNCHED and was able to produce its effects // on board — only the answer is missing. Replaying is not trivial. { "error": { "type": "request_timeout", "code": "TIMEOUT", "message": "Timeout", … } } ``` ## Headers | Header | Required | Value | | --- | --- | --- | | `apikey` | yes | `Project API key` | | `Authorization` | no | `Bearer ` | | `Content-Type` | yes | `application/json` | | `x-aurabase-invoke-mode` | no | `raw returns the function's raw response (real status, content-type and bytes) instead of the { data, meta } envelope` | ## Bodysuit | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `method` | `string` | no | HTTP method seen by the handler. Default `POST`. | | `path` | `string` | no | Path seen by the handler. Default `/`. | | `headers` | `object` | no | Headers passed to the handler (string → string pairs). | | `body` | `any` | no | Payload passed to the handler. | > **Note:** > > These four fields describe the request that **your** function receives. On the Deno runtime, `req.method`, `new URL(req.url).pathname`, `req.headers` and `await req.json()` render exactly what you sent — `body` is the application body, not the shell. `GET` and `HEAD` leave without a body (Fetch spec). ## Idempotence > **Warning:** > > `Idempotency-Key` is **not** read on this route: no deduplication is done, two identical invocations are executed twice. If you need idempotence, handle it in the function code. ## Execution Limits > **Note:** > > The timeout is set **by function**: default 30 s, hard ceiling 300 s (5 min) — it does not depend on the plan. Memory ranges from 16 to 1024 MB. Invocations are limited to their own throughput profile, and each call consumes the project's `functions.invocations` quota. ## Asynchronous execution > **Tip:** > > For long work, prefer the job queue: `POST /v1/functions/{project_id}/jobs`, followed by `GET …/jobs/{job_id}`, with restart (`…/retry`) and scrap queue (`…/jobs/dlq`). --- ### Chat completion & streaming Source: https://aurabase.dev/en/docs/api/ai/chat.md # Chat completion & streaming > Proxies chat completions to OpenAI, Anthropic Claude, and Google Gemini with prompt injection defenses and automated fallback. **TypeScript** ```typescript tab="TypeScript" filename="chat.ts" // Synchronous chat const { data: res } = await aura.ai.chat([ { role: 'user', content: 'Explain EU data sovereignty under GDPR.' } ], { provider: 'anthropic', model: 'claude-3-5-sonnet', temperature: 0.2 }) // Real-time token streaming (SSE) for await (const chunk of aura.ai.chatStream([ { role: 'user', content: 'Draft a Data Processing Agreement clause.' } ])) { process.stdout.write(chunk.delta) } ``` **cURL** ```bash tab="cURL" filename="chat.sh" curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/chat" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -d '{ "messages": [ { "role": "user", "content": "Explain EU cloud sovereignty." } ], "system": "Answer accurately in 2 sentences.", "provider": "anthropic", "model": "claude-3-5-sonnet", "temperature": 0.2, "max_tokens": 1024 }' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" { "data": { "content": "European cloud sovereignty guarantees that personal data is processed strictly within EU jurisdiction under GDPR...", "model": "claude-3-5-sonnet", "provider": "anthropic", "fallback_used": false, "input_tokens": 28, "output_tokens": 54, "reasoning_tokens": null, "finish_reason": "stop" } } ``` **Response 400** ```json response="400" tone="error" filename="400.json" { "error": { "type": "bad_request", "code": "BAD_REQUEST", "message": "Message `system` interdit en position 0 : utilisez le champ `system` de la requête." } } ``` **Response 429** ```json response="429" tone="warn" filename="429.json" { "error": { "type": "rate_limited", "code": "TOO_MANY_REQUESTS", "message": "Limite de débit dépassée pour ce projet." } } ``` ## Headers | Header | Required | Value | | --- | --- | --- | | `apikey` | yes | Project public anon key or private service_role key | | `Authorization` | no | `Bearer ` | | `Content-Type` | yes | `application/json` | | `Accept` | no | `text/event-stream` (when calling `/chat/stream`) | ## Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `messages` | `ChatMessage[]` | yes | Array of conversation turns. Only roles `user` and `assistant` are permitted. | | `system` | `string` | no | System prompt instructing the model. Composed automatically with project-level prompt. | | `provider` | `string` | no | Target LLM provider (`anthropic`, `openai`, `google`). Defaults to project setting. | | `model` | `string` | no | Provider model identifier (e.g., `claude-3-5-sonnet`, `gpt-4o`). | | `temperature` | `number` | no | Sampling temperature (0.0 to 1.0). | | `max_tokens` | `number` | no | Maximum output tokens generated. | ## Prompt injection protection > **Note:** > > System messages are strictly forbidden inside the `messages` array (`validate_roles`). They must be passed via the `system` parameter. The server concatenates the project's administrator-configured `system_prompt` ahead of any user-supplied prompt, guaranteeing that platform policies cannot be overridden by user requests. --- ### Ephemeral AI Sessions Source: https://aurabase.dev/en/docs/api/ai/session.md # Ephemeral AI Sessions > Eliminates API key exposure on mobile and SPA frontends by issuing bounded capability tokens. **TypeScript** ```typescript tab="TypeScript" filename="session.ts" // 1. Backend / Edge Function mints ephemeral session ticket const session = await aura.ai.session() // 2. Browser client safely chats without exposing project secrets const { content, budget_remaining } = await session.chat([ { role: 'user', content: 'Summarize my account activity.' } ]) console.log('Remaining budget:', budget_remaining) ``` **cURL (Mint)** ```bash tab="cURL (Mint)" filename="mint.sh" # 1. Server mints session ticket curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/session" \ -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` **cURL (Invoke)** ```bash tab="cURL (Invoke)" filename="chat_session.sh" # 2. Frontend invokes chat with ticket ONLY (no apikey allowed) curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/session/chat" \ -H "Authorization: Bearer aura_sess_eyJhbGciOi..." \ -H "Content-Type: application/json" \ -d '{ "messages": [{ "role": "user", "content": "Hello AI" }] }' ``` **Response 200** ```json response="200" tone="ok" filename="mint_200.json" { "data": { "ticket": "aura_sess_eyJhbGciOi...", "expires_at": 1730410300, "budget_remaining": 50000 } } ``` **Response 429** ```json response="429" tone="warn" filename="429.json" { "error": { "type": "rate_limited", "code": "session_budget_exceeded", "message": "Le budget de jetons alloué à cette session est épuisé." } } ``` ## Mint headers and body | Header | Required | Value | | --- | --- | --- | | `apikey` | yes | Service role key or authenticated user JWT | | `Content-Type` | yes | `application/json` | The minting endpoint checks and reserves token budgets against the project's real monthly quota and caches the resolved provider pipeline for 300 seconds. ## Strict capability authentication > **Warning:** > > Endpoints `/session/chat`, `/session/chat/stream`, and `/session/embed` strictly mandate `Authorization: Bearer `. Supplying standard `apikey` headers is rejected to prevent confusion between permanent keys and ephemeral session capabilities. --- ### Vector Embeddings Source: https://aurabase.dev/en/docs/api/ai/embed.md # Vector Embeddings > Computes text embeddings and stores them in dimension-isolated PostgreSQL columns (768, 1536, 3072). **TypeScript** ```typescript tab="TypeScript" filename="embed.ts" const { data, error } = await aura.ai.embed({ text: 'Sovereign cloud infrastructure hosted in Europe.', namespace: 'legal-docs', metadata: { section: 'compliance', author: 'Team' }, }) console.log('Indexed document ID:', data?.id, 'Dimensions:', data?.dimensions) ``` **cURL** ```bash tab="cURL" filename="embed.sh" curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/embed" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "Sovereign cloud infrastructure hosted in Europe.", "namespace": "legal-docs", "metadata": { "section": "compliance" } }' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" { "data": { "id": "c3d4e5f6-7890-4abc-def1-234567890abc", "dimensions": 1536 } } ``` **Response 400** ```json response="400" tone="error" filename="400.json" { "error": { "type": "bad_request", "code": "BAD_REQUEST", "message": "Dimension d'embedding non supportée : 1024. Dimensions acceptées : [768, 1536, 3072]." } } ``` ## Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `text` | `string` | yes | Text to embed and persist. | | `namespace` | `string` | yes | Target partition namespace isolating document spaces. | | `metadata` | `object` | no | Arbitrary JSON metadata attached to the vector record. | ## Multi-Dimension Storage > **Note:** > > Aurabase provides multi-dimension vector routing with dedicated columns: > - `768`: Gemini `text-embedding-004` (stored in `embedding_768`). > - `1536`: OpenAI `text-embedding-3-small` (stored in `embedding_1536`). > - `3072`: OpenAI `text-embedding-3-large` (stored in `embedding_3072` using `halfvec` for HNSW indexing). > > Vectors are tagged with the active `embedding_model` to prevent cross-model semantic drift. --- ### Semantic Vector Search Source: https://aurabase.dev/en/docs/api/ai/search.md # Semantic Vector Search > Performs high-performance semantic similarity queries across vector namespaces with tunable thresholds and top-k limits. **TypeScript** ```typescript tab="TypeScript" filename="search.ts" const { data: matches } = await aura.ai.semanticSearch( 'What are the encryption requirements?', 'legal-docs', { threshold: 0.8, top_k: 5 } ) for (const match of matches ?? []) { console.log(`[${match.similarity.toFixed(2)}] ${match.content}`) } ``` **cURL** ```bash tab="cURL" filename="search.sh" curl -G "https://.aurabase.dev/v1/ai/$PROJECT_ID/search" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ --data-urlencode "query=What are the encryption requirements?" \ --data-urlencode "namespace=legal-docs" \ --data-urlencode "threshold=0.8" \ --data-urlencode "top_k=5" ``` **Response 200** ```json response="200" tone="ok" filename="200.json" { "data": [ { "id": "c3d4e5f6-7890-4abc-def1-234567890abc", "content": "All data at rest must be encrypted using AES-256-GCM or native Vault Transit KEKs...", "metadata": { "section": "compliance" }, "similarity": 0.895 } ] } ``` ## Query Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `query` | `string` | yes | Search phrase or natural language query. | | `namespace` | `string` | yes | Target partition namespace to query against. | | `top_k` | `number` | no | Maximum documents returned (default `5`, max `100`). | | `threshold` | `number` | no | Minimum cosine similarity threshold from `0.0` to `1.0` (default `0.7`). | ## Dynamic HNSW Tuning > **Note:** > > The search endpoint dynamically sets PostgreSQL's `hnsw.ef_search` variable based on requested `top_k` (`(top_k * 4).max(64)`), guaranteeing high recall even when filtering post-index candidates. --- ### RAG Query & Document Ingestion Source: https://aurabase.dev/en/docs/api/ai/rag.md # RAG Query & Document Ingestion > Ingest large documents (up to 5 MB) and query context-grounded LLM responses. **TypeScript** ```typescript tab="TypeScript" filename="rag.ts" // 1. Ingest large text document into namespace await aura.ai.ragIngest({ content: 'Full text of enterprise security guide...', namespace: 'security-kb', }) // 2. Query grounded RAG response const { data: answer } = await aura.ai.rag({ question: 'How are database backups encrypted?', namespace: 'security-kb', system: 'Answer using only the provided context.', }) console.log('Answer:', answer?.answer) console.log('Sources cited:', answer?.sources) ``` **cURL (Query)** ```bash tab="cURL (Query)" filename="rag_query.sh" curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/rag/query" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -d '{ "question": "How are database backups encrypted?", "namespace": "security-kb" }' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" { "data": { "answer": "Database backups are encrypted at rest using AES-256-GCM via Vault Transit KEK...", "sources": [ { "id": "b1a2c3d4-...", "content": "All automated WAL and snapshot backups utilize AES-256-GCM keys...", "similarity": 0.912 } ], "model": "claude-3-5-sonnet", "provider": "anthropic" } } ``` ## Ingestion parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `content` | `string` | yes | Document content (up to 5 MB payload size). The service splits it into chunks itself: the chunk size is not a request parameter. | | `namespace` | `string` | yes | Target partition namespace. | | `metadata` | `object` | no | Arbitrary JSON metadata attached to each chunk. | ## Namespace lifecycle operations - `GET /v1/ai/{project_id}/rag/namespaces`: Lists all active RAG namespaces. - `DELETE /v1/ai/{project_id}/rag/{namespace}`: Deletes all chunks and vector entries in the namespace. - `POST /v1/ai/{project_id}/rag/{namespace}/reindex`: Recomputes embeddings for all chunks in the namespace when switching embedding models. --- ### Natural Language to SQL Source: https://aurabase.dev/en/docs/api/ai/nl2sql.md # Natural Language to SQL > Converts natural language into secure, read-only PostgreSQL queries checked by an Abstract Syntax Tree (AST) parser. **TypeScript** ```typescript tab="TypeScript" filename="nl2sql.ts" const { data, error } = await aura.ai.nl2sql( 'What are the 10 most recent user registrations?', { dialect: 'postgresql', limit: 10 } ) console.log('Safe SQL Query:', data?.sql) console.log('Injected Limit:', data?.limit, 'Confidence:', data?.confidence) ``` **cURL** ```bash tab="cURL" filename="nl2sql.sh" curl -X POST "https://.aurabase.dev/v1/ai/$PROJECT_ID/nl2sql" \ -H "apikey: $NEXT_PUBLIC_AURABASE_ANON_KEY" \ -H "Content-Type: application/json" \ -d '{ "question": "What are the 10 most recent user registrations?", "dialect": "postgresql", "limit": 10 }' ``` **Response 200** ```json response="200" tone="ok" filename="200.json" { "data": { "sql": "SELECT id, email, created_at FROM users ORDER BY created_at DESC LIMIT 10;", "explanation": "Retrieves the latest 10 users ordered by creation timestamp.", "confidence": 0.96, "limit_injected": false, "limit": 10 } } ``` **Response 400** ```json response="400" tone="error" filename="400.json" { "error": { "type": "bad_request", "code": "BAD_REQUEST", "message": "Requête mutante interdite : seules les requêtes SELECT en lecture seule sont autorisées." } } ``` ## Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `question` | `string` | yes | Natural language question about the project's data. | | `dialect` | `string` | no | Database dialect. Accepts `'postgresql'` or `'postgres'`. | | `examples` | `object[]` | no | Optional few-shot examples `[{ question, sql }]` guiding query generation. | | `limit` | `number` | no | Maximum row limit injected if omitted by model (default `100`, max `1000`). | ## AST mutation guards > **Note:** > > The server parses the generated SQL with an Abstract Syntax Tree (AST) engine prior to returning it: > - Any non-SELECT mutation statement (`INSERT`, `UPDATE`, `DELETE`, `DROP`, `ALTER`, `TRUNCATE`) is rejected immediately with `HTTP 400`. > - System catalog tables (`pg_catalog`, `information_schema`) are strictly disallowed. > - If the model omits a `LIMIT` clause, the server injects `LIMIT 100` (capped at 1000) and marks `limit_injected: true`.