prabodh1194 commented on code in PR #687: URL: https://github.com/apache/iceberg-python/pull/687#discussion_r1632063906
########## pyiceberg/catalog/snowflake_catalog.py: ########## @@ -0,0 +1,237 @@ +# 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. +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from typing import Iterator, List, Optional, Set, Union + +import pyarrow as pa +from boto3.session import Session +from snowflake.connector import DictCursor, SnowflakeConnection + +from pyiceberg.catalog import MetastoreCatalog, PropertiesUpdateSummary +from pyiceberg.exceptions import NoSuchTableError, TableAlreadyExistsError +from pyiceberg.io import S3_ACCESS_KEY_ID, S3_REGION, S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN +from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC, PartitionSpec +from pyiceberg.schema import Schema +from pyiceberg.table import CommitTableRequest, CommitTableResponse, StaticTable, Table, sorting +from pyiceberg.typedef import EMPTY_DICT, Identifier, Properties + + +class SnowflakeCatalog(MetastoreCatalog): + @dataclass(frozen=True, eq=True) + class _SnowflakeIdentifier: + database: str | None + schema: str | None + table: str | None + + def __iter__(self) -> Iterator[str]: + """ + Iterate of the non-None parts of the identifier. + + Returns: + Iterator[str]: Iterator of the non-None parts of the identifier. + """ + yield from filter(None, [self.database, self.schema, self.table]) + + @classmethod + def table_from_string(cls, identifier: str) -> SnowflakeCatalog._SnowflakeIdentifier: + parts = identifier.split(".") + if len(parts) == 1: + return cls(None, None, parts[0]) + elif len(parts) == 2: + return cls(None, parts[0], parts[1]) + elif len(parts) == 3: + return cls(parts[0], parts[1], parts[2]) + + raise ValueError(f"Invalid identifier: {identifier}") + + @classmethod + def schema_from_string(cls, identifier: str) -> SnowflakeCatalog._SnowflakeIdentifier: + parts = identifier.split(".") + if len(parts) == 1: + return cls(None, parts[0], None) + elif len(parts) == 2: + return cls(parts[0], parts[1], None) + + raise ValueError(f"Invalid identifier: {identifier}") + + @property + def table_name(self) -> str: + return ".".join(self) + + @property + def schema_name(self) -> str: + return ".".join(self) + + def __init__(self, name: str, **properties: str): + super().__init__(name, **properties) + + params = { + "user": properties["user"], + "account": properties["account"], + } + + if "authenticator" in properties: + params["authenticator"] = properties["authenticator"] + + if "password" in properties: + params["password"] = properties["password"] + + if "private_key" in properties: + params["private_key"] = properties["private_key"] + + self.connection = SnowflakeConnection(**params) + + def load_table(self, identifier: Union[str, Identifier]) -> Table: + sf_identifier = SnowflakeCatalog._SnowflakeIdentifier.table_from_string( + identifier if isinstance(identifier, str) else ".".join(identifier) + ) + + metadata_query = "SELECT SYSTEM$GET_ICEBERG_TABLE_INFORMATION(%s) AS METADATA" + + with self.connection.cursor(DictCursor) as cursor: + try: + cursor.execute(metadata_query, (sf_identifier.table_name,)) + metadata = json.loads(cursor.fetchone()["METADATA"])["metadataLocation"] + except Exception as e: + raise NoSuchTableError(f"Table {sf_identifier.table_name} not found") from e + + session = Session() + credentials = session.get_credentials() + current_credentials = credentials.get_frozen_credentials() + + s3_props = { + S3_ACCESS_KEY_ID: current_credentials.access_key, + S3_SECRET_ACCESS_KEY: current_credentials.secret_key, + S3_SESSION_TOKEN: current_credentials.token, + S3_REGION: os.environ.get("AWS_REGION", "us-east-1"), + } + + tbl = StaticTable.from_metadata(metadata, properties=s3_props) + tbl.identifier = tuple(identifier.split(".")) if isinstance(identifier, str) else identifier + tbl.catalog = self + + return tbl Review Comment: i have added support for GCS now @questsul -- 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