Skip to content

Instantly share code, notes, and snippets.

@kva1966
Created October 16, 2019 03:44
Show Gist options
  • Save kva1966/e177df8a9c833aa0386ac7268901cf5c to your computer and use it in GitHub Desktop.
Save kva1966/e177df8a9c833aa0386ac7268901cf5c to your computer and use it in GitHub Desktop.
Very basic SQL Formatter
#!/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