Fokko commented on code in PR #6034: URL: https://github.com/apache/iceberg/pull/6034#discussion_r1009151430
########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): Review Comment: ```suggestion def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str) -> None: ``` ########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): + ToOutputFile.table_metadata(metadata, io.new_output(metadate_path)) + + +def _delete_files(io: FileIO, files_to_delete: Set[str], file_type: str) -> None: + for file in files_to_delete: + try: + io.delete(file) + except OSError as e: + raise OSError(f"Failed to delete {file_type} file {file} ") from e + + +def _delete_data_files(io: FileIO, manifests_to_delete: List[ManifestFile]) -> None: + deleted_files: Dict[str, bool] = {} + for manifest_file in manifests_to_delete: + for entry in manifest_file.fetch_manifest_entry(io): + path = entry.data_file.file_path + if not deleted_files.get(path, False): + try: + io.delete(path) + except OSError as e: + raise OSError(f"Failed to delete data file {path}") from e + deleted_files[path] = True + + +class GlueCatalog(Catalog): + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + self.glue = boto3.client("glue") + + def _convert_glue_to_iceberg(self, glue_table: Dict[str, Any]) -> Table: + properties: Properties = glue_table.get(PROP_GLUE_TABLE_PARAMETERS, {}) + + if TABLE_TYPE not in properties: + raise NoSuchPropertyException( + f"Property {TABLE_TYPE} missing, could not determine type: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + glue_table_type = properties[TABLE_TYPE] + + if glue_table_type.lower() != ICEBERG: + raise NoSuchIcebergTableError( + f"Property table_type is {glue_table_type}, expected {ICEBERG}: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + + if METADATA_LOCATION not in properties: + raise NoSuchPropertyException( + f"Table property {METADATA_LOCATION} is missing, cannot find metadata for: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + metadata_location = properties[METADATA_LOCATION] + + io = load_file_io(properties=self.properties, location=metadata_location) + file = io.new_input(metadata_location) + metadata = FromInputFile.table_metadata(file) + return Table( + identifier=(glue_table[PROP_GLUE_TABLE_DATABASE_NAME], glue_table[PROP_GLUE_TABLE_NAME]), + metadata=metadata, + metadata_location=metadata_location, + ) + + def _default_warehouse_location(self, database_name: str, table_name: str): + try: + response = self.glue.get_database(Name=database_name) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchNamespaceError(f"The database: {database_name} does not exist") from e + + if database_location := response.get(PROP_GLUE_DATABASE, {}).get(PROP_GLUE_DATABASE_LOCATION): + return f"{database_location}/{table_name}" + + if warehouse_path := self.properties.get(WAREHOUSE): + return f"{warehouse_path}/{database_name}.db/{table_name}" + + raise ValueError("No default path is set, please specify a location when creating a table") + + def _resolve_table_location(self, location: Optional[str], database_name: str, table_name: str) -> str: + if not location: + return self._default_warehouse_location(database_name, table_name) + return location + + def _create_glue_table(self, identifier: Union[str, Identifier], table_input: Dict[str, Any]) -> None: + database_name, table_name = self.identifier_to_tuple(identifier) + try: + self.glue.create_table(DatabaseName=database_name, TableInput=table_input) + except self.glue.exceptions.AlreadyExistsException as e: + raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchNamespaceError(f"Database {database_name} not found") from e + + 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 in Glue catalog + 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 + """ + database_name, table_name = self.identifier_to_tuple(identifier) + + location = self._resolve_table_location(location, database_name, table_name) + metadata_location = f"{location}/metadata/00000-{uuid.uuid4()}.metadata.json" + 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) + _write_metadata(metadata, io, metadata_location) + + self._create_glue_table( + identifier=identifier, table_input=_construct_table_input(table_name, metadata_location, properties) + ) + try: + loaded_table = self.load_table(identifier=(database_name, table_name)) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchTableError(f"Table {database_name}.{table_name} fail to be created") from e Review Comment: I think this would throw if the database doesn't exist, right? Let's make that explicit in the error message. ```suggestion raise NoSuchTableError(f"Table {database_name}.{table_name} fail to be created") from e ``` ########## python/pyproject.toml: ########## @@ -86,6 +88,8 @@ pyarrow = ["pyarrow"] snappy = ["python-snappy"] hive = ["thrift"] s3fs = ["s3fs"] +boto3 = ["boto3"] +moto = ["moto"] Review Comment: I think we should move `moto` to the dev dependencies ########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): + ToOutputFile.table_metadata(metadata, io.new_output(metadate_path)) + + +def _delete_files(io: FileIO, files_to_delete: Set[str], file_type: str) -> None: + for file in files_to_delete: + try: + io.delete(file) + except OSError as e: + raise OSError(f"Failed to delete {file_type} file {file} ") from e + + +def _delete_data_files(io: FileIO, manifests_to_delete: List[ManifestFile]) -> None: + deleted_files: Dict[str, bool] = {} + for manifest_file in manifests_to_delete: + for entry in manifest_file.fetch_manifest_entry(io): + path = entry.data_file.file_path + if not deleted_files.get(path, False): + try: + io.delete(path) + except OSError as e: + raise OSError(f"Failed to delete data file {path}") from e + deleted_files[path] = True + + +class GlueCatalog(Catalog): + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + self.glue = boto3.client("glue") + + def _convert_glue_to_iceberg(self, glue_table: Dict[str, Any]) -> Table: + properties: Properties = glue_table.get(PROP_GLUE_TABLE_PARAMETERS, {}) + + if TABLE_TYPE not in properties: + raise NoSuchPropertyException( + f"Property {TABLE_TYPE} missing, could not determine type: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + glue_table_type = properties[TABLE_TYPE] + + if glue_table_type.lower() != ICEBERG: + raise NoSuchIcebergTableError( Review Comment: In Hive we throw a `NoSuchTableError`: https://github.com/apache/iceberg/blob/master/python/pyiceberg/catalog/hive.py#L249 Can we do the same here? ########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): + ToOutputFile.table_metadata(metadata, io.new_output(metadate_path)) + + +def _delete_files(io: FileIO, files_to_delete: Set[str], file_type: str) -> None: + for file in files_to_delete: + try: + io.delete(file) + except OSError as e: + raise OSError(f"Failed to delete {file_type} file {file} ") from e + + +def _delete_data_files(io: FileIO, manifests_to_delete: List[ManifestFile]) -> None: + deleted_files: Dict[str, bool] = {} + for manifest_file in manifests_to_delete: + for entry in manifest_file.fetch_manifest_entry(io): + path = entry.data_file.file_path + if not deleted_files.get(path, False): + try: + io.delete(path) + except OSError as e: + raise OSError(f"Failed to delete data file {path}") from e + deleted_files[path] = True + + +class GlueCatalog(Catalog): + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + self.glue = boto3.client("glue") + + def _convert_glue_to_iceberg(self, glue_table: Dict[str, Any]) -> Table: + properties: Properties = glue_table.get(PROP_GLUE_TABLE_PARAMETERS, {}) + + if TABLE_TYPE not in properties: + raise NoSuchPropertyException( + f"Property {TABLE_TYPE} missing, could not determine type: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + glue_table_type = properties[TABLE_TYPE] + + if glue_table_type.lower() != ICEBERG: + raise NoSuchIcebergTableError( + f"Property table_type is {glue_table_type}, expected {ICEBERG}: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + + if METADATA_LOCATION not in properties: + raise NoSuchPropertyException( + f"Table property {METADATA_LOCATION} is missing, cannot find metadata for: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + metadata_location = properties[METADATA_LOCATION] + + io = load_file_io(properties=self.properties, location=metadata_location) + file = io.new_input(metadata_location) + metadata = FromInputFile.table_metadata(file) + return Table( + identifier=(glue_table[PROP_GLUE_TABLE_DATABASE_NAME], glue_table[PROP_GLUE_TABLE_NAME]), + metadata=metadata, + metadata_location=metadata_location, + ) + + def _default_warehouse_location(self, database_name: str, table_name: str): Review Comment: ```suggestion def _default_warehouse_location(self, database_name: str, table_name: str) -> str: ``` ########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): + ToOutputFile.table_metadata(metadata, io.new_output(metadate_path)) + + +def _delete_files(io: FileIO, files_to_delete: Set[str], file_type: str) -> None: + for file in files_to_delete: + try: + io.delete(file) + except OSError as e: + raise OSError(f"Failed to delete {file_type} file {file} ") from e + + +def _delete_data_files(io: FileIO, manifests_to_delete: List[ManifestFile]) -> None: + deleted_files: Dict[str, bool] = {} + for manifest_file in manifests_to_delete: + for entry in manifest_file.fetch_manifest_entry(io): + path = entry.data_file.file_path + if not deleted_files.get(path, False): + try: + io.delete(path) + except OSError as e: + raise OSError(f"Failed to delete data file {path}") from e + deleted_files[path] = True + + +class GlueCatalog(Catalog): + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + self.glue = boto3.client("glue") + + def _convert_glue_to_iceberg(self, glue_table: Dict[str, Any]) -> Table: + properties: Properties = glue_table.get(PROP_GLUE_TABLE_PARAMETERS, {}) + + if TABLE_TYPE not in properties: + raise NoSuchPropertyException( + f"Property {TABLE_TYPE} missing, could not determine type: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + glue_table_type = properties[TABLE_TYPE] + + if glue_table_type.lower() != ICEBERG: + raise NoSuchIcebergTableError( + f"Property table_type is {glue_table_type}, expected {ICEBERG}: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + + if METADATA_LOCATION not in properties: + raise NoSuchPropertyException( + f"Table property {METADATA_LOCATION} is missing, cannot find metadata for: " + f"{glue_table[PROP_GLUE_TABLE_DATABASE_NAME]}.{glue_table[PROP_GLUE_TABLE_NAME]}" + ) + metadata_location = properties[METADATA_LOCATION] + + io = load_file_io(properties=self.properties, location=metadata_location) + file = io.new_input(metadata_location) + metadata = FromInputFile.table_metadata(file) + return Table( + identifier=(glue_table[PROP_GLUE_TABLE_DATABASE_NAME], glue_table[PROP_GLUE_TABLE_NAME]), + metadata=metadata, + metadata_location=metadata_location, + ) + + def _default_warehouse_location(self, database_name: str, table_name: str): + try: + response = self.glue.get_database(Name=database_name) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchNamespaceError(f"The database: {database_name} does not exist") from e + + if database_location := response.get(PROP_GLUE_DATABASE, {}).get(PROP_GLUE_DATABASE_LOCATION): + return f"{database_location}/{table_name}" + + if warehouse_path := self.properties.get(WAREHOUSE): + return f"{warehouse_path}/{database_name}.db/{table_name}" + + raise ValueError("No default path is set, please specify a location when creating a table") + + def _resolve_table_location(self, location: Optional[str], database_name: str, table_name: str) -> str: + if not location: + return self._default_warehouse_location(database_name, table_name) + return location + + def _create_glue_table(self, identifier: Union[str, Identifier], table_input: Dict[str, Any]) -> None: + database_name, table_name = self.identifier_to_tuple(identifier) + try: + self.glue.create_table(DatabaseName=database_name, TableInput=table_input) + except self.glue.exceptions.AlreadyExistsException as e: + raise TableAlreadyExistsError(f"Table {database_name}.{table_name} already exists") from e + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchNamespaceError(f"Database {database_name} not found") from e + + 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 in Glue catalog + 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 + """ + database_name, table_name = self.identifier_to_tuple(identifier) + + location = self._resolve_table_location(location, database_name, table_name) + metadata_location = f"{location}/metadata/00000-{uuid.uuid4()}.metadata.json" + 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) + _write_metadata(metadata, io, metadata_location) + + self._create_glue_table( + identifier=identifier, table_input=_construct_table_input(table_name, metadata_location, properties) + ) + try: + loaded_table = self.load_table(identifier=(database_name, table_name)) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchTableError(f"Table {database_name}.{table_name} fail to be created") from e + + 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_tuple(identifier) + try: + load_table_response = self.glue.get_table(DatabaseName=database_name, Name=table_name) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchTableError(f"Table does not exists: {database_name}.{table_name}") from e + + return self._convert_glue_to_iceberg(load_table_response.get(PROP_GLUE_TABLE, {})) + + 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_tuple(identifier) + try: + self.glue.delete_table(DatabaseName=database_name, Name=table_name) + except self.glue.exceptions.EntityNotFoundException as e: + raise NoSuchTableError(f"Table does not exists: {database_name}.{table_name}") from e + + def purge_table(self, identifier: Union[str, Identifier]) -> None: + """Drop a table and purge all data and metadata files. + + Args: + identifier (str | Identifier): Table identifier. + + Raises: + NoSuchTableError: If a table with the name does not exist + """ + 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: Review Comment: I think we should move the logic of deleting the files into a function (`purge_files(table: Table)`?) in `__init__.py`. We can re-use this for the Hive catalog as well. ########## python/pyproject.toml: ########## @@ -86,6 +88,8 @@ pyarrow = ["pyarrow"] snappy = ["python-snappy"] hive = ["thrift"] s3fs = ["s3fs"] +boto3 = ["boto3"] Review Comment: How about naming this `glue` instead? This makes it easier when installing extras: `pip install pyiceberg[glue]` instead of `pip install pyiceberg[boto3]`, because people are interested in glue, and don't care about boto3. ########## python/pyproject.toml: ########## @@ -86,6 +88,8 @@ pyarrow = ["pyarrow"] snappy = ["python-snappy"] hive = ["thrift"] s3fs = ["s3fs"] +boto3 = ["boto3"] Review Comment: ```suggestion glue = ["boto3"] ``` ########## python/pyiceberg/catalog/base.py: ########## @@ -0,0 +1,22 @@ +# 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. + + +ICEBERG = "iceberg" Review Comment: Can we move these variables to `catalog/__init__.py`? ########## python/pyiceberg/catalog/glue.py: ########## @@ -0,0 +1,491 @@ +# 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 typing import ( + Any, + Dict, + List, + Optional, + Set, + Union, +) + +import boto3 + +from pyiceberg.catalog import ( + Catalog, + Identifier, + Properties, + PropertiesUpdateSummary, +) +from pyiceberg.catalog.base import ( + ICEBERG, + METADATA_LOCATION, + TABLE_TYPE, + WAREHOUSE, +) +from pyiceberg.exceptions import ( + NamespaceAlreadyExistsError, + NamespaceNotEmptyError, + NoSuchIcebergTableError, + NoSuchNamespaceError, + NoSuchPropertyException, + NoSuchTableError, + TableAlreadyExistsError, +) +from pyiceberg.io import FileIO, load_file_io +from pyiceberg.manifest import ManifestFile +from pyiceberg.schema import Schema +from pyiceberg.serializers import FromInputFile, ToOutputFile +from pyiceberg.table import Table +from pyiceberg.table.metadata import TableMetadata, new_table_metadata +from pyiceberg.table.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder +from pyiceberg.typedef import EMPTY_DICT + +EXTERNAL_TABLE_TYPE = "EXTERNAL_TABLE" + +PROP_GLUE_TABLE = "Table" +PROP_GLUE_TABLE_TYPE = "TableType" +PROP_GLUE_TABLE_DESCRIPTION = "description" +PROP_GLUE_TABLE_PARAMETERS = "Parameters" +PROP_GLUE_TABLE_DATABASE_NAME = "DatabaseName" +PROP_GLUE_TABLE_NAME = "Name" + +PROP_GLUE_TABLELIST = "TableList" + +PROP_GLUE_DATABASE = "Database" +PROP_GLUE_DATABASE_LIST = "DatabaseList" +PROP_GLUE_DATABASE_NAME = "Name" +PROP_GLUE_DATABASE_LOCATION = "LocationUri" +PROP_GLUE_DATABASE_DESCRIPTION = "Description" +PROP_GLUE_DATABASE_PARAMETERS = "Parameters" + +PROP_GLUE_NEXT_TOKEN = "NextToken" + +GLUE_DESCRIPTION_KEY = "comment" +GLUE_DATABASE_LOCATION_KEY = "location" + + +def _construct_parameters(metadata_location: str) -> Properties: + return {TABLE_TYPE: ICEBERG.upper(), METADATA_LOCATION: metadata_location} + + +def _construct_table_input(table_name: str, metadata_location: str, properties: Properties) -> Dict[str, Any]: + table_input = { + PROP_GLUE_TABLE_NAME: table_name, + PROP_GLUE_TABLE_TYPE: EXTERNAL_TABLE_TYPE, + PROP_GLUE_TABLE_PARAMETERS: _construct_parameters(metadata_location), + } + + if table_description := properties.get(GLUE_DESCRIPTION_KEY): + table_input[PROP_GLUE_TABLE_DESCRIPTION] = table_description + + return table_input + + +def _construct_database_input(database_name: str, properties: Properties) -> Dict[str, Any]: + database_input: Dict[str, Any] = {PROP_GLUE_DATABASE_NAME: database_name} + parameters = {} + for k, v in properties.items(): + if k == GLUE_DESCRIPTION_KEY: + database_input[PROP_GLUE_DATABASE_DESCRIPTION] = v + elif k == GLUE_DATABASE_LOCATION_KEY: + database_input[PROP_GLUE_DATABASE_LOCATION] = v + else: + parameters[k] = v + database_input[PROP_GLUE_DATABASE_PARAMETERS] = parameters + return database_input + + +def _write_metadata(metadata: TableMetadata, io: FileIO, metadate_path: str): + ToOutputFile.table_metadata(metadata, io.new_output(metadate_path)) + + +def _delete_files(io: FileIO, files_to_delete: Set[str], file_type: str) -> None: + for file in files_to_delete: + try: + io.delete(file) + except OSError as e: + raise OSError(f"Failed to delete {file_type} file {file} ") from e + + +def _delete_data_files(io: FileIO, manifests_to_delete: List[ManifestFile]) -> None: + deleted_files: Dict[str, bool] = {} + for manifest_file in manifests_to_delete: + for entry in manifest_file.fetch_manifest_entry(io): + path = entry.data_file.file_path + if not deleted_files.get(path, False): + try: + io.delete(path) + except OSError as e: + raise OSError(f"Failed to delete data file {path}") from e + deleted_files[path] = True + + +class GlueCatalog(Catalog): + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + self.glue = boto3.client("glue") Review Comment: Since we're doing such an excellent job of putting everything in constants, maybe also create one for glue? :) -- 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-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org