samredai commented on a change in pull request #3450: URL: https://github.com/apache/iceberg/pull/3450#discussion_r772006512
########## 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 (as @rdblue described)? Should `apply_func` then be an argument in the base `Transform` class which can also contain this `apply` method that calls `self._apply(value)`? -- 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]
