Approach: Use a Git pre-commit hook (pre-commit local script) that finds staged files with .sql, runs sqlfluff lint (or fix --no-progress) on the staged content via git show :path to avoid linting unstaged changes, and fail the commit if any linting errors exist.python
#!/usr/bin/env python3
"""
pre-commit hook: lint staged .sql files with sqlfluff.
Exit non-zero to reject commit if any errors found.
"""
import subprocess
import sys
from pathlib import Path
def get_staged_sql_files():
# list staged files (Added/Modified) only
out = subprocess.check_output(
["git", "diff", "--cached", "--name-only", "--diff-filter=AM"]
).decode().splitlines()
return [p for p in out if p.lower().endswith(".sql")]
def lint_file_from_index(path):
# get staged content from index and pipe to sqlfluff lint via stdin
staged = subprocess.check_output(["git", "show", f":{path}"])
# run sqlfluff lint reading from stdin; specify dialect if needed e.g. --dialect postgres
proc = subprocess.run(
["sqlfluff", "lint", "--stdin", path],
input=staged,
)
return proc.returncode
def main():
files = get_staged_sql_files()
if not files:
return 0
failed = []
for f in files:
rc = lint_file_from_index(f)
if rc != 0:
failed.append(f)
if failed:
print("sqlfluff lint failed for staged files:")
for f in failed:
print(" ", f)
print("Please fix lint errors or run `sqlfluff fix` before committing.")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
CLI commands to detect staged SQL files (examples):- git diff --cached --name-only --diff-filter=AM | grep -i '\.sql$'- git show :path/to/file.sql (to read staged content)Install instructions:1. Save the script as .git/hooks/pre-commit at repo root.2. Make it executable: chmod +x .git/hooks/pre-commit3. Ensure sqlfluff is installed (pip install sqlfluff) and configured (.sqlfluff config) or specify dialect in script.4. Optional: Use pre-commit framework — add to .pre-commit-config.yaml with a local hook that calls this script.Notes:- Using git show :path ensures you lint exactly what will be committed.- For auto-fix, run sqlfluff fix on working files, re-add, then commit.- For CI, run sqlfluff lint across the repo to enforce same rules.