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 ecdc4c446d [python] Add list schemas & lookup by schema-id support for 
Python CLI. (#11112)
ecdc4c446d is described below

commit ecdc4c446def10c23a264957b736ea6c45e0f19d
Author: Master.TJ <[email protected]>
AuthorDate: Thu Nov 12 17:27:15 2026 +0800

    [python] Add list schemas & lookup by schema-id support for Python CLI. 
(#11112)
---
 docs/docs/pypaimon/cli-query.md                |  60 +++++++
 docs/docs/pypaimon/cli.md                      |   2 +
 paimon-python/pypaimon/cli/cli_table.py        | 156 ++++++++++++++---
 paimon-python/pypaimon/tests/cli_table_test.py | 223 +++++++++++++++++++++++++
 4 files changed, 418 insertions(+), 23 deletions(-)

diff --git a/docs/docs/pypaimon/cli-query.md b/docs/docs/pypaimon/cli-query.md
index 7561e3ca96..3038c09df5 100644
--- a/docs/docs/pypaimon/cli-query.md
+++ b/docs/docs/pypaimon/cli-query.md
@@ -205,6 +205,66 @@ Output:
 
 **Note:** The output JSON can be saved to a file and used directly with the 
`table create` command to recreate the table structure.
 
+Use an explicit schema ID or resolve the schema referenced by a historical 
snapshot:
+
+```shell
+paimon table get mydb.users --schema-id 0
+paimon table get mydb.users --schema-id 3 --format json
+paimon table get mydb.users --snapshot-id 42 --format json
+paimon table get mydb.users --schema-id 3 --format table
+```
+
+**Options:**
+
+- `--schema-id`: Schema ID to inspect, including `0`. Defaults to the current 
table schema.
+- `--snapshot-id`: Read the schema ID recorded in this snapshot, then load 
that schema.
+  Mutually exclusive with `--schema-id`.
+- `--format, -f`: Output format, `json` (default) or `table`.
+
+## Table List Schemas
+
+List available schema versions in ascending numeric schema-ID order. JSON is 
the default output
+format. Each array element contains the complete serialized `TableSchema`, 
including its ID,
+metadata version, field definitions and IDs, highest field ID, keys, options, 
comment, and update
+time. Field definitions preserve nested types, nullability, and column 
comments.
+
+```shell
+# List all available schema versions as JSON
+paimon table list-schemas mydb.users
+
+# Return the oldest 20 available versions
+paimon table list-schemas mydb.users --limit 20
+
+# Display schema definitions and update times in a readable table
+paimon table list-schemas mydb.users --format table
+```
+
+**Options:**
+
+- `--limit, -l`: Maximum number of schemas to return, starting with the 
oldest. Must be positive;
+  omitted by default, which returns all available schemas.
+- `--format, -f`: Output format, `json` (default) or `table`.
+
+Example JSON for a table with one schema version:
+
+```json
+[
+  {
+    "version": 3,
+    "id": 0,
+    "fields": [
+      {"id": 0, "name": "user_id", "type": "BIGINT NOT NULL"}
+    ],
+    "highestFieldId": 0,
+    "partitionKeys": [],
+    "primaryKeys": [],
+    "options": {"bucket": "-1"},
+    "comment": null,
+    "timeMillis": 1700000000123
+  }
+]
+```
+
 ## Table Snapshot
 
 Get the latest snapshot or inspect a specific retained snapshot. JSON remains 
the default output
diff --git a/docs/docs/pypaimon/cli.md b/docs/docs/pypaimon/cli.md
index e718375cbf..0a045680c2 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-schemas demo.people --limit 20
 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-read"></span>
 <span id="table-explain"></span>
 <span id="table-get"></span>
+<span id="table-list-schemas"></span>
 <span id="table-snapshot"></span>
 <span id="table-list-snapshots"></span>
 <span id="table-create"></span>
diff --git a/paimon-python/pypaimon/cli/cli_table.py 
b/paimon-python/pypaimon/cli/cli_table.py
index 5e43a65c0d..f43d0edace 100644
--- a/paimon-python/pypaimon/cli/cli_table.py
+++ b/paimon-python/pypaimon/cli/cli_table.py
@@ -326,35 +326,80 @@ def cmd_table_get(args):
     Args:
         args: Parsed command line arguments.
     """
-    from pypaimon.cli.cli import load_catalog_config, create_catalog
-    
-    # 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)
+    table = _open_schema_table(args)
+    schema_id = getattr(args, 'schema_id', None)
+    snapshot_id = getattr(args, 'snapshot_id', None)
+    try:
+        if snapshot_id is not None:
+            snapshot = table.snapshot_manager().get_snapshot_by_id(snapshot_id)
+            if snapshot is None:
+                raise ValueError(f"Snapshot {snapshot_id} not found for table 
'{args.table}'.")
+            schema_id = snapshot.schema_id
+            if schema_id is None:
+                raise ValueError(f"Snapshot {snapshot_id} does not contain a 
schema ID.")
+        table_schema = table.table_schema if schema_id is None else 
table.schema_manager.get_schema(schema_id)
+        if table_schema is None:
+            raise ValueError(f"Schema {schema_id} not found for table 
'{args.table}'.")
+        
+        # Get table schema and convert to Schema, then output as JSON
+        schema = table_schema.to_schema()
+        if getattr(args, 'format', 'json') == 'json':
+            print(JSON.to_json(schema, indent=2))
+        else:
+            import pandas as pd
+            values = json.loads(JSON.to_json(schema))
+            rows = [[key, _snapshot_display_value(value)] for key, value in 
values.items()]
+            print(pd.DataFrame(rows, columns=['Field', 
'Value']).to_string(index=False))
+    except Exception as e:
+        target = 'latest schema' if schema_id is None else f'schema 
{schema_id}'
+        if snapshot_id is not None:
+            target = f'schema for 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_schemas(args):
+    """
+    Execute the 'table list-schemas' command.
     
-    database_name, table_name = parts
+    Lists available schemas in ascending schema-ID order without reading table 
data.
     
-    # Get table
+    Args:
+        args: Parsed command line arguments.
+    """
+    table = _open_schema_table(args)
     try:
-        table = catalog.get_table(f"{database_name}.{table_name}")
+        manager = table.schema_manager
+        schemas = []
+        for schema_id in sorted(manager._list_versioned_files()):
+            schema = manager.get_schema(schema_id)
+            if schema is None:
+                continue
+            schemas.append(schema)
+            if args.limit is not None and len(schemas) >= args.limit:
+                break
+        
+        if args.format == 'json':
+            print(json.dumps([json.loads(JSON.to_json(s)) for s in schemas], 
ensure_ascii=False, indent=2))
+        elif not schemas:
+            print(f"No schemas found for table '{args.table}'.")
+        else:
+            import pandas as pd
+            rows = []
+            for s in schemas:
+                row = [str(s.id)]
+                for value in ([f.to_dict() for f in s.fields], 
s.partition_keys, s.primary_keys, s.options):
+                    row.append(json.dumps(value, ensure_ascii=False, 
separators=(',', ':')))
+                update_time = _snapshot_commit_time(s.time_millis) if 
s.time_millis is not None else '-'
+                row.extend([s.comment, update_time])
+                rows.append(row)
+            # Convert before Pandas can coerce nullable integers to floats.
+            rows = [[_snapshot_display_value(value) for value in row] for row 
in rows]
+            columns = ['schema_id', 'fields', 'partition_keys', 
'primary_keys', 'options', 'comment', 'update_time']
+            print(pd.DataFrame(rows, columns=columns).to_string(index=False))
     except Exception as e:
-        print(f"Error: Failed to get table '{table_identifier}': {e}", 
file=sys.stderr)
+        print(f"Error: Failed to list schemas for table '{args.table}': {e}", 
file=sys.stderr)
         sys.exit(1)
-    
-    # Get table schema and convert to Schema, then output as JSON
-    schema = table.table_schema.to_schema()
-    print(JSON.to_json(schema, indent=2))
 
 
 def cmd_table_snapshot(args):
@@ -955,6 +1000,36 @@ def cmd_table_drop_partition(args):
         sys.exit(1)
 
 
+def _open_schema_table(args):
+    """Load a file-store table for the schema inspection commands."""
+    from pypaimon.cli.cli import load_catalog_config, create_catalog
+    
+    # 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)
+    
+    database_name, table_name = parts
+    
+    try:
+        # Load catalog configuration
+        config_path = args.config
+        config = load_catalog_config(config_path)
+        
+        # Create catalog
+        catalog = create_catalog(config)
+        
+        # Get table
+        table = catalog.get_table(f"{database_name}.{table_name}")
+        return table
+    except Exception as e:
+        print(f"Error: Failed to get table '{table_identifier}': {e}", 
file=sys.stderr)
+        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
@@ -1080,7 +1155,31 @@ def add_table_subcommands(table_parser):
         'table',
         help='Table identifier in format: database.table'
     )
+    schema_target = get_parser.add_mutually_exclusive_group()
+    schema_target.add_argument('--schema-id', type=_non_negative_int, 
default=None,
+                               help='Schema ID to inspect (default: the latest 
schema)')
+    schema_target.add_argument('--snapshot-id', type=_positive_int, 
default=None,
+                               help='Inspect the schema referenced by this 
snapshot')
+    get_parser.add_argument(
+        '--format', '-f', choices=['table', 'json'], default='json',
+        help='Output format: json (default) or table'
+    )
     get_parser.set_defaults(func=cmd_table_get)
+
+    # table list-schemas command
+    list_schemas_parser = table_subparsers.add_parser(
+        'list-schemas', help='List available schemas in ascending schema-ID 
order'
+    )
+    list_schemas_parser.add_argument('table', help='Table identifier in 
format: database.table')
+    list_schemas_parser.add_argument(
+        '--limit', '-l', type=_positive_int, default=None,
+        help='Maximum number of schemas to display, starting with the oldest 
(default: all)'
+    )
+    list_schemas_parser.add_argument(
+        '--format', '-f', choices=['table', 'json'], default='json',
+        help='Output format: json (default) or table'
+    )
+    list_schemas_parser.set_defaults(func=cmd_table_list_schemas)
     
     # table snapshot command
     snapshot_parser = table_subparsers.add_parser('snapshot', help='Get the 
latest or a specific snapshot of a table')
@@ -1327,6 +1426,17 @@ def add_table_subcommands(table_parser):
     update_comment_parser.set_defaults(func=cmd_table_alter)
 
 
+def _non_negative_int(value):
+    """Argparse type for schema IDs, including the initial schema ID zero."""
+    try:
+        number = int(value)
+        if number >= 0:
+            return number
+    except ValueError:
+        pass
+    raise argparse.ArgumentTypeError('must be a non-negative integer')
+
+
 def _positive_int(value):
     """Argparse type for snapshot IDs and result limits."""
     try:
diff --git a/paimon-python/pypaimon/tests/cli_table_test.py 
b/paimon-python/pypaimon/tests/cli_table_test.py
index 5fab4ab9a2..d35398be3b 100644
--- a/paimon-python/pypaimon/tests/cli_table_test.py
+++ b/paimon-python/pypaimon/tests/cli_table_test.py
@@ -30,6 +30,8 @@ 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.schema.schema_manager import SchemaManager
+from pypaimon.schema.table_schema import TableSchema
 from pypaimon.snapshot.snapshot import Snapshot
 from pypaimon.snapshot.snapshot_manager import SnapshotManager
 
@@ -132,6 +134,28 @@ class CliTableTest(unittest.TestCase):
             table.file_io.try_to_write_atomic(manager.latest_file, 
str(max(s.id for s in snapshots)))
         return identifier, table
 
+    def _create_schema_table(self):
+        """Create schema history whose snapshots reference different field 
definitions."""
+        identifier, table = self._create_snapshot_table(
+            snapshots=[self._snapshot(4, schema_id=0), self._snapshot(5, 
schema_id=2),
+                       self._snapshot(6, schema_id=10)], suffix='schemas')
+        definitions = [
+            {'id': 0, 'name': 'id', 'type': 'BIGINT NOT NULL', 'description': 
'Identifier'},
+            {'id': 1, 'name': 'region', 'type': 'STRING'},
+            {'id': 2, 'name': 'profile', 'type': {'type': 'ROW', 'fields': [
+                {'id': 3, 'name': 'city', 'type': 'STRING', 'description': 
'城市'}]}},
+            {'id': 4, 'name': 'age', 'type': 'INT'},
+        ]
+        for schema_id, field_count in ((10, 4), (0, 2), (2, 3)):
+            schema = TableSchema.from_schema(schema_id, Schema(
+                fields=[DataField.from_dict(f) for f in 
definitions[:field_count]],
+                partition_keys=['region'], options={'bucket': '-1', 'custom': 
'值'},
+                comment='Schema {}'.format(schema_id)))
+            schema.time_millis = 1700000000123 + schema_id
+            with open(table.schema_manager._to_schema_path(schema_id), 'w') as 
f:
+                f.write(JSON.to_json(schema))
+        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()
@@ -270,6 +294,205 @@ class CliTableTest(unittest.TestCase):
                 self.assertIn('age', field_names)
                 self.assertIn('city', field_names)
 
+                self.assertEqual({'fields', 'partitionKeys', 'primaryKeys', 
'options', 'comment'}, set(schema_json))
+                expected = 
JSON.to_json(self.catalog.get_table('test_db.users').table_schema.to_schema(), 
indent=2)
+                self.assertEqual(expected + '\n', output)
+
+    def test_cli_table_get_schema_versions(self):
+        identifier, _ = self._create_schema_table()
+        cases = [((), ['id', 'region', 'profile', 'age']),
+                 (('--schema-id', '0'), ['id', 'region']),
+                 (('--schema-id', '2', '-f', 'json'), ['id', 'region', 
'profile']),
+                 (('--snapshot-id', '4'), ['id', 'region']),
+                 (('--snapshot-id', '5'), ['id', 'region', 'profile'])]
+        with patch.object(SnapshotManager, 'get_latest_snapshot', 
side_effect=AssertionError('latest snapshot lookup')):
+            for options, field_names in cases:
+                with self.subTest(options=options):
+                    output = self._run_table_command_success('get', 
identifier, *options)
+                    schema = json.loads(output)
+                    self.assertEqual({'fields', 'partitionKeys', 
'primaryKeys', 'options', 'comment'}, set(schema))
+                    self.assertEqual(field_names, [f['name'] for f in 
schema['fields']])
+                    self.assertEqual(field_names, [f.name for f in 
JSON.from_json(output, Schema).fields])
+
+    def test_cli_table_list_schemas_json(self):
+        identifier, _ = self._create_schema_table()
+        output = self._run_table_command_success('list-schemas', identifier)
+        schemas = json.loads(output)
+        self.assertEqual([0, 2, 10], [s['id'] for s in schemas])
+        self.assertEqual([2, 3, 4], [len(s['fields']) for s in schemas])
+        self.assertEqual([1, 3, 4], [s['highestFieldId'] for s in schemas])
+        self.assertEqual(3, schemas[1]['version'])
+        self.assertEqual(1700000000125, schemas[1]['timeMillis'])
+        self.assertEqual(['region'], schemas[1]['partitionKeys'])
+        self.assertEqual([], schemas[1]['primaryKeys'])
+        self.assertEqual({'bucket': '-1', 'custom': '值'}, 
schemas[1]['options'])
+        self.assertEqual('Schema 2', schemas[1]['comment'])
+        self.assertEqual({'id': 0, 'name': 'id', 'type': 'BIGINT NOT NULL', 
'description': 'Identifier'},
+                         schemas[1]['fields'][0])
+        profile = schemas[1]['fields'][2]
+        self.assertEqual(2, profile['id'])
+        self.assertTrue(profile['type']['nullable'])
+        self.assertEqual([{'id': 3, 'name': 'city', 'type': 'STRING', 
'description': '城市'}],
+                         profile['type']['fields'])
+        self.assertIn('城市', output)
+        self.assertEqual(schemas, 
json.loads(self._run_table_command_success('list-schemas', identifier, '-f', 
'json')))
+
+    def test_cli_table_schemas_format_table(self):
+        identifier, _ = self._create_schema_table()
+        for command in ('get', 'list-schemas'):
+            with self.subTest(command=command):
+                output = self._run_table_command_success(command, identifier, 
'--format', 'table')
+                for value in ('id', 'region', 'profile', 'city', 'BIGINT NOT 
NULL', 'Identifier', 'Schema 10', '值'):
+                    self.assertIn(value, output)
+                if command == 'list-schemas':
+                    self.assertEqual(['schema_id', 'fields', 'partition_keys', 
'primary_keys',
+                                      'options', 'comment', 'update_time'], 
output.splitlines()[0].split())
+                    self.assertIn('2023-11-14T22:13:20.125Z', output)
+                    self.assertIn('{"bucket":"-1","custom":"值"}', output)
+                    
self.assertIn('{"id":3,"name":"city","type":"STRING","description":"城市"}', 
output)
+        output = self._run_table_command_success('list-schemas', 
'test_db.users', '--format', 'table')
+        self.assertRegex(output, r'-\s+\d{4}-\d{2}-\d{2}')
+
+    def test_cli_table_list_schemas_limit(self):
+        identifier, table = self._create_schema_table()
+        schemas = json.loads(self._run_table_command_success('list-schemas', 
identifier, '-l', '2'))
+        self.assertEqual([0, 2], [s['id'] for s in schemas])
+        # The manager must stop before reading an unselected, corrupt schema.
+        with open(table.schema_manager._to_schema_path(5), 'w') as f:
+            f.write('{invalid json')
+        schemas = json.loads(self._run_table_command_success('list-schemas', 
identifier, '-l', '2'))
+        self.assertEqual([0, 2], [s['id'] for s in schemas])
+
+    def test_cli_table_list_schemas_skips_missing(self):
+        identifier, _ = self._create_schema_table()
+        original = SchemaManager.get_schema
+
+        def disappearing_read(manager, schema_id):
+            return None if schema_id == 0 else original(manager, schema_id)
+
+        with patch.object(SchemaManager, 'get_schema', autospec=True, 
side_effect=disappearing_read):
+            schemas = 
json.loads(self._run_table_command_success('list-schemas', identifier, 
'--limit', '1'))
+        self.assertEqual([2], [s['id'] for s in schemas])
+
+    def test_cli_table_schemas_without_snapshots(self):
+        identifier, _ = self._create_snapshot_table(snapshots=[], 
suffix='schemas')
+        with patch.object(SnapshotManager, 'get_latest_snapshot', 
side_effect=AssertionError('snapshot lookup')):
+            self.assertEqual([0], [s['id'] for s in json.loads(
+                self._run_table_command_success('list-schemas', identifier))])
+            schema = json.loads(self._run_table_command_success('get', 
identifier, '--schema-id', '0'))
+        self.assertEqual(['id'], [f['name'] for f in schema['fields']])
+
+    def test_cli_table_list_schemas_empty(self):
+        table = self.catalog.get_table('test_db.users')
+        with patch('pypaimon.cli.cli_table._open_schema_table', 
return_value=table):
+            with patch.object(table.schema_manager, '_list_versioned_files', 
return_value=[]):
+                self.assertEqual([], 
json.loads(self._run_table_command_success('list-schemas', 'test_db.users')))
+                self.assertIn('No schemas', self._run_table_command_success(
+                    'list-schemas', 'test_db.users', '-f', 'table'))
+
+    def test_cli_table_get_missing_schema_or_snapshot(self):
+        identifier, table = self._create_schema_table()
+        os.remove(table.schema_manager._to_schema_path(2))
+        for option, value, target in (('--schema-id', '7', '7'), 
('--snapshot-id', '99', '99'),
+                                      ('--snapshot-id', '5', '2')):
+            with self.subTest(option=option, value=value):
+                out, err, code = self._run_table_command('get', identifier, 
option, value)
+                self.assertEqual(('', 1), (out, code))
+                self.assertIn(identifier, err)
+                self.assertIn(target, err)
+
+    def test_cli_table_schema_invalid_selectors(self):
+        for command, option, values in (('get', '--schema-id', ('-1', 'bad')),
+                                        ('get', '--snapshot-id', ('0', '-1', 
'bad')),
+                                        ('list-schemas', '--limit', ('0', 
'-1', 'bad'))):
+            for value in values:
+                with self.subTest(command=command, option=option, value=value):
+                    out, err, code = self._run_table_command(command, 
'test_db.users', option, value)
+                    self.assertEqual(('', 2), (out, code))
+                    self.assertIn(option, err)
+        out, err, code = self._run_table_command('get', 'test_db.users', 
'--schema-id', '0', '--snapshot-id', '1')
+        self.assertEqual(('', 2), (out, code))
+        self.assertIn('not allowed with argument', err)
+
+    def test_cli_table_get_snapshot_without_schema_id(self):
+        identifier, table = self._create_schema_table()
+        snapshot = json.loads(JSON.to_json(self._snapshot(5, schema_id=None)))
+        for missing in (False, True):
+            with self.subTest(missing=missing):
+                if missing:
+                    del snapshot['schemaId']
+                with open(table.snapshot_manager().get_snapshot_path(5), 'w') 
as f:
+                    json.dump(snapshot, f)
+                out, err, code = self._run_table_command('get', identifier, 
'--snapshot-id', '5')
+                self.assertEqual(('', 1), (out, code))
+                self.assertIn('5', err)
+                self.assertIn('schema', err.lower())
+
+    def test_cli_table_schemas_invalid_target(self):
+        for command in ('get', 'list-schemas'):
+            identifiers = ('db', '.t', 'db.', 'db.t.extra', 
'test_db.missing_schema_table', 'test_db.users$schemas')
+            for identifier in identifiers:
+                with self.subTest(command=command, identifier=identifier):
+                    out, err, code = self._run_table_command(command, 
identifier)
+                    self.assertEqual(('', 1), (out, code))
+                    self.assertIn(identifier, err)
+            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_schemas_corrupt_metadata(self):
+        identifier, table = self._create_schema_table()
+        cases = [(table.schema_manager._to_schema_path(2),
+                  [('get', '--schema-id', '2'), ('get', '--snapshot-id', '5'), 
('list-schemas',)]),
+                 (table.snapshot_manager().get_snapshot_path(5), [('get', 
'--snapshot-id', '5')])]
+        for path, commands in cases:
+            with open(path) as f:
+                original = f.read()
+            with open(path, 'w') as f:
+                f.write('{invalid json')
+            for command in commands:
+                with self.subTest(path=path, command=command):
+                    out, err, code = self._run_table_command(command[0], 
identifier, *command[1:])
+                    self.assertEqual(('', 1), (out, code))
+                    self.assertIn(identifier, err)
+            with open(path, 'w') as f:
+                f.write(original)
+
+    def test_cli_table_schemas_permission_error(self):
+        identifier, table = self._create_schema_table()
+        file_io = table.file_io
+        original = type(file_io).read_file_utf8
+
+        def denied_read(io, path):
+            if path.endswith('/schema-2'):
+                raise PermissionError('access denied')
+            return original(io, path)
+
+        with patch.object(type(file_io), 'read_file_utf8', autospec=True, 
side_effect=denied_read):
+            for command in (('get', '--schema-id', '2'), ('get', 
'--snapshot-id', '5'), ('list-schemas',)):
+                with self.subTest(command=command):
+                    out, err, code = self._run_table_command(command[0], 
identifier, *command[1:])
+                    self.assertEqual(('', 1), (out, code))
+                    self.assertIn(identifier, err)
+
+    def test_cli_table_schemas_table_modes(self):
+        modes = [('append', [], {'bucket': '-1'}),
+                 ('primary_key', ['id'], {'bucket': '1'}),
+                 ('data_evolution', [], {'bucket': '-1', 
'row-tracking.enabled': 'true',
+                                         'data-evolution.enabled': 'true'})]
+        for name, primary_keys, options in modes:
+            with self.subTest(mode=name):
+                identifier, _ = self._create_snapshot_table(
+                    snapshots=[], primary_keys=primary_keys, options=options, 
suffix=name)
+                schemas = 
json.loads(self._run_table_command_success('list-schemas', identifier))
+                self.assertEqual([0], [s['id'] for s in schemas])
+                self.assertEqual(primary_keys, schemas[0]['primaryKeys'])
+                self.assertEqual(options, schemas[0]['options'])
+                schema = json.loads(self._run_table_command_success('get', 
identifier, '--schema-id', '0'))
+                self.assertEqual(primary_keys, schema['primaryKeys'])
+                self.assertEqual(options, schema['options'])
+
     def test_cli_table_snapshot_basic(self):
         """Test basic table snapshot via CLI."""
         # Simulate CLI command: paimon -c <config> table snapshot test_db.users

Reply via email to