PreToolUse hook that inspects a database migration before it is written and blocks irreversible or lock-heavy operations — DROP TABLE/COLUMN, TRUNCATE, table/column RENAME, and CREATE INDEX without CONCURRENTLY — following the strong_migrations safe-migration checks.
Runs before Write, Edit, and MultiEdit on files under a migrations path or with a .sql extension; for edits, it reads only regular, non-symlink existing files up to 1 MiB and applies the requested replacement before scanning the final SQL., Blocks the write with exit code 2 when it detects DROP TABLE/COLUMN, TRUNCATE, a table/column RENAME, or CREATE INDEX without CONCURRENTLY; the hook never connects to or runs SQL against any database., Provides an explicit escape hatch - include a '-- safety-gate: allow' comment in the pending Write, Edit, or MultiEdit content to acknowledge the risk and let it through; stale allow comments already present in an edited file do not bypass new risky edits., Uses regex heuristics, so it can miss obfuscated statements or flag an intentional change; review every migration regardless of the result.
Privacy notes
Reads the pending Write content from the tool input and, for Edit or MultiEdit, the targeted local migration file only when it is a regular, non-symlink file up to 1 MiB so it can scan the final content; it opens no database connections and makes no network calls., Prints the file path and the names of the detected risky operation classes to local hook stderr; it writes no logs., The file path shown in output may reveal local directory structure in your terminal.
Author
techforgeworks
Submitted by
techforgeworks
Claim status
unclaimed
Last verified
2026-06-04
Decision playbook
Review trust signals before you adopt
Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.
Compare context
Selected
0
Current score
78
Baseline
—
Delta
No baseline selected
No major trust-signal divergence detected in the current selection.
Source and provenance checks
Complete
Confirm ownership and provenance before trusting install instructions.
Source link availableRequired
Open the canonical repository and verify ownership.
Done
Source provenance statusRequired
Marked as source-backed.
Done
Metadata reviewed
Registry metadata indicates a reviewed listing.
Done
Safety and privacy checks
Complete
Validate risk disclosures before installation or API wiring.
Safety notes presentRequired
Review the listed safety guidance before running commands.
Done
Privacy notes presentRequired
Review data handling notes before connecting accounts or secrets.
Done
Trust level risk gateRequired
Trust level does not block evaluation.
Done
Package and install checks
Needs review
Check package metadata and artifact integrity signals.
Install payload available
Install or copy payload is available for review.
Done
Package verification flag
No package verification flag provided.
Pending
Checksum metadata
No checksum provided for downloaded artifact.
Pending
Compare-driven decision checks
Needs review
Use compare context to validate trade-offs before adoption.
Compare tray has multiple entries
Add at least one more entry to compare trust differences.
Current risk score 16/100. Use staged verification before broader rollout.
Risk 16
Pre-adoption checks
Validate source and review signals before any execution.
Confirm source provenanceRequired
Source URL/provenance metadata is present.
Done
Confirm metadata review state
Listing has review metadata.
Done
Verify install payload
Install/config payload exists and can be inspected.
Done
Security checks
Confirm safety, privacy, and package integrity signals.
Review safety notesRequired
Safety notes are present.
Done
Review privacy notesRequired
Privacy notes are present.
Done
Verify package integrity metadata
No package verification/checksum metadata.
Pending
Rollout
Adopt in controlled steps based on the selected plan.
Run in isolated sandbox firstRequired
Use a constrained sandbox and observe behavior across multiple tasks.
Pending
Roll out graduallyRequired
Roll out to a small cohort before wider usage.
Pending
Set monitoring and fallback
Define rollback path and monitor errors after adoption.
Pending
Evidence readiness
Evidence readiness matrix · balanced
Required evidence gates are covered (5/6 signals complete).
Risk 15
Source provenance
Present
Source repository/provenance is listed.
Required in this preset
Metadata review
Present
Review metadata is present.
Required in this preset
Safety notes
Present
Safety notes are present.
Required in this preset
Privacy notes
Present
Privacy notes are present.
Optional in this preset
Package integrity
Missing
Package integrity metadata is missing.
Optional in this preset
Install payload
Present
Install payload is available.
Required in this preset
Required evidence gates are covered for this preset.
Decision timeline
Decision timeline · balanced
5/6 steps complete with no blocking gaps for this preset.
Risk 14
triage
Confirm source provenanceRequired
Source/provenance metadata is available.
Done
triage
Check metadata review statusRequired
Review metadata is available.
Done
verify
Review safety notesRequired
Safety notes are available.
Done
verify
Review privacy notes
Privacy notes are available.
Done
verify
Validate package integrity metadata
Package integrity metadata is missing.
Pending
rollout
Verify install payload and commandsRequired
Install payload is available.
Done
No required blockers for this timeline preset.
Prerequisite readiness
Prerequisite readiness
2 prerequisites to line up before setup.
0/2 ready
Install & runtime1General1
Safety & privacy surface
Safety & privacy surface
4 safety and 3 privacy notes across 4 risk areas. Review closely: network access.
4 areas
SafetyNetwork accessRuns before Write, Edit, and MultiEdit on files under a migrations path or with a .sql extension; for edits, it reads only regular, non-symlink existing files up to 1 MiB and applies the requested replacement before scanning the final SQL.
SafetyExecution & processesBlocks the write with exit code 2 when it detects DROP TABLE/COLUMN, TRUNCATE, a table/column RENAME, or CREATE INDEX without CONCURRENTLY; the hook never connects to or runs SQL against any database.
SafetyLocal filesProvides an explicit escape hatch - include a '-- safety-gate: allow' comment in the pending Write, Edit, or MultiEdit content to acknowledge the risk and let it through; stale allow comments already present in an edited file do not bypass new risky edits.
SafetyGeneralUses regex heuristics, so it can miss obfuscated statements or flag an intentional change; review every migration regardless of the result.
PrivacyNetwork accessReads the pending Write content from the tool input and, for Edit or MultiEdit, the targeted local migration file only when it is a regular, non-symlink file up to 1 MiB so it can scan the final content; it opens no database connections and makes no network calls.
PrivacyLocal filesPrints the file path and the names of the detected risky operation classes to local hook stderr; it writes no logs.
PrivacyLocal filesThe file path shown in output may reveal local directory structure in your terminal.
Safety notes
Runs before Write, Edit, and MultiEdit on files under a migrations path or with a .sql extension; for edits, it reads only regular, non-symlink existing files up to 1 MiB and applies the requested replacement before scanning the final SQL.
Blocks the write with exit code 2 when it detects DROP TABLE/COLUMN, TRUNCATE, a table/column RENAME, or CREATE INDEX without CONCURRENTLY; the hook never connects to or runs SQL against any database.
Provides an explicit escape hatch - include a '-- safety-gate: allow' comment in the pending Write, Edit, or MultiEdit content to acknowledge the risk and let it through; stale allow comments already present in an edited file do not bypass new risky edits.
Uses regex heuristics, so it can miss obfuscated statements or flag an intentional change; review every migration regardless of the result.
Privacy notes
Reads the pending Write content from the tool input and, for Edit or MultiEdit, the targeted local migration file only when it is a regular, non-symlink file up to 1 MiB so it can scan the final content; it opens no database connections and makes no network calls.
Prints the file path and the names of the detected risky operation classes to local hook stderr; it writes no logs.
The file path shown in output may reveal local directory structure in your terminal.
Prerequisites
Claude Code CLI with hooks enabled.
bash and jq on PATH; the hook fails open and stays silent when jq is missing.
Schema details
Install type
cli
Troubleshooting
No
Source repository stats
Scope
Source repo
Runtime and command metadata
Trigger
PreToolUse
Script language
bash
Script body
#!/usr/bin/env bash
set -u
# Claude Code PreToolUse hook. Inspects a pending database migration and blocks
# irreversible or lock-heavy operations (the strong_migrations safe-migration
# check classes). Exit code 2 blocks the write and feeds the reason back to
# Claude. An explicit "-- safety-gate: allow" comment in the pending write or
# edit content acknowledges the risk and lets the migration through. Fails open
# when jq is missing.
command -v jq >/dev/null 2>&1 || exit 0
INPUT=$(cat)
FILE=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
# Only gate files that look like database migrations.
case "$FILE" in
*migrations/*|*migrate/*|*/db/migrate/*|*.sql) : ;;
*) exit 0 ;;
esac
TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // ""')
CONTENT=$(printf '%s' "$INPUT" | jq -r '.tool_input.content // ""')
ACK_CONTENT=$(printf '%s' "$INPUT" | jq -r '
[ .tool_input.content,
.tool_input.new_string,
(.tool_input.edits[]?.new_string) ]
| map(select(. != null)) | join("\n")
')
if [ "$TOOL_NAME" = "Edit" ] || [ "$TOOL_NAME" = "MultiEdit" ]; then
EXISTING_FILE=""
MAX_EXISTING_BYTES=1048576
READ_BLOCK_REASON=""
CANDIDATES=("$FILE")
if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then
CANDIDATES+=("$CLAUDE_PROJECT_DIR/$FILE")
fi
for CANDIDATE in "${CANDIDATES[@]}"; do
[ -n "$CANDIDATE" ] || continue
[ -e "$CANDIDATE" ] || [ -L "$CANDIDATE" ] || continue
if [ -L "$CANDIDATE" ]; then
READ_BLOCK_REASON="refuses to read symlink target $CANDIDATE"
break
fi
if [ ! -f "$CANDIDATE" ]; then
READ_BLOCK_REASON="refuses to read non-regular file $CANDIDATE"
break
fi
if [ ! -r "$CANDIDATE" ]; then
READ_BLOCK_REASON="refuses to read unreadable file $CANDIDATE"
break
fi
FILE_BYTES=$(wc -c < "$CANDIDATE" | tr -d '[:space:]')
case "$FILE_BYTES" in
''|*[!0-9]*)
READ_BLOCK_REASON="cannot determine size for $CANDIDATE"
break
;;
esac
if [ "$FILE_BYTES" -gt "$MAX_EXISTING_BYTES" ]; then
READ_BLOCK_REASON="refuses to read $CANDIDATE larger than $MAX_EXISTING_BYTES bytes"
break
fi
EXISTING_FILE="$CANDIDATE"
break
done
if [ -n "$READ_BLOCK_REASON" ]; then
echo "Unable to safely inspect edited migration for ${FILE:-pending write}: $READ_BLOCK_REASON." >&2
exit 2
fi
if [ -n "$EXISTING_FILE" ]; then
if ! CONTENT=$(printf '%s' "$INPUT" | jq -r --rawfile content "$EXISTING_FILE" '
def replace_once($old; $new):
if ($old == "") then .
else (index($old) as $ix
| if $ix == null then .
else .[0:$ix] + $new + .[($ix + ($old | length)):]
end)
end;
def apply_edit($edit):
if ($edit.replace_all == true) then split($edit.old_string) | join($edit.new_string)
else replace_once($edit.old_string; $edit.new_string)
end;
. as $input
| if $input.tool_name == "Edit" then
$content | apply_edit($input.tool_input)
elif $input.tool_name == "MultiEdit" then
reduce ($input.tool_input.edits[]? // empty) as $edit ($content; apply_edit($edit))
else
$content
end
'); then
echo "Unable to reconstruct edited migration for ${FILE:-pending write}; blocked by the safety gate." >&2
exit 2
fi
else
if ! CONTENT=$(printf '%s' "$INPUT" | jq -r '
[ .tool_input.new_string,
(.tool_input.edits[]?.new_string) ]
| map(select(. != null)) | join("\n")
'); then
echo "Unable to inspect edited migration for ${FILE:-pending write}; blocked by the safety gate." >&2
exit 2
fi
fi
fi
[ -z "$CONTENT" ] && exit 0
# Escape hatch: require the acknowledgement in the pending write/edit text so
# stale allow comments already in the file cannot suppress newly added risks.
if printf '%s' "$ACK_CONTENT" | grep -qiE 'safety-gate:[[:space:]]*allow|safety_assured|strong_migrations[[:space:]]*:[[:space:]]*disable'; then
exit 0
fi
findings=""
flag() {
if printf '%s' "$CONTENT" | grep -iqE "$2"; then
findings="${findings}${1}"$'\n'
fi
}
flag "DROP TABLE (irreversible data loss)" 'drop[[:space:]]+table'
flag "DROP COLUMN (irreversible data loss)" 'drop[[:space:]]+column'
flag "TRUNCATE (removes all rows)" '(^|[^a-z])truncate[[:space:]]'
flag "Table/column RENAME (breaks running code mid-deploy)" 'rename[[:space:]]+(table|column|to)[[:space:]]'
# CREATE INDEX without CONCURRENTLY locks writes on large tables.
if printf '%s' "$CONTENT" | grep -iE 'create[[:space:]]+(unique[[:space:]]+)?index' | grep -ivqE 'concurrently'; then
findings="${findings}CREATE INDEX without CONCURRENTLY (locks writes on large tables)"$'\n'
fi
if [ -n "$findings" ]; then
echo "Unsafe database migration in ${FILE:-pending write} blocked by the safety gate:" >&2
printf '%s' "$findings" | while IFS= read -r f; do
[ -n "$f" ] && echo " - $f" >&2
done
echo "Use a safe pattern (add columns nullable then backfill, create indexes CONCURRENTLY, expand-then-contract for renames) or add a '-- safety-gate: allow' comment to acknowledge the risk and proceed." >&2
exit 2
fi
exit 0
Gates database migrations before they are written, blocking irreversible or lock-heavy operations rather than discovering them after a bad deploy.
Detection classes follow the strong_migrations safe-migration checks: DROP TABLE, DROP COLUMN, TRUNCATE, table/column RENAME, and CREATE INDEX without CONCURRENTLY.
Blocks with exit code 2 and feeds the reason back to Claude, so the model can switch to a safe pattern instead of shipping the risky statement.
Includes an explicit escape hatch — a -- safety-gate: allow comment acknowledges the risk and lets an intentional change through.
Pure local bash + jq; it never connects to a database, runs SQL, or makes a network call.
How it works
On PreToolUse, the hook checks whether the target path looks like a migration (a migrations/, migrate/, or db/migrate/ directory, or a .sql file). If so, it reads Write content from the tool input, or reconstructs the final migration for Edit and MultiEdit by applying the requested replacements to the existing local file, then scans that final SQL for the unsafe operation classes above. Any match prints a blocked-reason list to stderr and exits 2, which stops the write — unless the content carries an acknowledgement comment.
Safe-pattern guidance it nudges toward
Add columns nullable, backfill, then add the NOT NULL constraint in a later migration.
Create indexes with CONCURRENTLY to avoid locking writes on large tables.
Use expand-then-contract for renames so running code never breaks mid-deploy.
Treat DROP/TRUNCATE as deliberate, acknowledged steps.
Use cases
Stop an agent from generating a DROP COLUMN or non-concurrent index migration during a refactor.
Enforce safe-migration discipline in a team without wiring a full migration linter into CI.
Make irreversible schema changes an explicit, acknowledged decision.
Installation
Create the hooks directory: mkdir -p .claude/hooks
Create the hook file: touch .claude/hooks/database-migration-safety-gate.sh
Paste the script body into that file and make it executable: chmod +x .claude/hooks/database-migration-safety-gate.sh
Add the configuration below to .claude/settings.json (project) or ~/.claude/settings.json (user).
Regex heuristics target common SQL phrasings; ORM-DSL migrations (for example remove_column in Rails or a Knex dropColumn call) and heavily obfuscated SQL may not match — extend the patterns for your toolchain.
Detecting DELETE/UPDATE without a WHERE clause reliably requires real SQL parsing and is intentionally left out to avoid false positives.
Show that Database Migration Safety Gate - Claude Code Hook is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.
[](https://heyclau.de/entry/hooks/database-migration-safety-gate)
How it compares
Database Migration Safety Gate - Claude Code Hook side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.
2 trust signals differ across this comparison (Source provenance, Submitter).
PreToolUse hook that inspects a database migration before it is written and blocks irreversible or lock-heavy operations — DROP TABLE/COLUMN, TRUNCATE, table/column RENAME, and CREATE INDEX without CONCURRENTLY — following the strong_migrations safe-migration checks.
PreToolUse Bash guardrail implementing the Claude Code hooks guide drop-table example: exit 2 with stderr feedback when Bash command text contains a case-insensitive DROP TABLE pattern.
PostToolUse hook that detects writes to migration, schema, and SQL files then runs framework-specific status checks — runs knex migrate:status for Node.js projects and python manage.py showmigrations for Django projects.
PreToolUse hook that scans the exact text Claude Code is about to write or edit for high-confidence secret formats (AWS access keys, GitHub tokens, OpenAI keys, Slack tokens, Google API keys, Stripe keys, and private key blocks) and blocks the write with a non-zero exit before the secret ever reaches disk.
✓Runs before Write, Edit, and MultiEdit on files under a migrations path or with a .sql extension; for edits, it reads only regular, non-symlink existing files up to 1 MiB and applies the requested replacement before scanning the final SQL.
Blocks the write with exit code 2 when it detects DROP TABLE/COLUMN, TRUNCATE, a table/column RENAME, or CREATE INDEX without CONCURRENTLY; the hook never connects to or runs SQL against any database.
Provides an explicit escape hatch - include a '-- safety-gate: allow' comment in the pending Write, Edit, or MultiEdit content to acknowledge the risk and let it through; stale allow comments already present in an edited file do not bypass new risky edits.
Uses regex heuristics, so it can miss obfuscated statements or flag an intentional change; review every migration regardless of the result.
✓Implements only the hooks-guide drop-table guardrail; extend locally for additional patterns.
Exit code 2 blocks the Bash tool call and returns stderr feedback to Claude.
✓Runs automatically after write or edit activity on migration, schema, and SQL files.
Invokes knex migrate:status for Knex projects and python manage.py showmigrations for Django projects when the respective framework CLI is available.
Scans raw SQL for destructive statements and reports warnings but does not apply migrations itself.
✓Runs before every Write, Edit, and MultiEdit and reads the pending content from the tool input on stdin.
Blocks the write with exit code 2 when a high-confidence secret pattern matches; no files are created, deleted, or modified by the hook itself.
Uses regex heuristics, so it can produce false positives (block a non-secret) or false negatives (miss an obfuscated secret); treat it as a guardrail, not proof of safety.
Makes no network calls and runs entirely locally.
Safe for user-level settings only when the command points to a trusted script you installed under your home directory; do not configure global hooks to execute scripts from `$CLAUDE_PROJECT_DIR`.
Privacy notes
✓Reads the pending Write content from the tool input and, for Edit or MultiEdit, the targeted local migration file only when it is a regular, non-symlink file up to 1 MiB so it can scan the final content; it opens no database connections and makes no network calls.
Prints the file path and the names of the detected risky operation classes to local hook stderr; it writes no logs.
The file path shown in output may reveal local directory structure in your terminal.
✓Reads proposed Bash command text from stdin locally; no network access.
✓Reads migration, schema, SQL, package, and framework configuration files to infer migration state.
Command output may reveal database names, migration names, table names, or schema details in the local hook output.
✓Reads the text about to be written but never prints the matched secret value; only the detected secret type and the target file path are written to stderr.
Writes nothing to disk and retains no logs.
The target file path shown in the message may reveal local directory structure in your terminal output.
Prerequisites
Claude Code CLI with hooks enabled.
bash and jq on PATH; the hook fails open and stays silent when jq is missing.
— none listed
— none listed
Claude Code CLI with hooks enabled.
bash and jq available on PATH (the hook fails open and does not block if jq is missing).