The Python Oracle

How to pretty format the printing of SQL Queries in SQLAlchemy?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 How To Pretty Format The Printing Of Sql Queries In Sqlalchemy?
01:17 Answer 1 Score 38
01:27 Accepted Answer Score 12
01:40 Answer 3 Score 19
02:19 Answer 4 Score 0
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/4433...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oracle #python27 #sqlalchemy

#avk47



ANSWER 1

Score 38


Use the sqlparse package:

sqlparse.format(sql, reindent=True, keyword_case='upper')`



ANSWER 2

Score 19


The project sqlparse is mature (more than 10 years) and is still very active. sqlparse aims at parsing, splitting and formatting SQL statements.

The following example uses sqlparse to pretty formats SQL files:

import argparse
import sqlparse

# Parse command line arguments
parser = argparse.ArgumentParser(prog="pretty_print_sql")
parser.add_argument("file", type=argparse.FileType("r"), nargs="+")
args = parser.parse_args()

# Pretty print input files
for file in args.file:
    print(sqlparse.format(file.read(), reindent=True, keyword_case='upper'))

To install sqlparse using pip for personal usage:

python3 -m pip install sqlparse --user --upgrade

To install sqlparse using pipenv (within a project):

python3 -m pipenv install sqlparse



ACCEPTED ANSWER

Score 12


Some options:




ANSWER 4

Score 0


Following both v_retoux and oHo's examples, I created an easy-to-deploy script on GitHub that uses sqlparse. It handles one or more SQL files and has a clean output that can be piped for single files.

Here is the source:

import argparse, sqlparse, re

parser = argparse.ArgumentParser(prog="sqlpp")
parser.add_argument("--verbose", "-v", action='store_true')
parser.add_argument("file", type=argparse.FileType("r"), nargs="+")

args = parser.parse_args()

def prepend(s, s2): return s2 + re.sub('\n', '\n'+s2, s)

# Pretty print input files
n=len(args.file)
for i, file in enumerate(args.file):
    sIn = file.read().replace('\n', '')
    file.close()
    sOut = sqlparse.format(sIn, reindent=True, keyword_case='upper')
    if args.verbose or n > 1:
        print("File{0}:\n    {1}\n{2}\nFormatted SQL:\n{3}\n".format(
             (' ' + str(i+1) if n > 1 else '')
            ,file.name
            ,("\nOriginal SQL:\n{}\n".format(prepend(sIn, "    "))
                    if args.verbose else "")
            ,prepend(sOut, "    ")
        ))
    else:
        print(sOut)