vertical-blank / sql-formatter

SQL formatter written with only Java Standard Library, without dependencies.
MIT License
223 stars 46 forks source link

Formatting issue after LIKE Predicate Escape Character '\' #31

Open Darphbobo1573 opened 3 years ago

Darphbobo1573 commented 3 years ago

This only seems to happen when using '\' as the escape character. I've tired all the supported languages using the of(...) with the same results. I've provide a simple sample code and console output.

String a = "SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A\_%' ESCAPE '\' AND prcstype = :1"; System.out.println(SqlFormatter.format(a));

Output: SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A_%' ESCAPE '\' AND prcstype = :1

Using some other character, in this case '!' String a = "SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A!_%' ESCAPE '!' AND prcstype = :1"; System.out.println(SqlFormatter.format(a));

Output: SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A!_%' ESCAPE '!' AND prcstype = :1

vertical-blank commented 3 years ago

It seems that your sinppet contains compilation error about escape sequences.

error: illegal escape character
    String a = "SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A\_%' ESCAPE '\' AND prcstype = :1";
                                                                ^
1 error

When I correct it as:

    String a = "SELECT * FROM psprcsrqst WHERE prcsname LIKE 'A\\_%' ESCAPE '\\' AND prcstype = :1";

Then output is:

SELECT
  *
FROM
  psprcsrqst
WHERE
  prcsname LIKE 'A\_%' ESCAPE '\' AND prcstype = :1
Darphbobo1573 commented 3 years ago

Yes I see the typo I had for which I'm sorry; However, the output you got after correcting the typo, when using the backslash as the escape character, is still not formatted properly as the AND prcstype = :1 didn't wrap to the next line as one would expect when formatting. This behavior is what I was trying to convey as the issue, albeit I slight issue.

manticore-projects commented 1 year ago

Greetings.

With JSQLFormatter, those queries will be formatted well. Although it took me quite some effort to get it right: The problem is the greediness of the Regular Expressions, since \' would be interpreted as escaped ' already. You will need to mangle the matches as shown for QUOTED_IDENTIFIER at https://github.com/manticore-projects/JSqlParser/blob/5e7732c870a66afff5b39214b2cfbb0409e12585/src/main/jjtree/net/sf/jsqlparser/parser/JSqlParserCC.jjt#L562