Skip to content

Commit d37a5bb

Browse files
authored
Fix(snowflake): handle DIV0 case where divident is null (#3975)
1 parent f7e4e4a commit d37a5bb

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

sqlglot/dialects/snowflake.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ def _builder(args: t.List) -> E:
9393

9494
# https://docs.snowflake.com/en/sql-reference/functions/div0
9595
def _build_if_from_div0(args: t.List) -> exp.If:
96-
cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0))
96+
cond = exp.EQ(this=seq_get(args, 1), expression=exp.Literal.number(0)).and_(
97+
exp.Is(this=seq_get(args, 0), expression=exp.null()).not_()
98+
)
9799
true = exp.Literal.number(0)
98100
false = exp.Div(this=seq_get(args, 0), expression=seq_get(args, 1))
99101
return exp.If(this=cond, true=true, false=false)

tests/dialects/test_snowflake.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -598,12 +598,12 @@ def test_snowflake(self):
598598
self.validate_all(
599599
"DIV0(foo, bar)",
600600
write={
601-
"snowflake": "IFF(bar = 0, 0, foo / bar)",
602-
"sqlite": "IIF(bar = 0, 0, CAST(foo AS REAL) / bar)",
603-
"presto": "IF(bar = 0, 0, CAST(foo AS DOUBLE) / bar)",
604-
"spark": "IF(bar = 0, 0, foo / bar)",
605-
"hive": "IF(bar = 0, 0, foo / bar)",
606-
"duckdb": "CASE WHEN bar = 0 THEN 0 ELSE foo / bar END",
601+
"snowflake": "IFF(bar = 0 AND NOT foo IS NULL, 0, foo / bar)",
602+
"sqlite": "IIF(bar = 0 AND NOT foo IS NULL, 0, CAST(foo AS REAL) / bar)",
603+
"presto": "IF(bar = 0 AND NOT foo IS NULL, 0, CAST(foo AS DOUBLE) / bar)",
604+
"spark": "IF(bar = 0 AND NOT foo IS NULL, 0, foo / bar)",
605+
"hive": "IF(bar = 0 AND NOT foo IS NULL, 0, foo / bar)",
606+
"duckdb": "CASE WHEN bar = 0 AND NOT foo IS NULL THEN 0 ELSE foo / bar END",
607607
},
608608
)
609609
self.validate_all(

0 commit comments

Comments
 (0)