stack-postgresql
Skill0 starsChanged 5 months agoApache-2.0View on GitHub
PostgreSQL implementation patterns for agents working in projects whose docs/TECH_STACK.md lists postgresql. Load when implementing, testing, or reviewing code on this stack.
In this repository17 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- flow-adoptionSkill
- flow-legacy-migrationSkill
- stack-awsSkill
- stack-azureSkill
- stack-design-systemSkill
- stack-gcpSkill
- stack-javaSkill
- stack-kafkaSkill
- stack-mongodbSkill
- stack-natsSkill
- stack-nestjsSkill
- stack-nextjs-reactSkill
- stack-nxSkill
- stack-playwrightSkill
- stack-quarkusSkill
- stack-react-nativeSkill
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
Every tenant-scoped table has tenant_id uuid NOT NULL AND an RLS policy created in the same migration.
- Distinctive: line 60
Never put non-immutable expressions in CHECK constraints: If Postgres rejects the expression, move that validation to the application layer …
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Stack: PostgreSQL
Multi-tenant orientation is the headline of this skill: every pattern below assumes tenants share one database and the DB itself is the last line of tenant isolation.
When this applies
Detection markers (any of):
docs/TECH_STACK.md## Detected stackslistspostgresql- Dependencies:
pg,prismawith apostgresqldatasource,@prisma/client,typeorm+ postgres driver,knex+pg - Files:
prisma/schema.prismawithprovider = "postgresql", amigrations/directory of.sqlfiles, apostgresservice indocker-compose.yml docs/DATABASE.mddocuments a PostgreSQL data dictionary
Implementation patterns
Driver access goes through the framework's persistence module (R-PAT-03)
- The repository adapter is built on the host framework's first-party persistence integration, never a hand-managed
pgpool / raw JDBCDataSource: NestJS →@nestjs/typeormor the Nest Prisma module pattern the host'sdocs/ARCHITECTURE.mddeclares; Spring → Spring Data JPA; Quarkus → Hibernate ORM with Panache. The module owns connection pooling, transaction binding (SET app.tenant_idper request runs on a pooled connection the module hands out — see Tenant discipline), and DI. - Two sanctioned exceptions, both inside the adapter behind the port: (1) the migration DDL below — integrity primitives (
EXCLUDE, generated columns, RLS, partial indexes) that ORM schema generators cannot express are hand-edited.sql; (2) hand-tuned read queries the ORM cannot express. Neither is a bare connection in the domain — both stay ininfrastructure/. A rawpg/JDBC client as the primary data path is the fallback only when no framework module covers Postgres.
Tenant discipline (non-negotiable)
- Every tenant-scoped table has
tenant_id uuid NOT NULLAND an RLS policy created in the same migration. - RLS is the LAST line of defense, with application-level filtering on top. One query that forgets
WHERE tenant_id = ?must still hit the policy wall. - Per-request tenant context:
SET app.tenant_id = '<uuid>'; policies read it viacurrent_setting('app.tenant_id')::uuid. - Least privilege (R-SEC-01): the app's PG user gets only
SELECT/INSERT/UPDATE/DELETEon its own tables — no DDL, never superuser. The migration runner uses a SEPARATE user with DDL privileges, run only at deploy.
Integrity primitives the ORM does not generate
Hand-edit migrations to add what schema generators cannot express. Generate the skeleton (migrate dev --create-only or equivalent per docs/DEV_SETUP.md), then append:
CREATE EXTENSION IF NOT EXISTS btree_gist; -- must precede any gist EXCLUDE
ALTER TABLE bookings
ADD COLUMN during tstzrange
GENERATED ALWAYS AS (tstzrange(start_at, end_at, '[)')) STORED;
ALTER TABLE bookings
ADD CONSTRAINT no_overlapping_bookings
EXCLUDE USING gist (resource_id WITH =, during WITH &&)
WHERE (status IN ('held', 'confirmed'));
CREATE INDEX idx_bookings_hold_expiry ON bookings (expires_at)
WHERE status = 'held';
ALTER TABLE bookings ADD CONSTRAINT valid_range CHECK (end_at > start_at);
ALTER TABLE bookings ENABLE ROW LEVEL SECURITY;
CREATE POLICY bookings_tenant_isolation ON bookings
USING (tenant_id = current_setting('app.tenant_id')::uuid);Rules:
- Every time/range conflict table MUST use
EXCLUDE USING gistwithbtree_gist— never rely on application-level checks alone. - Half-open ranges
[)are the default —tstzrange(start_at, end_at, '[)')so adjacent bookings don't false-collide. - Generated columns (e.g.
during tstzrange) are database-computed, never application-set. - Partial predicates must reference STORED columns only. Do NOT put
now()or any volatile/stable function in theWHEREof an EXCLUDE or partial index — it will not self-clean and will silently misbehave. Lesson learned: a partial-index predicateWHERE expires_at > NOW()was committed and rejected at apply time becauseNOW()isSTABLE, notIMMUTABLE. Postgres requires IMMUTABLE predicates; expiry filtering belongs to the query or a reaper job, not the index predicate. - Never put non-immutable expressions in CHECK constraints. If Postgres rejects the expression, move that validation to the application layer — do not weaken the constraint.
- Idempotent endpoints require
UNIQUE (idempotency_key). Replay protection is non-negotiable. - Map driver error codes to typed domain errors at the adapter boundary: unique violation (
P2002/23505) → idempotency replay; exclusion violation (23P01) → conflict (e.g. SlotTaken).
Seed data rule
Every spec's migration work includes a seed script: realistic data covering ALL entity states, role configurations, and edge-case scenarios from the spec's ACs — and multiple tenants, so cross-tenant behavior can be explored by hand. Seed is a development convenience for manual exploration and UI validation — NOT test fixtures (those are per-test, created in Arrange).
Testing on this stack
Per .claude/rules/TESTING_INTEGRATION.md:
- R-TESTI-01 — real PostgreSQL via Testcontainers (
postgres:16), real ORM client, migrations applied inbeforeAll. Mocked-DB "integration" tests pass even when the EXCLUDE constraint is missing from the migration — that is the defect class this exists to catch. - R-TESTI-02 — ACs mentioning race/parallel/conflict/overlap fire concurrent operations (
Promise.allSettled), assert exactly-one-wins. Sequential awaits labeled "parallel" exercise nothing. - R-TESTI-04 — tests own their data: test DB has migrations only, NO seed; every test creates its entities in Arrange.
- R-TESTI-05 — tests clean up what they created: transactional rollback per test preferred; truncate in dependency order when commit semantics are under test.
Cross-tenant assertions are mandatory for tenant-scoped tables:
it('AC-<FEATURE>-NN: RLS blocks cross-tenant read', async () => {
const tenantA = await factory.createTenant()
const tenantB = await factory.createTenant()
const rowA = await factory.createRow({ tenantId: tenantA.id })
await db.$executeRawUnsafe(`SET app.tenant_id = '${tenantB.id}'`)
const visible = await db.rows.findMany()
expect(visible.map(r => r.id)).not.toContain(rowA.id)
})Spec validation checks
Stack-specific checks the spec validators (spec-validate-data, on SPEC_<FEATURE>.md §3 Data Model) delegate here:
| Check | Severity |
tenant_id present on every tenant-scoped table | BLOCKER |
| Time-range tables have an EXCLUDE constraint specified | BLOCKER |
| RLS migration mentioned for tenant-scoped tables | BLOCKER |
| Enums declared as DB/ORM enums, not freeform strings | BLOCKER |
| Any raw SQL constraint/index/predicate in §3 executes cleanly against live Postgres (IMMUTABLE predicates, STORED-column EXCLUDE references) | BLOCKER |
Idempotent endpoints have UNIQUE (idempotency_key) | WARNING |
| Generated columns marked as database-computed | WARNING |
Cascade rules (onDelete) explicitly stated for all relations | WARNING |
Column types consistent with docs/DATABASE.md and existing schema patterns | WARNING |
| Indexes declared for the spec's common query patterns (listing, expiry scan) | WARNING |
Validation IS execution: paste every DDL snippet into the live Postgres container and report-as-BLOCKER if Postgres refuses. A validator that reports PASS without running the SQL is a missed BLOCKER.
Live validation commands
R-VAL-02 matrix (database/migration changes) — exact invocations live in docs/DEV_SETUP.md; the rows below are the obligations:
| Check | Typical shape |
| Apply migrations on a FRESH DB | migrate reset --force / make migrate per DEV_SETUP |
| Regenerate client types (must compile) | prisma generate / equivalent |
| Run the seed | db seed target per DEV_SETUP |
| Smoke-query the new shape | psql -c '\d <new_table>' (or the project's DB MCP tool when docs/DEV_SETUP.md declares one) |
| Run integration tests against the migrated DB | affected test target per DEV_SETUP |
The smoke \d catches DDL the generator emitted incorrectly or Postgres refused (non-IMMUTABLE predicates, bad EXCLUDE predicates, missing extensions). All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.
Introspection (database-validator)
The data-dictionary refresh (docs/DATABASE.md) reads ONLY the live DB — never the ORM schema:
| What | Read command |
| Tables, columns, types, defaults | information_schema.columns or \d+ <table> |
| Constraints (CHECK, EXCLUDE, FK, UNIQUE) | pg_constraint joined to pg_class |
| Indexes (incl. partial/unique) | pg_indexes |
| RLS policies | pg_policies — a tenant-scoped table with no policy is a BLOCKER finding |
| Enums | pg_type + pg_enum |
| Extensions | pg_extension — btree_gist expected wherever EXCLUDE-on-range constraints exist |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

