mirror of
https://github.com/affaan-m/ECC.git
synced 2026-12-01 12:45:15 +09:00
fix: synchronize reviewed migration examples and context registry
This commit is contained in:
5 files changed
+533
-12
No files matched your search
@@ -46,17 +46,37 @@ Before applying any migration:
|
||||
### Adding a Column Safely
|
||||
|
||||
```sql
|
||||
-- GOOD: Nullable column, no lock
|
||||
-- Nullable column: no table rewrite, but takes ACCESS EXCLUSIVE lock
|
||||
ALTER TABLE users ADD COLUMN avatar_url TEXT;
|
||||
|
||||
-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)
|
||||
-- PostgreSQL 11+: a non-volatile default avoids a table rewrite
|
||||
-- Still takes ACCESS EXCLUSIVE lock and may wait for other transactions
|
||||
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- BAD: NOT NULL without default on existing table (requires full rewrite)
|
||||
-- BAD on a populated table: existing rows would have NULL in the new column
|
||||
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
|
||||
-- This locks the table and rewrites every row
|
||||
-- Fails with not_null_violation (SQLSTATE 23502); does not backfill existing rows
|
||||
```
|
||||
|
||||
Avoiding a table rewrite does not mean avoiding locks. These `ADD COLUMN`
|
||||
operations take an `ACCESS EXCLUSIVE` lock, held until the transaction ends.
|
||||
Keep the transaction short and use an appropriate `lock_timeout` to bound lock
|
||||
acquisition waits. A volatile default such as `clock_timestamp()` requires a
|
||||
table rewrite; the PostgreSQL 11+ fast path applies to non-volatile defaults.
|
||||
Adding a `NOT NULL` column without a default can succeed on an empty table.
|
||||
|
||||
Run the self-checking [reproduction SQL](examples/postgres-add-column.sql) on
|
||||
PostgreSQL 11+:
|
||||
|
||||
```bash
|
||||
psql -X -v ON_ERROR_STOP=1 -f skills/database-migrations/examples/postgres-add-column.sql
|
||||
```
|
||||
|
||||
It uses a temporary table, rolls back the ALTERs, and drops the fixture, checking
|
||||
lock acquisition, rewrites, and the expected constraint violation.
|
||||
|
||||
Reference: [PostgreSQL ALTER TABLE](https://www.postgresql.org/docs/current/sql-altertable.html).
|
||||
|
||||
### Adding an Index Without Downtime
|
||||
|
||||
```sql
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
-- PostgreSQL 11+; run with psql -X -v ON_ERROR_STOP=1 -f postgres-add-column.sql
|
||||
-- Do not use --single-transaction: fixture creation must commit before the lock check.
|
||||
-- Uses only a temporary table; rolls back ALTERs and drops the fixture.
|
||||
\set ON_ERROR_STOP on
|
||||
CREATE TEMP TABLE add_column_demo (id integer);
|
||||
INSERT INTO add_column_demo VALUES (1), (2);
|
||||
|
||||
-- Commit fixture creation before checking the lock acquired by ALTER TABLE.
|
||||
BEGIN;
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
original_file oid := pg_relation_filenode('add_column_demo');
|
||||
BEGIN
|
||||
ALTER TABLE add_column_demo ADD COLUMN avatar_url text;
|
||||
IF pg_relation_filenode('add_column_demo') <> original_file THEN
|
||||
RAISE EXCEPTION 'Nullable ADD COLUMN unexpectedly rewrote the table';
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_locks
|
||||
WHERE relation = 'add_column_demo'::regclass
|
||||
AND pid = pg_backend_pid()
|
||||
AND mode = 'AccessExclusiveLock' AND granted
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Expected AccessExclusiveLock after ADD COLUMN';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: nullable ADD COLUMN takes AccessExclusiveLock without a rewrite';
|
||||
|
||||
ALTER TABLE add_column_demo ADD COLUMN is_active boolean NOT NULL DEFAULT true;
|
||||
IF pg_relation_filenode('add_column_demo') <> original_file
|
||||
OR EXISTS (SELECT 1 FROM add_column_demo WHERE is_active IS DISTINCT FROM true) THEN
|
||||
RAISE EXCEPTION 'Expected constant default without a table rewrite';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: constant default supplies existing rows without a rewrite';
|
||||
|
||||
BEGIN
|
||||
ALTER TABLE add_column_demo ADD COLUMN role text NOT NULL;
|
||||
RAISE EXCEPTION 'Expected NOT NULL violation on populated table';
|
||||
EXCEPTION WHEN not_null_violation THEN
|
||||
RAISE NOTICE 'PASS: NOT NULL without default fails with SQLSTATE 23502';
|
||||
END;
|
||||
|
||||
ALTER TABLE add_column_demo ADD COLUMN sampled_at timestamptz DEFAULT clock_timestamp();
|
||||
IF pg_relation_filenode('add_column_demo') = original_file THEN
|
||||
RAISE EXCEPTION 'Expected volatile default to rewrite the table';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: volatile default rewrites the table';
|
||||
END $$;
|
||||
ROLLBACK;
|
||||
DROP TABLE add_column_demo;
|
||||
@@ -1 +1,382 @@
|
||||
{"coverage":{"skills":326,"withTriggers":42},"generatedAt":"2026-10-30T00:01:34.569Z","id":"skill-triggers@1","model":{"effort":null,"id":"hand-seeded","source":"manual-curation-pending-regeneration"},"registryDigest":"c9f199abd95ebb47fc8ca156c7cd037f5dc1ddb0660bab384d1a484d27bd428c","schemaVersion":1,"triggers":{"skill:agent-runtime-gateway-smoke-test":["test local agent gateway","remote sandbox callback smoke test","agent task stuck after dispatch","verify gateway tunnel","restore web api after agent test"],"skill:api-connector-builder":["add api integration","new provider connector","match existing integration pattern"],"skill:api-design":["rest endpoint design","pagination api","status codes","api versioning","rate limiting api","resource naming","filtering api","api error responses","offset pagination","limit query parameter","pagination defaults"],"skill:backend-patterns":["express api","node backend architecture","nextjs api routes","server side patterns","data access layer","static file server","url path handling","file server"],"skill:benchmark-optimization-loop":["turn user goal into benchmark","optimize task completion rate","compare implementation variants","improve correctness with fixed evaluation","reduce cost per resolved task","run bounded recursive optimization","verify improvement on independent cases","keep best measured admissible result"],"skill:browser-qa":["deployed feature test","visual regression screenshots","core web vitals check","axe accessibility audit","ship do not ship","staging verification"],"skill:canary-watch":["post deploy monitoring","smoke test url","production url check","console errors production","sse stream check","after deploy verification"],"skill:code-tour":["onboarding walkthrough","explain subsystem","architecture tour","pr walkthrough","rca tour"],"skill:coding-standards":["code review standards","naming conventions","readability review","immutability conventions","fix naming typo","export naming","consistent exports"],"skill:content-hash-cache-pattern":["cache file processing","content addressed cache","sha256 hash cache"],"skill:database-migrations":["zero downtime migration","schema change production","add column large table","backfill data","expand contract","concurrent index","migration rollback","prisma migration","django migration"],"skill:deployment-patterns":["ci cd setup","dockerize app","health checks","rollback strategy","production readiness","deploy pipeline","containerize application"],"skill:design-system":["design tokens","visual consistency audit","css custom properties","ui audit","design system bootstrap"],"skill:django-patterns":["django orm","drf api","django rest framework","django caching","django signals","django middleware"],"skill:django-security":["django authentication","csrf protection","sql injection prevention","xss prevention","django deployment security","role based access control","authorization middleware","permissions checks"],"skill:docker-patterns":["dockerfile review","docker compose setup","container security","multi service orchestration"],"skill:ecc-contribution-review":["prepare ecc skill contribution for review","organize skill contribution security evidence","review cross-harness skill contribution observations","compile ecc skill contribution proposal"],"skill:error-handling":["error types","retry logic","circuit breaker","user facing errors","exception handling patterns","typed errors","error boundaries","go error handling","custom error class","error codes","config validation"],"skill:evm-token-decimals":["token decimals","wei conversion","erc20 balance off","bridge token precision"],"skill:frontend-a11y":["aria attributes","screen reader support","focus management","semantic html","form labeling","keyboard navigation react","a11y lint errors"],"skill:git-workflow":["merge vs rebase","commit conventions","resolve merge conflict","branching strategy","clean up commits","pull request cleanup","git history tidy"],"skill:godot-patterns":["godot gdscript patterns","godot 4 best practices","gdscript static typing","godot signals vs direct calls","godot scene tree design","godot autoload singleton","godot resource data","gdscript style guide","godot node freed after await"],"skill:godot-testing":["godot unit tests","gdunit4","gut godot tests","godot headless tests","test gdscript","godot ci tests","godot scene runner test","godot check-only"],"skill:hexagonal-architecture":["ports and adapters","dependency injection boundaries","decouple domain from io"],"skill:kubernetes-patterns":["kubernetes manifests","kubectl debugging","pod probes","k8s rbac","autoscaling config","configmap secrets"],"skill:orch-fix-defect":["fix a bug","broken behavior","regression fix","reproduce bug","defect repair"],"skill:platform-factory":["platform factory","pf freeze","pf build","reproducible oci image","oci sbom provenance","microvm container"],"skill:postgres-patterns":["slow postgres query","query optimization","index design","rls pLine truncated
|
||||
{
|
||||
"coverage": {
|
||||
"skills": 326,
|
||||
"withTriggers": 42
|
||||
},
|
||||
"generatedAt": "2026-10-30T00:01:34.569Z",
|
||||
"id": "skill-triggers@1",
|
||||
"model": {
|
||||
"effort": null,
|
||||
"id": "hand-seeded",
|
||||
"source": "manual-curation-pending-regeneration"
|
||||
},
|
||||
"registryDigest": "a34627588523ed01c6202a6a35a6a08caef984d73e34d80b4aea5a48e8d4973a",
|
||||
"schemaVersion": 1,
|
||||
"triggers": {
|
||||
"skill:agent-runtime-gateway-smoke-test": [
|
||||
"test local agent gateway",
|
||||
"remote sandbox callback smoke test",
|
||||
"agent task stuck after dispatch",
|
||||
"verify gateway tunnel",
|
||||
"restore web api after agent test"
|
||||
],
|
||||
"skill:api-connector-builder": [
|
||||
"add api integration",
|
||||
"new provider connector",
|
||||
"match existing integration pattern"
|
||||
],
|
||||
"skill:api-design": [
|
||||
"rest endpoint design",
|
||||
"pagination api",
|
||||
"status codes",
|
||||
"api versioning",
|
||||
"rate limiting api",
|
||||
"resource naming",
|
||||
"filtering api",
|
||||
"api error responses",
|
||||
"offset pagination",
|
||||
"limit query parameter",
|
||||
"pagination defaults"
|
||||
],
|
||||
"skill:backend-patterns": [
|
||||
"express api",
|
||||
"node backend architecture",
|
||||
"nextjs api routes",
|
||||
"server side patterns",
|
||||
"data access layer",
|
||||
"static file server",
|
||||
"url path handling",
|
||||
"file server"
|
||||
],
|
||||
"skill:benchmark-optimization-loop": [
|
||||
"turn user goal into benchmark",
|
||||
"optimize task completion rate",
|
||||
"compare implementation variants",
|
||||
"improve correctness with fixed evaluation",
|
||||
"reduce cost per resolved task",
|
||||
"run bounded recursive optimization",
|
||||
"verify improvement on independent cases",
|
||||
"keep best measured admissible result"
|
||||
],
|
||||
"skill:browser-qa": [
|
||||
"deployed feature test",
|
||||
"visual regression screenshots",
|
||||
"core web vitals check",
|
||||
"axe accessibility audit",
|
||||
"ship do not ship",
|
||||
"staging verification"
|
||||
],
|
||||
"skill:canary-watch": [
|
||||
"post deploy monitoring",
|
||||
"smoke test url",
|
||||
"production url check",
|
||||
"console errors production",
|
||||
"sse stream check",
|
||||
"after deploy verification"
|
||||
],
|
||||
"skill:code-tour": [
|
||||
"onboarding walkthrough",
|
||||
"explain subsystem",
|
||||
"architecture tour",
|
||||
"pr walkthrough",
|
||||
"rca tour"
|
||||
],
|
||||
"skill:coding-standards": [
|
||||
"code review standards",
|
||||
"naming conventions",
|
||||
"readability review",
|
||||
"immutability conventions",
|
||||
"fix naming typo",
|
||||
"export naming",
|
||||
"consistent exports"
|
||||
],
|
||||
"skill:content-hash-cache-pattern": [
|
||||
"cache file processing",
|
||||
"content addressed cache",
|
||||
"sha256 hash cache"
|
||||
],
|
||||
"skill:database-migrations": [
|
||||
"zero downtime migration",
|
||||
"schema change production",
|
||||
"add column large table",
|
||||
"backfill data",
|
||||
"expand contract",
|
||||
"concurrent index",
|
||||
"migration rollback",
|
||||
"prisma migration",
|
||||
"django migration"
|
||||
],
|
||||
"skill:deployment-patterns": [
|
||||
"ci cd setup",
|
||||
"dockerize app",
|
||||
"health checks",
|
||||
"rollback strategy",
|
||||
"production readiness",
|
||||
"deploy pipeline",
|
||||
"containerize application"
|
||||
],
|
||||
"skill:design-system": [
|
||||
"design tokens",
|
||||
"visual consistency audit",
|
||||
"css custom properties",
|
||||
"ui audit",
|
||||
"design system bootstrap"
|
||||
],
|
||||
"skill:django-patterns": [
|
||||
"django orm",
|
||||
"drf api",
|
||||
"django rest framework",
|
||||
"django caching",
|
||||
"django signals",
|
||||
"django middleware"
|
||||
],
|
||||
"skill:django-security": [
|
||||
"django authentication",
|
||||
"csrf protection",
|
||||
"sql injection prevention",
|
||||
"xss prevention",
|
||||
"django deployment security",
|
||||
"role based access control",
|
||||
"authorization middleware",
|
||||
"permissions checks"
|
||||
],
|
||||
"skill:docker-patterns": [
|
||||
"dockerfile review",
|
||||
"docker compose setup",
|
||||
"container security",
|
||||
"multi service orchestration"
|
||||
],
|
||||
"skill:ecc-contribution-review": [
|
||||
"prepare ecc skill contribution for review",
|
||||
"organize skill contribution security evidence",
|
||||
"review cross-harness skill contribution observations",
|
||||
"compile ecc skill contribution proposal"
|
||||
],
|
||||
"skill:error-handling": [
|
||||
"error types",
|
||||
"retry logic",
|
||||
"circuit breaker",
|
||||
"user facing errors",
|
||||
"exception handling patterns",
|
||||
"typed errors",
|
||||
"error boundaries",
|
||||
"go error handling",
|
||||
"custom error class",
|
||||
"error codes",
|
||||
"config validation"
|
||||
],
|
||||
"skill:evm-token-decimals": [
|
||||
"token decimals",
|
||||
"wei conversion",
|
||||
"erc20 balance off",
|
||||
"bridge token precision"
|
||||
],
|
||||
"skill:frontend-a11y": [
|
||||
"aria attributes",
|
||||
"screen reader support",
|
||||
"focus management",
|
||||
"semantic html",
|
||||
"form labeling",
|
||||
"keyboard navigation react",
|
||||
"a11y lint errors"
|
||||
],
|
||||
"skill:git-workflow": [
|
||||
"merge vs rebase",
|
||||
"commit conventions",
|
||||
"resolve merge conflict",
|
||||
"branching strategy",
|
||||
"clean up commits",
|
||||
"pull request cleanup",
|
||||
"git history tidy"
|
||||
],
|
||||
"skill:godot-patterns": [
|
||||
"godot gdscript patterns",
|
||||
"godot 4 best practices",
|
||||
"gdscript static typing",
|
||||
"godot signals vs direct calls",
|
||||
"godot scene tree design",
|
||||
"godot autoload singleton",
|
||||
"godot resource data",
|
||||
"gdscript style guide",
|
||||
"godot node freed after await"
|
||||
],
|
||||
"skill:godot-testing": [
|
||||
"godot unit tests",
|
||||
"gdunit4",
|
||||
"gut godot tests",
|
||||
"godot headless tests",
|
||||
"test gdscript",
|
||||
"godot ci tests",
|
||||
"godot scene runner test",
|
||||
"godot check-only"
|
||||
],
|
||||
"skill:hexagonal-architecture": [
|
||||
"ports and adapters",
|
||||
"dependency injection boundaries",
|
||||
"decouple domain from io"
|
||||
],
|
||||
"skill:kubernetes-patterns": [
|
||||
"kubernetes manifests",
|
||||
"kubectl debugging",
|
||||
"pod probes",
|
||||
"k8s rbac",
|
||||
"autoscaling config",
|
||||
"configmap secrets"
|
||||
],
|
||||
"skill:orch-fix-defect": [
|
||||
"fix a bug",
|
||||
"broken behavior",
|
||||
"regression fix",
|
||||
"reproduce bug",
|
||||
"defect repair"
|
||||
],
|
||||
"skill:platform-factory": [
|
||||
"platform factory",
|
||||
"pf freeze",
|
||||
"pf build",
|
||||
"reproducible oci image",
|
||||
"oci sbom provenance",
|
||||
"microvm container"
|
||||
],
|
||||
"skill:postgres-patterns": [
|
||||
"slow postgres query",
|
||||
"query optimization",
|
||||
"index design",
|
||||
"rls policies",
|
||||
"supabase schema",
|
||||
"postgres indexing",
|
||||
"database performance",
|
||||
"schema design postgres",
|
||||
"postgres driver",
|
||||
"node postgres",
|
||||
"query planner"
|
||||
],
|
||||
"skill:python-patterns": [
|
||||
"pythonic code",
|
||||
"pep 8",
|
||||
"type hints python",
|
||||
"python code review",
|
||||
"idiomatic python"
|
||||
],
|
||||
"skill:python-testing": [
|
||||
"pytest fixtures",
|
||||
"mocking python",
|
||||
"parametrized tests",
|
||||
"coverage python",
|
||||
"tdd python"
|
||||
],
|
||||
"skill:redis-patterns": [
|
||||
"cache aside pattern",
|
||||
"distributed lock",
|
||||
"redis rate limiting",
|
||||
"cache invalidation"
|
||||
],
|
||||
"skill:regex-vs-llm-structured-text": [
|
||||
"parse invoice",
|
||||
"extract receipt data",
|
||||
"text extraction pipeline",
|
||||
"parse form fields",
|
||||
"cheap document parser",
|
||||
"extract table data",
|
||||
"parse log lines",
|
||||
"parse access logs",
|
||||
"common log format",
|
||||
"log line parsing"
|
||||
],
|
||||
"skill:rust-patterns": [
|
||||
"rust ownership",
|
||||
"borrow checker",
|
||||
"rust error handling",
|
||||
"traits rust",
|
||||
"rust concurrency",
|
||||
"idiomatic rust"
|
||||
],
|
||||
"skill:scientific-db-openalex-database": [
|
||||
"openalex api",
|
||||
"cross disciplinary literature search",
|
||||
"look up paper by doi",
|
||||
"resolve pmid to metadata",
|
||||
"find open access copy",
|
||||
"citation count lookup",
|
||||
"verify a citation exists"
|
||||
],
|
||||
"skill:search-first": [
|
||||
"find existing library",
|
||||
"npm package research",
|
||||
"before writing custom code",
|
||||
"evaluate existing tools",
|
||||
"add dependency research"
|
||||
],
|
||||
"skill:security-review": [
|
||||
"security audit",
|
||||
"authentication review",
|
||||
"sanitize user input",
|
||||
"secrets handling",
|
||||
"payment security checklist",
|
||||
"prevent injection attacks",
|
||||
"secure api endpoints",
|
||||
"authn authz review",
|
||||
"vulnerability checklist",
|
||||
"input validation security",
|
||||
"parameterized queries",
|
||||
"sql injection"
|
||||
],
|
||||
"skill:security-scan": [
|
||||
"audit claude config",
|
||||
"claudemd security",
|
||||
"mcp server audit",
|
||||
"agentshield scan",
|
||||
"hook configuration audit",
|
||||
"settings json security"
|
||||
],
|
||||
"skill:short-video-distribution": [
|
||||
"publish video to tiktok youtube reels",
|
||||
"cross-post short video",
|
||||
"schedule short-form video",
|
||||
"upload reel and short",
|
||||
"video captions per platform"
|
||||
],
|
||||
"skill:tdd-workflow": [
|
||||
"write test first",
|
||||
"failing test",
|
||||
"red green refactor",
|
||||
"test driven development",
|
||||
"regression test first",
|
||||
"write a regression test"
|
||||
],
|
||||
"skill:typescript-patterns": [
|
||||
"strict typescript compiler configuration",
|
||||
"fix cascading type errors",
|
||||
"remove any and tighten types",
|
||||
"design discriminated unions",
|
||||
"narrow unknown at api boundary",
|
||||
"review typescript pull request",
|
||||
"refactor to strict mode",
|
||||
"generics for caller dependent types",
|
||||
"async error handling patterns",
|
||||
"validate config with type guards",
|
||||
"bounded concurrency mapper",
|
||||
"module boundary exports"
|
||||
],
|
||||
"skill:verification-loop": [
|
||||
"pre pr checks",
|
||||
"verification report",
|
||||
"quality gates",
|
||||
"build lint test coverage",
|
||||
"before creating a pr"
|
||||
],
|
||||
"skill:yoruba-localization-testing": [
|
||||
"yoruba localization testing",
|
||||
"yoruba english bilingual interface",
|
||||
"yoruba tone marks",
|
||||
"yoruba diacritics",
|
||||
"yoruba unicode normalization",
|
||||
"yoruba translation fallback",
|
||||
"yoruba screen reader language",
|
||||
"yoruba bilingual ui",
|
||||
"test yoruba character preservation",
|
||||
"yoruba accents not rendering"
|
||||
]
|
||||
},
|
||||
"triggersDigest": "b1f4c1bd0602860615fb67ecf4d16b6a0f7171ab4d65862c3db66aa0a2d6487c"
|
||||
}
|
||||
@@ -30,8 +30,8 @@ Safe, reversible database schema changes for production systems.
|
||||
Before applying any migration:
|
||||
|
||||
- [ ] Migration has both UP and DOWN (or is explicitly marked irreversible)
|
||||
- [ ] No full table locks on large tables (use concurrent operations)
|
||||
- [ ] New columns have defaults or are nullable (never add NOT NULL without default)
|
||||
- [ ] Lock modes and expected hold times reviewed; use concurrent operations where supported
|
||||
- [ ] On populated tables, new columns are nullable or have defaults compatible with their constraints
|
||||
- [ ] Indexes created concurrently (not inline with CREATE TABLE for existing tables)
|
||||
- [ ] Data backfill is a separate migration from schema change
|
||||
- [ ] Tested against a copy of production data
|
||||
@@ -42,17 +42,37 @@ Before applying any migration:
|
||||
### Adding a Column Safely
|
||||
|
||||
```sql
|
||||
-- GOOD: Nullable column, no lock
|
||||
-- Nullable column: no table rewrite, but takes ACCESS EXCLUSIVE lock
|
||||
ALTER TABLE users ADD COLUMN avatar_url TEXT;
|
||||
|
||||
-- GOOD: Column with default (Postgres 11+ is instant, no rewrite)
|
||||
-- PostgreSQL 11+: a non-volatile default avoids a table rewrite
|
||||
-- Still takes ACCESS EXCLUSIVE lock and may wait for other transactions
|
||||
ALTER TABLE users ADD COLUMN is_active BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- BAD: NOT NULL without default on existing table (requires full rewrite)
|
||||
-- BAD on a populated table: existing rows would have NULL in the new column
|
||||
ALTER TABLE users ADD COLUMN role TEXT NOT NULL;
|
||||
-- This locks the table and rewrites every row
|
||||
-- Fails with not_null_violation (SQLSTATE 23502); does not backfill existing rows
|
||||
```
|
||||
|
||||
Avoiding a table rewrite does not mean avoiding locks. These `ADD COLUMN`
|
||||
operations take an `ACCESS EXCLUSIVE` lock, held until the transaction ends.
|
||||
Keep the transaction short and use an appropriate `lock_timeout` to bound lock
|
||||
acquisition waits. A volatile default such as `clock_timestamp()` requires a
|
||||
table rewrite; the PostgreSQL 11+ fast path applies to non-volatile defaults.
|
||||
Adding a `NOT NULL` column without a default can succeed on an empty table.
|
||||
|
||||
Run the self-checking [reproduction SQL](examples/postgres-add-column.sql) on
|
||||
PostgreSQL 11+:
|
||||
|
||||
```bash
|
||||
psql -X -v ON_ERROR_STOP=1 -f skills/database-migrations/examples/postgres-add-column.sql
|
||||
```
|
||||
|
||||
It uses a temporary table, rolls back the ALTERs, and drops the fixture, checking
|
||||
lock acquisition, rewrites, and the expected constraint violation.
|
||||
|
||||
Reference: [PostgreSQL ALTER TABLE](https://www.postgresql.org/docs/current/sql-altertable.html).
|
||||
|
||||
### Adding an Index Without Downtime
|
||||
|
||||
```sql
|
||||
@@ -476,7 +496,7 @@ Later: Separate migration drops status after all contract gates pass
|
||||
|-------------|-------------|-----------------|
|
||||
| Manual SQL in production | No audit trail, unrepeatable | Always use migration files |
|
||||
| Editing deployed migrations | Causes drift between environments | Create new migration instead |
|
||||
| NOT NULL without default | Locks table, rewrites all rows | Add nullable, backfill, then add constraint |
|
||||
| Adding NOT NULL column without default to populated table | Fails because existing rows would contain NULL | Add nullable, backfill, then set NOT NULL |
|
||||
| Inline index on large table | Blocks writes during build | CREATE INDEX CONCURRENTLY |
|
||||
| Schema + data in one migration | Hard to rollback, long transactions | Separate migrations |
|
||||
| Dropping column before removing code | Application errors on missing column | Remove code first, drop column next deploy |
|
||||
@@ -0,0 +1,50 @@
|
||||
-- PostgreSQL 11+; run with psql -X -v ON_ERROR_STOP=1 -f postgres-add-column.sql
|
||||
-- Do not use --single-transaction: fixture creation must commit before the lock check.
|
||||
-- Uses only a temporary table; rolls back ALTERs and drops the fixture.
|
||||
\set ON_ERROR_STOP on
|
||||
CREATE TEMP TABLE add_column_demo (id integer);
|
||||
INSERT INTO add_column_demo VALUES (1), (2);
|
||||
|
||||
-- Commit fixture creation before checking the lock acquired by ALTER TABLE.
|
||||
BEGIN;
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
original_file oid := pg_relation_filenode('add_column_demo');
|
||||
BEGIN
|
||||
ALTER TABLE add_column_demo ADD COLUMN avatar_url text;
|
||||
IF pg_relation_filenode('add_column_demo') <> original_file THEN
|
||||
RAISE EXCEPTION 'Nullable ADD COLUMN unexpectedly rewrote the table';
|
||||
END IF;
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_locks
|
||||
WHERE relation = 'add_column_demo'::regclass
|
||||
AND pid = pg_backend_pid()
|
||||
AND mode = 'AccessExclusiveLock' AND granted
|
||||
) THEN
|
||||
RAISE EXCEPTION 'Expected AccessExclusiveLock after ADD COLUMN';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: nullable ADD COLUMN takes AccessExclusiveLock without a rewrite';
|
||||
|
||||
ALTER TABLE add_column_demo ADD COLUMN is_active boolean NOT NULL DEFAULT true;
|
||||
IF pg_relation_filenode('add_column_demo') <> original_file
|
||||
OR EXISTS (SELECT 1 FROM add_column_demo WHERE is_active IS DISTINCT FROM true) THEN
|
||||
RAISE EXCEPTION 'Expected constant default without a table rewrite';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: constant default supplies existing rows without a rewrite';
|
||||
|
||||
BEGIN
|
||||
ALTER TABLE add_column_demo ADD COLUMN role text NOT NULL;
|
||||
RAISE EXCEPTION 'Expected NOT NULL violation on populated table';
|
||||
EXCEPTION WHEN not_null_violation THEN
|
||||
RAISE NOTICE 'PASS: NOT NULL without default fails with SQLSTATE 23502';
|
||||
END;
|
||||
|
||||
ALTER TABLE add_column_demo ADD COLUMN sampled_at timestamptz DEFAULT clock_timestamp();
|
||||
IF pg_relation_filenode('add_column_demo') = original_file THEN
|
||||
RAISE EXCEPTION 'Expected volatile default to rewrite the table';
|
||||
END IF;
|
||||
RAISE NOTICE 'PASS: volatile default rewrites the table';
|
||||
END $$;
|
||||
ROLLBACK;
|
||||
DROP TABLE add_column_demo;
|
||||
Reference in new issue
Block a user