You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "JonasJ-ap (via GitHub)" <gi...@apache.org> on 2023/01/27 19:58:20 UTC

[GitHub] [iceberg] JonasJ-ap commented on a diff in pull request #6646: Implement Support for DynamoDB Catalog

JonasJ-ap commented on code in PR #6646:
URL: https://github.com/apache/iceberg/pull/6646#discussion_r1088546035


##########
python/tests/catalog/__init__.py:
##########
@@ -0,0 +1,52 @@
+#  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 random

Review Comment:
   [doubt] I understand having a `_init_.py` can share some util methods across different test. However, according to #5919, it seems we should not have `_init_.py` in the test packages.
   
   May be we can put these into `conftest.py`?



##########
python/pyiceberg/catalog/dynamodb.py:
##########
@@ -0,0 +1,733 @@
+#  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 uuid
+from time import time
+from typing import (
+    Any,
+    Dict,
+    List,
+    Optional,
+    Set,
+    Union,
+)
+
+import boto3
+
+from pyiceberg.catalog import (
+    ICEBERG,
+    METADATA_LOCATION,
+    PREVIOUS_METADATA_LOCATION,
+    TABLE_TYPE,
+    Identifier,
+    Properties,
+    PropertiesUpdateSummary,
+)
+from pyiceberg.catalog.base_aws_catalog import BaseAwsCatalog
+from pyiceberg.exceptions import (
+    ConditionalCheckFailedException,
+    GenericDynamoDbError,
+    ItemNotFound,
+    NamespaceAlreadyExistsError,
+    NamespaceNotEmptyError,
+    NoSuchIcebergTableError,
+    NoSuchNamespaceError,
+    NoSuchPropertyException,
+    NoSuchTableError,
+    TableAlreadyExistsError,
+    ValidationError,
+)
+from pyiceberg.io import load_file_io
+from pyiceberg.serializers import FromInputFile
+from pyiceberg.table import Table
+from pyiceberg.typedef import EMPTY_DICT
+
+DYNAMODB_CLIENT = "dynamodb"
+
+DYNAMODB_COL_IDENTIFIER = "identifier"
+DYNAMODB_COL_NAMESPACE = "namespace"
+DYNAMODB_COL_VERSION = "v"
+DYNAMODB_COL_UPDATED_AT = "updated_at"
+DYNAMODB_COL_CREATED_AT = "created_at"
+DYNAMODB_NAMESPACE = "NAMESPACE"
+DYNAMODB_NAMESPACE_GSI = "namespace-identifier"
+DYNAMODB_PAY_PER_REQUEST = "PAY_PER_REQUEST"
+
+PROPERTY_KEY_PREFIX = "p."
+
+ACTIVE = "ACTIVE"
+ITEM = "Item"
+
+
+class DynamoDbCatalog(BaseAwsCatalog):
+    def __init__(self, name: str, **properties: str):
+        super().__init__(name, **properties)
+        self.dynamodb = boto3.client(DYNAMODB_CLIENT)
+        self._ensure_catalog_table_exists_or_create()
+
+    def _ensure_catalog_table_exists_or_create(self) -> None:
+        if self._dynamodb_table_exists(name=ICEBERG):
+            return
+
+        try:
+            self.dynamodb.create_table(
+                TableName=ICEBERG,
+                AttributeDefinitions=_get_create_catalog_attribute_definitions(),
+                KeySchema=_get_key_schema(),
+                GlobalSecondaryIndexes=_get_global_secondary_indexes(),
+                BillingMode=DYNAMODB_PAY_PER_REQUEST,
+            )
+        except (
+            self.dynamodb.exceptions.ResourceInUseException,
+            self.dynamodb.exceptions.LimitExceededException,
+            self.dynamodb.exceptions.InternalServerError,
+        ) as e:
+            raise GenericDynamoDbError(e.message) from e
+
+    def _dynamodb_table_exists(self, name: str) -> bool:
+        try:
+            response = self.dynamodb.describe_table(TableName=name)
+        except self.dynamodb.exceptions.ResourceNotFoundException:
+            return False
+        except self.dynamodb.exceptions.InternalServerError as e:
+            raise GenericDynamoDbError(e.message) from e
+
+        if response["Table"]["TableStatus"] != ACTIVE:
+            raise GenericDynamoDbError(f"DynamoDB table for catalog {name} is not {ACTIVE}")
+        else:
+            return True
+
+    def _create_table(
+        self, identifier: Union[str, Identifier], table_name: str, metadata_location: str, properties: Properties = EMPTY_DICT
+    ) -> None:
+
+        database_name, table_name = self.identifier_to_database_and_table(identifier)
+
+        self._ensure_namespace_exists(database_name=database_name)
+
+        try:
+            self._put_dynamo_item(
+                item=_get_create_table_item(
+                    database_name=database_name, table_name=table_name, properties=properties, metadata_location=metadata_location
+                ),
+                condition_expression=f"attribute_not_exists({DYNAMODB_COL_IDENTIFIER})",
+            )
+        except ConditionalCheckFailedException as e:
+            raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e
+
+    def load_table(self, identifier: Union[str, Identifier]) -> Table:
+        """
+        Loads the table's metadata and returns the table instance.
+
+        You can also use this method to check for table existence using 'try catalog.table() except TableNotFoundError'
+        Note: This method doesn't scan data stored in the table.
+
+        Args:
+            identifier: Table identifier.
+
+        Returns:
+            Table: the table instance with its metadata
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid
+        """
+        database_name, table_name = self.identifier_to_database_and_table(identifier, NoSuchTableError)
+        dynamo_table_item = self._get_iceberg_table_item(database_name=database_name, table_name=table_name)
+        return self._convert_dynamo_table_item_to_iceberg_table(dynamo_table_item=dynamo_table_item)
+
+    def drop_table(self, identifier: Union[str, Identifier]) -> None:
+        """Drop a table.
+
+        Args:
+            identifier: Table identifier.
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid
+        """
+        database_name, table_name = self.identifier_to_database_and_table(identifier, NoSuchTableError)
+        try:
+            self.dynamodb.delete_item(
+                TableName=ICEBERG,
+                Key={
+                    DYNAMODB_COL_IDENTIFIER: {
+                        "S": f"{database_name}.{table_name}",
+                    },
+                    DYNAMODB_COL_NAMESPACE: {
+                        "S": database_name,
+                    },
+                },
+                ConditionExpression=f"attribute_exists({DYNAMODB_COL_IDENTIFIER})",
+            )
+        except self.dynamodb.exceptions.ConditionalCheckFailedException as e:
+            raise NoSuchTableError(f"Table does not exist: {database_name}.{table_name}") from e
+        except (
+            self.dynamodb.exceptions.ProvisionedThroughputExceededException,
+            self.dynamodb.exceptions.ResourceNotFoundException,
+            self.dynamodb.exceptions.ItemCollectionSizeLimitExceededException,
+            self.dynamodb.exceptions.TransactionConflictException,
+            self.dynamodb.exceptions.RequestLimitExceeded,
+            self.dynamodb.exceptions.InternalServerError,
+        ) as e:
+            raise GenericDynamoDbError(e.message) from e
+
+    def rename_table(self, from_identifier: Union[str, Identifier], to_identifier: Union[str, Identifier]) -> Table:
+        """Rename a fully classified table name
+
+        This method can only rename Iceberg tables in AWS Glue
+
+        Args:
+            from_identifier: Existing table identifier.
+            to_identifier: New table identifier.
+
+        Returns:
+            Table: the updated table instance with its metadata
+
+        Raises:
+            ValueError: When from table identifier is invalid
+            NoSuchTableError: When a table with the name does not exist
+            NoSuchIcebergTableError: When from table is not a valid iceberg table
+            NoSuchPropertyException: When from table miss some required properties
+            NoSuchNamespaceError: When the destination namespace doesn't exist
+        """
+        from_database_name, from_table_name = self.identifier_to_database_and_table(from_identifier, NoSuchTableError)
+        to_database_name, to_table_name = self.identifier_to_database_and_table(to_identifier)
+
+        from_table_item = self._get_iceberg_table_item(database_name=from_database_name, table_name=from_table_name)
+
+        try:
+            # Verify that from_identifier is a valid iceberg table
+            self._convert_dynamo_table_item_to_iceberg_table(dynamo_table_item=from_table_item)
+        except NoSuchPropertyException as e:
+            raise NoSuchPropertyException(
+                f"Failed to rename table {from_database_name}.{from_table_name} since it is missing required properties"
+            ) from e
+        except NoSuchIcebergTableError as e:
+            raise NoSuchIcebergTableError(
+                f"Failed to rename table {from_database_name}.{from_table_name} since it is not a valid iceberg table"
+            ) from e
+
+        self._ensure_namespace_exists(database_name=from_database_name)
+        self._ensure_namespace_exists(database_name=to_database_name)
+
+        try:
+            self._put_dynamo_item(
+                item=_get_rename_table_item(
+                    from_dynamo_table_item=from_table_item, to_database_name=to_database_name, to_table_name=to_table_name
+                ),
+                condition_expression=f"attribute_not_exists({DYNAMODB_COL_IDENTIFIER})",
+            )
+        except ConditionalCheckFailedException as e:
+            raise TableAlreadyExistsError(f"Table {to_database_name}.{to_table_name} already exists") from e
+
+        try:
+            self.drop_table(from_identifier)
+        except (NoSuchTableError, GenericDynamoDbError) as e:
+            self.drop_table(to_identifier)
+            raise ValueError(
+                f"Failed to drop old table {from_database_name}.{from_table_name}, "
+                f"after renaming to {to_database_name}.{to_table_name}. Rolling back to use the old one."
+            ) from e
+
+        return self.load_table(to_identifier)
+
+    def create_namespace(self, namespace: Union[str, Identifier], properties: Properties = EMPTY_DICT) -> None:
+        """Create a namespace in the catalog.
+
+        Args:
+            namespace: Namespace identifier
+            properties: A string dictionary of properties for the given namespace
+
+        Raises:
+            ValueError: If the identifier is invalid
+            AlreadyExistsError: If a namespace with the given name already exists
+        """
+        database_name = self.identifier_to_database(namespace)
+
+        try:
+            self._put_dynamo_item(
+                item=_get_create_database_item(database_name=database_name, properties=properties),
+                condition_expression=f"attribute_not_exists({DYNAMODB_COL_NAMESPACE})",
+            )
+        except ConditionalCheckFailedException as e:
+            raise NamespaceAlreadyExistsError(f"Database {database_name} already exists") from e
+
+    def drop_namespace(self, namespace: Union[str, Identifier]) -> None:
+        """Drop a namespace.
+
+        A Glue namespace can only be dropped if it is empty
+
+        Args:
+            namespace: Namespace identifier
+
+        Raises:
+            NoSuchNamespaceError: If a namespace with the given name does not exist, or the identifier is invalid
+            NamespaceNotEmptyError: If the namespace is not empty
+        """
+        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
+        table_identifiers = self.list_tables(namespace=database_name)
+
+        if len(table_identifiers) > 0:
+            raise NamespaceNotEmptyError(f"Database {database_name} is not empty")
+
+        try:
+            self.dynamodb.delete_item(
+                TableName=ICEBERG,
+                Key={
+                    DYNAMODB_COL_IDENTIFIER: {
+                        "S": DYNAMODB_NAMESPACE,
+                    },
+                    DYNAMODB_COL_NAMESPACE: {
+                        "S": database_name,
+                    },
+                },
+                ConditionExpression=f"attribute_exists({DYNAMODB_COL_NAMESPACE})",
+            )
+        except self.dynamodb.exceptions.ConditionalCheckFailedException as e:
+            raise NoSuchNamespaceError(f"Database does not exist: {database_name}") from e
+        except (
+            self.dynamodb.exceptions.ProvisionedThroughputExceededException,
+            self.dynamodb.exceptions.ResourceNotFoundException,
+            self.dynamodb.exceptions.ItemCollectionSizeLimitExceededException,
+            self.dynamodb.exceptions.TransactionConflictException,
+            self.dynamodb.exceptions.RequestLimitExceeded,
+            self.dynamodb.exceptions.InternalServerError,
+        ) as e:
+            raise GenericDynamoDbError(e.message) from e
+
+    def list_tables(self, namespace: Union[str, Identifier]) -> List[Identifier]:
+        """List tables under the given namespace in the catalog (including non-Iceberg tables)
+
+        Args:
+            namespace (str | Identifier): Namespace identifier to search.
+
+        Returns:
+            List[Identifier]: list of table identifiers.
+        """
+
+        database_name = self.identifier_to_database(namespace, NoSuchNamespaceError)
+
+        paginator = self.dynamodb.get_paginator("query")
+
+        try:
+            page_iterator = paginator.paginate(
+                TableName=ICEBERG,
+                IndexName=DYNAMODB_NAMESPACE_GSI,
+                KeyConditionExpression=f"{DYNAMODB_COL_NAMESPACE} = :namespace ",
+                ExpressionAttributeValues={
+                    ":namespace": {
+                        "S": database_name,
+                    }
+                },
+            )
+        except (
+            self.dynamodb.exceptions.ProvisionedThroughputExceededException,
+            self.dynamodb.exceptions.ResourceNotFoundException,
+            self.dynamodb.exceptions.RequestLimitExceeded,
+            self.dynamodb.exceptions.InternalServerError,
+        ) as e:
+            raise GenericDynamoDbError(e.message) from e
+
+        table_identifiers = []
+        for page in page_iterator:
+            for item in page["Items"]:
+                _dict = _convert_dynamo_item_to_regular_dict(item)
+                identifier_col = _dict[DYNAMODB_COL_IDENTIFIER]
+                if identifier_col == DYNAMODB_NAMESPACE:
+                    continue
+
+                table_identifiers.append(self.identifier_to_tuple(identifier_col))
+
+        return table_identifiers
+
+    def list_namespaces(self, namespace: Union[str, Identifier] = ()) -> List[Identifier]:
+        """
+        List top-level namespaces from the catalog.
+        We do not support hierarchical namespace.
+
+        Returns:
+            List[Identifier]: a List of namespace identifiers
+        """
+
+        if namespace:
+            raise ValidationError("This API is not supported for hierarchical namespaces.")

Review Comment:
   [Doubt] Shall we just return an empty list here just like what [`hive.py`](https://github.com/apache/iceberg/blob/038091f6b65bf63d028af175dbbbc7285815d6be/python/pyiceberg/catalog/hive.py#L476-L485) do?  



##########
python/pyiceberg/catalog/dynamodb.py:
##########
@@ -0,0 +1,733 @@
+#  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 uuid
+from time import time
+from typing import (
+    Any,
+    Dict,
+    List,
+    Optional,
+    Set,
+    Union,
+)
+
+import boto3
+
+from pyiceberg.catalog import (
+    ICEBERG,
+    METADATA_LOCATION,
+    PREVIOUS_METADATA_LOCATION,
+    TABLE_TYPE,
+    Identifier,
+    Properties,
+    PropertiesUpdateSummary,
+)
+from pyiceberg.catalog.base_aws_catalog import BaseAwsCatalog
+from pyiceberg.exceptions import (
+    ConditionalCheckFailedException,
+    GenericDynamoDbError,
+    ItemNotFound,
+    NamespaceAlreadyExistsError,
+    NamespaceNotEmptyError,
+    NoSuchIcebergTableError,
+    NoSuchNamespaceError,
+    NoSuchPropertyException,
+    NoSuchTableError,
+    TableAlreadyExistsError,
+    ValidationError,
+)
+from pyiceberg.io import load_file_io
+from pyiceberg.serializers import FromInputFile
+from pyiceberg.table import Table
+from pyiceberg.typedef import EMPTY_DICT
+
+DYNAMODB_CLIENT = "dynamodb"
+
+DYNAMODB_COL_IDENTIFIER = "identifier"
+DYNAMODB_COL_NAMESPACE = "namespace"
+DYNAMODB_COL_VERSION = "v"
+DYNAMODB_COL_UPDATED_AT = "updated_at"
+DYNAMODB_COL_CREATED_AT = "created_at"
+DYNAMODB_NAMESPACE = "NAMESPACE"
+DYNAMODB_NAMESPACE_GSI = "namespace-identifier"
+DYNAMODB_PAY_PER_REQUEST = "PAY_PER_REQUEST"
+
+PROPERTY_KEY_PREFIX = "p."
+
+ACTIVE = "ACTIVE"
+ITEM = "Item"
+
+
+class DynamoDbCatalog(BaseAwsCatalog):
+    def __init__(self, name: str, **properties: str):
+        super().__init__(name, **properties)
+        self.dynamodb = boto3.client(DYNAMODB_CLIENT)
+        self._ensure_catalog_table_exists_or_create()
+
+    def _ensure_catalog_table_exists_or_create(self) -> None:
+        if self._dynamodb_table_exists(name=ICEBERG):
+            return
+
+        try:
+            self.dynamodb.create_table(
+                TableName=ICEBERG,
+                AttributeDefinitions=_get_create_catalog_attribute_definitions(),
+                KeySchema=_get_key_schema(),
+                GlobalSecondaryIndexes=_get_global_secondary_indexes(),
+                BillingMode=DYNAMODB_PAY_PER_REQUEST,
+            )
+        except (
+            self.dynamodb.exceptions.ResourceInUseException,
+            self.dynamodb.exceptions.LimitExceededException,
+            self.dynamodb.exceptions.InternalServerError,
+        ) as e:
+            raise GenericDynamoDbError(e.message) from e
+
+    def _dynamodb_table_exists(self, name: str) -> bool:
+        try:
+            response = self.dynamodb.describe_table(TableName=name)
+        except self.dynamodb.exceptions.ResourceNotFoundException:
+            return False
+        except self.dynamodb.exceptions.InternalServerError as e:
+            raise GenericDynamoDbError(e.message) from e
+
+        if response["Table"]["TableStatus"] != ACTIVE:
+            raise GenericDynamoDbError(f"DynamoDB table for catalog {name} is not {ACTIVE}")
+        else:
+            return True
+
+    def _create_table(
+        self, identifier: Union[str, Identifier], table_name: str, metadata_location: str, properties: Properties = EMPTY_DICT
+    ) -> None:
+
+        database_name, table_name = self.identifier_to_database_and_table(identifier)
+
+        self._ensure_namespace_exists(database_name=database_name)
+
+        try:
+            self._put_dynamo_item(
+                item=_get_create_table_item(
+                    database_name=database_name, table_name=table_name, properties=properties, metadata_location=metadata_location
+                ),
+                condition_expression=f"attribute_not_exists({DYNAMODB_COL_IDENTIFIER})",
+            )
+        except ConditionalCheckFailedException as e:
+            raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e
+
+    def load_table(self, identifier: Union[str, Identifier]) -> Table:
+        """
+        Loads the table's metadata and returns the table instance.
+
+        You can also use this method to check for table existence using 'try catalog.table() except TableNotFoundError'
+        Note: This method doesn't scan data stored in the table.
+
+        Args:
+            identifier: Table identifier.
+
+        Returns:
+            Table: the table instance with its metadata
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid
+        """
+        database_name, table_name = self.identifier_to_database_and_table(identifier, NoSuchTableError)
+        dynamo_table_item = self._get_iceberg_table_item(database_name=database_name, table_name=table_name)
+        return self._convert_dynamo_table_item_to_iceberg_table(dynamo_table_item=dynamo_table_item)
+
+    def drop_table(self, identifier: Union[str, Identifier]) -> None:
+        """Drop a table.
+
+        Args:
+            identifier: Table identifier.
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid
+        """
+        database_name, table_name = self.identifier_to_database_and_table(identifier, NoSuchTableError)
+        try:
+            self.dynamodb.delete_item(
+                TableName=ICEBERG,
+                Key={
+                    DYNAMODB_COL_IDENTIFIER: {
+                        "S": f"{database_name}.{table_name}",
+                    },
+                    DYNAMODB_COL_NAMESPACE: {
+                        "S": database_name,
+                    },
+                },
+                ConditionExpression=f"attribute_exists({DYNAMODB_COL_IDENTIFIER})",
+            )
+        except self.dynamodb.exceptions.ConditionalCheckFailedException as e:
+            raise NoSuchTableError(f"Table does not exist: {database_name}.{table_name}") from e
+        except (
+            self.dynamodb.exceptions.ProvisionedThroughputExceededException,
+            self.dynamodb.exceptions.ResourceNotFoundException,
+            self.dynamodb.exceptions.ItemCollectionSizeLimitExceededException,
+            self.dynamodb.exceptions.TransactionConflictException,
+            self.dynamodb.exceptions.RequestLimitExceeded,
+            self.dynamodb.exceptions.InternalServerError,

Review Comment:
   [Curiosity] I am curious about the reason behind this exception catch. I think these errors are dynamodb internal and not related to user input/output for `drop_table`. So what's the difference between re-throwing them as a `GenericDynamoDbError` and just not catching them at all?
   
   I am asking this because I simply ignore these exceptinos in the glueCatalog implementations. May be a good lesson for me to learn.



##########
python/pyiceberg/catalog/__init__.py:
##########
@@ -431,3 +440,114 @@ def namespace_from(identifier: Union[str, Identifier]) -> Identifier:
             Identifier: Namespace identifier
         """
         return Catalog.identifier_to_tuple(identifier)[:-1]
+
+    @staticmethod
+    def _check_for_overlap(removals: Optional[Set[str]], updates: Properties) -> None:
+        if updates and removals:
+            overlap = set(removals) & set(updates.keys())
+            if overlap:
+                raise ValueError(f"Updates and deletes have an overlap: {overlap}")
+
+    def _resolve_table_location(self, location: Optional[str], database_name: str, table_name: str) -> str:
+        if not location:
+            return self._get_default_warehouse_location(database_name, table_name)
+        return location
+
+    def _get_default_warehouse_location(self, database_name: str, table_name: str) -> str:
+        database_properties = self.load_namespace_properties(database_name)
+        if database_location := database_properties.get(LOCATION):
+            database_location = database_location.rstrip("/")
+            return f"{database_location}/{table_name}"
+
+        if warehouse_path := self.properties.get(WAREHOUSE_LOCATION):
+            warehouse_path = warehouse_path.rstrip("/")
+            return f"{warehouse_path}/{database_name}.db/{table_name}"
+
+        raise ValueError("No default path is set, please specify a location when creating a table")
+
+    @staticmethod
+    def identifier_to_database(
+        identifier: Union[str, Identifier], err: Union[Type[ValueError], Type[NoSuchNamespaceError]] = ValueError
+    ) -> str:
+        tuple_identifier = Catalog.identifier_to_tuple(identifier)
+        if len(tuple_identifier) != 1:
+            raise err(f"Invalid database, hierarchical namespaces are not supported: {identifier}")
+
+        return tuple_identifier[0]
+
+    @staticmethod
+    def identifier_to_database_and_table(
+        identifier: Union[str, Identifier],
+        err: Union[Type[ValueError], Type[NoSuchTableError], Type[NoSuchNamespaceError]] = ValueError,
+    ) -> Tuple[str, str]:
+        tuple_identifier = Catalog.identifier_to_tuple(identifier)
+        if len(tuple_identifier) != 2:
+            raise err(f"Invalid path, hierarchical namespaces are not supported: {identifier}")
+
+        return tuple_identifier[0], tuple_identifier[1]
+
+    def purge_table(self, identifier: Union[str, Identifier]) -> None:
+        """Drop a table and purge all data and metadata files.
+
+        Note: This method only logs warning rather than raise exception when encountering file deletion failure
+
+        Args:
+            identifier (str | Identifier): Table identifier.
+
+        Raises:
+            NoSuchTableError: If a table with the name does not exist, or the identifier is invalid
+        """
+        table = self.load_table(identifier)
+        self.drop_table(identifier)
+        io = load_file_io(self.properties, table.metadata_location)
+        metadata = table.metadata
+        manifest_lists_to_delete = set()
+        manifests_to_delete = []
+        for snapshot in metadata.snapshots:
+            manifests_to_delete += snapshot.manifests(io)
+            if snapshot.manifest_list is not None:
+                manifest_lists_to_delete.add(snapshot.manifest_list)
+
+        manifest_paths_to_delete = {manifest.manifest_path for manifest in manifests_to_delete}
+        prev_metadata_files = {log.metadata_file for log in metadata.metadata_log}
+
+        delete_data_files(io, manifests_to_delete)
+        delete_files(io, manifest_paths_to_delete, MANIFEST)
+        delete_files(io, manifest_lists_to_delete, MANIFEST_LIST)
+        delete_files(io, prev_metadata_files, PREVIOUS_METADATA)
+        delete_files(io, {table.metadata_location}, METADATA)
+
+    @staticmethod
+    def _write_metadata(metadata: TableMetadata, io: FileIO, metadata_path: str) -> None:
+        ToOutputFile.table_metadata(metadata, io.new_output(metadata_path))
+
+    @staticmethod
+    def _get_metadata_location(location: str) -> str:
+        return f"{location}/metadata/00000-{uuid.uuid4()}.metadata.json"
+
+    def _get_updated_props_and_update_summary(

Review Comment:
   [Doubt] May be this method can also be utilized by `update_namespace_properties` in `hive.py`?



-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org