Fokko commented on code in PR #687:
URL: https://github.com/apache/iceberg-python/pull/687#discussion_r1666852105


##########
pyiceberg/catalog/snowflake_catalog.py:
##########
@@ -0,0 +1,289 @@
+# 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 logging
+import os
+import warnings
+from dataclasses import dataclass
+from typing import Iterator, List, Optional, Set, Union
+from urllib.parse import urlparse
+
+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
+
+logger = logging.getLogger(__name__)
+
+
+class SnowflakeCatalog(MetastoreCatalog):
+    @dataclass(frozen=True, eq=True)
+    class _SnowflakeIdentifier:
+        """
+        Snowflake follows the following format for identifiers:
+        [database_name].[schema_name].[table_name]
+
+        If the database_name is not provided, the schema_name is the first 
part of the identifier.
+        Similarly, if the schema_name is not provided, the table_name is the 
first part of the identifier.
+
+        This class is used to parse the identifier into its constituent parts 
and
+        provide utility methods to work with them.
+        """
+
+        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):
+        """
+        params:
+            name: Name of the catalog.
+            user: Snowflake user.
+            account: Snowflake account.
+            authenticator: Snowflake authenticator.
+            password: Snowflake password.
+            private_key: Snowflake private key.
+            role: Snowflake role.
+
+        There are multiple ways to authenticate with Snowflake. We are 
supporting the following
+        as of now:
+
+        1. externalbrowser
+        2. password
+        3. private_key
+        """
+
+        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"]
+
+        if "role" in properties:
+            params["role"] = properties["role"]
+
+        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
+
+        _fs_scheme = urlparse(metadata)
+        _fs_props = {}
+
+        if _fs_scheme.scheme == "s3":
+            _fs_props.update(self._generate_s3_access_credentials())
+        elif _fs_scheme.scheme == "gcs":
+            assert os.environ.get(
+                "GOOGLE_APPLICATION_CREDENTIALS"
+            ), "GOOGLE_APPLICATION_CREDENTIALS not set. This is required for 
GCS access."
+        else:
+            warnings.warn(f"Unsupported filesystem scheme: 
{_fs_scheme.scheme}")
+
+        tbl = StaticTable.from_metadata(metadata, properties=_fs_props)

Review Comment:
   Why do you return a `StaticTable` here instead of a full `Table`?



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

Reply via email to