samredai commented on a change in pull request #3450: URL: https://github.com/apache/iceberg/pull/3450#discussion_r772005917
########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" Review comment: Here's a suggestion for a more descriptive docstring. ``` """Transform base class for concrete transforms. A base class to transform values, check or types, and project predicates on partition values. This class is typically not called directly. Instead, use one of the child classes. Args: transform_string (str): name of the transform type repr_string (str): string representation of a transform instance to_human_str (callable, optional): A function that returns the human-readable string given a value. By default, the built-in `str` method is used. """ ``` ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" + + def __init__( + self, + transform_string: str, + repr_string: str, + to_human_str: Callable[[Any], str] = str, + ): + self._transform_string = transform_string + self._repr_string = repr_string + self._to_human_string = to_human_str + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + raise NotImplementedError() + + def can_transform(self, target: Type) -> bool: + return False + + def result_type(self, source: Type) -> Type: + return source + + def preserves_order(self) -> bool: + return False + + def satisfies_order_of(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + if value is None: + return "null" + return self._to_human_string(value) + + def dedup_name(self) -> str: + return self._transform_string + + +class Bucket(Transform): + _MAX_32_BITS_INT = 2147483647 + _INT_TRANSFORMABLE_TYPES = { + IntegerType, + DateType, + LongType, + TimeType, + TimestampType, + TimestamptzType, + } + _SAME_TRANSFORMABLE_TYPES = { + StringType, + BinaryType, + UUIDType, + FloatType, + DoubleType, + } + + def __init__(self, source_type: Type, num_buckets: int): + super().__init__( + f"bucket[{num_buckets}]", + f"transforms.bucket(source_type={repr(source_type)}, num_buckets={num_buckets})", + ) + self._type = source_type + self._num_buckets = num_buckets + + if isinstance(self._type, FixedType) or isinstance(self._type, DecimalType): + self._can_transform = lambda t: type(self._type) is type(t) + elif self._type in Bucket._SAME_TRANSFORMABLE_TYPES: + self._can_transform = lambda t: self._type == t + elif self._type in Bucket._INT_TRANSFORMABLE_TYPES: + self._can_transform = ( + lambda t: self._type in Bucket._INT_TRANSFORMABLE_TYPES + ) + else: + raise ValueError(f"Cannot bucket by type: {source_type}") + + if ( + isinstance(self._type, FixedType) + or self._type == StringType + or self._type == BinaryType + ): + self._hash_func = lambda v: mmh3.hash(v) + elif isinstance(self._type, DecimalType): + self._hash_func = lambda v: mmh3.hash(transform_util.decimal_to_bytes(v)) + elif self._type == FloatType or self._type == DoubleType: + # bucketing by Float/Double is not allowed by the spec, but they have hash implementation + self._hash_func = lambda v: mmh3.hash(struct.pack("d", v)) + elif self._type == UUIDType: + self._hash_func = lambda v: mmh3.hash( + struct.pack( + ">QQ", + (v.int >> 64) & 0xFFFFFFFFFFFFFFFF, + v.int & 0xFFFFFFFFFFFFFFFF, + ) + ) + else: + self._hash_func = lambda v: mmh3.hash(struct.pack("q", v)) + + @property + def num_buckets(self) -> int: + return self._num_buckets + + def apply(self, value) -> Optional[int]: + if value is None: + return None + + return (self._hash_func(value) & Bucket._MAX_32_BITS_INT) % self._num_buckets + + def can_transform(self, target: Type) -> bool: + return self._can_transform(target) + + def result_type(self, source: Type): + return IntegerType + + +class TimeTransform(Transform): + """Time class is for both Date transforms and Timestamp transforms.""" + + _TIME_SATISFIED_ORDER = dict(year=3, month=2, day=1, hour=0) + + def __init__(self, source_type: Type, name: str, apply_func: Callable[[int], int]): + super().__init__( + name, + f"transforms.{name}(source_type={repr(source_type)})", + getattr(transform_util, f"human_{name}"), + ) + self._type = source_type + self._name = name + self._apply = apply_func + self._result_type = DateType if self._name == "day" else IntegerType + + def apply(self, value: int) -> int: + return self._apply(value) + + def can_transform(self, target: Type) -> bool: + if self._type == DateType: + return target == DateType + else: # self._type is either TimestampType or TimestamptzType + return target == TimestampType or target == TimestamptzType + + def result_type(self, source_type: Type) -> Type: + return self._result_type + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + + if isinstance(other, TimeTransform): + return ( + TimeTransform._TIME_SATISFIED_ORDER[self._name] + <= TimeTransform._TIME_SATISFIED_ORDER[other._name] + ) + + return False + + def dedup_name(self) -> str: + return "time" + + +class Identity(Transform): + def __init__( + self, + source_type: Type, + human_str: Callable[[Any], str], + ): + super().__init__( + "identity", + f"transforms.identity(source_type={repr(source_type)})", + human_str, + ) + self._type = source_type + + def apply(self, value): + return value + + def can_transform(self, target: Type) -> bool: + return target.is_primitive + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + return other.preserves_order() + + +class Truncate(Transform): Review comment: Suggestion for a docstring: ``` """A transform for truncating a value to a specified width. Args: source_type (Type): An Iceberg Type of IntegerType, LongType, StringType, or BinaryType width (int): The truncate width Raises: ValueError: If a type is provided that is incompatible with a Truncate transform """ ``` ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,520 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import base64 +import math +import re +import struct +from datetime import datetime, timedelta +from decimal import Decimal + +import mmh3 # type: ignore +import pytz + +from .types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) + + +class Transform(object): + """ + Transform base class for concrete transforms. The default implementation is for VoidTransform. + """ + + _EPOCH = datetime.utcfromtimestamp(0) + + @staticmethod + def _human_day(day_ordinal): + time = Transform._EPOCH + timedelta(days=day_ordinal) + return "{0:0=4d}-{1:0=2d}-{2:0=2d}".format(time.year, time.month, time.day) + + @staticmethod + def _unscale_decimal(decimal_value: Decimal): + value_tuple = decimal_value.as_tuple() + return int( + ("-" if value_tuple.sign else "") + + "".join([str(d) for d in value_tuple.digits]) + ) + + def __init__(self, transform_string: str, repr_string: str): + self._transform_string = transform_string + self._repr_string = repr_string + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + return None + + def can_transform(self, target: Type) -> bool: + return True + + def get_result_type(self, source: Type) -> Type: + return source + + def preserve_order(self) -> bool: + return False + + def satisfy_order(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + return "null" + + def dedup_name(self) -> str: + return self.__str__() + + +class Bucket(Transform): + _MURMUR3 = mmh3 + _MAX_32_BITS_INT = 2147483647 + _FUNCTIONS_MAP = { # [0] is hash function and [1] is can_transform check function + DateType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in [IntegerType, DateType], + ), + IntegerType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in [IntegerType, DateType], + ), + TimeType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in {LongType, TimeType, TimestampType, TimestamptzType}, + ), + TimestampType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in {LongType, TimeType, TimestampType, TimestamptzType}, + ), + TimestamptzType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in {LongType, TimeType, TimestampType, TimestamptzType}, + ), + LongType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("q", v)), + lambda t: t in [LongType, TimeType, TimestampType, TimestamptzType], + ), + StringType: ( + lambda v: Bucket._MURMUR3.hash(v), + lambda t: t == StringType, + ), + BinaryType: ( + lambda v: Bucket._MURMUR3.hash(v), + lambda t: t == BinaryType or isinstance(t, FixedType), + ), + UUIDType: ( + lambda v: Bucket._MURMUR3.hash( + struct.pack( + ">QQ", + (v.int >> 64) & 0xFFFFFFFFFFFFFFFF, + v.int & 0xFFFFFFFFFFFFFFFF, + ) + ), + lambda t: t == UUIDType, + ), + # bucketing by Float/Double is not allowed by the spec, but they have hash implementation + FloatType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("d", v)), + lambda t: t == FloatType, + ), + DoubleType: ( + lambda v: Bucket._MURMUR3.hash(struct.pack("d", v)), + lambda t: t == DoubleType, + ), + } + + @staticmethod + def _decimal_to_bytes(value: Decimal): + unscaled_value = Transform._unscale_decimal(value) + number_of_bytes = int(math.ceil(unscaled_value.bit_length() / 8)) + return unscaled_value.to_bytes(length=number_of_bytes, byteorder="big") + + def __init__(self, transform_type: Type, num_buckets: int): + if ( + transform_type not in Bucket._FUNCTIONS_MAP + and not isinstance(transform_type, FixedType) + and not isinstance(transform_type, DecimalType) + ): + raise ValueError(f"Cannot bucket by type: {transform_type}") + + super().__init__( + f"bucket[{num_buckets}", + f"transforms.bucket(transform_type={repr(transform_type)}, num_buckets={num_buckets})", + ) + self._type = transform_type + self._num_buckets = num_buckets + + @property + def num_buckets(self) -> int: + return self._num_buckets + + def apply(self, value): + if value is None: + return None + + if isinstance(self._type, FixedType): + return ( + Bucket._MURMUR3.hash(value) & Bucket._MAX_32_BITS_INT + ) % self._num_buckets + elif isinstance(self._type, DecimalType): + return ( + Bucket._MURMUR3.hash(Bucket._decimal_to_bytes(value)) + & Bucket._MAX_32_BITS_INT + ) % self._num_buckets + + return ( + Bucket._FUNCTIONS_MAP[self._type][0](value) & Bucket._MAX_32_BITS_INT + ) % self._num_buckets + + def can_transform(self, target: Type) -> bool: + if isinstance(self._type, FixedType): + return target == BinaryType or isinstance(target, FixedType) + elif isinstance(self._type, DecimalType): + return isinstance(target, DecimalType) + + return Bucket._FUNCTIONS_MAP[self._type][1](target) + + def get_result_type(self, source: Type): + return IntegerType + + def to_human_string(self, value): + return str(value) + + +class Time(Transform): + """ + Time class is for both Date transforms and Timestamp transforms. + """ + + _TIME_ORDER = datetime(year=3, month=2, day=1, hour=0) + _VALID_TIME_GRANULARITY = { + DateType: {"year", "month", "day"}, + TimestampType: {"year", "month", "day", "hour"}, + TimestamptzType: {"year", "month", "day", "hour"}, + } + _DIFF_MAP = { + "year": lambda t1, t2: (t1.year - t2.year) + - ( + 1 + if t1.month < t2.month or (t1.month == t2.month and t1.day < t2.day) + else 0 + ), + "month": lambda t1, t2: (t1.year - t2.year) * 12 + + (t1.month - t2.month) + - (1 if t1.day < t2.day else 0), + "day": lambda t1, t2: (t1 - t2).days, + "hour": lambda t1, t2: int((t1 - t2).total_seconds() / 3600), + } + + def __init__(self, transform_type: Type, name: str): + if name not in Time._VALID_TIME_GRANULARITY.get(transform_type, {}): + raise ValueError(f"Cannot transform type: {transform_type} by {name}") + + super().__init__( + name, f"transforms.{name}(transform_type={repr(transform_type)})" + ) + self._type = transform_type + self._name = name + + def apply(self, value: int) -> int: Review comment: Is it always the case that we want to set the apply method during init of a transform? Should `apply_func` then be an argument in the base `Transform` class which can also contain this `apply` method that calls `self._apply(value)`? ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" + + def __init__( + self, + transform_string: str, + repr_string: str, + to_human_str: Callable[[Any], str] = str, + ): + self._transform_string = transform_string + self._repr_string = repr_string + self._to_human_string = to_human_str + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + raise NotImplementedError() + + def can_transform(self, target: Type) -> bool: + return False + + def result_type(self, source: Type) -> Type: + return source + + def preserves_order(self) -> bool: + return False + + def satisfies_order_of(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + if value is None: + return "null" + return self._to_human_string(value) + + def dedup_name(self) -> str: + return self._transform_string + + +class Bucket(Transform): + _MAX_32_BITS_INT = 2147483647 + _INT_TRANSFORMABLE_TYPES = { + IntegerType, + DateType, + LongType, + TimeType, + TimestampType, + TimestamptzType, + } + _SAME_TRANSFORMABLE_TYPES = { + StringType, + BinaryType, + UUIDType, + FloatType, + DoubleType, + } + + def __init__(self, source_type: Type, num_buckets: int): + super().__init__( + f"bucket[{num_buckets}]", + f"transforms.bucket(source_type={repr(source_type)}, num_buckets={num_buckets})", + ) + self._type = source_type + self._num_buckets = num_buckets + + if isinstance(self._type, FixedType) or isinstance(self._type, DecimalType): + self._can_transform = lambda t: type(self._type) is type(t) + elif self._type in Bucket._SAME_TRANSFORMABLE_TYPES: + self._can_transform = lambda t: self._type == t + elif self._type in Bucket._INT_TRANSFORMABLE_TYPES: + self._can_transform = ( + lambda t: self._type in Bucket._INT_TRANSFORMABLE_TYPES + ) + else: + raise ValueError(f"Cannot bucket by type: {source_type}") + + if ( + isinstance(self._type, FixedType) + or self._type == StringType + or self._type == BinaryType + ): + self._hash_func = lambda v: mmh3.hash(v) + elif isinstance(self._type, DecimalType): + self._hash_func = lambda v: mmh3.hash(transform_util.decimal_to_bytes(v)) + elif self._type == FloatType or self._type == DoubleType: + # bucketing by Float/Double is not allowed by the spec, but they have hash implementation + self._hash_func = lambda v: mmh3.hash(struct.pack("d", v)) + elif self._type == UUIDType: + self._hash_func = lambda v: mmh3.hash( + struct.pack( + ">QQ", + (v.int >> 64) & 0xFFFFFFFFFFFFFFFF, + v.int & 0xFFFFFFFFFFFFFFFF, + ) + ) + else: + self._hash_func = lambda v: mmh3.hash(struct.pack("q", v)) + + @property + def num_buckets(self) -> int: + return self._num_buckets + + def apply(self, value) -> Optional[int]: + if value is None: + return None + + return (self._hash_func(value) & Bucket._MAX_32_BITS_INT) % self._num_buckets + + def can_transform(self, target: Type) -> bool: + return self._can_transform(target) + + def result_type(self, source: Type): + return IntegerType + + +class TimeTransform(Transform): + """Time class is for both Date transforms and Timestamp transforms.""" + + _TIME_SATISFIED_ORDER = dict(year=3, month=2, day=1, hour=0) + + def __init__(self, source_type: Type, name: str, apply_func: Callable[[int], int]): + super().__init__( + name, + f"transforms.{name}(source_type={repr(source_type)})", + getattr(transform_util, f"human_{name}"), + ) + self._type = source_type + self._name = name + self._apply = apply_func + self._result_type = DateType if self._name == "day" else IntegerType + + def apply(self, value: int) -> int: + return self._apply(value) + + def can_transform(self, target: Type) -> bool: + if self._type == DateType: + return target == DateType + else: # self._type is either TimestampType or TimestamptzType + return target == TimestampType or target == TimestamptzType + + def result_type(self, source_type: Type) -> Type: + return self._result_type + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + + if isinstance(other, TimeTransform): + return ( + TimeTransform._TIME_SATISFIED_ORDER[self._name] + <= TimeTransform._TIME_SATISFIED_ORDER[other._name] + ) + + return False + + def dedup_name(self) -> str: + return "time" + + +class Identity(Transform): + def __init__( + self, + source_type: Type, + human_str: Callable[[Any], str], + ): + super().__init__( + "identity", + f"transforms.identity(source_type={repr(source_type)})", + human_str, + ) + self._type = source_type + + def apply(self, value): + return value + + def can_transform(self, target: Type) -> bool: + return target.is_primitive + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + return other.preserves_order() + + +class Truncate(Transform): + _VALID_TYPES = {IntegerType, LongType, StringType, BinaryType} + _TO_HUMAN_STR = {BinaryType: transform_util.base64encode} + + def __init__(self, source_type: Type, width: int): + if source_type not in Truncate._VALID_TYPES and not isinstance( + source_type, DecimalType + ): + raise ValueError(f"Cannot truncate type: {source_type}") + + super().__init__( + f"truncate[{width}]", + f"transforms.truncate(source_type={repr(source_type)}, width={width})", + Truncate._TO_HUMAN_STR.get(source_type, str), + ) + self._type = source_type + self._width = width + + if self._type == IntegerType or self._type == LongType: + self._apply = lambda v, w: v - v % w + elif self._type == StringType or self._type == BinaryType: + self._apply = lambda v, w: v[0 : min(w, len(v))] + else: # decimal case + self._apply = transform_util.truncate_decimal + + @property + def width(self): + return self._width + + def apply(self, value): + if value is None: + return None + return self._apply(value, self._width) + + def can_transform(self, target: Type) -> bool: + return self._type == target + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + elif ( + StringType == self._type + and isinstance(other, Truncate) + and StringType == other._type + ): + return self._width >= other._width + + return False + + +class UnknownTransform(Transform): Review comment: docstring suggestion: ``` """A transform that represents when an unknown transform is provided Args: source_type (Type): An Iceberg `Type` transform (str): A string name of a transform Raises: AttributeError: If the apply method is called. """ ``` ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" + + def __init__( + self, + transform_string: str, + repr_string: str, + to_human_str: Callable[[Any], str] = str, + ): + self._transform_string = transform_string + self._repr_string = repr_string + self._to_human_string = to_human_str + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + raise NotImplementedError() + + def can_transform(self, target: Type) -> bool: + return False + + def result_type(self, source: Type) -> Type: + return source + + def preserves_order(self) -> bool: + return False + + def satisfies_order_of(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + if value is None: + return "null" + return self._to_human_string(value) + + def dedup_name(self) -> str: + return self._transform_string + + +class Bucket(Transform): Review comment: docstring suggestion: ``` """Transforms a value into a bucket partition value Bucket partition transforms use a 32-bit hash of the source value. The 32-bit hash implementation is the 32-bit Murmur3 hash, x86 variant, seeded with 0. Transforms are parameterized by a number of buckets [1], N. The hash mod N must produce a positive value by first discarding the sign bit of the hash value. Args: source_type (Type): An Iceberg Type of IntegerType, LongType, DecimalType, DateType, TimeType, TimestampType, TimestamptzType, StringType, BinaryType, UUIDType, FloatType, or DoubleType. num_buckets (int): The number of buckets. Raises: ValueError: If a type is provided that is incompatible with a Bucket transform """ ``` ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" + + def __init__( + self, + transform_string: str, + repr_string: str, + to_human_str: Callable[[Any], str] = str, + ): + self._transform_string = transform_string + self._repr_string = repr_string + self._to_human_string = to_human_str + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + raise NotImplementedError() + + def can_transform(self, target: Type) -> bool: + return False + + def result_type(self, source: Type) -> Type: + return source + + def preserves_order(self) -> bool: + return False + + def satisfies_order_of(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + if value is None: + return "null" + return self._to_human_string(value) + + def dedup_name(self) -> str: + return self._transform_string + + +class Bucket(Transform): + _MAX_32_BITS_INT = 2147483647 + _INT_TRANSFORMABLE_TYPES = { + IntegerType, + DateType, + LongType, + TimeType, + TimestampType, + TimestamptzType, + } + _SAME_TRANSFORMABLE_TYPES = { + StringType, + BinaryType, + UUIDType, + FloatType, + DoubleType, + } + + def __init__(self, source_type: Type, num_buckets: int): + super().__init__( + f"bucket[{num_buckets}]", + f"transforms.bucket(source_type={repr(source_type)}, num_buckets={num_buckets})", + ) + self._type = source_type + self._num_buckets = num_buckets + + if isinstance(self._type, FixedType) or isinstance(self._type, DecimalType): + self._can_transform = lambda t: type(self._type) is type(t) + elif self._type in Bucket._SAME_TRANSFORMABLE_TYPES: + self._can_transform = lambda t: self._type == t + elif self._type in Bucket._INT_TRANSFORMABLE_TYPES: + self._can_transform = ( + lambda t: self._type in Bucket._INT_TRANSFORMABLE_TYPES + ) + else: + raise ValueError(f"Cannot bucket by type: {source_type}") + + if ( + isinstance(self._type, FixedType) + or self._type == StringType + or self._type == BinaryType + ): + self._hash_func = lambda v: mmh3.hash(v) + elif isinstance(self._type, DecimalType): + self._hash_func = lambda v: mmh3.hash(transform_util.decimal_to_bytes(v)) + elif self._type == FloatType or self._type == DoubleType: + # bucketing by Float/Double is not allowed by the spec, but they have hash implementation + self._hash_func = lambda v: mmh3.hash(struct.pack("d", v)) + elif self._type == UUIDType: + self._hash_func = lambda v: mmh3.hash( + struct.pack( + ">QQ", + (v.int >> 64) & 0xFFFFFFFFFFFFFFFF, + v.int & 0xFFFFFFFFFFFFFFFF, + ) + ) + else: + self._hash_func = lambda v: mmh3.hash(struct.pack("q", v)) + + @property + def num_buckets(self) -> int: + return self._num_buckets + + def apply(self, value) -> Optional[int]: + if value is None: + return None + + return (self._hash_func(value) & Bucket._MAX_32_BITS_INT) % self._num_buckets + + def can_transform(self, target: Type) -> bool: + return self._can_transform(target) + + def result_type(self, source: Type): + return IntegerType + + +class TimeTransform(Transform): + """Time class is for both Date transforms and Timestamp transforms.""" + + _TIME_SATISFIED_ORDER = dict(year=3, month=2, day=1, hour=0) + + def __init__(self, source_type: Type, name: str, apply_func: Callable[[int], int]): + super().__init__( + name, + f"transforms.{name}(source_type={repr(source_type)})", + getattr(transform_util, f"human_{name}"), + ) + self._type = source_type + self._name = name + self._apply = apply_func + self._result_type = DateType if self._name == "day" else IntegerType + + def apply(self, value: int) -> int: + return self._apply(value) + + def can_transform(self, target: Type) -> bool: + if self._type == DateType: + return target == DateType + else: # self._type is either TimestampType or TimestamptzType + return target == TimestampType or target == TimestamptzType + + def result_type(self, source_type: Type) -> Type: + return self._result_type + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + + if isinstance(other, TimeTransform): + return ( + TimeTransform._TIME_SATISFIED_ORDER[self._name] + <= TimeTransform._TIME_SATISFIED_ORDER[other._name] + ) + + return False + + def dedup_name(self) -> str: + return "time" + + +class Identity(Transform): + def __init__( + self, + source_type: Type, + human_str: Callable[[Any], str], + ): + super().__init__( + "identity", + f"transforms.identity(source_type={repr(source_type)})", + human_str, + ) + self._type = source_type + + def apply(self, value): + return value + + def can_transform(self, target: Type) -> bool: + return target.is_primitive + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + return other.preserves_order() + + +class Truncate(Transform): + _VALID_TYPES = {IntegerType, LongType, StringType, BinaryType} + _TO_HUMAN_STR = {BinaryType: transform_util.base64encode} + + def __init__(self, source_type: Type, width: int): + if source_type not in Truncate._VALID_TYPES and not isinstance( + source_type, DecimalType + ): + raise ValueError(f"Cannot truncate type: {source_type}") + + super().__init__( + f"truncate[{width}]", + f"transforms.truncate(source_type={repr(source_type)}, width={width})", + Truncate._TO_HUMAN_STR.get(source_type, str), + ) + self._type = source_type + self._width = width + + if self._type == IntegerType or self._type == LongType: + self._apply = lambda v, w: v - v % w + elif self._type == StringType or self._type == BinaryType: + self._apply = lambda v, w: v[0 : min(w, len(v))] + else: # decimal case + self._apply = transform_util.truncate_decimal + + @property + def width(self): + return self._width + + def apply(self, value): + if value is None: + return None + return self._apply(value, self._width) + + def can_transform(self, target: Type) -> bool: + return self._type == target + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + elif ( + StringType == self._type + and isinstance(other, Truncate) + and StringType == other._type + ): + return self._width >= other._width + + return False + + +class UnknownTransform(Transform): + def __init__(self, source_type: Type, transform: str): + super().__init__( + transform, + f"UnknownTransform(source_type={repr(source_type)}, transform={repr(transform)})", + ) + self._type = source_type + self._transform = transform + + def apply(self, value): + raise AttributeError(f"Cannot apply unsupported transform: {self.__str__()}") + + def can_transform(self, target: Type) -> bool: + return repr(self._type) == repr(target) + + def result_type(self, source: Type) -> Type: + return StringType + + +class VoidTransform(Transform): Review comment: docstring suggestion: ``` """A transform that always returns null""" ``` ########## File path: python/src/iceberg/transforms.py ########## @@ -0,0 +1,425 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import re +import struct +from typing import Any, Callable, Optional + +import mmh3 # type: ignore + +from iceberg.types import ( + BinaryType, + DateType, + DecimalType, + DoubleType, + FixedType, + FloatType, + IntegerType, + LongType, + StringType, + TimestampType, + TimestamptzType, + TimeType, + Type, + UUIDType, +) +from iceberg.utils import transform_util + + +class Transform: + """Transform base class for concrete transforms.""" + + def __init__( + self, + transform_string: str, + repr_string: str, + to_human_str: Callable[[Any], str] = str, + ): + self._transform_string = transform_string + self._repr_string = repr_string + self._to_human_string = to_human_str + + def __repr__(self): + return self._repr_string + + def __str__(self): + return self._transform_string + + def apply(self, value): + raise NotImplementedError() + + def can_transform(self, target: Type) -> bool: + return False + + def result_type(self, source: Type) -> Type: + return source + + def preserves_order(self) -> bool: + return False + + def satisfies_order_of(self, other) -> bool: + return self == other + + def to_human_string(self, value) -> str: + if value is None: + return "null" + return self._to_human_string(value) + + def dedup_name(self) -> str: + return self._transform_string + + +class Bucket(Transform): + _MAX_32_BITS_INT = 2147483647 + _INT_TRANSFORMABLE_TYPES = { + IntegerType, + DateType, + LongType, + TimeType, + TimestampType, + TimestamptzType, + } + _SAME_TRANSFORMABLE_TYPES = { + StringType, + BinaryType, + UUIDType, + FloatType, + DoubleType, + } + + def __init__(self, source_type: Type, num_buckets: int): + super().__init__( + f"bucket[{num_buckets}]", + f"transforms.bucket(source_type={repr(source_type)}, num_buckets={num_buckets})", + ) + self._type = source_type + self._num_buckets = num_buckets + + if isinstance(self._type, FixedType) or isinstance(self._type, DecimalType): + self._can_transform = lambda t: type(self._type) is type(t) + elif self._type in Bucket._SAME_TRANSFORMABLE_TYPES: + self._can_transform = lambda t: self._type == t + elif self._type in Bucket._INT_TRANSFORMABLE_TYPES: + self._can_transform = ( + lambda t: self._type in Bucket._INT_TRANSFORMABLE_TYPES + ) + else: + raise ValueError(f"Cannot bucket by type: {source_type}") + + if ( + isinstance(self._type, FixedType) + or self._type == StringType + or self._type == BinaryType + ): + self._hash_func = lambda v: mmh3.hash(v) + elif isinstance(self._type, DecimalType): + self._hash_func = lambda v: mmh3.hash(transform_util.decimal_to_bytes(v)) + elif self._type == FloatType or self._type == DoubleType: + # bucketing by Float/Double is not allowed by the spec, but they have hash implementation + self._hash_func = lambda v: mmh3.hash(struct.pack("d", v)) + elif self._type == UUIDType: + self._hash_func = lambda v: mmh3.hash( + struct.pack( + ">QQ", + (v.int >> 64) & 0xFFFFFFFFFFFFFFFF, + v.int & 0xFFFFFFFFFFFFFFFF, + ) + ) + else: + self._hash_func = lambda v: mmh3.hash(struct.pack("q", v)) + + @property + def num_buckets(self) -> int: + return self._num_buckets + + def apply(self, value) -> Optional[int]: + if value is None: + return None + + return (self._hash_func(value) & Bucket._MAX_32_BITS_INT) % self._num_buckets + + def can_transform(self, target: Type) -> bool: + return self._can_transform(target) + + def result_type(self, source: Type): + return IntegerType + + +class TimeTransform(Transform): + """Time class is for both Date transforms and Timestamp transforms.""" + + _TIME_SATISFIED_ORDER = dict(year=3, month=2, day=1, hour=0) + + def __init__(self, source_type: Type, name: str, apply_func: Callable[[int], int]): + super().__init__( + name, + f"transforms.{name}(source_type={repr(source_type)})", + getattr(transform_util, f"human_{name}"), + ) + self._type = source_type + self._name = name + self._apply = apply_func + self._result_type = DateType if self._name == "day" else IntegerType + + def apply(self, value: int) -> int: + return self._apply(value) + + def can_transform(self, target: Type) -> bool: + if self._type == DateType: + return target == DateType + else: # self._type is either TimestampType or TimestamptzType + return target == TimestampType or target == TimestamptzType + + def result_type(self, source_type: Type) -> Type: + return self._result_type + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + + if isinstance(other, TimeTransform): + return ( + TimeTransform._TIME_SATISFIED_ORDER[self._name] + <= TimeTransform._TIME_SATISFIED_ORDER[other._name] + ) + + return False + + def dedup_name(self) -> str: + return "time" + + +class Identity(Transform): + def __init__( + self, + source_type: Type, + human_str: Callable[[Any], str], + ): + super().__init__( + "identity", + f"transforms.identity(source_type={repr(source_type)})", + human_str, + ) + self._type = source_type + + def apply(self, value): + return value + + def can_transform(self, target: Type) -> bool: + return target.is_primitive + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + return other.preserves_order() + + +class Truncate(Transform): + _VALID_TYPES = {IntegerType, LongType, StringType, BinaryType} + _TO_HUMAN_STR = {BinaryType: transform_util.base64encode} + + def __init__(self, source_type: Type, width: int): + if source_type not in Truncate._VALID_TYPES and not isinstance( + source_type, DecimalType + ): + raise ValueError(f"Cannot truncate type: {source_type}") + + super().__init__( + f"truncate[{width}]", + f"transforms.truncate(source_type={repr(source_type)}, width={width})", + Truncate._TO_HUMAN_STR.get(source_type, str), + ) + self._type = source_type + self._width = width + + if self._type == IntegerType or self._type == LongType: + self._apply = lambda v, w: v - v % w + elif self._type == StringType or self._type == BinaryType: + self._apply = lambda v, w: v[0 : min(w, len(v))] + else: # decimal case + self._apply = transform_util.truncate_decimal + + @property + def width(self): + return self._width + + def apply(self, value): + if value is None: + return None + return self._apply(value, self._width) + + def can_transform(self, target: Type) -> bool: + return self._type == target + + def preserves_order(self) -> bool: + return True + + def satisfies_order_of(self, other: Transform) -> bool: + if self == other: + return True + elif ( + StringType == self._type + and isinstance(other, Truncate) + and StringType == other._type + ): + return self._width >= other._width + + return False + + +class UnknownTransform(Transform): + def __init__(self, source_type: Type, transform: str): + super().__init__( + transform, + f"UnknownTransform(source_type={repr(source_type)}, transform={repr(transform)})", + ) + self._type = source_type + self._transform = transform + + def apply(self, value): + raise AttributeError(f"Cannot apply unsupported transform: {self.__str__()}") + + def can_transform(self, target: Type) -> bool: + return repr(self._type) == repr(target) + + def result_type(self, source: Type) -> Type: + return StringType + + +class VoidTransform(Transform): + _instance = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(VoidTransform, cls).__new__(cls) + return cls._instance + + def __init__(self): + super().__init__("void", "transforms.always_null()", lambda v: "null") + + def apply(self, value): + return None + + def can_transform(self, target: Type) -> bool: + return True + + +_HAS_WIDTH = re.compile("(\\w+)\\[(\\d+)\\]") +_TIME_TRANSFORMS = { + DateType: { + "year": TimeTransform(DateType, "year", transform_util.years_for_days), + "month": TimeTransform(DateType, "month", transform_util.months_for_days), + "day": TimeTransform(DateType, "day", lambda d: d), + }, + TimestampType: { + "year": TimeTransform(TimestampType, "year", transform_util.years_for_ts), + "month": TimeTransform(TimestampType, "month", transform_util.months_for_ts), + "day": TimeTransform(TimestampType, "day", transform_util.days_for_ts), + "hour": TimeTransform(TimestampType, "hour", transform_util.hours_for_ts), + }, + TimestamptzType: { + "year": TimeTransform(TimestamptzType, "year", transform_util.years_for_ts), + "month": TimeTransform(TimestamptzType, "month", transform_util.months_for_ts), + "day": TimeTransform(TimestamptzType, "day", transform_util.days_for_ts), + "hour": TimeTransform(TimestamptzType, "hour", transform_util.hours_for_ts), + }, +} + +_SPECIAL_IDENTITY_TRANSFORMS = { + DateType: Identity(DateType, transform_util.human_day), + TimeType: Identity(TimeType, transform_util.human_time), + TimestampType: Identity(TimestampType, transform_util.human_timestamp), + TimestamptzType: Identity(TimestamptzType, transform_util.human_timestamptz), + BinaryType: Identity(BinaryType, transform_util.base64encode), +} + + +def from_string(source_type: Type, transform: str) -> Transform: Review comment: docstring: ``` """Get a transform instance given an Iceberg `Type` and transform name Args: source_type (Type): An Iceberg `Type` transform (str): A string name of a transform Returns: Transform: An instance of a child class of the `Transform` base class """ ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
