rdblue commented on a change in pull request #3450:
URL: https://github.com/apache/iceberg/pull/3450#discussion_r783357012



##########
File path: python/src/iceberg/transforms.py
##########
@@ -0,0 +1,471 @@
+# 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.
+
+    A base class to transform values and project predicates on partition 
values.
+    This class is not used directly. Instead, use one of module method to 
create 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.
+    """
+
+    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):
+    """Transforms a value into a bucket partition value
+
+    Transforms are parameterized by a number of buckets. Bucket partition 
transforms use a 32-bit
+    hash of the source value to produce a positive value by mod the bucket 
number.
+
+    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
+    """
+
+    _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):

Review comment:
       When referring to both Date and Timestamp, it is usually better to use 
"DateTime" so it is clear that you're not talking about a specific type (date, 
time or timestamp).
   
   However, this may be moot because I recommend the same thing I said for the 
bucket transform. Using lambdas doesn't seem to have value to me. I would 
probably decompose this into more specific classes.




-- 
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]

Reply via email to