Idempotent sql design

From CarlosCaPe/octorato · View interactive version

Idempotent sql design is an AI agent skill from the GitHub repository CarlosCaPe/octorato. Idempotent SQL Design

How to use this skill

Skill file

Idempotent SQL Design

What

Scripts that check the current state before acting, so they can be safely

re-run without causing errors or duplicate changes. Running the script once

or ten times produces the same final state.

Why

Deployments fail. Networks drop. Operators re-run scripts "just to be sure."

An idempotent script handles all of these gracefully -- it skips work that's

already done and only applies what's missing.

How

Column renames

-- Check before acting
IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public'
      AND table_name = 'Applicant'
      AND column_name = 'SpeialtyRequirement'  -- old name
) THEN
    ALTER TABLE public."Applicant"
        RENAME COLUMN "SpeialtyRequirement" TO "SpecialtyRequirement";
    RAISE NOTICE 'Renamed: SpeialtyRequirement -> SpecialtyRequirement';
ELSE
    RAISE NOTICE 'Skipped: SpeialtyRequirement (already renamed)';
END IF;

Index creation

-- Only create if missing
IF NOT EXISTS (
    SELECT 1 FROM pg_indexes
    WHERE schemaname = 'public'
      AND indexname = 'ix_my_index'
) THEN
    CREATE INDEX ix_my_index ON public."MyTable" ("MyColumn");
END IF;

FK constraints

-- Only add if missing
IF NOT EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_name = 'fk_my_constraint'
) THEN
    ALTER TABLE public."MyTable"
        ADD CONSTRAINT fk_my_constraint
        FOREIGN KEY ("MyColumn") REFERENCES public."OtherTable"("Id");
END IF;

Key Principle

The pattern is always:

  1. Query current state (does the old column exist? does the index exist?)
  2. Act only if needed (IF EXISTS / IF NOT EXISTS)
  3. Report what happened (RAISE NOTICE with [OK] or [--] prefix)

When to Use

some may already have partial changes applied

Where We Used It


Category: Reliability | Origin:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.