Skip to content

Instantly share code, notes, and snippets.

@jim-my
Last active March 23, 2025 01:38
Show Gist options
  • Save jim-my/f0a9ff714f5569a6ea3358e9494fd08e to your computer and use it in GitHub Desktop.
Save jim-my/f0a9ff714f5569a6ea3358e9494fd08e to your computer and use it in GitHub Desktop.
SQL formatter using sql-parse(because it doesn't do strict validation, it can also work with template files)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlparse
def format_sql(sql):
"""Format SQL query using sqlparse library."""
return sqlparse.format(
sql,
reindent=True,
reindent_aligned=False, # statements are aligned by keywords.
wrap_after=0, # after how many columns to put column in next line
comma_first=False,
keyword_case="upper",
indent_after_first=False,
indent_width=4,
indent_columns=False,
conpact=True,
strip_whitespace=True,
# right_margin=79, # not implemented in sqlparse
)
if __name__ == "__main__":
# read sql from stdin
import sys
if len(sys.argv) > 1:
with open(sys.argv[1], "r", encoding="utf8") as f:
sql = f.read()
else:
sql = sys.stdin.read()
print(format_sql(sql))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment