2121from abc import ABC , abstractmethod
2222from datetime import datetime
2323from functools import singledispatch
24- from typing import TYPE_CHECKING , Annotated , Any , Dict , Generic , List , Literal , Optional , Set , Tuple , TypeVar , Union , cast
24+ from typing import TYPE_CHECKING , Annotated , Any , Dict , Generic , List , Literal , Optional , Tuple , TypeVar , Union , cast
2525
26- from pydantic import Field , field_validator , model_validator
26+ from pydantic import Field , field_validator , model_serializer , model_validator
2727
2828from pyiceberg .exceptions import CommitFailedException
2929from pyiceberg .partitioning import PARTITION_FIELD_ID_START , PartitionSpec
5252from pyiceberg .utils .properties import property_as_int
5353
5454if TYPE_CHECKING :
55+ from pydantic .functional_serializers import ModelWrapSerializerWithoutInfo
56+
5557 from pyiceberg .table import Transaction
5658
5759U = TypeVar ("U" )
@@ -727,6 +729,12 @@ class AssertRefSnapshotId(ValidatableTableRequirement):
727729 ref : str = Field (...)
728730 snapshot_id : Optional [int ] = Field (default = None , alias = "snapshot-id" )
729731
732+ @model_serializer (mode = "wrap" )
733+ def serialize_model (self , handler : ModelWrapSerializerWithoutInfo ) -> dict [str , Any ]:
734+ partial_result = handler (self )
735+ # Ensure "snapshot-id" is always present, even if value is None
736+ return {** partial_result , "snapshot-id" : self .snapshot_id }
737+
730738 def validate (self , base_metadata : Optional [TableMetadata ]) -> None :
731739 if base_metadata is None :
732740 raise CommitFailedException ("Requirement failed: current table metadata is missing" )
@@ -745,13 +753,6 @@ def validate(self, base_metadata: Optional[TableMetadata]) -> None:
745753 elif self .snapshot_id is not None :
746754 raise CommitFailedException (f"Requirement failed: branch or tag { self .ref } is missing, expected { self .snapshot_id } " )
747755
748- # override the override method, allowing None to serialize to `null` instead of being omitted.
749- def model_dump_json (
750- self , exclude_none : bool = False , exclude : Optional [Set [str ]] = None , by_alias : bool = True , ** kwargs : Any
751- ) -> str :
752- # `snapshot-id` is required in json response, even if null
753- return super ().model_dump_json (exclude_none = False )
754-
755756
756757class AssertLastAssignedFieldId (ValidatableTableRequirement ):
757758 """The table's last assigned column id must match the requirement's `last-assigned-field-id`."""
0 commit comments