sqldelight/sqldelight

PostgreSql Dialect - INSERT VALUES...SELECT...RETURNING clause won't compile

griffio opened this issue ยท 3 comments

SQLDelight Version

2.0.1 / 2.1.0 SNAPSHOT

SQLDelight Dialect

PostgreSql

Describe the Bug

๐Ÿ”• Common Table Expression (CTE) INSERT VALUES...SELECT...RETURNING clause won't compile

https://www.postgresql.org/docs/current/queries-with.html

This is the smallest reproducible error - a real use case is for CTEs that insert parent/child records

WITH new_test AS (
   INSERT INTO test (name) SELECT 'a' FROM sample
   RETURNING *
)
SELECT * FROM new_test;

Compilation error 'WITH' unexpected - this normally means that none of rules matched the grammar.

Work-around add ON CONFLICT (...) DO NOTHING - for some reason this causes the grammar rule to match

https://github.com/griffio/sqldelight/blob/3abf9496e273237b76909333fcf9ed3c28795bda/dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/grammar/PostgreSql.bnf#L241-L245

WITH new_test AS (
   INSERT INTO test (name) SELECT 'a' FROM sample
   ON CONFLICT (name) DO NOTHING
   RETURNING *
)
SELECT * FROM new_test;

Stacktrace

No response

Closing this for now as it does work on current 2.0.1 ๐Ÿ˜–
There is even a test fixture in sql-psi test-fixtures/build/resources/main/fixtures/well-formed-selects

I will re-open and update if issue reappears with a more complex usage

Re-opened with actual problem

Seems to be similar to other issue caused by nested square brackets sqldelight/sql-psi#554

๐Ÿ™… Have tried fix in sql-psi but not quite working fully
https://github.com/AlecKazakova/sql-psi/blob/4d6f68a981b82daeecbd157c1f36af4223782a0a/core/src/main/kotlin/com/alecstrong/sql/psi/core/sql.bnf#L368