db
Run SQL files and typed seeds against the local stack or another database, and diff the schema into a migration.
query
pnpm better-supabase db query supabase/tests/seed.sql supabase/tests/more.sql
pnpm better-supabase db query --single-transaction a.sql b.sqldb query runs each file as one script, in the order you pass them. A file
can hold many statements, so a data migration or a fixture file runs as it
would in psql -f, without a psql install.
| Flag | Effect |
|---|---|
--single-transaction | Wraps every file in one transaction, so a failure keeps none. |
--stack <name> | Uses the database of supabase/stacks/<name>/config.toml (default $BETTER_SUPABASE_STACK). |
--db-url-stdin | Reads the connection string from stdin, so it never reaches argv. |
Without --db-url-stdin, the command connects through $DATABASE_URL,
$SUPABASE_DB_URL, $POSTGRES_URL_NON_POOLING, $POSTGRES_URL, or the local stack. Against a database that is not local,
an agent needs the user's consent first. A failing file stops the run, and
the error names it. The JSON envelope lists the files that ran in data.ran.
Side effects: Writes to the database.
diff
pnpm better-supabase db diff -f add_invoices
pnpm better-supabase db diff --in-stackdb diff turns the declarative schema files into a migration. On a local
database under pg-delta, it plans with pg-delta's library: it creates a shadow
database in the same Postgres as the stack, loads the files into it, and plans
the changes from the stack to the shadow. The shadow is dropped afterwards,
also when a step fails. The stack has to have applied every migration first
(supabase migration up), or the diff would repeat them.
Under migra, or on a database that isn't local, db diff runs the Supabase
CLI's command for the workflow (supabase db diff). Both engines stay
supported. A feature only pg-delta has (--in-stack, the baseline of db squash) stops under migra with one message that names it and the two config
lines that switch: experimental.pgdelta.enabled = true and removing
db.migrations.schema_paths. Doctor rule BS713 lists
what a migra diff drops from your files. When that command can't
start its shadow database, usually because every System V shared memory
segment is in use (macOS allows 32, and each running stack holds one), db diff plans with the library on the stack you already run.
The plan is checked before anything is written:
- A table or column that looks renamed is never guessed. Record the rename in
a migration as
-- bsb: rename old_name -> new_nameand the next diff plans a rename that keeps the data. Without it, the diff plans a drop and a create and tells you which rename it suspects. - An action that destroys data (dropping a table or column, narrowing a
column type) stops the diff with a
check_failederror and writes nothing. Run it again with--allow-data-lossonce you have read the list. - Under pg-delta the diff runs with strict coverage. When the schema files
create an object pg-delta cannot manage (a kind it does not model, an
unmodeled object the target lacks, a security label it cannot place, or
supabase_vaultin use), the diff stops with acheck_failederror that lists each object and writes nothing. Deliver the object in a migration or a_custom/file, or run again with--no-strict-coverageto leave it out. The Supabase CLI path passes--strict-coveragetosupabase db schema declarative syncfor the same reason. - With
--prove, the plan is applied to a clone of the local stack and refused unless the clone converges to the files, no table loses rows, and no undeclared action rewrites a table. Cloning briefly disconnects the stack's services, which reconnect on their own. A stack that cannot be cloned skips the proof and says why.
| Flag | Effect |
|---|---|
-f, --file | Saves the diff as supabase/migrations/<timestamp>_<name>.sql instead of printing it. |
--in-stack | Plans with the library on the running stack, without the Supabase CLI. |
--allow-data-loss | Writes the migration even when it destroys data. |
--no-strict-coverage | Writes the migration even when pg-delta finds objects it cannot manage. |
--prove | Applies the plan to a clone of the stack and refuses it unless it converges and keeps data. |
--stack <name> | Uses the database of supabase/stacks/<name>/config.toml (default $BETTER_SUPABASE_STACK). |
A migration from the library plan starts with a comment that asks you to
review it: it compares two databases, so check the order of the statements
before you apply it. The JSON envelope names the engine in data.engine, lists
the plan's findings in data.issues, the objects strict coverage refused in data.blocking, the proof's verdict in data.proof, the _custom/ files that no migration delivers in data.custom and sets data.fellBack when the shadow
database failed. better-supabase dev stack prune frees the segments that idle
stacks hold.
Side effects: Writes to the database, writes files with --file.
Tenant defaults
The organizations block installs better_supabase.seed_tenant_defaults(tenant, variants, locale). It calls the seed_<block>_defaults function of every installed block that declares rows (pipelines, the accounting chart, inbox statuses, leave types, tax codes, and others), in install order, and each function skips rows that exist. create_organization calls it for the new organization. Set database.seed.defaults to false to leave it out, or { onCreate: false } to call it yourself. locale and variants in the same object are the defaults of the function's second and third argument.
seed
Define fixtures once, in app casing, checked against your Insert types:
import { defineSeed } from "better-supabase/testing";
import { betterSupabase } from "../src/lib/supabase/index.ts";
export const ACME = "00000000-0000-4000-8000-000000000001";
export const seed = defineSeed(betterSupabase, {
organizations: { acme: { id: ACME, name: "Acme", slug: "acme" } },
customers: {
first: {
organizationId: ACME,
name: "First customer",
metadata: { tier: "pro" },
},
},
});pnpm better-supabase db seed # writes supabase/seeds/000_better_supabase.sql
pnpm better-supabase db seed --check # fails in CI when the SQL is stale
pnpm better-supabase db seed --yes # also inserts into the local database--entry <file> and --out <file> override database.seed.entry and
database.seed.file. --dry-run prints the diff and writes nothing; neither it nor
--check runs --yes. --yes connects to $DATABASE_URL or $SUPABASE_DB_URL, or to the local stack;
to seed another database, pipe its connection string in with
--db-url-stdin.
- Tables are inserted parents first, following foreign keys.
- Missing columns use their defaults, and every insert is
on conflict do nothing, so a seed can run twice. - Unknown tables and columns are type errors. A column you leave out that
has no default fails in the editor, not at
db reset. - Add the file to
[db.seed] sql_pathsinsupabase/config.toml.db seedprints the line when it's missing, and it never overwrites a file it didn't write unless you pass--force.
Tests import the same rows: seed.rows.customers.first, and
await seed.insert(sql) in a beforeAll. Node loads seed.ts directly,
so use .ts extensions in its relative imports.
Seeds per tenant
A tenant seed builds rows from a tenant, so every organization can start
with the same demo data. Put it in database.seed.perTenant
(supabase/seed.tenant.ts by default):
import { defineTenantSeed } from "better-supabase/testing";
import { betterSupabase } from "../src/lib/supabase/index.ts";
export const seed = defineTenantSeed(betterSupabase, (tenant) => ({
customers: { demo: { organizationId: tenant.id, name: "Demo customer" } },
}));pnpm better-supabase db seed --tenant acme # one organization, by slug or id
pnpm better-supabase db seed --tenant '*' # every organization--tenant looks organizations up in the
organizations block and inserts the rows for
all of them in one transaction, so a failure leaves none behind. --entry
overrides database.seed.perTenant. The database and consent rules are the ones
--yes follows: the local stack needs no consent, any other database
does, and --dry-run connects to nothing. tenant.slug and tenant.name
are set when the organization has them. Every insert is
on conflict do nothing, so give rows a key when the seed may run twice
for the same tenant; a row whose id comes from a default is inserted again.
To seed each organization as it's created in development, register the seed once on the server with a service-role client:
import { createPostgres } from "better-supabase/postgres";
import { seedTenantOnCreate } from "better-supabase/testing";
import { seed } from "../../../supabase/seed.tenant.ts";
import { betterSupabase } from "./index.ts";
const postgres = createPostgres({
connectionString: process.env.SUPABASE_DB_URL,
});
seedTenantOnCreate(betterSupabase, seed, { sql: postgres.admin });It listens for organization.created and runs only when NODE_ENV is
development (pass enabled to decide yourself). The seed runs after the
create call has returned, so it can't change its result; a failed seed goes
to onError, or to console.error by default.
Defaults for existing organizations
A block that declares tenant defaults ships a seed_<block>_defaults
function, and new organizations get its rows when they are created.
db seed --defaults calls those functions again for organizations that
already exist, so a block you add later fills in the rows it needs. Rows that
exist are kept, so it can run twice.
pnpm better-supabase db seed --defaults --tenant acme --locale nl
pnpm better-supabase db seed --defaults --variant helpdesk=support--tenant defaults to every organization. --variant block=name picks a
block's starting set (repeat it for more blocks) over
database.seed.defaults.variants, and --locale picks the language
(database.seed.defaults.locale, en by default). A variant that the block
does not declare is refused. Setting database.seed.defaults.onCreate to
false stops new organizations from getting defaults. The database and
consent rules are the ones --yes follows.
Blocks that declare defaults today are risks, cases, leave, tax,
pipelines and accounting. pipelines offers the variants b2b-sales and
recruiting, and accounting offers generic (the default) and nl-rgs. The
catalog roles owner, admin and member are not per-organization defaults;
the permissions data step adds them once.
Sample data
db seed --sample asks the Better Supabase cloud for realistic sample rows
that fit your blocks and applies them in one transaction. It needs a Pro
account and better-supabase login (login).
pnpm better-supabase db seed --sample --demo-org --size m --seed 7
pnpm better-supabase db seed --sample --tenant acme --out supabase/seeds/900_sample.sqlSay where the rows go with --tenant <slug> or --demo-org, which creates a
demo organization. --size is s, m or l, and the same --seed gives the
same rows. --out <file> writes the statements to a file instead of running
them, and --dry-run shows how many would run. Without a Pro plan the cloud
answers 402 and the command exits with code 2 and the upgrade address.
database.seed.sample holds the defaults for size, seed, locale and
output.
Side effects: Writes files, writes to the database with --yes, writes to the database with --tenant, writes to the database with --defaults, calls the Better Supabase cloud with --sample.
backfill
pnpm better-supabase db backfill invoices.organization_id --from projects.organization_id via project_id
pnpm better-supabase db backfill invoices.currency --value "'EUR'" --dry-run
pnpm better-supabase db backfill projects.settings --array tags --match '{"name":"old"}' --delete --dry-rundb backfill fills the null values of a column that a migration added to a
table that already holds rows, the middle step of expand and contract. With
--from, it copies each value from the table a foreign key column points at:
via project_id names the column of the target table, and the command finds
the key it references (the foreign key, else the primary key of the source
table). With --value, it writes one SQL literal, such as 'EUR', 0,
true or '{}'::jsonb, to every null row.
It updates --batch-size rows per statement, each in its own transaction,
and locks only those rows (for update skip locked), so the app keeps
writing while it runs. It prints a line per batch. It only touches rows where
the column is null, so a run that stops can start again, and a second run
fills nothing. Rows whose source value is null, or that have no source row,
stay null; the result counts them in remaining.
| Flag | Effect |
|---|---|
--from <table.col> | Copies the value from this column, joined through via <column>. |
--via <column> | The foreign key column of the target table, the same as a trailing via <column>. |
--value <literal> | Writes this SQL literal instead of --from. |
--array <path> | Changes the elements of the jsonb array at this key path instead of filling nulls. |
--match <json> | With --array: the JSON object an element must contain to change. |
--delete | With --array: removes the matching elements. |
--merge <json> | With --array: merges this JSON object into each matching element. |
--batch-size <n> | Rows per statement (default 1000). |
--dry-run | Counts the rows (and elements) it would change and writes nothing. |
--stack <name> | Uses the database of supabase/stacks/<name>/config.toml (default $BETTER_SUPABASE_STACK). |
--db-url-stdin | Reads the connection string from stdin, so it never reaches argv. |
Array elements
--array changes the elements inside a jsonb column instead of filling nulls,
for the data step of removing an enum value or renaming a key. --array tags
reads the array at tags in the column, --array settings.tags reads
settings then tags, and --array . reads the column itself. An element
matches when it contains the --match object (jsonb @>). Pass exactly one of
--delete, which removes the matching elements, or --merge '{"name":"new"}',
which merges an object into each of them (jsonb ||) and keeps the order of
the array. Rows whose value at the path isn't an array are left alone, and
--from, via and --value don't combine with --array.
It runs in ctid batches like the fill mode, only reads rows that still have an
element to change, and a merge only counts the elements it would alter, so a
second run changes nothing. --dry-run prints the rows and elements it would
change, and the JSON envelope returns data.rows, data.elements,
data.batches and data.remaining.
Removing an enum value
Postgres has no alter type ... drop value, and a schema diff that removes a
value plans a type drop that fails while a column uses the type.
doctor reports alter type ... rename value and
delete from pg_enum in an unapplied migration. Remove a value in three
steps, each its own migration:
- Move the rows off the value (
update, ordb backfill --arrayfor values stored in ajsonbarray). - Create the new type without the value, change the column with
alter table ... alter column ... type new_type using column::text::new_type, and drop the old type. - Rename the new type back if you need the old name.
A table rewrite holds an access exclusive lock, so run step 2 with
set lock_timeout (BS233) in a quiet window, or add a
new column and backfill it.
A table name without a schema means public. The command connects like
db query, and against a database that is not local, an agent
needs the user's consent first. The JSON envelope returns data.filled,
data.batches and data.remaining, or data.pending with --dry-run.
Each update fires the table's triggers, so audit, version and event triggers
record every backfilled row. When nothing is left null, add the not-null check
as not valid in a migration, then run
doctor --yes, which validates it. Then
set not null needs no scan:
alter table invoices
add constraint invoices_currency_not_null check (currency is not null) not valid;A tables.<name> entry that enriches a table you already have adds that check
to the scope column itself, so the order there is the other way round: new
rows must name an owner at once, and db backfill fills the existing rows
that doctor reports as BS238. See
Your own schemas.
Side effects: Writes to the database.
partition
pnpm better-supabase db partition audit --dry-run
pnpm better-supabase db partition audit --batch-size 100000db partition audit moves an audit log that was created before the audit
block's options.partitioned was turned on onto monthly partitions, while the
app keeps writing. Set the option, run better-supabase gen, and apply the
migration first: it adds the convert_audit_log_to_partitioned procedure the
command calls. The procedure builds the partitioned table beside the old one,
copies the rows in id batches (each batch commits), and then takes one short
lock that blocks writes but not reads to copy the last rows, swap the names
and move the grants, policies and triggers. The old table stays as
<name>_unpartitioned until you run the command again with --drop-old. A run
that stops can start again; it resumes from the rows already copied.
| Flag | Effect |
|---|---|
--batch-size <n> | Rows copied per transaction (default 50000). |
--drop-old | Drops the unpartitioned copy after the swap. |
--dry-run | Checks that the procedure exists and changes nothing. |
--stack <name> | Uses the database of supabase/stacks/<name>/config.toml (default $BETTER_SUPABASE_STACK). |
Side effects: Writes to the database.
rows
pnpm better-supabase db rows
pnpm better-supabase db rows --checkdb rows turns the files in supabase/rows into data migrations. A rows file
is a list of upserts of literal rows by their natural key:
insert into better_supabase.declared_defaults (kind, subject, key, position, value)
values
('option_set_item', 'project.priority', 'low', 0, jsonb_build_object('label', 'Low')),
('option_set_item', 'project.priority', 'high', 1, jsonb_build_object('label', 'High'))
on conflict (kind, subject, key) do update
set position = excluded.position, value = excluded.value;For each file, the command hashes the statements (comments and whitespace do
not count) and looks for the newest migration that carries
-- @bsb-rows <file> sha256:<hash>. When the hash is the same it does nothing.
When it differs, it writes a new migration with the statements and the new
hash, so a migration that was pushed is never rewritten. The reader refuses
anything that is not an upsert: do nothing, a missing conflict target, a
select source, returning, a subquery, a key that is not a literal, and every
function call except jsonb_build_object, jsonb_build_array and to_jsonb.
A row that you remove from a file stays in the database, because a migration
cannot know whether the app changed it. The command prints a review: line for
it. Put -- bsb-rows: delete-removed in the file to make the migration delete
the removed rows by their natural key.
| Flag | Effect |
|---|---|
--check | Writes nothing and exits 1 when a file has no migration with its hash. |
--dry-run | Prints the migrations it would write, and writes nothing. |
Side effects: Writes files.
squash
pnpm better-supabase db squash --dry-run
pnpm better-supabase db squash --keep reference_data,billing_plans --yesdb squash replaces every migration in supabase/migrations with one
baseline of the declarative schema files, which it writes with
supabase db schema declarative sync --no-apply --strict-coverage. A schema
diff never writes the module extensions or your seed data, so the command
carries them over: the better_supabase_extensions migration goes in before
the baseline, and each name in --keep goes in after it, with the files of one
name merged in order (name_1, name_2 and name_10 from pg-delta's
multi-file output sort by number, and files that disagree about
-- pg-delta: transaction=false are refused). A name with no migration is an error. When the baseline
fails, the command puts the old migrations back. Never squash migrations a
hosted project has applied; run it for a deliberate reset and reset the
database afterwards.
| Flag | Effect |
|---|---|
--name <name> | Name of the baseline migration (default init). |
--keep <names> | Comma-separated data migration names to carry over. |
--schemas <list> | Schemas the baseline covers (default: the schemas of the config). |
--dry-run | Prints what it would remove and keep, and changes nothing. |
Side effects: Writes files.
verify
pnpm better-supabase db verify
pnpm better-supabase db verify --write-testsdb verify reads the security facts of the database for the schemas in your
config: whether row level security is on, the grants and policies of each
table, and the search_path of each security definer function. It reports
what verifyCatalog finds (a table readable by anon through a policy that is
only true, a write grant to anon, a grant to PUBLIC, a definer function
without a search_path) and exits 1 on an error. It only reads the database.
With --write-tests, it also writes the access matrix as one pgTAP file per
persona (anon, signed in without a membership, member of tenant A, member of
tenant B, read-only support and the service role) to --dir, by default
supabase/tests/database. Memberships belong to your app, so the member
personas carry no setup SQL: add the rows and claims they need before you rely
on those files.
| Flag | Effect |
|---|---|
--write-tests | Writes the pgTAP access matrix files. |
--dir <path> | The folder of those files (default supabase/tests/database). |
--stack <name> | Uses the database of supabase/stacks/<name>/config.toml (default $BETTER_SUPABASE_STACK). |
Side effects: Reads the database, writes files with --write-tests.
_custom/ files
pg-delta loads every file under supabase/schemas/_custom into the shadow
database and never into yours. The in-stack diff lists, in the log and in
data.custom, each file that has no -- pgdelta-migration: line (undelivered)
and each file whose directive names a migration that does not exist
(dangling). Neither stops the diff: an object that exists only in _custom/
and is missing from your database is the case strict coverage already refuses.
Add the directive when a migration carries the file, or -- pgdelta-migration: none when none has to.
Last updated on