anotherben/claude-harness/sql-guard
Claude Code and agent skill by anotherben/claude-harness
- community
Checking that the SKILL.md file is still in the repository.
SQL safety checker for database queries and migrations. This skill should be used before writing or modifying any SQL query, database migration, or code that constructs SQL strings. It enforces multi-tenant tenant_id scoping, parameterized queries, correct timestamp types, IF NOT EXISTS guards, and type-safe joins. Invoke this skill when writing INSERT/UPDATE/DELETE statements, creating migrations, modifying database queries, joining tables with mixed ID types, or when any code touches the database layer. Even for "simple SELECT queries", invoke this — tenant_id scoping bugs are silent and ship to production undetected.
Install
npx vskill@latest install anotherben/claude-harness/sql-guardSKILL.md
The same SKILL.md was published earlier as anotherben/claude-harness/sql-guard.
SQL Guard
A pre-edit checker for all SQL and database code. These rules have zero automated enforcement but cause the most insidious production bugs — tenant isolation violations, type mismatches, and unsafe query construction.
Before Writing Any SQL
- Read `references/schema.md` for the authoritative table-by-table tenant_id map, type traps, and REX SKU field mapping. That file is the source of truth for which tables need tenant_id and which don't. (Use Read — this is a reference doc, not code.)
- Choose the safest real schema proof surface. For pre-PR schema/query testing, prefer a local Postgres instance restored from a sanitized clone, approved snapshot, or schema-only dump plus representative fixtures. Do not run proof against production, print credentials, store dumps in the repo, or depend on machine-local paths in committed evidence. If local full-schema proof is unavailable, treat schema/query claims as blocked or explicitly narrowed.
- Explore the actual service file that already queries the tables you are about to use. Column names, join patterns, and scoping conventions vary across this codebase — do not guess from training data:
search_symbols(query="[table-name]")to find which service files query that tableget_symbol([service-file], [function-name])to pull the specific query functionget_file_outline([service-file])to see all query functions in large service files- Only use Read for full-file context or before editing
- Verify the migration files for any table you are adding columns to or creating indexes on:
search_text(query="CREATE TABLE [table-name]", path="apps/api/database/migrations/")to find the right migrationget_symbol([migration-file], [table-name])to pull the CREATE TABLE block- This confirms the actual column types, existing indexes, and constraints
The Pre-Write Checklist
Run through every item before writing or modifying database code. Skipping even one item has caused production bugs in this codebase.
1. Tenant Isolation
The #1 silent bug. A missing tenant_id WHERE clause leaks data across tenants with zero errors.
- Every
INSERTinto a tenant-scoped table includestenant_idcolumn - Every
SELECT/UPDATE/DELETEon a tenant-scoped table hasWHERE tenant_id = $N(or joins to a table that does) - Check `references/schema.md` to confirm whether the table has
tenant_id— don't guess
Tables that commonly trip people up:
customers— hastenant_idcolumn but it is NOT scoped in existing queries (ambiguous — match existing patterns)products— has NOtenant_id— do NOT add onecall_logs— HAStenant_id(INTEGER) — easy to forgetconversations— HAStenant_id(INTEGER) — must scopecustomer_portal_tokens— HAStenant_id(UUID, not INTEGER like others)
2. Parameterized Queries
The #1 security vulnerability. Template literals in SQL strings = SQL injection.
- All user-supplied values use
$1,$2, etc. placeholders - NEVER use template literals (
${value}) inside SQL strings — not even for "known safe" values - For
INclauses: build placeholder list dynamically, not string concatenation:
``javascript const placeholders = ids.map((_, i) => $${i + 1}).join(', '); const result = await pool.query( SELECT * FROM products WHERE id IN (${placeholders}), ids ); ``
- For dynamic column/table names (rare): whitelist against an explicit array of known values, never interpolate
3. Timestamp Types
The Melbourne timezone trap. This codebase serves an Australian business. The server runs UTC but all business dates are Melbourne time.
- Always use
TIMESTAMPTZ, neverTIMESTAMP, in DDL - Date filtering pattern (the only correct way):
``sql WHERE created_at >= $1::DATE::TIMESTAMP AT TIME ZONE 'Australia/Melbourne' AND created_at < ($1::DATE + INTERVAL '1 day')::TIMESTAMP AT TIME ZONE 'Australia/Melbourne' ``
- The
::TIMESTAMPcast beforeAT TIME ZONEis mandatory —DATE AT TIME ZONEwithout it goes backwards on UTC servers (shifts +10 instead of -10) - CURRENT_DATE trap:
CURRENT_DATEreturns the UTC date, which is wrong for Melbourne after ~2pm AEST. For "today" queries use:
``sql (CURRENT_TIMESTAMP AT TIME ZONE 'Australia/Melbourne')::date ` Any code using bare CURRENT_DATE` for business logic is a bug — it will miss or duplicate records during the UTC/Melbourne date boundary.
- See
references/schema.md"Melbourne Timezone Pattern" section for the full explanation
4. Migration Safety
CREATE TABLE IF NOT EXISTS— alwaysADD COLUMN IF NOT EXISTS— wrap in DO block:
``sql DO $$ BEGIN ALTER TABLE orders ADD COLUMN IF NOT EXISTS tracking_number TEXT; EXCEPTION WHEN duplicate_column THEN NULL; END $$; ``
CREATE INDEX IF NOT EXISTS— and NEVER inside a transaction if usingCONCURRENTLY- Check next migration number: currently 338 in MEMORY.md — verify with
ls apps/api/database/migrations/ | tail -5 - Migration file exists does NOT mean it was run. Verify with
\d table_nameon the actual database if uncertain.
Migration collision handling: If the next number (338) already exists from another branch, increment to the next available number. Check both apps/api/database/migrations/ and any open worktrees for pending migrations to avoid collisions.
Rollback safety: Every migration should be reversible or at minimum non-destructive:
ADD COLUMNis safe (reversible withDROP COLUMN)DROP COLUMNis NOT reversible — gate behind explicit user confirmationALTER COLUMN TYPEmay lose data — add a comment noting the original typeCREATE INDEX CONCURRENTLYcan fail partway — always useIF NOT EXISTSso re-running is safe
Dev vs production: Migrations run on the dev database first (DATABASE_URL in .env). Production migrations are a separate deploy step. Never assume a migration that ran on dev has run on production — check the handover/deploy notes.
5. Type-Safe Joins
This codebase has mixed column types that cause silent bugs. The full list is in references/schema.md "Type Traps" section. The most dangerous ones:
| Join | Trap | Fix | |
|---|---|---|---|
products.supplier_id → suppliers.id | INTEGER vs UUID | Cast: supplier_id::text = suppliers.id::text | |
shopify_orders.shopify_id → any VARCHAR | BIGINT vs VARCHAR | Cast: shopify_id::text or $1::bigint | |
orders.rex_order_id → bigint param | VARCHAR vs BIGINT | Cast: $1::text | |
products.retail_express_id → integer param | VARCHAR vs INTEGER | Cast: $1::text or retail_express_id::int |
Never rely on implicit PostgreSQL coercion. Always cast explicitly when types differ.
Cast safety is not just type matching:
- Cast untrusted JSON/text/external IDs only after a guard proves the value is non-empty, well-formed, and in range.
- Numeric-looking text outside the destination range, such as
bigintoverflow, must be filtered before::bigint; one corrupt payload row must not abort the whole worker query. - Prefer casting the parameter side, not the indexed column side.
p.id = ANY($1::uuid[])can use the primary-key index;p.id::text = ANY($1::text[])can force scans. - For every changed SQL cast on a hot path, worker, sync, proof lane, or high-cardinality table, capture query-plan/index evidence or classify the missing proof as a finding.
Established join patterns in this codebase (verified from service files):
| From → To | Correct Pattern | Notes | |
|---|---|---|---|
products → suppliers | products.rex_supplier_id::text = suppliers.retail_express_id | NOT via supplier_id → suppliers.id | |
orders → customers | orders.customer_id = customers.id | Both INTEGER | |
shopify_orders → orders | shopify_orders.order_id = orders.id | Both INTEGER | |
call_logs → customers | call_logs.customer_id = customers.id | Both INTEGER, but call_logs needs tenant_id |
6. REX SKU Field Mapping
When working with REX (Retail Express) product data, the SKU fields are misleadingly named. See references/schema.md "REX SKU Field Mapping" for the full map. The critical trap:
- REX
supplier_sku→ oursku(this is the primary SKU you want) - REX
sku(top-level) → usually NULL (do NOT use this) - REX
supplier_sku2→ oursku2(secondary/alternate)
7. Batch/Bulk Operations
- Use
unnest()for bulk inserts (more efficient than VALUES lists for large batches):
``sql INSERT INTO products (sku, name, price) SELECT * FROM unnest($1::text[], $2::text[], $3::numeric[]) ON CONFLICT (sku) DO UPDATE SET name = EXCLUDED.name, price = EXCLUDED.price; ``
- Use
VALUESlists for small batches (under ~50 rows):
``javascript const values = items.map((_, i) => ($${i3+1}, $${i3+2}, $${i*3+3})).join(', '); const params = items.flatMap(item => [item.sku, item.name, item.price]); await pool.query(INSERT INTO products (sku, name, price) VALUES ${values}, params); ``
- Bound all queries — add
LIMITor date windows to prevent unbounded table scans - For large result sets, use cursor-based pagination (
WHERE id > $last_id ORDER BY id LIMIT $page_size)
Post-Write Review Checklist
After writing any SQL query or migration, run through these 8 items. This takes 30 seconds and catches the mistakes that pass code review:
- Tenant scoped? Every tenant-scoped table in the query has
WHERE tenant_id = $N - Parameterized? Zero template literals inside SQL strings
- Types match safely? Every JOIN and WHERE comparison uses matching types, casts untrusted values only after malformed/empty/out-of-range guards, and keeps indexed column predicates indexable
- Timestamps correct?
TIMESTAMPTZin DDL,AT TIME ZONEpattern in queries, no bareCURRENT_DATE - Bounded? Query has
LIMIT, date window, pagination, or a proof-specific sample set — no unbounded scans in runtime paths or live-proof lanes - Idempotent? Migration uses
IF NOT EXISTS/IF EXISTSguards - Column names real? Every column name was verified by reading the actual table's migration or service file
- CONCURRENTLY safe? If using
CREATE INDEX CONCURRENTLY, it is NOT inside a transaction block - Local full-schema proof safe? Schema/query changes ran against local restored Postgres or have a documented blocker/narrowed claim; evidence shows no production writes, no secrets, no repo dumps, and cleanup/reset.
Common Mistakes from Evaluations
These specific mistakes have been observed in A/B testing. They are the highest-probability errors:
| Mistake | Why It Happens | Prevention | |
|---|---|---|---|
Adding WHERE products.tenant_id = $1 | Guessing from table name — products has no tenant_id | Check references/schema.md | |
Using duration instead of call_duration_seconds | Guessing column name from context | Read actual migration/service file | |
Using created_at instead of ring_time on call_logs | Generic timestamp assumption | Read actual migration/service file | |
Joining products.supplier_id = suppliers.id directly | Looks obvious but types mismatch (INT vs UUID) | Check Type Traps table | |
Using bare CURRENT_DATE in WHERE clause | Seems correct but wrong after 2pm AEST | Use (CURRENT_TIMESTAMP AT TIME ZONE 'Australia/Melbourne')::date |
Quick Reference: Safe Patterns
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/sql-guard/SKILL.md
Popularity
- Repository stars
- 7
- 7-day trend score
- 10
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/anotherben/claude-harness/sql-guard)