You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2022/02/11 23:48:56 UTC

[GitHub] [iceberg] kbendick commented on a change in pull request #4081: PyArrowFileIO Implementation

kbendick commented on a change in pull request #4081:
URL: https://github.com/apache/iceberg/pull/4081#discussion_r805075063



##########
File path: python/src/iceberg/io/pyarrow.py
##########
@@ -0,0 +1,215 @@
+# 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.
+"""FileIO implementation for reading and writing table files that uses pyarrow.fs
+
+This file contains a FileIO implementation that relies on the filesystem interface provided
+by PyArrow. It relies on PyArrow's `from_uri` method that infers the correct filesytem
+type to use. Theoretically, this allows the supported storage types to grow naturally
+with the pyarrow library.
+"""
+
+from typing import Union
+from urllib.parse import ParseResult, urlparse
+
+from pyarrow import NativeFile
+from pyarrow.fs import FileSystem, FileType
+
+from iceberg.io.base import FileIO, InputFile, InputStream, OutputFile, OutputStream
+
+
+class PyArrowInputFile(InputFile):
+    """An InputFile implementation that uses a pyarrow filesystem to generate pyarrow.lib.NativeFile instances for reading
+
+    Args:
+        location(str): A URI or a path to a local file
+
+    Attributes:
+        location(str): The URI or path to a local file for a PyArrowInputFile instance
+        parsed_location(urllib.parse.ParseResult): The parsed location with attributes `scheme`, `netloc`, `path`, `params`,
+          `query`, and `fragment`
+        exists(bool): Whether the file exists or not
+
+    Examples:
+        >>> from iceberg.io.pyarrow import PyArrowInputFile
+        >>> input_file = PyArrowInputFile("s3://foo/bar.txt")
+        >>> file_content = input_file.open().read()
+    """
+
+    def __init__(self, location: str):
+        parsed_location = urlparse(location)  # Create a ParseResult from the uri
+
+        if parsed_location.scheme and parsed_location.scheme not in (
+            "file",
+            "mock",
+            "s3fs",
+            "hdfs",
+            "viewfs",
+        ):  # Validate that a uri is provided with a scheme of `file`
+            raise ValueError("PyArrowInputFile location must have a scheme of `file`, `mock`, `s3fs`, `hdfs`, or `viewfs`")
+
+        super().__init__(location=location)
+        self._parsed_location = parsed_location
+
+    def __len__(self) -> int:
+        """Returns the total length of the file, in bytes"""
+        filesytem, path = FileSystem.from_uri(self.location)  # Infer the proper filesystem
+        file = filesytem.open_input_file(path)
+        return file.size()
+
+    @property
+    def parsed_location(self) -> ParseResult:
+        """The parsed location
+
+        Returns:
+            ParseResult: The parsed results which has attributes `scheme`, `netloc`, `path`,
+            `params`, `query`, and `fragments`.
+        """
+        return self._parsed_location
+
+    @property
+    def exists(self) -> bool:
+        """Checks whether the file exists"""
+        filesytem, path = FileSystem.from_uri(self.location)  # Infer the proper filesystem
+        file_info = filesytem.get_file_info(path)
+        return False if file_info.type == FileType.NotFound else True
+
+    def open(self) -> NativeFile:
+        """Opens the location using a PyArrow FileSystem inferred from the scheme
+
+        Returns:
+            pyarrow.lib.NativeFile: A NativeFile instance for the file located at self.location
+        """
+        filesytem, path = FileSystem.from_uri(self.location)  # Infer the proper filesystem
+        input_file = filesytem.open_input_file(path)
+        if not isinstance(input_file, InputStream):
+            raise TypeError("""Object returned from PyArrowInputFile.open does not match the InputStream protocol.""")
+        return input_file
+
+
+class PyArrowOutputFile(OutputFile):
+    """An OutputFile implementation that uses a pyarrow filesystem to generate pyarrow.lib.NativeFile instances for writing
+
+    Args:
+        location(str): A URI or a path to a local file
+
+    Attributes:
+        location(str): The URI or path to a local file for a PyArrowOutputFile instance
+        parsed_location(urllib.parse.ParseResult): The parsed location with attributes `scheme`, `netloc`, `path`, `params`,
+          `query`, and `fragment`
+        exists(bool): Whether the file exists or not
+
+    Examples:
+        >>> from iceberg.io.pyarrow import PyArrowOutputFile
+        >>> output_file = PyArrowOutputFile("s3://foo/bar.txt")
+        >>> output_file.create().write(b'baz')
+    """
+
+    def __init__(self, location: str):
+        parsed_location = urlparse(location)  # Create a ParseResult from the uri
+
+        if parsed_location.scheme and parsed_location.scheme not in (
+            "file",
+            "mock",
+            "s3fs",
+            "hdfs",
+            "viewfs",

Review comment:
       Nit: These are repeated multiple times. Could we just add them to a list or something somewhere and then reference that? The list could even be used in the raised exception too.




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