Format SQL strings
See original GitHub issueWith Black and Prettier in place SQL strings are pretty much the only major holdouts in the project I’m working on. Manually enforcing a SQL style is time consuming and boring, format-sql
is broken and unmaintained, and there doesn’t seem to be any other options at the moment.
Of course, detecting plain SQL strings is not going to work on its own; there would be too many false positives. What we could do is detect string literals being used in certain specific method calls, such as psycopg2.SQL("""SELECT …""")
, and format only those. More advanced versions could support psycopg2.SQL(query)
or even psycopg2.SQL(query + optional_where_clause)
.
Ideally the solution would apply similar rules as in Python to common structures. So SELECT foo, bar
would be unchanged, while SELECT foo, [lots of columns], bar
would be formatted as something like
SELECT foo,
first_intermediate_column,
…,
bar
or
SELECT
foo,
first_intermediate_column,
…,
bar
I suspect this is not appropriate as a Black core module because of the dependency on third party packages to determine which strings are actually SQL, but maybe as a plugin?
Issue Analytics
- State:
- Created 4 years ago
- Comments:13
Top GitHub Comments
This is not something that’s likely going to make it into Black itself. Having said that, at my company we use Black’s APIs to parse out all strings and then determine if they’re SQL or not. If they are well-formed SQL statements, we format those using an external binary, shove them back into the AST and then let Black run on the result. So it’s basically the approach you describe. It’s a bit slow because of the need to identify if a string is SQL or not, but in practice it works well enough.
That’s awesome!!! Thanks!