Is there a cli tool that can be used to format SQL code inside strings in a given .py file? Example:
import foo
query = """SELECT please, format, me
FROM i-am-an-unformatted-query
"""
some_client.query(query)
could for example yield
import foo
query = """
SELECT
please,
format,
me
FROM i-am-an-unformatted-query"""
some_client.query(query)
ie, formatting would only occur inside the query string.
Does such a tool exist? The once I've looked at only format standalone files. I would prefer not having discussions about SQL formatting with my colleagues but align around a tool, much like we do with for example black
for python formatting.
CodePudding user response:
According to answer https://stackoverflow.com/a/44335609/687896, in Python you can use package sqlparse
:
>>> import sqlparse
>>> sql = """SELECT please, format, me
FROM i-am-an-unformatted-query
"""
>>> sql_formatted = sqlparse.format(sql, reindent=True, keyword_case='upper')
>>> print(sql_formatted)
SELECT please,
format,
me
FROM i-am-an-unformatted-query
CodePudding user response:
I mean I probably didn't get your question right but, if you're referring to formatting the query i.e : changing it based upon a request or variable you could simply use:
print( """
SELECT {},
format, me
FROM i-am-an-unformatted-query""",format(please))
and the print could be placed in a function that takes the please as an argument.