sql-formatter-org / sql-formatter

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

Table name or alias "call" misinterpreted by formatter #732

Open ipus1 opened 2 months ago

ipus1 commented 2 months ago

Describe the bug When an alias for a table or expression is called "call", the formatter throws an error when trying to access its fields.

Expected behavior Running

sql = `SELECT call.id as "id" FROM c as call`;
console.log(format(sql, { language: "postgresql" }));

should work, but it doesn't. This, however, does:

sql = `SELECT calls.id as "id" FROM c as calls`;
console.log(format(sql, { language: "postgresql" }));

Actual behavior I got this error:

Error: Parse error at token: . at line 1 column 12
Unexpected PROPERTY_ACCESS_OPERATOR token: {"type":"PROPERTY_ACCESS_OPERATOR","raw":".","text":".","start":11}.

I assume this might happen for other keywords as well, not only "CALL".

Usage

nene commented 2 months ago

Thanks for reporting.

This happens because the formatter expects CALL to be a start of a CALL statement. Similar problem happens with other keywords that mark the start of some statement like SELECT, UPDATE, etc.

Even when that particular crash were to be fixed (we could detect that CALL is followed by .), this will still leave the problem that call inside an alias definition would get formatted on a separate line (as again, the formatter assumes it'll start a CALL-statement):

SELECT
  call.id as "id"
FROM
  c as
call

You might be interested in trying out prettier-plugin-sql-cst, which has a much better support for PostgreSQL (although that support is far from 100%) and doesn't have fundamental problems like this.