This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/paimon.git
The following commit(s) were added to refs/heads/master by this push:
new 7fa24d786b [python] Add list-files & file command support for Python
CLI. (#11154)
7fa24d786b is described below
commit 7fa24d786b77324728965e2a845f383cb3ba5256
Author: Master.TJ <[email protected]>
AuthorDate: Thu Nov 19 15:43:10 2026 +0800
[python] Add list-files & file command support for Python CLI. (#11154)
---
docs/docs/pypaimon/cli-query.md | 62 ++++
docs/docs/pypaimon/cli.md | 4 +
paimon-python/pypaimon/cli/cli_table.py | 231 +++++++++++++-
paimon-python/pypaimon/tests/cli_table_test.py | 400 +++++++++++++++++++++++--
4 files changed, 667 insertions(+), 30 deletions(-)
diff --git a/docs/docs/pypaimon/cli-query.md b/docs/docs/pypaimon/cli-query.md
index da12abcd21..f2681084bd 100644
--- a/docs/docs/pypaimon/cli-query.md
+++ b/docs/docs/pypaimon/cli-query.md
@@ -426,6 +426,68 @@ Output:
}
```
+## Table List Files
+
+List the live data files referenced by the latest or a specific retained
snapshot.
+
+```shell
+paimon table list-files mydb.orders
+paimon table list-files mydb.orders --snapshot-id 1 --format json
+paimon table list-files mydb.orders --bucket 0 --limit 20
+```
+
+**Options:**
+
+- `--snapshot-id`: Positive snapshot ID. Omit it to use the latest snapshot.
+- `--bucket`: Only display files in the specified bucket.
+- `--limit, -l`: Positive maximum number of live files after filtering. Omit
it to show all.
+- `--format, -f`: Output format: `table` (default) or `json`.
+
+Table output follows the `$files` system table, with `snapshot_id` as the
first column and
+`delete_row_count` for the delete-row count. It includes partition, bucket,
full file path, format,
+file schema ID, level, record count, size, key bounds, column statistics,
sequence-number bounds,
+creation time, file source, first row ID, and written columns. JSON output
contains
+`table`, `snapshot_id`, and a `files` array.
+
+Output (selected columns):
+```text
+snapshot_id bucket file_path
file_format record_count file_size_in_bytes creation_time
+ 1 0 /warehouse/mydb.db/orders/bucket-0/data-example.parquet
parquet 2 803 2026-11-14T18:23:49.778000
+```
+
+## Table File
+
+Inspect a Parquet file's schema and footer metadata without reading data
records. Use the
+`file_path` returned by `list-files`:
+
+```shell
+paimon table file mydb.orders --file
/warehouse/mydb.db/orders/bucket-0/data-example.parquet
+paimon table file mydb.orders --file
/warehouse/mydb.db/orders/bucket-0/data-example.parquet --format table
+```
+
+**Options:**
+
+- `--file`: Actual Parquet file path or filesystem URI. **Required**.
+- `--format, -f`: Output format: `json` (default) or `table`.
+
+If a `file:` input matches both a literal path and a different URL-decoded
file, the command
+reports an ambiguity. Use a plain filesystem path to select the intended file.
+
+Output includes the file path, format, size, schema, and Parquet metadata such
as row groups and
+column statistics. Table output displays `schema` and `metadata` as indented,
multiline JSON.
+
+Output (selected fields):
+```json
+{
+ "table": "mydb.orders",
+ "file_path": "/warehouse/mydb.db/orders/bucket-0/data-example.parquet",
+ "file_format": "parquet",
+ "file_size_in_bytes": 803,
+ "schema": {"arrow": "id: int64\nname: string"},
+ "metadata": {"num_columns": 2, "num_rows": 2, "num_row_groups": 1}
+}
+```
+
## Table List Partitions
List partitions of a Paimon table. Supports optional pattern filtering to
match specific partitions.
diff --git a/docs/docs/pypaimon/cli.md b/docs/docs/pypaimon/cli.md
index 0795b91868..bd4d1b0491 100644
--- a/docs/docs/pypaimon/cli.md
+++ b/docs/docs/pypaimon/cli.md
@@ -107,6 +107,8 @@ paimon table list-snapshots demo.people --limit 20
paimon table snapshot demo.people
paimon table list-manifests demo.people --limit 20
paimon table manifest demo.people --file manifest-example
+paimon table list-files demo.people --limit 20
+paimon table file demo.people --file /path/to/data-example.parquet
paimon table explain demo.people --where "id = 2"
```
@@ -120,6 +122,8 @@ paimon table explain demo.people --where "id = 2"
<span id="table-list-snapshots"></span>
<span id="table-list-manifests"></span>
<span id="table-manifest"></span>
+<span id="table-list-files"></span>
+<span id="table-file"></span>
<span id="table-create"></span>
<span id="table-import"></span>
<span id="import-from-csv"></span>
diff --git a/paimon-python/pypaimon/cli/cli_table.py
b/paimon-python/pypaimon/cli/cli_table.py
index f3ff9c459f..e20ba2f20b 100644
--- a/paimon-python/pypaimon/cli/cli_table.py
+++ b/paimon-python/pypaimon/cli/cli_table.py
@@ -595,12 +595,175 @@ def cmd_table_manifest(args):
sys.exit(1)
+def cmd_table_list_files(args):
+ """
+ Execute the 'table list-files' command.
+
+ Lists the live data files referenced by the latest or a specified snapshot.
+
+ Args:
+ args: Parsed command line arguments.
+ """
+ from pypaimon.table.file_store_table import FileStoreTable
+ from pypaimon.table.system.files_table import FilesTable
+
+ table = _open_schema_table(args)
+ try:
+ if not isinstance(table, FileStoreTable):
+ raise ValueError('File listing is not supported for this table
type; expected a FileStoreTable.')
+ if table.options.query_auth_enabled:
+ raise NotImplementedError('Raw file metadata is not supported on a
query-auth table.')
+ manager = table.snapshot_manager()
+ snapshot = (manager.get_latest_snapshot() if args.snapshot_id is None
+ else manager.get_snapshot_by_id(args.snapshot_id))
+ if snapshot is None and args.snapshot_id is not None:
+ raise ValueError(f"Snapshot {args.snapshot_id} not found for table
'{args.table}'.")
+
+ if args.snapshot_id is not None and snapshot.schema_id !=
table.table_schema.id:
+ if snapshot.schema_id is None:
+ raise ValueError(f"Snapshot {snapshot.id} does not contain a
schema ID.")
+ schema = table.schema_manager.get_schema(snapshot.schema_id)
+ if schema is None:
+ raise ValueError(f"Schema {snapshot.schema_id} not found for
snapshot {snapshot.id}.")
+ dynamic_options = getattr(table, '_applied_dynamic_options', {})
+ options = table._exclude_current_schema_field_options(schema,
table.options.options, set(dynamic_options))
+ table = FileStoreTable(table.file_io, table.identifier,
table.table_path,
+ schema.copy(new_options=options),
table.catalog_environment)
+ table._applied_dynamic_options = dict(dynamic_options)
+
+ # Pin the resolved snapshot, including an empty table, before reading
its live files.
+ files =
FilesTable(table._copy_with_snapshot(snapshot))._build_arrow_table()
+ if args.bucket is not None:
+ import pyarrow.compute as pc
+ files = files.filter(pc.equal(files.column('bucket'), args.bucket))
+ if args.limit is not None:
+ files = files.slice(0, args.limit)
+ files = files.rename_columns(['delete_row_count' if name ==
'deleteRowCount' else name
+ for name in files.column_names])
+ snapshot_id = snapshot.id if snapshot is not None else None
+ # Table.to_pylist is unavailable in the supported PyArrow 6 release.
+ columns = files.to_pydict()
+ rows = [dict(snapshot_id=snapshot_id, **dict(zip(columns, values)))
for values in zip(*columns.values())]
+ if args.format == 'json':
+ result = _manifest_json_value({'table': args.table, 'snapshot_id':
snapshot_id, 'files': rows})
+ print(json.dumps(result, ensure_ascii=False, indent=2,
allow_nan=False))
+ elif not rows:
+ print(f"No files found for table '{args.table}' (snapshot
{_snapshot_display_value(snapshot_id)}).")
+ else:
+ import pandas as pd
+ for row in rows:
+ if row['creation_time'] is not None:
+ row['creation_time'] = row['creation_time'].isoformat()
+ # Convert before Pandas can coerce nullable integers to floats.
+ values = [[_snapshot_display_value(value) for value in
row.values()] for row in rows]
+ print(pd.DataFrame(values, columns=['snapshot_id'] +
files.column_names).to_string(index=False))
+ except Exception as e:
+ print(f"Error: Failed to list files for table '{args.table}': {e}",
file=sys.stderr)
+ sys.exit(1)
+
+
+def cmd_table_file(args):
+ """
+ Execute the 'table file' command.
+
+ Displays a Parquet file's schema and footer metadata without reading data
records.
+
+ Args:
+ args: Parsed command line arguments.
+ """
+ import errno
+ from os.path import basename, samefile
+
+ import pyarrow.fs as pafs
+ import pyarrow.parquet as pq
+
+ from pypaimon.table.file_store_table import FileStoreTable
+ from pypaimon.table.system.files_table import _data_file_format
+ from pypaimon.table.system.system_table import SystemTable
+
+ table = _open_schema_table(args)
+ try:
+ base_table = table.base_table if isinstance(table, SystemTable) else
table
+ if isinstance(base_table, FileStoreTable) and
base_table.options.query_auth_enabled:
+ raise NotImplementedError('Raw file metadata is not supported on a
query-auth table.')
+ status = None
+ missing = None
+ non_file_found = False
+ # Check both literal Paimon paths and encoded file URIs without
guessing their meaning.
+ for path in dict.fromkeys(_table_file_paths(table, args.file)):
+ try:
+ candidate = table.file_io.get_file_status(path)
+ except OSError as e:
+ if not isinstance(e, FileNotFoundError) and e.errno !=
errno.ENAMETOOLONG:
+ raise
+ missing = e
+ continue
+ if candidate.type != pafs.FileType.File:
+ non_file_found = True
+ continue
+ if status is not None and not samefile(status.path,
candidate.path):
+ raise ValueError(
+ f"Ambiguous --file: '{status.path}' and '{candidate.path}'
both exist. "
+ "Use a plain filesystem path without the 'file:' prefix.")
+ io_path, status = path, candidate
+ if status is None:
+ if non_file_found:
+ raise ValueError('--file must point to a regular file.')
+ raise missing
+ file_format = _data_file_format(basename(status.path)).lower()
+ if file_format != 'parquet':
+ raise ValueError('Unsupported file format. Only Parquet files are
supported.')
+ with table.file_io.new_input_stream(io_path) as stream:
+ parquet_file = pq.ParquetFile(stream)
+ metadata = parquet_file.metadata.to_dict()
+ columns = []
+ for i in range(parquet_file.metadata.num_columns):
+ column = parquet_file.schema.column(i)
+ columns.append({
+ 'name': column.name,
+ 'path': column.path,
+ 'physical_type': column.physical_type,
+ 'logical_type': str(column.logical_type),
+ 'converted_type': column.converted_type,
+ 'max_definition_level': column.max_definition_level,
+ 'max_repetition_level': column.max_repetition_level,
+ 'length': column.length,
+ 'precision': column.precision,
+ 'scale': column.scale,
+ })
+ result = _manifest_json_value({
+ 'table': args.table,
+ 'file_path': args.file,
+ 'file_format': file_format,
+ 'file_size_in_bytes': status.size,
+ 'schema': {'arrow': str(parquet_file.schema_arrow), 'parquet':
columns},
+ 'metadata': metadata,
+ })
+ if args.format == 'json':
+ print(json.dumps(result, ensure_ascii=False, indent=2,
allow_nan=False))
+ else:
+ field_width = max(len(key) for key in result)
+ print(f'{"Field":<{field_width}} Value')
+ for key, value in result.items():
+ if isinstance(value, (dict, list)):
+ # Only LF separates indented JSON lines; Unicode
separators may be string data.
+ lines = json.dumps(value, ensure_ascii=False, indent=2,
allow_nan=False).split('\n')
+ else:
+ lines = _snapshot_display_value(value).split('\n')
+ for i, line in enumerate(lines or ['']):
+ field = key if i == 0 else ''
+ print(f'{field:<{field_width}} {line}')
+ except Exception as e:
+ print(f"Error: Failed to inspect file '{args.file}' for table
'{args.table}': {e}", file=sys.stderr)
+ sys.exit(1)
+
+
def cmd_table_rollback(args):
"""
Execute the 'table rollback' command.
Rolls a table back to an earlier snapshot, tag, or timestamp using the
- table's existing rollback API. Exactly one of --snapshot / --tag /
+ table's existing rollback API. Exactly one of --snapshot-id / --tag /
--timestamp must be provided.
Args:
@@ -632,9 +795,9 @@ def cmd_table_rollback(args):
sys.exit(1)
try:
- if args.snapshot is not None:
- table.rollback_to(args.snapshot)
- target_desc = f"snapshot {args.snapshot}"
+ if args.snapshot_id is not None:
+ table.rollback_to(args.snapshot_id)
+ target_desc = f"snapshot {args.snapshot_id}"
elif args.tag is not None:
table.rollback_to(args.tag)
target_desc = f"tag '{args.tag}'"
@@ -1252,6 +1415,33 @@ def _manifest_json_value(value, field_names=None):
return value
+def _table_file_paths(table, path):
+ """Yield the FileIO paths a CLI file argument can refer to."""
+ from pathlib import Path
+
+ from pypaimon.utils.path import to_file_io_path
+
+ def file_uri(value):
+ scheme, separator, rest = str(value).partition(':')
+ return 'file:' + rest if separator and scheme.lower() == 'file' else
None
+
+ uri = file_uri(path) or path
+ literal = to_file_io_path(uri)
+ yield literal
+ if literal == uri:
+ return
+
+ table_uri = file_uri(getattr(table, 'table_path', None))
+ if table_uri and '%' in table_uri:
+ # Metadata paths have a URI-encoded table root and literal partition
directories.
+ logical_root = Path(to_file_io_path(table_uri))
+ logical_file = Path(literal)
+ if logical_root in logical_file.parents:
+ physical_root = Path(table.file_io.to_filesystem_path(table_uri))
+ yield str(physical_root / logical_file.relative_to(logical_root))
+ yield uri
+
+
def add_table_subcommands(table_parser):
"""
Add table subcommands to the parser.
@@ -1436,6 +1626,34 @@ def add_table_subcommands(table_parser):
)
manifest_parser.set_defaults(func=cmd_table_manifest)
+ # table list-files command
+ list_files_parser = table_subparsers.add_parser('list-files', help='List
the live data files of a snapshot')
+ list_files_parser.add_argument('table', help='Table identifier in format:
database.table')
+ list_files_parser.add_argument(
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Snapshot ID to inspect (default: the latest snapshot)'
+ )
+ list_files_parser.add_argument('--bucket', type=int, default=None,
help='Only display files in this bucket')
+ list_files_parser.add_argument(
+ '--limit', '-l', type=_positive_int, default=None,
+ help='Maximum number of live files to display after filtering
(default: all)'
+ )
+ list_files_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='table',
+ help='Output format: table (default) or json'
+ )
+ list_files_parser.set_defaults(func=cmd_table_list_files)
+
+ # table file command
+ file_parser = table_subparsers.add_parser('file', help="Inspect a Parquet
file's schema and footer metadata")
+ file_parser.add_argument('table', help='Table identifier in format:
database.table (provides FileIO context)')
+ file_parser.add_argument('--file', required=True, help='Actual Parquet
file path or filesystem URI')
+ file_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='json',
+ help='Output format: json (default) or table'
+ )
+ file_parser.set_defaults(func=cmd_table_file)
+
# table rollback command
rollback_parser = table_subparsers.add_parser(
'rollback',
@@ -1445,9 +1663,10 @@ def add_table_subcommands(table_parser):
help='Table identifier in format: database.table'
)
rollback_target =
rollback_parser.add_mutually_exclusive_group(required=True)
+ # Keep the prefixes unambiguous for scripts using --snapshot or --snap.
rollback_target.add_argument(
- '--snapshot', type=int, default=None,
- help='Snapshot ID to roll back to'
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Snapshot ID to roll back to (also accepts --snapshot and --snap)'
)
rollback_target.add_argument(
'--tag', type=str, default=None,
diff --git a/paimon-python/pypaimon/tests/cli_table_test.py
b/paimon-python/pypaimon/tests/cli_table_test.py
index 8792699903..5757cc5fcb 100644
--- a/paimon-python/pypaimon/tests/cli_table_test.py
+++ b/paimon-python/pypaimon/tests/cli_table_test.py
@@ -208,8 +208,8 @@ class CliTableTest(unittest.TestCase):
code = e.code
return out.getvalue(), err.getvalue(), code
- def _run_table_command_success(self, *argv):
- out, err, code = self._run_table_command(*argv)
+ def _run_table_command_success(self, *argv, config=None):
+ out, err, code = self._run_table_command(*argv, config=config)
self.assertEqual(0, code, err)
self.assertEqual('', err)
return out
@@ -891,6 +891,364 @@ class CliTableTest(unittest.TestCase):
self.assertEqual(('', 1), (out, code))
self.assertIn(message, err)
+ def test_cli_table_list_files_live_snapshots_and_limits(self):
+ identifier, table, entry = self._create_manifest_table()
+ added = replace(entry, file=replace(entry.file,
file_name='data-added.parquet',
+ delete_row_count=0,
first_row_id=9007199254740993))
+ bucket = replace(added, bucket=1, file=replace(added.file,
file_name='data-bucket.parquet', first_row_id=None))
+ ManifestFileManager(table).write('manifest-delta', [replace(entry,
kind=1), added, bucket])
+ latest = table.snapshot_manager().get_latest_snapshot()
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
+ side_effect=[latest, AssertionError('resolved
twice')]):
+ result = json.loads(self._run_table_command_success('list-files',
identifier, '-f', 'json'))
+ self.assertEqual((identifier, 2), (result['table'],
result['snapshot_id']))
+ files = result['files']
+ self.assertEqual(['data-added.parquet', 'data-bucket.parquet'],
+ [os.path.basename(row['file_path']) for row in files])
+ expected = dict(snapshot_id=2, file_format='parquet',
delete_row_count=0,
+ creation_time='2023-11-14T22:13:20.123000',
file_source='APPEND',
+ first_row_id=9007199254740993, write_cols=None)
+ self.assertEqual(expected, {key: files[0][key] for key in expected})
+ self.assertEqual([2, 2], [row['snapshot_id'] for row in files])
+ self.assertNotIn('deleteRowCount', files[0])
+ for options, names in ((('-l', '1'), ['data-added.parquet']),
+ (('--bucket', '1', '-l', '1'),
['data-bucket.parquet']),
+ (('--bucket', '9'), [])):
+ with self.subTest(options=options):
+ result =
json.loads(self._run_table_command_success('list-files', identifier, *options,
'-f', 'json'))
+ self.assertEqual(names, [os.path.basename(row['file_path'])
for row in result['files']])
+ self.assertEqual(2, result['snapshot_id'])
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
side_effect=AssertionError('latest lookup')):
+ result = json.loads(self._run_table_command_success(
+ 'list-files', identifier, '--snapshot-id', '1', '-f', 'json'))
+ self.assertEqual((1, 'data-test.parquet'),
+ (result['snapshot_id'],
os.path.basename(result['files'][0]['file_path'])))
+ output = self._run_table_command_success('list-files', identifier)
+ self.assertEqual(list(files[0]), output.splitlines()[0].split())
+ self.assertRegex(output, r'9007199254740993\s+-\n')
+ self.assertIn(files[0]['creation_time'], output)
+ self.assertRegex(output, r'\s-\s+-\s*$')
+
+ def test_cli_table_list_files_rejects_query_auth(self):
+ identifier, table = self._create_snapshot_table(snapshots=[],
options={'query-auth.enabled': 'true'})
+ with patch.object(type(table), 'snapshot_manager',
side_effect=AssertionError('snapshot accessed')) as manager:
+ out, err, code = self._run_table_command('list-files', identifier)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('not supported on a query-auth table', err)
+ manager.assert_not_called()
+
+ def test_cli_table_list_files_snapshot_schema(self):
+ from pypaimon.schema.data_types import AtomicType
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier, _, _ = self._create_manifest_table()
+ for changes, current_min in (
+ ([SchemaChange.rename_column('id', 'renamed')], '{renamed=7}'),
+ ([SchemaChange.add_column('keep', AtomicType('INT')),
SchemaChange.drop_column('renamed'),
+ SchemaChange.add_column('id', AtomicType('INT'))],
'{id=null, keep=null}')):
+ with self.subTest(current_min=current_min):
+ self.catalog.alter_table(identifier, changes)
+ history = json.loads(self._run_table_command_success(
+ 'list-files', identifier, '--snapshot-id', '1', '-f',
'json'))
+ file, = history['files']
+ self.assertEqual(('{id=7}', '{id=8}', '{id=0}'),
+ (file['min_value_stats'],
file['max_value_stats'], file['null_value_counts']))
+
+ latest =
json.loads(self._run_table_command_success('list-files', identifier, '-f',
'json'))
+ self.assertEqual(current_min,
latest['files'][0]['min_value_stats'])
+
+ def test_cli_table_list_files_arrow6_compatibility(self):
+ from pypaimon.table.system.files_table import FilesTable
+
+ class Arrow6Table:
+ """Expose the Arrow 6 Table interface, which has no to_pylist
method."""
+
+ def __init__(self, table):
+ self.table = table
+
+ def rename_columns(self, names):
+ return Arrow6Table(self.table.rename_columns(names))
+
+ def __getattr__(self, name):
+ if name == 'to_pylist':
+ raise AttributeError('Arrow 6 Table has no to_pylist')
+ return getattr(self.table, name)
+
+ identifier, _, _ = self._create_manifest_table()
+ build = FilesTable._build_arrow_table
+ with patch.object(FilesTable, '_build_arrow_table', lambda view:
Arrow6Table(build(view))):
+ result = json.loads(self._run_table_command_success(
+ 'list-files', identifier, '--snapshot-id', '1', '-f', 'json'))
+ self.assertEqual(1, len(result['files']))
+ self.assertEqual(9007199254740993,
result['files'][0]['min_sequence_number'])
+
+ def test_cli_table_list_files_empty_and_errors(self):
+ identifier, _ = self._create_snapshot_table(snapshots=[])
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
+ side_effect=[None, AssertionError('resolved
twice')]):
+ result = json.loads(self._run_table_command_success('list-files',
identifier, '-f', 'json'))
+ self.assertEqual(dict(table=identifier, snapshot_id=None, files=[]),
result)
+ self.assertIn('No files found',
self._run_table_command_success('list-files', identifier))
+ identifier, table, _ = self._create_manifest_table()
+ os.remove(os.path.join(table.table_path, 'manifest', 'manifest-base'))
+ for args, message in (((identifier, '--snapshot-id', '99'), 'Snapshot
99 not found'),
+ ((identifier, '--snapshot-id', '1'), 'Failed to
list files'),
+ ((identifier + '$snapshots',), 'expected a
FileStoreTable')):
+ with self.subTest(args=args):
+ out, err, code = self._run_table_command('list-files', *args)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(message, err)
+
+ def test_cli_table_file_rejects_query_auth(self):
+ identifier, _ = self._create_snapshot_table(snapshots=[],
options={'query-auth.enabled': 'true'})
+ with patch('pypaimon.cli.cli_table._table_file_paths',
+ side_effect=AssertionError('file path resolved')) as paths:
+ for table_name in (identifier, identifier + '$snapshots'):
+ with self.subTest(table=table_name):
+ out, err, code = self._run_table_command('file',
table_name, '--file', 'missing.parquet')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('not supported on a query-auth table', err)
+ paths.assert_not_called()
+
+ def test_cli_table_file_parquet_metadata_and_formats(self):
+ import pyarrow.parquet as pq
+
+ identifier, table = self._create_snapshot_table(snapshots=[])
+ label = 'east\u2028west\u2029south'
+ path = Path(self.tempdir) / f'standalone file%2F#{label}.PARQUET'
+ schema = pa.schema([('id', pa.int64()), ('payload', pa.binary()),
('unknown', pa.int32()),
+ ('label', pa.string())],
+ metadata={b'author': b'test'})
+ data = pa.Table.from_pydict(dict(id=[9007199254740993,
9007199254740994],
+ payload=[b'\x00\xff', None],
unknown=[None, None],
+ label=[label, 'north']),
schema=schema)
+ pq.write_table(data, path, row_group_size=1, compression='zstd',
write_statistics=['id', 'payload', 'label'])
+ with patch.object(type(table), 'snapshot_manager',
side_effect=AssertionError('snapshot read')), \
+ patch.object(pq.ParquetFile, 'read',
side_effect=AssertionError('data read')), \
+ patch.object(pq.ParquetFile, 'iter_batches',
side_effect=AssertionError('data read')):
+ result = json.loads(self._run_table_command_success('file',
identifier, '--file', str(path)))
+ output = self._run_table_command_success('file', identifier,
'--file', str(path), '-f', 'table')
+ uri = json.loads(self._run_table_command_success('file',
identifier, '--file', path.as_uri()))
+ self.assertEqual((identifier, str(path), 'parquet',
path.stat().st_size),
+ (result['table'], result['file_path'],
result['file_format'], result['file_size_in_bytes']))
+ self.assertNotIn('snapshot_id', result)
+ metadata = result['metadata']
+ self.assertEqual((2, 4, 2), (metadata['num_rows'],
metadata['num_columns'], metadata['num_row_groups']))
+ self.assertIn('id: int64', result['schema']['arrow'])
+ self.assertEqual(('id', 'INT64'),
+ (result['schema']['parquet'][0]['path'],
result['schema']['parquet'][0]['physical_type']))
+ columns = metadata['row_groups'][0]['columns']
+ self.assertEqual((9007199254740993, 'ZSTD'),
(columns[0]['statistics']['min'], columns[0]['compression']))
+ self.assertEqual({'encoding': 'base64', 'data': 'AP8='},
columns[1]['statistics']['min'])
+ self.assertEqual(1,
metadata['row_groups'][1]['columns'][1]['statistics']['null_count'])
+ self.assertIsNone(columns[2]['statistics'])
+ self.assertEqual(label, columns[3]['statistics']['min'])
+ self.assertNotIn('key_value_metadata', metadata)
+ lines = output.rstrip('\n').split('\n')
+ self.assertEqual(['Field', 'Value'], lines[0].split())
+ value_start = lines[0].index('Value')
+ rows = {}
+ field = None
+ for line in lines[1:]:
+ if line[:value_start].strip():
+ field = line[:value_start].strip()
+ rows[field] = line[value_start:]
+ else:
+ rows[field] += '\n' + line[value_start:]
+ self.assertTrue(rows['schema'].startswith('{\n'))
+ self.assertTrue(rows['metadata'].startswith('{\n'))
+ self.assertEqual(result, dict(rows,
file_size_in_bytes=int(rows['file_size_in_bytes']),
+ schema=json.loads(rows['schema']),
metadata=json.loads(rows['metadata'])))
+ self.assertEqual(dict(result, file_path=path.as_uri()), uri)
+
+ def test_cli_table_file_metadata_path_round_trip(self):
+ pa_schema = pa.schema([('id', pa.int32()), ('pt', pa.string())])
+ schema = Schema.from_pyarrow_schema(pa_schema, partition_keys=['pt'],
options={'bucket': '-1'})
+ warehouse_uri = Path(self.warehouse).as_uri()
+ for index, warehouse in enumerate((self.warehouse, warehouse_uri,
+ warehouse_uri.replace('file:///',
'file://localhost/'))):
+ with self.subTest(warehouse=warehouse):
+ name = '{}_{}'.format(self._testMethodName, index)
+ identifier = 'test_db.' + name
+ # Write through the local catalog; URI handling is exercised
by the CLI below.
+ self.catalog.create_table(identifier, schema, False)
+ table = self.catalog.get_table(identifier)
+ builder = table.new_batch_write_builder()
+ writer, commit = builder.new_write(), builder.new_commit()
+ try:
+ writer.write_arrow(pa.Table.from_pydict(
+ {'id': [1, 2, 3], 'pt': ['a/b', 'a%2Fb', 'a b?#']},
schema=pa_schema))
+ commit.commit(writer.prepare_commit())
+ finally:
+ writer.close()
+ commit.close()
+ config = Path(self.tempdir) /
('file-path-{}.yaml'.format(index))
+ config.write_text('metastore: filesystem\nwarehouse:
{}\n'.format(warehouse))
+ files = json.loads(self._run_table_command_success(
+ 'list-files', identifier, '-f', 'json',
config=str(config)))['files']
+ self.assertEqual(3, len(files))
+ paths = {row['file_path'] for row in files}
+ self.assertTrue(any('/pt=a%2Fb/' in path for path in paths))
+ if index:
+ self.assertTrue(all(path.startswith('file:') for path in
paths))
+ manifests = json.loads(self._run_table_command_success(
+ 'list-manifests', identifier, '--type', 'delta', '-f',
'json', config=str(config)))
+ manifest_paths = set()
+ for manifest in manifests['manifests']:
+ entries = json.loads(self._run_table_command_success(
+ 'manifest', identifier, '--file',
manifest['file_name'], config=str(config)))['entries']
+ manifest_paths.update(entry['file']['file_path'] for entry
in entries)
+ self.assertEqual(paths, manifest_paths)
+ physical_files = list((Path(self.warehouse) / 'test_db.db' /
name).rglob('*.parquet'))
+ for row in files:
+ with self.subTest(file=row['file_path']):
+ physical = next(path for path in physical_files
+ if
row['file_path'].endswith(path.relative_to(self.warehouse).as_posix()))
+ expected = json.loads(self._run_table_command_success(
+ 'file', identifier, '--file', str(physical),
config=str(config)))
+ self.assertEqual(row['record_count'],
expected['metadata']['num_rows'])
+ self.assertEqual(row['file_size_in_bytes'],
expected['file_size_in_bytes'])
+ for path in (row['file_path'], physical.as_uri()):
+ actual =
json.loads(self._run_table_command_success(
+ 'file', identifier, '--file', path,
config=str(config)))
+ self.assertEqual(dict(expected, file_path=path),
actual)
+
+ def test_cli_table_file_literal_paths_and_encoded_uris(self):
+ import pyarrow.parquet as pq
+
+ literal = Path(self.tempdir) / 'literal%20file.parquet'
+ decoded = Path(self.tempdir) / 'literal file.parquet'
+ literal_only = Path(self.tempdir) / 'literal%2Fonly.parquet'
+ uri_only = Path(self.tempdir) / 'encoded only.parquet'
+ for path, rows in ((literal, [1]), (decoded, [2, 3]), (literal_only,
[4]), (uri_only, [5, 6])):
+ pq.write_table(pa.table({'id': rows}), path)
+ linked_literal = Path(self.tempdir) / 'linked%20file.parquet'
+ linked_decoded = Path(self.tempdir) / 'linked file.parquet'
+ os.link(literal, linked_literal)
+ os.link(literal, linked_decoded)
+ for path, expected, rows in ((str(literal), literal, 1),
(literal.as_uri(), literal, 1),
+ (str(decoded), decoded, 2),
(linked_decoded.as_uri(), linked_literal, 1),
+ ('file:///' +
literal_only.as_posix().lstrip('/'), literal_only, 1),
+ (uri_only.as_uri(), uri_only, 2),
+ (uri_only.as_uri().replace('file:',
'FILE:'), uri_only, 2),
+ (uri_only.as_uri().replace('file:',
'FiLe:'), uri_only, 2),
+ (uri_only.as_uri().replace('file:///',
'file:/'), uri_only, 2),
+ (uri_only.as_uri().replace('file:///',
'file://localhost/'), uri_only, 2)):
+ with self.subTest(path=path):
+ result = json.loads(self._run_table_command_success('file',
'test_db.users', '--file', path))
+ self.assertEqual(path, result['file_path'])
+ self.assertEqual(rows, result['metadata']['num_rows'])
+ self.assertEqual(expected.stat().st_size,
result['file_size_in_bytes'])
+
+ def test_cli_table_file_uri_with_directory_candidate(self):
+ import pyarrow.parquet as pq
+
+ path = Path(self.tempdir) / 'day 1.parquet'
+ (path.parent / 'day%201.parquet').mkdir()
+ pq.write_table(pa.table({'id': [7, 9]}), path)
+
+ result = json.loads(self._run_table_command_success('file',
'test_db.users', '--file', path.as_uri()))
+ self.assertEqual(2, result['metadata']['num_rows'])
+
+ def test_cli_table_file_ambiguous_paths(self):
+ import pyarrow.parquet as pq
+
+ literal = Path(self.tempdir) / 'collision%20file.parquet'
+ decoded = Path(self.tempdir) / 'collision file.parquet'
+ for path, rows in ((literal, [1]), (decoded, [2, 3])):
+ pq.write_table(pa.table({'id': rows}), path)
+ table = self.catalog.get_table('test_db.users')
+ for prefix in ('file://localhost/', 'file:/', 'file:///',
+ 'FILE://localhost/', 'FILE:/', 'FILE:///',
+ 'FiLe://localhost/', 'FiLe:/', 'FiLe:///'):
+ with self.subTest(prefix=prefix):
+ uri = decoded.as_uri().replace('file:///', prefix)
+ with patch('pypaimon.cli.cli_table._open_schema_table',
return_value=table), \
+ patch.object(table.file_io, 'new_input_stream',
+ wraps=table.file_io.new_input_stream) as
stream:
+ out, err, code = self._run_table_command('file',
'test_db.users', '--file', uri)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('Ambiguous --file', err)
+ self.assertIn(literal.as_posix(), err)
+ self.assertIn(decoded.as_posix(), err)
+ self.assertIn('plain filesystem path', err)
+ stream.assert_not_called()
+
+ def test_cli_table_file_io_errors_do_not_retry_uri(self):
+ table = self.catalog.get_table('test_db.users')
+ path = Path(self.tempdir) / 'unreadable%20file.parquet'
+ path.write_bytes(b'not parquet')
+ for operation, error in (('get_file_status', PermissionError('access
denied')),
+ ('new_input_stream', PermissionError('access
denied')),
+ ('new_input_stream', FileNotFoundError('file
disappeared'))):
+ with self.subTest(operation=operation, error=error):
+ with patch('pypaimon.cli.cli_table._open_schema_table',
return_value=table), \
+ patch.object(table.file_io, operation,
side_effect=error) as call:
+ out, err, code = self._run_table_command(
+ 'file', 'test_db.users', '--file', 'file:/' +
path.as_posix().lstrip('/'))
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(str(error), err)
+ call.assert_called_once()
+ self.assertEqual(path, Path(call.call_args[0][0]))
+
+ uri = 'file:' + path.as_posix()
+ get_status = table.file_io.get_file_status
+
+ def deny_uri(candidate):
+ if candidate == uri:
+ raise PermissionError('cannot check URI candidate')
+ return get_status(candidate)
+
+ with patch('pypaimon.cli.cli_table._open_schema_table',
return_value=table), \
+ patch.object(table.file_io, 'get_file_status',
side_effect=deny_uri), \
+ patch.object(table.file_io, 'new_input_stream',
+ wraps=table.file_io.new_input_stream) as stream:
+ out, err, code = self._run_table_command('file', 'test_db.users',
'--file', uri)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('cannot check URI candidate', err)
+ stream.assert_not_called()
+
+ missing = (Path(self.tempdir) / 'missing file.parquet').as_uri()
+ out, err, code = self._run_table_command('file', 'test_db.users',
'--file', missing)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('Failed to inspect file', err)
+ self.assertNotIn('Ambiguous --file', err)
+
+ def test_cli_table_file_empty_and_invalid_files(self):
+ import pyarrow.parquet as pq
+
+ path = Path(self.tempdir) / 'empty.parquet'
+ pq.write_table(pa.table({'id': pa.array([], type=pa.int64())}), path)
+ result = json.loads(self._run_table_command_success('file',
'test_db.users', '--file', str(path)))
+ self.assertEqual(0, result['metadata']['num_rows'])
+ renamed = Path(self.tempdir) / 'renamed.avro'
+ renamed.write_bytes(path.read_bytes())
+ corrupt = Path(self.tempdir) / 'corrupt.parquet'
+ corrupt.write_bytes(b'invalid footer')
+ for candidate, message in ((Path(self.tempdir) / 'missing.parquet',
'Failed to inspect file'),
+ (Path(self.tempdir), 'regular file'),
+ (renamed, 'Only Parquet'),
+ (corrupt, 'Failed to inspect file')):
+ with self.subTest(path=candidate):
+ out, err, code = self._run_table_command('file',
'test_db.users', '--file', str(candidate))
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(message, err)
+ if candidate == corrupt:
+ self.assertNotIn('Unsupported file format', err)
+
+ def test_cli_table_files_invalid_arguments(self):
+ for command, args in (
+ ('list-files', ('--snapshot-id', '0')), ('list-files',
('--limit', '-1')),
+ ('list-files', ('--bucket', 'bad')), ('list-files',
('--partition', 'dt=2024-01-01')),
+ ('file', ()), ('file', ('--file', 'data.parquet',
'--snapshot-id', '1')),
+ ('file', ('--file', 'data.parquet', '--limit', '1')),
+ ('file', ('--file', 'data.parquet', '--bucket', '0'))):
+ with self.subTest(command=command, args=args):
+ out, err, code = self._run_table_command(command,
'test_db.users', *args)
+ self.assertEqual(('', 2), (out, code))
+ option = args[2] if len(args) > 2 else args[0] if args else
'--file'
+ self.assertIn(option, err)
+
def test_cli_table_create_with_json_schema(self):
"""Test table create with JSON schema file."""
import json
@@ -2231,13 +2589,12 @@ class CliTableTest(unittest.TestCase):
self.assertIn("Invalid WHERE clause", mock_stderr.getvalue())
def test_cli_table_rollback_to_snapshot(self):
- """table rollback --snapshot restores an earlier snapshot."""
+ """table rollback restores an earlier snapshot with each accepted
spelling."""
pa_schema = pa.schema([('id', pa.int32()), ('name', pa.string())])
schema = Schema.from_pyarrow_schema(pa_schema)
- self.catalog.create_table('test_db.rollback_users', schema, True)
- def _write(row_id, name):
- table = self.catalog.get_table('test_db.rollback_users')
+ def _write(identifier, row_id, name):
+ table = self.catalog.get_table(identifier)
wb = table.new_batch_write_builder()
w = wb.new_write()
c = wb.new_commit()
@@ -2247,28 +2604,23 @@ class CliTableTest(unittest.TestCase):
w.close()
c.close()
- _write(1, 'a') # snapshot 1
- _write(2, 'b') # snapshot 2
-
- def _latest_id():
+ def _latest_id(identifier):
fresh = CatalogFactory.create({'warehouse': self.warehouse})
- return fresh.get_table(
-
'test_db.rollback_users').snapshot_manager().get_latest_snapshot().id
+ return
fresh.get_table(identifier).snapshot_manager().get_latest_snapshot().id
- self.assertEqual(_latest_id(), 2)
+ for option in ('--snapshot-id', '--snapshot', '--snap'):
+ with self.subTest(option=option):
+ identifier = 'test_db.rollback_' +
option.lstrip('-').replace('-', '_')
+ self.catalog.create_table(identifier, schema, True)
+ _write(identifier, 1, 'a') # snapshot 1
+ _write(identifier, 2, 'b') # snapshot 2
+ self.assertEqual(_latest_id(identifier), 2)
- with patch('sys.argv',
- ['paimon', '-c', self.config_file, 'table', 'rollback',
- 'test_db.rollback_users', '--snapshot', '1']):
- with patch('sys.stdout', new_callable=StringIO) as out:
- try:
- main()
- except SystemExit:
- pass
- self.assertIn('Rolled back', out.getvalue())
+ out = self._run_table_command_success('rollback', identifier,
option, '1')
+ self.assertIn('Rolled back', out)
- # The latest snapshot is back to 1 (snapshot 2 was rolled back).
- self.assertEqual(_latest_id(), 1)
+ # The latest snapshot is back to 1 (snapshot 2 was rolled
back).
+ self.assertEqual(_latest_id(identifier), 1)
def test_cli_table_rollback_requires_a_target(self):
"""table rollback without any target selector exits with an error."""