You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "Fokko (via GitHub)" <gi...@apache.org> on 2023/02/06 22:53:48 UTC

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

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


##########
python/mkdocs/docs/configuration.md:
##########
@@ -85,3 +85,16 @@ catalog:
   default:
     type: glue
 ```
+
+## DynamoDB Catalog
+
+If you want to use AWS DynamoDB as the catalog, you can use the last two ways to configure the pyiceberg and refer
+[How to configure AWS credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+to set your AWS account credentials locally.
+
+```yaml
+catalog:
+  default:
+    type: dynamodb
+    dynamodb_table_name: iceberg

Review Comment:
   For the rest of the configuration we tend to use dashes instead of underscores:
   ```suggestion
       table-name: iceberg
   ```
   
   Also, this makes it in line with Java: https://iceberg.apache.org/docs/latest/aws/#dynamodb-catalog



##########
python/pyiceberg/catalog/__init__.py:
##########
@@ -93,17 +101,28 @@ def load_glue(name: str, conf: Properties) -> Catalog:
         raise NotInstalledError("AWS glue support not installed: pip install 'pyiceberg[glue]'") from exc
 
 
+def load_dynamodb(name: str, conf: Properties) -> Catalog:
+    try:
+        from pyiceberg.catalog.dynamodb import DynamoDbCatalog
+
+        return DynamoDbCatalog(name, **conf)
+    except ImportError as exc:
+        raise NotInstalledError("AWS DynamoDB support not installed: pip install 'pyiceberg[dynamodb]'") from exc
+
+
 AVAILABLE_CATALOGS: dict[CatalogType, Callable[[str, Properties], Catalog]] = {
     CatalogType.REST: load_rest,
     CatalogType.HIVE: load_hive,
     CatalogType.GLUE: load_glue,
+    CatalogType.DYNAMODB: load_dynamodb,
 }
 
 
 def infer_catalog_type(name: str, catalog_properties: RecursiveDict) -> Optional[CatalogType]:
     """Tries to infer the type based on the dict
 
     Args:
+        name:

Review Comment:
   ```suggestion
           name: Name of the catalog
   ```



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

Review Comment:
   Nit: Should we return this directly?



##########
python/pyproject.toml:
##########
@@ -103,6 +103,7 @@ hive = ["thrift"]
 s3fs = ["s3fs"]
 glue = ["boto3"]
 adlfs = ["adlfs"]
+dynamodb = ["boto3"]

Review Comment:
   I think we have to fix the exception for hierarchical namespaces, so it falls over to listing the nyc namespace:
   ```
   ➜  python git:(support-ddb-catalog) ✗ pyiceberg --catalog dynamo list  
   nyc
   ➜  python git:(support-ddb-catalog) ✗ pyiceberg --catalog dynamo list nyc
   This API is not supported for hierarchical namespaces.
   ➜  python git:(support-ddb-catalog) ✗ pyiceberg --catalog dynamo describe nyc.taxis
   Table format version  1                                                                                                                                      
   Metadata location     s3://emr-spark-and-iceberg/mywarehouse/nyc.db/taxis/metadata/00002-8b2a348f-e940-4d8d-a6fe-8786bd67b353.metadata.json                  
   Table UUID            2b066a47-3d03-47d6-90b0-9d3099df2fab                                                                                                   
   Last Updated          1639172467515   
   ```



##########
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:
   I agree that it is best to avoid throwing implementation-specific exceptions.



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