You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "maxdebayser (via GitHub)" <gi...@apache.org> on 2023/07/04 20:16:55 UTC

[GitHub] [iceberg] maxdebayser commented on a diff in pull request #7873: Python: Avro write

maxdebayser commented on code in PR #7873:
URL: https://github.com/apache/iceberg/pull/7873#discussion_r1252330938


##########
python/pyiceberg/avro/file.py:
##########
@@ -204,3 +214,58 @@ def __next__(self) -> D:
 
     def _read_header(self) -> AvroFileHeader:
         return construct_reader(META_SCHEMA, {-1: AvroFileHeader}).read(self.decoder)
+
+
+class AvroOutputFile(Generic[D]):
+    output_file: OutputFile
+    output_stream: OutputStream
+    schema: Schema
+    schema_name: str
+    encoder: BinaryEncoder
+    sync_bytes: bytes
+    writer: Writer
+
+    def __init__(self, output_file: OutputFile, schema: Schema, schema_name: str) -> None:
+        self.output_file = output_file
+        self.schema = schema
+        self.schema_name = schema_name
+        self.sync_bytes = os.urandom(SYNC_SIZE)
+        self.writer = construct_writer(self.schema)
+
+    def __enter__(self) -> AvroOutputFile[D]:
+        """
+        Opens the file and writes the header.
+
+        Returns:
+            The file object to write records to
+        """
+        self.output_stream = self.output_file.create(overwrite=True)
+        self.encoder = BinaryEncoder(self.output_stream)
+
+        self._write_header()
+        self.writer = construct_writer(self.schema)
+
+        return self
+
+    def __exit__(
+        self, exctype: Optional[Type[BaseException]], excinst: Optional[BaseException], exctb: Optional[TracebackType]
+    ) -> None:
+        """Performs cleanup when exiting the scope of a 'with' statement."""
+        self.output_stream.close()
+
+    def _write_header(self) -> None:
+        json_schema = json.dumps(AvroSchemaConversion().iceberg_to_avro(self.schema, schema_name=self.schema_name))
+        header = AvroFileHeader(magic=MAGIC, meta={_SCHEMA_KEY: json_schema, _CODEC_KEY: "null"}, sync=self.sync_bytes)

Review Comment:
   Thanks for the suggestion! I've added your code changes and also modified a test case to verify the new feature.



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