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 530263ea46 [python] Add list snapshots & lookup by snapshot-id support
for Python CLI. (#11094)
530263ea46 is described below
commit 530263ea4609757722ab61e564063702b7f286fa
Author: Master.TJ <[email protected]>
AuthorDate: Wed Nov 11 17:36:35 2026 +0800
[python] Add list snapshots & lookup by snapshot-id support for Python CLI.
(#11094)
---
docs/docs/pypaimon/cli-query.md | 51 ++++-
docs/docs/pypaimon/cli.md | 2 +
paimon-python/pypaimon/cli/cli_table.py | 188 ++++++++++++++----
paimon-python/pypaimon/tests/cli_table_test.py | 263 ++++++++++++++++++++++---
4 files changed, 439 insertions(+), 65 deletions(-)
diff --git a/docs/docs/pypaimon/cli-query.md b/docs/docs/pypaimon/cli-query.md
index 109ca465c4..7561e3ca96 100644
--- a/docs/docs/pypaimon/cli-query.md
+++ b/docs/docs/pypaimon/cli-query.md
@@ -207,12 +207,29 @@ Output:
## Table Snapshot
-Get and display the latest snapshot information of a Paimon table in JSON
format. The snapshot contains metadata about the current state of the table.
+Get the latest snapshot or inspect a specific retained snapshot. JSON remains
the default output
+format for compatibility with existing scripts. The snapshot includes its
schema ID, manifest-list
+references, commit information, record counts, and other available metadata.
```shell
paimon table snapshot mydb.users
+
+# Inspect a historical snapshot without falling back to the latest snapshot
+paimon table snapshot mydb.users --snapshot-id 42 --format json
+
+# Display all available fields as a readable table
+paimon table snapshot mydb.users --snapshot-id 42 --format table
```
+**Options:**
+
+- `--snapshot-id`: Positive snapshot ID to inspect. Omit it to resolve the
latest snapshot once.
+- `--format, -f`: Output format: `json` (default) or `table`. Table output
includes the UTC commit
+ time alongside the original epoch-millisecond value.
+
+The command fails with a non-zero exit status if the table has no snapshots,
the requested snapshot
+is unavailable, or its metadata cannot be read. Errors are written to stderr.
+
Output:
```json
{
@@ -235,6 +252,38 @@ Output:
}
```
+## Table List Snapshots
+
+List retained snapshots in ascending numeric snapshot-ID order. The default
table output shows
+the snapshot ID, schema ID, commit time in UTC, commit kind, commit user, and
total, delta, and
+changelog record counts. Missing optional counts are displayed as `-`.
+
+```shell
+# List all available snapshots, oldest first
+paimon table list-snapshots mydb.users
+
+# Show the first 20 snapshots in that order
+paimon table list-snapshots mydb.users --limit 20
+
+# Export complete snapshot metadata as a JSON array
+paimon table list-snapshots mydb.users --format json
+```
+
+**Options:**
+
+- `--limit, -l`: Maximum number of snapshots to display; must be a positive
integer.
+ Omit it to list all available snapshots.
+- `--format, -f`: Output format: `table` (default) or `json`.
+
+JSON output contains the same snapshot objects as `table snapshot`, preserving
metadata field
+names such as `schemaId`, `timeMillis`, and `baseManifestList`. Timestamps
remain epoch milliseconds
+and record counts remain integers. Optional fields with no value are omitted.
+
+An empty table returns an empty JSON array or a `No snapshots found` message,
with a successful
+exit status. Expired snapshots are not reconstructed. If a snapshot disappears
during listing,
+it is skipped; other metadata read errors fail the command. These commands
read snapshot metadata
+without opening manifest or data files or modifying the table.
+
## 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 d31cfaee73..e718375cbf 100644
--- a/docs/docs/pypaimon/cli.md
+++ b/docs/docs/pypaimon/cli.md
@@ -102,6 +102,7 @@ The query returns the row with `id` 2 and `name` `Bob`.
Inspect what you created
```shell
paimon table get demo.people
+paimon table list-snapshots demo.people --limit 20
paimon table snapshot demo.people
paimon table explain demo.people --where "id = 2"
```
@@ -112,6 +113,7 @@ paimon table explain demo.people --where "id = 2"
<span id="table-explain"></span>
<span id="table-get"></span>
<span id="table-snapshot"></span>
+<span id="table-list-snapshots"></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 dc6f9d6481..5e43a65c0d 100644
--- a/paimon-python/pypaimon/cli/cli_table.py
+++ b/paimon-python/pypaimon/cli/cli_table.py
@@ -21,8 +21,11 @@ Table commands for Paimon CLI.
This module provides table-related commands for the CLI.
"""
+import argparse
+import json
import sys
from dataclasses import asdict
+from datetime import datetime, timedelta, timezone
from pypaimon.common.json_util import JSON
@@ -363,53 +366,77 @@ def cmd_table_snapshot(args):
Args:
args: Parsed command line arguments.
"""
- from pypaimon.cli.cli import load_catalog_config, create_catalog
- from pypaimon.table.file_store_table import FileStoreTable
-
- # Load catalog configuration
- config_path = args.config
- config = load_catalog_config(config_path)
-
- # Create catalog
- catalog = create_catalog(config)
-
- # Parse table identifier
- table_identifier = args.table
- parts = table_identifier.split('.')
- if len(parts) != 2:
- print(f"Error: Invalid table identifier '{table_identifier}'. "
- f"Expected format: 'database.table'", file=sys.stderr)
- sys.exit(1)
-
- database_name, table_name = parts
-
- # Get table
+ manager = _open_snapshot_manager(args)
+ snapshot_id = getattr(args, 'snapshot_id', None)
try:
- table = catalog.get_table(f"{database_name}.{table_name}")
+ snapshot = (
+ # Get latest snapshot
+ manager.get_latest_snapshot() if snapshot_id is None
+ else manager.get_snapshot_by_id(snapshot_id)
+ )
+ if snapshot is None:
+ if snapshot_id is None:
+ raise ValueError(f"No snapshot found for table
'{args.table}'.")
+ raise ValueError(f"Snapshot {snapshot_id} not found for table
'{args.table}'.")
+
+ if getattr(args, 'format', 'json') == 'json':
+ # Output snapshot as JSON
+ print(JSON.to_json(snapshot, indent=2))
+ else:
+ import pandas as pd
+ values = json.loads(JSON.to_json(snapshot))
+ rows = [[key, _snapshot_display_value(value)] for key, value in
values.items()]
+ for row in rows:
+ if row[0] == 'timeMillis':
+ row[1] += '
({})'.format(_snapshot_commit_time(snapshot.time_millis))
+ print(pd.DataFrame(rows, columns=['Field',
'Value']).to_string(index=False))
except Exception as e:
- print(f"Error: Failed to get table '{table_identifier}': {e}",
file=sys.stderr)
+ target = 'latest snapshot' if snapshot_id is None else f'snapshot
{snapshot_id}'
+ print(f"Error: Failed to get {target} for table '{args.table}': {e}",
file=sys.stderr)
sys.exit(1)
+
+
+def cmd_table_list_snapshots(args):
+ """
+ Execute the 'table list-snapshots' command.
- # Check if table is FileStoreTable
- if not isinstance(table, FileStoreTable):
- print(f"Error: Table '{table_identifier}' is not a FileStoreTable. "
- f"Snapshot operation is not supported for this table type.",
file=sys.stderr)
- sys.exit(1)
+ Lists retained snapshots in ascending snapshot-ID order without reading
table data.
- # Get latest snapshot
+ Args:
+ args: Parsed command line arguments.
+ """
+ manager = _open_snapshot_manager(args)
try:
- snapshot_manager = table.snapshot_manager()
- snapshot = snapshot_manager.get_latest_snapshot()
-
- if snapshot is None:
- print(f"Error: No snapshot found for table '{table_identifier}'.",
file=sys.stderr)
- sys.exit(1)
-
- # Output snapshot as JSON
- print(JSON.to_json(snapshot, indent=2))
+ snapshots = []
+ for snapshot_id in manager.list_snapshot_ids():
+ try:
+ snapshot = manager.get_snapshot_by_id(snapshot_id)
+ except FileNotFoundError:
+ # Expiration can remove a file between listing and opening it.
+ continue
+ if snapshot is None:
+ continue
+ snapshots.append(snapshot)
+ if args.limit is not None and len(snapshots) >= args.limit:
+ break
+ if args.format == 'json':
+ # Preserve Snapshot's JSON field names, optional values and
integers.
+ print(json.dumps([json.loads(JSON.to_json(s)) for s in snapshots],
ensure_ascii=False, indent=2))
+ elif not snapshots:
+ print(f"No snapshots found for table '{args.table}'.")
+ else:
+ import pandas as pd
+ rows = [[s.id, s.schema_id, _snapshot_commit_time(s.time_millis),
+ s.commit_kind, s.commit_user, s.total_record_count,
+ s.delta_record_count, s.changelog_record_count] for s in
snapshots]
+ # Convert before Pandas can coerce nullable integers to floats.
+ rows = [[_snapshot_display_value(value) for value in row] for row
in rows]
+ columns = ['Snapshot ID', 'Schema ID', 'Commit Time (UTC)',
'Commit Kind',
+ 'Commit User', 'Total Records', 'Delta Records',
'Changelog Records']
+ print(pd.DataFrame(rows, columns=columns).to_string(index=False))
except Exception as e:
- print(f"Error: Failed to get snapshot: {e}", file=sys.stderr)
+ print(f"Error: Failed to list snapshots for table '{args.table}':
{e}", file=sys.stderr)
sys.exit(1)
@@ -928,6 +955,39 @@ def cmd_table_drop_partition(args):
sys.exit(1)
+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
+ from pypaimon.table.file_store_table import FileStoreTable
+
+ # Parse table identifier
+ table_identifier = args.table
+ parts = table_identifier.split('.')
+ if len(parts) != 2 or not all(parts):
+ print(f"Error: Invalid table identifier '{table_identifier}'. "
+ f"Expected format: 'database.table'", file=sys.stderr)
+ sys.exit(1)
+
+ try:
+ # Load catalog configuration
+ config = load_catalog_config(args.config)
+
+ # Create catalog
+ catalog = create_catalog(config)
+
+ # Get table
+ table = catalog.get_table(table_identifier)
+
+ # Check if table is FileStoreTable
+ if not isinstance(table, FileStoreTable):
+ raise ValueError('Snapshot operation is not supported for this
table type; '
+ 'expected a FileStoreTable.')
+ return table.snapshot_manager()
+ except Exception as e:
+ print(f"Error: Failed to get table '{table_identifier}': {e}",
file=sys.stderr)
+ sys.exit(1)
+
+
def add_table_subcommands(table_parser):
"""
Add table subcommands to the parser.
@@ -1023,13 +1083,36 @@ def add_table_subcommands(table_parser):
get_parser.set_defaults(func=cmd_table_get)
# table snapshot command
- snapshot_parser = table_subparsers.add_parser('snapshot', help='Get the
latest snapshot of a table')
+ snapshot_parser = table_subparsers.add_parser('snapshot', help='Get the
latest or a specific snapshot of a table')
snapshot_parser.add_argument(
'table',
help='Table identifier in format: database.table'
)
+ snapshot_parser.add_argument(
+ '--snapshot-id', type=_positive_int, default=None,
+ help='Snapshot ID to inspect (default: the latest snapshot)'
+ )
+ snapshot_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='json',
+ help='Output format: json (default) or table'
+ )
snapshot_parser.set_defaults(func=cmd_table_snapshot)
+ # table list-snapshots command
+ list_snapshots_parser = table_subparsers.add_parser(
+ 'list-snapshots', help='List available snapshots in ascending
snapshot-ID order'
+ )
+ list_snapshots_parser.add_argument('table', help='Table identifier in
format: database.table')
+ list_snapshots_parser.add_argument(
+ '--limit', '-l', type=_positive_int, default=None,
+ help='Maximum number of snapshots to display, starting with the oldest
(default: all)'
+ )
+ list_snapshots_parser.add_argument(
+ '--format', '-f', choices=['table', 'json'], default='table',
+ help='Output format: table (default) or json'
+ )
+ list_snapshots_parser.set_defaults(func=cmd_table_list_snapshots)
+
# table rollback command
rollback_parser = table_subparsers.add_parser(
'rollback',
@@ -1242,3 +1325,28 @@ def add_table_subcommands(table_parser):
update_comment_parser = alter_subparsers.add_parser('update-comment',
help='Update table comment')
update_comment_parser.add_argument('--comment', '-c', required=True,
help='New table comment')
update_comment_parser.set_defaults(func=cmd_table_alter)
+
+
+def _positive_int(value):
+ """Argparse type for snapshot IDs and result limits."""
+ try:
+ number = int(value)
+ if number > 0:
+ return number
+ except ValueError:
+ pass
+ raise argparse.ArgumentTypeError('must be a positive integer')
+
+
+def _snapshot_commit_time(time_millis):
+ # Keep millisecond precision and make the display independent of local TZ.
+ instant = datetime(1970, 1, 1, tzinfo=timezone.utc) +
timedelta(milliseconds=time_millis)
+ return instant.isoformat(timespec='milliseconds').replace('+00:00', 'Z')
+
+
+def _snapshot_display_value(value):
+ if value is None:
+ return '-'
+ if isinstance(value, (dict, list)):
+ return json.dumps(value, ensure_ascii=False)
+ return str(value)
diff --git a/paimon-python/pypaimon/tests/cli_table_test.py
b/paimon-python/pypaimon/tests/cli_table_test.py
index 1752e07397..5fab4ab9a2 100644
--- a/paimon-python/pypaimon/tests/cli_table_test.py
+++ b/paimon-python/pypaimon/tests/cli_table_test.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
+import json
import os
import shutil
import tempfile
@@ -27,6 +28,10 @@ import pytest
from pypaimon import CatalogFactory, Schema
from pypaimon.cli.cli import main
+from pypaimon.common.json_util import JSON
+from pypaimon.schema.data_types import DataField
+from pypaimon.snapshot.snapshot import Snapshot
+from pypaimon.snapshot.snapshot_manager import SnapshotManager
class CliTableTest(unittest.TestCase):
@@ -91,6 +96,60 @@ class CliTableTest(unittest.TestCase):
table_write.close()
table_commit.close()
+ @staticmethod
+ def _snapshot(snapshot_id, **overrides):
+ values = dict(version=3, id=snapshot_id, schema_id=0,
+ base_manifest_list='base-{}'.format(snapshot_id),
+ delta_manifest_list='delta-{}'.format(snapshot_id),
+ total_record_count=3, delta_record_count=3,
+ commit_user='user-{}'.format(snapshot_id),
commit_identifier=100,
+ commit_kind='APPEND', time_millis=1700000000123,
uuid=None)
+ values.update(overrides)
+ return Snapshot(**values)
+
+ def _create_snapshot_table(self, snapshots=None, primary_keys=None,
options=None, suffix='snapshots'):
+ """Create isolated metadata in the shared catalog without manifest or
data files."""
+ identifier = 'test_db.{}_{}'.format(self._testMethodName, suffix)
+ fields = [DataField.from_dict({'id': 0, 'name': 'id', 'type': 'INT NOT
NULL'})]
+ self.catalog.create_table(identifier, Schema(fields=fields,
primary_keys=primary_keys, options=options), False)
+ table = self.catalog.get_table(identifier)
+ manager = table.snapshot_manager()
+ if snapshots is None:
+ # Deliberately unordered, non-contiguous IDs distinguish numeric
ordering
+ # from lexical ordering. Referenced manifests/data files do not
exist.
+ snapshots = [
+ self._snapshot(10, schema_id=2,
total_record_count=9007199254740993,
+ next_row_id=9007199254740993,
properties={'job': 'test'},
+ writer_version='test-writer', watermark=0),
+ self._snapshot(2, schema_id=1, commit_kind='COMPACT',
delta_record_count=0,
+ changelog_record_count=0,
changelog_manifest_list='changelog-2'),
+ self._snapshot(1, total_record_count=0, delta_record_count=0),
+ ]
+ if snapshots:
+ table.file_io.mkdirs(manager.snapshot_dir)
+ for snapshot in snapshots:
+
table.file_io.try_to_write_atomic(manager.get_snapshot_path(snapshot.id),
JSON.to_json(snapshot))
+ table.file_io.try_to_write_atomic(manager.latest_file,
str(max(s.id for s in snapshots)))
+ return identifier, table
+
+ def _run_table_command(self, *argv, config=None):
+ """Run a table command and capture stdout, stderr and the exit code."""
+ out, err = StringIO(), StringIO()
+ code = 0
+ with patch('sys.argv', ['paimon', '-c', config or self.config_file,
'table'] + list(argv)):
+ with patch('sys.stdout', out), patch('sys.stderr', err):
+ try:
+ main()
+ except SystemExit as e:
+ code = e.code
+ return out.getvalue(), err.getvalue(), code
+
+ def _run_table_command_success(self, *argv):
+ out, err, code = self._run_table_command(*argv)
+ self.assertEqual(0, code, err)
+ self.assertEqual('', err)
+ return out
+
def test_cli_table_read_basic(self):
"""Test basic table read via CLI."""
# Simulate CLI command: paimon -c <config> table read test_db.users
@@ -214,30 +273,186 @@ class CliTableTest(unittest.TestCase):
def test_cli_table_snapshot_basic(self):
"""Test basic table snapshot via CLI."""
# Simulate CLI command: paimon -c <config> table snapshot test_db.users
- with patch('sys.argv', ['paimon', '-c', self.config_file, 'table',
'snapshot', 'test_db.users']):
- with patch('sys.stdout', new_callable=StringIO) as mock_stdout:
- try:
- main()
- except SystemExit:
- pass
-
- output = mock_stdout.getvalue()
-
- # Verify output is valid JSON
- import json
- snapshot_json = json.loads(output)
-
- # Verify snapshot structure
- self.assertIn('id', snapshot_json)
- self.assertIn('schemaId', snapshot_json)
- self.assertIn('commitKind', snapshot_json)
- self.assertIn('timeMillis', snapshot_json)
- self.assertIn('totalRecordCount', snapshot_json)
- self.assertIn('deltaRecordCount', snapshot_json)
-
- # Verify snapshot has valid data
- self.assertGreater(snapshot_json['id'], 0)
- self.assertGreater(snapshot_json['totalRecordCount'], 0)
+ manager = self.catalog.get_table('test_db.users').snapshot_manager()
+ # A second lookup could observe a different concurrent commit.
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
wraps=manager.get_latest_snapshot) as latest:
+ output = self._run_table_command_success('snapshot',
'test_db.users')
+ latest.assert_called_once_with()
+
+ # Verify output is valid JSON
+ snapshot_json = json.loads(output)
+
+ # Verify snapshot structure
+ self.assertIn('id', snapshot_json)
+ self.assertIn('schemaId', snapshot_json)
+ self.assertIn('commitKind', snapshot_json)
+ self.assertIn('timeMillis', snapshot_json)
+ self.assertIn('totalRecordCount', snapshot_json)
+ self.assertIn('deltaRecordCount', snapshot_json)
+
+ # Verify snapshot has valid data
+ self.assertGreater(snapshot_json['id'], 0)
+ self.assertGreater(snapshot_json['totalRecordCount'], 0)
+
+ def test_cli_table_list_snapshots_json(self):
+ identifier, _ = self._create_snapshot_table()
+ snapshots =
json.loads(self._run_table_command_success('list-snapshots', identifier, '-f',
'json'))
+ self.assertEqual([1, 2, 10], [s['id'] for s in snapshots])
+ self.assertEqual([0, 1, 2], [s['schemaId'] for s in snapshots])
+ self.assertEqual(0, snapshots[0]['totalRecordCount'])
+ self.assertNotIn('changelogRecordCount', snapshots[0])
+ self.assertEqual(0, snapshots[1]['changelogRecordCount'])
+ self.assertEqual('COMPACT', snapshots[1]['commitKind'])
+ self.assertEqual('changelog-2', snapshots[1]['changelogManifestList'])
+ self.assertEqual(9007199254740993, snapshots[2]['totalRecordCount'])
+ self.assertIsInstance(snapshots[2]['totalRecordCount'], int)
+ self.assertEqual({'job': 'test'}, snapshots[2]['properties'])
+ self.assertEqual(1700000000123, snapshots[2]['timeMillis'])
+
+ def test_cli_table_list_snapshots_format_table(self):
+ identifier, _ = self._create_snapshot_table()
+ out = self._run_table_command_success('list-snapshots', identifier)
+ for text in ('Schema', 'Commit', 'Total', 'Delta', 'Changelog',
+ 'user-2', 'COMPACT', '2023-11-14T22:13:20.123Z',
'9007199254740993'):
+ self.assertIn(text, out)
+ rows = out.strip().splitlines()[1:]
+ self.assertEqual(['1', '2', '10'], [row.split()[0] for row in rows])
+ self.assertEqual(['0', '0', '-'], rows[0].split()[-3:])
+ self.assertEqual(['3', '0', '0'], rows[1].split()[-3:])
+
+ def test_cli_table_list_snapshots_limit(self):
+ identifier, _ = self._create_snapshot_table()
+ original = SnapshotManager.get_snapshot_by_id
+
+ def bounded_read(manager, snapshot_id):
+ self.assertIn(snapshot_id, (1, 2), 'read beyond the requested
limit')
+ return original(manager, snapshot_id)
+
+ with patch.object(SnapshotManager, 'get_snapshot_by_id',
autospec=True, side_effect=bounded_read):
+ snapshots = json.loads(self._run_table_command_success(
+ 'list-snapshots', identifier, '-l', '2', '-f', 'json'))
+ self.assertEqual([1, 2], [s['id'] for s in snapshots])
+
+ def test_cli_table_list_snapshots_skips_expired(self):
+ identifier, _ = self._create_snapshot_table()
+ original = SnapshotManager.get_snapshot_by_id
+
+ def disappearing_read(manager, snapshot_id):
+ if snapshot_id == 1:
+ return None # Expired before the existence check.
+ if snapshot_id == 2:
+ raise FileNotFoundError('expired during read')
+ return original(manager, snapshot_id)
+
+ with patch.object(SnapshotManager, 'get_snapshot_by_id',
autospec=True, side_effect=disappearing_read):
+ snapshots = json.loads(self._run_table_command_success(
+ 'list-snapshots', identifier, '--limit', '1', '-f', 'json'))
+ self.assertEqual([10], [s['id'] for s in snapshots])
+
+ def test_cli_table_snapshot_by_id(self):
+ identifier, _ = self._create_snapshot_table()
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
side_effect=AssertionError('latest lookup')):
+ snapshot = json.loads(self._run_table_command_success(
+ 'snapshot', identifier, '--snapshot-id', '2', '--format',
'json'))
+ self.assertEqual(2, snapshot['id'])
+ self.assertEqual(1, snapshot['schemaId'])
+ self.assertEqual(3, snapshot['totalRecordCount'])
+ self.assertEqual(0, snapshot['deltaRecordCount'])
+ self.assertEqual('base-2', snapshot['baseManifestList'])
+ self.assertEqual('delta-2', snapshot['deltaManifestList'])
+
+ def test_cli_table_snapshot_format_table(self):
+ identifier, _ = self._create_snapshot_table()
+ out = self._run_table_command_success('snapshot', identifier, '-f',
'table')
+ for text in ('schemaId', 'baseManifestList', 'base-10',
'deltaManifestList', 'delta-10',
+ 'nextRowId', '9007199254740993', 'properties', '{"job":
"test"}',
+ 'writerVersion', 'test-writer',
'2023-11-14T22:13:20.123Z'):
+ self.assertIn(text, out)
+ self.assertNotIn('changelogManifestList', out)
+
+ def test_cli_table_snapshots_empty(self):
+ identifier, _ = self._create_snapshot_table(snapshots=[])
+ self.assertEqual([],
json.loads(self._run_table_command_success('list-snapshots', identifier, '-f',
'json')))
+ self.assertIn('No snapshots',
self._run_table_command_success('list-snapshots', identifier))
+ out, err, code = self._run_table_command('snapshot', identifier)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('No snapshot', err)
+
+ def test_cli_table_snapshot_missing_id(self):
+ identifier, _ = self._create_snapshot_table()
+ with patch.object(SnapshotManager, 'get_latest_snapshot',
side_effect=AssertionError('latest lookup')):
+ out, err, code = self._run_table_command('snapshot', identifier,
'--snapshot-id', '9')
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('9', err)
+ self.assertIn(identifier, err)
+
+ def test_cli_table_snapshot_invalid_numbers(self):
+ for command, option in (('list-snapshots', '--limit'), ('snapshot',
'--snapshot-id')):
+ for value in ('0', '-1', 'bad'):
+ with self.subTest(command=command, value=value):
+ out, err, code = self._run_table_command(command,
'test_db.users', option, value)
+ self.assertEqual(('', 2), (out, code))
+ self.assertIn(option, err)
+
+ def test_cli_table_snapshot_invalid_identifiers(self):
+ for command in ('snapshot', 'list-snapshots'):
+ for table in ('db', '.t', 'db.', 'db.t.extra'):
+ with self.subTest(command=command, table=table):
+ out, err, code = self._run_table_command(command, table)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('Invalid table identifier', err)
+
+ def test_cli_table_snapshot_invalid_table(self):
+ for command in ('snapshot', 'list-snapshots'):
+ for table in ('test_db.missing_snapshot_table',
'test_db.users$snapshots'):
+ with self.subTest(command=command, table=table):
+ out, err, code = self._run_table_command(command, table)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn(table, err)
+
+ def test_cli_table_snapshot_config_failure(self):
+ for command in ('snapshot', 'list-snapshots'):
+ with self.subTest(command=command):
+ out, err, code = self._run_table_command(
+ command, 'test_db.users',
config=os.path.join(self.tempdir, 'missing.yaml'))
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('missing.yaml', err)
+
+ def test_cli_table_snapshot_corrupt_metadata(self):
+ identifier, table = self._create_snapshot_table()
+ with open(table.snapshot_manager().get_snapshot_path(2), 'w') as f:
+ f.write('{invalid json')
+ for args in (('snapshot', identifier, '--snapshot-id', '2'),
('list-snapshots', identifier, '-f', 'json')):
+ with self.subTest(args=args):
+ out, err, code = self._run_table_command(*args)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('snapshot', err.lower())
+
+ def test_cli_table_snapshot_permission_error(self):
+ with patch.object(SnapshotManager, 'get_snapshot_by_id',
side_effect=PermissionError('access denied')):
+ for args in (('snapshot', 'test_db.users', '--snapshot-id', '2'),
+ ('list-snapshots', 'test_db.users', '-f', 'json')):
+ with self.subTest(args=args):
+ out, err, code = self._run_table_command(*args)
+ self.assertEqual(('', 1), (out, code))
+ self.assertIn('access denied', err)
+
+ def test_cli_table_snapshots_table_modes(self):
+ for name, primary_keys, options in (
+ ('append', [], {'bucket': '-1'}),
+ ('pk', ['id'], {'bucket': '1'}),
+ ('evolution', [], {'bucket': '-1', 'row-tracking.enabled':
'true',
+ 'data-evolution.enabled': 'true'})):
+ with self.subTest(mode=name):
+ identifier, _ = self._create_snapshot_table(
+ snapshots=[self._snapshot(1, next_row_id=3 if name ==
'evolution' else None)],
+ primary_keys=primary_keys, options=options, suffix=name)
+ snapshot =
json.loads(self._run_table_command_success('snapshot', identifier,
'--snapshot-id', '1'))
+ self.assertEqual(1, snapshot['id'])
+ if name == 'evolution':
+ self.assertEqual(3, snapshot['nextRowId'])
+ listed =
json.loads(self._run_table_command_success('list-snapshots', identifier, '-f',
'json'))
+ self.assertEqual([1], [s['id'] for s in listed])
def test_cli_table_create_with_json_schema(self):
"""Test table create with JSON schema file."""