arminnajafi commented on code in PR #6646:
URL: https://github.com/apache/iceberg/pull/6646#discussion_r1103900051


##########
python/pyiceberg/catalog/dynamodb.py:
##########
@@ -0,0 +1,776 @@
+#  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,
+    Catalog,
+    Identifier,
+    Properties,
+    PropertiesUpdateSummary,
+)
+from pyiceberg.exceptions import (
+    ConditionalCheckFailedException,
+    GenericDynamoDbError,
+    ItemNotFound,
+    NamespaceAlreadyExistsError,
+    NamespaceNotEmptyError,
+    NoSuchIcebergTableError,
+    NoSuchNamespaceError,
+    NoSuchPropertyException,
+    NoSuchTableError,
+    TableAlreadyExistsError,
+    ValidationError,
+)
+from pyiceberg.io import load_file_io
+from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec
+from pyiceberg.schema import Schema
+from pyiceberg.serializers import FromInputFile
+from pyiceberg.table import Table
+from pyiceberg.table.metadata import new_table_metadata
+from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder
+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"
+
+DYNAMODB_TABLE_NAME = "dynamodb_table_name"
+DYNAMODB_TABLE_NAME_DEFAULT = "iceberg"
+
+PROPERTY_KEY_PREFIX = "p."
+
+ACTIVE = "ACTIVE"
+ITEM = "Item"
+
+
+class DynamoDbCatalog(Catalog):
+    def __init__(self, name: str, **properties: str):
+        super().__init__(name, **properties)
+        self.dynamodb = boto3.client(DYNAMODB_CLIENT)
+        self.dynamodb_table_name = self.properties.get(DYNAMODB_TABLE_NAME, 
DYNAMODB_TABLE_NAME_DEFAULT)
+        self._ensure_catalog_table_exists_or_create()
+
+    def _ensure_catalog_table_exists_or_create(self) -> None:
+        if self._dynamodb_table_exists():
+            return
+
+        try:
+            self.dynamodb.create_table(
+                TableName=self.dynamodb_table_name,
+                
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) -> bool:
+        try:
+            response = 
self.dynamodb.describe_table(TableName=self.dynamodb_table_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 
{self.dynamodb_table_name} is not {ACTIVE}")
+        else:
+            return True
+
+    def create_table(
+        self,
+        identifier: Union[str, Identifier],
+        schema: Schema,
+        location: Optional[str] = None,
+        partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
+        sort_order: SortOrder = UNSORTED_SORT_ORDER,
+        properties: Properties = EMPTY_DICT,
+    ) -> Table:
+        """
+        Create an Iceberg table
+
+        Args:
+            identifier: Table identifier.
+            schema: Table's schema.
+            location: Location for the table. Optional Argument.
+            partition_spec: PartitionSpec for the table.
+            sort_order: SortOrder for the table.
+            properties: Table properties that can be a string based dictionary.
+
+        Returns:
+            Table: the created table instance
+
+        Raises:
+            AlreadyExistsError: If a table with the name already exists
+            ValueError: If the identifier is invalid, or no path is given to 
store metadata
+
+        """
+        database_name, table_name = 
self.identifier_to_database_and_table(identifier)
+
+        location = self._resolve_table_location(location, database_name, 
table_name)
+        metadata_location = self._get_metadata_location(location=location)
+        metadata = new_table_metadata(
+            location=location, schema=schema, partition_spec=partition_spec, 
sort_order=sort_order, properties=properties
+        )
+        io = load_file_io(properties=self.properties, 
location=metadata_location)
+        self._write_metadata(metadata, io, metadata_location)
+
+        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
+
+        loaded_table = self.load_table(identifier=identifier)
+        return loaded_table
+
+    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=self.dynamodb_table_name,
+                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=self.dynamodb_table_name,
+                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,

Review Comment:
   I tried to do a function also a variable:
   ```
   ddb_put_and_delete_exceptions: Tuple[Exception, ...] = (
               self.dynamodb.exceptions.ResourceNotFoundException,
               
self.dynamodb.exceptions.ItemCollectionSizeLimitExceededException,
               self.dynamodb.exceptions.TransactionConflictException,
           )
   ```
   
   But mypy fails me:
   ```
   
mypy.....................................................................Failed
   - hook id: mypy
   - exit code: 1
   
   python/pyiceberg/catalog/dynamodb.py:358: error: Exception type must be 
derived from BaseException  [misc]
   ...
   ```
   
   I think it's not compatible somehow. I reverting this change. But please let 
me know if there is a good way to do this. 



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