Skip to content

Fix UUID support #2007

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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/avro/writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
List,
Optional,
Tuple,
Union,
)
from uuid import UUID

Expand Down Expand Up @@ -121,8 +122,11 @@ def write(self, encoder: BinaryEncoder, val: Any) -> None:

@dataclass(frozen=True)
class UUIDWriter(Writer):
def write(self, encoder: BinaryEncoder, val: UUID) -> None:
encoder.write(val.bytes)
def write(self, encoder: BinaryEncoder, val: Union[UUID, bytes]) -> None:
if isinstance(val, UUID):
encoder.write(val.bytes)
else:
encoder.write(val)


@dataclass(frozen=True)
Expand Down
4 changes: 3 additions & 1 deletion pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ def visit_string(self, _: StringType) -> pa.DataType:
return pa.large_string()

def visit_uuid(self, _: UUIDType) -> pa.DataType:
return pa.binary(16)
return pa.uuid()

def visit_unknown(self, _: UnknownType) -> pa.DataType:
return pa.null()
Expand Down Expand Up @@ -1252,6 +1252,8 @@ def primitive(self, primitive: pa.DataType) -> PrimitiveType:
return FixedType(primitive.byte_width)
elif pa.types.is_null(primitive):
return UnknownType()
elif isinstance(primitive, pa.UuidType):
return UUIDType()

raise TypeError(f"Unsupported type: {primitive}")

Expand Down
13 changes: 11 additions & 2 deletions pyiceberg/partitioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,8 +467,17 @@ def _(type: IcebergType, value: Optional[time]) -> Optional[int]:


@_to_partition_representation.register(UUIDType)
def _(type: IcebergType, value: Optional[uuid.UUID]) -> Optional[str]:
return str(value) if value is not None else None
def _(type: IcebergType, value: Optional[Union[uuid.UUID, int, bytes]]) -> Optional[Union[bytes, int]]:
if value is None:
return None
elif isinstance(value, bytes):
return value # IdentityTransform
elif isinstance(value, uuid.UUID):
return value.bytes # IdentityTransform
elif isinstance(value, int):
return value # BucketTransform
else:
raise ValueError(f"Type not recognized: {value}")


@_to_partition_representation.register(PrimitiveType)
Expand Down
51 changes: 50 additions & 1 deletion tests/integration/test_writes/test_writes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os
import random
import time
import uuid
from datetime import date, datetime, timedelta
from decimal import Decimal
from pathlib import Path
Expand Down Expand Up @@ -48,7 +49,7 @@
from pyiceberg.schema import Schema
from pyiceberg.table import TableProperties
from pyiceberg.table.sorting import SortDirection, SortField, SortOrder
from pyiceberg.transforms import DayTransform, HourTransform, IdentityTransform
from pyiceberg.transforms import DayTransform, HourTransform, IdentityTransform, BucketTransform, Transform
from pyiceberg.types import (
DateType,
DecimalType,
Expand All @@ -58,6 +59,7 @@
LongType,
NestedField,
StringType,
UUIDType,
)
from utils import _create_table

Expand Down Expand Up @@ -1841,3 +1843,50 @@ def test_read_write_decimals(session_catalog: Catalog) -> None:
tbl.append(arrow_table)

assert tbl.scan().to_arrow() == arrow_table


@pytest.mark.integration
@pytest.mark.parametrize("transform", [IdentityTransform(), BucketTransform(32)])
def test_uuid_partitioning(session_catalog: Catalog, spark: SparkSession, transform: Transform) -> None:
identifier = f"default.test_uuid_partitioning_{str(transform).replace('[32]', '')}"

schema = Schema(NestedField(field_id=1, name="uuid", field_type=UUIDType(), required=True))

try:
session_catalog.drop_table(identifier=identifier)
except NoSuchTableError:
pass

partition_spec = PartitionSpec(
PartitionField(source_id=1, field_id=1000, transform=transform, name="uuid_identity")
)

import pyarrow as pa

arr_table = pa.Table.from_pydict(
{
"uuid": [
uuid.UUID("00000000-0000-0000-0000-000000000000").bytes,
uuid.UUID("11111111-1111-1111-1111-111111111111").bytes,
],
},
schema=pa.schema(
[
# Uuid not yet supported, so we have to stick with `binary(16)`
# https://github.com/apache/arrow/issues/46468
pa.field("uuid", pa.binary(16), nullable=False),
]
),
)

tbl = session_catalog.create_table(
identifier=identifier,
schema=schema,
partition_spec=partition_spec,
)

tbl.append(arr_table)

lhs = [r[0] for r in spark.table(identifier).collect()]
rhs = [str(u.as_py()) for u in tbl.scan().to_arrow()["uuid"].combine_chunks()]
assert lhs == rhs
Loading