コンテンツへスキップ
オーラベースのロゴ
オーラベース

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.

ハウツーガイド10 分 読み取りレベル 中間

このページはまだお使いの言語では利用できません。英語で表示されます。

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 <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 docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See 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).

The examples create migrations named wf_mig_… and the tables wf_mig_notes and wf_mig_labels; the 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#

StepWhat happens
Filesaurabase/migrations/*.sql, applied in the order of their names. aura db migration new <name> prefixes the name with the current UTC time (YYYYMMDDHHMMSS_<name>.sql), so the order is the order of creation. Files ending in .down.sql are never applied by push (Roll back and repair migrations).
Sendingaura 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.
RunningThe 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), and views get security_invoker = true.
Time limitsBy default a statement waits at most 5 seconds for a lock and runs at most 5 minutes.
LedgerAfter 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 failurepush 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#

aura db migration new wf_mig_notes | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
✔ 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:

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#

aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
» 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.

aura db push 2>&1 | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
» 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.

aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
aura db migration list --json | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
» 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).

RouteBodyAnswer
GET /v1/db/{project_id}/migrationsThe 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 fieldapplied: 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:

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_"))'
{"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:

StatementIn a migration
create table, alter table, drop table, create index, create view, create policy, grant, revokeAccepted
create function … language sql or plpgsql, with a dollar-quoted bodyAccepted, security invoker only
create trigger … execute function …Accepted
begin, commit, rollback, savepointRefused: Transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT) is not allowed in migrations
security definerRefused: create such a function with aura db function create (Database functions)
do $$ … $$ blocksRefused: Anonymous blocks (DO) are not allowed in raw queries
create extensionRefused: enable the extension with aura db extensions enable <name>
set search_path, set roleRefused
create index concurrentlyFails 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_catalogRefused
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)"
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:

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
» 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:

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_/'
» 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.

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.

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(", "))'
    ℹ 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:

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_"))'
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 <file> --applied (Roll back and repair migrations).

Revert the edit of the example before going on:

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'
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):

StepMigration or actionThe application
1. ExpandAdd the new column, nullable or with a default.Still reads and writes the old column.
2. BackfillCopy the values (update … set new = old where new is null), in batches on a large table.Writes both columns.
3. SwitchReads and writes the new column only.
4. ContractDrop 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 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):

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.

Result#

aura db status | sed -E 's/[0-9]{14}_/YYYYMMDDHHMMSS_/'
aura db table list | grep -A1 wf_mig_
» 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#

MessageCauseFix
Migration '<file>' 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 existsThe 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.Mark the file as applied: aura db migration repair <file> --applied.
(already applied) after editing a fileThe 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 momentA lock was not obtained within 5 seconds.Push again later.
Transaction control (BEGIN/COMMIT/ROLLBACK/SAVEPOINT) is not allowed in migrationsThe file has begin or commit.Remove them: the file already runs in a transaction.
Empty migration SQL: nothing to applyPOST …/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.

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
  ℹ 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 <name>.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する