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 <project-id>. -
The example schema, installed with the service role key of the project:
export AURABASE_SERVICE_ROLE_KEY=aura_sk_… aura db seed --example docsIt creates
profiles,orgs,org_members,posts,todos, the viewopen_todosand the functiontodo_count(p_user uuid). See Example schema.
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#
aura db raw "select title, done from todos order by title" 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 |
|---|---|
"<sql>" | The SQL to run. - reads it from standard input. |
-f, --file <FILE> | Read the SQL from a file. |
-p, --params <VALUE>... | 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 <uuid> | 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:
aura db raw --json "select title, done from todos where user_id = \$1::uuid order by title" -p 00000000-0000-4000-8000-0000000000b2[
{
"done": false,
"title": "Invite a teammate"
}
]Read the SQL from a file, or from standard input:
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 title
───────────────────────────────
Add a row level security policy
Create a table
Invite a teammate
ℹ 3 row(s).echo "select count(*) as todos from todos" | aura db raw - 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:
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" ℹ 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.
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" ℹ 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.
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]}'{"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.
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)[ { title: 'Read the quickstart' } ] null
[ { todos: 4 } ] null
null 400 BAD_REQUESTdb.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:
aura db raw --json "select count(*)::int as todos, (count(*) filter (where done))::int as done from todos"[
{
"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 <name>. |
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_<other-id>.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.
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:
rm open-todos.sqlSee also#
- Connect to your database
psql, ORMs and the direct connection, which the /raw check does not apply to.
- Row-level security
Policies that --as anon and --as authenticated let you test.
- Database CLI reference
Every option of aura db raw and the other aura db commands.
- Example schema
The tables used in the examples of this page.