Skip to content

Instantly share code, notes, and snippets.

@BrianMehrman
Last active July 5, 2018 20:10
Show Gist options
  • Save BrianMehrman/9e80579386cf416a16be1d90b7786374 to your computer and use it in GitHub Desktop.
Save BrianMehrman/9e80579386cf416a16be1d90b7786374 to your computer and use it in GitHub Desktop.
pretty print your SQL
#!/usr/bin/env python
import argparse
import sys
import sqlparse
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalTrueColorFormatter
def prettyPrint(raw_sql):
lexer = get_lexer_by_name('sql', stripall=True)
formatter = TerminalTrueColorFormatter()
formatted_sql = sqlparse.format(raw_sql, encoding=None, keyword_case='upper', identifier_case='lower', reindent=True)
return highlight(formatted_sql, lexer, formatter)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Pretty print sql.")
parser.add_argument('sql', nargs='?', help='sql as a string')
parser.add_argument('-f', '--file', help='read from file.')
args = parser.parse_args()
if args.file:
sql = open(args.file, 'r')
elif args.sql:
sql = args.sql
else:
sql = sys.stdin
print(prettyPrint(sql))
@BrianMehrman
Copy link
Author

BrianMehrman commented Feb 14, 2018

Set file permission to run as executable.

chmod +x prettySQL.py

test.sql

SELECT * FROM foos WHERE foo.blah > 0;

Pretty SQL takes an sql file and outputs formatted sql

» ./prettySQL.py -f test.sql
SELECT *
FROM foos
WHERE foo.blah > 0;

or

» cat test.sql | ./prettySQL.py                                                                                                                                                       
SELECT *
FROM foos
WHERE foo.blah > 0;

or

./prettySQL.py 'SELECT * FROM foos WHERE foo.blah > 0;'                                                                                                                              brian.mehrman@centro-201727
SELECT *
FROM foos
WHERE foo.blah > 0;

Warning if you do not pass in an argument the script will just hang there.

@ddrscott
Copy link

I do: pbpaste | sqlpp a lot. I wonder if there's an easy way to support that.

@BrianMehrman
Copy link
Author

I will see what I can do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment