sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

Snowflake/Postgres generate unparseable INTERVAL for expression amounts

Open princejain756 opened this issue 1 month ago • 1 comments

Snowflake (and Postgres) drop interval amounts that are expressions rather than literals. INTERVAL (-1) MONTH parses to an Interval whose this is Paren(Neg(1)) with an empty .name. SINGLE_STRING_INTERVAL dialects treat that empty name the same as a missing amount and emit INTERVAL MONTH, which no longer parses.

import sqlglot

sql = "SELECT CAST('2016-05-31' AS DATE) + INTERVAL (-1) MONTH"
out = sqlglot.parse_one(sql, read="snowflake").sql(dialect="snowflake")
print(out)  # SELECT CAST('2016-05-31' AS DATE) + INTERVAL MONTH
sqlglot.parse_one(out, read="snowflake")  # ParseError

INTERVAL ((((1 - ISODOW(d)) + 6) % 7) + 1) DAY similarly collapses to INTERVAL DAY.

Fix ready on princejain756/sqlglot@fix-interval-expr-amount (0765108): the bare-unit early return now only applies when the interval has no amount at all, so expression amounts fall through to the generic path and emit INTERVAL (-1) MONTH. Includes two test_snowflake.py identities; the full dialect suite passes. I could not open the PR (GitHub denied createPullRequest for my account on this repo), so leaving it here for review.

princejain756 avatar Oct 21 '26 20:10 princejain756

@princejain756 are you testing these against the warehouse? The input you show above is invalid Snowflake:

(sqlglot) ➜  sqlglot git:(main) snow sql -q "SELECT CAST('2016-05-31' AS DATE) + INTERVAL (-1) MONTH"
SELECT CAST('2016-05-31' AS DATE) + INTERVAL (-1) MONTH
╭─ Error ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ 002139 (02000): 01c7e6b2-0014-0da7-0001-b9fe14174e16: SQL compilation error:                                                                                                            │
│ Unknown function INTERVAL.                                                                                                                                                              │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

georgesittas avatar Oct 22 '26 13:10 georgesittas