diff --git a/pyiceberg/expressions/__init__.py b/pyiceberg/expressions/__init__.py index ad916171c5..acdd7c3e42 100644 --- a/pyiceberg/expressions/__init__.py +++ b/pyiceberg/expressions/__init__.py @@ -710,8 +710,12 @@ def __init__( def bind(self, schema: Schema, case_sensitive: bool = True) -> BoundSetPredicate: bound_term = self.term.bind(schema, case_sensitive) - literal_set = self.literals - return self.as_bound(bound_term, {lit.to(bound_term.ref().field.field_type) for lit in literal_set}) # type: ignore + bound_literals = {lit.to(bound_term.ref().field.field_type) for lit in self.literals} + # A literal outside the column type matches no row, so it is left out of the set + in_range = {lit for lit in bound_literals if not isinstance(lit, (AboveMax, BelowMin))} + if self.literals and not in_range: + return AlwaysFalse() if isinstance(self, In) else AlwaysTrue() + return self.as_bound(bound_term, in_range) # type: ignore def __str__(self) -> str: """Return the string representation of the SetPredicate class.""" diff --git a/pyiceberg/expressions/literals.py b/pyiceberg/expressions/literals.py index 041d32bc91..34313a8084 100644 --- a/pyiceberg/expressions/literals.py +++ b/pyiceberg/expressions/literals.py @@ -371,14 +371,53 @@ def _(self, type_var: DecimalType) -> Literal[Decimal]: return DecimalLiteral(Decimal((sign, digits + zeros, -type_var.scale))) -def _float_to_decimal(value: float, type_var: DecimalType) -> Decimal: +class DecimalAboveMax(AboveMax[Decimal], Singleton): + def __init__(self, max_value: Decimal) -> None: + super().__init__(max_value, Decimal) + + @singledispatchmethod + def to(self, type_var: IcebergType) -> Literal: # type: ignore + raise TypeError("Cannot change the type of DecimalAboveMax") + + @to.register(DecimalType) + def _(self, _: DecimalType) -> Literal[Decimal]: + return self + + +class DecimalBelowMin(BelowMin[Decimal], Singleton): + def __init__(self, min_value: Decimal) -> None: + super().__init__(min_value, Decimal) + + @singledispatchmethod + def to(self, type_var: IcebergType) -> Literal: # type: ignore + raise TypeError("Cannot change the type of DecimalBelowMin") + + @to.register(DecimalType) + def _(self, _: DecimalType) -> Literal[Decimal]: + return self + + +def _float_to_decimal(value: float, type_var: DecimalType) -> Literal[Decimal]: + """Convert a float to a decimal column, or return the sentinel when the value is outside the column range.""" if not isfinite(value): raise ValueError(f"Could not convert {value} into a {type_var}, value is not finite") # Use the shortest repr of the float, like BigDecimal.valueOf in Java, so 2.675 rounds to 2.68 shortest = Decimal(str(value)) # Quantize needs a context precision that covers every digit of the result, which can exceed the default 28 digits - with localcontext(prec=max(getcontext().prec, shortest.adjusted() + type_var.scale + 2)): - return shortest.quantize(Decimal((0, (1,), -type_var.scale)), rounding=ROUND_HALF_UP) + with localcontext(prec=max(getcontext().prec, type_var.precision + 2)): + step = Decimal((0, (1,), -type_var.scale)) + limit = Decimal(10) ** (type_var.precision - type_var.scale) + if shortest >= limit: + return DecimalAboveMax(limit - step) + if shortest <= -limit: + return DecimalBelowMin(step - limit) + rounded = shortest.quantize(step, rounding=ROUND_HALF_UP) + # Rounding can carry a value just below the limit up to it, as 9999999.996 to 10000000.00 + if rounded >= limit: + return DecimalAboveMax(limit - step) + if rounded <= -limit: + return DecimalBelowMin(step - limit) + return DecimalLiteral(rounded) class FloatLiteral(Literal[float]): @@ -424,7 +463,7 @@ def _(self, _: DoubleType) -> Literal[float]: @to.register(DecimalType) def _(self, type_var: DecimalType) -> Literal[Decimal]: - return DecimalLiteral(_float_to_decimal(self.value, type_var)) + return _float_to_decimal(self.value, type_var) class DoubleLiteral(Literal[float]): @@ -451,7 +490,17 @@ def _(self, _: FloatType) -> Literal[float]: @to.register(DecimalType) def _(self, type_var: DecimalType) -> Literal[Decimal]: - return DecimalLiteral(_float_to_decimal(self.value, type_var)) + return _float_to_decimal(self.value, type_var) + + @to.register(IntegerType) + @to.register(LongType) + def _(self, type_var: IntegerType | LongType) -> Literal[int]: + if not isfinite(self.value): + raise ValueError(f"Could not convert {self.value} into a {type_var}, value is not finite") + if not self.value.is_integer(): + raise ValueError(f"Could not convert {self.value} into a {type_var}, value has a fractional part") + # The decimal conversion checks the range of the column type + return DecimalLiteral(Decimal(self.value)).to(type_var) class DateLiteral(Literal[int]): diff --git a/pyiceberg/expressions/parser.py b/pyiceberg/expressions/parser.py index a851b9bd3a..b2ae8b7b8b 100644 --- a/pyiceberg/expressions/parser.py +++ b/pyiceberg/expressions/parser.py @@ -40,6 +40,7 @@ ParserElement, ParseResults, QuotedString, + Regex, Suppress, Word, alphanums, @@ -76,6 +77,7 @@ from pyiceberg.expressions.literals import ( BooleanLiteral, DecimalLiteral, + DoubleLiteral, Literal, LongLiteral, StringLiteral, @@ -119,11 +121,13 @@ def _(result: ParseResults) -> Reference: boolean = one_of(["true", "false"], caseless=True) string = sgl_quoted_string.set_results_name("raw_quoted_string") +# A number with an exponent is an approximate numeric literal (a double), as in ANSI SQL +double = Regex(r"[+-]?(?:\d+\.?\d*|\.\d+)[eE][+-]?\d+").set_results_name("double") decimal = common.real().set_results_name("decimal") integer = common.signed_integer().set_results_name("integer") -literal = Group((string | decimal | integer | boolean).set_name("a literal value")).set_results_name("literal") +literal = Group((string | double | decimal | integer | boolean).set_name("a literal value")).set_results_name("literal") literal_set = Group( - (DelimitedList(string) | DelimitedList(decimal) | DelimitedList(integer) | DelimitedList(boolean)).set_name( + (DelimitedList(string) | DelimitedList(double | decimal | integer) | DelimitedList(boolean)).set_name( "a non-empty list of literals" ) ).set_results_name("literal_set") @@ -142,6 +146,11 @@ def _(result: ParseResults) -> Literal[str]: return StringLiteral(result.raw_quoted_string[1:-1].replace("''", "'")) +@double.set_parse_action +def _(result: ParseResults) -> Literal[float]: + return DoubleLiteral(float(result.double)) + + @decimal.set_parse_action def _(result: ParseResults) -> Literal[Decimal]: return DecimalLiteral(Decimal(result.decimal)) diff --git a/tests/expressions/test_literals.py b/tests/expressions/test_literals.py index 04bfcbde14..943f912a2a 100644 --- a/tests/expressions/test_literals.py +++ b/tests/expressions/test_literals.py @@ -274,6 +274,21 @@ def test_double_to_float_outside_bound() -> None: assert below_min_lit == FloatBelowMin() +def test_double_to_integer_and_long_conversion() -> None: + for type_var in (IntegerType(), LongType()): + assert DoubleLiteral(1e3).to(type_var) == LongLiteral(1000) + assert DoubleLiteral(-2.0).to(type_var) == LongLiteral(-2) + with pytest.raises(ValueError, match="value has a fractional part"): + DoubleLiteral(1.5).to(type_var) + with pytest.raises(ValueError, match="value is not finite"): + DoubleLiteral(float("inf")).to(type_var) + # A float literal still does not convert to an integer type + with pytest.raises(TypeError): + FloatLiteral(1e3).to(type_var) + assert DoubleLiteral(1e10).to(IntegerType()) == IntAboveMax() + assert DoubleLiteral(-1e19).to(LongType()) == LongBelowMin() + + @pytest.mark.parametrize( "decimal_type, decimal_value", [(DecimalType(9, 1), "34.6"), (DecimalType(9, 2), "34.56"), (DecimalType(9, 4), "34.5600")] ) @@ -731,8 +746,6 @@ def test_invalid_long_conversions() -> None: "test_type", [ BooleanType(), - IntegerType(), - LongType(), DateType(), TimeType(), TimestampType(), diff --git a/tests/expressions/test_parser.py b/tests/expressions/test_parser.py index 74a2e82a04..7899e7d4fd 100644 --- a/tests/expressions/test_parser.py +++ b/tests/expressions/test_parser.py @@ -43,7 +43,10 @@ Reference, StartsWith, ) -from pyiceberg.expressions.literals import DecimalLiteral, LongLiteral, literal +from pyiceberg.expressions.literals import DecimalLiteral, DoubleLiteral, LongLiteral, literal +from pyiceberg.expressions.visitors import bind +from pyiceberg.schema import Schema +from pyiceberg.types import DecimalType, DoubleType, LongType, NestedField def test_always_true() -> None: @@ -158,6 +161,88 @@ def test_not_in_different_types() -> None: parser.parse("foo not in (5, 'a')") +def test_in_mixed_numbers() -> None: + for values in ("5, 6.5", "6.5, 5"): + result = parser.parse(f"foo in ({values})") + assert result == In("foo", {LongLiteral(5), DecimalLiteral(Decimal("6.5"))}), values + assert isinstance(result, In) + assert {type(value) for value in result.literals} == {LongLiteral, DecimalLiteral}, values + + result = parser.parse("foo not in (5, 6.5, 1e3)") + assert result == NotIn("foo", {LongLiteral(5), DecimalLiteral(Decimal("6.5")), DoubleLiteral(1000.0)}) + assert isinstance(result, NotIn) + assert {type(value) for value in result.literals} == {LongLiteral, DecimalLiteral, DoubleLiteral} + + +def test_scientific_notation() -> None: + # A number with an exponent is a double, as in ANSI SQL + for expression, expected in [ + ("foo > 1e-3", GreaterThan("foo", 0.001)), + ("1e-3 < foo", GreaterThan("foo", 0.001)), + ("foo < -1.5E3", LessThan("foo", -1500.0)), + ("foo = 2e2", EqualTo("foo", 200.0)), + ("foo = .5e1", EqualTo("foo", 5.0)), + ]: + result = parser.parse(expression) + assert result == expected, expression + assert isinstance(result.literal, DoubleLiteral), expression + + assert And(GreaterThanOrEqual("foo", 10.0), LessThanOrEqual("foo", 25.0)) == parser.parse("foo between 1e1 and 2.5e1") + + +def test_bind_numeric_literals() -> None: + schema = Schema( + NestedField(1, "dec", DecimalType(9, 2), required=False), + NestedField(2, "lng", LongType(), required=False), + NestedField(3, "dbl", DoubleType(), required=False), + ) + for expression, expected in [ + ("dec = 1e3", DecimalLiteral(Decimal("1000.00"))), + ("dec > 2.5e-1", DecimalLiteral(Decimal("0.25"))), + ("dec = 12.34", DecimalLiteral(Decimal("12.34"))), + ("lng = 1e3", LongLiteral(1000)), + ("lng = 7", LongLiteral(7)), + ("dbl > 1e-3", DoubleLiteral(0.001)), + ("dbl > 2.5", DoubleLiteral(2.5)), + ]: + bound = bind(schema, parser.parse(expression), case_sensitive=True) + assert bound.literal == expected, expression + assert type(bound.literal) is type(expected), expression + if isinstance(expected, DecimalLiteral): + assert bound.literal.value.as_tuple() == expected.value.as_tuple(), expression + + bound = bind(schema, parser.parse("lng in (1, 2e1, 3)"), case_sensitive=True) + assert bound.literals == {LongLiteral(1), LongLiteral(20), LongLiteral(3)} + with pytest.raises(ValueError, match="value has a fractional part"): + bind(schema, parser.parse("lng = 1.5e0"), case_sensitive=True) + + +def test_bind_out_of_range_numeric_literals() -> None: + schema = Schema( + NestedField(1, "dec", DecimalType(9, 2), required=False), + NestedField(2, "lng", LongType(), required=False), + ) + for expression, expected in [ + ("dec = 1e10", AlwaysFalse()), + ("dec = -1e30", AlwaysFalse()), + ("dec < 1e30", AlwaysTrue()), + ("dec > -1e30", AlwaysTrue()), + # 9999999.996 rounds up to 10000000.00, which is above the column maximum 9999999.99 + ("dec <= 9.999999996e6", AlwaysTrue()), + ("dec > 9.999999996e6", AlwaysFalse()), + ("dec in (1e30)", AlwaysFalse()), + ("dec not in (1e30)", AlwaysTrue()), + ("lng = 1e19", AlwaysFalse()), + ("lng < 1e19", AlwaysTrue()), + ]: + assert bind(schema, parser.parse(expression), case_sensitive=True) == expected, expression + + # A value outside the column range is left out of an IN list, so the other values still match + assert bind(schema, parser.parse("lng in (1e19, 7)"), case_sensitive=True) == bind( + schema, parser.parse("lng = 7"), case_sensitive=True + ) + + def test_simple_and() -> None: assert And(GreaterThanOrEqual("foo", 5), LessThan("foo", 10)) == parser.parse("5 <= foo and foo < 10")