# 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 glob
import datetime
import os
import shutil

import tempfile
import unittest
from unittest.mock import Mock, patch

from pypaimon import CatalogFactory, Schema
import pyarrow as pa
from parameterized import parameterized

from pypaimon.common.json_util import JSON
from pypaimon.common.options.core_options import CoreOptions
from pypaimon.manifest.manifest_list_manager import ManifestListManager
from pypaimon.write.table_write import TableWrite
from pypaimon.write.writer.append_only_data_writer import AppendOnlyDataWriter


class TableWriteTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.tempdir = tempfile.mkdtemp()
        cls.warehouse = os.path.join(cls.tempdir, 'warehouse')
        cls.catalog = CatalogFactory.create({
            'warehouse': cls.warehouse
        })
        cls.catalog.create_database('default', True)

        cls.pa_schema = pa.schema([
            ('user_id', pa.int32()),
            ('item_id', pa.int64()),
            ('behavior', pa.string()),
            ('dt', pa.string())
        ])
        cls.pk_pa_schema = pa.schema([
            pa.field('user_id', pa.int32(), nullable=False),
            ('item_id', pa.int64()),
            ('behavior', pa.string()),
            pa.field('dt', pa.string(), nullable=False)
        ])
        cls.expected = pa.Table.from_pydict({
            'user_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            'item_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010],
            'behavior': ['a', 'b', 'c', None, 'e', 'f', 'g', 'h', 'i', 'j'],
            'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2', 'p2', 'p2', 'p1']
        }, schema=cls.pa_schema)
        cls.pk_expected = pa.Table.from_pydict({
            'user_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            'item_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010],
            'behavior': ['a', 'b', 'c', None, 'e', 'f', 'g', 'h', 'i', 'j'],
            'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2', 'p2', 'p2', 'p1']
        }, schema=cls.pk_pa_schema)

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls.tempdir, ignore_errors=True)

    @staticmethod
    def _commit_rows(table, rows):
        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        for row in rows:
            table_write.write_row(row)
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

    @staticmethod
    def _read_sorted(table, sort_keys):
        read_builder = table.new_read_builder()
        return read_builder.new_read().to_arrow(
            read_builder.new_scan().plan().splits()).sort_by(sort_keys)

    @staticmethod
    def _mock_table_write(partitions, buckets):
        table_write = object.__new__(TableWrite)
        table_write._validate_pyarrow_schema = Mock()
        table_write.row_key_extractor = Mock()
        table_write.file_store_write = Mock()
        table_write.row_key_extractor.extract_partition_bucket_batch.return_value = (
            partitions, buckets)
        return table_write

    def test_write_arrow_batch_reuses_full_batch(self):
        data = pa.RecordBatch.from_pydict({
            'id': [0, 1],
            'payload': [b'a', b'b'],
        })
        table_write = self._mock_table_write(
            [('p1',), ('p1',)], [0, 0])

        with patch.object(pa.compute, 'take', wraps=pa.compute.take) as take:
            table_write.write_arrow_batch(data)

        take.assert_not_called()
        written = table_write.file_store_write.write.call_args[0][2]
        self.assertIs(data, written)

    def test_write_arrow_batch_uses_zero_copy_for_contiguous_groups(self):
        data = pa.RecordBatch.from_pydict({
            'id': [0, 1, 2, 3],
            'payload': [b'a', b'b', b'c', b'd'],
        })
        table_write = self._mock_table_write(
            [('p1',), ('p1',), ('p2',), ('p2',)],
            [0, 0, 1, 1])
        with patch.object(pa.compute, 'take', wraps=pa.compute.take) as take:
            table_write.write_arrow_batch(data)

        take.assert_not_called()
        calls = table_write.file_store_write.write.call_args_list
        self.assertEqual(2, len(calls))
        self.assertEqual({'id': [0, 1], 'payload': [b'a', b'b']},
                         calls[0][0][2].to_pydict())
        self.assertEqual({'id': [2, 3], 'payload': [b'c', b'd']},
                         calls[1][0][2].to_pydict())
        self.assertEqual(
            data.column(1).buffers()[2].address,
            calls[0][0][2].column(1).buffers()[2].address)

    def test_write_arrow_batch_uses_take_for_non_contiguous_groups(self):
        data = pa.RecordBatch.from_pydict({
            'id': [0, 1, 2, 3],
            'payload': [b'a', b'b', b'c', b'd'],
        })
        table_write = self._mock_table_write(
            [('p1',), ('p2',), ('p1',), ('p2',)],
            [0, 1, 0, 1])

        with patch.object(pa.compute, 'take', wraps=pa.compute.take) as take:
            table_write.write_arrow_batch(data)

        self.assertEqual(2, take.call_count)
        calls = table_write.file_store_write.write.call_args_list
        self.assertEqual({'id': [0, 2], 'payload': [b'a', b'c']},
                         calls[0][0][2].to_pydict())
        self.assertEqual({'id': [1, 3], 'payload': [b'b', b'd']},
                         calls[1][0][2].to_pydict())

    def test_write_snapshot(self):
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['dt'])
        self.catalog.create_table('default.test_write_snapshot', schema, False)
        table = self.catalog.get_table('default.test_write_snapshot')
        write_builder = table.new_batch_write_builder()

        # write
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        table_write.write_arrow(self.expected)
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

        # read
        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits).sort_by('user_id')
        self.assertEqual(self.expected, actual)

        # snapshot
        snapshot_json: str = JSON.to_json(table.snapshot_manager().get_latest_snapshot())
        self.assertEqual(True, snapshot_json.__contains__("baseManifestList"))
        self.assertEqual(False, snapshot_json.__contains__("nextRowId"))

    def test_write_row_append_only_partitioned_table(self):
        from pypaimon.table.row.generic_row import GenericRow

        schema = Schema.from_pyarrow_schema(
            self.pa_schema, partition_keys=['dt'])
        self.catalog.create_table(
            'default.test_write_row_append_only_partitioned', schema, False)
        table = self.catalog.get_table(
            'default.test_write_row_append_only_partitioned')

        reordered_fields = [
            table.field_dict['dt'],
            table.field_dict['behavior'],
            table.field_dict['item_id'],
            table.field_dict['user_id'],
        ]
        rows = [
            GenericRow(['p1', 'a', 1001, 1], reordered_fields),
            GenericRow(['p2', 'b', 1002, 2], reordered_fields),
        ]
        self._commit_rows(table, rows)

        expected = pa.Table.from_pydict({
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p2'],
        }, schema=self.pa_schema)
        actual = self._read_sorted(table, 'user_id')
        self.assertEqual(expected, actual)

    def test_write_row_fixed_bucket_primary_key_table(self):
        from pypaimon.table.row.generic_row import GenericRow

        schema = Schema.from_pyarrow_schema(
            self.pk_pa_schema,
            partition_keys=['dt'],
            primary_keys=['user_id', 'dt'],
            options={'bucket': '2'},
        )
        self.catalog.create_table(
            'default.test_write_row_fixed_bucket_pk', schema, False)
        table = self.catalog.get_table(
            'default.test_write_row_fixed_bucket_pk')

        rows = [
            GenericRow([1, 1001, 'a', 'p1'], table.fields),
            GenericRow([2, 1002, 'b', 'p2'], table.fields),
        ]
        self._commit_rows(table, rows)

        expected = pa.Table.from_pydict({
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p2'],
        }, schema=self.pk_pa_schema)
        sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')]
        self.assertEqual(
            expected.sort_by(sort_keys), self._read_sorted(table, sort_keys))

    def test_write_row_dynamic_bucket_primary_key_table(self):
        from pypaimon.table.row.generic_row import GenericRow

        schema = Schema.from_pyarrow_schema(
            self.pk_pa_schema,
            partition_keys=['dt'],
            primary_keys=['user_id', 'dt'],
            options={'bucket': '-1'},
        )
        self.catalog.create_table(
            'default.test_write_row_dynamic_bucket_pk', schema, False)
        table = self.catalog.get_table(
            'default.test_write_row_dynamic_bucket_pk')

        rows = [
            GenericRow([1, 1001, 'a', 'p1'], table.fields),
            GenericRow([2, 1002, 'b', 'p2'], table.fields),
        ]
        self._commit_rows(table, rows)

        expected = pa.Table.from_pydict({
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p2'],
        }, schema=self.pk_pa_schema)
        sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')]
        self.assertEqual(
            expected.sort_by(sort_keys), self._read_sorted(table, sort_keys))

    def test_multi_prepare_commit_ao(self):
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['dt'])
        self.catalog.create_table('default.test_append_only_parquet', schema, False)
        table = self.catalog.get_table('default.test_append_only_parquet')
        write_builder = table.new_stream_write_builder()

        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        # write 1
        data1 = {
            'user_id': [1, 2, 3, 4],
            'item_id': [1001, 1002, 1003, 1004],
            'behavior': ['a', 'b', 'c', None],
            'dt': ['p1', 'p1', 'p2', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data1, schema=self.pa_schema)
        table_write.write_arrow(pa_table)
        table_write.prepare_commit(0)
        # write 2
        data2 = {
            'user_id': [5, 6, 7, 8],
            'item_id': [1005, 1006, 1007, 1008],
            'behavior': ['e', 'f', 'g', 'h'],
            'dt': ['p2', 'p1', 'p2', 'p2'],
        }
        pa_table = pa.Table.from_pydict(data2, schema=self.pa_schema)
        table_write.write_arrow(pa_table)
        table_write.prepare_commit(1)
        # write 3
        data3 = {
            'user_id': [9, 10],
            'item_id': [1009, 1010],
            'behavior': ['i', 'j'],
            'dt': ['p2', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data3, schema=self.pa_schema)
        table_write.write_arrow(pa_table)
        cm = table_write.prepare_commit(2)
        # commit
        table_commit.commit(cm, 2)
        table_write.close()
        table_commit.close()
        self.assertEqual(2, table_write.file_store_write.commit_identifier)

        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits).sort_by('user_id')
        self.assertEqual(self.expected, actual)

    def test_commit_minor_compacts_manifest_files(self):
        schema = Schema.from_pyarrow_schema(
            self.pa_schema,
            partition_keys=['dt'],
            options={'manifest.merge-min-count': '2'},
        )
        self.catalog.create_table('default.test_minor_manifest_compaction', schema, False)
        table = self.catalog.get_table('default.test_minor_manifest_compaction')

        expected_data = {
            'user_id': [],
            'item_id': [],
            'behavior': [],
            'dt': [],
        }
        for i in range(3):
            row = {
                'user_id': [i + 1],
                'item_id': [1000 + i],
                'behavior': ['click'],
                'dt': ['p1'],
            }
            for key, values in row.items():
                expected_data[key].extend(values)

            write_builder = table.new_batch_write_builder()
            table_write = write_builder.new_write()
            table_commit = write_builder.new_commit()
            table_write.write_arrow(pa.Table.from_pydict(row, schema=self.pa_schema))
            table_commit.commit(table_write.prepare_commit())
            table_write.close()
            table_commit.close()

        snapshot = table.snapshot_manager().get_latest_snapshot()
        manifest_list_manager = ManifestListManager(table)
        base_manifests = manifest_list_manager.read(snapshot.base_manifest_list)
        delta_manifests = manifest_list_manager.read(snapshot.delta_manifest_list)

        self.assertEqual(len(base_manifests), 1)
        self.assertEqual(base_manifests[0].num_added_files, 2)
        self.assertEqual(base_manifests[0].num_deleted_files, 0)
        self.assertEqual(len(delta_manifests), 1)

        expected = pa.Table.from_pydict(expected_data, schema=self.pa_schema)
        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits).sort_by('user_id')
        self.assertEqual(expected, actual)

    def test_multi_prepare_commit_pk(self):
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['dt'], primary_keys=['user_id', 'dt'],
                                            options={'bucket': '2'})
        self.catalog.create_table('default.test_primary_key_parquet', schema, False)
        table = self.catalog.get_table('default.test_primary_key_parquet')
        write_builder = table.new_stream_write_builder()

        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        # write 1
        data1 = {
            'user_id': [1, 2, 3, 4],
            'item_id': [1001, 1002, 1003, 1004],
            'behavior': ['a', 'b', 'c', None],
            'dt': ['p1', 'p1', 'p2', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data1, schema=self.pk_pa_schema)
        table_write.write_arrow(pa_table)
        table_write.prepare_commit(0)
        # write 2
        data2 = {
            'user_id': [5, 6, 7, 8],
            'item_id': [1005, 1006, 1007, 1008],
            'behavior': ['e', 'f', 'g', 'h'],
            'dt': ['p2', 'p1', 'p2', 'p2'],
        }
        pa_table = pa.Table.from_pydict(data2, schema=self.pk_pa_schema)
        table_write.write_arrow(pa_table)
        table_write.prepare_commit(1)
        # write 3
        data3 = {
            'user_id': [9, 10],
            'item_id': [1009, 1010],
            'behavior': ['i', 'j'],
            'dt': ['p2', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data3, schema=self.pk_pa_schema)
        table_write.write_arrow(pa_table)
        cm = table_write.prepare_commit(2)
        # commit
        table_commit.commit(cm, 2)
        table_write.close()
        table_commit.close()
        self.assertEqual(2, table_write.file_store_write.commit_identifier)

        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits).sort_by('user_id')
        self.assertEqual(self.pk_expected, actual)

    def test_postpone_read_write(self):
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['user_id'], primary_keys=['user_id', 'dt'],
                                            options={'bucket': -2})
        self.catalog.create_table('default.test_postpone', schema, False)
        table = self.catalog.get_table('default.test_postpone')
        data = {
            'user_id': [1, 2, 3, 4],
            'item_id': [1001, 1002, 1003, 1004],
            'behavior': ['a', 'b', 'c', None],
            'dt': ['p1', 'p1', 'p2', 'p1'],
        }
        expect = pa.Table.from_pydict(data, schema=self.pk_pa_schema)

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        table_write.write_arrow(expect)
        commit_messages = table_write.prepare_commit()
        table_commit.commit(commit_messages)
        table_write.close()
        table_commit.close()

        self.assertTrue(os.path.exists(self.warehouse + "/default.db/test_postpone/snapshot/LATEST"))
        self.assertTrue(os.path.exists(self.warehouse + "/default.db/test_postpone/snapshot/snapshot-1"))
        self.assertTrue(os.path.exists(self.warehouse + "/default.db/test_postpone/manifest"))
        self.assertEqual(len(glob.glob(self.warehouse + "/default.db/test_postpone/manifest/*")), 3)
        self.assertEqual(len(glob.glob(self.warehouse + "/default.db/test_postpone/user_id=2/bucket-postpone/*.avro")),
                         1)
        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits)
        self.assertTrue(not actual)

    def test_data_file_prefix_postpone(self):
        """Test that generated data file names follow the expected prefix format."""
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['user_id'], primary_keys=['user_id', 'dt'],
                                            options={'bucket': -2})
        self.catalog.create_table('default.test_file_prefix_postpone', schema, False)
        table = self.catalog.get_table('default.test_file_prefix_postpone')

        # Write some data to generate files
        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()

        data = {
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data, schema=self.pk_pa_schema)
        table_write.write_arrow(pa_table)

        commit_messages = table_write.prepare_commit()
        table_commit.commit(commit_messages)
        table_write.close()
        table_commit.close()

        # Find generated data files
        table_path = os.path.join(self.warehouse, 'default.db', 'test_file_prefix_postpone')
        data_files = []
        for root, dirs, files in os.walk(table_path):
            for file in files:
                if file.endswith('.parquet') or file.endswith('.avro') or file.endswith('.orc'):
                    data_files.append(file)

        # Verify at least one data file was created
        self.assertGreater(len(data_files), 0, "No data files were generated")

        # Verify file name format: {table_prefix}-u-{commit_user}-s-{random_number}-w--{uuid}-0.{format}
        # Expected pattern: data--u-{user}-s-{random}-w--{uuid}-0.{format}
        expected_pattern = r'^data--u-.+-s-\d+-w-.+-0\.avro$'

        for file_name in data_files:
            self.assertRegex(file_name, expected_pattern,
                             f"File name '{file_name}' does not match expected prefix format")

            # Additional checks for specific components
            parts = file_name.split('-')
            self.assertEqual('data', parts[0], f"File prefix should start with 'data', got '{parts[0]}'")
            self.assertEqual('u', parts[2], f"Second part should be 'u', got '{parts[2]}'")
            self.assertEqual('s', parts[8], f"Fourth part should be 's', got '{parts[8]}'")
            self.assertEqual('w', parts[10], f"Sixth part should be 'w', got '{parts[10]}'")

    def test_data_file_prefix_default(self):
        """Test that generated data file names follow the expected prefix format."""
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['user_id'])
        self.catalog.create_table('default.test_file_prefix_default', schema, False)
        table = self.catalog.get_table('default.test_file_prefix_default')

        # Write some data to generate files
        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()

        data = {
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data, schema=self.pa_schema)
        table_write.write_arrow(pa_table)

        commit_messages = table_write.prepare_commit()
        table_commit.commit(commit_messages)
        table_write.close()
        table_commit.close()

        # Find generated data files
        table_path = os.path.join(self.warehouse, 'default.db', 'test_file_prefix_default')
        data_files = []
        for root, dirs, files in os.walk(table_path):
            for file in files:
                if file.endswith('.parquet') or file.endswith('.avro') or file.endswith('.orc'):
                    data_files.append(file)

        # Verify at least one data file was created
        self.assertGreater(len(data_files), 0, "No data files were generated")

        expected_pattern = r'^data-.+-0\.parquet$'

        for file_name in data_files:
            self.assertRegex(file_name, expected_pattern,
                             f"File name '{file_name}' does not match expected prefix format")

            # Additional checks for specific components
            parts = file_name.split('-')
            self.assertEqual('data', parts[0], f"File prefix should start with 'data', got '{parts[0]}'")

    def test_data_file_prefix(self):
        """Test that generated data file names follow the expected prefix format."""
        schema = Schema.from_pyarrow_schema(self.pa_schema, partition_keys=['user_id'],
                                            options={'data-file.prefix': 'test_prefix'})
        self.catalog.create_table('default.test_file_prefix', schema, False)
        table = self.catalog.get_table('default.test_file_prefix')

        # Write some data to generate files
        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()

        data = {
            'user_id': [1, 2],
            'item_id': [1001, 1002],
            'behavior': ['a', 'b'],
            'dt': ['p1', 'p1'],
        }
        pa_table = pa.Table.from_pydict(data, schema=self.pa_schema)
        table_write.write_arrow(pa_table)

        commit_messages = table_write.prepare_commit()
        table_commit.commit(commit_messages)
        table_write.close()
        table_commit.close()

        # Find generated data files
        table_path = os.path.join(self.warehouse, 'default.db', 'test_file_prefix')
        data_files = []
        for root, dirs, files in os.walk(table_path):
            for file in files:
                if file.endswith('.parquet') or file.endswith('.avro') or file.endswith('.orc'):
                    data_files.append(file)

        # Verify at least one data file was created
        self.assertGreater(len(data_files), 0, "No data files were generated")

        expected_pattern = r'^test_prefix.+-0\.parquet$'

        for file_name in data_files:
            self.assertRegex(file_name, expected_pattern,
                             f"File name '{file_name}' does not match expected prefix format")

    def test_dynamic_bucket_write(self):
        schema = Schema.from_pyarrow_schema(
            self.pa_schema,
            partition_keys=['dt'],
            primary_keys=['user_id', 'dt'],
            options={'bucket': '-1'}
        )
        self.catalog.create_table(
            'default.test_dynamic_bucket', schema, False)
        table = self.catalog.get_table(
            'default.test_dynamic_bucket')
        expected = pa.Table.from_pydict({
            'user_id': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
            'item_id': [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010],
            'behavior': ['a', 'b', 'c', None, 'e', 'f', 'g', 'h', 'i', 'j'],
            'dt': ['p1', 'p1', 'p2', 'p1', 'p2', 'p1', 'p2', 'p2', 'p2', 'p1']
        }, schema=self.pk_pa_schema)
        write_builder = table.new_batch_write_builder()

        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        table_write.write_arrow(expected)
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits)
        sort_keys = [('user_id', 'ascending'), ('dt', 'ascending')]
        self.assertEqual(
            self.pk_expected.sort_by(sort_keys),
            actual.sort_by(sort_keys),
        )

    def test_column_subset_write_rejects_int64_for_int32(self):
        pa_schema = pa.schema([
            ('id', pa.int32()),
            ('name', pa.string()),
        ])
        schema = Schema.from_pyarrow_schema(pa_schema)
        self.catalog.create_table(
            'default.test_column_subset_reject_int64', schema, False)
        table = self.catalog.get_table(
            'default.test_column_subset_reject_int64')

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write().with_write_type(['id'])
        with self.assertRaises(ValueError) as e:
            table_write.write_arrow(pa.Table.from_pydict(
                {'id': [1]}))
        self.assertTrue(str(e.exception).startswith(
            "Input schema isn't consistent with table schema and write cols."))

    def test_write_pandas_respects_write_cols(self):
        import pandas as pd

        pa_schema = pa.schema([
            ('id', pa.int32()),
            ('name', pa.string()),
            ('score', pa.int64()),
        ])
        schema = Schema.from_pyarrow_schema(pa_schema)
        self.catalog.create_table(
            'default.test_write_pandas_write_cols', schema, False)
        table = self.catalog.get_table(
            'default.test_write_pandas_write_cols')

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write().with_write_type(['id', 'name'])
        table_commit = write_builder.new_commit()
        # DataFrame only carries the written subset; missing ``score`` is
        # padded with null on read.
        table_write.write_pandas(pd.DataFrame({
            'id': [1, 2],
            'name': ['a', 'b'],
        }))
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

        expected = pa.Table.from_pydict({
            'id': [1, 2],
            'name': ['a', 'b'],
            'score': [None, None],
        }, schema=pa_schema)
        actual = self._read_sorted(table, 'id')
        self.assertEqual(expected, actual)

    def test_write_pandas_full_columns_unchanged(self):
        import pandas as pd

        pa_schema = pa.schema([
            ('id', pa.int32()),
            ('name', pa.string()),
        ])
        schema = Schema.from_pyarrow_schema(pa_schema)
        self.catalog.create_table(
            'default.test_write_pandas_full', schema, False)
        table = self.catalog.get_table('default.test_write_pandas_full')

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        table_write.write_pandas(pd.DataFrame({
            'id': [1, 2],
            'name': ['a', 'b'],
        }))
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

        expected = pa.Table.from_pydict({
            'id': [1, 2],
            'name': ['a', 'b'],
        }, schema=pa_schema)
        actual = self._read_sorted(table, 'id')
        self.assertEqual(expected, actual)

    def test_validate_schema_allows_binary_family_for_write_cols(self):
        pa_schema = pa.schema([
            ('id', pa.int32()),
            ('payload', pa.binary()),
        ])
        schema = Schema.from_pyarrow_schema(pa_schema)
        self.catalog.create_table(
            'default.test_validate_binary_family', schema, False)
        table = self.catalog.get_table('default.test_validate_binary_family')

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_write._validate_pyarrow_schema(pa.schema([
            ('id', pa.int32()),
            ('payload', pa.binary(4)),
        ]))

        table_write.with_write_type(['payload'])
        table_write._validate_pyarrow_schema(pa.schema([
            ('payload', pa.binary(4)),
        ]))

    @parameterized.expand([('parquet',), ('orc',), ('avro',)])
    def test_write_time_type(self, file_format):
        time_schema = pa.schema([
            ('id', pa.int32()),
            ('t', pa.time32('ms'))
        ])
        expected = pa.Table.from_pydict({
            'id': [1, 2, 3],
            't': [datetime.time(0, 0, 1), datetime.time(0, 0, 2), datetime.time(0, 0, 3)]
        }, schema=time_schema)

        table_name = 'default.test_write_time_' + file_format
        schema = Schema.from_pyarrow_schema(time_schema, options={'file.format': file_format})
        self.catalog.create_table(table_name, schema, False)
        table = self.catalog.get_table(table_name)

        write_builder = table.new_batch_write_builder()
        table_write = write_builder.new_write()
        table_commit = write_builder.new_commit()
        table_write.write_arrow(expected)
        table_commit.commit(table_write.prepare_commit())
        table_write.close()
        table_commit.close()

        read_builder = table.new_read_builder()
        table_read = read_builder.new_read()
        splits = read_builder.new_scan().plan().splits()
        actual = table_read.to_arrow(splits)
        self.assertEqual(expected, actual)

    def test_rolling(self):
        pa_schema = pa.schema([('name', pa.string())])
        schema = Schema.from_pyarrow_schema(pa_schema, partition_keys=[])
        self.catalog.create_table('default.test_rolling_recursion', schema, True)
        table = self.catalog.get_table('default.test_rolling_recursion')

        row_value = 'x' * 100
        sample = pa.Table.from_batches([
            pa.RecordBatch.from_pydict({'name': pa.array([row_value], type=pa.string())})
        ])
        # Set target just above single chunk nbytes so best_split=1 every time
        target = sample.nbytes + 1

        options = CoreOptions.copy(table.options)
        options.set(CoreOptions.TARGET_FILE_SIZE, str(target))
        writer = AppendOnlyDataWriter(
            table=table, partition=(), bucket=0,
            max_seq_number=0, options=options,
        )

        num_rows = 1500
        big_batch = pa.RecordBatch.from_pydict(
            {'name': pa.array([row_value] * num_rows, type=pa.string())}
        )
        writer.write(big_batch)

        pending_rows = writer.pending_data.num_rows if writer.pending_data is not None else 0
        committed_rows = sum(f.row_count for f in writer.committed_files)
        self.assertEqual(committed_rows + pending_rows, num_rows)
        self.assertGreater(len(writer.committed_files), 0)
        if writer.pending_data is not None:
            self.assertLessEqual(writer.pending_data.nbytes, target)
