agentleFS
isabelle-barpisabelle-barp/agent-brain/skills/stack-postgresql/SKILL.md

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.

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
  1. Very specific:

    Every tenant-scoped table has tenant_id uuid NOT NULL AND an RLS policy created in the same migration.

    line 25
  2. Distinctive:

    Never put non-immutable expressions in CHECK constraints: If Postgres rejects the expression, move that validation to the application layer …

    line 60

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 stacks lists postgresql
  • Dependencies: pg, prisma with a postgresql datasource, @prisma/client, typeorm + postgres driver, knex + pg
  • Files: prisma/schema.prisma with provider = "postgresql", a migrations/ directory of .sql files, a postgres service in docker-compose.yml
  • docs/DATABASE.md documents 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 pg pool / raw JDBC DataSource: NestJS → @nestjs/typeorm or the Nest Prisma module pattern the host's docs/ARCHITECTURE.md declares; Spring → Spring Data JPA; Quarkus → Hibernate ORM with Panache. The module owns connection pooling, transaction binding (SET app.tenant_id per 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 in infrastructure/. A raw pg/JDBC client as the primary data path is the fallback only when no framework module covers Postgres.

Tenant discipline (non-negotiable)

  1. Every tenant-scoped table has tenant_id uuid NOT NULL AND an RLS policy created in the same migration.
  2. 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.
  3. Per-request tenant context: SET app.tenant_id = '<uuid>'; policies read it via current_setting('app.tenant_id')::uuid.
  4. Least privilege (R-SEC-01): the app's PG user gets only SELECT/INSERT/UPDATE/DELETE on 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 gist with btree_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 the WHERE of an EXCLUDE or partial index — it will not self-clean and will silently misbehave. Lesson learned: a partial-index predicate WHERE expires_at > NOW() was committed and rejected at apply time because NOW() is STABLE, not IMMUTABLE. 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 in beforeAll. 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:

CheckSeverity
tenant_id present on every tenant-scoped tableBLOCKER
Time-range tables have an EXCLUDE constraint specifiedBLOCKER
RLS migration mentioned for tenant-scoped tablesBLOCKER
Enums declared as DB/ORM enums, not freeform stringsBLOCKER
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-computedWARNING
Cascade rules (onDelete) explicitly stated for all relationsWARNING
Column types consistent with docs/DATABASE.md and existing schema patternsWARNING
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:

CheckTypical shape
Apply migrations on a FRESH DBmigrate reset --force / make migrate per DEV_SETUP
Regenerate client types (must compile)prisma generate / equivalent
Run the seeddb seed target per DEV_SETUP
Smoke-query the new shapepsql -c '\d <new_table>' (or the project's DB MCP tool when docs/DEV_SETUP.md declares one)
Run integration tests against the migrated DBaffected 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:

WhatRead command
Tables, columns, types, defaultsinformation_schema.columns or \d+ <table>
Constraints (CHECK, EXCLUDE, FK, UNIQUE)pg_constraint joined to pg_class
Indexes (incl. partial/unique)pg_indexes
RLS policiespg_policies — a tenant-scoped table with no policy is a BLOCKER finding
Enumspg_type + pg_enum
Extensionspg_extension — btree_gist expected wherever EXCLUDE-on-range constraints exist

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.