mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-07 12:26:52 +00:00
adds sql formatter
This commit is contained in:
parent
d4b887a69e
commit
087a963817
2 changed files with 40 additions and 0 deletions
|
|
@ -183,3 +183,8 @@
|
||||||
entry: trailing-whitespace-fixer
|
entry: trailing-whitespace-fixer
|
||||||
language: python
|
language: python
|
||||||
types: [text]
|
types: [text]
|
||||||
|
- id: format-sql
|
||||||
|
name: Format SQL Files
|
||||||
|
description: This hook formats SQL files
|
||||||
|
entry: sql-formatter
|
||||||
|
language: python
|
||||||
|
|
|
||||||
35
pre_commit_hooks/format_sql.py
Executable file
35
pre_commit_hooks/format_sql.py
Executable file
|
|
@ -0,0 +1,35 @@
|
||||||
|
import sys
|
||||||
|
import click
|
||||||
|
import os
|
||||||
|
import sqlparse
|
||||||
|
|
||||||
|
options = {"keyword_case": "upper", "comma_first": True}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def reformat(sql_file):
|
||||||
|
with open(sql_file, "r") as f:
|
||||||
|
original = f.read()
|
||||||
|
new = sqlparse.format(original, **options)
|
||||||
|
with open(sql_file, "w") as f:
|
||||||
|
f.write(new)
|
||||||
|
if new == original:
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
@click.command()
|
||||||
|
@click.option('--directory', required=True)
|
||||||
|
def main(directory):
|
||||||
|
res = 0
|
||||||
|
for root, dirs, files in os.walk(directory):
|
||||||
|
for f in files:
|
||||||
|
if f.split('.')[-1] == 'sql':
|
||||||
|
res = max(res, reformat(os.path.join(root, f)))
|
||||||
|
print(f"reformatted {f}")
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
Loading…
Add table
Add a link
Reference in a new issue