Created
October 16, 2019 03:44
-
-
Save kva1966/e177df8a9c833aa0386ac7268901cf5c to your computer and use it in GitHub Desktop.
Very basic SQL Formatter
This file contains 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 python3 | |
## Simple, regex-based SQL formatter. The core idea is to not muck around | |
## with any indenting, but to simply convert keywords to uppercase. What an | |
## utterly annoying convention today. | |
## Reads stdin, writes to stdout, allowing for use in IDE processes or similar. | |
import sys | |
import re | |
## Incomplete set, updated on demand. :-) | |
keywords = [ | |
'all', | |
'and', | |
'as', | |
'char', | |
'create', | |
'double precision', | |
'from', | |
'function', | |
'inner', | |
'int', | |
'join', | |
'language', | |
'on', | |
'or', | |
'replace', | |
'returns', | |
'select', | |
'sql', | |
'table', | |
'text', | |
'union', | |
'where', | |
] | |
# Potential issues with encoding -- relying on platform defaults. | |
val = sys.stdin.read() | |
for k in keywords: | |
val = re.sub( | |
# Ignore comment-only lines, limitation: inline comments affected still | |
r'^(?!\s*--)(.*)' + k + r'(\s+|\[|\(|,)', | |
r'\1' + k.upper() + r'\2', | |
val, | |
flags=re.IGNORECASE | re.MULTILINE | |
) | |
print(val, end='') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment