Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions pyiceberg/expressions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
59 changes: 54 additions & 5 deletions pyiceberg/expressions/literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]):
Expand Down Expand Up @@ -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]):
Expand All @@ -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]):
Expand Down
13 changes: 11 additions & 2 deletions pyiceberg/expressions/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
ParserElement,
ParseResults,
QuotedString,
Regex,
Suppress,
Word,
alphanums,
Expand Down Expand Up @@ -76,6 +77,7 @@
from pyiceberg.expressions.literals import (
BooleanLiteral,
DecimalLiteral,
DoubleLiteral,
Literal,
LongLiteral,
StringLiteral,
Expand Down Expand Up @@ -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")
Expand All @@ -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))
Expand Down
17 changes: 15 additions & 2 deletions tests/expressions/test_literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
)
Expand Down Expand Up @@ -731,8 +746,6 @@ def test_invalid_long_conversions() -> None:
"test_type",
[
BooleanType(),
IntegerType(),
LongType(),
DateType(),
TimeType(),
TimestampType(),
Expand Down
87 changes: 86 additions & 1 deletion tests/expressions/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dec <= 5e-3 binds to dec <= 0.01 (and dec = 1e-3 to dec = 0.00) because DoubleLiteral.to(DecimalType) rounds half-up to the column scale, so a 0.01 row matches a 0.005 bound. Should exponent forms on a decimal column fail on a scale mismatch like DecimalLiteral does, and can this case get a test?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jackylee-ch, good catch. DoubleLiteral.to(DecimalType) rounds half-up to the column scale, like Java's DoubleLiteral.to(DECIMAL), so the expression API already binds LessThanOrEqual("dec", 0.005) as dec <= 0.01; this PR makes that reachable from string filters. I'd suggest raising Could not convert 0.005 into a decimal(10, 2) when the value does not fit the column scale exactly, so dec <= 5e-3 fails like dec <= 0.005 while dec <= 5e-1 still binds as 0.50. That also changes the expression API for Python floats on decimal columns and differs from Java's rounding, so I'd like to confirm that's acceptable before changing it. I'll add a test either way.

("dec = 12.34", DecimalLiteral(Decimal("12.34"))),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add cases for values outside the column range, such as dec = 1e10, dec < 1e30, dec > -1e30 and lng = 1e19, asserting that they bind to AlwaysFalse() or AlwaysTrue()?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added test_bind_out_of_range_numeric_literals in tests/expressions/test_parser.py, with dec = 1e10, dec < 1e30, dec > -1e30, lng = 1e19, the 9999999.996 rounding case and the IN cases. dec = 1e10 binds to 10000000000.00 on base, so the test fails there.

("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")

Expand Down