agentleFS
golid-aigolid-ai/golid/.cursor/rules/sql-migrations.mdc

golid / rules

Cursor rule40 starsChanged 6 months agoMITView on GitHub

Patterns for SQL migration files — schema changes, enums, indexes, triggers

  • Deletes or force-pushes

The file

We split this sql-migrations.mdc into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 are 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.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    When writing status transitions in service code that references these enums:

    line 82
  2. Very specific:

    Always precede the ADD CONSTRAINT with a DO $$ ...

    line 93
  3. Very specific:

    When this matters most: any CHECK that tightens a previously-loose column (NOT NULL → > 0, free-text → enum, etc.).

    line 115

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule 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
sql-migrations.mdc
---
description: Patterns for SQL migration files — schema changes, enums, indexes, triggers
globs: backend/migrations/*.sql
alwaysApply: false
---

# SQL Migration Patterns

> **Thesis:** Migrations are the source of truth for the data model. Every table gets UUIDs, TIMESTAMPTZ, FK indexes, and an updated_at trigger.

**Reference files:** `000001_init.up.sql`

## File Naming

`000NNN_description.up.sql` and `000NNN_description.down.sql` — always create both.

## Once Committed, Never Edited

Migrations are append-only history. Once a migration file is committed, even on
a feature branch, do not modify it. Any schema change goes in a new migration
with the next sequence number.

- Need to add a column? New `ALTER TABLE ... ADD COLUMN`.
- Need to drop a column you just added? New `ALTER TABLE ... DROP COLUMN`.
- Forgot an index? New `CREATE INDEX`.

Editing an already-committed `.up.sql` silently desyncs schemas: any environment
that ran the old version will never pick up the change, while fresh databases
will. Before editing any `00NN_*.sql` file, ask: "is this committed?" If yes,
create a new migration.

## Up Migration

```sql
-- Enums first
CREATE TYPE item_status AS ENUM ('new', 'in_progress', 'complete', 'cancelled');

-- Tables (with UUID PKs, timestamps, FKs with ON DELETE CASCADE)
CREATE TABLE items (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  status item_status DEFAULT 'new',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Indexes on FKs and frequently filtered columns
CREATE INDEX idx_items_user_id ON items(user_id);
CREATE INDEX idx_items_status ON items(status);

-- Reuse the existing updated_at trigger function
CREATE TRIGGER items_updated_at BEFORE
UPDATE ON items FOR EACH ROW EXECUTE FUNCTION update_updated_at();
```

## Down Migration

Drop in reverse dependency order: columns (ALTER), then tables, then enums.

```sql
DROP TABLE IF EXISTS item_history;
DROP TABLE IF EXISTS items;
DROP TYPE IF EXISTS item_status;
```

## Conventions

- **UUIDs** for all primary keys (not serial/bigint).
- **TIMESTAMPTZ** for all timestamps (not TIMESTAMP).
- **TEXT** for strings (not VARCHAR) — PostgreSQL treats them identically.
- **DECIMAL(x,2)** for money/hours (not FLOAT).
- **JSONB** for structured metadata (audit trails, preferences).
- **TEXT[]** for tag-like arrays (skills, industries).
- **Enums** for finite status sets — add a `cancelled` state if the entity can be deactivated.
- **ON DELETE CASCADE** on child table FKs.
- **Index every FK** and every column used in WHERE filters.
- **`updated_at` trigger** on every table that has the column.

## Idempotent Status Transitions

When writing status transitions in service code that references these enums:

```sql
-- GOOD — idempotent, no error on repeat
UPDATE items SET status = 'in_progress' WHERE id = $1 AND status = 'new';
```

## Adding a CHECK Constraint to an Existing Table

Any `ADD CONSTRAINT ... CHECK (...)` against an existing table risks failing at deploy time on a single legacy row that violates the new predicate. The `ALTER TABLE` errors out with a generic message and no row IDs, blocking the migration.

Always precede the `ADD CONSTRAINT` with a `DO $$ ... RAISE` pre-flight that names the offending IDs. Defensive only — no-op when data is clean.

```sql
DO $$
DECLARE
    bad_ids TEXT;
BEGIN
    SELECT string_agg(id::text, ', ') INTO bad_ids
    FROM feature_flags
    WHERE key IS NULL OR trim(key) = '';
    IF bad_ids IS NOT NULL THEN
        RAISE EXCEPTION
            'Migration NNN cannot apply feature_flags_key_not_empty: % row(s) have empty key (ids: %). Fix data before re-running.',
            (SELECT count(*) FROM feature_flags WHERE key IS NULL OR trim(key) = ''),
            bad_ids;
    END IF;
END $$;

ALTER TABLE feature_flags
    ADD CONSTRAINT feature_flags_key_not_empty CHECK (trim(key) <> '');
```

When this matters most: any CHECK that tightens a previously-loose column (`NOT NULL` → `> 0`, free-text → enum, etc.). One bad legacy row is enough to fail the deploy.

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.