Last active
March 23, 2025 01:38
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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