sqlglot icon indicating copy to clipboard operation
sqlglot copied to clipboard

DATEADD with MILLISECOND or MICROSECOND produces wrong output for Hive and Spark

Open saanvimundra opened this issue 2 weeks ago • 0 comments

Read dialect: tsql (also any dialect that produces exp.DateAdd/exp.DateSub) Write dialects: hive, spark, spark2 Tested on: main at 3194cf845 (v30.32.1.dev5)

Repro

import sqlglot

sqlglot.transpile("SELECT DATEADD(MILLISECOND, 500, ts) FROM t", read="tsql", write="hive")
# ['SELECT DATE_ADD(ts, 500) FROM t']

sqlglot.transpile("SELECT DATEADD(MILLISECOND, 500, ts) FROM t", read="tsql", write="spark")
# ['SELECT DATE_ADD(ts, 500) FROM t']

sqlglot.transpile("SELECT DATEADD(MICROSECOND, 100, ts) FROM t", read="tsql", write="hive")
# ['SELECT DATE_ADD(ts, 100) FROM t']

Expected:

Input Expected Hive output Expected Spark output
DATEADD(MILLISECOND, 500, ts) CAST(ts AS TIMESTAMP) + INTERVAL '500' MILLISECOND TIMESTAMPADD(MILLISECOND, 500, ts)
DATEADD(MICROSECOND, 100, ts) CAST(ts AS TIMESTAMP) + INTERVAL '100' MICROSECOND TIMESTAMPADD(MICROSECOND, 100, ts)
DATEADD(SECOND, 30, ts) CAST(ts AS TIMESTAMP) + INTERVAL '30' SECOND ✓ TIMESTAMPADD(SECOND, 30, ts) ✓

SECOND already works correctly after #9085. MILLISECOND and MICROSECOND do not.

Root cause

#9083 / #9085 added dateadd_sql overrides to HiveGenerator, SparkGenerator, and Spark2Generator to route sub-day units through INTERVAL or TIMESTAMPADD instead of falling back to _add_date_sql. The guard condition was:

if expression.text("unit").upper() in ("HOUR", "MINUTE", "SECOND"):

MILLISECOND and MICROSECOND were not included, so they reach _add_date_sql, which looks up the unit in DATE_DELTA_INTERVAL. That dict has no entry for sub-second units, so the default ("DATE_ADD", 1) applies — adding N days instead of N milliseconds or microseconds.

Severity

Silent wrong result, exits 0. For 500 ms the query adds 500 days instead. The error is 86,400,000× for milliseconds and 86,400,000,000× for microseconds.

Fix

Add "MILLISECOND" and "MICROSECOND" to the guard tuple in all three generators. The existing codepaths already produce the correct output for those units once they are admitted.

saanvimundra avatar Nov 16 '26 20:11 saanvimundra