Stored procedure logic hardening

From CarlosCaPe/octorato · View interactive version

Stored procedure logic hardening is an AI agent skill from the GitHub repository CarlosCaPe/octorato. Stored Procedure Logic Hardening

How to use this skill

Skill file

Stored Procedure Logic Hardening

What

Rewriting stored procedure logic for safety, determinism, and correctness --

beyond just rebuilding the definition (Skill #06). This includes:

Why

Database procedures that do DELETE, UPDATE, or data migration are the most

dangerous code in the system. A procedure without proper error handling can

silently delete wrong records. A procedure without FK-aware delete ordering

can fail mid-execution, leaving partial results.

How

FK-aware delete ordering

-- BAD: delete parent before children -> FK violation
DELETE FROM public."Users" WHERE "UserId" = p_user_id;
DELETE FROM public."UserRoles" WHERE "UserId" = p_user_id;  -- too late!

-- GOOD: delete children first, then parent
DELETE FROM public."UserRoles" WHERE "UserId" = p_user_id;
DELETE FROM public."UserSessions" WHERE "UserId" = p_user_id;
DELETE FROM public."Users" WHERE "UserId" = p_user_id;  -- safe now

Explicit error handling

-- BAD: silent failure
DELETE FROM public."Users" WHERE "UserId" = p_user_id;

-- GOOD: validate and report
IF NOT EXISTS (SELECT 1 FROM public."Users" WHERE "UserId" = p_user_id) THEN
    RAISE EXCEPTION 'User % not found -- cannot delete', p_user_id;
END IF;

DELETE FROM public."Users" WHERE "UserId" = p_user_id;
GET DIAGNOSTICS v_count = ROW_COUNT;

IF v_count <> 1 THEN
    RAISE EXCEPTION 'Expected to delete 1 user, deleted % -- rolling back', v_count;
END IF;

Deterministic behavior

-- BAD: implicit ordering, non-deterministic
SELECT * FROM public."Hospitals" WHERE "RegionId" = p_region_id;

-- GOOD: explicit ordering, deterministic
SELECT * FROM public."Hospitals"
WHERE "RegionId" = p_region_id
ORDER BY "HospitalId";

Audit logging

-- Log destructive operations
INSERT INTO audit."OperationLog" ("Operation", "TableName", "AffectedId", "Timestamp")
VALUES ('HARD_DELETE', 'Users', p_user_id, now());

When to Use

Where We Used It

explicit row-count validation, and audit logging

deterministic column selection and FK-safe update ordering

Related Skills

Gotchas

expected silent failures -- coordinate with the app team

(unlike RAISE NOTICE which just logs)


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.