SQL string formatter [closed]

Try sqlparse module’s sqlformat

Check out sqlparse. It is a Python module that installs the command sqlformat. Usage is simple, e.g.:

sqlformat --reindent --keywords upper --identifiers lower my_file.sql

Example:

$ echo "sElECt f1,f2,fname,lName FrOm tblName WhErE f1=true aNd fname iS nOt null oRdEr bY lName aSc" | \
sqlformat - --reindent --keywords upper --use_space_around_operators
SELECT f1,
       f2,
       fname,
       lName
FROM tblName
WHERE f1 = TRUE
  AND fname IS NOT NULL
ORDER BY lName ASC

I tried the aforementioned CLI alternatives, but:

  • sqlinform is out, because I want an open source CLI application.
  • fsqlf has only few features (create view is missing for example).

Note on SQL keywords

There are many SQL keywords. And they differ by SQL dialect. Wikipedia has a list: List of SQL reserved words

These keywords are illegal for use as an identifier. And if you still try, then there might be unpleasant surprises.

Thanks to sqlformat I learned that “REF” is a reserved keyword in SQL:2011 and SQL:2008.

So this explains why when you say want uppercase keywords but lowercase identifiers “rEf” here becomes “REF”, but “mYrEf” becomes “myref”:

$ echo 'sElEcT rEf fRoM mYtAbLe' | sqlformat - --reindent --keywords upper --identifiers lower
SELECT REF
FROM mytable


$ echo 'sElEcT mYrEf fRoM mYtAbLe' | sqlformat - --reindent --keywords upper --identifiers lower
SELECT myref
FROM mytable

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)