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 af85147a5b [python] Add --snapshot-id to table read and explain for
Python CLI. (#11297)
af85147a5b is described below
commit af85147a5ba0c26a864d809a0a7679834f804d05
Author: Master.TJ <[email protected]>
AuthorDate: Fri Nov 20 22:53:57 2026 +0800
[python] Add --snapshot-id to table read and explain for Python CLI.
(#11297)
---
docs/docs/pypaimon/cli-query.md | 8 +
paimon-python/pypaimon/cli/cli_table.py | 158 +++++++++++-----
paimon-python/pypaimon/tests/cli_table_test.py | 246 +++++++++++++++++++++++++
3 files changed, 361 insertions(+), 51 deletions(-)
diff --git a/docs/docs/pypaimon/cli-query.md b/docs/docs/pypaimon/cli-query.md
index f2681084bd..d297e76cd7 100644
--- a/docs/docs/pypaimon/cli-query.md
+++ b/docs/docs/pypaimon/cli-query.md
@@ -38,6 +38,7 @@ paimon table read mydb.users
**Options:**
- `--select, -s`: Select specific columns to read (comma-separated)
+- `--snapshot-id` reads all rows visible at the specified positive snapshot ID
on the table's branch. Use the column names from that snapshot in `--select`
and `--where`.
- `--where, -w`: Filter condition in SQL-like syntax
- `--limit, -l`: Maximum number of results to display (default: 100)
- `--format, -f`: Output format: `table` (default) or `json`
@@ -51,6 +52,9 @@ paimon table read mydb.users -l 50
# Read specific columns
paimon table read mydb.users -s id,name,age
+# Read the rows visible at snapshot 5 using the column names at that time
+paimon table read mydb.users --snapshot-id 5 -s id,name -w "age >= 20"
+
# Filter with WHERE clause
paimon table read mydb.users --where "age > 18"
@@ -122,6 +126,7 @@ paimon table explain mydb.events
**Options:**
- `--select, -s`: Project specific columns (comma-separated)
+- `--snapshot-id` plans the scan for the specified positive snapshot ID using
the same branch, schema, and selection rules as `table read`.
- `--where, -w`: Filter condition in SQL-like syntax (same operators as `table
read`)
- `--limit, -l`: Row limit to push down
- `--verbose, -v`: List every split with its files
@@ -133,6 +138,9 @@ paimon table explain mydb.events
# Whole-table scan plan
paimon table explain mydb.events
+# Inspect the plan for the snapshot 5 query from the Table Read example
+paimon table explain mydb.users --snapshot-id 5 -s id,name -w "age >= 20"
--verbose
+
# Push filter and projection through the planner
paimon table explain mydb.events --where "dt = '2026-05-16' AND id = 7" -s
dt,id,val
diff --git a/paimon-python/pypaimon/cli/cli_table.py
b/paimon-python/pypaimon/cli/cli_table.py
index e20ba2f20b..4fe6aa453a 100644
--- a/paimon-python/pypaimon/cli/cli_table.py
+++ b/paimon-python/pypaimon/cli/cli_table.py
@@ -59,10 +59,15 @@ def cmd_table_read(args):
database_name, table_name = parts
# Get table
+ snapshot_id = args.snapshot_id
+ target = f"table '{table_identifier}'"
try:
table = catalog.get_table(f"{database_name}.{table_name}")
+ if snapshot_id is not None:
+ target += f" at snapshot {snapshot_id}"
+ _, table = _resolve_snapshot_view(table, snapshot_id)
except Exception as e:
- print(f"Error: Failed to get table '{table_identifier}': {e}",
file=sys.stderr)
+ print(f"Error: Failed to get {target}: {e}", file=sys.stderr)
sys.exit(1)
# Build read pipeline
@@ -117,39 +122,45 @@ def cmd_table_read(args):
read_builder = read_builder.with_limit(limit)
# Scan and read
- scan = read_builder.new_scan()
- plan = scan.plan()
- splits = plan.splits()
+ try:
+ scan = read_builder.new_scan()
+ plan = scan.plan()
+ splits = plan.splits()
- read = read_builder.new_read()
+ read = read_builder.new_read()
- # Read splits incrementally, stopping early when limit is reached
- if limit:
- import pandas as pd
- collected_rows = 0
- table_list = []
- for split in splits:
- if collected_rows >= limit:
- break
- partial_df = read.to_pandas([split])
- collected_rows += len(partial_df)
- table_list.append(partial_df)
- df = pd.concat(table_list, ignore_index=True) if table_list else
read.to_pandas([])
- if len(df) > limit:
- df = df.head(limit)
- else:
- df = read.to_pandas(splits)
+ # Read splits incrementally, stopping early when limit is reached
+ if limit:
+ import pandas as pd
+ collected_rows = 0
+ table_list = []
+ for split in splits:
+ if collected_rows >= limit:
+ break
+ partial_df = read.to_pandas([split])
+ collected_rows += len(partial_df)
+ table_list.append(partial_df)
+ df = pd.concat(table_list, ignore_index=True) if table_list else
read.to_pandas([])
+ if len(df) > limit:
+ df = df.head(limit)
+ else:
+ df = read.to_pandas(splits)
- # Drop extra columns that were added only for where-clause filtering
- if extra_where_columns:
- df = df.drop(columns=extra_where_columns, errors='ignore')
+ # Drop extra columns that were added only for where-clause filtering
+ if extra_where_columns:
+ df = df.drop(columns=extra_where_columns, errors='ignore')
- output_format = getattr(args, 'format', 'table')
- if output_format == 'json':
- import json
- print(json.dumps(df.to_dict(orient='records'), ensure_ascii=False))
- else:
- print(df.to_string(index=False))
+ output_format = getattr(args, 'format', 'table')
+ if output_format == 'json':
+ import json
+ print(json.dumps(df.to_dict(orient='records'), ensure_ascii=False))
+ else:
+ print(df.to_string(index=False))
+ except Exception as e:
+ if snapshot_id is None:
+ raise
+ print(f"Error: Failed to query {target}: {e}", file=sys.stderr)
+ sys.exit(1)
def cmd_table_explain(args):
@@ -159,6 +170,9 @@ def cmd_table_explain(args):
Prints the scan plan (snapshot, pushed-down predicate / projection /
limit, partition / bucket / file-stats pruning funnel and split-
level signals) without reading any data files.
+
+ Args:
+ args: Parsed command line arguments.
"""
from pypaimon.cli.cli import load_catalog_config, create_catalog
@@ -173,10 +187,15 @@ def cmd_table_explain(args):
sys.exit(1)
database_name, table_name = parts
+ snapshot_id = args.snapshot_id
+ target = f"table '{table_identifier}'"
try:
table = catalog.get_table(f"{database_name}.{table_name}")
+ if snapshot_id is not None:
+ target += f" at snapshot {snapshot_id}"
+ _, table = _resolve_snapshot_view(table, snapshot_id)
except Exception as e:
- print(f"Error: Failed to get table '{table_identifier}': {e}",
file=sys.stderr)
+ print(f"Error: Failed to get {target}: {e}", file=sys.stderr)
sys.exit(1)
read_builder = table.new_read_builder()
@@ -214,7 +233,7 @@ def cmd_table_explain(args):
try:
result = read_builder.explain(verbose=verbose)
except Exception as e:
- print(f"Error: Failed to explain table '{table_identifier}': {e}",
file=sys.stderr)
+ print(f"Error: Failed to explain {target}: {e}", file=sys.stderr)
sys.exit(1)
output_format = getattr(args, 'format', 'table')
@@ -613,26 +632,9 @@ def cmd_table_list_files(args):
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()
+ snapshot, view = _resolve_snapshot_view(table, args.snapshot_id,
for_query=False)
+ files = FilesTable(view)._build_arrow_table()
if args.bucket is not None:
import pyarrow.compute as pc
files = files.filter(pc.equal(files.column('bucket'), args.bucket))
@@ -1303,6 +1305,49 @@ def _open_schema_table(args):
sys.exit(1)
+def _resolve_snapshot_view(table, snapshot_id, *, for_query=True):
+ """Pin a file-store scan to one snapshot, using its schema when an ID was
requested."""
+ from pypaimon.table.file_store_table import FileStoreTable
+
+ if not isinstance(table, FileStoreTable):
+ raise ValueError('Reading a snapshot requires a FileStoreTable.')
+ manager = table.snapshot_manager()
+ if snapshot_id is None:
+ snapshot = manager.get_latest_snapshot()
+ return snapshot, table._copy_with_snapshot(snapshot)
+
+ snapshot = manager.get_snapshot_by_id(snapshot_id)
+ if snapshot is None:
+ raise ValueError(f"Snapshot {snapshot_id} not found for table
'{table.identifier.get_full_name()}'.")
+ dynamic_options = getattr(table, '_applied_dynamic_options', {})
+ layout_keys = {'partition.default-name', 'partition.legacy-name',
'data-file.path-directory'}
+ if snapshot.schema_id == table.table_schema.id and (not for_query or
layout_keys.isdisjoint(dynamic_options)):
+ return snapshot, table._copy_with_snapshot(snapshot)
+ 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}.")
+ options = table._exclude_current_schema_field_options(schema,
table.options.options, set(dynamic_options))
+ if for_query:
+ # Use the snapshot's directory layout and honor explicit overrides of
its merge options.
+ merge_keys = {'bucket', 'bucket-key', 'merge-engine',
'sequence.field', 'sequence.field.sort-order',
+ 'ignore-delete', 'changelog-producer',
'deletion-vectors.enabled',
+ 'deletion-vectors.merge-on-read'}
+ prefixes = ('fields.', 'aggregation.', 'partial-update.',
'deduplicate.', 'first-row.')
+ merge_keys.update(key for key in options.keys() |
schema.options.keys() if key.startswith(prefixes))
+ for key in layout_keys | (merge_keys - dynamic_options.keys()):
+ if key in schema.options:
+ options[key] = schema.options[key]
+ else:
+ options.pop(key, None)
+ view = FileStoreTable(table.file_io, table.identifier, table.table_path,
+ schema.copy(new_options=options),
table.catalog_environment)
+ view._applied_dynamic_options = dict(dynamic_options)
+ return snapshot, view._copy_with_snapshot(snapshot)
+
+
def _open_snapshot_manager(args):
"""Load a file-store table for the snapshot inspection commands."""
from pypaimon.cli.cli import load_catalog_config, create_catalog
@@ -1457,6 +1502,12 @@ def add_table_subcommands(table_parser):
'table',
help='Table identifier in format: database.table'
)
+ read_parser.add_argument(
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Read the table at this snapshot ID using its schema'
+ )
+ # Preserve --s as an abbreviation for --select alongside --snapshot-id.
+ read_parser.add_argument('--s', dest='select', default=argparse.SUPPRESS,
help=argparse.SUPPRESS)
read_parser.add_argument(
'--select', '-s',
type=str,
@@ -1495,6 +1546,11 @@ def add_table_subcommands(table_parser):
'table',
help='Table identifier in format: database.table'
)
+ explain_parser.add_argument(
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Explain the table scan at this snapshot ID using its schema'
+ )
+ explain_parser.add_argument('--s', dest='select',
default=argparse.SUPPRESS, help=argparse.SUPPRESS)
explain_parser.add_argument(
'--select', '-s',
type=str,
diff --git a/paimon-python/pypaimon/tests/cli_table_test.py
b/paimon-python/pypaimon/tests/cli_table_test.py
index 5757cc5fcb..05282ee67f 100644
--- a/paimon-python/pypaimon/tests/cli_table_test.py
+++ b/paimon-python/pypaimon/tests/cli_table_test.py
@@ -214,6 +214,252 @@ class CliTableTest(unittest.TestCase):
self.assertEqual('', err)
return out
+ def _append_table_row(self, identifier, **values):
+ builder = self.catalog.get_table(identifier).new_batch_write_builder()
+ writer = builder.new_write()
+ commit = builder.new_commit()
+ try:
+ columns = {
+ name: pa.array([value.as_py()], type=value.type) if
isinstance(value, pa.Scalar) else [value]
+ for name, value in values.items()
+ }
+ writer.write_arrow(pa.Table.from_pydict(columns))
+ commit.commit(writer.prepare_commit())
+ finally:
+ writer.close()
+ commit.close()
+
+ def test_cli_table_read_explain_snapshot_schema(self):
+ from pypaimon.schema.data_types import AtomicType
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_schema_reads'
+ schema = pa.schema([('id', pa.int64()), ('message', pa.string())])
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(schema), False)
+ self._append_table_row(identifier, id=1, message='old')
+ self.catalog.alter_table(identifier,
[SchemaChange.rename_column('message', 'body')])
+ self._append_table_row(identifier, id=2, body='new')
+ self._append_table_row(identifier, id=3, body='later')
+
+ def read(*args):
+ return json.loads(self._run_table_command_success('read',
identifier, *args, '-f', 'json'))
+
+ self.assertEqual([{'id': 1, 'message': 'old'}], read('--snapshot-id',
'1'))
+ self.assertEqual([{'id': 1}], read('--snapshot-id', '1', '--s', 'id',
'-w', "message = 'old'", '-l', '1'))
+ self.assertCountEqual([{'id': 1, 'body': 'old'}, {'id': 2, 'body':
'new'}], read('--snapshot-id', '2'))
+ self.assertCountEqual([{'id': 1}, {'id': 2}, {'id': 3}], read('-s',
'id'))
+ self.assertEqual(1, len(read('--snapshot-id', '2', '-l', '1')))
+ plan = json.loads(self._run_table_command_success(
+ 'explain', identifier, '--snapshot-id', '1', '--s', 'id', '-w',
"message = 'old'",
+ '-l', '1', '-f', 'json'))
+ self.assertEqual((1, 0, ['id'], 1), (plan['snapshot_id'],
plan['schema_id'], plan['projection'], plan['limit']))
+ self.assertIn('message', plan['predicate'])
+ verbose_plan = self._run_table_command_success('explain', identifier,
'--snapshot-id', '2', '--verbose')
+ self.assertRegex(verbose_plan, r'Snapshot:\s+2\s+\(schema 1\)')
+ self.assertRegex(verbose_plan, r'(?m)^ +file: \S')
+ self.assertIn('old', self._run_table_command_success('read',
identifier, '--snapshot-id', '1', '-s', 'message'))
+
+ for command in ('read', 'explain'):
+ for option, value in (('--select', 'body'), ('--where', "body =
'new'")):
+ with self.subTest(command=command, option=option):
+ out, err, code = self._run_table_command(command,
identifier, '--snapshot-id', '1', option, value)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('body', err)
+
+ # Reusing a name gets a new field ID, even before a fourth data
snapshot exists.
+ self.catalog.alter_table(identifier, [SchemaChange.drop_column('body'),
+
SchemaChange.add_column('message', AtomicType('STRING'))])
+ self.assertEqual([{'message': 'old'}], read('--snapshot-id', '1',
'-s', 'message'))
+ self.assertEqual([{'message': None}] * 3, read('-s', 'message'))
+
+ def test_cli_table_read_snapshot_aggregation(self):
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_aggregation'
+ schema = pa.schema([('id', pa.int64()), ('v', pa.int64())])
+ options = {'bucket': '1', 'merge-engine': 'aggregation',
'fields.v.aggregate-function': 'sum',
+ 'write-only': 'true'}
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(schema, primary_keys=['id'], options=options),
+ False)
+ self._append_table_row(identifier, id=1, v=4)
+ self._append_table_row(identifier, id=1, v=6)
+ self.catalog.alter_table(identifier,
[SchemaChange.set_option('fields.v.aggregate-function', 'max')])
+ self._append_table_row(identifier, id=2, v=3)
+
+ rows = json.loads(self._run_table_command_success('read', identifier,
'--snapshot-id', '2', '-f', 'json'))
+ self.assertEqual([{'id': 1, 'v': 10}], rows)
+ latest = json.loads(self._run_table_command_success('read',
identifier, '-f', 'json'))
+ self.assertCountEqual([{'id': 1, 'v': 6}, {'id': 2, 'v': 3}], latest)
+ table = self.catalog.get_table(identifier)
+ for override, expected in (('min', 4), (None, 6)):
+ view =
table.copy_without_time_travel({'fields.v.aggregate-function': override})
+ with self.subTest(override=override),
patch.object(type(self.catalog), 'get_table', return_value=view):
+ rows = json.loads(self._run_table_command_success(
+ 'read', identifier, '--snapshot-id', '2', '-f', 'json'))
+ self.assertEqual([{'id': 1, 'v': expected}], rows)
+
+ def test_cli_table_read_snapshot_sequence_field(self):
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_sequence'
+ schema = pa.schema([('id', pa.int64()), ('seq', pa.int64())])
+ options = {'bucket': '1', 'sequence.field': 'seq', 'write-only':
'true'}
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(schema, primary_keys=['id'], options=options),
+ False)
+ self._append_table_row(identifier, id=1, seq=20)
+ self._append_table_row(identifier, id=1, seq=10)
+ self.catalog.alter_table(identifier,
[SchemaChange.rename_column('seq', 'rev'),
+
SchemaChange.set_option('sequence.field.sort-order', 'descending')])
+
+ rows = json.loads(self._run_table_command_success('read', identifier,
'--snapshot-id', '2', '-f', 'json'))
+ self.assertEqual([{'id': 1, 'seq': 20}], rows)
+
+ def
test_cli_table_read_explain_snapshot_deletion_vectors_merge_on_read(self):
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_deletion_vectors'
+ key = 'deletion-vectors.merge-on-read'
+ schema = pa.schema([('id', pa.int64())])
+ options = {'bucket': '1', 'deletion-vectors.enabled': 'true',
'write-only': 'true'}
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(schema, primary_keys=['id'], options=options),
+ False)
+
+ # Each commit adds one level-0 file. The option in that snapshot
determines its visibility.
+ for snapshot_id, change, expected in (
+ (1, SchemaChange.set_option(key, 'true'), []),
+ (2, SchemaChange.remove_option(key), [{'id': 1}, {'id': 2}])):
+ self._append_table_row(identifier, id=snapshot_id)
+ self.catalog.alter_table(identifier, [change])
+ args = (identifier, '--snapshot-id', str(snapshot_id), '-f',
'json')
+ with self.subTest(snapshot_id=snapshot_id):
+ rows = json.loads(self._run_table_command_success('read',
*args))
+ plan = json.loads(self._run_table_command_success('explain',
*args))
+ self.assertCountEqual(expected, rows)
+ self.assertEqual(len(expected), plan['file_count'])
+
+ def test_cli_table_read_explain_snapshot_partition_paths(self):
+ from contextlib import closing
+
+ from pypaimon.schema.schema_change import SchemaChange
+
+ for suffix, pt, option, value, names in (
+ ('null', pa.scalar(None, pa.string()),
'partition.default-name', 'EMPTY',
+ ('__DEFAULT_PARTITION__', 'EMPTY')),
+ ('date', pa.scalar(date(1970, 1, 2), pa.date32()),
'partition.legacy-name', 'false',
+ ('1', '1970-01-02'))):
+ identifier = 'test_db.snapshot_partition_' + suffix
+ schema = pa.schema([('id', pa.int64()), ('pt', pt.type)])
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(schema, partition_keys=['pt']), False)
+ self._append_table_row(identifier, id=1, pt=pt)
+ self.catalog.alter_table(identifier,
[SchemaChange.set_option(option, value)])
+ table = self.catalog.get_table(identifier)
+ # Replace the old data so each snapshot uses a single partition
layout.
+ with closing(table.new_batch_write_builder().new_commit()) as
commit:
+ commit.truncate_table()
+ self._append_table_row(identifier, id=2, pt=pt)
+
+ for snapshot_id, row_id, name, override in ((1, 1, names[0],
value), (3, 2, names[1], None)):
+ with self.subTest(option=option, snapshot=snapshot_id):
+ args = (identifier, '--snapshot-id', str(snapshot_id))
+ plan = self._run_table_command_success('explain', *args,
'--verbose')
+ planned = [Path(line.split('file: ', 1)[1]) for line in
plan.splitlines()
+ if line.lstrip().startswith('file: ')]
+ path = next((Path(table.table_path) / ('pt=' +
name)).rglob('*.parquet'))
+ self.assertEqual([path], planned)
+ read_args = ('read', *args, '-s', 'id', '-f', 'json')
+ rows =
json.loads(self._run_table_command_success(*read_args))
+ self.assertEqual([{'id': row_id}], rows)
+
+ # A catalog override cannot move files already written
with the old layout.
+ view = table.copy_without_time_travel({option: override})
+ with patch.object(type(self.catalog), 'get_table',
return_value=view):
+ self.assertEqual(rows,
json.loads(self._run_table_command_success(*read_args)))
+
+ def test_cli_table_read_explain_snapshot_branch_and_selectors(self):
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_branch_reads'
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(pa.schema([('id', pa.int64())])), False)
+ self._append_table_row(identifier, id=1)
+ self.catalog.get_table(identifier).create_tag('base')
+ self.catalog.create_branch(identifier, 'dev', 'base')
+ branch = identifier + '$branch_dev'
+ self._append_table_row(branch, id=20)
+ self._append_table_row(identifier, id=2)
+
+ for name, extra_id in ((branch, 20), (identifier, 2)):
+ rows = json.loads(self._run_table_command_success('read', name,
'--snapshot-id', '2', '-f', 'json'))
+ self.assertCountEqual([{'id': 1}, {'id': extra_id}], rows)
+ plan = json.loads(self._run_table_command_success('explain', name,
'--snapshot-id', '2', '-f', 'json'))
+ self.assertEqual((name, 2), (plan['table_identifier'],
plan['snapshot_id']))
+
+ for key, value, default_id in (('scan.tag-name', 'base', 1),
('incremental-between', '1,2', 2)):
+ with self.subTest(key=key):
+ self.catalog.alter_table(identifier,
[SchemaChange.set_option(key, value)])
+ self.assertEqual([{'id': default_id}],
json.loads(self._run_table_command_success(
+ 'read', identifier, '-f', 'json')))
+ rows = json.loads(self._run_table_command_success(
+ 'read', identifier, '--snapshot-id', '2', '-f', 'json'))
+ self.assertCountEqual([{'id': 1}, {'id': 2}], rows)
+ plan = json.loads(self._run_table_command_success(
+ 'explain', identifier, '--snapshot-id', '2', '-f', 'json'))
+ self.assertEqual((2, 2), (plan['snapshot_id'],
plan['estimated_row_count']))
+ self.catalog.alter_table(identifier,
[SchemaChange.remove_option(key)])
+
+ # The tag still retains snapshot 1 after its numbered snapshot file
expires.
+ table = self.catalog.get_table(identifier)
+ os.remove(table.snapshot_manager().get_snapshot_path(1))
+ for command in ('read', 'explain'):
+ out, err, code = self._run_table_command(command, identifier,
'--snapshot-id', '1')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('Snapshot 1 not found', err)
+
+ def test_cli_table_read_explain_snapshot_query_auth(self):
+ from pypaimon.schema.schema_change import SchemaChange
+
+ identifier = 'test_db.snapshot_authorized_reads'
+ self.catalog.create_table(identifier,
Schema.from_pyarrow_schema(pa.schema([('id', pa.int64())])), False)
+ self._append_table_row(identifier, id=1)
+ self.catalog.alter_table(identifier,
[SchemaChange.set_option('query-auth.enabled', 'true')])
+ for command in ('read', 'explain'):
+ denial = PermissionError('catalog denied SELECT')
+ with self.subTest(command=command), patch.object(
+ type(self.catalog), 'auth_table_query',
side_effect=denial) as auth:
+ out, err, code = self._run_table_command(command, identifier,
'--snapshot-id', '1')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('catalog denied SELECT', err)
+ auth.assert_called_once()
+
+ def test_cli_table_read_explain_snapshot_errors(self):
+ identifier, _ = self._create_snapshot_table([
+ self._snapshot(3, schema_id=99), self._snapshot(4,
schema_id=None)])
+ empty, _ = self._create_snapshot_table([], suffix='empty')
+ for command in ('read', 'explain'):
+ for target, snapshot_id, message in (
+ (empty, '1', 'not found'), (identifier, '2', 'not found'),
(identifier, '3', 'Schema 99'),
+ (identifier, '4', 'does not contain a schema ID'),
+ (identifier + '$snapshots', '3', 'FileStoreTable')):
+ with self.subTest(command=command, target=target,
snapshot_id=snapshot_id):
+ out, err, code = self._run_table_command(command, target,
'--snapshot-id', snapshot_id)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(target, err)
+ self.assertIn(snapshot_id, err)
+ self.assertIn(message, err)
+ with patch.object(SnapshotManager, 'get_snapshot_by_id',
side_effect=OSError('metadata unavailable')):
+ out, err, code = self._run_table_command(command, identifier,
'--snapshot-id', '3')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('metadata unavailable', err)
+ self.assertIn(identifier, err)
+ self.assertIn('3', err)
+ for invalid in ('0', '-1', 'abc'):
+ with self.subTest(command=command, invalid=invalid):
+ out, err, code = self._run_table_command(command,
identifier, '--snapshot-id', invalid)
+ self.assertEqual(('', 2), (out, code))
+ self.assertIn('positive integer', err)
+ help_text = self._run_table_command_success(command, '--help')
+ self.assertIn('--snapshot-id', help_text)
+ self.assertNotRegex(help_text, r'--s\b')
+
def test_cli_table_read_basic(self):
"""Test basic table read via CLI."""
# Simulate CLI command: paimon -c <config> table read test_db.users