Skip to main content

3 posts tagged with "Database"

View all tags

pg_dump backup empty? FORCE RLS blocks the table owner too

Β· 7 min read

Ran into this during a disaster-recovery drill on a Node.js + PostgreSQL multi-tenant system: ran pg_dump with the business owner role, the command printed a few errors but still produced a backup file β€” and the database restored from that file had complete structure and zero rows of data.

TL;DR​

FORCE ROW LEVEL SECURITY puts the table owner under policy evaluation, and pg_dump's COPY is just a SELECT β€” an owner session without tenant context gets every row filtered out. pg_dump reports query would be affected by row-level security policy but does not stop: it hands you a plausible-looking, data-free dump. Data-touching actions (backfills, backups, full scans) run as superuser or per-tenant with context injected, and restore drills need row-count checks that can tell "structure complete" from "data complete".

Symptoms: a "successful" backup, an empty restore​

Exporting with the owner role: the command printed a few errors, the backup file was still produced, and the restored database had complete structure with zero rows of data. The raw drill output:

$ pg_dump -U app_owner -Fc appdb -f drill.dump
pg_dump: warning: query would be affected by row-level security
policy for table "attachments"
... (one line per table)
$ echo $?
1

Those lines look like warnings. The file exists and is not empty. The problem surfaced only after restoring this dump into the drill database and counting rows: every business table had complete structure β€” indexes, sequences, constraints β€” and 0 rows.

A few weeks earlier, the same root cause had shown up on the migration side. A data-action migration (nulling out a legacy column) ran through the owner channel; deployment bookkeeping stayed green. A later superuser check found 2 rows the UPDATE had missed β€” it had silently modified 0 rows. Stranger still, running SELECT count(*) on one of those tables from the owner session returned 0, while the superuser saw 6. The owner could not read rows from a table it owned.

Two incidents, weeks apart, in different parts of the pipeline β€” one root cause. The migration side has another silent failure family unrelated to RLS: UPDATE FROM laterals can't reference the target table, and drizzle-kit swallows the error β€” the fix is to rewrite correlated reads as a CTE.

Root cause: why FORCE RLS stops the owner and pg_dump too​

Once policies apply to the owner, owner data access goes through the same evaluation as any other role β€” and pg_dump's COPY is an ordinary SELECT. Three layers stack into the silence:

Layer 1: FORCE removes the owner's exemption. With only ENABLE ROW LEVEL SECURITY, the table owner bypasses policies. Multi-tenant tables usually add FORCE ROW LEVEL SECURITY, which pulls the owner into evaluation as well β€” a deliberate tightening, not a misconfiguration.

Layer 2: maintenance sessions carry no tenant context. The typical tenant-isolation policy:

CREATE POLICY tenant_isolation ON tasks
USING (tenant_id = current_setting('app.tenant_id', true));

The second argument of current_setting('app.tenant_id', true) is missing_ok: unset variable β†’ NULL instead of an error. NULL in a comparison is never true β€” the policy rejects every row. Without missing_ok, the owner session would fail loudly with unrecognized configuration parameter and the problem would surface immediately; missing_ok turns "no context" into "silently zero rows".

Layer 3: pg_dump's failure signal is weak. A COPY blocked by RLS logs a warning, but pg_dump continues exporting whatever it can β€” nonzero exit code, file still on disk. Any pipeline that only checks "did the file get created" will treat an empty backup as a good one. DDL never touches policy evaluation, which is why structural changes in the same batch all succeed while data actions silently do nothing.

Fix: pick the channel by action type, then design the checks​

One-line rule: data-touching actions never run through a bare owner session.

ActionChannel
DDL migrations (create/alter/index)owner channel as usual
Data-action migrations (UPDATE / backfill / cleanup)superuser, or per-tenant SET app.tenant_id
Backups (pg_dump), full-table scanssuperuser
Application connectionsbusiness role + tenant context injected per connection (RLS works as designed)

Per-tenant injection, for tenant-by-tenant repairs:

SET app.tenant_id = 'tenant-a';
UPDATE ...; -- the policy passes rows for this tenant as intended

One-shot full backfills are simpler as superuser.

The backup fix is one character deep: pg_dump -U postgres. After switching, the re-run drill reconciled cleanly β€” migration records present, five key tables' row counts identical to production, RLS policy count matching, zero ownership anomalies.

Restore-drill checks must distinguish "structure complete" from "data complete". This drill nearly passed on its own criteria: the checklist said "row counts ≀ production + tenant table equal", which zero rows satisfies. Two corrections:

  1. Same-instant snapshot (export inside a write-freeze window) β†’ row counts must be exactly equal.
  2. Hot export from a live database β†’ tolerance allowed, but stated explicitly with its cause (normal writes during export). Zero rows is never inside any tolerance.

Add one foolproof line: row count 0 on a core table fails outright, no tolerance discussion.

Watch out

  • A nonzero pg_dump exit code is not "just a warning" under FORCE RLS β€” it means data did not make it into the file. A file existing is not a backup existing.
  • Do not reach for BYPASSRLS on the owner to make this go away: isolation matters precisely for roles that hold migration rights β€” that is why FORCE was chosen. Pick channels by action type instead of loosening roles.
  • One-command self-check across your pipeline: run SELECT count(*) on a core table as each operational role and compare against the superuser's count. Any mismatch means this trap is live.

The full backfill-side walkthrough of the same FORCE RLS chain β€” the layer-by-layer anatomy of a silent INSERT 0 0 β€” is in the companion post: Postgres RLS migration all green, backfill 0 rows? FORCE RLS stops the table owner too. Between the two: that one covers the backfill side, this one the backup and drill-check side.

FAQ​

Why does pg_dump produce only schema without data?​

With FORCE ROW LEVEL SECURITY on the tables, even the table owner's dump session must pass the RLS policies. Maintenance sessions carry no tenant context, so the policy evaluates to false for every row and COPY returns an empty set. pg_dump prints 'query would be affected by row-level security policy' warnings yet still writes a structure-only file β€” a healthy-looking backup with zero data.

Does row level security affect the table owner?​

Only ENABLE ROW LEVEL SECURITY leaves the owner exempt β€” policies constrain other roles. Adding FORCE ROW LEVEL SECURITY removes that exemption, so every row-access statement from the owner goes through policy evaluation too. Policies built on current_setting('app.tenant_id', true) return NULL in sessions without tenant context, and NULL compares false against everything: silently zero rows.

How do I verify a backup actually contains data?​

Restore it and compare per-table row counts against production. On a same-instant snapshot the counts must match exactly; for a hot export allow a tolerance you can state and explain. Zero rows in a core business table fails under any tolerance β€” treat it as a hard stop, not a gray zone.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Postgres RLS Backfill Lands 0 Rows? FORCE RLS Binds Owners

Β· 10 min read

While running a one-off data backfill against a multi-tenant table, the command finished normally and returned INSERT 0 0 β€” the baseline had 23 rows to migrate, and not one of them landed. In the same deployment, every CREATE TABLE and ADD COLUMN migration had succeeded.

TL;DR​

ENABLE ROW LEVEL SECURITY does not constrain the table owner; FORCE ROW LEVEL SECURITY removes that exemption. An owner's ops session has no app.tenant_id context, so a tenant-scoped policy evaluates to false on every row, and the SELECT source of an INSERT…SELECT is filtered to an empty set β€” the statement succeeds, inserts nothing, and raises no error. DDL never passes through RLS, which is why migrations stay green on the same channel. Run data backfills as a superuser (or per-tenant with SET app.tenant_id), and always verify "baseline row count vs landed row count".

The symptom​

On a FORCE-RLS multi-tenant table, an owner-session backfill silently inserts 0 rows β€” the statement succeeds with no error and no warning, and the command output alone reads as success. Here is how it happened for real.

The setting: a multi-tenant SaaS deployment. A batch of migrations (create table, add column) goes through the owner database channel and all succeed. Right after, an idempotent backfill moves data from legacy single-select columns into a new child table:

INSERT INTO task_assignees (tenant_id, task_id, assignee_user_id, assignee_vendor_id)
SELECT tenant_id, id, assignee_user_id, assignee_vendor_id
FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL
ON CONFLICT DO NOTHING;

Run as the project's owner role (app_owner for short):

INSERT 0 0

The statement exits successfully, ON_ERROR_STOP never fires, and the deployment pipeline moves on. But a superuser count shows 23 tasks with non-null legacy columns β€” the backfill effectively never ran. Judged by exit status alone, this step slips through silently.

The confusing part is the contrast within the same channel: in one and the same psql pipeline, CREATE TABLE and ALTER TABLE … ADD COLUMN work fine, and only this INSERT…SELECT lands 0 rows.

Root cause: FORCE RLS binds the owner too​

FORCE RLS extends policy enforcement to the owner, while the owner's ops session carries no tenant context β€” the policy evaluates false on every row and the SELECT is silently filtered to empty; DDL never passes through RLS, so migrations stay green on the same channel. Three layers stack into the silent chain, and each one looks reasonable on its own.

Layer 1: ENABLE and FORCE are different switches. PostgreSQL has shipped RLS since 9.5. ENABLE ROW LEVEL SECURITY turns policies on, but the table owner is exempt by default β€” policies only bind other roles. Multi-tenant tables usually add FORCE ROW LEVEL SECURITY to cancel that exemption:

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY; -- the owner is no longer exempt

Security-wise this is right: if the owner account ever leaks into an application connection, tenant isolation still holds. The cost is that the owner's ops channel is governed by policies too β€” a detail that deployment docs tend to omit.

Layer 2: current_setting with missing_ok silently returns NULL. The policy is the standard tenant-header filter:

CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

The second argument, missing_ok = true, means "return NULL instead of raising an error when the setting is absent" β€” a lenient read designed for application connections. Nobody runs SET app.tenant_id in an ops session, so the policy expression becomes tid = NULL, which evaluates to NULL (not true, not false), and the row is filtered out. The session raises nothing; the query raises nothing; you simply see no rows.

Layer 3: DDL never passes through RLS. RLS evaluates row access only (SELECT visibility, write legality). CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation. So the same owner channel splits in two:

OperationOwner-channel result
Create table / add column / build index (DDL)Runs normally
INSERT…SELECT (DML, source governed by FORCE RLS)SELECT source filtered to empty, INSERT 0 0
Bare INSERT with VALUES into the governed tableError: "violates row-level security" (visible)

The second row is the dangerous one: INSERT…SELECT fails in the shape of an emptied source, not a rejected target. No row ever attempts to enter, so no violation is ever raised β€” a silent 0 is far harder to notice than an error.

The fix​

The way out is to make the backfill session bypass β€” or satisfy β€” the tenant policy: a superuser (first choice for one-off migrations), a dedicated BYPASSRLS role (regular corrections), or per-tenant SET (keeping isolation semantics). A minimal reproduction first, then each option in turn.

Minimal reproduction​

-- A FORCE-RLS multi-tenant table
CREATE TABLE tasks (
id INT GENERATED ALWAYS AS IDENTITY,
tid UUID NOT NULL,
title TEXT,
done BOOLEAN DEFAULT false
);
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY;
CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

-- An unguarded archive table (the backfill target)
CREATE TABLE tasks_archived (
id INT,
tid UUID,
title TEXT,
done BOOLEAN
);

-- Seed two rows as superuser
INSERT INTO tasks (tid, title) VALUES ('11111111-1111-1111-1111-111111111111', 'a'),
('22222222-2222-2222-2222-222222222222', 'b');

-- Switch to an owner-role session (no tenant context):
SELECT count(*) FROM tasks; -- 0
INSERT INTO tasks_archived SELECT * FROM tasks; -- INSERT 0 0

count(*) returning 0 is the diagnostic pivot: the SQL is not wrong, the session simply cannot see the rows.

A superuser is not subject to RLS. Hand the backfill to the postgres role:

psql -U postgres -d mydb -v ON_ERROR_STOP=1 -f backfill.sql

The same statement flips from INSERT 0 0 to INSERT 0 23. The trade-off: maximum privilege, so reserve it for controlled one-off ops and never put it into application connection strings.

Option 2: a dedicated BYPASSRLS role​

If the ops channel runs data corrections regularly, create a dedicated role:

CREATE ROLE migrator WITH LOGIN BYPASSRLS;

A BYPASSRLS role skips every policy without acquiring the rest of the superuser privilege set β€” a narrower surface. It still needs explicit GRANTs per table, and the role's credentials must be treated as sensitive secrets.

Option 3: set tenant context per tenant​

To keep RLS semantics intact (the migration logic itself passes through isolation rules), run tenant by tenant inside a session:

SET app.tenant_id = '11111111-1111-1111-1111-111111111111';
-- backfill statements for that tenant

Fits backfills whose logic differs per tenant; for a straight full copy, a per-tenant loop is more ceremony than bypassing outright.

Always verify row counts afterwards​

Whichever channel you pick, the acceptance criterion for a backfill is not "command succeeded" β€” it is row reconciliation:

-- Baseline: affected rows (counted before the backfill)
SELECT count(*) FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL;

-- Landed: after the backfill
SELECT count(*) FROM task_assignees; -- total = baseline
SELECT count(DISTINCT task_id) FROM task_assignees; -- distinct tasks = baseline (single-select case)

In this incident, it was exactly the "baseline 23 = landed 23" check failing to add up that exposed the problem β€” the owner channel had printed INSERT 0 0, and without reconciliation the deployment would have shipped an empty child table. For belt-and-suspenders, join old and new rows on the primary key and compare migrated column values: zero diffs closes the loop.

Pitfalls on database write paths are rarely syntax errors β€” they are deployment-order and constraint-semantics mismatches. ON CONFLICT unique-constraint matching is the same family: the SQL is right, and a mismatched migration/deploy ordering still breaks everything.

The same FORCE RLS chain has a backup-side shape too: running pg_dump as the owner produces a structure-only backup with zero rows. Which channel each data action should take, and how to design restore-drill checks that catch it, is in the companion post pg_dump backup empty? FORCE RLS blocks the table owner too.

Gotchas​

On FORCE-RLS tables, the acceptance criterion for ops actions shifts from "command succeeded" to "row counts reconcile". All four points come straight from this incident:

Gotchas

  • A silent 0 is riskier than an error: when RLS empties the source of an INSERT…SELECT, nothing is raised. Backfill-type operations need a "baseline vs landed" row-count check, not just an exit code.
  • Never infer the data path from migration success: DDL bypasses RLS, so green DDL on the same channel proves nothing about DML. Probe the channel with a real DML statement.
  • missing_ok=true is part of the silent chain: current_setting('app.tenant_id', true) returns NULL when the setting is absent (policy always false, whole table filtered); with missing_ok=false a missing setting raises immediately, which surfaces the problem sooner. The lenient read is fine for app connections β€” just know what it does in ops sessions.
  • Keep superuser credentials in their own lane: the postgres role is for one-off ops only; it should never appear in connection strings, app config, or CI.

FAQ​

Why does Postgres row level security not seem to apply to the table owner?​

Because ENABLE ROW LEVEL SECURITY alone never constrains the table owner β€” policies only bind other roles by default. Add ALTER TABLE … FORCE ROW LEVEL SECURITY and every row-access statement from the owner session goes through policy evaluation too.

What does INSERT 0 0 mean in PostgreSQL?​

The two numbers are OID and row count: the statement succeeded but inserted 0 rows. Under FORCE RLS, a policy can filter the SELECT source of an INSERT…SELECT down to an empty set β€” nothing violates any policy, so nothing is raised. To pinpoint it, run SELECT count(*) in the same session first; a 0 confirms visibility filtering rather than a broken statement.

How do I bypass row level security in PostgreSQL for a data migration?​

Three options: run as a superuser such as the postgres role (bypasses RLS by definition β€” best for one-off backfills); create a dedicated role with BYPASSRLS; or SET app.tenant_id per tenant to keep RLS semantics. Whichever you choose, follow up with a row-count check against the baseline.

Does FORCE ROW LEVEL SECURITY affect DDL statements?​

No. RLS evaluates row access only β€” SELECT visibility and write legality. CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation, which is why the same migration run shows all-green DDL next to a silently empty DML backfill.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

PostgreSQL ON CONFLICT: there is no unique constraint? Sync INSERTs after changing the unique key

Β· 6 min read

Right after tightening a table's unique key β€” dropping a column that no longer discriminated between rows β€” every previously working UPSERT immediately failed in bulk with there is no unique or exclusion constraint matching the ON CONFLICT specification.

Encountered this while building AI Analytics β€” an LLM-powered analytics pipeline that surfaces market trends, user behavior, and sales data for precise operations.

TL;DR​

PostgreSQL's ON CONFLICT (cols) requires cols to exactly match an existing unique constraint or unique index (same columns, same order β€” otherwise SQL state 42P10). The moment you ALTER the unique key, every INSERT ... ON CONFLICT that references it must be updated; and once the migration lands, the write side must deploy immediately, because the in-between window keeps erroring.

The symptom​

As soon as the unique-key change went live, the scheduled import job failed across the board, with only this line in the write log:

ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
SQL state: 42P10

Zero rows written to the business table, while plain SELECTs against the same table worked fine β€” the failure was isolated to the ON CONFLICT write path.

Root cause​

The column set you pass to ON CONFLICT (cols) is the arbiter. PostgreSQL requires it to exactly match some UNIQUE constraint or unique index on the table:

  • the set of columns must be the same;
  • the order of columns must be the same;
  • for a partial unique index (one with a WHERE), ON CONFLICT must carry the same WHERE.

When nothing matches, PostgreSQL has no index to decide what "conflict" means, and raises 42P10.

The classic trigger is shrinking a unique key. The original key had 3 columns; you realize one of them (say audience) has 4 distinct values whose metric rows are 100% identical β€” pure redundancy β€” so you drop it down to 2 columns. That's the right optimization, but the old INSERT still says ON CONFLICT (c1, c2, c3) while only (c1, c2) remains as a unique constraint. The arbiter has no landing spot, and the statement errors out.

old unique key: UNIQUE (store_id, metric_key, audience)
new unique key: UNIQUE (store_id, metric_key)

old INSERT: ON CONFLICT (store_id, metric_key, audience) ← no match

The fix​

Here is a minimal reproduction β€” create, trigger, and fix in one go, runnable directly in psql:

-- 1. A table with a 3-column unique key
CREATE TABLE daily_metric (
store_id TEXT NOT NULL,
metric_key TEXT NOT NULL,
audience TEXT NOT NULL,
value NUMERIC,
CONSTRAINT daily_metric_unique UNIQUE (store_id, metric_key, audience)
);

-- 2. Old UPSERT: ON CONFLICT includes audience
INSERT INTO daily_metric (store_id, metric_key, audience, value)
VALUES ('s1', 'revenue', 'visitor', 100)
ON CONFLICT (store_id, metric_key, audience)
DO UPDATE SET value = EXCLUDED.value;

-- 3. Shrink the unique key: drop audience
ALTER TABLE daily_metric
DROP CONSTRAINT daily_metric_unique,
ADD CONSTRAINT daily_metric_unique_new UNIQUE (store_id, metric_key);

-- 4. Re-run the INSERT from step 2 β€” it now errors ↓
-- ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification

The fix is to shrink the INSERT's ON CONFLICT columns to match the 2-column key. Since audience no longer discriminates, pin it to a literal on the write side so incoming parameters can't synthesize extra rows:

INSERT INTO daily_metric (store_id, metric_key, audience, value)
VALUES ('s1', 'revenue', 'visitor', 100)
ON CONFLICT (store_id, metric_key) -- ← shrunk to match
DO UPDATE SET value = EXCLUDED.value;

The part that actually bites is the deployment order, not the SQL itself:

  1. Ship the migration first (DROP old constraint + ADD new constraint);
  2. Immediately ship the write-side code (the INSERT's ON CONFLICT becomes 2 columns);
  3. Leave no gap between the two β€” old code against the new schema raises 42P10, and new code against the old schema raises 42P10 just the same (no 2-column unique constraint exists yet).

If you use an ORM like Drizzle, an ON CONFLICT column list baked into a sql template is easy to forget when the schema changes β€” the cost of schema/write-side drift shows up in another Drizzle + PostgreSQL pitfall too.

Caveats​

Caveats

  • Column order matters: ON CONFLICT (a, b) does not match UNIQUE (b, a) β€” the order must agree.
  • Partial unique indexes need the WHERE: if the arbiter is UNIQUE ... WHERE active, the INSERT must read ON CONFLICT (cols) WHERE active DO ..., or you get 42P10 all the same.
  • "Just skip on any conflict": use ON CONFLICT DO NOTHING without columns β€” it specifies no arbiter and matches no specific index, catching every conflict.
  • During rollout: old and new write-side versions may briefly coexist. Make sure both can match the current schema, or ship the migration and the code together with no window in between.

FAQ​

Does PostgreSQL ON CONFLICT require a unique constraint?​

Only when you name columns. ON CONFLICT (cols) must match an existing UNIQUE constraint or unique index exactly, or you get 42P10. If you just want "skip on any conflict" without caring which constraint fired, use ON CONFLICT DO NOTHING without columns β€” it needs no specific index.

Can PostgreSQL ON CONFLICT target multiple unique constraints?​

No. A single INSERT's ON CONFLICT can name only one arbiter constraint (one column set, or one index name). A table may have multiple unique keys, but a single statement picks exactly one for conflict detection. To handle different unique keys differently, either split into multiple writes or query first in the application layer before choosing INSERT vs UPDATE.

How to fix there is no unique or exclusion constraint matching the ON CONFLICT specification?​

That is error code 42P10: the ON CONFLICT column set has no matching unique index on the table. Check in order: a UNIQUE constraint covers those columns, the columns and their order match exactly, and any INSERT was updated after a recent unique-key change. If the arbiter is a partial unique index with a WHERE, add the same WHERE clause to ON CONFLICT.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me