cashapp / sqldelight

SQLDelight - Generates typesafe Kotlin APIs from SQL
https://cashapp.github.io/sqldelight/
Apache License 2.0
6.04k stars 501 forks source link

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

Open griffio opened 6 months ago

griffio commented 6 months ago

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

griffio commented 6 months ago

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

griffio commented 6 months ago

Re-opened with actual problem

griffio commented 5 months ago

Seems to be similar to other issue caused by nested square brackets https://github.com/AlecKazakova/sql-psi/pull/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