Created
February 13, 2018 22:24
-
-
Save ddrscott/62f5791b8fe1ddccf22b77b6d4a7bea6 to your computer and use it in GitHub Desktop.
Helper to beautify SQL statements. Works as file or pipe.
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 ruby | |
| require 'open3' | |
| # # Dependencies | |
| # `sqlformat` and `pygmentize` are Python programs :/ | |
| # make sure it's installed and available in your path. | |
| # ``` | |
| # $ pip install --upgrade sqlparse | |
| # $ pip install --upgrade pygment | |
| # $ export PATH=$PATH:~/Library/Python/3.5/bin | |
| sql = ARGF.read.strip | |
| cmd = 'sqlformat -k upper -i lower --reindent_aligned -' + ($stdout.isatty ? '| pygmentize -g -l sql' : '') | |
| out, _status = Open3.capture2(cmd, stdin_data: sql) | |
| puts out |
Author
Author
ln -s sqlpp.rb /usr/local/bin/sqlpp
chmod +x sqlpp.rb
sqlpp something.sql
pbpaste | sqlpp
pbpaste | sqlpp | pbcopy # paste in your IDE.
Is this what you are looking for?
# prettySQL.py
#!/usr/bin/env python
import sys
import sqlparse
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalTrueColorFormatter
def prettyPrint(file_name):
raw_sql = open(file_name, 'r')
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__':
print(prettyPrint(sys.argv[-1]))
-- test.sql
SELECT * FROM foos WHERE foo.blah > 0;
» ./prettySQL.py test.sql
SELECT *
FROM foos
WHERE foo.blah > 0;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be great if someone could convert this to a pure Python script...