doctor
Security, performance and drift checks for your database, config.toml and env files.
pnpm better-supabase doctordoctor introspects the database the same way gen does,
then reads supabase/config.toml, your .env* files and .gitignore. Every
finding has a code, a severity and a link to its section on this page. When a
finding is about a table, function or policy, doctor points at the file that
creates it: declarative schemas in supabase/schemas first, then the newest
migration.
It also runs Supabase's own Security and Performance
Advisors (BS100
and BS200), so the dashboard's findings show up locally and in CI. It exits
with 1 when there are errors, or with any warning under --fail-on warning.
| Option | Description |
|---|---|
--format <f> | text (default), sarif or github; also tooling.doctor.format. The global --json prints the JSON report |
--out <file> | Write the report to a file; also tooling.doctor.file, which applies with tooling.doctor.format |
--only <codes> | Run only these checks, e.g. --only BS100,BS304; also tooling.doctor.only |
--ignore <codes> | Skip checks. Adds to tooling.doctor.ignore in the config |
--fail-on <level> | Exit 1 on findings at this level: error (the default), warning (the default with tooling.doctor.strict) or never |
--snapshot <file> | Check a saved snapshot instead of the database |
--metadata <path|-> | Check a GeneratorMetadata document (- for stdin). Checks that need policies, grants, indexes, triggers or other data it lacks are skipped with an info finding; it exits 65 for a document it rejects (gen) |
--db-url-stdin | Read the connection string of the database to check from stdin |
--project-ref <ref> | Hosted project to read through the Management API (needs SUPABASE_ACCESS_TOKEN) |
--stats | Report slow frequent statements from pg_stat_statements (BS209) |
--explain <tables> | Plan these tables, or functions such as rs_customers_hub and order_payload, under RLS (BS212) |
--explain-write <tables> | Plan an insert (a copy of one row with fresh keys) and an update on these tables, with the time of each trigger (BS212) |
--args <json> | With --explain <function>: the arguments, a JSON array (positional) or object (named) |
--as <uuid> | With --explain or --explain-write: plan as this authenticated user. Also measures the claims the custom access token hook returns for them (BS405) |
--claims <json> | With --explain or --explain-write: plan with these JWT claims |
--fix-grants | Print the grant and revoke SQL that BS404 asks for, as one block for a schema file or migration |
--vercel | Check the variables of each Vercel environment that vercel pull wrote to .vercel/.env.<name>.local (BS513 to BS515) |
--update-baseline | Rewrite the baseline file to accept this run's errors and warnings |
Doctor never prints env values, only variable names and line numbers.
Side effects: Reads the database, writes to the database with --yes, calls the Supabase Management API with --project-ref, downloads from GitHub.
Large projects
Doctor checks --out before it reads anything: a path outside the project, or
a directory, stops the run at once. It logs how long each phase took (reading
the project, running the rules) while it works, prints them under the text
report, and lists them as phases in the JSON report. A text report of 20
findings or more starts with one line per rule and its count, worst severity
first, then the largest count.
Without a database
When no database runs and none is configured, doctor reads the schema from
the saved snapshot instead: source.snapshot in the config, else
supabase/snapshot.json, which better-supabase gen --save-snapshot writes.
It says so on stderr, since the result is as current as the last save:
pnpm better-supabase gen --save-snapshot # while the stack is up
pnpm better-supabase doctor --only BS103,BS106,BS430Some checks need the database itself: the advisors (BS100 and BS200) and the
checks that read statistics, plans, settings or live rows (BS208, BS209,
BS212, BS225, BS236, BS238, BS241, BS242, BS245, BS363, BS399, BS638, BS639 and
BS732). When a run includes one of them and no database answers, doctor stops
and names them, so you can leave them out with --ignore or --only. The
flags --stats, --explain, --explain-write, --as and --yes always
need the database.
In CI
--format github writes workflow annotations, so findings show up on the pull
request diff:
- run: pnpm better-supabase doctor --format github --fail-on warningThe github and sarif formats write file paths relative to the repository
root (the directory that holds .git, else the Supabase project root), so
annotations land on the right files when the CLI runs from a package. The text
format keeps paths relative to the project directory.
For GitHub code scanning, upload SARIF:
- run: pnpm better-supabase doctor --format sarif --out doctor.sarif
- uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: doctor.sarifTo keep the workflow step to better-supabase doctor, put the CI settings in
the config's ci environment, which the CLI
applies when $CI is set:
export default defineConfig({
$ci: {
tooling: {
doctor: { format: "sarif", file: "doctor.sarif", strict: true },
},
},
});doctor --json puts the report in the envelope's data. The report follows
doctor-report-v1.json,
and a run with errors has the findings error code.
Ignoring checks
export default defineConfig({
tooling: { doctor: { ignore: ["BS204"], strict: true } },
});tooling.doctor.sources lists the app files that checks such as BS210 scan, as globs
relative to the project root. The default is ['src/**/*.{ts,tsx}']; at the
root of a pnpm or npm workspace, doctor also scans that glob in each package,
such as apps/web/src/**/*.{ts,tsx}. A sources you set is used as it is.
tooling.doctor.claimsLimit is a BS405 limit in bytes: the budget of the
authorization provider's hook when
it sets tokenHook.budget, otherwise the limit for the whole token (default
2048).
tooling.doctor.policyHelperLimit (default 5) is how many policies a security definer
helper may appear in before BS206 reports it.
tooling.doctor.parallelReads (default 3) is how many database reads one
Promise.all may await before BS609 suggests a read set. Raise it to
quiet the hint on pages that load a few reads at once.
Baseline
A baseline accepts the findings an existing project already has, so CI fails
only on new ones. Point tooling.doctor.baseline at a JSON file and write it
once:
export default defineConfig({
tooling: { doctor: { baseline: "doctor-baseline.json" } },
});pnpm better-supabase doctor --update-baselineThe file lists one entry per accepted finding, keyed by its code and target
(its title when it has none). Fill in each reason so a reviewer can see why
the finding stays:
[
{
"code": "BS351",
"target": "src/app/settings/actions.ts:12",
"reason": "Moves to the credentials API in the next release"
}
]Doctor leaves out the findings the file lists. An entry that no finding matches
fails the run as an error with its code, so the baseline shrinks as you fix
findings: remove the entry, or run --update-baseline again. It only judges an
entry when its check ran, so a run without a database keeps the entries of the
checks that need one, and --only keeps the rest. --update-baseline keeps
each entry's reason, gives a new entry the reason of another entry with its
code, and leaves out info findings.
The source checks BS609, BS634 and BS635 key a
finding by file, enclosing function and callee, such as
src/lib/tasks.ts#loadTask:db.quoteTasks.list, with #2 for the second call
of the same callee in that function, so an edit elsewhere in the file keeps the
entry. An entry from an older release that names the finding's file:line
still matches it, and --update-baseline rewrites it to the new target with
its reason.
The full doctor block, generated from the DoctorConfig type:
Prop
Type
Supabase advisors
BS100
Security Advisor findings. Each finding keeps the advisor's own severity
(error, warning or info), title and remediation link. The advisor covers RLS
disabled in exposed schemas, RLS without policies, security definer functions
anon or authenticated can call, mutable search_path, auth.users exposed
through views, user_metadata in policies and more. The message ends with the
lint name, for example [rls_disabled_in_public].
Where the findings come from depends on what doctor reads:
- Hosted projects (
--project-refordatabase.source.projectRef): the Management API'sGET /v1/projects/{ref}/advisors/security, the same data the dashboard shows. - A database on this machine (the local stack or a loopback URL):
supabase db advisorswhen the Supabase CLI is 2.81.3 or later. Doctor passes the URL with--remote=<url>(--db-urlbefore CLI 3.0),--typeand--level info, and reads the JSON output (a list, an object withlints, or one lint per line). A missing or older CLI, a remote database, a failed run or an output shape it doesn't know falls back to splinter. - Any other database, or the fallback (
$DATABASE_URL,$SUPABASE_DB_URLor--db-url-stdin): splinter, the SQL behind the advisors. Doctor downloadssplinter.sqlat a pinned commit, checks its SHA-256, caches it innode_modules/.cache/better-supabaseand runs it in a read-only transaction that is rolled back. splinter has no license, so it isn't bundled. - Saved snapshots: there is no database to lint, so doctor reports an info finding saying the advisors were skipped.
If the advisors can't run (offline, no access token), doctor reports a warning
instead of failing silently. For --project-ref, use a scoped personal access
token limited to the project and the advisor and read-only query permissions
(see Hosted projects),
not a classic token with access to your whole account.
BS200
Performance Advisor findings. Same sources as BS100: unindexed foreign
keys, auth.uid() re-evaluated per row in policies, multiple permissive
policies, unused and duplicate indexes, tables without a primary key, table
bloat and more. Doctor's own BS207 and BS216 repeat
splinter's multiple_permissive_policies and unindexed_foreign_keys; when
BS200 runs and the advisor loads, they skip the tables splinter reports, so
each problem shows up once.
Security
BS103
Error: policy allows anonymous writes. A permissive insert, update,
delete or all policy for anon or public uses true. Anyone can change
rows. Restrict the policy to authenticated and check ownership.
BS106
Error: table not granted to the Data API. Hosted projects grant new
tables to anon and authenticated unless the project turns default
privileges off (auto_expose_new_tables = false locally). Without a grant,
every request fails with
42501 before RLS runs. Tables listed in expose
need exactly the privileges listed; other tables in the generated schemas need
select for authenticated, except tables with RLS on and no permissive
policy when
blocks.grants.options.fromPolicies is on: those are service-only, so
BS106 expects no grants for them (BS115). Add the table to expose
and run better-supabase add grants. When config.toml sets
[api] auto_expose_new_tables = false, the finding says so.
A table that only the server reads, such as an audit log written with the
secret key, is kept off the Data API on purpose. Mark it
tables: { audit_logs: { serviceRole: true } }: BS106 then checks the
opposite, that anon and authenticated (directly or through public) have
no grant on it, and reports any they have. Its models are still generated, so
an admin client keeps its types. exclude also silences BS106, but leaves
the table out of the generated models.
BS107
Warning: tenant table without a policy for every command. A table with
the tenant column (or whose policies call a membership or tenant helper) has
permissive policies for authenticated covering some of select, insert,
update and delete, but not all. RLS denies the missing commands without
an error, so an update or delete matches 0 rows and the UI looks like it
worked. Add the missing policies, or a restrictive using (false) policy to
make a read-only table explicit, and cover the table with
expectTenantIsolation. The tenant table
itself (the one the tenant column references) is skipped. On an app table a
block runs over, only your own policies decide whether the table is reported:
the block reads it through its bsb_ policies and writes it through its own
functions, so a table with only block policies is left alone. A command that
anon and authenticated hold no table or column privilege for fails with
42501 before row security runs, so it needs no policy and isn't reported.
BS108
Error: policy reads auth.mfa_factors directly. authenticated can't
select from auth.mfa_factors, so the policy fails every request with
42501. Use (select better_supabase.mfa_satisfied()) from
better-supabase add mfa, a security definer function. See
MFA and SSO.
BS109
Warning: auth.role() in a policy or function. Supabase deprecated
auth.role(). Doctor reads every policy, the functions policies call and the
functions in the exposed schemas. Scope the policy with to authenticated
instead, or read the claim with (select auth.jwt() ->> 'role').
BS110
Warning: update policy without a select policy or with check. An update
finds its rows through the select policies first, so a role with an update
policy but no select policy updates nothing and gets no error. Add a select
policy for the same role. An update policy without with check is an info
finding: Postgres then checks the new row against using, which leaves
unstated whether a row may move to another owner or tenant. Write both:
create policy notes_update on public.notes for update to authenticated
using (organization_id in (select better_supabase.member_organization_ids()))
with check (organization_id in (select better_supabase.member_organization_ids()));BS111
Warning: API roles hold privileges they don't use. anon and
authenticated never need truncate, references or trigger on a table,
and truncate skips RLS. The finding lists the revoke. A grant to anon
on a table with RLS where no policy applies to anon is an info finding: it
lets no request through, but lists the table in the Data API schema that
anyone with the publishable key can read.
BS112
Warning: exposed security definer function that doesn't check the
caller. A security definer function runs as its owner, past RLS. In an
exposed schema the Data API serves it at /rpc/<name>, so when anon or
authenticated may execute it and its body never reads auth.uid(),
auth.jwt(), the request claims or better_supabase.is_service_role(), and
never calls the access contract (better_supabase.can, can_user,
is_platform, tenant_ids_with) or a function in a schema of the
authorization provider's functions (authorization.requires), any caller gets
the owner's access. Check
the caller in the body, revoke execute from the API roles, or move the
function to a schema the API doesn't expose. Trigger functions are skipped;
/rpc can't call them. Needs a snapshot taken with this version, which
records who may execute each function.
BS113
Info: storage upload policy without the upsert policies. An upload with
upsert: true (the x-upsert header) needs select and update policies
on storage.objects besides insert. Without them, replacing a file that
exists fails with 403. Doctor reads the policies in supabase/schemas and the
migrations; add the missing ones with the same bucket and path check.
BS114
Error: policy helper reads user_metadata. Users can change their own
raw_user_meta_data with auth.updateUser(), so a function that reads
user_metadata to decide access lets them grant themselves rights. Read
app_metadata, which only the service role can write. Splinter's
rls_references_user_metadata (BS100) covers the policy text; this check
covers the functions policies call, and the functions those call.
BS115
Warning: table without a policy still granted to the Data API. A table
with RLS on and no permissive policy for anon or authenticated answers
every request with no rows or a denied write, yet a grant lists it in the API
schema. With blocks.grants.options.fromPolicies, better-supabase upgrade
revokes anon, authenticated and public on every table in schemas with
RLS on that no expose entry and no permissive policy reaches, and keeps the privileges
of service_role. Until the migration is applied, doctor reports the grants
that are still on the database. Tables in expose, tables.<name>.exclude
and tables.<name>.serviceRole are skipped.
BS116
Warning: security definer function open to the API roles but not
exposed. Postgres grants execute on a new function to public, so a
security definer function in an exposed schema is callable at /rpc by
anon and authenticated unless it is revoked. When no
expose entry lists the function and no
policy calls it, nothing in the project says the API roles should reach it.
Doctor never revokes anything. Run
revoke all on function schema.name(args) from public, anon, authenticated;,
then grant execute to the roles that call it (or list the function in
expose). BS112 reports the same functions when they also skip a
caller check. Needs a snapshot taken with this version, which records who may
execute each function.
BS117
Warning: policy without a role. A policy without to, or with
to public, applies to every role, anon included. Postgres evaluates it on
requests it was never written for, and a later edit to its expression can
open the table to signed-out users. Name the roles the policy is for:
create policy notes_read on public.notes for select to authenticated
using (organization_id = (select better_supabase.current_tenant_id()));Restrictive policies only narrow access, so doctor skips them. When anon
holds no privilege on the table, a signed-out request fails before the policy
runs, so the finding is info instead of a warning.
Performance
BS204
Warning: tenant column without an index. With the memberships extension, every query filters on the tenant column. Add an index that starts with it; an expression index whose first key is the plain column counts, a partial one doesn't. Views are left out, because a query on a view uses the indexes of its tables.
BS205
Warning: policy calls a slow function once per row. A policy passes a
column of the row, such as is_member(organization_id), to a function
Postgres can't inline: plpgsql or another non-SQL language, volatile,
security definer, or with any set option (set search_path = ''
included). The call runs once for every row the query reads. Doctor finds the
functions a policy calls in pg_depend, so helpers in private schemas count
too. Have the helper return the allowed values once and compare, which works
for security definer helpers as well:
create policy notes_member on public.notes for select to authenticated
using (organization_id in (select private.user_organization_ids()));An insert policy's with check runs once per written row, never over a scan,
so on an insert-only policy the finding is info.
BS206
Warning: security definer policy helper that cannot be inlined. A
security definer function appears in more than tooling.doctor.policyHelperLimit
policies (default 5). Postgres never inlines a security definer function, even
one written in language sql stable, so a call that takes a column of the row
runs once per row. Call it as (select helper(...)) when its arguments don't
come from the row, so Postgres evaluates it once per statement as an
InitPlan, or have it return the allowed ids as a set and compare with
organization_id in (select helper()). When the helper itself is slow, compute
its answer once per transaction with
better_supabase.memo_get and memo_set.
A policy whose every call to the
helper takes constant arguments in a sub-query, such as
(select tenant_ids_with('crm.read')), col in (select helper('k')), a
union all select helper('k') branch or from helper('k') t(id), doesn't
count.
BS207
Warning: several permissive policies for one command and role. Postgres
evaluates every permissive policy that applies to a command and role, and ORs
the results, so each extra policy adds its cost to every row. The message
lists each command and role with its policies; a policy for public counts
for every role. Merge each group into one policy with or. When
BS200 runs, splinter's multiple_permissive_policies reports the
tables it covers and this check skips them; on a saved snapshot, or when the
advisor can't run, this check reports every table. On one of your tables that a
block runs over, one of your policies next to the block's bsb_ policy for the
same command is left to BS347: it reports the pair when the block's
condition is wider. When your policy already covers the block's, the block
adds no policy there.
BS208
Warning: queries spill to temporary files. Reads temp_files and
temp_bytes from pg_stat_database since the statistics were last reset,
with the current work_mem. When pg_stat_statements is installed, the
message lists the five statements that wrote the most temporary blocks.
Statements run by Supabase's service roles (PostgREST's schema cache query as
authenticator, Auth and Storage) are left out, and so are better-supabase's
own catalog reads from gen and doctor, which start with the
comment /* better-supabase */. When only those spilled, there is no finding. Add indexes so large sorts go away, or raise work_mem
for the role that runs them. Needs a database; saved snapshots skip it.
BS209
Warning: slow frequent statements. With --stats, doctor reads
pg_stat_statements and reports statements with a mean time above 50 ms and
more than 1000 calls, slowest total first. When a statement names a table in
the exposed schemas, the finding points at the file that creates the table.
Without the extension, doctor reports an info finding with the
create extension command.
BS210
Warning: aggregates used while PostgREST disables them. PostgREST
answers aggregate(), _sum, _avg, _min and _max includes and list
facetCounts with PGRST123 unless pgrst.db_aggregates_enabled is on for the authenticator
role. Doctor reads the role's settings from the database and scans the files
in tooling.doctor.sources (default src/**/*.{ts,tsx}) for those calls. Turn
aggregates on in a migration:
alter role authenticator set pgrst.db_aggregates_enabled = 'true';
notify pgrst, 'reload config';Saved snapshots from before this check carry no role settings, so they skip it.
BS211
Info: statement timeouts for the Data API roles. PostgREST switches to
anon or authenticated for each request, so their statement_timeout
limits Data API queries; doctor reports the values set on anon,
authenticated and authenticator. A function's own
set statement_timeout = ... only applies to an RPC when PostgREST hoists
it into the transaction. When pgrst.db_hoisted_tx_settings is set without
statement_timeout, doctor warns for each exposed function that sets one.
It also reports each role's idle_in_transaction_session_timeout, which ends
a session that leaves a transaction open. A role setting applies to the role
a connection logs in as, not to set role, so for better-supabase/postgres
set it on the login role or with the pool's idleInTransactionTimeout.
BS212
Info: RLS plan for a table. --explain customers,notes runs, for each
table, in a transaction that is rolled back:
set local track_functions = 'all'; -- skipped if the role may not set it
select set_config('request.jwt.claims', '<claims>', true);
set local role authenticated; -- the claims' role, default anon
explain (analyze, buffers, format json) select * from public.customers limit 1000;That is the query list() sends, capped at Supabase's default max_rows.
--as <uuid> plans as { "sub": uuid, "role": "authenticated" };
--claims '{"role":"authenticated","tenant_id":"..."}' sets any claims your
policies read. Qualify tables outside the exposed schemas, such as
better_supabase.memberships.
The finding lists node types, timings and loops, never row data, with the
number of InitPlans and each function's share of the execution time from
pg_stat_xact_user_functions. A SubPlan that runs more than once means a
policy is evaluated per row, and the finding becomes a warning: wrap the
policy's function calls in (select ...) so they run once as an InitPlan.
--explain needs a direct connection (local stack, $DATABASE_URL, $SUPABASE_DB_URL or --db-url-stdin); the
Management API's read-only endpoint can't switch roles.
--explain-write customers measures what a write costs, which a read plan can't show: audit, updated_at and
outbox triggers all run inside the write. It copies one existing row with fresh keys (a new uuid, a unique text
value, or the key's default) into an insert, and assigns one non-key column its own value in an update. Each
statement runs under EXPLAIN (ANALYZE) in a transaction that is rolled back, and the finding lists the time
of every trigger from the plan. The update assigns a column its own value, so a trigger that fires only when a
column changes (like an audit trigger with ignore) shows only its cheap exit. Compare the numbers with
audit(..., statement => true) for bulk writes.
--explain also takes a function in an exposed schema, such as a compiled read
set (rs_customers_hub) or a payload function (order_payload). Pass the
arguments with --args, as a JSON array (positional) or object (named), and
the user with --as:
better-supabase doctor --explain rs_customers_hub --as 0000…00ff \
--args '{"p_customer":"c7d1…"}'Each value is sent as a literal cast to the argument's declared type, and the finding never prints rows. When a security definer helper ran, the finding adds a policy time share: the helpers' self time over the execution time, next to the calls each helper made in the statement.
info BS212 RLS plan for a table
public.customers as authenticated 0000…00ff: 0.15 ms, 1 InitPlan.
Plan: Limit 0.14 ms ×1 > InitPlan 1: Result 0.13 ms ×1 > Seq Scan on
customers 0.14 ms ×1. Function time: better_supabase.current_tenant_id
0.13 ms over 1 call (83%).BS213
Warning: API roles can write the columns that grant access. RLS helpers
decide who sees a row from other rows: better_supabase.has_organization_role reads
memberships.user_id and memberships.role, and a contact-scoped helper reads
contacts.user_id and contacts.customer_id. Doctor collects the columns
that the helpers your policies call read, including the helpers those call,
plus the decidingColumns of the authorization provider. It warns when anon or authenticated may insert or update one of
those columns and a policy lets them write the row: a member who can update
their own role, or a portal contact who can change customer_id, grants
themselves access.
Six kinds of column don't count. A single-column primary key doesn't, because
its uniqueness stops a write from taking over another row. A tenant column
doesn't when every policy for the write pins it to
better_supabase.current_tenant_id(), to better_supabase.can('tenant', column, ...),
to column in (select better_supabase.tenant_ids_with(...)) or
column in (select better_supabase.member_organization_ids()), or to the
authorization provider's idsWith or memberIds helper, so a write can only
name a tenant the caller is a member of or holds the permission in. An or
counts only when each branch pins the column, or writes column is null next
to a platform check (better_supabase.is_platform(...) or the provider's
isPlatform), which only a platform role passes. A tenant column that a
composite foreign key with not-null columns ties to a parent row, such as
foreign key (job_id, organization_id) references jobs (id, organization_id),
doesn't count when every policy for the write checks one of the key's other
columns, such as j.id = job_parties.job_id inside an exists that checks
access to the job j: the key keeps the column equal to the parent's, and the
policy keeps the parent one the caller may write. A column every insert policy
pins to the caller, column = (select auth.uid()), doesn't count on insert:
the caller can only name themselves on a row they create. It still counts on
update, where it would let them take another row over. A
subject's deletedAt column in config.recordTypes doesn't: can_subject
filters soft-deleted rows out of a check that the row's own policies already
pass, so clearing the column only shows a row again to someone who could
already write it. A block's soft-delete column that its triggers never let a
write clear, such as comments.deleted_at, doesn't either. A column the
provider lists in decidingColumns always counts.
A table-level grant counts even after a column-level revoke, because
Postgres checks the table grant first. A grant to public counts for both
roles, and the SQL then revokes it from public too. The finding lists the SQL that keeps
the other columns writable:
revoke insert, update on public.contacts from authenticated;
grant insert (id, name, email), update (id, name, email) on public.contacts to authenticated;When a trigger already protects a column, mark it in the trigger's comment. Doctor doesn't read trigger bodies, so the marker is how you tell it that the trigger raises when the column changes:
create trigger memberships_keep_role
before update on public.memberships
for each row execute function public.keep_role();
comment on trigger memberships_keep_role on public.memberships is
'better-supabase:guards(role, user_id)';The marker is better-supabase:guards(column, ...) on a line of its own, so
the comment can hold other text on the lines around it. A column may be
double-quoted. Doctor then leaves the named columns out for a command only
when the trigger is a row-level before trigger for that command (update
for updates, insert for inserts) and fires in a normal session, so a trigger
disabled with alter table ... disable trigger or enabled only for replica
sessions doesn't count. A trigger with a when condition doesn't count
either, because it may skip the check, and an update of trigger counts only
for the columns it lists. The marker also covers a column the provider lists in
decidingColumns. Snapshots taken before this version have no markers.
Helper bodies come from the database, or from your SQL files when the snapshot doesn't have them. Column grants need a snapshot taken with this version; older snapshots only show table grants.
BS214
Error: permission the provider's SQL functions don't fully answer in a
Storage or Realtime policy. An access policy on a bucket or topic reaches
the authorization provider's
functions through its sql templates, or through the access contract under
the provider access model. Those functions decide by role and scope, so a
permission with other conditions (such as ownerId = principal.id) would grant
every object or topic in the scope. Doctor reports every key whose
authorization.permissions entry isn't sqlComplete: true: a key marked
false, a key without the flag, a key the provider doesn't list, and every
key when the provider lists no permissions. better-supabase gen refuses to
write those bucket policies.
Doctor checks the buckets in the config and the bs_ policies on
storage.objects and realtime.messages in your SQL files, matching the
provider's idsWith and isPlatform templates. It also reports a scope the
provider doesn't declare, and a key checked at a scope its entry's scopes
doesn't list.
It warns when a bucket's sql templates differ from the provider's idsWith
and isPlatform, because a copy goes stale when the provider changes. Set
sql: "provider" so better-supabase gen writes the provider's templates.
BS215
Warning: policy calls a helper per row that could run once. A call such
as current_tenant_id() takes no column of the row, so its result is the same
for every row. Written bare, Postgres may run it for each row; wrapped as
(select current_tenant_id()), it runs once per statement as an InitPlan.
Splinter's auth_rls_initplan (BS200) covers auth.uid() and auth.jwt();
this check covers your own helpers. Immutable functions are skipped.
BS216
Info: foreign key without an index. Deleting or updating a referenced row
scans the referencing table for each row, and joins on the key can't use an
index. Add an index whose leading columns are the key's columns, in any order.
A partial index counts when its where only skips rows whose key is null
(where customer_id is not null), because those rows reference nothing.
When BS200 runs, splinter's unindexed_foreign_keys reports the
tables it covers and this check skips them; on a saved snapshot, or when the
advisor can't run, this check reports every table.
BS217
Warning: tenant foreign key that can cross tenants. With the
memberships extension, a tenant table that references another tenant
table by id alone can point at a parent in another organization: RLS checks
each row, not the pair. Reference the tenant column as well, backed by a
unique key on the parent:
alter table public.customers add unique (id, organization_id);
alter table public.notes add foreign key (customer_id, organization_id)
references public.customers (id, organization_id) on delete cascade;BS218
Info: soft-delete table without a partial index. A table with a nullable
deleted_at or archived_at column is mostly read for its live rows. A
partial index with where deleted_at is null stays small and matches those
queries:
create index customers_active_idx on public.customers (organization_id, created_at desc)
where archived_at is null;Snapshots from before index predicates were recorded accept any partial index.
BS219
Warning: containment filter on a column without a GIN index. @>, <@,
?, ?|, ?& and && on jsonb and array columns, and the
.contains(), .containedBy() and .overlaps() filters, can only use a GIN
index; without one, every query reads the table. Doctor looks in the
policies, the functions in the exposed schemas and the files in
tooling.doctor.sources. A function counts for a table only when its own
definition names the table and filters the column. A negated test,
not (meta ? 'k'), and one inside a case expression don't filter rows
through an index, so they don't count. Use jsonb_path_ops when you only filter with @>, which
makes the index smaller; leave it out for ?:
create index notes_meta_idx on public.notes using gin (meta jsonb_path_ops);BS220
Info: column type to avoid. timestamp drops the time zone, varchar(n)
and char(n) only add a length limit that a check constraint on text
states as well, money rounds by locale, and json is parsed again on every
read. Use timestamptz, text, numeric and jsonb.
BS221
Warning: direct database connection in a serverless app. Each serverless
or edge invocation opens its own connection, so through the direct host
(db.<ref>.supabase.co, which is also IPv6 only) or the session pooler on
port 5432 they run out of max_connections. Use the transaction pooler on
port 6543 (postgres://postgres.<ref>:<password>@<region>.pooler.supabase.com:6543/postgres).
Doctor checks the env files when the sources export route handlers, a
runtime, a fetch handler or Deno.serve, or an env file sets VERCEL
variables. The message names the variable, never its value.
BS222
Warning: column that can exceed a JavaScript number. int8 and numeric
decode as number by default, which matches supabase gen types, but a
number loses precision past 2^53 (about 15 to 17 significant digits). Doctor
reports int8 identity and sequence columns, which keep growing toward that
limit, and numeric columns, which usually hold exact amounts. Set
gen.codecs.int8 to "bigint" or "string", or gen.codecs.numeric to "string",
in better-supabase.config.ts (codecs), or add BS222
to tooling.doctor.ignore when the values stay small.
BS223
Info: function returns an int8 or numeric scalar. PostgREST sends a
function's scalar int8 or numeric result, or an array of them, as a JSON
number, so a value past 2^53 (about 15 to 17 significant digits) loses
precision before any codec sees it. db.$rpc casts the codec columns of
table and record results to text (function
results), but a scalar has no column
to cast. Return it as text (returns text, select total::text) when it can
grow that large, or add BS223 to tooling.doctor.ignore when it stays small. Doctor
can't see inside a json or jsonb result: cast large numbers to text when
you build it.
BS224
Warning: Data API role without a timeout. Without statement_timeout,
one slow request holds a connection until the query finishes. Without
idle_in_transaction_session_timeout, a client that leaves a transaction
open keeps its locks and its connection. PostgREST applies the settings of
anon and authenticated to each request, and the login role's
(authenticator) apply when the request role sets none, so doctor reports a
setting only when neither sets it. A value of 0 turns the timeout off and
counts as unset. BS211 lists the current values. Set them in a
migration:
alter role authenticated set statement_timeout = '8s';
alter role authenticated set idle_in_transaction_session_timeout = '60s';
notify pgrst, 'reload config';Saved snapshots from before role settings were recorded skip it.
BS225
Info: pg_stat_statements is not installed. The extension records the
time and calls of each statement. --stats (BS209), BS208
and the Supabase query performance report read it, so without it nothing
shows which queries are slow. Doctor checks pg_extension on every run
against a database; with --stats, BS209 reports it instead. Install it in a
migration:
create extension if not exists pg_stat_statements with schema extensions;BS226
Warning: prepared statements through the transaction pooler. The
transaction pooler on port 6543 gives each transaction any server connection,
so a named prepared statement from one transaction doesn't exist in the next
and the query fails with prepared statement does not exist. When an env
file or a file in tooling.doctor.sources has a :6543 URL, doctor reports each
source file that imports postgres.js without prepare: false, and, when the
sources use Prisma, each :6543 URL without pgbouncer=true:
const sql = postgres(process.env.DATABASE_URL!, { prepare: false });pg, which better-supabase/postgres uses, sends unnamed statements and
works through the pooler as it is. This is the reverse of BS221,
which asks serverless apps to use the pooler.
BS227
Info: offset pagination or exact counts. pagination: "offset" on a
resource or list reads and skips every row before the page, so late pages get
slower as the table grows, and rows written between requests shift the pages.
count: "exact" counts every matching row on each request, and so does a
.count() call without a mode. Doctor reports each line in
tooling.doctor.sources that sets either. Use pagination: "cursor"
unless the UI needs page numbers, keep [api] max_rows set so no request
reads a whole table, and use count: "planned" or "estimated" on tables
that can grow large.
BS228
Warning: app table column drifted from tables. A column of an app
table has a different type or nullability in the database than
tables gives it, usually after an edit by
hand or a migration that wasn't regenerated. gen types the column from
tables, so the app reads values the database doesn't hold. Change
tables to match the database, or run better-supabase upgrade and
apply the migration it generates. When rows depend on the old shape, follow
the expand-and-contract steps that apply --preset prints for a breaking
change. A table or column the database doesn't have yet is left out, since
that is a migration not applied.
BS229
Warning: index built without concurrently. BS229 to BS235 read the
migrations that haven't run yet, statement by statement, and flag the ones
that lock a table that already holds rows. With --db-url, doctor checks the
migrations missing from supabase_migrations.schema_migrations. Offline, it
checks the migrations after tooling.doctor.migrationSafety.since, or only the newest
migration when since is unset; init and add --adopt set since to the latest
migration so older files aren't reported. Tables a migration creates are
skipped, since nothing reads them yet.
create index blocks every write to the table until the index is built. Use
create index concurrently, and put it in a migration of its own, because it
can't run inside a transaction.
BS230
Warning: foreign key or check validated in the same step. Adding a foreign
key or a check scans the whole table while it holds a lock that blocks writes.
Add the constraint with not valid, then run
alter table ... validate constraint ... in a later statement, which scans
without blocking writes. A references or check written inline in
add column can't be not valid, so BS230 flags it too: add the column,
then the constraint. For a check, BS236 tells you when the rows
pass and doctor --yes validates it.
BS231
Warning: column change that rewrites or scans the table.
alter column ... type rewrites every row under an exclusive lock, unless the
types are binary compatible. set not null scans the table under the same
lock. For a type change, add a new column, backfill it, and switch reads to
it. For set not null, first add check (column is not null) not valid,
validate it, and then set not null, which Postgres then accepts without a
scan. BS231 also flags add column ... not null without a default, which
fails once the table has rows: add the column nullable, fill it with
db backfill, and then add the check.
BS232
Warning: column added with a volatile default. A default like
gen_random_uuid(), random() or clock_timestamp() makes Postgres write
the value into every existing row while it holds an exclusive lock. now()
and constants are stored once and don't rewrite. Add the column without a
default, backfill it in batches, and then set the default.
BS233
Warning: no lock_timeout before an exclusive lock. A migration that
alters an existing table waits behind long-running queries for its lock, and
every query that arrives after it waits too. Start the migration with
set lock_timeout = '5s'; so it fails fast and can be retried instead of
stalling the app. A statement that only runs validate constraint takes a
share update exclusive lock, which doesn't block reads or writes, so it
doesn't count.
BS234
Info: drop or rename. Dropping or renaming a table or a column breaks the
deployed app until it ships the matching code. Rename in steps: add the new
name, write to both, move the reads, and drop the old name in a later release.
apply --preset prints these steps for a breaking change.
BS235
Warning: a better_supabase function dropped with a new signature. When
a better-supabase release changes a function's arguments, a schema diff drops
the old function and creates the new one. 0.12 did this for audit(), which
went from 9 to 11 arguments. A call with positional arguments, or a grant that
names the old argument list, fails once the migration runs. Doctor flags a
drop function better_supabase.<name>(...) in an unapplied migration unless
the same file creates that function again with the same number of arguments.
Read the upgrade notes for the release, call the function
with named arguments, and grant on the new signature in the same migration.
BS236
Info: not valid check ready to validate. Expand and contract adds a
column nullable, adds check (column is not null) not valid so new rows must
fill it, backfills the old rows with db backfill,
and then validates the check. BS236 reads the checks the database holds as not
valid and tests each one against the rows. When no row fails it, the finding
carries the fix, and doctor --yes runs
alter table ... validate constraint ... without a statement timeout. That
scans the table but doesn't block reads or writes. After it, set not null on
the column needs no scan. When rows still fail, the finding names the
db backfill command for a not-null check; for the scope column of an
enriched app table, BS238 reports it instead. BS236 needs a
database, so a saved snapshot skips it.
Postgres checks a not valid constraint on every insert and update, so an update of a row the backfill hasn't reached yet fails until it fills the column. Add the check after the backfill when the app still writes those rows.
BS237
Warning: app table keeps permissive policies or grants of its own. When a
tables.<name> entry enriches a table your schema already creates, your own
policies on it stay: the entry names its policies bsb_<table>_<command>, so it
never replaces one of yours, even one named <table>_select. Postgres ORs permissive policies, so each one widens what
the entry's scope allows. In tenant scope the restrictive bsb_tenant_scope_*
policies still keeps every row inside the member's tenants, so BS237 is a hint
(info): check that your policies need no role or permission the scope's
policies ask for. In user scope, or without bsb_tenant_scope_*, nothing
narrows them, and a signed-in user reaches every row they allow. Drop your
policies, or recreate them as restrictive.
Enriching never revokes your grants either; it only adds the ones the scope
needs. BS237 lists the select, insert, update and delete grants that anon and
authenticated hold beyond that. While row level security filters the rows
this is a hint (info). It is a warning when the entry restricts columns
(access or encrypted), because a table-level grant reaches every column:
revoke it in your schema and the entry's column grants take over. BS111 reports
truncate, references and trigger grants.
BS238
Warning: rows of an enriched app table without an owner. Enriching a table
that already has rows adds the scope column (organization_id, or user_id in
user scope) nullable, with a not valid not-null check. The scope's policies
match nobody for a row without a value, so only the service role reads or
writes it, and updates to it fail the check. BS238 counts those rows and names
the db backfill command that fills them; then
doctor --yes validates the check (BS236). BS238 needs a database,
so a saved snapshot skips it. The check is not valid on purpose; see
Your own schemas.
BS239
Retired. It reported @supabase/pg-delta or @supabase/pg-topo as not
installed. better-supabase now installs both as dependencies, so the check can
no longer fail, and the code stays reserved. See BS709 for the
opposite mistake.
BS240
Warning: enum value renamed or removed. A migration that isn't applied yet
runs alter type ... rename value or deletes from pg_enum. Rows and app code
that still use the old value break once it runs, and Postgres can't drop a
value from a type a column uses. Editing pg_enum by hand corrupts indexes and
stored data. Create the new type, move the column with
alter column ... type ... using, then drop the old type. The steps are in
removing an enum value.
BS241
Warning: embedding jobs read too often. An app table with embedding
queues each changed row on the pgmq queue <table>_embed, and the drain reads a
message again after 60 seconds until the worker applies it. A message read five
times or more is a job the worker can't finish: the embedder refuses the text, or
the worker URL or token is wrong. The row keeps no vector. BS241 lists the queues
that hold such messages. Fix the cause, then delete the message with
select pgmq.delete('<queue>', <msg_id>). BS241 needs a database, so a saved
snapshot skips it.
BS242
Warning: embedding worker requests fail. The drain posts each batch to the
worker with pg_net, which keeps the answers in net._http_response for six
hours. BS242 counts the responses of the last hour that have an error or a
status of 400 or more, when an app table has embedding or
blocks.knowledge.options.autoEmbed is on. Check that the Vault secrets
embedding_worker_url and embedding_worker_token match the deployed worker.
BS242 needs a database, so a saved snapshot skips it.
BS243
Warning: security definer helper holds a large literal. A
security definer function whose body holds a quoted literal above 1 KB, such
as a permission map or a JSON catalog. Postgres parses the literal again on
every call, and a policy helper runs once per table per statement. Store the
data in a table, or parse it once per transaction and keep it with
better_supabase.memo_get and memo_set.
BS243 reads the SQL files, so a saved snapshot works too. It measures the quoted literals inside a function body and ignores the quote that wraps the body itself ($function$ ... $function$), so a long body with short literals is not reported.
BS244
Warning: schema cache pressure. PostgREST loads every table, function and
relationship of the exposed schemas into its schema cache at start and after
each notify pgrst, 'reload schema'. BS244 reports an exposed schema with more
than 1500 tables and functions, and generated module SQL above 2 MB.
Two changes keep the cache small. Set gen.api.expose to "used" so gen
writes API wrappers only for the block functions your code calls (list the
rest in gen.api.exposeAlso; see gen).
And run DDL in one batch per deploy: every migration that ends a statement with
a schema change makes PostgREST reload, so put all of a deploy's DDL in one
transaction and send one reload.
Drift
BS245
Warning: a task pipeline lacks a stage an option names.
blocks.tasks.options.hold.stage, claims.startStage and claims.expiredStage
name a stage by key or { category }. A hold in a pipeline without that stage
raises TASK_HOLD_STAGE_MISSING, and a claim or an expiry in one leaves the
task where it is. BS245 lists each live pipeline of the task subject type that
has no live stage for an option that is set. Add the stage, or point the option
at a category every pipeline has. BS245 needs a database, so a saved snapshot
skips it.
BS260
Warning: code uses a name that api/naming.json renamed. Doctor reads the
app sources in doctor.sources for an export, type, subpath
or environment variable named in the rename table, which the
Naming page lists. The old names have no alias. Run better-supabase codemod naming to rename them.
BS301
Warning: soft delete hidden by a select policy. After an update, PostgREST reads the row back through the select policy. If that policy hides rows where the soft-delete column is set, the trash extension's delete fails with an RLS error. Filter deleted rows in queries instead; the trash extension already does.
BS302
Warning: bucket differs from the config. A bucket in buckets is missing
from the database, or its public, file size limit or MIME types differ.
When the Storage version has the columns, versioning and lifecycle are
compared too (generated lifecycle rule ids are ignored). Update the config,
or run bucket.apply(client) to set the bucket through the Storage API.
BS303
Error: generated code is out of date. The generated module doesn't match
the database, so types and metadata are wrong. Run better-supabase gen. This
is the same check as gen --check.
BS304
Warning: SQL module files are out of date. A module in blocks differs from
the version this release ships. Doctor renders the files with the same layout
as upgrade (grants from policies, session policies, audited tables and the
vector schema), so the two agree on what is out of date. Run better-supabase upgrade, then
supabase db schema declarative sync (supabase db diff on migra) to create
a migration. Under database.sql.workflow: 'migrations', doctor compares against the
newest *_better_supabase_modules.sql migration instead, and upgrade
writes the new one; apply it with supabase migration up.
A file whose @bsb-hash line no longer matches its SQL was edited by hand.
upgrade leaves that file alone. Move the change into your own schema file
or a SQL hook, or pass --force to overwrite it. A block file that no
installed block renders any more is reported too, and upgrade removes it
unless it was edited by hand.
For the read-sets module, doctor imports the modules in readSets and
compares the functions they compile to. If a module can't be imported,
doctor skips that file instead of reporting it.
BS305
Warning: live query table without change broadcasts. A table in
database.realtime.tables has no bsb_realtime trigger, so
live queries never hear about its changes. Run
better-supabase add realtime-tables, then
supabase db schema declarative sync.
BS306
Warning: Realtime delete events without keys. A table in the
supabase_realtime publication has replica identity nothing, or default
without a primary key, so postgres_changes delete events carry no keys. Add a
primary key, or run alter table ... replica identity full.
BS307
Error: custom SQL module without its contract. A module in blocks uses
ownership: "custom", so the app writes the functions other modules and the
TypeScript APIs call. With a database connection, doctor compares each
function's argument and return types with the contract; without one, it looks
for a create function in supabase/schemas and the migrations. Write the
function, or switch the module to managed, which also runs over tables you
already have. better-supabase blocks view <module> --sql lists the signatures.
BS308
Warning: tenant claim the hook does not write. With the memberships module and
blocks.permissions.activeTenant: 'claim', current_tenant_id() and the
memberships extension read the active tenant from the auth.tenant.claim claim, at the
top level or in app_metadata. With --as <user id>, doctor calls the custom
access token hook for that user and warns when neither is in the claims it
returns. Write the claim in the hook, or, for apps that pick the tenant from
the URL or a profile, use the default 'resolver' (with
ServerOptions.tenant) or { profileColumn }.
BS309
Warning: deprecated SQL module symbol. A file in supabase/schemas or a
policy uses a function, table, column or claim that a SQL module in blocks
deprecated or removed, such as better_supabase.current_org_id() or the
org_id claim. A deprecated symbol keeps a compatibility wrapper for at least
one minor release; a removed one fails at run time. The message names the
replacement. A renamed column such as memberships.org_id also counts
unqualified (m.org_id) in a statement that names its table. Block files and
migrations are skipped, and so is a claim the config maps in claims. Tables
and columns a block maps onto the app's own, and those of a module in custom
mode, are the app's names and are never reported.
BS310
Warning: duplicate block trigger. A table has bsb_updated_at and another
trigger whose function looks like updated_at, moddatetime or touch, or
bsb_audit and another audit trigger, so both run on every write. Drop the
older trigger, or call track_updated_at() or audit() with
replace_trigger => true in a migration.
BS311
Warning: SQL module behind its current version. A module file's
@bsb-block line, or its row in better_supabase.blocks on a live database,
records an older version than this release ships. Run better-supabase sql upgrade, which writes the forward steps into a migration and rewrites the
files, then create the schema migration. BS304 skips files this check reports.
BS312
Error: block schema exposed through the Data API. [api] schemas in
supabase/config.toml lists better_supabase or a schema a module in blocks
sets. Block schemas hold internal tables and helpers that authenticated can
execute so policies can call them; exposing the schema makes them callable over
REST and RPC as well. Remove the schema from [api] schemas and from the
exposed schemas in the dashboard, and set blocks.<module>.api to an
exposed schema such as api: add writes security invoker entry points
there for the module's client functions, and rpcTransport(supabase, { schema: "api" }) calls them. Doctor reads [api] schemas for every exposure check and falls
back to schemas in better-supabase.config.ts without a config.toml.
BS313
Warning: rate limits not wired to PostgREST. The rate-limit module is in
blocks, but on the live database pgrst.db_pre_request for the
authenticator role is unset, or names a function whose body doesn't call
better_supabase.check_request(), so Data API writes are never counted. Apply
the migration better-supabase add --adopt writes, which sets the hook when no
other one is set, or call check_request() from your own pre-request
function. Doctor needs a database connection for this check. With
blocks["rate-limit"].options.preRequest set to false, the app calls
check_request() itself and BS313 does not run.
BS314
Warning: migration-only block option. A module in blocks sets an option
that only exists to match a schema the app already has: tokenStorage: "plain"
for invitations, secretStorage: "column" for credentials,
secretStorage: "column", statuses or an eventIdType or runIdType
other than text for webhooks, a blockSource or defaultSource for
the outbox, or values or metadataColumns for the audit log. The config
only accepts them when the block runs over a table the app already has.
Move the data to the managed default (hash the tokens, move the secrets into
Vault), then remove the option.
BS315
Error: table without an audit trigger. The audit module is in
blocks, and a table in schemas has no bsb_audit trigger, nor another
trigger that calls better_supabase.audit_row_change(), so its inserts,
updates and deletes are not in the audit log. Register it with
select better_supabase.audit('public.customers') in a schema file. Doctor
skips the block schemas and the app's tables that blocks run over; list other tables in
blocks.audit.options.exempt as { table, reason } entries, where table is
a schema.table glob (* matches any run of characters) and reason says why
its changes need no audit entry. { class: "no-tenant-column", reason } leaves
out every table that has no tenant column, which the audit helpers can't
register. A bare glob string still works, but doctor reports it as an error and
asks for the reason. A table whose comment carries @bsb audit-exempt reason="..." is exempt too, and a tag without a reason is reported here. Doctor only checks tables in schemas, and
a partition counts through its parent.
export default defineConfig({
blocks: {
audit: {
options: {
exempt: [
{ table: "public.*_archive", reason: "read-only copies" },
{ table: "public.sessions", reason: "high volume, no user data" },
],
},
},
},
});The same rule runs in pgTAP with
select tests.every_table_audited('public', array['sessions', '%_archive'])
(see testing).
BS316
Warning: legacy migra diff engine. The project keeps declarative schemas
in supabase/schemas or lists blocks, but supabase/config.toml has
no [experimental.pgdelta] enabled = true, so the Supabase CLI diffs the
schema with migra. Migra drops grants, comments and security_invoker on
views, and runs only while the stack is stopped. Projects from supabase init
and better-supabase init use pg-delta. To switch, add the table, remove
[db.migrations] schema_paths (pg-delta orders files by dependency), and
create migrations with supabase db schema declarative sync instead of
supabase db diff:
[experimental.pgdelta]
enabled = trueBS316 fires when database.sql.workflow is unset and the CLI detects migra (see
Workflows), or when the workflow is pg-delta and
config.toml doesn't turn it on yet. To stay on migra, set
sql: { workflow: 'migra' }; that and workflow: 'migrations' silence it.
BS317
Warning: bulk grant in a pg-delta schema file. Under pg-delta, a
grant ... on all tables in schema, on all routines in schema or on all sequences in schema statement in supabase/schemas that reaches anon,
authenticated or public has no dependency position. pg-delta can run it after the per-object revokes that narrow a
function or table, which re-opens them to anon and authenticated. Grant
each object by name next to its definition:
revoke execute on function public.recalculate_totals(uuid) from public, anon;
grant execute on function public.recalculate_totals(uuid) to authenticated;For objects created later, use Supabase default privileges instead of a bulk
grant: alter default privileges in schema public grant select on tables to authenticated;. The grants module writes
per-table grants from expose.
BS318
Warning: catalog loop in a pg-delta schema file. A do block in
supabase/schemas that reads information_schema or pg_catalog (pg_class,
pg_tables, ...) and executes statements runs, under pg-delta, before the
tables it looks for exist. It creates nothing, and the diff never sees the
triggers, grants or policies it was meant to add. Write the statements as
static SQL, one per table, or call a per-table function once per table, such
as select better_supabase.audit('public.invoices'); or
select better_supabase.track_updated_at('public.invoices');.
BS319
Error: SQL alters a reserved role. A schema file, SQL module or migration
alters, drops or changes the memberships of a role that supautils reserves on
Supabase: supabase_admin, supabase_auth_admin, supabase_storage_admin,
supabase_functions_admin, supabase_read_only_user,
supabase_realtime_admin, supabase_replication_admin, supabase_etl_admin,
dashboard_user and pgbouncer. The statement works on a local superuser
connection and fails on a hosted project. authenticator, authenticated,
anon and service_role accept alter role ... set and reset, such as
alter role authenticator set pgrst.db_pre_request = '...', and nothing
else. Granting privileges on objects to a reserved role
(grant usage on schema auth to supabase_auth_admin) is not flagged. Create
your own role for anything else.
BS320
Warning: table without the session policy. The sessions module is in
blocks, and a table with RLS in schemas has no restrictive policy
that calls better_supabase.session_active(), so a token whose session was
signed out, or whose user was banned or deleted, keeps reaching the table
until it expires. Set blocks.sessions.options.policies to true and
run better-supabase upgrade to write the policy on every table, or add it
by hand. Doctor skips the block schemas and the app's tables that blocks run over; list
other tables in blocks.sessions.options.exclude as schema.table
globs. See Ended sessions.
BS321
Warning: extension missing from the migrations under pg-delta. A
create extension in supabase/schemas, a SQL module's file included, that
no migration in supabase/migrations repeats. pg-delta can leave an
extension that owns its own schema, such as pgmq, out of the generated
migration, so a database built from the migrations (a branch, CI or
production) lacks it. For a module that owns such an extension, run
better-supabase upgrade: it writes the extension into a migration that
runs before the schema migration. For your own schema files, add
create extension if not exists <name>; to a migration that runs before the
one that uses it. The rule stays quiet until the project has a migration.
BS322
Warning: audit registration of a dropped table. The audit module is in
blocks, and better_supabase.audited_tables on the live database has
a row whose table no longer exists. Since the module installs the
bsb_audit_forget_dropped event trigger, dropping a table deletes its row,
but a table dropped before that keeps it. Run better-supabase upgrade
and apply the migration better-supabase add --adopt writes: the module's data
file deletes registrations whose table is gone. Doctor checks this only
against a database.
BS323
Warning: module event trigger missing. A module in blocks
creates an event trigger (bsb_audit_forget_dropped for audit,
bsb_ensure_rls for rls-guard) that the live database lacks, or, without
a database, that no migration in supabase/migrations creates. Event
triggers belong to no schema, so a schema diff limited to some schemas
(supabase db schema declarative sync -s ...) leaves them out of the
migration, and dropped tables keep their audit registrations or new tables
get no RLS. Run better-supabase upgrade, then better-supabase add --adopt:
the module's data file repeats its event triggers, so the data migration
creates them. Run the declarative sync without -s from then on.
BS324
Error: shared roles table without a role condition. Under the
provider model, the tenant module's roleThrough and the invitations
module's platformRoles.through name the same roles table, and one of them
has no where. That side then resolves a role id or key of the other kind:
an organization invitation, its accept or update_member_role can grant a
platform role, or a platform invitation a tenant role. better-supabase sql sync refuses the config. Set where on both, a condition on the roles row
{row} such as {row}.scope = 'organization' and {row}.scope = 'system'.
A roleThrough from the provider's roleSources has no where, so set
blocks.memberships.options.roleThrough in the config.
BS325
Warning: audit log readable only as the service role. The audit module
defaults eventRoles to service_role and readPolicy to false, so
audit.list() under a user session is 403. Set options.readPolicy: true
and include authenticated in options.eventRoles when the app lists the
log as the signed-in user.
BS326
Warning: admin Auth call without a secret key in env files.
deleteAccount and bsb.admin() need SUPABASE_SECRET_KEY. Add it to
.env.local (and the hosted environments), listed without a value in
.env.example.
BS327
Warning: aal2 required without MFA enabled. The app calls
requireAal('aal2'), but [auth.mfa.totp] in config.toml does not set
enroll_enabled and verify_enabled to true, so no user can satisfy the
check.
BS328
Warning: rpc() on a Supabase Lite SQLite driver. [db] driver in
config.toml is sqlite-postgres or sqlite, and a file in
tooling.doctor.sources calls $rpc, .rpc() or rpcTransport. Lite has no
rpc() on SQLite, so the server returns an unsupported error without
sending the request. Switch [db] driver to pglite or postgres, or
replace the function with table queries. See
Supabase Lite.
BS329
Warning: feature Supabase Lite does not implement. config.toml sets
[db] driver, so the project runs on Supabase Lite, and a file in
tooling.doctor.sources uses Realtime (better-supabase/realtime or .channel())
or Edge Functions (functions.invoke()). Lite implements neither on any
driver. Run the full Supabase stack for that feature, or move the project
with supabase lite upgrade.
BS330
Error: app table without a column a block uses. A block runs over a
table of the app's, and the live database lacks a column the block's SQL
names, so the block's functions fail until that column exists. Doctor reads
every column the module's SQL names: the ones in blocks.<name>.columns
and the defaults for the unmapped ones, leaving out the columns mapped to
null and the optional columns the config doesn't name. A table without an
optional column keeps that feature off (ADR 0580). Blocks don't add columns to
your tables, so add the column to your schema (codemod owned-columns
declares the block's columns) or map it. Tables that a block uses only when blocks.<name>.tables maps them
(the notifications deliveryEvents and suppressions, the audit
restricted table and the invitations platformInvitations) are checked
once they are mapped, and skipped otherwise, as the generated SQL skips them.
Apply the block's migration, which adds the missing column with
add column if not exists, or map the logical column to the column that
holds it, or to null when the module allows that. A column on a table that
blocks.<name>.on names isn't added by the block: map it or add it yourself.
Needs a database.
BS331
Error: subject registry names a missing table or column. An entry in
config.recordTypes names a table that the snapshot lacks, or a column the
table lacks: id, tenant, title, deletedAt, a url placeholder,
rank or a search column. subject_title, subject_url, can_subject
and every module that falls back to the registry fail when they run. Point
the entry at the existing table or column, or add it. Doctor skips tables in
schemas the snapshot did not read.
BS332
Warning: subject table without RLS. A table in config.recordTypes has row
level security disabled. can_subject treats a row the caller can read as
visible, so every signed-in user passes the visibility half of the check for
every row. Enable RLS and add the policies that scope the table.
BS333
Warning: admin() inside a workflow-editor executor. A source file that
runs workflow-editor steps (it uses executeGraph, nodeRunReporter or
GraphStepCall) calls admin(). A file that only builds the builder's
service transport or starts runs with graphStarter isn't reported. The steps
then run with the service role's rights, so a workflow keeps running after its
publisher is demoted. Call builder.versions.runAs(call.version) in each step
and query with the claims it returns. See
publisher rights.
BS334
Info: a policy checks a role name instead of a permission. An app policy
or a function in schemas calls member_organization_ids(),
has_organization_role() or organization_member_role(). Under an
authorization provider these take membership from its memberIds, but a role
list still names roles the provider may not have, and a role check skips the
delegation cap. Check a permission with
better_supabase.tenant_ids_with('<permission>') or member_can() instead.
The modules' own bs_ policies aren't reported.
BS335
Warning: partitioned table created unpartitioned. A block's
options.partitioned is on, but its table was created before it: the primary
key is id alone, so the purge deletes row by row instead of dropping whole
months. The rule checks these tables in better_supabase:
| Block | Table |
|---|---|
audit | audit_events |
outbox | outbox_events |
usage (with options.history) | usage_history |
webhooks | webhook_deliveries |
notifications | notification_delivery_events |
Postgres can't convert a table in place. Copy the rows into a partitioned table and swap the names in a maintenance window, or turn the option off.
BS336
Warning: flag past its expiry. The flags table has an expires_at column
(a column your schema files add to the flags table), and a flag on the live database that
isn't archived has an expires_at in the past. A release flag that outlives
its rollout keeps a dead branch in the code. Remove its checks, then archive
the flag (flags.upsert(key, { archived: true })), or move expires_at when
the flag stays. The finding names the owner column when the table has one.
See owner and expiry.
BS337
Warning: broadcast trigger sends whole rows. A trigger function calls
realtime.broadcast_changes(..., new, old) or sends old_record and record
through realtime.send(), and has no better-supabase: payload row comment.
Every subscriber of the topic then sees every column, including ones their
column grants hide. Hand-written trigger functions are reported. Regenerate the trigger with topic.trigger(), whose default payload
sends the primary key and the topic values, or pass payload: "row" to keep
whole rows on purpose. See
row changes.
BS338
Info: gen.functions.notNull entry a comment tag could replace. gen reads
@notNull and @notNull(a, b) from a function's comment, so the promise can
live next to the SQL instead of in better-supabase.config.ts. Doctor lists
each gen.functions.<name>.notNull entry for a function in the read schemas: one
the function's tag already matches (remove the entry), one with no tag (add
the tag the finding prints, then remove the entry), and one that differs from
the tag, where the config entry wins. See
nullable function results.
BS339
Warning: expose excludes a column the table doesn't have. An expose
privilege such as select(*, -token_hash) grants every declared column but
the excluded ones. When the table has no token_hash column, the exclusion
excludes nothing, and a renamed secret column is granted under its new name.
Remove the exclusion, or exclude the column's new name. See
column privileges.
BS340
Info: a tenant foreign key has no same-tenant trigger. With the memberships
block, doctor lists each single-column foreign key between two tables that
both have the tenant column, when the key doesn't include that column and
the table has no bsb_same_tenant_<column> trigger. The foreign key checks
that the referenced row exists, not that it belongs to the same tenant. Add
the reference to blocks.memberships.options.sameTenant, or set
sameTenant: { auto: true }. See
references within one tenant.
BS341
Warning: a data export includes a column that looks like a secret. A
data export writes every column of the tables it reads, except the ones in
omit. Doctor reports each column of an exported table, including the ones
autoTables finds, whose name contains token, secret, _hash,
password, api_key or license_key, when no omit and no omitPattern
leaves it out. Add the column to the table's omit, keep the table out of
exports with export: false or autoTables.exclude, or set
blocks.data-lifecycle.options.omitPattern. See
data lifecycle.
BS342
Error: an enum column of the app's that a module writes as text. A
module writes a text parameter or a computed text value into a column of a
table the app already has, and the snapshot declares that column as an enum;
string literals are fine. Postgres has
no implicit cast from text to an enum, so the module's functions fail when
they run. Change the column to text with a check constraint on its values.
The columns the module casts to their declared type may stay enums or
domains: status columns, the tags kind and subjectType, the numbering
entity and the profiles locale. upgrade and
better-supabase add --adopt refuse the same columns when the schema files declare
the enum. See
existing tables.
BS343
Error: a partition without row level security. A table in schemas is a
partition of a table that has RLS on, but RLS is off on the partition itself.
Policies belong to the parent, so a query that names the partition (for
example select * from decision_events_default) never applies them, and a
role with a grant on it reads every row. The default partition counts too.
Run alter table <partition> enable row level security, and enable RLS in
the code that creates new partitions. The partition functions of the SQL
modules (ensure_partitions, defaultPartition) already do this for the
outbox, usage, webhook delivery, notification and audit tables
(ADR 0038).
In pgTAP, tests.partitions_have_rls('schema') checks the same thing.
BS344
Warning: app webhook endpoints without a format. webhooks runs
over an endpoints table of the app's, that table maps no format column, and
blocks.webhooks.options.defaultFormat isn't set. Every endpoint then
gets defaultFormat, whose default changed from the 0.8 body (standard)
to cloudevents in 0.9, so receivers built for the old body break with no
change to the config. The message says whether the table has no format
column or has one the config doesn't map. Set defaultFormat to the body
your receivers expect, or map columns.endpoints.format. upgrade refuses
the same config; doctor reports it for configs it loads without that check.
See connectors.
BS345
Warning: attachments subject on the block-wide upload key with stricter
RLS. An attachments subject has no upload key of its own, so files are
attached with the block-wide attachments.upload key, but the subject
table's insert or update policies check more than tenant membership: a
permission key of their own, an owner or auth.uid() comparison, or another
condition. Any member of the tenant then attaches files to rows they can't
change. Reads aren't checked: the block's read policy already asks whether
the caller can read the subject row. Doctor counts current_tenant_id(),
tenant_ids_with, member_<tenant>_ids (and an authorization provider's own
*_ids_with and *member_*ids helpers), can('tenant', ...) and
member_can with the block's key as tenant membership, and a soft-delete
is null as neutral. A policy with an or branch that needs only membership
is wider, not stricter, and a table with no insert or update policy for
clients isn't reported, nor is a subject with upload: "subject", whose
uploads follow the table's own update policies. Set
subjects.<type>.permissions.upload in the registry to the key the table
checks, or blocks.attachments.on.<type>.upload: "subject". See
permissions per subject.
BS346
Warning: block on names an unknown record type. A block entry's on
lists a type, or has a key, that config.recordTypes doesn't register. The
block's SQL refuses such a type when gen renders the migration, so doctor
reports it first. An on entry that carries its own table registers the
type inline and isn't reported. Register the type in config.recordTypes, or
remove it from on. See record types.
BS347
Warning: block policy widens an app table's access. A block that runs
over one of your tables adds its own permissive policies there, named
bsb_<table>_<command> (such as bsb_teams_select), so they never replace
one of yours. Postgres ORs permissive policies, so when you have policies for
that command and none has the same condition, or true, for the same roles,
the block's policy can let a user reach rows yours keep closed. A block
condition that is yours with more and operands (such as the block's
authz_actor_may_write() check) is narrower, so it isn't reported either,
and so is the block's condition when it is one of the or operands of yours. A
command you have no policy for is the block's to grant, so doctor doesn't
report it. Doctor compares the conditions as text, so it also reports a
condition that means the same thing written differently. If the block's
condition is what you mean, repeat
it in your policy. Otherwise narrow the permission key the block checks, or
drop the bsb_ policy in a schema file that runs after the block's. Your
policy and the block's for the same command don't also count as an overlap
under BS207. When one of your policies covers the block's in this
sense, upgrade leaves the block's policy out of its file and says so in a
comment, so Postgres doesn't evaluate two policies for the same rows. When
your policies should govern the table on their own, set ownTablePolicies: "app" on the block or in database.sql: the block then adds no bsb_
policy there, and doctor doesn't report the table (see
keeping your own policies).
BS348
Info: app table keeps its own updated_at trigger. A block that runs over
one of your tables found a trigger of yours that keeps updated_at current
(one that calls set_updated_at, moddatetime or a function that sets
new.updated_at), so it adds no bsb_updated_at trigger there. Keep your
trigger firing on update. If you drop it, run better-supabase upgrade to add
the block's.
BS349
Warning: block writes through a view Postgres can't update. A block table
is mapped to one of your views, and the block's TypeScript API inserts,
updates or deletes its rows, but Postgres can't write through the view: it has
distinct, group by, a join, an aggregate or a set operation, or it is a
materialized view, and no instead of trigger. The block's functions that read
the view work; the API calls that write it fail. Write those rows to the table
under the view, add instead of triggers, or map the block's table to a table.
See Blocks over your schemas.
BS350
Warning: app table governs its policies but lacks one for a command. A
block runs over one of your tables with ownTablePolicies: "app", so it adds
none of its bsb_ policies there, and the table has no permissive policy for
a command one of those policies would have granted. With row level security
on, or off (the block's file turns it on), Postgres denies that command to
every caller, so the block's functions that run as the caller and its
TypeScript API find no rows for it. A missing select policy is a warning;
a missing write policy is info, since your app may not write through the
block. Add your own policy for each command your app uses, or set
ownTablePolicies back to block for that block.
BS351
Warning: app code writes a block's table directly. A source file matched
by doctor.sources calls .from("x").insert(), .update(), .upsert() or
.delete() with supabase-js, or create(), insert(), update(), upsert()
or delete() on the typed client's repository (db.webhookEndpoints.create()),
on a table a block creates, the tables blockTables(config).byBlock lists. The
block clients themselves (db.webhooks) are the API to use and are not
reported. The write skips the block's functions,
so its events, hooks and the checks it runs before a write don't run, and the
block's other tables can disagree with the row. A .from() without
.schema() counts when you have no table of that name in public, since a
client created with db: { schema } reaches the block's. Tables of yours that
a block runs over are yours to write and are not reported. Write the row
through the block's API that createBlocks
returns.
A write through your own view over a block's table counts too: with
create view public.job_attachments ... from better_supabase.attachments,
db.jobAttachments.update() and .from("job_attachments").insert() are
reported. Reads go through the view, writes go through the block.
BS352
Warning: plain secret column next to a block that encrypts it. One of
your tables has a text, varchar, char, json or jsonb column whose
name ends in credentials, token, secret or header_value
(access_token, client_secret, auth_header_value), and field-encryption or
the credentials module is installed. The
value sits in the row as written, so every role that reads the row, and every
backup, has the secret. With field-encryption, set encrypted: true on the
column under tables.<name>.columns in the config, or name it in the table's
@bsb encrypted tag. The block
then stores it as ciphertext under a Vault data key.
With credentials, move the secret to Vault and store a credential_ref jsonb
in its place. Block tables, columns already marked encrypted in the config
or in an @bsb encrypted tag, and names that end in another word, such as
token_hash, secret_id or credential_ref, are not reported.
If your own trigger seals the column, name its function in
tooling.doctor.sealTriggers (["public.seal_integration_secrets"]). A
before row trigger that runs one of those functions silences the finding
for the columns it fills, or for every column of the table when doctor can't
tell which ones it fills.
BS360
Warning: secret column outside Vault. One of your tables has a text,
varchar, char, json or jsonb column whose name ends in credentials,
token, secret or header_value, and neither
field-encryption nor the
credentials module is installed. The value
sits in the row as written, so every role that reads the row, and every
backup, has the secret. Store the value with vault.create_secret, keep the
returned id in a uuid column such as access_token_secret_id, and read it
through vault.decrypted_secrets in a security definer function. Block
tables, columns that a function in tooling.doctor.sealTriggers fills, and
names that end in another word, such as token_hash or secret_id, are not
reported. BS352 reports the same columns when field-encryption or credentials
is installed.
BS361
Warning: an app table's check rejects values a block writes. A block runs
over one of your tables, and the check constraint or enum on a column the block
writes rejects a value the block writes into it. The module's own table declares
the values it writes in a check (column in (...)) constraint, and the block
writes them through the column your config maps. A narrower check, such as one
that predates a new delivery status, makes the block's inserts and updates fail.
Widen the check constraint to accept every value the block writes, or add the
values to the enum. Doctor reads simple membership checks (in (...) and = any (array[...])), and leaves a check that also constrains another column, a
negation or an expression alone. A column with no check accepts every value and
is not reported. For the notifications block, the delivery status check must
accept pending, sent, failed, skipped, held and digested; see
digests.
BS362
Warning: update policy checks a read permission. A permissive policy for
update (or all) calls better_supabase.can(...) or
better_supabase.tenant_ids_with(...) with a key that ends in .read or
.view. Anyone who may read the row can then change every column of it. Check
a write permission in the policy. When only some columns need a stricter
permission, list them in
tables.<name>.columnGroups: the generated
trigger raises 42501 when a caller without the group's permission changes one
of them.
BS363
Warning: a partial index differs from the module's definition. create index if not exists never changes an index that already exists. When a module now
writes another where predicate for an index, such as the mapped status values
in the webhooks delivery indexes, a database set up earlier keeps the old
one. Doctor compares the string literals of each partial index in the module
files with the live index of the same name and table, and lists the ones that
differ. Drop the index, run better-supabase sql upgrade and apply the
migration. Needs a database; saved snapshots skip it.
BS364
Warning: an API wrapper is volatile around a stable function. A language sql wrapper without stable is volatile, so Postgres can't inline it into a
policy or cache it for the statement. The wrappers gen.api writes copy the
volatility of the function they wrap. Doctor lists a volatile security invoker
SQL function with the same name and arguments as a stable or immutable
function in another schema, which is how a wrapper from an older release looks.
Run better-supabase sql upgrade to rewrite it.
BS365
Warning: an update policy has no select policy. Postgres only updates rows the
caller can also select, so a table with a for update policy and no for select
or for all policy updates zero rows and reports no error. Add a select policy
with the same condition. Doctor reads the app's own schema files.
BS366
Error: a policy decides on user_metadata. raw_user_meta_data and
user_metadata are editable by the signed-in user, so a policy that reads them
lets anyone grant themselves access. Put authorization data in app_metadata or
in the authorization provider. A trigger may read raw_user_meta_data for
display fields; a policy never does.
BS367
Warning: a view skips the caller's row level security. A view runs with its
owner's rights unless it sets security_invoker = true, so it returns rows the
caller's policies would hide. Create the view with (security_invoker = true).
BS368
Info: a column uses timestamp or serial. timestamp has no time zone and
serial is the legacy form of an identity column. Use timestamptz and
generated always as identity.
BS383
Warning: a storage policy set has insert but no select and update. A storage
upload with upsert: true reads the existing object and then updates it, so it
needs insert, select and update policies on storage.objects. With
insert alone the first upload works and every overwrite fails. Add the select
and update policies, or turn upsert off. Doctor reads the app's own schema files.
BS384
Warning: a policy calls auth.uid() once per row. auth.uid(),
auth.jwt() and auth.role() called bare in a policy run for every row the
policy checks. Written as (select auth.uid()), Postgres evaluates the call
once per statement. Wrap each call in select.
BS385
Info: a policy column has no index. A policy that filters on
user_id = (select auth.uid()) runs that filter in every query on the table, so
the column needs an index that starts with it. A composite index puts the tenant
column first. Without one, Postgres reads the whole table. Doctor counts an
index, a primary key or a unique constraint that starts with the column.
BS386
Warning: a policy calls a volatile, PL/pgSQL or non-inlinable function per row. A policy
that calls a volatile function, or one written in PL/pgSQL, outside
(select ...) runs it once for every row the statement reads, and Postgres
can't hoist a volatile call. Wrap the call in (select fn(...)) so it runs once
per statement, or replace a per-row check with a set helper such as
tenant_id in (select tenant_ids_with('key')). A helper called inside
(select ...) is accepted even when it is volatile, and so is a set helper in
the from of a subquery whose arguments read no column of the row, such as
id in (select t.id from thread_ids('key') as t(id)): Postgres calls it once
and rescans its result. In a select policy, a function that is
security definer or has a set clause counts too, even a stable SQL one,
because Postgres never inlines it: can_note(notes, 'read') runs once per row.
A call that passes the whole row is accepted as the or fallback after a set check, as in
id in (select note_ids('read')) or can_note(notes, 'read'), because it then
runs only for rows outside the set, such as a row the statement itself inserted.
Policies named bsb_* belong to a block module and are left to upgrade. Doctor reads the policy
expressions and the functions they call from the catalog.
BS387
Info: many row-level triggers on one table. Every row-level trigger runs
once per row a statement writes. A table with six or more bsb_* row triggers
(search, audit, events, totals) multiplies the cost of each import or bulk
update. Use the statement-level form where a block offers one, such as
audit.statement, or skip the triggers an import doesn't need.
BS388
Warning: a search trigger on an import target has no import guard. An import
writes thousands of rows in one transaction. A search trigger whose function
neither checks better_supabase.import_run() is not null nor calls
better_supabase.search_enqueue (which defers the refresh to the end of the
transaction) rebuilds the search entry after every row. Run better-supabase upgrade so the search module skips
per-row refreshes while an import runs. Doctor reads the trigger function's
source in the schema files, so a function it can't find is left alone, and the
tables are the record types that blocks.imports.options.targets names.
BS389
Info: the audit log has no scheduled purge. better_supabase.audit_events
grows with every audited write until something calls
better_supabase.purge_audit_log(). Schedule it nightly with pg_cron or call
purgeAuditLog from the jobs drain route. Doctor accepts a call in the schema
files, the seeds, the app sources or a pg_cron job (it reads cron.job when it
has a database), and skips projects without an audit table. With
blocks.audit.options.retention set, the audit_retention job of
maintenance() purges the log and the rule stops.
BS390
Info: a redundant index. A non-unique btree index whose columns are the start of another index on the same table, with the same predicate, answers no query the longer index doesn't, and only slows writes. Drop it. Primary keys, unique indexes and expression indexes are left out.
BS391
Info: a parameter that is null or matched with any(). A function that
filters with param is null or col = any(param) can't use an index on col
once Postgres caches a generic plan, because the plan has to cover both
branches. Split the statement by whether the parameter is null, or set
plan_cache_mode = force_custom_plan on a PL/pgSQL function so the planner
folds the null. Doctor reads the functions in the app's schema files, not the
block modules'.
BS392
Info: a searched table has no trigram or sort index. A table with the search
option (@bsb search or a search_tsv column) has a GIN index on the tsvector,
which only serves full-text queries. A list that matches with ilike '%text%'
needs a GIN trigram index on the searched column, and a newest-first list needs
a btree index that contains created_at or updated_at. Add both in the schema
file.
BS393
Warning: import batches run close to the statement timeout. With --stats,
doctor reads import_upsert_batch from pg_stat_statements and compares its
mean time with the statement_timeout of the service_role, else the
authenticator, else the server. A mean above half of it fails once the table
grows or another job holds a lock. Send smaller batches, or raise the timeout of
the role that imports.
BS394
Warning: an app override of a block function has drifted. An app file that
replaces a block function marks it with -- @bsb-override-of schema.fn <hash>
above its own create function. The hash is the first twelve hex digits of the
SHA-256 of the block's function statement with its whitespace collapsed, and
doctor prints the current one in its message. When the block module's function
changes, upgrade leaves the override behind and it keeps the old behavior, so
doctor reports a recorded hash that no longer matches, and a tag whose target no
module declares. Diff the module's function against your copy, merge what
changed, then write the new hash. BS369 skips a tagged function. Doctor reads
every schema file.
BS395
Error: verify_jwt is off for a function that expects a user.
[functions.<name>] verify_jwt = false turns off the gateway's JWT check. A
function written with auth: 'user' relies on that check to refuse requests
without a token before any code runs. Turn verify_jwt back on, or verify the
token in the function and drop auth: 'user'. The mcp function is the
documented exception: it verifies the OAuth token itself, because the gateway
would reject the MCP client first. Doctor reads supabase/config.toml and the
files under supabase/functions.
BS396
Info: a seed file inserts one row at a time. A file under supabase/seeds
with ten or more single-row insert ... values (...) statements for one table
is slow to parse and run, because each statement is planned and sent on its own.
Write one insert with several value tuples, or insert ... select from
generate_series. Files that db seed --sample wrote are left out.
BS397
Warning: a schema file changes rows a data migration holds. A schema file in
the declarative layout holds structure. An insert, update or delete in it
runs on every sync, and when a migration or block data file writes the same
table, the rows have two owners. Remove the statement from the schema file and
keep the rows in the data migration or a seed. Files a block module wrote are
left out.
BS398
Warning: an app trigger replaces the same-tenant check without the tenant.
sameTenant.auto emits no check for a foreign key column that an app trigger
(any trigger not named bsb_*) reads or writes through new.<column> or
old.<column>, because the app is taken to guard it, and BS340 accepts that
column for the same reason. A trigger that touches the column but never mentions
the tenant column guards nothing about the tenant, so nothing checks the
referenced row. Compare the tenant of the referenced row in the trigger, or list
the reference in blocks.memberships.options.sameTenant so the block emits the
check. Doctor reads the trigger functions in the schema files.
BS399
Info: a large audit log is not partitioned. better_supabase.audit_events is
a plain table with an estimated one million rows or more, so the retention purge
deletes row by row and a date-range read scans one large heap. Turn on
blocks.audit.options.partitioned and call
better_supabase.convert_audit_log_to_partitioned() in a quiet period; the
procedure copies in committed batches and keeps reads open. The estimate is
pg_class.reltuples, so a table that was never analyzed reports nothing. Needs a
database; saved snapshots skip it.
BS369
Warning: an app file declares an object a block module declares. A table, view, function or type that both a block module file and one of the app's files create is defined twice, so the declarative diff keeps whichever file it reads last. Declare the object once: let the app file alter the block's table, or map the block to another name.
BS370
Error: a schema file asks for transaction=false. The line
-- pg-delta: transaction=false runs a file's statements outside a transaction,
so a failure halfway leaves the schema partly applied. Create the index
concurrently in a hand migration with a lock_timeout instead.
BS371
Warning: two schema files declare the same object. A function, policy,
trigger, index, table, view, type or sequence that two schema files both create
has two definitions, and the declarative diff keeps whichever file it reads
last. The helpers every block calls (actor_may_write, import_run, the memo
functions and the rest) live once in the prelude file, so a copy of one in a
module file means the file is older than the prelude: run
better-supabase upgrade, which upgrade --check also reports.
BS372
Warning: a do block in an app file creates objects. A do block that
runs create or execute builds objects at run time, so a schema diff can't
see them and reports them missing. Write the statements out as plain DDL.
BS373
Warning: an app file creates an object with if not exists. create table if not exists and create index if not exists skip the statement when an
object of that name exists, so a changed definition never applies. Write
create table and let the diff change the table.
BS374
Warning: a block module file inserts rows. A schema diff reads tables, not
rows, so a top-level insert in a block module file never reaches the database
from the sync. Rows belong in the module's data file, which upgrade writes into
a migration. The generator writes none; this finds a hand edit.
BS375
Warning: two policies decide the same way. Two policies on one table have the same command, roles and expressions under different names. Postgres ORs permissive policies, so the second adds nothing, and a restrictive pair checks the same condition twice. Delete one.
BS376
Warning: a migration creates an object no schema file declares. Under
pg-delta, supabase db schema declarative sync --strict-coverage fails for a
table, view, type or function that the migration history creates and the schema
files don't, because the next diff would drop it. Declare it in
supabase/schemas, or drop it in a migration. Objects in Supabase's own
schemas and objects a later migration drops or renames are left out. A history
with a do block reports nothing, because the block can rename or create an
object by name.
BS377
Warning: a schema file declares an object no migration creates. The other
direction of BS376: a table, view, type or function in supabase/schemas that no
migration creates is a change the sync has not turned into a migration yet. Run
supabase db schema declarative sync and review the migration.
BS378
Warning: a trigger aimed at a view. A before or after trigger on a view
never fires for the rows of the table under it. Put the trigger on that table, or
use an instead of trigger that writes it. Reads every schema file.
BS379
Error: a columns entry the render refuses. blocks.<name>.columns.<table>.<column>
is null for an optional column the view the block runs over lacks anyway, or
columns.<table>.tenant repeats sql.tenantColumn. The block already leaves out
a column its view lacks, and sql.tenantColumn fills every tenant column, so the
entry says nothing. Run better-supabase codemod config to remove the entries.
A null for a column the view has, or for a table you own, is fine.
better-supabase upgrade --check runs the checks of BS369 to BS375 that apply to
the installed block files (a helper two files define, an object two block files
declare, transaction=false, a top-level insert and duplicate policies) and
fails with a line for each.
Auth config
BS380
Warning: a check constraint mixes between with and or or. Postgres
rewrites x between a and b into two comparisons, so a check that joins a
between to other conditions reads back in another shape than the file declares,
and the next diff proposes the same constraint again. Write the comparisons out.
Reads the app's schema files.
BS381
Warning: a call names a block table that the app projects through a view. An
app view over a block table (public.job_attachments over
better_supabase.attachments) is what clients read: it names the columns they
may see, and better-supabase powersync streams syncs the same columns.
createNativeClient, powersyncEngine, attachmentQueueRoute or queryEngine
given the block table's name skips the view. The qualified name always counts;
the bare name counts when the view is called something else. Name the view
instead. Reads the app's schema files and the files in doctor.sources.
BS382
Error: a subject's config entry and its table comment disagree. The
@bsb subject tag on a table is the registry of the app's subjects, and a
subjects.<type> entry can set the same options. When both give an option
(table, id, idType, tenant, title, url, scope, deletedAt,
cascade) and the values differ, gen keeps the config's and the comment says
something else. Remove one, or make them agree.
BS353
Warning: declared link needs the relations block. A block declares a
conversion or relation link to another block, such as an order created from a
quote, and both blocks are installed, but relations
is not. The conversion still runs through the source row's origin_type and
origin_id columns, but no created_from or converted_to link is written,
so lineage reads find nothing. Run better-supabase add relations.
BS354
Warning: declared defaults are not applied to new organizations. An
installed block declares tenant defaults, such as the tax codes of a country,
but the seeds block is not installed, database.seed.defaults is false or
has onCreate: false, or organizations is not installed. Nothing calls
seed_tenant_defaults when an organization is created, so new organizations
start without the defaults. Run better-supabase add seeds, turn the config key
back on, or run better-supabase db seed --defaults for each organization.
BS355
Warning: seed variant is not declared. database.seed.defaults.variants
names a block that doesn't exist, or a variant the block doesn't declare.
better-supabase blocks lists the variants each block offers. Use one of them
or remove the entry.
BS356
Info: sample data file outside database.seed.sample.output. A file under
supabase/seeds starts with the comment better-supabase db seed --sample --out writes, but database.seed.sample.output points at another path. The
next run writes a second file instead of replacing it, and supabase db reset
loads both. Set database.seed.sample.output to the file, or delete it.
BS357
Error: a data file insert has no key. A block data file runs again in every
data migration that changes it, so each insert in
supabase/better-supabase-data ends with on conflict (...) or guards itself
with not exists. Without a key a second run adds the rows again.
BS358
Warning: an app seed writes a table a block seeds. A file under
supabase/seeds inserts into a table that a block data file also inserts into,
so both own its rows. Let the block seed the table, or keep the rows in your
seed and remove the block's. Files from db seed --sample are left out.
BS359
Warning: a seed function takes no locale. A function named
seed_<name>_defaults has no p_locale parameter. Defaults that depend on a
country need it, and seed_tenant_defaults passes it to every seed function.
Reads every schema file.
BS401
Warning: refresh token reuse interval is 0. With refresh token rotation,
server instances that refresh the same session at the same time need a reuse
interval, or all but one of them sign the user out. Use 10, the Supabase
default.
BS402
Info: long access token lifetime. better-supabase verifies tokens locally
instead of calling the auth server, so a revoked session stays valid until its
token expires. Keep jwt_expiry at 3600 or less; the proxy refreshes sessions
for you.
BS403
Info: local stack signs tokens with a shared secret. Hosted projects sign
with asymmetric keys. Run better-supabase dev keys so
local tokens verify through JWKS, the same as in production.
BS404
Error: Auth hook function grants. For every enabled
[auth.hook.<name>] in supabase/config.toml with a
pg-functions://postgres/<schema>/<function> URI, doctor introspects the
function, even in a schema outside schemas. Auth calls it as
supabase_auth_admin, which needs usage on the schema and execute on the
function. Nobody else should be able to call it: through the Data API, a
client could call the custom access token hook for any user id and read the
claims it adds. The finding lists the SQL that fixes it:
grant usage on schema rbac to supabase_auth_admin;
grant execute on function rbac.custom_access_token_hook(event jsonb) to supabase_auth_admin;
revoke execute on function rbac.custom_access_token_hook(event jsonb) from authenticated, anon, public;Add the statements to the schema file that defines the function and run
supabase db schema declarative sync: pg-delta carries function grants into
the migration. better-supabase doctor --fix-grants prints the block for
every hook at once, ready to paste into that file.
On the legacy migra engine (BS316), supabase db diff drops
function grants, so append the block to the migration it wrote:
supabase db diff -f auth_hook
better-supabase doctor --fix-grants >> supabase/migrations/<timestamp>_auth_hook.sqlUnder database.sql.workflow: 'migrations' there is no schema file, so the finding
says to put the block in a new migration and apply it:
supabase migration new auth_hook_grants
better-supabase doctor --fix-grants >> supabase/migrations/<timestamp>_auth_hook_grants.sql
supabase migration upWhen the function is the authorization provider's hook
(authorization.tokenHook.function, or a file with its markers.hook line),
the finding lets the provider write the grants instead, with its
grantsCommand when it sets one.
When a file already grants the function, the database is behind, and the
finding names that file. On migra only a migration with the provider's
markers.grants line counts, and the finding says to run
supabase migration up. With pg-delta the declarative schema file that
defines the hook counts too, and the finding says to run
supabase db schema declarative sync, then supabase migration up.
Doctor reads the declarative schemas, then the migrations newest first, and
points findings at the first file that declares the object. With pg-delta it
reads every file in declarative_schema_path (default supabase/schemas) in
name order. On migra it follows [db.migrations] schema_paths, then the files
no entry matches.
A hook whose function doesn't exist is reported at its config.toml line,
because every sign-in fails until it does. Snapshots taken before the hook
was configured skip it; run better-supabase gen --save-snapshot again.
BS405
Warning: custom access token hook shape. Auth runs the hook on every
sign-in and token refresh. Declare it stable and give it
set search_path = '', qualifying every table it reads.
The claims it returns travel with every request, in the session cookie and in
the Authorization header. With --as <uuid>, doctor calls the hook for that
user the way Auth does, as supabase_auth_admin with the user's standard
claims, in a transaction that is rolled back. Two limits apply:
| Limit | Measures | Default |
|---|---|---|
| Whole token | octet_length of all the claims | 2048 bytes, or tooling.doctor.claimsLimit without a hook budget |
| The provider's hook budget | octet_length of each of tokenHook.budget.claims | tokenHook.budget.bytes, or tooling.doctor.claimsLimit |
Each one is a separate warning, so a token of 1.5 KB whose budget claims fit
the budget passes. When the hook sets tokenHook.budget.truncatedClaim,
doctor also reports that the token lists only some entries, so server checks
for that user need a database lookup. Keep ids and roles in the token and
look everything else up. This needs a direct connection (local stack,
$DATABASE_URL, $SUPABASE_DB_URL or --db-url-stdin).
BS406
Warning: foreign key to auth.users blocks account deletion. A key with
no action or restrict makes auth.admin.deleteUser, and
deleteAccount, fail with "Database error
deleting user" while the user still has rows. Use on delete cascade for data
the user owns (profiles, memberships, notifications) and on delete set null
for records that outlive them (created_by on shared documents, audit rows).
BS407
Error: two authorization hooks. The authorization provider's hook
(authorization.tokenHook) owns the claims in ownedClaims, plus its
tenantClaim. A custom access token hook that also calls
better_supabase.membership_claims (when memberships is owned) or
better_supabase.permission_claims (when permissions is owned), or writes
one of those claims itself through jsonb_set or jsonb_build_object, gives
them two sources that drift apart. Use the provider's hook and remove the
extra writes.
The provider's own hook is not reported: doctor recognizes it by
tokenHook.function or by its markers.hook line in the file that creates
it. Claims in registeredClaims, such as features from
better_supabase.feature_claims, are sources of the provider's hook and are
not a second writer. A hook that wraps the provider's hook and then writes one
of those claims again is reported, with the function that already fills it.
BS408
Warning: the entitlements module can't read the provider's memberships.
With auth.entitlements.memberships: "provider" (the default when the config has
authorization), the entitlements block
module reads memberships through the provider's
memberIds template in has_entitlement, which runs as authenticated, and
memberIdsFor in feature_claims, which the provider's hook calls as
supabase_auth_admin. When entitlements is in blocks, doctor warns
when:
- the provider can't back the mode:
tenantScopeis not one of its scopes, the scope has noidTypeor one other thanuuid,text,bigintorinteger, ormemberIdsormemberIdsForis missing.sql add entitlementsrefuses to render the module then; setauth.entitlements.memberships: "tenant"to use the tenant module's memberships; - the provider's hook doesn't fill
auth.claims.featuresfrombetter_supabase.feature_claims(tokenHook.registeredClaims), sohasEntitlement()would never see the plan features. Withauth.entitlements.claim: falsethe token carries no features, so doctor skips this check; - no
authorization.membershipstable covers the tenant scope, soentitlement_members()finds no users to sign out after a plan change (an info finding when the provider lists no memberships at all); - a function those templates call is missing from
authorization.requires, isn't executable by the role that calls it, or isn't in the database.
BS409
Warning: the authorization provider and the better-supabase config
disagree. The provider's hook writes the active tenant to
tokenHook.tenantClaim. Doctor warns when auth.tenant.claim names another
claim, because the memberships extension, the guards and the module's RLS would then
read a claim the hook never writes. It also warns when the provider's
tokenHook.activeOrganizationFrom (the app_metadata claim, a profile column or
the request, which is "resolver") differs from
blocks.permissions.activeTenant, where switch_organization writes the
active organization, since switching would then never change the token. The
config default is "resolver", so a provider that states "resolver" needs no
config entry. It notes when auth.claims.scope is neither
tenant nor the provider's tenantScope, notes when the provider sets
suspension or roleSources while blocks.permissions.model is not
provider (only that model reads them), notes when functions.canApprove
or approvals.distinctApprover is set (both are ignored; isApprover
decides), warns when a function template uses a placeholder it does not
take, and reports every entry of the provider's problems, such as a file
version it can't read.
Under the provider model it also warns when blocks.permissions.disabled.user
or .tenant replaces the provider's suspension entry with the other form.
The column form ("schema.table.column") disables a user or tenant only when
that column is set, so one with no row gets through. The row form needs an
active row, so one with no row is disabled. The two values are not equal, so
BS427 stays silent; the warning names both forms. Remove the config entry to use
the provider's check, or give both the same form.
BS410
Warning: HTTP auth hooks. Auth calls an [auth.hook.<hook>] with an
http:// or https:// URI by sending a request signed with the Standard
Webhooks secret in secrets (v1,whsec_<base64>, several joined with |).
Doctor can't read the endpoint's code, so it reports each HTTP hook as an info
finding; verify the request there with authHook from
better-supabase/blocks/webhooks. It also reports:
- an error when
secretsis missing, or when a secret is notv1,whsec_<base64>or decodes to fewer than 24 or more than 64 bytes. The message never quotes the secret; - a warning when the secret is written in
config.tomlinstead of read withsecrets = "env(BETTER_SUPABASE_AUTH_HOOK_SECRET)". A value read fromenv()is checked only when@supabase/configinterpolated it; - a warning when a non-local endpoint uses plain
http.
BS411
Error: the provider access model can't use the authorization provider.
With blocks.permissions.model: "provider", can() and the SQL modules fill
the provider's idsWith template for tenant checks and isPlatform for
platform checks, at its tenantScope. Doctor reports, and add refuses:
- a config without
authorization; - a
tenantScopethe provider doesn't declare, a scopeidTypeother thanuuid,text,bigintorinteger, or ablocks.permissions.idTypethat differs from it; - a function those templates call that
authorization.requiresdoesn't list, doesn't letauthenticatedexecute, or the database lacks; - a permission key a SQL module checks (
modulePermissionKeysfrombetter-supabase/sqllists them) that the provider doesn't marksqlComplete: true. Its functions decide by role and scope only, so a key with other conditions would be granted everywhere in the scope. Map the action to another key inblocks.<module>.permissions.
It warns when neither blocks.permissions.functions.canAssign nor the
provider's canAssign is set, because only the service role then assigns
roles. See the permissions block for the recipe.
It also warns for each optional template an installed module calls that the provider doesn't set, and names the modules:
| Template | Modules | Without it |
|---|---|---|
idsWithFor | invitations, inbox, comments, sso, notifications, connectors, workflow-sdk | checks of another user's tenant permissions raise 0A000 or are skipped |
isPlatformFor | invitations | checks of another user's platform permissions answer false or are skipped |
canAssignFor | invitations | the inviter's right to assign the role is not checked again at acceptance |
memberIds | usage | membership checks read the tenant module's memberships table instead |
blocks.permissions.functions.canAssignFor silences the canAssignFor
warning.
BS412
Info: the session cookie encoding differs between server and browser.
@supabase/ssr needs the same cookies.encode on both sides. Doctor reads
the files in tooling.doctor.sources: a file that imports better-supabase/client or
calls createBrowserClient is the browser side, and a file that imports
better-supabase/server, next, ssr, hono, orpc, edge or expo, or
calls createServerClient, is the server side. When a file on one side sets
encode: 'tokens-only' and a file on the other side doesn't, the other side
uses the default user-and-tokens: it writes the user object back into the
cookie, or reads a session without one and session.user throws. Set the same
encode in createClient and on the server. See
Encoding. Doctor reads imports, calls and
properties from the syntax tree, so a comment or a string that mentions
tokens-only doesn't count.
BS413
Warning: support sessions are not tied to the provider's read-only check.
Support sessions are installed, blocks.permissions.model is provider, and
authorization.functions.actorMayWrite is not set. Writes still refuse a
read-only act through the built-in check. Set actorMayWrite to the
provider's read-only helper so that helper is the only check.
BS414
Warning: the access contract answers from built-in roles next to a
provider. The config sets authorization, but blocks.permissions.model
names another model, so better_supabase.can() and
better_supabase.tenant_ids_with() answer from the built-in roles. Doctor
reports each policy and each function in schemas that calls them. Remove
model to use the provider (the default with authorization), or call the
provider's own function in that policy.
BS416
Warning: isApprover has no branch for support sessions. Under the
provider access model, the impersonation module asks
authorization.functions.isApprover who may approve a support request, with
{kind} set to 'support-session' and {subject} the request id. A
template written only for 'ai-tool' answers false, so no admin can approve
and every start that needs a second admin stays pending. Doctor reads the
template and the live definition of each function it calls. Add a
'support-session' branch, or set blocks["impersonation"].options.approval
to "none".
BS417
Warning: the provider declares teams but sets no teamIdsOf template.
Under the provider access model, team_ids_of() and the team sharing in
saved-views and collections call authorization.functions.teamIdsOf for
the caller's teams. Without it, team_ids_of() reads the teams block's own
team_members, which a provider that keeps its own teams never fills, and
saved-views and collections without the teams block share with no team.
Doctor warns when the provider declares a team (or teams) scope, one of
those blocks is installed, and the template is unset. Set teamIdsOf to a
set-returning call with {user}, such as provider.team_ids_of({user}).
BS419
Warning: permissionsAuthorizer checks keys the token leaves out. The
permissions claim carries only the keys the authorization provider marks
sqlComplete: true, because the SQL functions can't decide the others.
Doctor reports app files in doctor.sources that call
permissionsAuthorizer( while authorization.permissions is missing or has
keys without sqlComplete. A check for such a key is denied unless the
authorizer's load option reads my_permissions. Mark the keys
sqlComplete when the SQL functions answer for them, or pass load.
BS420
Error: a second authorization version source. When the authorization
provider keeps the versions (authorization.versions), the sessions
module's authzVersions option renders no table, trigger or broadcast and
reads the provider's function instead. Doctor reports a
better_supabase.user_authz_versions table still in the database, and a
custom access token hook other than the provider's that reads
better_supabase.authz_version(. Either one gives tokens and the bootstrap a
version nothing bumps, so a role change never looks newer. Drop the table
with a migration (better-supabase db diff writes it), and use the
provider's hook or read its versions function.
BS421
Error: access token hook behind the tenant scope. Auth runs the custom
access token hook as supabase_auth_admin, where auth.uid() is null. The
restrictive bsb_tenant_scope_* policies are to public, so they apply to
that role too and let it see no rows. Doctor reports a security invoker hook
whose body reads a table with a restrictive bsb_tenant_scope_select policy
that doesn't let supabase_auth_admin through. Every token then misses the
claims the hook reads from that table. Add the role to the tenant scope:
export default defineConfig({
database: { sql: { tenantScope: { exemptRoles: ["supabase_auth_admin"] } } },
});The exemption only lifts the restrictive scope. The hook still needs the grant
and the permissive policy for supabase_auth_admin that the Supabase hook guide
describes. Or make the hook security definer, owned by a role that bypasses
row level security.
BS426
Retired in 0.82. The code stays reserved and doctor no longer reports it. BS427 covers its checks.
BS427
Warning: config restates its default. An entry equals the value the render uses without it, so it is a second copy that goes stale. Doctor reports:
- an identity mapping for an optional column, such as
columns.<table>.<column>set to the column's default name, when a render without it gives the same files. Write{ column: "name", required: true }when the table must have the column. A mapping that turns on a column the render would not find otherwise is not reported; - a
nullfor a column the view lacks anyway; - an empty
columns,valuesortablesmap; columns.<table>.tenantequal tosql.tenantColumn;- a value equal to the authorization provider's:
platformRoles, a role source'sthrough, a membership'sdisabledAt,suspensionandtokenHook.functionforimpersonation.options.claimsHook; blocks.permissions.activeTenantset to"resolver", the request and the default;- a block
apiwritten as{ schema: "api" }(no function list) that equalsdatabase.sql.api; - a
recordTypes.<type>.permissions.<action>key equal to the provider'sactionKeys.recordTypesentry; - a
permissionskey, anoptionsentry or asameTenantelement of an installed block whose removal leaves every rendered file unchanged: a key the block would pick anyway, an option equal to its default, an entry the schema already derives.
Values are compared after they resolve, not as written: object key order, the
order of active values, white space and the case of unquoted words in a SQL
template (where, canAssign, canAssignFor) and the case of the claims hook
name do not matter, while a string literal, a quoted identifier and a
placeholder do. A column string (schema.table.column) and an active row
({ table, id, disabledAt }) are never equal, because a missing row disables
the tenant or user only in the second form.
The provider kinds are reported under the provider access model only, and
disabled.userKey only when disabled.user is unset or equal to the
provider's, because the provider's key applies only then.
better-supabase codemod config --prune removes each entry when the render
stays the same.
BS428
Error: a table the provider shares per tenant has row-level reads. An
authorization provider's tables entry with share: "tenant" says every
caller with the same permissions in a tenant reads the same rows, so
bsb.kept and bsb.remote with share: "tenant" keep one entry for all of
them. Doctor reads the table's permissive select policies for authenticated
and reports:
- a
tenanttable whose policy filters by the caller (auth.uid(),auth.jwt(),auth.email(),better_supabase.current_user_id()orcurrent_user), or whose policies don't pin the tenant column to a tenant the caller acts in. A shared entry would hand one caller's rows to another; declare the tableshare: "row"; - a table whose policies pass other keys to the provider's
idsWiththan itspermissions, so the entry would be keyed on the wrong grant; - a name the database has no table for.
BS430
Error: a function the provider shares per tenant reads past its tables. An
authorization provider's sharedFunctions entry says a database function
returns the same rows to every caller with the entry's permissions in a
tenant, so a share: "tenant" fill of bsb.kept or bsb.remote may call it
and keep one entry for all of them. Doctor reads the function from the catalog
and reports, in one finding, every reason it fails. A function fails when it:
- is
security definer, so it reads past the caller's RLS; - isn't
language sql: doctor can't read a PL/pgSQL body, so it can't tell which tables the function reads; - is volatile;
- has no body in the catalog, or one that doesn't parse;
- reads the caller:
current_user,current_role,session_useroruser, anyauth.*function,current_setting, or a function namedcurrent_user_id; - reads a table its
tablesdon't list; - calls a function in a schema doctor didn't read (built-ins and
pg_catalogpass); - calls a function in the read schemas that isn't admitted.
Names match as schema.name. A bare table or function name resolves through
the function's search_path (its own schema, then public, when it sets
none), and a bare key in sharedFunctions or tables means public. A call
is admitted in three cases:
| The callee | Condition |
|---|---|
A function sharedFunctions lists | Its reads stay inside this entry's tables; its own finding covers the rest |
A better_supabase helper | It passes the same check on its own |
One of the provider's permissionFilters | The permission key is a string literal, and the entry's permissions lists it |
The library helpers that pass on their own read no tables and no caller, so
their result depends only on their arguments. With every block installed, this
release has 48: bsb_valid_bsn, bsb_valid_iban, chain_row_hash,
currency_minor_units, data_lifecycle_credentials, the deadline_*
validators (deadline_citation_bad, deadline_codes,
deadline_condition_bad, deadline_meta_bad, deadline_rule_from_v1,
deadline_sorted, deadline_whole), document_address,
document_slot_rank, document_tax_summary, drive_retention_kind,
flag_condition_matches, the form_* helpers (form_answer_matches,
form_answer_merge, form_answer_split, form_condition_holds,
form_condition_schema, form_correct_fits), import_entities,
incoming_webhook_subject_readable, inspection_team_with_lead,
interactive_only, interactive_only_role, leave_working_days,
messaging_file_anchor_valid, metric_definitions, normalize_phone,
number_format_pattern, number_format_period, number_period_kind,
observation_flag, operation_permission, parse_mentions,
permission_matches, request_id_or_null, round_half_even,
rule_boolean, rule_text, scim_group_role, scope_permissions,
subject_types, time_week and usage_meters. Run
better-supabase config functions --shareable 'better_supabase.*' for the
list in your schema. A helper that answers for the caller, such as
better_supabase.tenant_ids_with (security definer), fails the check, so a
shared function can't call it; use a permissionFilters helper instead.
It also reports a listed table the provider's tables doesn't share per
tenant, a permission key a permissionFilters call passes that the entry's
permissions leaves out, and a function or table the database lacks. A
function that returns the caller's own rows next to the tenant's can't be
shared: split it into a tenant function and a per-user read.
config functions --shareable
runs the same check before you list a function.
BS429
Info: a write definition sets no enforcement. An action, a route bound to
POST, PUT, PATCH or DELETE, a resource action that writes, or an MCP
tool without annotations.readOnlyHint: true that checks a permission and
sets no enforcement reaches the authorizer as definer. A provider then
reads the authorization version live on each of those checks, because a
security definer function or the admin client could do the write. Doctor
names each definition with its file and line. Set enforcement: "rls" only
when every write in the definition runs through the caller's db, where RLS
checks it again, and set "definer" to record the default.
Env files
BS501
Error: secret in a browser variable. A variable with a public prefix
(NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_, PUBLIC_, NUXT_PUBLIC_) holds a
secret key. Bundlers inline these into client code. Rename the variable and
rotate the key.
BS502
Warning: env file with secrets isn't ignored by git. An env file holds a
secret key or database URL but git doesn't ignore it. Doctor asks
git check-ignore, so the .gitignore files of parent folders (a monorepo
root's, for example), .git/info/exclude and the global excludes count, and a
committed file is reported even when a pattern matches it. Outside a git work
tree it reads every .gitignore from the app up to the folder that holds
.git, each against paths relative to its own folder, with ! negations.
Add the file, for example .env*.local, to a .gitignore, and run
git rm --cached on one that was committed. .example files are skipped.
BS503
Warning: exported Supabase variable differs from the running stack. A
SUPABASE_* variable exported in your shell, such as a SUPABASE_URL left
over from another worktree, has another value than the local stack. The app
then talks to the wrong stack, because frameworks never override a variable
that is already set. The finding names the variable and both values, redacted:
the host and port for a URL, and a SHA-256 fingerprint for a key. Unset the
variable, or start the app with better-supabase dev run -- <cmd>, which sets the
stack's values over the shell's. An exported SUPABASE_JWKS is reported too:
the server prefers those inline keys over SUPABASE_JWKS_URL, so keys from a
hosted project reject every token the local stack signs. Keys the stack's
JWKS URL serves too (what pnpm env:local writes) are accepted. Doctor only checks
this when the shell exports a SUPABASE_* variable and the local stack is
running.
BS504
Error: env key a block needs is missing. An installed block declares an env
key, such as CRON_SECRET for the outbox relay or STRIPE_WEBHOOK_SECRET for
billing, and no env file lists it and the shell doesn't set it. The route or
worker that reads it then fails at runtime. better-supabase add and init
append the keys to .env.example; set them in .env.local and in every
deployed environment. Optional keys, like AI_GATEWAY_API_KEY (the OIDC token
works on Vercel), are never reported. CRON_SECRET is one the app passes to
the route itself, so doctor asks for it only while a file in doctor.sources
names it: an app that authenticates its cron routes another way, such as
caller: "vercel-schedule", doesn't need the key.
BS505
Error: required provider is not wired. A block that can't run without an
implementation is installed: enrichment needs an EnrichmentProvider and
mail-sync needs its MailProviders. No app source passes the instance one with
.with(...) or .using(...). add writes a commented stub for it in
providers.ts, next to blocks.generated.ts. Fill in the stub, then spread
...providers into defineBlocks(blockConfig, { ...blocks, ...providers }).
Comments don't count, so the finding stays until the stub is real code.
BS507
Warning: block actions are not registered. An installed block ships
automation actions, such as the conversions tasks.from_conversation or
quotes.from_deal, but no app source calls blockActions(...) or
createActionRegistry(...). A default automation that you turn on then names an
action the rules consumer can't run. Build the registry with
createActionRegistry([...blockActions(blocks, { clients })]) from
better-supabase/blocks/automations in the outbox route.
BS508
Warning: block timers have no handler. An installed block declares timers,
such as an SLA check, but no app source calls blockTickHandler(...), so the
timers never fire. Call
jobs.ensureSchedules(blockSchedules(blocks), { prefix: BLOCK_SCHEDULE_PREFIX })
once and drain the block_ticks queue with blockTickHandler. A timer
switched off with blocks.<name>.schedules ({ expire: false }) is left out.
BS509
Error: SUPABASE_JWKS does not parse. An env file sets SUPABASE_JWKS
to a value that is not JSON, or that holds no key with a kty. getEnv
rejects it, so the server fails to start. Fill it with the output of
curl <url>/auth/v1/.well-known/jwks.json, as {"keys":[...]} or [...],
or leave it empty so the server fetches SUPABASE_JWKS_URL. An empty
SUPABASE_JWKS= in a .env.example is fine.
BS510
Warning: maintenance jobs have no scheduler. The schema files install the
housekeeping module (the maintenance_jobs view), but no schema file calls
maintenance_schedule() or schedules maintenance() with cron.schedule, and no
source calls maintenanceTick(...). The purges and expiries the installed blocks
contribute never run. Run select better_supabase.maintenance_schedule() once,
which registers pg_cron, or drain the block_ticks queue with maintenanceTick
when pg_cron is not available. The check is static: it cannot see whether a job
is due in the live database, so it does not replace reading maintenance_jobs.
BS511
Warning: a client component reaches the server block wiring. A module with
"use client" imports blocks.generated or providers.ts, or calls
defineBlocks, so every installed block client ends up in the browser bundle.
Import blockConfig from blocks.config.ts, which holds data only. When the
browser needs a few block clients, list those instances in gen.clientBlocks
and import clientBlocks from blocks.client.ts.
BS512
Warning: queue schedule wiring misfires. The clock that drives the queue
misses or doubles runs. vercel.json still calls a path from crons: move it
to schedules as a path target with "requestMethod": "GET", which sends the
same CRON_SECRET bearer, and remove the crons entry, since a path in both
runs twice. A schedule targets a private function whose functions entry has
no schedule/v1beta trigger, so Vercel never calls it. A schedule with a
service is looked up in that service's functions, and an entry matches by
its file (app/api/drain/route.ts) or its route (api/drain). Or
blocks.queue.options.httpTick is on, but no schema file creates pg_net, or
no SQL file stores the jobs_tick_url and jobs_tick_token Vault secrets that
better_supabase.http_tick() reads. Secrets set from the dashboard are
invisible to this static check; ignore that finding when you set them there.
BS513
Warning: a Vercel environment lacks a Supabase variable. With --vercel,
doctor reads .vercel/.env.development.local, .vercel/.env.preview.local and
.vercel/.env.production.local, the files vercel pull --environment=<name>
writes. It reports an environment that sets no SUPABASE_URL or no
SUPABASE_PUBLISHABLE_KEY (plain or with a browser prefix), one that sets only
the legacy SUPABASE_ANON_KEY name, which the library does not read, and a
Supabase or database variable that production or preview sets but another
environment lacks, as when the integration is connected to production only.
Names are checked, not values, so a sensitive variable that Vercel does not
return still counts as set. With nothing pulled, the finding tells you which
command to run.
BS514
Error: a secret under a browser prefix in a Vercel environment. With
--vercel, a variable whose name starts with NEXT_PUBLIC_, VITE_,
PUBLIC_, EXPO_PUBLIC_ or NUXT_PUBLIC_ and continues with a secret name
(SECRET, SERVICE_ROLE, JWT_SECRET, a database URL, PASSWORD,
PRIVATE), or whose value starts with sb_secret_, is inlined into client
code at build time. The name is enough, so the check works when Vercel hides
the value. Rename the variable, redeploy and rotate the key. The same check on
.env files is BS501.
BS515
Warning: preview and production share a Supabase project. With --vercel,
the preview and production files name the same project: the same project ref
for a hosted URL, or the same origin for any other. Every preview deployment
then reads and writes production data. Connect preview to its own project or a
branch database. The check is skipped when Vercel hides either URL. At runtime,
assertDeployment from
better-supabase/vercel
fails a preview that starts against the production project.
BS506
Warning: server and browser Supabase URLs differ. An env file sets
SUPABASE_URL and a browser spelling such as NEXT_PUBLIC_SUPABASE_URL to
different URLs. The session cookie name comes from the URL
(sb-<project-ref>-auth-token), so the server and the browser client then
read different cookies, and a sign-in on one side is invisible to the other.
The finding shows each URL's host and port. Use one URL, or when the split
is intended (a custom domain in the browser, the project URL on the server),
set auth.cookie.name on createNext and on the browser client to the same
name.
Dependencies
BS601
Warning: peer outside its range. An optional peer of better-supabase is
installed at a version outside the range better-supabase declares, for
example @vercel/queue@0.12.0 against >=0.11.0 <0.12. With
strictPeerDependencies the install fails, and the subpath that needs the
peer can break at runtime. Doctor reads the version from the nearest
node_modules above the project root and skips peers that aren't installed.
It also skips a peer that neither the project's package.json nor a package
of its workspace lists, such as undici or vue that a framework or SDK
installs for itself: that copy follows the other package's range. A project
that uses the subpath needing the peer lists it in its dependencies, and doctor
checks it from then on. Install a version in the range, or remove the package
if nothing imports it.
Peers lists which subpath needs which peer.
BS602
Error: content mapper not set up. gen.contentMapper is on, so gen
writes schema.bsb instead of the type files, but tsc can't load the
content mapper that serves its types. The finding
names each missing piece: tsconfig.json has no contentMappers entry for
better-supabase, the project resolves TypeScript older than 7.1, or the
typecheck script in package.json runs tsc without --runExternalCode.
Doctor skips the script check when there is no typecheck script.
better-supabase init --content-mapper adds the entry and the flag. To go
back to the type files, turn gen.contentMapper off and run gen.
BS607
Warning: installed better-supabase differs from the lockfile or the database. Doctor compares three records of which release the project runs. The finding names the one that differs:
- The
better-supabaseinnode_modulesis not a version the nearest lockfile at or above the project resolves (pnpm-lock.yaml,package-lock.json,yarn.lockorbun.lock), which happens after a pull that changed the lockfile. Run the install command the finding prints. Workspace links and file paths are skipped. - A block file in
supabase/schemas, or the module migration under the migrations workflow, carries a@bsb-blockversion newer than this release ships. - A
better_supabase.blocksrow in the database records a newer version, read when doctor checks a live database.
The last two mean a newer release wrote the SQL, so gen, add and
upgrade would render the blocks of an older release. Install the release
your lockfile and teammates use, then run better-supabase upgrade --check.
BS311 reports the opposite case, SQL older than the release.
BS608
Warning: remote cache scope without a remote cache handler. A source file
uses bsb.remote(), bsb.cached({ scope: "remote" }) or
"use cache: remote", the project has no vercel.ts, vercel.json or
.vercel/project.json, and next.config sets no cacheHandlers.remote.
Next.js then keeps remote entries in each instance's memory, so instances
never share them and every deploy starts cold. Set remoteCacheHandler in
createNextConfig() (or cacheHandlers.remote) to a shared handler such as
Redis. See remote cache scope.
BS609
Info: three or more database reads in one Promise.all. A source file
awaits at least three repository, block client or $rpc calls in one
Promise.all. They run in parallel, but each is its own request to
PostgREST. A read set compiles the same reads into one stable database
function, so the page waits on one round trip: defineReadSet(db, "name", ...)
and db.$many(readSet, params), or bsb.bootstrap for a page's first load.
The finding prints the read set that replaces the reads: the same calls on the
builder s, keyed by table, and the db.$many call. A value that comes from
the page becomes a placeholder. See read sets.
tooling.doctor.parallelReads sets the count (default 3).
BS634
Warning: database read once per item (N+1). A source file reads the
database inside a for ... of loop or a map, flatMap or forEach
callback, and the read's arguments use the loop variable (or a value derived
from it), so a list of n items makes n requests:
const items = await Promise.all(
ids.map(async (id) => await db.customers.get(id)), // one request per id
);Doctor counts repository reads (get, list, count, counted,
aggregate), $rpc, $search, $run and $many, block client calls,
supabase-js .from(...).select(...) chains, and two kinds of indirect read:
a function in the same file that only reads (followed through other such
functions in that file), and a get, list, load, find, fetch,
count, read or search method on a service object, one whose name ends
in Service, Services, Repository or Queries, one returned by a
create...Service(...) factory, or a parameter typed as one
(customers: CustomersService). It doesn't follow calls into other files.
Besides for ... of and the array callbacks, it reads the callback of a helper
that runs once per item, one whose name has map, each, chunk, batch,
concurrent, parallel or limit in it, such as
mapInChunks(ids, 20, async (id) => ...). A callback that takes a whole
chunk or batch is one request per batch, but chunk.map((id) => ...)
inside it is again one per item.
The finding names the fix. When the loop runs over rows of an earlier read
and the snapshot has a foreign key between the two tables, it names the
include to add to that read, such as include: { customer: true } (or
include: { _count: { notes: true } } for a count). Otherwise it suggests one
read with an in filter (where: { id: { in: ids } }) grouped by key, an
array parameter for an RPC, or a batched variant of the helper. When the loop
variable is a search term (contains, ilike, q, search, textSearch)
or a value matched inside a JSON column (contains: { ... }), an in filter
can't replace the reads, so the finding names one read with an OR of the
conditions or an RPC that takes the terms as an array, and says when no batched
form applies.
To keep false positives low it skips a read already batched with in over
the loop variable, a loop over chunks, batches or retry attempts, a loop
over a literal array without a spread, page reads, and any loop that also
writes: a repository or supabase-js write, an RPC, block or service method
named for a write such as create, update, assign, approve, decide or
publish (services.agenda.assignTask too), or a call named for a side effect
such as notifyAgendaUpdated(...), publish..., send..., emit... or
enqueue.... Accept a deliberate
case in the baseline, or turn the check off with
ignore: ["BS634"].
BS635
Warning: dependent read of a related table (waterfall). An awaited read filters by rows that an earlier awaited read in the same scope returned, and the snapshot has a foreign key between the two tables on the column the filter uses. The second request waits for the first:
const orders = await db.orders.list({ limit: 20 }).orThrow();
const customers = await db.customers
.list({ where: { id: { in: orders.map((order) => order.customerId) } } })
.orThrow();Add the include the finding names to the first read, here
include: { customer: true }, so one request returns both. Doctor follows
the rows through const and let declarations, including the entries of a
destructured Promise.all, and only within the block that declares them.
Two tables that both reference a third in the same schema, such as
quote_tasks and invoice_tasks through tasks, get a nested include
(include: { task: { include: { invoiceTasks: true } } }) when the second read
filters its key column by the first read's rows. Columns that only ride along
in composite foreign keys, such as a tenant column, and tables in other schemas,
such as auth.users, don't link two reads, and neither does a view, whose
generated table has no relations to include. Other reads whose tables have no
foreign key between them are left alone, because an include can't replace
them; BS609 covers independent reads.
When the dependent read sits in one Promise.all with other reads that also
filter by the same rows, the wait happens anyway. The finding is then info and
says an include saves a request, not a wait.
BS634, BS635 and BS609 read only source files. Run with --only and no
database or snapshot, they still run; BS634 then names no include, BS635 finds
no waterfall, and an info finding says so. --snapshot also reads the CLI's
cached snapshot (node_modules/.cache/better-supabase/snapshot-*.json).
The source rules BS210, BS219, BS227, BS351, BS609, BS634 and BS635 match a receiver by its name, such as db or userService.
With typescript 7.1 or newer installed, doctor asks TypeScript for the type
of the receiver and drops the finding when it is a plain collection such as a
Map, a Set or an array. Without it, a run that reports one of the rules adds an info
finding that says receivers were matched by name only.
A comment or a string that mentions a call never counts for these source rules, or for the other source rules that read TypeScript: they read the syntax tree, not the file text. Rules that read SQL or dotenv files still match text.
BS610
Warning: nested private cache scopes. A function with
"use cache: private" calls another function in the project that has the same
directive. Next.js doesn't nest private scopes, and each scope resolves the
session again. Call the inner function from the page and pass its result down,
read both in one scope, or give every scope the same
session handle.
The check reads source text, so it follows function declarations and arrow
functions that carry the directive as their first statement.
BS611
Warning: service-role client in a private cache scope. A function with
"use cache: private" calls bsb.admin() or createAdminClient. The service
role skips the user's policies, so what it returns is cached under the user's
key but isn't their data, and each call adds a verification. Read as the user,
or move the admin read out of the cached function.
BS640
Warning: request read inside a plain "use cache" scope. A function with
"use cache" as its first statement calls cookies(), headers(),
bsb.cached(), bsb.context() or bsb.user(). Next.js rejects request reads
in a shared cache scope, and a per-user result must not be shared. Call
bsb.public()
for data every visitor may read, or use "use cache: private" for the user's
own. The check reads source text, so it follows function declarations and arrow
functions that carry the directive as their first statement.
Shims
These checks read the app's source text, matched by doctor.sources, for code the library now covers. Each one reports once per file and only in files that name better-supabase. The shim registry in src/cli/doctor/shims.ts lists them, so one entry adds a check.
BS621
Warning: a client file imports a generated barrel. A file with
"use client" imports generated-schema, blocks.generated or
blocks.config. Each one lists every table or every installed block, so the
page ships all of them. Import the table modules (tables/<table>) and block
slices (blocks/slices) the page uses, and build the browser's client over
clientSchema. The check is off with gen.tableModules: false and in content
mapper mode.
BS622
Warning: a block adds a required column to a table your files create. A
block runs over a table you create and needs a required column that your schema
files don't declare, so it adds the column with add column if not exists. Run
better-supabase codemod owned-columns to declare the column in your schema
files. A block never adds an optional column to such a table: the feature that
needs one stays off until the table declares the column, and no finding says so.
BS623
Warning: a block's unique index repeats one of yours. A block creates a
unique index on a table where your own files already have a unique index over
the same columns, or over a subset of them. A partial unique index whose
where is exactly <column> is not null counts as that full key. An
expression key, such as unique (tenant_id, lower(number)), does not. Blocks
leave out an index over the same columns, and the invoices number key when
your key is a subset of it, so this finding is left for a case the block can't
decide: the index serves an on conflict target or a foreign key. Drop the
block's index with a hand migration, or narrow the block's key to the columns
your index covers.
BS624
Warning: a block's trigger repeats one of yours. A block creates a trigger
that keeps updated_at current on a table where your files already call
track_updated_at(). Blocks leave their own trigger out of a table whose files call it, so the finding appears only for a trigger the block still adds, and both then run on every write. Keep one of them.
BS625
Warning: a block-columns file adds a column you pinned to an old name. A
*.block-columns.sql file adds a column under its 0.58 name, and
blocks.<name>.columns pins that column to the name your table already has.
Applying the file adds a second column. Delete the add column line, or drop
the pin after you rename the column.
BS626
Warning: SQL still names a column 0.58 renamed. An audit ignore or
redact list (a better_supabase.audit() call or the JSON argument of an
audit_row_change() trigger), or a ->> '...' key in your own SQL, still
uses a column name this release renamed. codemod naming rewrites the
audit() lists; edit a trigger's JSON by hand. Update a JSON
key a block function used to return. organization_id in your own JSON is
left alone, and files upgrade rewrites are skipped.
BS636
Warning: an entity page's list has no index for a sort, multi-column sort, facet or search. A
page declared in gen.entityPages lists its entity by the sorts, facets and
searched columns the block manifest declares. Each one that is a column of the
entity's table needs a btree index that starts with the column (after the
tenant column), or a GIN trigram index for a searched column. Without it the
page sorts or groups the tenant's rows on every request. A multi-column sort the
page declares in sortLists needs a btree index that starts with its columns in
order (after the tenant column); an index on the same columns in another order
does not serve it. Run better-supabase gen, which writes the indexes in a migration, or add the index to the schema
file. See Entity pages.
BS628
Warning: a list cursor has no matching index. A list function orders or
continues by created_at and id, and the same file has no btree index that
contains both columns. The cursor then sorts the tenant on every page. Add an
index on (tenant, created_at, id) in the same direction as the order.
Doctor reads each order by clause up to the end of its query level, so a
column named after an inner order by doesn't count, and an order by ... limit 1 that picks one row isn't a cursor.
BS629
Warning: a migration drops import dispatch arms. The newest migration that
defines a function must contain every when '<entity>' then arm the schema
file contains. An import_apply_batch in a schema file must also dispatch
every entity in blocks.imports.options.targets. A regenerated migration that
replaces the whole function from an older body drops targets the schema still
calls. Sync the migration with the schema file.
BS627
Warning: a raise has no stable code. A raise exception in a schema file
without a hint leaves an app matching English message text. The hint is the
code. better-supabase codes --json prints the catalog.
BS630
Warning: foreign keys to one table need two relation names. Two foreign
keys to the same table whose first columns differ become two relations, with a
suffix so the names stay unique. A composite key that starts with the same
column as a single-column key to that table is an alias of that relation.
Rename one relation in gen.tables, or share the first column.
BS631
Error: team members keep employees, but the user column is required. The
teams and employees blocks run over your own team_members table, and it has
the employee column, so teams keeps an employee on a team without a user. The
table's user column is not null, often because it is part of the primary
key, so removing a member or a user who has an employee record fails, and so
does adding an employee without an account. Drop the employee column, or map
blocks.teams.columns.members.employee to null, to keep user-only members.
To keep employees, give the table its own primary key, drop the not null on
the user column and add unique indexes on (team_id, user_id) and
(team_id, employee_id).
BS632
Warning: a search key comparison mixes column types. Search joins a source view and follows watch keys on the columns' own type. When the live catalog gives the two columns different types, the comparison stays text and cannot use the key's index. Make the columns the same type.
BS637
Warning: a search source view reads a column search.columns leaves out.
A record type with search.from re-indexes when one of the columns in
search.columns (or its id, tenant, deletedAt or exclude column) changes, because the
generator cannot see what the view reads. Doctor reads
information_schema.view_column_usage for each source view and reports every
column of the record's own table that the view reads and the list leaves out.
An update of such a column leaves the search document stale. Add the column to
search.columns.
BS638
Warning: stored open items differ from the fold. invoice_open_items
keeps today's open invoices and unallocated payments, and triggers keep it
current. A write that skips them, such as a restore or an update with
triggers off, leaves rows that differ from what the invoices and ledger
entries add up to. Doctor calls open_items_drift_rows for each organization
with stored rows or invoices and lists the ones that differ. Run
select better_supabase.rebuild_open_items('<organization id>') for each.
Needs a database; saved snapshots skip it.
BS639
Info: tables left out of the audit log. One finding per table that BS315
skips because blocks.audit.options.exempt or an @bsb audit-exempt tag names
it, with the reason and the time of the table's last entry in
better_supabase.audit_events, or never. A table that had entries before its
exemption shows when they stopped. The JSON report carries the same rows, one
finding each. Review the list when a table's purpose changes. Needs a database;
saved snapshots skip it.
BS641
Info: many policies for one command. Postgres evaluates every permissive
policy (or-ed together) and every restrictive policy (and-ed) of a command for
each row, so each policy adds a condition to every query on the table. Doctor
reports a table and command with more than doctor.policies.max policies for
authenticated (default 4) and lists each with its kind and origin: library
for bsb_ policies and block tables, provider when it calls a function of
the authorization provider, and app otherwise. The library adds one
restrictive guard and one permissive grant per command, so a long list usually
points at provider or app policies to fold into fewer conditions:
export default defineConfig({ doctor: { policies: { max: 6 } } });BS642
Info: an index leads with an enum column on an RLS table. Postgres marks
enum_eq as not leakproof (checked on Postgres 17.6), so on a table with RLS
it can't use where status = 'open' as an index condition before the policies
pass, and the query filters after a wider scan. text and uuid comparisons
are leakproof. Store the value as text with a check constraint, the way every
block does:
status text not null check (status in ('open', 'paid', 'void'))Marking enum_eq leakproof needs a superuser, which Supabase doesn't grant, so
the library ships no helper for it.
BS643
Info: functions by caller. One finding per schema with how many of its
functions a policy calls, a trigger runs, anon or authenticated may execute
(app RPC), only service_role may execute (service only), or nothing names
(unreferenced). config functions --all
lists each one. An unreferenced function may still be called by another
function, so doctor drops nothing. Snapshots saved before 0.85 have no
inventory and skip the rule.
BS644
Info: the session cookie carries the user object. Neither the browser
client nor the server sets tokens-only, so @supabase/ssr writes the user
object into the session cookie next to the tokens, and every request carries
it. Doctor finds the two sides the way BS412 does. Set
cookies: { encode: 'tokens-only' } in createClient and
auth: { cookie: { encode: 'tokens-only' } } in the server options; init
writes both for a new app. The finding lists the server files that call
auth.getSession(), which read the user from the cookie: move them to
bsb.claims() before you switch. With --as <user id> and a database, it adds
the bytes that user's object takes in the cookie. See
Encoding.
BS645
Warning: a public kept entry reads a table anon can't select.
bsb.kept(fn, { share: "public" }) fills as the anon role and keeps one
entry for every visitor. Doctor reads the tables of each such call in the
app's sources and reports a table without an anon select grant, or with RLS
and no permissive select policy that applies to anon. The fill would keep an
empty read for everyone until the entry expires. Add an anon select policy
that exposes only the public rows, or keep the read per user. See
Keep public data for every visitor.
BS646
Warning: durable use cache entries with a shared reader. next.config
turns on experimental.durableUseCacheEntries and a source file calls
bsb.public(), bsb.remote(), bsb.cached({ scope: "remote" }) or uses
"use cache: remote". The entries then outlive a deploy: their key follows
your code and the generated schema, not the database's policies or the
Supabase project. A migration that changes only a policy or a function body
keeps the old entries, and so does a deployment on another Supabase project
that shares the cache handler. Expire the tables' tags after such a
migration, keep one cache handler per Supabase project, or use bsb.kept()
with a version. See
durable use cache entries.
BS647
Warning: bsb.kept runs on the memory store. A source calls bsb.kept()
and no source gives createNext a kept: { store }, or one sets it to
memoryKeptStore(). The entries then live in each instance's memory: a second
instance fills its own copy, and a write on one instance never expires the
others. Pass postgresKeptStore({ client }) or
vercelRuntimeCacheAdapter(getCache, { lease }) when the app runs more than one
instance. Doctor can't see the instance count, so it reports every app that
keeps entries without a durable store. See
Keep reads across requests and deploys.
BS648
Warning: updateTag or revalidateTag beside bsb.kept. A source calls
one of them from next/cache and the app keeps reads with bsb.kept(). The
call expires Next's cache and leaves the kept entry, which the store keeps for
every instance until its life ends. Call await bsb.expireTags([...]), which
expires both and resolves once the store has the tags.
better-supabase codemod expire-tags lists each call with its replacement.
BS649
Info: refresh() without expiring tags beside bsb.kept. A file calls
refresh() from next/cache, writes, expires no tags, and the app keeps reads with
bsb.kept(). The re-render reads the kept entries again, so the page shows the
data from before the write. Expire what the write changed with
bsb.expireTags() (or name invalidates on bsb.action), then refresh.
BS650
Info: the proxy bundle is large. The last next build traced more than
400 KB of files for proxy.ts, read from .next/server/proxy.js.nft.json (or
middleware.js.nft.json). The proxy runs before every request, so the app
definition, the generated schema or a block set in its imports slows each one.
Build it with createProxy({ auth }), which needs no definition, and read
permissions from the generated proxy-permissions.generated.ts. Doctor skips
the rule when the project has not been built.
BS633
Info: an app row trigger has no importing() guard. An import writes many
rows in one transaction, and a row trigger of yours runs for each of them. If
the function sends, enqueues or recomputes something per row, return early
when better_supabase.importing() is true and do the work once after the
import. Doctor reads the trigger functions in supabase/schemas and skips
triggers named bsb_* and triggers whose function lives in a schema of the
authorization provider's functions (authorization.requires): those guard the
provider's own rows, so an import has to run them.
BS612
Info: the proxy re-syncs session cookies with setAll. Since 0.40 the library's own cookie handling in bsb.proxy writes them. Remove the callback.
BS613
Info: an extra Auth call follows bootstrap. auth.getUser() or auth.getClaims() next to a bootstrap call. Since 0.44, Bootstrap.endReason says why a session ended without a second Auth call.
BS614
Info: the authorization version is seeded by hand after bootstrap. The bootstrap already seeds the live version.
BS615
Info: comment paging filters deletedAt in the app. Use includeDeleted on the comments client.
BS616
Info: comment authors are read again after a comment list. With profiles installed, Message.author is { id, name, avatarUrl }.
BS617
Info: withPublicPolicyRoles. The catalog query maps empty policy roles to public itself.
BS618
Info: a unique violation is detected by code === "23505" or by a message search. Use isConflict(error, constraint).
BS619
Info: a support caller is built as an AuthState by hand. Pass { token, claims }, a SupportCaller, to the support API.
BS620
Info: settings are merged into one JSON blob by hand. The settings block validates each key against a Standard Schema and writes one key at a time.
Local stacks
These checks read the machine's System V shared memory with ipcs, so they
report on every stack the Supabase CLI runs, not only this project's. They
skip on Windows.
BS700
Warning: shared memory segments almost used up. At least 80% of the
System V shared memory segment limit is in use. Every running Postgres keeps
one small segment as an interlock, even with shared_memory_type = mmap, and
macOS allows 32 (kern.sysv.shmmni). When they run out, the next stack or
shadow database fails with could not create shared memory segment: No space left on device, which is how supabase db diff and declarative sync fail
on a machine with many worktrees. The finding names the stacks that hold
segments. Run stack prune --stop-idle to destroy
the stacks of deleted worktrees and branches and stop the others, or raise
the limit. db diff needs no shadow database.
BS701
Warning: local stack uses System V shared memory. A stack holds more than
the one small interlock segment, so its Postgres sets shared_memory_type or
dynamic_shared_memory_type to sysv. Its shared buffers and parallel query
memory then take segments of their own and fill the limit faster. The
defaults on macOS and Linux are mmap and posix; remove the override from
the stack's Postgres settings.
BS702
Info: table fact held in the config. The config holds an audit exemption,
a data-lifecycle table entry or an expose entry for a table whose comment
does not carry it. A comment on table with @bsb audit-exempt reason="...",
@bsb data-lifecycle user=owner_id or @bsb grant authenticated=select sits
next to the table, so a review of the schema shows the fact. Run
codemod table-tags to move the entries. The config entry
keeps working.
BS703
Warning: table tag cannot take effect. A @bsb data-lifecycle, grant or
same-tenant tag is malformed or incomplete: a flag that is not true or
false, a data-lifecycle tag with neither user= nor tenant=, a grant
with an unknown role or privilege, or same-tenant on a column that no
foreign key holds. The tag is ignored until you fix it.
BS704
Info: inline JSON Schema repeats an exported schema. A gen.json column or
a blocks.settings.options.schemas entry holds a JSON Schema that an exported
Standard Schema already produces, in a module the standardSchema() generator
names. Pass "./schemas.ts#name" instead, so the database check and the column
type share one schema. The inline schema keeps working.
BS705
Warning: the authorization provider's doctor reports a finding. When the
provider sets doctor: { command: [...] }, doctor runs the command in the
project root and reads { findings: [{ code, severity?, title?, message, target?, help? }] } from its output. The exit status does not matter, only
the JSON. Each finding is reported as BS705 with the provider's code first in
its target, so tooling.doctor.baseline can accept it. A command that prints
nothing, or JSON of another shape, is itself reported.
The command is stopped after authorization.doctor.timeoutMs milliseconds
(60000 by default). A command that runs longer is reported as a BS705 finding
that names the setting. A finding the provider gives severity: "error" fails
the run under the default --fail-on error, like any other error. When
--update-baseline adds a new BS705 entry, it copies a reason only from an
entry with the same provider code, never from a different one.
BS706
Warning: shim of a feature the library ships. The project rebuilds
something better-supabase already does. Doctor reports a seal trigger listed
in tooling.doctor.sealTriggers while field-encryption is installed (mark
the columns @bsb encrypted instead), a decider option on leave, expenses
or time entries while the authorization provider has functions.approverFor,
and an app schema file that redefines a better_supabase function a block
creates. approvals: false next to standaloneApprovals on expenses is not a
shim: approvals covers reports, and standalone approvals run without them.
BS707
Info: a columns entry no enabled feature reads. blocks.<name>.columns.<table>.<column>
maps a column, but the block's render never reads it, because the feature that uses it is off (an optional
table mapped to null, or an option left at its default). The entry does nothing today. Remove it, or turn the
feature on and the column starts to count. Doctor renders each block once with a read recorder to find the
entries, so the finding costs one extra render per block that has columns entries. The message ends with what
gates the column: tables.<table>: null, options.<name> (the boolean option that, set to true, makes the render
read the column; found by rendering again with each option that was off) or no option found.
BS708
Info: generated SQL size per block. Doctor lists each installed block with the kilobytes of SQL it adds to the
module files, largest first, in one finding that doctor --json carries under this code. Use it to decide which
block to leave out, or which optional table to set to null (inventory allocations and accounting budgets drop
their SQL that way). BS244 names the largest five once the total passes 2 MB. There is no sql size command,
because the sql engine is internal.
BS709
Warning: own copy of a pg-delta package. package.json, or the
package.json of a workspace package, lists @supabase/pg-delta or
@supabase/pg-topo. better-supabase depends on both at an exact version,
because the migration db diff plans depends on the
version. A second entry writes the version twice and can install a second copy
that plans differently. Remove the entries:
pnpm remove @supabase/pg-delta @supabase/pg-topoBS710
Warning: Supabase CLI older than 3.3.0. The CLI the project runs
($SUPABASE_BIN, node_modules/.bin/supabase, then the PATH) is older than
3.3.0, the release this version of better-supabase is built on. It reads
config.json and config.jsonc, runs config validate and stack prune,
selects stacks with --stack <id> (3.3.0 removed --stack-id), and expects
the multi-file migrations 3.3.0 writes. Commands that need it fail with
supabase_cli_too_old. Update it to
3.4.0, the release the repository tests:
pnpm add -D supabase@3.4.0BS711
Error: Supabase config fails validation. supabase config validate rejects
config.toml, config.json or config.jsonc: a value of the wrong type, an
unknown key, or a removed key. Each problem is one finding with the file and
line the CLI reports, and a removed key names its replacement (for example
rename [inbucket] to [local_smtp]). The check needs CLI 3.2.0; BS710 covers
an older one. db.major_version is BS712.
BS712
Error or warning: Postgres major version the local stack refuses.
db.major_version is 13 (an error: Supabase CLI 3.2 refuses to start it) or 14
(a warning: the next version to go). Upgrade the project to Postgres 17 and set
db.major_version = 17. The
upgrade guide lists the
steps.
BS713
Error or warning: a migra diff drops part of the schema files. The project
diffs supabase/schemas with migra, which drops comment on statements, grants
and the security_invoker option of views. A comment on that holds @bsb
tags is an error, because the owner, policies or access the tags record would be
lost from the database. Grants and security-invoker views are warnings. Keep
them by switching to pg-delta:
[experimental.pgdelta]
enabled = trueRemove schema_paths from [db.migrations] too, and create migrations with
supabase db schema declarative sync.
BS714
Warning: a module file lost its hash marker. A module file has no
@bsb-hash line. supabase db pull --declarative exports the database into
new files without comments, which removes the marker, and gen sql then can't
tell the file from one you wrote. Run better-supabase gen sql after a pull to
write the module files again. A pull keeps public/_custom/app_tables.sql and
the module files where they are, so nothing needs to move.
BS715
Info: action keys the provider could supply. Under the provider access
model, the config writes action keys (blocks.<name>.permissions,
recordTypes.<type>.permissions, a bucket's policy.access) that the
authorization provider's actionKeys could name instead. Doctor counts them by
kind and counts the keys actionKeys already supplies.
better-supabase config actions --json lists every action with the key it
resolves to and whether the config, the provider or the block's default named
it. A key equal to the provider's is BS427; BS715 is about keys the provider
does not name yet. Move each key into the provider's actionKeys so one place
names the keys the provider checks.
BS720
Error: a schema file does not parse. pg-topo, the analysis behind BS720 to
BS724, could not parse a file under supabase/schemas. pg-delta loads the same
files and stops on the same statement. The analysis skips the whole file, so
fix this first. The group needs no database and runs in every project that has
files under supabase/schemas.
BS721
Warning: a schema file uses an object no file creates. A statement refers
to a table, view, type, sequence or schema that no schema file creates, outside
the platform's schemas (auth, storage, extensions and the others pg-delta
treats as provided). Create the object in a schema file. When dynamic SQL
creates it, say so above the statement that does:
-- pg-topo:provides table:app.orders
select app.create_orders();pg-topo also reads -- pg-topo:depends_on <schema.name>,
-- pg-topo:requires <kind>:<schema.name> and -- pg-topo:phase <phase>
annotations, for a dependency inside a function or do body that it cannot
read.
BS722
Warning: two schema statements create the same object. A policy or function copied between files. pg-delta keeps the last one it loads, so the result depends on file order. Keep one definition.
BS723
Warning: schema statements depend on each other in a cycle. pg-delta cannot
order a cycle and loads it in a fixed order that can fail. Break it with a
deferred reference, or drop a wrong edge with -- pg-topo:depends_on.
BS724
Error: a pg-topo annotation is invalid. A -- pg-topo: comment names a
directive pg-topo does not know (phase, depends_on, requires and
provides are the four) or a value it cannot read.
BS725
Warning: a statement pg-delta cannot see in a schema file. Under pg-delta
the doctor reads every file in supabase/schemas, the module files better-supabase
writes included, for four patterns: a do block that runs DDL (a catalog
loop is BS318), a cron.schedule call inside a function or do body that does not first check that pg_cron is installed, an
alter publication through execute or format, and an alter default privileges without for role. pg-delta reads the database the files load
into, so what runs later is invisible to it, and default privileges without a
role attach to whichever role loads the file. Write each as a plain top-level
statement:
select cron.schedule('process_embeddings', '10 seconds', 'select process()');
alter publication supabase_realtime add table public.messages;
alter default privileges for role postgres in schema app
revoke all on tables from anon, authenticated;BS726
Error: a reserved name in a declarative tree. pg-delta reserves _cluster/
and _custom/ as root folders of the tree. A schema named _cluster or
_custom, or a folder that differs from _cluster only in case, would write
into them. Pick another name.
BS727
Warning: schema_paths with pg-delta. [db.migrations] schema_paths is set
and [experimental.pgdelta] enabled = true. pg-delta loads every file under
supabase/schemas and ignores the list. Remove it.
BS728
Warning: a _custom/ file without its migration. pg-delta loads
supabase/schemas/_custom files into the shadow database only, never into
yours, so what they hold has to ship in a migration. Record which one at the
top of the file, or say there is none:
-- pgdelta-migration: ../../migrations/20261122120000_add_cast.sql
-- pgdelta-migration: noneThe rule also reports a directive whose migration file does not exist.
db diff stops under strict coverage while an object that lives only in
_custom/ is missing from the target.
BS729
Warning: a modeled object in _custom/. The file creates a table, view,
function, policy, index, trigger, sequence, schema, type or domain. pg-delta
models those, so put them next to their table. _custom/ is for casts,
operators, text search objects, statistics objects, transforms and idempotent
data.
BS730
Warning: a published table without a replication key. A table listed in a
publication other than supabase_realtime has no primary key and no replica identity full. A Pipeline (replication) source cannot replicate its updates and
deletes. Add a primary key.
BS731
Warning: a SQL file does not parse. The schema reader parses each SQL file
with the grammar of db.major_version in supabase/config.toml (15, 16 or 17;
17 when unset). A file it rejects keeps no facts, so the rules that read tables,
policies or functions skip it, and gen stops on it. Doctor names the file,
the line and column, the parser's message and the Postgres version whose
grammar rejected it. Fix the statement, or set db.major_version when the file
uses syntax of another version.
BS732
Warning: a slow statement in pg_stat_statements. A statement the API roles
(authenticated, anon, service_role) ran at least five times has a mean
execution time of 100 ms or more, or a function in the public or
better_supabase schema has the same mean in pg_stat_user_functions, which
needs track_functions set to pl or all. The planning and executor start-up
of a SQL function body count toward the call that runs it, so an RPC that is
slow here often has a policy or a function inside it that is. Run explain (analyze, buffers) as the signed-in role with its claims set, or use
better-supabase doctor --explain. The check reads statistics from the running
database, reports nothing when pg_stat_statements is not installed, and a
saved snapshot skips it. Reset the statistics with select pg_stat_statements_reset() after a fix to see the new means.
Last updated on