sql-formatter-org / sql-formatter

A whitespace formatter for different query languages
https://sql-formatter-org.github.io/sql-formatter/
MIT License
2.32k stars 398 forks source link

[FORMATTING] psycopg2 params broken up by formatter #733

Closed ibrokemypie closed 5 months ago

ibrokemypie commented 5 months ago

Input data

Which SQL and options did you provide as input?

SELECT
%(param)s param
FROM 
table;

Expected Output

SELECT
  %(param)s param
FROM
  table;

Actual Output

SELECT
  % (param) s param
FROM
  table;

Usage

Using sql-formatter version 15.3.0 through nvim lsp-config with the language set to postgresql. Usage is described by the psycopg2 docs here https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries

Seems like this is the pyformat style from the PEP 249 standard https://peps.python.org/pep-0249/#paramstyle. Found https://github.com/sql-formatter-org/sql-formatter/issues/545#issuecomment-1479827705 but as I am using a higher version already I believe this is a separate issue.

nene commented 5 months ago

I think you misread the issue you're referencing. What was implemented in the context of it wasn't support for PEP 245 (or whatever other parameter syntax). What was actually implemented was a way to define custom SQL parameters syntax.

ibrokemypie commented 5 months ago

To anyone who ends up here in the future, I got it working with this monstrosity (config for conform.nvim)

formatters = {
sql_formatter = {
    args = {
        "-l",
        "postgresql",
        "--config",
        "{ "
        .. '"keywordCase": "upper", '
        .. '"paramTypes": { '
        .. '"custom": ['
        .. "{ "
        .. [["regex": "%\\(.+\\)s"]]
        -- .. '"key": "(text) => text.slice(2, -2)"'
                .. " },"                                    
                .. "{ "                                     
                .. [["regex": "%s"]]                        
                .. " }"                                     
                .. "] "                                     
        .. "} "
        .. "}",
    },
    },
},

I wasn't able to get key working as it seems to require a function which I don't know if it is possible to encode in json, but as I am not using sql-formatter's param substitution (using psycopg2's) I think thats okay.

Both of these now format correctly

SELECT
  %s foo
  %(bar)s
FROM
  table;