Agent skill

Diesel Guard

by ayarotsky in ayarotsky/diesel-guard

Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks.

MITAuto-check passedDatabases

Install Diesel Guard

skills CLI
$ npx skills add ayarotsky/diesel-guard --skill diesel-guard -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ayarotsky/diesel-guard diesel-guard --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ayarotsky/diesel-guard.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/diesel-guard .claude/skills/diesel-guard && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
diesel-guard
GitHub stars
121
Token cost
~3.1k tokens
SKILL.md length
972 words
Files
1
Skills in repo
1
Repo updated
First seen
Licence
MIT

At a glance

Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks.

  • Works in 3 steps: Run the linter → Interpret the result. Exit code is the… → Fix by applying the printed…
  • Fixing SQL migrations
  • SKILL.md covers Core workflow: run → interpret…, Fixing violations, Escape hatches (only when the… and Configuring diesel-guard.toml, plus 3 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Diesel Guard is an agent skill from ayarotsky/diesel-guard. Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks. Use when reviewing, writing, or fixing SQL migrations, when diesel-guard reports a violation, when configuring diesel-guard.toml, or when the user mentions migration safety, table locks, or zero-downtime migrations.

Its SKILL.md is about 3.1k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering Linting and formatting, SQL and Database migrations. It works with PostgreSQL, SQL and Rust. The repository describes itself as: Linter for dangerous Postgres migration patterns in Diesel and SQLx. Prevents downtime caused by unsafe schema changes. The licence is MIT.

When your agent uses it

  • Fixing SQL migrations
  • Diesel-guard reports a violation
  • Configuring diesel-guard.toml
  • The user mentions migration safety

Example prompts

  • “Use the diesel-guard skill to lint Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors…”
  • “/diesel-guard”

Workflow steps

3 steps, taken from the first numbered list in SKILL.md.

  1. Run the linter
  2. Interpret the result. Exit code is the contract
  3. Fix by applying the printed safe_alternative, then re-run to confirm 0 (see below).

What it can do on your machine

Read from SKILL.md and the folder at commit b579eb1. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are rhai, bash, sql and toml).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • rhai.rs

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Diesel Guard loads about 3.1k tokens when it runs. Until then it costs about 91 tokens; SKILL.md has 972 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~91
When it runs · the whole SKILL.md, loaded when a task matches
~3.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ayarotsky/diesel-guard at commit b579eb1, republished under its MIT licence (© ayarotsky). 972 words, ~3,148 tokens.

Download SKILL.mdSave it as .claude/skills/diesel-guard/SKILL.md (or your agent's skills folder).
name
diesel-guard
description
Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks. Use when reviewing, writing, or fixing SQL migrations, when diesel-guard reports a violation, when configuring diesel-guard.toml, or when the user mentions migration safety, table locks, or zero-downtime migrations.

diesel-guard

diesel-guard is a CLI that lints Diesel and SQLx Postgres migrations using PostgreSQL's own parser (libpg_query). It flags operations that take dangerous locks or rewrite tables, and prints a safe alternative for each one. It needs no database connection — it reads .sql files directly. Use it to vet a migration before it ships, to fix a reported violation, or to add project-specific rules.

Core workflow: run → interpret → fix

  1. Run the linter:

    sh
    diesel-guard check                 # checks ./migrations/ by default
    diesel-guard check path/to/up.sql  # a single file
    cat up.sql | diesel-guard check -  # stdin
    diesel-guard check migrations/ --format json   # text (default) | json | github
  2. Interpret the result. Exit code is the contract:

    • 0 — clean, or only warnings (warnings never block).
    • 1 — at least one error-level violation, or a fatal error (e.g. invalid diesel-guard.toml, unparsable SQL, or a bad invocation). Read stderr to tell the two apart.

    Each violation has three fields: operation (what was flagged), problem (why it's dangerous), and safe_alternative (what to do instead). In JSON each also carries check_name, line, and severity.

  3. Fix by applying the printed safe_alternative, then re-run to confirm 0 (see below).

Fixing violations

Apply the safe_alternative printed for the violation, then re-run until the exit code is 0. Prefer fixing the migration over suppressing the check.

Get the full reasoning and exact rewrite for any check by name — including the most common ones (AddColumnCheck, AddIndexCheck, AddNotNullCheck) — from the tool itself:

sh
diesel-guard explain <CheckName>

Treat that output and the violation's own safe_alternative as the source of truth; do not recite fixes from memory.

Escape hatches (only when the operation is genuinely verified safe)

  • Suppress a range — wrap statements (no nesting):
    sql
    -- safety-assured:start
    ALTER TABLE users DROP COLUMN legacy_field;
    -- safety-assured:end
  • Disable named checks for the whole file (comma-separated):
    sql
    -- diesel-guard:disable AddColumnCheck, DropColumnCheck
  • Diesel per-migration — in that migration's metadata.toml:
    toml
    run_in_transaction = false        # allows CONCURRENTLY operations
    disable_checks = ["AddColumnCheck"]
  • SQLx per-migration — make the migration non-transactional (required for CONCURRENTLY) by putting this as the first line of the file:
    sql
    -- no-transaction

Configuring diesel-guard.toml

Run diesel-guard init to scaffold the file (use --force to overwrite). Keys:

  • framework (required) — "diesel" or "sqlx". Case-sensitive.
  • start_after — skip migrations older than this timestamp. Diesel accepts YYYYMMDDHHMMSS, YYYY_MM_DD_HHMMSS, and YYYY-MM-DD-HHMMSS; SQLx accepts plain numeric versions like 42 and separator-formatted 14-digit timestamp filters. Good for retrofitting.
  • check_down (default false) — also check rollback/down migrations.
  • disable_checks — blacklist of check names to skip.
  • enable_checks — whitelist; only these run. Mutually exclusive with disable_checks.
  • warn_checks — demote these checks to warnings (reported, but exit stays 0).
  • custom_checks_dir — directory of .rhai custom checks.
  • postgres_version — target major version (e.g. 16); silences checks that are safe from that version onward.

Discovering checks (the source of truth)

The tool serves the live, config-aware list — do not hardcode it:

sh
diesel-guard list-checks                 # every check: NAME, TYPE, SEVERITY, ENABLED
diesel-guard list-checks --format json
diesel-guard explain AddIndexCheck       # full description + safe alternative for one check

Migration layouts

  • Diesel — one directory per migration containing up.sql (and optional down.sql, metadata.toml). check scans up.sql recursively.
  • SQLx — flat files: <version>_<name>.up.sql / .down.sql, or single-file <version>_<name>.sql.

Writing custom checks

Write project-specific rules in Rhai with full access to the parsed SQL AST — no forking required.

Setup

Point custom_checks_dir at a directory of .rhai files in diesel-guard.toml:

toml
custom_checks_dir = "checks"

Every .rhai file in that directory becomes a check. They load in alphabetical order. A check's name is its filename stem (require_concurrent_index.rhai → require_concurrent_index), so it can be listed by list-checks, disabled via disable_checks/enable_checks, and explained via explain. Compilation errors are non-fatal — they become warnings on stderr and the other checks still run. Safety-assured blocks and -- diesel-guard:disable apply to custom checks too.

Inspect the AST with dump-ast

Before writing a check, see exactly what node a statement produces:

sh
diesel-guard dump-ast --sql "CREATE INDEX idx ON t(id);"
diesel-guard dump-ast --file migrations/.../up.sql

The output strips the outer RawStmt/Node wrappers and starts at the concrete node type (e.g. {"IndexStmt": {...}}) — that is precisely the shape your script receives as node.

Show full SKILL.md (418 more words)Show less
Script inputs

Each script runs once per parsed statement with three variables in scope:

  • node — the AST node. Reach into the concrete type by name: node.IndexStmt.concurrent, node.CreateStmt.relation.relname, node.DropStmt.remove_type. A field that doesn't apply to the current statement is absent, so guard with ?? (see below).
  • config — the active configuration, e.g. config.postgres_version (an integer, or () when unset).
  • ctx — per-migration context: ctx.run_in_transaction (bool) and ctx.no_transaction_hint (a framework-specific string explaining how to make the migration non-transactional).
Return protocol

Return exactly one of:

  • () — no violation.
  • #{ operation, problem, safe_alternative } — one violation. All three values must be strings.
  • [#{ ... }, #{ ... }] — an array of such maps for multiple violations.

A bad return value (wrong type, a map missing a key, or a non-string value) and any runtime error thrown while the script runs do not crash diesel-guard — each produces a SCRIPT ERROR: <check-name> violation. That violation is error severity by default, so it makes check exit 1 just like a real finding; add the check's name to warn_checks in diesel-guard.toml to demote it to a warning. Scripts never panic.

(This is distinct from compile errors at load time, described under Setup, which are non-fatal and reported as warnings on stderr.)

pg:: constants

Reference pg_query protobuf enum values by name instead of raw integers via the pg:: module:

  • Object types: pg::OBJECT_INDEX, pg::OBJECT_TABLE, pg::OBJECT_COLUMN, pg::OBJECT_DATABASE, pg::OBJECT_SCHEMA, pg::OBJECT_SEQUENCE, pg::OBJECT_VIEW, pg::OBJECT_FUNCTION, pg::OBJECT_EXTENSION, pg::OBJECT_TRIGGER, pg::OBJECT_TYPE
  • ALTER TABLE subtypes: pg::AT_ADD_COLUMN, pg::AT_COLUMN_DEFAULT, pg::AT_DROP_NOT_NULL, pg::AT_SET_NOT_NULL, pg::AT_DROP_COLUMN, pg::AT_ALTER_COLUMN_TYPE, pg::AT_ADD_CONSTRAINT, pg::AT_DROP_CONSTRAINT, pg::AT_VALIDATE_CONSTRAINT
  • Constraint types: pg::CONSTR_NOTNULL, pg::CONSTR_DEFAULT, pg::CONSTR_IDENTITY, pg::CONSTR_GENERATED, pg::CONSTR_CHECK, pg::CONSTR_PRIMARY, pg::CONSTR_UNIQUE, pg::CONSTR_EXCLUSION, pg::CONSTR_FOREIGN
  • Drop behavior: pg::DROP_RESTRICT, pg::DROP_CASCADE

src/scripting.rs in the diesel-guard source is the authoritative list if you need one not shown here.

describe()

Optionally define fn describe() returning a string. diesel-guard explain <name> shows it.

rhai
fn describe() {
    "Requires CONCURRENTLY on every CREATE INDEX."
}
Engine limits

Per script: max_operations 100,000 · max_string_size 10,000 · max_array_size 1,000 · max_map_size 1,000.

Worked example

Require CONCURRENTLY on CREATE INDEX, and also flag CONCURRENTLY used inside a transaction (Postgres rejects that at runtime):

rhai
let stmt = node.IndexStmt ?? return;

if !stmt.concurrent {
    let idx_name = if stmt.idxname != "" { stmt.idxname } else { "(unnamed)" };
    return #{
        operation: "INDEX without CONCURRENTLY: " + idx_name,
        problem: "Creating index '" + idx_name + "' without CONCURRENTLY blocks writes on the table.",
        safe_alternative: "Use CREATE INDEX CONCURRENTLY:\n  CREATE INDEX CONCURRENTLY " + idx_name + " ON ...;"
    };
}

if ctx.run_in_transaction {
    let hint = if ctx.no_transaction_hint != "" { ctx.no_transaction_hint }
               else { "Run this migration outside a transaction block." };
    #{
        operation: "INDEX CONCURRENTLY inside a transaction",
        problem: "CREATE INDEX CONCURRENTLY cannot run inside a transaction block; Postgres errors at runtime.",
        safe_alternative: hint
    }
}

node.IndexStmt ?? return; bails when the statement isn't a CREATE INDEX.

More examples

Five more complete, runnable checks. Together with the worked example above they cover the common patterns: the ?? guard, optional chaining (?.), pg:: constants, returning an array, and iterating child nodes. Copy one into your custom_checks_dir as a starting point.

Require IF EXISTS on DROP TABLE — uses a pg:: constant and missing_ok:

rhai
let stmt = node.DropStmt ?? return;
if stmt.remove_type != pg::OBJECT_TABLE || stmt.missing_ok { return; }

#{
    operation: "DROP TABLE without IF EXISTS",
    problem: "DROP TABLE without IF EXISTS will error if the table doesn't exist, potentially breaking migrations.",
    safe_alternative: "Use IF EXISTS:\n  DROP TABLE IF EXISTS <table_name>;"
}

Ban UNLOGGED tables — optional chaining on a nested field (relpersistence is "u" when unlogged):

rhai
let rel = node.CreateStmt?.relation ?? return;
if rel.relpersistence != "u" { return; }

let table_name = rel.relname;
#{
    operation: "UNLOGGED TABLE: " + table_name,
    problem: "UNLOGGED tables are not crash-safe and are not replicated to standby servers.",
    safe_alternative: "Use a regular (logged) table instead:\n  CREATE TABLE " + table_name + " (...);"
}

Ban TRUNCATE — iterate child nodes and return an array of violations:

rhai
let stmt = node.TruncateStmt ?? return;

let violations = [];
for rel in stmt.relations {
    let name = rel.node?.RangeVar?.relname ?? continue;
    violations.push(#{
        operation: "TRUNCATE: " + name,
        problem: "TRUNCATE acquires ACCESS EXCLUSIVE lock on '" + name + "', blocking all reads and writes for the duration. Unlike DELETE, it also resets sequences and skips triggers.",
        safe_alternative: "Use batched DELETE instead:\n  DELETE FROM " + name + " WHERE id IN (SELECT id FROM " + name + " LIMIT 1000);"
    });
}
violations

Limit index width to 3 columns — read a config-like constant and count index_params:

rhai
let max_cols = 3;
let stmt = node.IndexStmt ?? return;

let col_count = stmt.index_params.len();
if col_count > max_cols {
    let idx_name = if stmt.idxname != "" { stmt.idxname } else { "(unnamed)" };
    #{
        operation: "Wide index: " + idx_name + " (" + col_count + " columns)",
        problem: "Index '" + idx_name + "' has " + col_count + " columns (limit: " + max_cols + "). Wide indexes are rarely effective and slow down writes.",
        safe_alternative: "Use narrower indexes targeting specific query patterns, or partial/covering indexes."
    }
}

Enforce an index naming convention — string method on a field:

rhai
let name = node.IndexStmt?.idxname ?? return;
if name == "" || name.starts_with("idx_") { return; }

#{
    operation: "Index naming violation: " + name,
    problem: "Index '" + name + "' does not follow naming convention. Index names should start with 'idx_'.",
    safe_alternative: "Rename the index:\n  CREATE INDEX idx_" + name + " ON ...;"
}

© ayarotsky, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/diesel-guard of ayarotsky/diesel-guard.

Open the folder on GitHubat commit b579eb1

Compare with similar skills

Diesel Guard next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Diesel Guard compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Diesel Guard this skillayarotsky/diesel-guard121—~3.1kAutomated safety check: PassMIT
Querying Tempotempoxyz/tidx108—~3.1kAutomated safety check: PassMIT
Database Migrations SQL Migrationsrmyndharis/antigravity-skills1.7k3 repos~577Automated safety check: NotesMIT
DB ContextSilvioBaratto/optimizer176—~6.4kAutomated safety check: NotesCustom licence
Postgrestimescale/pg-aiguide1.9k—~941Automated safety check: PassApache-2.0
Ron Databasebionic-gpt/bionic-gpt2.4k—~721Automated safety check: PassApache-2.0

Similar skills

  • Querying Tempo

    tempoxyz/tidx

    Query indexed Tempo chain data via tidx HTTP API and CLI. An agent skill from tempoxyz/tidx.

    108 GitHub stars~3.1k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Database Migrations SQL Migrations

    rmyndharis/antigravity-skills

    SQL database migrations with zero-downtime strategies for PostgreSQL, MySQL, SQL Server

    1.7k GitHub starsUsed in 3 repos~577 tokens
    DatabasesAuto-check: notes
  • DB Context

    SilvioBaratto/optimizer

    Complete knowledge of the optimizer PostgreSQL database: 57 ingestion tables, schema, relationships, live row counts, query patterns, and conventions.

    176 GitHub stars~6.4k tokensUpdated 4 days ago
    DatabasesAuto-check: notes
  • Postgres

    timescale/pg-aiguide

    A skill your agent uses for any PostgreSQL database work — table design, indexing, data types, constraints, extensions (pgvector, PostGIS, TimescaleDB), search, and migrations.

    1.9k GitHub stars~941 tokensUpdated 3 days ago
    DatabasesAuto-check passed
  • Ron Database

    bionic-gpt/bionic-gpt

    Manage PostgreSQL migrations, typed SQL queries, generated Rust bindings, and database authorization in Rust on Nails applications.

    2.4k GitHub stars~721 tokensUpdated 4 days ago
    DatabasesAuto-check passed
  • Database Migration

    Rain-kl/OpenFlare

    Wavelet 项目专用:当新增或修改数据库表结构、索引、初始化数据、系统配置 seed、模板 seed、默认管理员、goose SQL 迁移、internal/infra/persistence/migrator、ClickHouse 分析库 DDL 或数据库升级流程时必须使用。本技能指导在 internal/infra/persistence/migrator/goose 下编写…

    289 GitHub stars~1.3k tokensUpdated 3 days ago
    DatabasesAuto-check passed

Questions about Diesel Guard

What does Diesel Guard do?

Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks. Diesel Guard is an agent skill from ayarotsky/diesel-guard. Lints Diesel and SQLx Postgres migrations for unsafe schema changes that lock tables or cause downtime, and authors custom Rhai checks.

When should I use Diesel Guard?

Diesel Guard fits situations like: fixing SQL migrations; diesel-guard reports a violation; configuring diesel-guard.toml; the user mentions migration safety.

How do I install Diesel Guard in Claude Code?

Run `npx skills add ayarotsky/diesel-guard --skill diesel-guard -a claude-code`. Or copy the skill folder (skills/diesel-guard in ayarotsky/diesel-guard) into .claude/skills/diesel-guard in your project. Claude Code loads it when a task matches its description.

How do I install Diesel Guard in Codex?

Run `npx skills add ayarotsky/diesel-guard --skill diesel-guard -a codex`. Or copy the skill folder (skills/diesel-guard in ayarotsky/diesel-guard) into .agents/skills/diesel-guard in your project. Codex loads it when a task matches its description.

Can I use Diesel Guard in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ayarotsky/diesel-guard --skill diesel-guard -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/diesel-guard, .gemini/skills/diesel-guard, .github/skills/diesel-guard and .opencode/skills/diesel-guard in your project.

What does Diesel Guard need to run?

SKILL.md names no scripts, command-line tools or credentials: Diesel Guard is instructions for the agent only.

Does Diesel Guard access the network?

SKILL.md names 1 domain. As links in the text: rhai.rs. This is read from the text; nothing was executed.

Is Diesel Guard safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Diesel Guard use?

Diesel Guard is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Diesel Guard use?

About 3.1k tokens (SKILL.md is roughly 13k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Diesel Guard?

Skills that share tags, products or a category with Diesel Guard: Querying Tempo (tempoxyz/tidx, 108 stars), Database Migrations SQL Migrations (rmyndharis/antigravity-skills, 1.7k stars), DB Context (SilvioBaratto/optimizer, 176 stars) and Postgres (timescale/pg-aiguide, 1.9k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Diesel Guard?

ayarotsky (a GitHub user) maintains it in ayarotsky/diesel-guard, which has 121 GitHub stars. The repository was last updated on October 10, 2026.

Source: ayarotsky/diesel-guard on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.