Skip to main content

19 posts tagged with "PostgreSQL"

View all tags

Postgres Lateral Can't See the UPDATE Target? Use a CTE

· 7 min read

In a migration pipeline for a Node.js + PostgreSQL service, a data-migration SQL using UPDATE ... FROM lateral was rejected by psql with a clear error; the same file handed to drizzle-kit migrate failed silently — exit 1, with nothing but two unrelated NOTICEs in the output.

TL;DR​

The UPDATE/DELETE target table has zero visibility inside a lateral: top-level references fail, nested ones fail too — the SELECT intuition that "a lateral sees earlier FROM items" simply does not apply here. psql states the error plainly, while drizzle-kit (postgres-js driver) swallows it into a silent exit, which left a dev database's migration ledger three versions behind. Fix: rewrite every correlated reference to the target table as a CTE with correlated subqueries, and verify complex migrations with psql -v ON_ERROR_STOP=1 before they reach the toolchain.

Symptoms: psql speaks up, drizzle-kit says nothing​

The same migration file, two execution paths, opposite behavior: psql shows the error, drizzle-kit fails quietly.

The psql-side error, verbatim:

ERROR:  invalid reference to FROM-clause entry for table "t"
LINE 1: ... UPDATE tenants AS t SET settings = t.settings FROM lateral (SELECT t.settings ...
^
HINT: There is an entry for table "t", but it cannot be referenced from this part of the query.

The first instinct was "the reference is written wrong": move the target-table reference into the lateral's select list — still rejected; wrap it one level deeper in a scalar subquery — the same error again. Two edits died on the same sentence, which is what forced a change of direction: this is not about where you place the reference. Search phrasing for the same problem varies — "postgres update from lateral", "lateral reference to the outer update table" — all pointing at the same semantic gap.

The drizzle-kit side was worse: pnpm db:migrate exited 1 on the same file, stderr holding only two unrelated NOTICEs, no error message at all. The dev database's migration ledger stayed at 0027, three later migrations never applied, and tenant settings were missing the new keys — no alert anywhere in the process.

For why migration ledgers fall behind silently and how to reconcile them at deploy time, see drizzle-kit migrate: table missing? Journal silently skipped — same lesson: never trust a green tool alone.

Root cause: the lateral has zero visibility into the UPDATE target​

The conclusion, stated hard: the UPDATE/DELETE target table cannot be referenced from a lateral at any position — not "only at the top level", but nowhere.

In SELECT, a lateral sees the FROM items before it; carried over to UPDATE ... FROM, that intuition breaks: Postgres removes the target table from the lateral's visible set entirely in UPDATE/DELETE context. The HINT says it all — the entry exists, but it cannot be referenced from this part of the query, and both the top level and nested levels count as "this part". That is exactly why moving the reference into the select list still failed: no legal position exists.

A minimal reproduction on PG 16 (temp tables suffice; both variants fail with the identical message):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

-- Variant A: lateral top level references target t → rejected
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT t.settings->>'a' AS va) x
WHERE t.id = 1;
-- ERROR: invalid reference to FROM-clause entry for table "t"

-- Variant B: one nested scalar subquery to "relay" the value → same error
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT (SELECT t.settings->>'b') AS vb) x
WHERE t.id = 1;
ROLLBACK;

Of the two failure sources, the drizzle-kit half is the more dangerous: swallowed error → no logs → dev state lags indefinitely with no alert. The psql half at least says something every time.

Fix: move correlated reads into a CTE​

Put the reads of the target table into a plain CTE and let UPDATE ... FROM do a key join only — semantically equivalent to the original lateral intent, with no reference-position restrictions. This is the final shape of that 0029 migration:

WITH src AS (
SELECT id,
settings->>'daily_remind' AS v1,
settings->>'daily_remind_at' AS v2
FROM tenants
WHERE settings ? 'daily_remind'
)
UPDATE tenants AS t
SET settings = t.settings || jsonb_build_object('remind_time', src.v2)
FROM src
WHERE t.id = src.id;

The CTE is an ordinary SELECT — no restrictions on referencing the target table; UPDATE ... FROM src does an equality join only.

The matching minimal check (PG 16, fully self-contained — the previous block's temp table was rolled back, this one rebuilds it):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

WITH src AS (
SELECT id, settings->>'a' AS va
FROM t0
WHERE settings->>'a' IS NOT NULL
)
UPDATE t0 AS t
SET settings = t.settings || jsonb_build_object('a_cte', src.va)
FROM src
WHERE t.id = src.id;
-- UPDATE 1
ROLLBACK;

Three verification passes after the rewrite: the same file verified through both the pg 8.16 node driver and psql; applied twice to the dev database — UPDATE 3 the first run, UPDATE 0 the second — idempotent; ledger reconciled after backfilling, __drizzle_migrations count equal to the migration file count.

Before you ship

  • The SELECT lateral intuition does not carry to UPDATE/DELETE FROM: rewrite correlated references to the target as CTE + correlated subqueries, never lateral.
  • Verify complex data migrations with dev psql -v ON_ERROR_STOP=1 before they reach the drizzle-kit toolchain — never trust a green tool alone.
  • After drizzle-kit migrations, reconcile the ledger count against the file count routinely; a "done" with no output counts as a failure.

FAQs​

What does 'invalid reference to FROM-clause entry for table' mean in Postgres?​

A FROM entry exists but can't be referenced from where you used it. The classic trigger: a lateral subquery in UPDATE/DELETE FROM referencing the target table — Postgres rejects every position, top level included (verified on PG 16); the HINT says cannot be referenced from this part of the query. Other common causes are join order or alias scope mistakes.

Can a lateral subquery reference the UPDATE target table in Postgres?​

No — not at any position. Unlike SELECT, where a lateral sees earlier FROM items, UPDATE and DELETE give the lateral zero visibility into the target table at any nesting depth (PG 16 verified, top level included). Move the correlated reads into a CTE and join by key.

Why does drizzle-kit migrate fail with no error output?​

The postgres-js driver swallows the error: exit 1 with nothing but two unrelated NOTICEs on stderr. It once left a dev database stuck three migrations behind with no alert. Run complex SQL through psql -v ON_ERROR_STOP=1 first.

What is the correct rewrite for UPDATE FROM lateral?​

A CTE joined by key: WITH src AS (SELECT id, settings->>'k' AS v FROM target) UPDATE target t SET ... FROM src WHERE t.id = src.id. The CTE is a plain SELECT with no reference restrictions; verified on PG 16 with UPDATE 1, and idempotent as UPDATE 3 then UPDATE 0 on a real migration.

CCLEE

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

Work with me

Postgres Table Count 0=0? Schema Is Not the Database Name

· 7 min read

While adding a table-count comparison to our restore-drill script, the source and temp databases both reported 0 tables — 0=0, verdict "pass" — while a manual count of the same database showed 25 tables.

Ran into this while building CCLee Server Sentinel — monitoring and alerting for Linux servers: performance, availability, security and backup. Alerts arrive as conclusions with next steps, and backups are proven restorable by monthly real-restore drills.

TL;DR​

In PostgreSQL, information_schema.tables' table_schema column holds the namespace inside the current database — tables live in public by default — not the database name. Counting a database's tables requires connecting to that database first (psql -d dbname) and counting public. Our drill script got both wrong at once: it queried the database name as the schema and hardcoded -d postgres (the maintenance database), so every count was 0 and two equal zeros always "passed". After the fix, a real drill ran 25=25.

Symptom: the table-count check is a permanent 0=0 pass​

The drill's status file recorded per_db as "app_db:0:0" — source database 0 tables, temp database 0 tables, counts equal, status reported ok. That was the script's first real run on 2026-11-22.

The contradiction was already two days old: the manual drill on 2026-11-20 had counted 25 tables in the same imported copy. In other words, the script-side table-count comparison had never touched a real value — even if half the tables had gone missing during import, 0=0 still holds and the check still passes. A count of 0 on both sides is a check with a permanently green light.

Root cause: table_schema is not the database name, and psql connected to the wrong database​

Two bugs stacked — either alone breaks the count; together they make source and temp databases wrong in the same direction, which removes the comparison's ability to detect any difference.

First: the database name was used as the schema. PostgreSQL's hierarchy is database → schema (namespace) → table, and application tables land in the public namespace by default. The table_schema column of information_schema.tables stores the namespace name. Matching a database name against table_schema asks "is there a namespace named app_db" — always an empty set, so COUNT returns 0.

Second: the connection was hardcoded to the maintenance database. Every PostgreSQL instance ships with a default maintenance database named postgres. The old code pinned -d postgres, so the query ran against the maintenance database — and information_schema only shows the contents of the currently connected database.

The pre-fix db_count:

db_count(){  # $1=engine $2=container $3=user $4=schema → 表数(对正式库只读 COUNT,不改数据)
local sql="SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'"
if [ -n "$2" ]; then
case "$1" in
postgres) docker exec "$2" psql -U "$3" -d postgres -t -A -c "$sql" ;;
mysql) docker exec "$2" mysql -u "$3" -N -B -e "$sql" ;;
esac
else
mysql -N -B -e "$sql"
fi
}

The call site runs it once per database:

src=$(db_count "$engine" "$container" "$u" "$db")    # source tables
dst=$(db_count "$engine" "$container" "$u" "$tmp") # temp drill tables

Both calls go through the same function and make the same mistake, so src=0 and dst=0, and 0=0 passes.

Why MySQL never hits this​

In MySQL, schema and database are synonyms: CREATE DATABASE and CREATE SCHEMA are equivalent, and information_schema.tables is visible across the whole instance, so WHERE table_schema='dbname' is simply correct. This script supports both engines, and the MySQL semantics were carried into the PostgreSQL branch without a second look — inside one function, $4 meant two different things.

The fixed version branches by engine:

db_count(){  # $4 在 postgres 语义是目标库名,在 mysql 语义是 schema(=库名)
if [ -n "$2" ]; then
case "$1" in
postgres) docker exec "$2" psql -U "$3" -d "$4" -t -A -c \
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public'" ;;
mysql) docker exec "$2" mysql -u "$3" -N -B -e \
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'" ;;
esac
else
mysql -N -B -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'"
fi
}

The postgres branch changes two things: -d "$4" connects to the target database itself, and table_schema='public' counts the default namespace. The MySQL branch is untouched.

Why the regression tests stayed green: the stub mirrored the bug​

The script ships with a 22-assertion regression suite, and it was green the whole time — because the test stub was written to match the implementation's wrong semantics. The old stub parsed the table_schema='...' value out of the SQL and used it as a lookup key: however the implementation queried, the stub answered. Implementation and stub shared the same wrong assumption, so the test had nothing to catch.

# before: the stub answered by the caller's query semantics — argument used as schema
sch=$(printf '%s' "$sql" | sed -E "s/.*table_schema='([^']*)'.*/\1/")
cat "$ST/count.$sch" 2>/dev/null || echo 0

# after: the stub answers by the -d target database (matching real psql behavior)
cat "$ST/count.$tgt" 2>/dev/null || echo 0

The lesson: a stub should simulate the real contract of the external system (what information_schema returns after psql -d somedb), not copy the caller's query code. The moment a stub copies the implementation, the test only proves the implementation agrees with its own shadow.

Fix: connect to the target database and count public​

The fix was two moves: correct db_count's postgres branch (shown above), and correct the stub's lookup in the same commit. All 22 assertions stayed green, then a real drill re-ran on the client machine — this time per_db recorded app_db:25:25 (drill_date=2026-11-21), the first time the comparison touched real values.

Silent failure modes on a backup chain rarely come alone: the backup file itself can come out empty — PostgreSQL's FORCE RLS stops even the owner session's COPY, producing an archive that "looks fine". That pitfall and its fix are in Postgres pg_dump backs up no data? FORCE RLS blocks the owner too. For the cleanup side of information_schema.tables, see PostgreSQL left orphan tables after migration? Audit schema residue with information_schema.

Watch out

  • ON_ERROR_STOP=1 only catches import-time errors; "no errors on import" does not mean the content is intact. Table counts are the floor — row counts and sample queries against business tables cover actual data damage.
  • The same mistake recurs in disguise: filtering pg_tables by database name as schemaname, or pg_class by database name as namespace, also yields an empty set. The rule is simple — in PostgreSQL these columns mean namespace, and the database name only belongs in -d (which database to connect to).

FAQ​

How do I count tables in a PostgreSQL database?​

Connect to that database itself (psql -d dbname), then run SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public'. table_schema holds the namespace name (public by default), not the database name. Running the query from another database cannot see the target database's tables.

What does table_schema mean in information_schema.tables?​

In PostgreSQL it is the namespace inside the currently connected database — tables land in public by default. It is never the database name. In MySQL the two coincide, which is why the same SQL means different things across engines.

How often should you test your database backups?​

Run a real restore drill at least monthly: import the dump into a scratch database and verify the result. Comparing table counts is the floor; row counts and sample queries go further. A backup file that merely exists is not a verified backup.

CCLEE

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

Work with me

drizzle migration skipped silently? Check the journal first

· 7 min read

On a Node.js + PostgreSQL multi-tenant system, a deploy printed "no pending migrations", everything stayed green — and about 18 minutes later production hit "relation does not exist". The batch shipped a create-table migration that had never executed, and the application container logs held not a single error.

TL;DR​

drizzle decides "which migrations are applied" from two ledgers: drizzle.__drizzle_migrations in the database (execution ledger) and drizzle/meta/_journal.json (registration manifest). Either can break silently. Hand-edited future timestamps inflate the execution ledger's max(created_at) — the watermark migrate uses — pinning every later migration below it; a raw SQL file dropped into drizzle/ without journal registration never enters the pending list. Fix: register hand-written migrations via generate --custom, never hand-edit the ledgers, and put a "journal count = file count" gate in the deploy pipeline.

Symptoms: two incidents, two broken ledgers​

Incident one: migrate reports success, the next step fails on a missing table. pnpm db:migrate (drizzle-kit migrate) finished with normal output; the following step, applying RLS policies, failed with relation "task_assignees" does not exist — the create-table migration it depends on (0032) had not run, yet migrate's output and exit code showed nothing wrong.

Hand-fixing the ledger and re-running migrate produced a second problem: the tool re-applied 0028 and 0029, two migrations long since applied. __drizzle_migrations accumulated duplicate and orphan rows — 34 rows for 32 migration files.

Incident two: the deploy says "no pending migrations", production lacks the table. Another release carried a hand-written create-table SQL (0037). The deploy's migration check reported no pending work; nobody noticed, and the application container started normally. The missing table surfaced only when the WeCom-side department sync failed. Roughly 18 minutes ran with production missing the table and zero errors in the logs.

Post-incident reconciliation: journal 36 entries, production ledger 36 rows — both sides "consistent", each one entry short. The 0037 SQL file sat in drizzle/ with no journal registration.

Root cause: how drizzle decides "which migrations are applied"​

The decision reads only the ledgers, and each pit corrupts one of them.

The watermark: the ledger's max(created_at) is the only waterline. drizzle-orm's migrate uses the largest created_at in the ledger as the watermark and applies only journal entries whose when is greater. The setup for incident one came earlier: to force a re-apply, someone had hand-edited when values in _journal.json to future timestamps (like 1794716400000). After the journal was normalized back to real chronology, the future created_at rows were still in the ledger — the watermark stayed high, and 0032, whose when sat below it, could never satisfy "when > watermark". Skipped forever, no output.

Hashes are computed at execution time, so re-runs insert new rows. The hash migrate uses for bookkeeping is computed from the SQL file's content when it executes, not read from the ledger. That explains the second half of incident one: the old migrations re-running were not considered "already applied", and each inserted a fresh ledger row — hence the duplicates and orphans (34 > 32).

A raw file outside the journal is invisible to the pending list. The pending list is effectively the journal entries minus the ledger rows. 0037 had no journal entry: journal 36 = ledger 36, the difference was empty, so "no pending migrations". Tests did not catch it either: the catalog/integration tests run against a test database cloned from dev, and dev had already received 0037 by direct psql, with a bookkeeping row to match — structure complete, everything green. Of the three ledgers (journal, dev, test), exactly one was wrong and the other two agreed.

Fix: register through the proper channel, gate the deploy​

Hand-written migrations must go through generate --custom:

# Back up first! The command overwrites an existing file of the same name
cp drizzle/0037_departments.sql /tmp/0037_backup.sql
pnpm exec drizzle-kit generate --custom --name=departments
# Put the SQL into the generated stub; journal and snapshot register automatically

Never hand-edit journal when or ledger created_at — normalize what was edited: restore when to real chronology; delete duplicate/orphan ledger rows and align created_at with the journal; then verify three things — ledger rows = file count, max(created_at) matches the last migration, and a re-run of migrate is a no-op. Incident one cleared up in that order, and later migrations resumed applying.

Two hard rules for the deploy pipeline:

  1. Journal count ≠ drizzle/*.sql file count → halt the deploy and print the mismatched filenames. This is the only reliable signal of an unregistered raw file — the database-side ledger can look "normal" because dev was hand-applied.
  2. The output says "no pending migrations" while the batch ships migration files → contradiction. Stop and inspect the journal.

The ledger decision behind migrate, and where the two pits sit

The gate has caught a real case: after registering 0037, the journal held 37 entries, the deploy re-identified 1 pending migration, and the owner channel — per-file psql ON_ERROR_STOP, server-side sha256 bookkeeping, ownership and policy checks — completed with the ledger reconciled at 37/37. Why that owner channel replaced drizzle-kit migrate on the deploy path in the first place (a different pit: the ledger diverging from the actual tables) is in the companion post drizzle-kit migrate: exit 0 but no tables? Audit the journal — together the two posts map the whole ledger: that one covers ledger-vs-database, this one covers the ledger corrupting itself.

Watch out

  • drizzle-kit generate --custom overwrites an existing file of the same name — back up the hand-written SQL before generating, then fill the stub. Do not let the tool silently eat your file.
  • Run the count check twice over: journal vs file count (registration completeness), ledger vs journal (execution completeness). Incident two's 36 = 36 shows why one comparison is not enough.
  • When hand-inserting ledger rows, match the existing row shape (hash = sha256 of the full SQL file, created_at as a bigint epoch in seconds); mixed formats break later reconciliation — details in the companion post.

FAQ​

Why is drizzle-kit migrate not applying my migrations?​

Two ledgers, two failure modes. Count drizzle.__drizzle_migrations against the number of SQL files in drizzle/ — a mismatch means an unregistered file that will never apply. If the counts match, check drizzle/meta/_journal.json: any entry whose when is below the ledger's max(created_at) is pinned below the watermark and silently skipped forever.

Can I edit drizzle's journal manually?​

Leave the when fields in _journal.json and the created_at values in the ledger alone. migrate uses the ledger's max(created_at) as the watermark and only applies entries with when greater than it — a future timestamp inflates the watermark permanently, and later migrations stay skipped even after you normalize the journal.

How do I add a hand-written migration to drizzle properly?​

Never drop a SQL file straight into drizzle/ — without a journal entry it is invisible to the pending list and will never execute. Generate the file with drizzle-kit generate --custom --name=xxx (which registers the journal and snapshot) and put the SQL into the generated file.

CCLEE

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

Work with me

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

drizzle-kit migrate: exit 0 but no tables? Audit the journal

· 9 min read

While shipping a batch of new tables for a multi-tenant system, drizzle-kit migrate on the deploy host printed "applying migrations" and exited quietly with code 0 — the application then started and its very first query failed on a missing table.

Ran into this in the deploy pipeline of a Node.js + PostgreSQL multi-tenant system (Drizzle ORM for migrations, row-level security isolating tenants, drizzle-orm 0.45.4 / drizzle-kit 0.31.11).

TL;DR​

Exit code 0 does not mean the migration applied. drizzle-kit's journal (the drizzle.__drizzle_migrations ledger) and the actual tables in the database are two different books: when the journal says "applied" but the table is missing, every later migration is skipped silently. Three steps: reconcile (journal count = migration file count, key tables present in information_schema) → re-apply missing files with psql -v ON_ERROR_STOP=1 and insert the journal row by hand → fix table ownership with OWNER TO. On the deploy path we retired drizzle-kit migrate entirely in favor of an owner pipeline: per-file apply + server-side journaling + verify-or-stop.

Symptoms: three errors, all exit code 0​

There are three layers to this, the first two in the migration command and the third right after it — none of them produce a failure signal on the command level. If you searched "drizzle migrate not working", "migrations applied but no tables", or "must be owner of table", read on.

Symptom one: the migration prints "applying", exits 0, tables missing.

$ drizzle-kit migrate
...
applying migrations...
$ echo $?
0

The local dev database hit the "journaled but not created" shape first — an interrupted migration left a half state behind, and every later migrate run treated that batch as applied and skipped it. Production hit the same problem in the opposite shape: migration 0019 exited 0 with neither the SQL applied nor the journal row written.

Symptom two: adding a foreign key fails with an unrelated error.

ERROR:  unrecognized configuration parameter "app.tenant_id"

Symptom three: with the key in place, the policy script stalls.

ERROR:  must be owner of table conflict_events

All three errors are segments of the same deploy pipeline.

Root cause: the journal and the schema are two different books​

The journal records "booked", not "the table exists". drizzle-kit migrate reads the SQL files in the migrations folder and decides what to skip by comparing hashes in drizzle.__drizzle_migrations — the journal is its only input. Once a "journaled row, missing table" intermediate state exists (most often left by an interrupted migration), every later migrate run believes that batch is done and skips it: no error, exit code 0. Production's 0019 was the inverse — neither applied nor journaled — but it surfaced the same way: caught by the ledger reconciliation, with no signal from the command itself.

Plainly put: this is a design where status is judged from the ledger alone, and when the ledger is polluted or never written, drizzle-kit offers no clue about it. Why it skips silently on the normal path, the command does not explain — our response was to stop trusting its judgment on the deploy path (the trade-off is explained in the fix).

Foreign keys meet RLS: the RI check runs without tenant context​

The referential-integrity trigger reading the referenced table does not carry your application's tenant injection. Multi-tenant tables usually have row-level security (RLS) policies that read a session variable via current_setting('app.tenant_id'). But the referential integrity (RI) check is an internal trigger scan: it runs on a bare connection that never SET app.tenant_id, so current_setting throws unrecognized configuration parameter — the foreign key isn't wrong, the policy blows up on that bare connection first.

The fix is one parameter:

current_setting('app.tenant_id', true)  -- returns NULL when unset

NULL matches no rows inside the policy (equivalent to deny), so the isolation semantics are unchanged while the RI check's bare connection stops erroring. For an RLS database the order becomes fixed: fix the policies first, then add the foreign keys.

Ownership drift: superuser-owned tables block policy application​

Policies can only be changed by the owner, and historical tables may be owned by someone else. The three tables apply-policies choked on (conflict_events, equipments, vendors) had been created manually by a superuser much earlier — owned by postgres, not by the owner role migrations run as. CREATE POLICY requires the table owner; with the wrong owner, applying all 15 policy files stalls.

Reclaim ownership:

ALTER TABLE conflict_events OWNER TO app_owner;

And audit the whole database — this query must return 0 rows:

SELECT tablename FROM pg_tables WHERE tableowner <> 'app_owner';

Fix: reconcile → re-apply → reclaim → harden the deploy path​

For 0019 the order of events was: fix the policy, add the foreign key, get blocked again by table ownership — after reclaiming the three tables, all 15 policy files applied, and only then did the journal check reveal that 0019 had never been applied or recorded. Later, 0020 skipped silently on the same pipeline, and this time the deploy entry's ledger check stopped it before the half-applied state went live. After those two recurrences, the deploy-path migration became a fixed shape:

  1. Reconcile (a fixed step after every migration):
SELECT count(*) FROM drizzle.__drizzle_migrations;
-- must equal the number of files in the migrations folder

SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
-- key tables must actually exist
  1. Re-apply: for missing journal rows, pipe the SQL in as the owner role, then add the journal row:
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < drizzle/0019_missing.sql
# journal row: hash = sha256 of the full SQL file; created_at = epoch seconds (bigint), matching existing rows
  1. Reclaim: check owners, ALTER TABLE … OWNER TO app_owner (previous section), re-run policy application.

  2. Harden the deploy: replace "run drizzle-kit migrate once" with a per-file loop — apply each file with ON_ERROR_STOP and stop on the first failure, compute the journal hash server-side, and reconcile the count at the end:

for tag in $pending; do
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < "drizzle/$tag.sql"
hash=$(sha256sum "drizzle/$tag.sql" | cut -d' ' -f1)
psql -d appdb -c "INSERT INTO drizzle.__drizzle_migrations (hash, created_at)
VALUES ('$hash', extract(epoch from now())::bigint)"
done
# final check: journal count = local migration file count, otherwise abort the deploy

Deploy-time migration: the owner pipeline

The trade-off: why not keep drizzle-kit migrate? What a deploy needs is not "let the tool decide" but "the applied result is verifiable, and any failure stops the run". Per-file application turns every action into an assertable atomic step, and the ledger reconciliation turns "silently skipped" into an explicit failure. Local development keeps using the package.json db:migrate script (drizzle-kit migrate plus policy application) — what retired is the deploy usage, not the tool.

That owner pipeline guards against the journal and the schema diverging — but the ledger itself can be corrupted: hand-edited future timestamps in _journal.json inflate the watermark max(created_at) and pin every later migration below it, and a raw SQL file without journal registration never enters the pending list. Both shapes and their fixes are in the companion post drizzle migration skipped silently? Check the journal first.

The same family of "the migration looked done" exists on the SQLAlchemy side: three Alembic migration pitfalls (async engine misuse, broken revision chains, model changes without migrations). To systematize existence and ownership checks, see auditing orphan tables with information_schema.

Watch out

  • Run both checks after every migration: journal count = migration file count, and the key tables exist in information_schema. Both passing is what "migration complete" means; the exit code alone is not evidence.
  • Manual journal rows must match the existing format: hash is the sha256 of the full SQL file, created_at is epoch seconds as bigint — keep the same types drizzle-kit writes, or later reconciliations drift.
  • Run migrations as the owner role, always: tables created by a superuser are owned by the superuser, and the next policy application stalls for sure. The owner check belongs in the post-migration checklist.

FAQ​

Why does drizzle-kit migrate exit 0 without creating tables?​

The journal and the schema have diverged. Reconcile two counts: SELECT count(*) FROM drizzle.__drizzle_migrations; must equal the number of migration files, and information_schema.tables must contain the tables. Re-apply the missing SQL with psql -v ON_ERROR_STOP=1 and insert the journal row manually (hash = sha256 of the SQL file).

drizzle-kit migrate vs push — which one for production?​

migrate applies versioned SQL files tracked in a journal — one journal row per file; push diffs the schema directly with no history. Versioned files plus a verification step fit production better — but don't trust the exit code alone: reconcile the journal against the actual tables after every run.

How do I verify drizzle migrations were actually applied?​

Two counts plus one ownership check: the journal count equals the migration file count, the new tables exist in information_schema.tables, and SELECT tablename FROM pg_tables WHERE tableowner <> 'owner_role'; returns 0 rows — otherwise policy application fails with "must be owner of table".

CCLEE

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

Work with me

Postgres 42501 on new tables? Default grants per database

· 6 min read

While creating new tables with a dedicated owner role in a multi-tenant system, every query from the application role failed with permission denied for table — old tables were fine, every freshly migrated table was unreachable.

Ran into this in a Node.js + PostgreSQL multi-tenant system (row-level security isolating tenant data).

TL;DR​

ALTER DEFAULT PRIVILEGES is not a global switch: its scope is "which role grants × which database it runs in". Running it once in the postgres database gives future tables in your app database nothing — queries fail with 42501 anyway. Fix in two moves: run it in every application database; and when DROP ROLE complains about dependencies, clear the stale entries with DROP OWNED BY in that same database.

Symptoms: old tables work, new tables fail with 42501​

A freshly created table is immediately unreadable for the application role while the same role queries every existing table without trouble — grants missing only on "tables created after migration" is the signature of missing default privileges. If you searched "postgres permission denied for table", "42501 insufficient privilege", or "granted privileges but still permission denied", it's the same problem.

-- a table the owner role just created via migration
ERROR: permission denied for table vendors
SQLSTATE: 42501

The second symptom shows up later, when cleaning up a role:

ERROR:  role "app_role" cannot be dropped because some objects depend on it
DETAIL: privileges for default privileges in database appdb

The DETAIL line is the tell: the dependency is not a table or a function, it's a stale default-privileges entry.

Root cause: ALTER DEFAULT PRIVILEGES is scoped to a role × a database​

The default-privilege rule lives in the database where you ran it, and never crosses databases. What ALTER DEFAULT PRIVILEGES records is a rule — "objects created in this database, from now on, by the role named in FOR ROLE (default: the current role), are granted to the TO role automatically". The rule is stored in the database-local pg_default_acl catalog, which means:

  • run it in the postgres database → only future objects in the postgres database are covered
  • never ran it in the app database → new tables there carry no default grants at all
  • tables get created by a different role (no FOR ROLE) → the rule doesn't match

The order of events that produced this: a tutorial-style "global" default-privilege statement ran in the postgres database first, then the app database was created. The first few tables happened to be granted manually, so everything looked fine — until migrations started creating tables automatically and 42501 errors appeared in bulk. First hypothesis: a missing GRANT statement; adding grants changed nothing. The stale entry surfaced only when dropping an unused role failed with privileges for default privileges in the DETAIL — the grants did exist, just in the wrong database.

PostgreSQL treating "where you run it" as a behavior boundary shows up elsewhere too: fe_sendauth across containers is the same logic — identical command, different execution path, completely different rules.

ALTER DEFAULT PRIVILEGES scope: one role × one database

Fix: grants go into the app database, cleanup goes into the same database​

Three steps, all organized around the database unit:

  1. Inventory which databases have default privileges. Run in each database; 0 in an application database means it was missed:
SELECT count(*) FROM pg_default_acl;
  1. Run the default grants per database. One statement for TABLES, one for SEQUENCES, FOR ROLE naming the role that actually creates tables:
-- run with psql -d <appdb>, not while connected to the postgres database
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_role;

ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app_role;
  1. Clear stale entries. When DROP ROLE reports dependencies, connect to each database named in the DETAIL (every database holding default-privileges entries) and run:
DROP OWNED BY app_role;
DROP ROLE app_role;

For new databases, bake step 2 into the provisioning script — every grant statement in our init script is forced through -d <database>, which rules out the "ran it while connected to postgres" failure mode for good.

Default privileges only cover future objects, so tables that already exist need a one-time grant:

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_role;

Watch out

  • No FOR ROLE means the current role: run it as the superuser without FOR ROLE and the rule is attached to the superuser — it only fires when the superuser creates objects, and migrations running as the owner role still produce ungranted tables.
  • DROP OWNED drops objects too: it revokes the role's privileges in that database and drops objects it owns. Use it for dedicated roles being removed, not casually on shared roles.
  • A new database is a new grants gap: default privileges are not inherited on CREATE DATABASE. "Create database → immediately set default privileges" should be one fixed step in the provisioning script.

FAQ​

Why is ALTER DEFAULT PRIVILEGES not working for new tables?​

Its scope is one role in one database: running it in the postgres database only affects future objects created there. Run it in each application database, with FOR ROLE set to the role that actually creates tables.

What does PostgreSQL error 42501 (permission denied for table) mean?​

SQLSTATE 42501 is insufficient_privilege. When old tables query fine and only migrated tables fail, the app role is missing default grants — verify with SELECT count(*) FROM pg_default_acl; in that database (0 means none configured), then add the per-database ALTER DEFAULT PRIVILEGES.

Do I need ALTER DEFAULT PRIVILEGES FOR ROLE in every database?​

Yes — once per database per table-creating role, and it only covers future objects, so existing tables need a one-time GRANT ... ON ALL TABLES IN SCHEMA public. To drop a role blocked by "privileges for default privileges", run DROP OWNED BY in each database holding stale entries, and retry DROP ROLE once SELECT count(*) FROM pg_default_acl; returns 0 there.

CCLEE

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

Work with me

Airflow DAG gone but metadata stays? Delete order matters

· 5 min read

The .py file is gone from the codebase and deployed — yet the DAG still sits in Airflow's list. You clean the metadata tables by hand, and minutes later the rows are back.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Retiring old analysis types in the DAG pipeline left zombie entries piling up in the list page.

Symptom: the file is gone, the metadata refuses to leave​

Two symptoms, depending on the order you did things:

  • File deleted first, tables checked after: rows for the dag_id remain in dag, serialized_dag, dag_code and dag_version, and the UI list still shows the DAG;
  • Tables cleaned first, file deleted after: stranger still — freshly DELETEd rows reappear within minutes. The DAG "resurrects".

If you searched for "Airflow delete DAG still shows in UI" or "dag metadata comes back", same story.

Root cause: dag-processor registers whatever it finds; reserialize never cleans​

The resurrection is designed behavior, not a haunting:

  • dag-processor periodically scans the DAG directory. As long as the .py file exists, the scan parses it and re-registers metadata rows — which is exactly why cleaning tables before deleting the file resurrects the DAG: at clean time the file was still there, and the next scan rebuilt everything.
  • airflow dags reserialize only registers upward. It serializes "files currently in the directory" into the tables, but never removes rows whose files have disappeared — run reserialize after deleting a file and the leftovers don't budge.

So the order of "delete file" vs "clean metadata" is inherently one-directional: while the file exists, cleaning is futile; once it's gone, one clean is final.

The fix: delete file → clean tables in FK order → reserialize to verify​

Three steps, order not negotiable:

  1. Delete the .py file first. In production the DAG directory is a volume mount — sync via git pull on the host rather than deleting inside the container:
ssh <host> "cd /root/workspace/ai_dag && git pull"
# the DAG directory (mounted as /opt/airflow/dags) no longer has the .py
  1. Clean the metadata in foreign-key order (task_instance goes with dag_run via cascade):
DELETE FROM dag_run        WHERE dag_id = 'old_dag';      -- cascades task_instance
DELETE FROM serialized_dag WHERE dag_id = 'old_dag';
DELETE FROM dag_code WHERE dag_id = 'old_dag';
DELETE FROM dag_version WHERE dag_id = 'old_dag';
DELETE FROM dag WHERE dag_id = 'old_dag';
  1. Run reserialize as the verification: after airflow dags reserialize, query the dag table — if the dag_id doesn't reappear, the cleanup is final.

The whole thing takes under a minute; with the file gone from the directory, dag-processor's scans have nothing to re-register.

Boundary cases​

  • Make sure no scheduler/processor is mid-parse of that DAG before cleaning — avoid racing the registrar; off-peak windows keep it simple.
  • If run history matters as evidence, export it with SELECT first — run history is the only record of "what actually happened"; once deleted it's gone.
  • Same dag_id moving directories/platform folders follows the same logic: make the old file disappear from the directory first, then do the metadata surgery.
  • Metadata schemas differ across Airflow versions (dag_code/dag_version are relatively recent) — \d your own tables and foreign keys before running DELETEs; don't copy table names blind.

Watch out

  • The order is an iron rule: cleaning tables before deleting the file = guaranteed resurrection. Put "delete the file" at step one and everything after is downhill.
  • Direct SQL against a production metadata database is high-risk: WHERE must pin the exact dag_id — check affected row counts inside a transaction before committing.
  • The UI's "delete" button (newer versions) goes through an API path with different behavior from manual table cleaning; this flow targets scenarios needing precise control of what gets removed.

FAQ​

Why does a deleted DAG still show in the Airflow UI?​

Its metadata rows remain in dag, serialized_dag, dag_code and dag_version, and the UI renders from tables. reserialize only upserts files that exist — it never removes rows for vanished files, so the tables need a manual DELETE in foreign-key order.

Why did the metadata I cleaned come back?​

The DAG file was still on disk when the tables were cleaned: dag-processor periodically scans the DAG directory and re-registers any file it finds. Delete the file first (git pull into the mounted directory), then clean tables, then reserialize to confirm.

What is the right order to fully remove an Airflow DAG?​

  1. delete the .py file and sync the DAG directory; 2) DELETE in foreign-key order: dag_run (cascades task_instance) → serialized_dag → dag_code → dag_version → dag; 3) run airflow dags reserialize and confirm the dag table stays clean.

CCLEE

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

Work with me

Model Changed but Column Missing? 3 Alembic Pitfalls

· 7 min read

You add a field to a SQLAlchemy model in a FastAPI project using async SQLAlchemy. Everything works locally. After deploying, the first API call throws sqlalchemy.exc.ProgrammingError: column "xxx" does not exist — the model changed, the table did not.

Encountered this while building an AI Agent SaaS platform for a client — recording the root causes and fixes.

TL;DR​

When the model changed but the table didn't (or alembic won't even run), it is one of three pitfalls:

  1. Alembic still using the async engine — Alembic does not run inside an event loop. env.py must switch to a sync URL (postgresql+asyncpg:// → postgresql://, psycopg2 driver)
  2. down_revision pointing at a revision ID that doesn't exist — alembic upgrade fails with Can't locate revision
  3. Model edited, migration never generated — the code looks right, the table is untouched, and production blows up on first use of the new column

The three pitfalls map to "migration won't run", "chain is broken", "migration was never created" — in that triage order.

Symptoms​

Three symptoms, one per pitfall:

Symptom 1: production error after adding a model field

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column "risk_threshold" does not exist

Works locally, fails on the first production query.

Symptom 2: the migration command itself fails

Can't locate revision identified by '001_initial'

alembic upgrade head never reaches your new migration.

Symptom 3: autogenerate reports no changes

Generating migration ...  (no changes in schema detected)

You definitely edited a model, yet alembic sees nothing — usually env.py never imports your models, or it connects to the wrong database.

Root Cause 1: Alembic Running on an Async Engine​

Alembic migration scripts do not run inside an asyncio event loop. Your application can use async SQLAlchemy with the asyncpg driver, but the alembic command executes synchronously. If env.py reuses the app's async URL, the driver fails or behaves unpredictably.

The fix: give env.py its own sync engine. Swap postgresql+asyncpg:// for postgresql:// and install the psycopg2 driver.

pip install psycopg2-binary

Key part of alembic/env.py (after the config object is ready, before engine_from_config):

from sqlalchemy import pool, engine_from_config
from alembic import context

from app.config import settings
from app.database import Base
from app.models import * # noqa: F401,F403 - import all models

# Override sqlalchemy.url with sync URL for migrations
# Replace postgresql+asyncpg:// with postgresql:// for psycopg2
sync_url = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
config.set_main_option("sqlalchemy.url", sync_url)

Two details:

  • Replacing the async URL with the sync one via config.set_main_option() overrides the ini setting, so alembic.ini never needs a second connection string
  • The from app.models import * line is what registers every model into Base.metadata for autogenerate — drop it and you get symptom 3, "no changes in schema detected"

On dependencies: psycopg2-binary must be installed in whatever environment runs alembic. It is easy to miss in CI or a container that only runs migrations.

Root Cause 2: A Broken down_revision Chain​

Alembic maintains a one-way linked list through revision / down_revision. upgrade head walks that chain from the current version to the tail. down_revision must reference a revision identifier that actually exists in the chain, character for character. A "close enough" name from memory breaks the link.

A real repository's chain, three files under alembic/versions/:

# 001_initial.py
revision = '001_initial'
down_revision = None

# 002_rename_model_config_to_llm_config.py
revision = '002_rename_model_config'
down_revision = '001_initial'

# 003_add_cascade_delete.py
revision = '003'
down_revision = '002_rename_model_config'

Can't locate revision identified by 'xxx' means some down_revision string does not resolve — a wrong migration filename, half-copied ID, anything.

The fix is always the same two commands:

# 1. See the real chain (left column = revision ID)
alembic history

# 2. See where the database currently sits
alembic current

Point the new migration's down_revision at the real chain tail from alembic history, then alembic upgrade head. Alembic resumes from the position recorded in the alembic_version table; already-applied migrations do not re-run.

Use alembic history --verbose once the chain grows — guessing the topology from filenames does not scale.

Watch out

Two developers branch in parallel and both write a migration whose down_revision points at the same parent — upgrade head now reports multiple heads. Resolve it with alembic merge, which generates a merge migration. Our repository carries one such merge file, created to stitch two parallel branches. Multiple heads are not an anomaly; leaving them unmerged is.

Root Cause 3: Model Edited, Migration Never Created​

The most common misconception: an ORM model is a code-level declaration and never modifies the database by itself. Adding a field to a model class:

class Agent(Base):
__tablename__ = "agent_agents"
# ...
risk_threshold = Column(String, default="medium") # new

This changes a Python object definition. The agent_agents table is untouched, and the first query referencing the column raises column does not exist. Locally it often "just works" because your dev environment built tables with create_all(), or a SQLite in-memory database is recreated each run — both paths bypass migrations and mask the problem. Another model-layer trap is the Pydantic v2 ORM mode change; see Pydantic v2 ORM mode migration.

After any ORM model change, three fixed steps:

# 1. Generate a migration (autogenerate diffs model vs. database)
alembic revision --autogenerate -m "add risk_threshold to agent_agents"

# 2. Review the generated file by hand (autogenerate misses server defaults and
# constraint names; never upgrade blind)
# alembic/versions/xxxx_add_risk_threshold_to_agent_agents.py

# 3. Apply it
alembic upgrade head

Step 2 is not optional. Autogenerate is a diff tool with blind spots; upgrading its output unchecked is a gamble.

Verify the migration landed:

psql -c "\d agent_agents"   # confirm the new column exists
alembic current # confirm the version sits at the chain tail

Triage: Three Questions​

For any "changed the model, table didn't move" problem (also searched as "column does not exist" or "field missing in table"), three questions locate it in a minute:

  1. Does the migration command run at all? No → pitfall 2, check the down_revision chain
  2. It runs, but the column is still missing? → pitfall 3, confirm autogenerate produced a file, upgrade head ran, and alembic current sits at the tail
  3. Connection or driver errors from alembic upgrade? → pitfall 1, the sync URL setup in env.py

One team rule on top: model changes and their migration files ship in the same commit. A model without its migration hands every collaborator the exact production error on pull.

FAQ​

What are the basic alembic migration commands?​

Generate a migration with alembic revision --autogenerate -m "message", apply it with alembic upgrade head, roll back one step with alembic downgrade -1, and inspect the chain with alembic history. The standard workflow after any model change is exactly two steps: autogenerate, then upgrade head. Skip either one and the table stays unchanged.

I created my tables with SQLAlchemy — why doesn't a model change take effect?​

A SQLAlchemy model is a code-level declaration only; it never touches the database. Alembic migrations own schema changes. Even if you built tables with create_all() locally, the new column lives in in-memory metadata — production PostgreSQL raises ProgrammingError: column does not exist the first time a query touches it. Always generate a migration and run upgrade.

Why does alembic upgrade fail with Can't locate revision?​

Your down_revision references a revision identifier that does not exist in the chain — usually a short name typed from memory. Run alembic history to get the real IDs, point the new migration's down_revision at the actual chain tail, then run alembic upgrade head. revision and down_revision must match character for character; one wrong character breaks the whole chain.

CCLEE

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

Work with me

PostgreSQL fe_sendauth in Docker? exec trust vs TCP auth

· 5 min read

On the host that runs the database container, docker exec-ing in and running psql connects with no password at all. Run the same username from another container over TCP and it dies instantly with fe_sendauth: no password supplied.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Ops scripts inside the orchestration container reach the analytics database cross-container, and a connection string copied from the exec habit tripped on the very first hop.

Symptom: exec connects, TCP answers fe_sendauth: no password supplied​

Same host, same database, same user — two paths, two fates. Verified matrix (Airflow container → PostgreSQL container):

Connection methodResult
docker exec cclhub-db psql -U postgres (in-container socket)Connects, no password
Cross-container TCP, DSN without passwordfe_sendauth: no password supplied
Cross-container TCP, DSN with passwordConnects

If you searched for "fe_sendauth no password supplied", "psql no password error" or "docker postgres connection fails without password" — this is it.

Root cause: socket trust and TCP password auth are two different pg_hba paths​

PostgreSQL authentication is matched line by line in pg_hba.conf by connection type, and the official image ships completely different rules for the two paths:

  • docker exec uses the Unix domain socket, covered by a local all all trust-style rule — local socket is trusted, no password asked;
  • Cross-container traffic is TCP (a host-type rule), and the official image defaults to scram-sha-256 / md5 password auth.

So the no-password habit built on exec turns into "no password at all" the moment you switch to TCP — the literal meaning of fe_sendauth: no password supplied is "the server wants a password and the client supplied none".

Worth separating two often-confused errors: no password supplied means no password was provided; password authentication failed means one was, and it was wrong. The former points at the connection string; the latter at the credential itself — different fixes.

The fix: put the password in the DSN, don't copy the exec habit​

Cross-container scripts use a password-carrying connection string, always:

postgresql://postgres:<password>@<db host>:5432/<db>

The recommended source for the password is the DB container's own environment — the official image's POSTGRES_PASSWORD exists precisely for initialization — avoiding a second hardcode:

PW=$(docker exec cclhub-db printenv POSTGRES_PASSWORD)
psql "postgresql://postgres:${PW}@localhost:5432/postgres" -c "SELECT 1"

Application-side (Python here) it's the same shape, with the DSN in environment management:

import os
import psycopg

DSN = os.environ["APP_DB_DSN"] # postgresql://user:pass@host:5432/db
with psycopg.connect(DSN) as conn:
conn.execute("SELECT 1")

Note that passwords containing reserved characters like @ : / # must be percent-encoded in the URL — another place special characters bite; avoiding them in generated database passwords removes an entire class of trouble.

Boundary cases​

  • The error's shape varies by client: an interactive libpq terminal (psql without -t) first prompts Password for user postgres: and then fails with fe_sendauth; connection pools and GUI tools (pgAdmin) surface it as an auth failure in the UI — different texts, same root cause.
  • .pgpass files and the PGPASSWORD environment variable are two alternative ways to supply the password; in containerized setups, DSN/env injection is more common than mounting a .pgpass file.
  • You can set pg_hba to trust for TCP too — technically possible, and wrong for production: anything that can reach the port gets credential-free access.
  • Auth method version drift: newer official images default to scram-sha-256; very old client libraries may not support it — that's a different error class (unsupported authentication method), not "no password supplied".

Watch out

  • Diagnose the connection path first: socket or TCP, and which pg_hba rule it matches, decides whether a password is even requested — don't generalize exec behavior to everything.
  • Keep the error semantics straight: no password supplied (missing) and authentication failed (wrong) lead to completely different fixes.
  • Avoid or percent-encode special characters in DSN passwords — URL reserved characters silently change how the string parses.

FAQ​

What does fe_sendauth: no password supplied mean?​

The server's pg_hba.conf requires password auth, but the client's connection string carries no password. It is not "wrong password" (that's authentication failed) — it's "no password at all"; check whether the DSN is missing its password part.

Why does docker exec psql connect without a password?​

Inside the container psql uses the Unix domain socket, which pg_hba covers with a trust rule; cross-container traffic is TCP and hits a host rule that demands a password. Same command, different path, completely different auth requirements.

How should containerized scripts connect to PostgreSQL?​

Use a DSN with an explicit password — postgresql://user:password@host:5432/db — read from the DB container's POSTGRES_PASSWORD environment variable. Don't hardcode it and don't expect socket trust to apply over TCP.

CCLEE

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

Work with me