Skip to content

Commit

Permalink
Fix: interval execution closes #1650
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed May 18, 2023
1 parent 6f9d531 commit 72c5995
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 3 deletions.
9 changes: 6 additions & 3 deletions sqlglot/executor/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from functools import wraps

from sqlglot import exp
from sqlglot.generator import Generator
from sqlglot.helper import PYTHON_VERSION


Expand Down Expand Up @@ -119,9 +120,11 @@ def ordered(this, desc, nulls_first):

@null_if_any
def interval(this, unit):
if unit == "DAY":
return datetime.timedelta(days=float(this))
raise NotImplementedError
unit = unit.lower()
plural = unit + "s"
if plural in Generator.TIME_PART_SINGULARS:
unit = plural
return datetime.timedelta(**{unit: float(this)})


ENV = {
Expand Down
1 change: 1 addition & 0 deletions sqlglot/executor/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ class Generator(generator.Generator):
exp.Distinct: lambda self, e: f"set({self.sql(e, 'this')})",
exp.Extract: lambda self, e: f"EXTRACT('{e.name.lower()}', {self.sql(e, 'expression')})",
exp.In: lambda self, e: f"{self.sql(e, 'this')} in ({self.expressions(e, flat=True)})",
exp.Interval: lambda self, e: f"INTERVAL({self.sql(e.this)}, '{self.sql(e.unit)}')",
exp.Is: lambda self, e: self.binary(e, "is"),
exp.Lambda: _lambda_sql,
exp.Not: lambda self, e: f"not {self.sql(e.this)}",
Expand Down
4 changes: 4 additions & 0 deletions sqlglot/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3509,6 +3509,10 @@ def __init__(self, **args):
class Interval(TimeUnit):
arg_types = {"this": False, "unit": False}

@property
def unit(self) -> t.Optional[Var]:
return self.args.get("unit")


class IgnoreNulls(Expression):
pass
Expand Down
1 change: 1 addition & 0 deletions tests/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,7 @@ def test_scalar_functions(self):
("IF(false, 1, 0)", 0),
("CASE WHEN 0 = 1 THEN 'foo' ELSE 'bar' END", "bar"),
("CAST('2022-01-01' AS DATE) + INTERVAL '1' DAY", date(2022, 1, 2)),
("INTERVAL '1' week", datetime.timedelta(weeks=1)),
("1 IN (1, 2, 3)", True),
("1 IN (2, 3)", False),
("NULL IS NULL", True),
Expand Down

0 comments on commit 72c5995

Please sign in to comment.