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 00b4d05a6c [python] Infer existing table schemas when registering REST 
external tables (#11194)
00b4d05a6c is described below

commit 00b4d05a6cc118091a38eeca23549519cfb775f4
Author: zhoulii <[email protected]>
AuthorDate: Mon Nov 16 23:12:12 2026 +0800

    [python] Infer existing table schemas when registering REST external tables 
(#11194)
---
 docs/docs/pypaimon/catalogs.mdx                    |  26 ++
 .../pypaimon/catalog/rest/rest_catalog.py          |  21 ++
 paimon-python/pypaimon/schema/schema_manager.py    |  69 ++++-
 .../tests/native_index_result_scan_test.py         |   6 +-
 .../tests/native_pk_full_text_search_test.py       |   8 +-
 .../pypaimon/tests/native_vector_search_test.py    |  14 +-
 .../tests/ray_data_evolution_merge_into_test.py    |  12 +-
 .../tests/rest/rest_external_schema_test.py        | 293 +++++++++++++++++++++
 paimon-python/pypaimon/tests/rest/rest_server.py   |  15 +-
 .../pypaimon/tests/schema_manager_test.py          | 126 ++++++++-
 10 files changed, 579 insertions(+), 11 deletions(-)

diff --git a/docs/docs/pypaimon/catalogs.mdx b/docs/docs/pypaimon/catalogs.mdx
index 78937c5ec7..e538ee061a 100644
--- a/docs/docs/pypaimon/catalogs.mdx
+++ b/docs/docs/pypaimon/catalogs.mdx
@@ -275,6 +275,32 @@ table = catalog.get_table('database_name.table_name')
 table = catalog.get_table_by_id('table_id')
 ```
 
+### Register an Existing Table in a REST Catalog
+
+With a REST catalog, register an existing Paimon table by supplying its path:
+
+```python
+from pypaimon import Schema
+
+catalog.create_table(
+    identifier='database_name.existing_table',
+    schema=Schema(options={'path': 's3://bucket/existing-table'}),
+    ignore_if_exists=False,
+)
+```
+
+PyPaimon reads the latest filesystem schema and inherits its fields, partition 
keys,
+primary keys, options, and table comment. Explicitly supplied fields and keys 
must
+match the existing definition. Supplied options must match existing values, 
except
+for `owner` and `path`: a non-null `owner` overrides the inherited owner 
option in
+the create request, and `path` is set to the supplied location. Registration 
leaves
+the filesystem schema unchanged.
+
+If no Paimon schema exists at the path, PyPaimon sends the supplied definition 
in
+the REST create request without inference. The server handles the request; 
omitting
+fields in this case does not guarantee successful creation.
+This inference applies to Paimon tables, excluding format, object, and Iceberg 
tables.
+
 ## Alter Table
 
 Alter a table with a list of schema changes. Use `SchemaChange` from 
`pypaimon.schema.schema_change` and types from `pypaimon.schema.data_types` 
(e.g. `AtomicType`).
diff --git a/paimon-python/pypaimon/catalog/rest/rest_catalog.py 
b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
index 6caf66564a..79016b910b 100644
--- a/paimon-python/pypaimon/catalog/rest/rest_catalog.py
+++ b/paimon-python/pypaimon/catalog/rest/rest_catalog.py
@@ -16,6 +16,7 @@
 # under the License.
 
 import logging
+from copy import deepcopy
 from typing import Any, Callable, Dict, List, Optional, Union
 from pypaimon.api.api_response import ErrorResponse, GetTableResponse, 
GetTagResponse, PagedList, Partition
 from pypaimon.api.model import CreateModelRequest
@@ -57,6 +58,7 @@ from pypaimon.common.json_util import JSON
 from pypaimon.management.permission_management import PermissionManagement
 from pypaimon.management.policy_management import PolicyManagement
 from pypaimon.schema.schema import Schema
+from pypaimon.schema.schema_manager import SchemaManager
 from pypaimon.schema.schema_change import SchemaChange
 from pypaimon.schema.table_schema import TableSchema
 from pypaimon.snapshot.snapshot import Snapshot
@@ -305,6 +307,8 @@ class RESTCatalog(Catalog):
         check_not_branch(identifier, "create_table")
         check_not_system_table(identifier, "create_table")
         try:
+            if schema is not None:
+                schema = self._infer_schema_if_external_paimon_table(schema)
             self.rest_api.create_table(identifier, schema)
         except AlreadyExistsException as e:
             if not ignore_if_exists:
@@ -312,6 +316,23 @@ class RESTCatalog(Catalog):
         except NoSuchResourceException as e:
             raise DatabaseNotExistException(identifier.get_database_name()) 
from e
 
+    def _infer_schema_if_external_paimon_table(self, schema: Schema) -> Schema:
+        table_type = schema.options.get(CoreOptions.TYPE.key(), 
'table').strip().lower()
+        path = schema.options.get(CoreOptions.PATH.key())
+        if table_type != 'table' or path is None:
+            return schema
+
+        latest = SchemaManager(self.file_io_from_options(path), path).latest()
+        if latest is None:
+            return schema
+
+        existing = deepcopy(latest).to_schema()
+        SchemaManager.check_schema_for_external_table(existing, schema)
+        if schema.options.get(self.OWNER_PROP) is not None:
+            existing.options[self.OWNER_PROP] = schema.options[self.OWNER_PROP]
+        existing.options[CoreOptions.PATH.key()] = path
+        return existing
+
     def rename_table(self, source_identifier: Union[str, Identifier],
                      target_identifier: Union[str, Identifier]) -> None:
         if not isinstance(source_identifier, Identifier):
diff --git a/paimon-python/pypaimon/schema/schema_manager.py 
b/paimon-python/pypaimon/schema/schema_manager.py
index d5338a307a..07e34eb967 100644
--- a/paimon-python/pypaimon/schema/schema_manager.py
+++ b/paimon-python/pypaimon/schema/schema_manager.py
@@ -15,6 +15,7 @@
 # specific language governing permissions and limitations
 # under the License.
 
+import re
 from collections import Counter
 from typing import List, Optional
 
@@ -29,8 +30,9 @@ from pypaimon.schema.column_directive_utils import (
     apply_add_column_directive, apply_directives,
     remove_dropped_directive_options)
 from pypaimon.schema.data_type_casts import can_execute_cast, supports_cast
-from pypaimon.schema.data_types import (ArrayType, AtomicInteger, DataField,
+from pypaimon.schema.data_types import (ArrayType, AtomicInteger, AtomicType, 
DataField,
                                         DataType, MapType, MultisetType, 
RowType,
+                                        VectorType,
                                         is_array_blob_type, is_blob_file_field,
                                         is_blob_file_type, is_blob_type,
                                         is_map_blob_type, reassign_field_id)
@@ -922,6 +924,55 @@ def _handle_add_column(
     _modify_nested_column(new_fields, change.field_names, update_last)
 
 
+def _external_atomic_type_key(type_name: str):
+    """Canonical SQL aliases and parameters, following Java DataTypeJsonParser.
+
+    Keep aliases and defaults aligned with parseTypeByKeyword() and the type 
parsers in
+    paimon-api/src/main/java/org/apache/paimon/types/DataTypeJsonParser.java.
+    """
+    name = ' '.join(type_name.upper().split())
+    ltz = re.fullmatch(r'TIMESTAMP(?:\s*\(\s*(\d+)\s*\)\s*| )WITH LOCAL TIME 
ZONE', name)
+    if ltz:
+        name = 'TIMESTAMP_LTZ' + ('({})'.format(ltz.group(1)) if ltz.group(1) 
else '')
+    without_zone = re.fullmatch(r'(TIME(?:STAMP)?)(?:\s*\(\s*(\d+)\s*\)\s*| 
)WITHOUT TIME ZONE', name)
+    if without_zone:
+        name = without_zone.group(1) + ('({})'.format(without_zone.group(2)) 
if without_zone.group(2) else '')
+
+    parsed = re.fullmatch(r'([A-Z_]+(?: 
[A-Z_]+)*)(?:\s*\(\s*(\d+(?:\s*,\s*\d+)*)\s*\))?', name)
+    if parsed is None:
+        return name
+    root = {'INTEGER': 'INT', 'NUMERIC': 'DECIMAL', 'DEC': 'DECIMAL',
+            'DOUBLE PRECISION': 'DOUBLE'}.get(parsed.group(1), parsed.group(1))
+    parameters = tuple(int(value) for value in parsed.group(2).split(',')) if 
parsed.group(2) else ()
+    if not parameters and root in ('STRING', 'BYTES'):
+        return ('VARCHAR' if root == 'STRING' else 'VARBINARY'), (2147483647,)
+    if not parameters:
+        parameters = {'DECIMAL': (10, 0), 'TIME': (0,), 'TIMESTAMP': (6,), 
'TIMESTAMP_LTZ': (6,),
+                      'CHAR': (1,), 'VARCHAR': (1,), 'BINARY': (1,), 
'VARBINARY': (1,)}.get(root, ())
+    elif root == 'DECIMAL' and len(parameters) == 1:
+        parameters += (0,)
+    return root, parameters
+
+
+def _external_schema_type_key(data_type: DataType):
+    """Compare logical types and field metadata without depending on field 
IDs."""
+    if data_type is None:
+        return None
+    prefix = (type(data_type), data_type.nullable)
+    if isinstance(data_type, AtomicType):
+        return prefix + (_external_atomic_type_key(data_type.type),)
+    if isinstance(data_type, RowType):
+        return prefix + (tuple((field.name, 
_external_schema_type_key(field.type),
+                                field.description, field.default_value) for 
field in data_type.fields),)
+    if isinstance(data_type, (ArrayType, MultisetType)):
+        return prefix + (_external_schema_type_key(data_type.element),)
+    if isinstance(data_type, VectorType):
+        return prefix + (_external_schema_type_key(data_type.element), 
data_type.length)
+    if isinstance(data_type, MapType):
+        return prefix + (_external_schema_type_key(data_type.key), 
_external_schema_type_key(data_type.value))
+    return prefix + (data_type,)
+
+
 class SchemaManager:
 
     def __init__(self, file_io: FileIO, table_path: str, branch: str = 
DEFAULT_MAIN_BRANCH):
@@ -968,6 +1019,22 @@ class SchemaManager:
                 schemas.append(schema)
         return schemas
 
+    @staticmethod
+    def check_schema_for_external_table(existing: Schema, schema: Schema) -> 
None:
+        if schema.fields and (
+                _external_schema_type_key(RowType(True, schema.fields))
+                != _external_schema_type_key(RowType(True, existing.fields))):
+            raise ValueError("External table fields do not match the existing 
schema.")
+        for key in ('partition_keys', 'primary_keys'):
+            provided = getattr(schema, key)
+            if provided and provided != getattr(existing, key):
+                raise ValueError(
+                    "External table {} do not match the existing 
schema.".format(key.replace('_', ' ')))
+        for key, value in schema.options.items():
+            if key not in ('owner', CoreOptions.PATH.key()) and (
+                    key not in existing.options or existing.options[key] != 
value):
+                raise ValueError("External table option '{}' does not match 
the existing schema.".format(key))
+
     def create_table(self, schema: Schema) -> TableSchema:
         while True:
             latest = self.latest()
diff --git a/paimon-python/pypaimon/tests/native_index_result_scan_test.py 
b/paimon-python/pypaimon/tests/native_index_result_scan_test.py
index ef646e8026..db9ab406e8 100644
--- a/paimon-python/pypaimon/tests/native_index_result_scan_test.py
+++ b/paimon-python/pypaimon/tests/native_index_result_scan_test.py
@@ -152,10 +152,14 @@ def 
test_exposed_python_splits_and_pickled_results_use_current_metadata(source):
 def test_empty_native_pk_search_preserves_java_snapshot_zero(source, 
rest_catalog):
     catalog, _ = rest_catalog
     schema = source[0].table_schema
+    options = {key: value for key, value in schema.options.items()
+               if key not in ('path', 'createdBy', 'createdAt', 'updatedBy', 
'updatedAt')}
     catalog.create_table('default.empty_text', Schema(
-        schema.fields, schema.partition_keys, schema.primary_keys, 
schema.options), False)
+        schema.fields, schema.partition_keys, schema.primary_keys, options), 
False)
     table = catalog.get_table('default.empty_text').copy({
         'read.native.enabled': 'true', 'scan.native-plan.enabled': 'true'})
+    assert table.table_path != source[0].table_path
+    assert table.snapshot_manager().get_latest_snapshot() is None
     result = text._builder(table).execute_local()
     assert result.snapshot_id == 0
     with patch.object(FileScanner, 'scan', side_effect=AssertionError('Python 
scan ran')):
diff --git a/paimon-python/pypaimon/tests/native_pk_full_text_search_test.py 
b/paimon-python/pypaimon/tests/native_pk_full_text_search_test.py
index 0d2e1adbc1..10b22a482e 100644
--- a/paimon-python/pypaimon/tests/native_pk_full_text_search_test.py
+++ b/paimon-python/pypaimon/tests/native_pk_full_text_search_test.py
@@ -43,12 +43,16 @@ def source(rest_catalog, golden_catalog):
     catalog, server = rest_catalog
     golden = golden_catalog.get_table('default.test_pk_full_text_golden')
     schema = golden.table_schema
+    options = {key: value for key, value in schema.options.items() if key != 
'path'}
     catalog.create_table('default.pk_text', Schema(
-        schema.fields, schema.partition_keys, schema.primary_keys, 
schema.options), False)
+        schema.fields, schema.partition_keys, schema.primary_keys, options), 
False)
     destination = Path(server.data_path) / server.warehouse / 'default' / 
'pk_text'
     for directory in ('bucket-0', 'index', 'manifest', 'snapshot'):
         shutil.copytree(str(Path(golden.table_path) / directory), 
str(destination / directory))
-    return catalog.get_table('default.pk_text'), server
+    table = catalog.get_table('default.pk_text')
+    assert table.table_path == destination.as_uri()
+    assert table.catalog_environment.catalog_loader is not None
+    return table, server
 
 
 def _builder(table, text='Paimon', limit=10):
diff --git a/paimon-python/pypaimon/tests/native_vector_search_test.py 
b/paimon-python/pypaimon/tests/native_vector_search_test.py
index b7b8c54007..f81d2eb632 100644
--- a/paimon-python/pypaimon/tests/native_vector_search_test.py
+++ b/paimon-python/pypaimon/tests/native_vector_search_test.py
@@ -136,9 +136,13 @@ def test_empty_search_keeps_batch_arity(vector_table, 
rest_catalog, empty):
     if empty == 'table':
         catalog, _ = rest_catalog
         schema = vector_table.table_schema
+        options = {key: value for key, value in schema.options.items()
+                   if key not in ('path', 'createdBy', 'createdAt', 
'updatedBy', 'updatedAt')}
         catalog.create_table('default.empty_vectors', Schema(
-            schema.fields, schema.partition_keys, schema.primary_keys, 
schema.options), False)
+            schema.fields, schema.partition_keys, schema.primary_keys, 
options), False)
         native = 
catalog.get_table('default.empty_vectors').copy({'read.native.enabled': 'true'})
+        assert native.table_path != vector_table.table_path
+        assert native.snapshot_manager().get_latest_snapshot() is None
     predicate = native.new_read_builder().new_predicate_builder()
     builder = 
(native.new_batch_vector_search_builder().with_vector_column('embedding')
                .with_query_vectors([[1, 0], [0, 1]]).with_limit(2))
@@ -180,13 +184,17 @@ def pk_vector_table(rest_catalog, golden_catalog):
     catalog, server = rest_catalog
     golden = golden_catalog.get_table('default.test_pk_vector_golden')
     schema = golden.table_schema
+    options = {key: value for key, value in schema.options.items() if key != 
'path'}
     catalog.create_table('default.pk_vectors', Schema(
-        schema.fields, schema.partition_keys, schema.primary_keys, 
schema.options), False)
+        schema.fields, schema.partition_keys, schema.primary_keys, options), 
False)
     source = Path(golden.table_path)
     destination = Path(server.data_path) / server.warehouse / 'default' / 
'pk_vectors'
     for directory in ('bucket-0', 'index', 'manifest', 'snapshot'):
         shutil.copytree(str(source / directory), str(destination / directory))
-    return catalog.get_table('default.pk_vectors')
+    table = catalog.get_table('default.pk_vectors')
+    assert table.table_path == destination.as_uri()
+    assert table.catalog_environment.catalog_loader is not None
+    return table
 
 
 @pytest.mark.parametrize('filtered', [False, True])
diff --git a/paimon-python/pypaimon/tests/ray_data_evolution_merge_into_test.py 
b/paimon-python/pypaimon/tests/ray_data_evolution_merge_into_test.py
index 389f393cc6..ff8fad5efc 100644
--- a/paimon-python/pypaimon/tests/ray_data_evolution_merge_into_test.py
+++ b/paimon-python/pypaimon/tests/ray_data_evolution_merge_into_test.py
@@ -4457,9 +4457,13 @@ def 
test_merge_authorizes_named_source_separately(rest_catalog, policy):
 
     catalog, server = rest_catalog
     table = auth_test._table(catalog)
+    options = {key: value for key, value in table.table_schema.options.items()
+               if key not in ('path', 'createdBy', 'createdAt', 'updatedBy', 
'updatedAt')}
     catalog.create_table('default.source', Schema.from_pyarrow_schema(
-        auth_test._SCHEMA, options=table.table_schema.options), False)
+        auth_test._SCHEMA, options=options), False)
     source = catalog.get_table('default.source')
+    assert source.table_path != table.table_path
+    assert source.snapshot_manager().get_latest_snapshot() is None
     auth_test._append(source, auth_test._ROWS[1:])
     before = auth_test._files(table)
     with auth_test._restricted(server, source, policy) as authorize, 
patch.object(
@@ -4484,9 +4488,13 @@ def 
test_merge_authorizes_named_source_separately(rest_catalog, policy):
 def test_merge_with_full_source_and_target_grants(rest_catalog, seed):
     catalog, server = rest_catalog
     table = auth_test._table(catalog, seed=seed)
+    options = {key: value for key, value in table.table_schema.options.items()
+               if key not in ('path', 'createdBy', 'createdAt', 'updatedBy', 
'updatedAt')}
     catalog.create_table('default.source', Schema.from_pyarrow_schema(
-        auth_test._SCHEMA, options=table.table_schema.options), False)
+        auth_test._SCHEMA, options=options), False)
     source = catalog.get_table('default.source')
+    assert source.table_path != table.table_path
+    assert source.snapshot_manager().get_latest_snapshot() is None
     rows = [dict(id=2, value=22, name='B'), dict(id=4, value=40, name='d')]
     auth_test._append(source, rows)
     ray.init(ignore_reinit_error=True, num_cpus=4)
diff --git a/paimon-python/pypaimon/tests/rest/rest_external_schema_test.py 
b/paimon-python/pypaimon/tests/rest/rest_external_schema_test.py
new file mode 100644
index 0000000000..9c9519e988
--- /dev/null
+++ b/paimon-python/pypaimon/tests/rest/rest_external_schema_test.py
@@ -0,0 +1,293 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from copy import deepcopy
+from unittest.mock import patch
+
+import pyarrow as pa
+import pytest
+
+from pypaimon import Schema
+from pypaimon.api.api_request import CreateTableRequest
+from pypaimon.api.api_response import ConfigResponse
+from pypaimon.api.auth import BearTokenAuthProvider
+from pypaimon.catalog.catalog_context import CatalogContext
+from pypaimon.catalog.catalog_exception import TableAlreadyExistException
+from pypaimon.catalog.rest.rest_catalog import RESTCatalog
+from pypaimon.common.file_io import FileIO
+from pypaimon.common.json_util import JSON
+from pypaimon.common.options import Options
+from pypaimon.schema.data_types import ArrayType, AtomicType, DataField, 
MapType, RowType
+from pypaimon.schema.schema_change import SchemaChange
+from pypaimon.schema.schema_manager import SchemaManager
+from pypaimon.table.file_store_table import FileStoreTable
+from pypaimon.tests.rest.rest_server import RESTCatalogServer
+
+
+pytestmark = [pytest.mark.python_plan, pytest.mark.python_read,
+              pytest.mark.python_write, pytest.mark.python_commit]
+
+
[email protected]
+def catalog(tmp_path):
+    server = RESTCatalogServer(str(tmp_path / 'catalog'), 
BearTokenAuthProvider('test-token'),
+                               ConfigResponse(defaults={'prefix': 
'external-schema'}), 'warehouse')
+    server.start()
+    try:
+        rest = RESTCatalog(CatalogContext.create_from_options(Options({
+            'uri': server.get_url(), 'warehouse': 'warehouse',
+            'token.provider': 'bear', 'token': 'test-token', 
'data-token.enabled': 'true',
+        })))
+        rest.create_database('default', False)
+        yield rest, server
+    finally:
+        server.shutdown()
+
+
[email protected]
+def existing_table(tmp_path):
+    path = tmp_path / 'existing'
+    manager = SchemaManager(FileIO.get(str(path)), str(path))
+    manager.create_table(Schema(
+        fields=[DataField(0, 'id', AtomicType('BIGINT', False)),
+                DataField(1, 'pt', AtomicType('STRING', False)),
+                DataField(2, 'obsolete', AtomicType('INT')),
+                DataField(3, 'value', AtomicType('BIGINT'), 'counter', '0')],
+        partition_keys=['pt'], primary_keys=['id', 'pt'],
+        options={'bucket': '1', 'file.format': 'parquet', 'owner': 'original', 
'write-only': 'true',
+                 'scan.native-plan.enabled': 'false', 'read.native.enabled': 
'false',
+                 'write.native.enabled': 'false', 'commit.native.enabled': 
'false'},
+        comment='existing table',
+    ))
+    latest = manager.commit_changes([SchemaChange.drop_column('obsolete')])
+    assert latest.id == 1
+    assert [field.id for field in latest.fields] == [0, 1, 3]
+    return path, latest
+
+
+def _schema_files(path):
+    return {file.name: file.read_bytes() for file in (path / 
'schema').iterdir()}
+
+
[email protected]('explicit', [False, True], ids=['inferred', 
'explicit'])
[email protected]('owner', ['omitted', None, 'new-owner'])
+def test_registers_latest_schema_without_changing_files(catalog, 
existing_table, explicit, owner):
+    rest, server = catalog
+    path, latest = existing_table
+    provided = deepcopy(latest).to_schema() if explicit else Schema()
+    for field in provided.fields:
+        field.id += 100
+    provided.options = {'path': path.as_uri()}
+    if owner != 'omitted':
+        provided.options['owner'] = owner
+    provided.comment = 'registration comment'
+    before, supplied = _schema_files(path), JSON.to_json(provided)
+
+    with patch.object(server, '_tables_handle', wraps=server._tables_handle) 
as create:
+        rest.create_table('default.registered', provided, False)
+
+    create.assert_called_once()
+    sent = JSON.from_json(create.call_args[0][1], CreateTableRequest).schema
+    assert sent.fields == latest.fields
+    assert sent.partition_keys == latest.partition_keys
+    assert sent.primary_keys == latest.primary_keys
+    assert sent.comment == latest.comment
+    expected_options = dict(latest.options, path=path.as_uri())
+    if owner not in ('omitted', None):
+        expected_options['owner'] = owner
+    assert sent.options == expected_options
+    assert JSON.to_json(provided) == supplied
+    assert _schema_files(path) == before
+    loaded = rest.get_table('default.registered')
+    assert loaded.schema().id == latest.id
+    assert loaded.catalog_environment.catalog_loader is None
+    assert loaded.table_path == path.as_uri()
+
+
+def test_registered_table_reads_existing_data(catalog, existing_table):
+    rest, server = catalog
+    path, _ = existing_table
+    filesystem = FileStoreTable.from_path(path.as_uri())
+    builder = filesystem.new_batch_write_builder()
+    writer, commit = builder.new_write(), builder.new_commit()
+    rows = [{'id': 1, 'pt': 'a', 'value': 10}, {'id': 2, 'pt': 'a', 'value': 
20}]
+    try:
+        writer.write_arrow(pa.Table.from_pylist(rows))
+        commit.commit(writer.prepare_commit())
+    finally:
+        writer.close()
+        commit.close()
+    before = _schema_files(path)
+
+    rest.create_table('default.registered', Schema(options={'path': 
path.as_uri()}), False)
+    table = rest.get_table('default.registered')
+    with patch.object(server, '_table_snapshot_handle', 
side_effect=AssertionError(
+            'External snapshot reads must use the filesystem')) as 
snapshot_api:
+        reader = table.new_read_builder()
+        actual = 
reader.new_read().to_arrow(reader.new_scan().plan().splits()).to_pylist()
+        assert sorted(actual, key=lambda row: row['id']) == rows
+        assert table.snapshot_manager().get_latest_snapshot().id == 1
+        snapshot_api.assert_not_called()
+    assert _schema_files(path) == before
+
+
[email protected]('timestamp_type', [
+    pa.timestamp('us', tz='UTC'), pa.timestamp('ms', tz='UTC'), 
pa.timestamp('us'),
+], ids=['same-ltz', 'different-precision', 'without-time-zone'])
[email protected]('nullable', [True, False])
+def test_registers_java_schema_with_explicit_pyarrow_fields(catalog, tmp_path, 
timestamp_type, nullable):
+    rest, server = catalog
+    path = tmp_path / 'java-table'
+    ltz = AtomicType('TIMESTAMP(6) WITH LOCAL TIME ZONE')
+    latest = SchemaManager(FileIO.get(str(path)), 
str(path)).create_table(Schema(
+        fields=[DataField(7, 'event_time', ltz),
+                DataField(9, 'amount', AtomicType('DECIMAL(12, 2)')),
+                DataField(20, 'details', RowType(True, [
+                    DataField(21, 'times', ArrayType(True, ltz)),
+                    DataField(22, 'by_key', MapType(True, AtomicType('INT', 
False), ltz)),
+                ]))],
+        options={'bucket': '-1'},
+    ))
+    arrow_schema = pa.schema([
+        pa.field('event_time', timestamp_type, nullable=nullable),
+        pa.field('amount', pa.decimal128(12, 2)),
+        pa.field('details', pa.struct([
+            ('times', pa.list_(pa.timestamp('us', tz='UTC'))),
+            ('by_key', pa.map_(pa.int32(), pa.timestamp('us', tz='UTC'))),
+        ])),
+    ])
+    provided = Schema.from_pyarrow_schema(arrow_schema, options={'path': 
path.as_uri()})
+    before, supplied = _schema_files(path), JSON.to_json(provided)
+    with patch.object(server, '_tables_handle', wraps=server._tables_handle) 
as create:
+        if timestamp_type == pa.timestamp('us', tz='UTC') and nullable:
+            rest.create_table('default.registered', provided, False)
+            create.assert_called_once()
+            sent = JSON.from_json(create.call_args[0][1], 
CreateTableRequest).schema
+            assert sent.fields == latest.fields
+            assert sent.fields[0].type.type == 'TIMESTAMP(6) WITH LOCAL TIME 
ZONE'
+        else:
+            with pytest.raises(ValueError, match='External table fields'):
+                rest.create_table('default.registered', provided, False)
+            create.assert_not_called()
+    assert _schema_files(path) == before
+    assert JSON.to_json(provided) == supplied
+
+
[email protected]('ignore_if_exists', [False, True])
[email protected]('conflict', ['fields', 'partition', 'primary', 
'option', 'unknown-option'])
+def test_rejects_conflicts_before_sending_create(catalog, existing_table, 
conflict, ignore_if_exists):
+    rest, server = catalog
+    path, _ = existing_table
+    provided = Schema(options={'path': path.as_uri()})
+    if conflict == 'fields':
+        provided.fields = [DataField(0, 'wrong', AtomicType('INT'))]
+    elif conflict == 'partition':
+        provided.partition_keys = ['id']
+    elif conflict == 'primary':
+        provided.primary_keys = ['id']
+    elif conflict == 'option':
+        provided.options['file.format'] = 'orc'
+    else:
+        provided.options['new.option'] = 'value'
+    before = _schema_files(path)
+
+    with patch.object(rest.rest_api, 'create_table') as create:
+        with pytest.raises(ValueError, match='External table'):
+            rest.create_table('default.registered', provided, ignore_if_exists)
+        create.assert_not_called()
+
+    assert 'default.registered' not in server.table_metadata_store
+    assert _schema_files(path) == before
+
+
+def test_existing_registration_keeps_ignore_if_exists_behavior(catalog, 
existing_table):
+    rest, _ = catalog
+    path, _ = existing_table
+    provided = Schema(options={'path': path.as_uri()})
+    rest.create_table('default.registered', provided, False)
+    rest.create_table('default.registered', provided, True)
+    with pytest.raises(TableAlreadyExistException):
+        rest.create_table('default.registered', provided, False)
+
+
[email protected]('table_type', [None, 'format-table', 'object-table', 
'iceberg-table', 'lance'])
+def test_other_tables_do_not_read_filesystem_schema(catalog, table_type):
+    rest, _ = catalog
+    options = {} if table_type is None else {'type': table_type, 'path': 
's3://unused/table'}
+    provided = Schema(fields=[DataField(0, 'id', AtomicType('INT'))], 
options=options)
+    with patch.object(rest, 'file_io_from_options', 
side_effect=AssertionError('Unexpected filesystem lookup')), \
+            patch.object(rest.rest_api, 'create_table') as create:
+        rest.create_table('default.other', provided, False)
+        assert create.call_args[0][1] is provided
+
+
[email protected]('directory_exists', [False, True])
+def test_path_without_schema_keeps_original_request(catalog, tmp_path, 
directory_exists):
+    rest, _ = catalog
+    path = tmp_path / 'without-schema'
+    if directory_exists:
+        path.mkdir()
+    provided = Schema(fields=[DataField(0, 'id', AtomicType('INT'))], 
options={'path': path.as_uri()})
+    with patch.object(rest.rest_api, 'create_table') as create:
+        rest.create_table('default.other', provided, False)
+        assert create.call_args[0][1] is provided
+    assert path.exists() == directory_exists
+    assert not directory_exists or list(path.iterdir()) == []
+
+
+def test_null_schema_keeps_api_validation(catalog):
+    rest, server = catalog
+    with patch.object(server, '_tables_handle', wraps=server._tables_handle) 
as create:
+        with pytest.raises(ValueError, match='Schema cannot be None'):
+            rest.create_table('default.other', None, False)
+        create.assert_not_called()
+
+
[email protected]('corrupt', [False, True], ids=['unreadable', 
'corrupt'])
+def test_schema_read_errors_do_not_send_create(catalog, existing_table, 
corrupt):
+    rest, _ = catalog
+    path, latest = existing_table
+    if corrupt:
+        (path / 'schema' / ('schema-%d' % latest.id)).write_text('invalid 
JSON')
+    before = _schema_files(path)
+    file_io = FileIO.get(path.as_uri())
+    with patch.object(rest, 'file_io_from_options', return_value=file_io), \
+            patch.object(rest.rest_api, 'create_table') as create:
+        if corrupt:
+            with pytest.raises(RuntimeError, match='Failed to load schema'):
+                rest.create_table('default.registered', 
Schema(options={'path': path.as_uri()}), False)
+        else:
+            with patch.object(file_io, 'read_file_utf8', 
side_effect=PermissionError('denied')):
+                with pytest.raises(RuntimeError, match='Failed to load 
schema'):
+                    rest.create_table('default.registered', 
Schema(options={'path': path.as_uri()}), False)
+        create.assert_not_called()
+    assert _schema_files(path) == before
+
+
+def test_inference_does_not_mutate_cached_schema(catalog, existing_table):
+    rest, _ = catalog
+    path, latest = existing_table
+    before = deepcopy(latest)
+    with patch('pypaimon.catalog.rest.rest_catalog.SchemaManager') as manager, 
\
+            patch.object(rest.rest_api, 'create_table') as create:
+        manager.return_value.latest.return_value = latest
+        rest.create_table('default.registered', Schema(options={
+            'path': path.as_uri(), 'owner': 'new-owner'}), False)
+    sent = create.call_args[0][1]
+    assert sent.fields is not latest.fields
+    assert sent.options['owner'] == 'new-owner'
+    assert latest == before
diff --git a/paimon-python/pypaimon/tests/rest/rest_server.py 
b/paimon-python/pypaimon/tests/rest/rest_server.py
index 704bbfe21e..1434157f62 100755
--- a/paimon-python/pypaimon/tests/rest/rest_server.py
+++ b/paimon-python/pypaimon/tests/rest/rest_server.py
@@ -2072,11 +2072,20 @@ class RESTCatalogServer:
                 create_table = JSON.from_json(data, CreateTableRequest)
                 if create_table.identifier.get_full_name() in 
self.table_metadata_store:
                     raise TableAlreadyExistException(create_table.identifier)
+                options = create_table.schema.options
+                external = PATH in options and options.get(TYPE, 
'table').strip().lower() == 'table'
+                schema_id = 0
+                if external:
+                    latest = SchemaManager(self._get_file_io(), 
options[PATH]).latest()
+                    if latest is not None:
+                        schema_id = latest.id
                 table_metadata = self._create_table_metadata(
-                    create_table.identifier, 0, create_table.schema, 
str(uuid.uuid4()), False
+                    create_table.identifier, schema_id, create_table.schema, 
str(uuid.uuid4()), external
                 )
                 
self.table_metadata_store.update({create_table.identifier.get_full_name(): 
table_metadata})
                 
self.table_identifiers[create_table.identifier.get_full_name()] = 
create_table.identifier
+                if external:
+                    return self._mock_response("", 200)
                 table_dir = (
                     Path(self.data_path) / self.warehouse / database_name /
                     create_table.identifier.get_object_name() / 'schema'
@@ -2098,6 +2107,8 @@ class RESTCatalogServer:
                 identifier, (response_identifier or 
identifier).get_branch_name())
             table_path = (f'file://{self.data_path}/{self.warehouse}/'
                           
f'{identifier.get_database_name()}/{identifier.get_object_name()}')
+            if table_metadata.is_external:
+                table_path = table_metadata.schema.options.get(PATH, 
table_path)
             schema = table_metadata.schema.to_schema()
             response = self.mock_table(
                 response_identifier or identifier, table_metadata, table_path, 
schema)
@@ -2389,6 +2400,8 @@ class RESTCatalogServer:
         table_path = (
             f'file://{self.data_path}/{self.warehouse}/'
             f'{identifier.get_database_name()}/{identifier.get_object_name()}')
+        if table_metadata.is_external:
+            table_path = table_schema.options.get(PATH, table_path)
 
         table_identifier = Identifier.create(
             identifier.get_database_name(), identifier.get_table_name(), 
branch=branch)
diff --git a/paimon-python/pypaimon/tests/schema_manager_test.py 
b/paimon-python/pypaimon/tests/schema_manager_test.py
index 1b0f493042..6d33e198ea 100644
--- a/paimon-python/pypaimon/tests/schema_manager_test.py
+++ b/paimon-python/pypaimon/tests/schema_manager_test.py
@@ -18,6 +18,7 @@
 import os
 import tempfile
 import unittest
+from copy import deepcopy
 from unittest.mock import patch
 
 from pypaimon import CatalogFactory
@@ -28,7 +29,7 @@ from pypaimon.common.file_io import FileIO
 from pypaimon.common.options.core_options import CoreOptions, MergeEngine
 from pypaimon.common.options.options import Options
 from pypaimon.schema.data_types import (ArrayType, AtomicType, DataField,
-                                        MapType, RowType)
+                                        MapType, MultisetType, RowType, 
VectorType)
 from pypaimon.schema.schema import Schema
 from pypaimon.schema.schema_change import RemoveOption, SchemaChange, SetOption
 from pypaimon.schema.schema_manager import SchemaManager
@@ -927,5 +928,128 @@ class TestColumnAndKeyValidation(unittest.TestCase):
                     self.catalog.create_table("default.t", 
self._schema(**kwargs), False)
 
 
+class TestExternalSchemaValidation(unittest.TestCase):
+
+    @staticmethod
+    def _schema(offset=0):
+        return Schema(
+            fields=[
+                DataField(offset + 9, 'id', AtomicType('INT', False), 
'identifier', '0'),
+                DataField(offset + 20, 'pt', AtomicType('STRING', False)),
+                DataField(offset + 30, 'payload', MapType(
+                    True, RowType(False, [DataField(offset + 31, 'key', 
AtomicType('INT', False))]),
+                    ArrayType(True, MultisetType(False, RowType(True, [
+                        DataField(offset + 32, 'text', AtomicType('STRING'), 
'nested value'),
+                    ]))))),
+                DataField(offset + 40, 'embedding', VectorType(True, 
AtomicType('FLOAT'), 3)),
+            ],
+            partition_keys=['pt'], primary_keys=['id', 'pt'],
+            options={'bucket': '1', 'file.format': 'parquet', 'owner': 
'original'},
+        )
+
+    def test_accepts_different_field_ids_without_mutating_inputs(self):
+        existing, provided = self._schema(), self._schema(100)
+        before = deepcopy((existing, provided))
+
+        SchemaManager.check_schema_for_external_table(existing, provided)
+
+        self.assertEqual((existing, provided), before)
+
+    def test_accepts_omitted_definitions_and_owner_path_overrides(self):
+        existing = self._schema()
+        provided = Schema(options={'path': 'file:///registered', 'owner': 
'new-owner'})
+
+        SchemaManager.check_schema_for_external_table(existing, provided)
+        SchemaManager.check_schema_for_external_table(
+            existing, Schema(options={'file.format': 'parquet'}))
+
+    def test_accepts_equivalent_logical_type_spellings(self):
+        cases = [
+            ('TIMESTAMP(6) WITH LOCAL TIME ZONE', 'TIMESTAMP_LTZ(6)'),
+            ('TIMESTAMP WITH LOCAL TIME ZONE', 'TIMESTAMP_LTZ(6)'),
+            ('TIMESTAMP_LTZ', 'TIMESTAMP(6) WITH LOCAL TIME ZONE'),
+            ('TIMESTAMP', 'TIMESTAMP(6)'),
+            ('TIMESTAMP(3) WITHOUT TIME ZONE', 'TIMESTAMP(3)'),
+            ('TIME', 'TIME(0)'),
+            ('TIME(3) WITHOUT TIME ZONE', 'TIME(3)'),
+            ('DECIMAL(12,2)', 'DECIMAL(12, 2)'),
+            ('NUMERIC(12)', 'DECIMAL(12, 0)'),
+            ('DEC', 'DECIMAL(10, 0)'),
+            ('DECIMAL', 'DECIMAL(10)'),
+            ('INTEGER', 'INT'),
+            ('DOUBLE PRECISION', 'DOUBLE'),
+            ('CHAR', 'CHAR(1)'),
+            ('VARCHAR', 'VARCHAR(1)'),
+            ('STRING', 'VARCHAR(2147483647)'),
+            ('BINARY', 'BINARY(1)'),
+            ('VARBINARY', 'VARBINARY(1)'),
+            ('BYTES', 'VARBINARY(2147483647)'),
+            (' decimal ( 12 , 02 ) ', 'DECIMAL(12, 2)'),
+        ]
+        for source, target in cases:
+            with self.subTest(source=source, target=target):
+                existing = Schema(fields=[DataField(7, 'value', 
AtomicType(source))])
+                provided = Schema(fields=[DataField(0, 'value', 
AtomicType(target))])
+                before = deepcopy((existing, provided))
+                SchemaManager.check_schema_for_external_table(existing, 
provided)
+                SchemaManager.check_schema_for_external_table(provided, 
existing)
+                self.assertEqual((existing, provided), before)
+
+    def test_rejects_different_logical_types(self):
+        cases = [
+            ('TIMESTAMP(6) WITH LOCAL TIME ZONE', 'TIMESTAMP_LTZ(3)'),
+            ('TIMESTAMP(6) WITH LOCAL TIME ZONE', 'TIMESTAMP_LTZ(5)'),
+            ('TIMESTAMP(6) WITH LOCAL TIME ZONE', 'TIMESTAMP(6)'),
+            ('DECIMAL(12, 2)', 'NUMERIC(12, 3)'),
+            ('DECIMAL(12, 0)', 'DECIMAL(13)'),
+            ('TIME', 'TIME(6)'),
+            ('VARCHAR', 'STRING'),
+            ('VARCHAR(10)', 'VARCHAR(11)'),
+            ('CHAR(10)', 'VARCHAR(10)'),
+            ('BINARY(10)', 'VARBINARY(10)'),
+            ('BYTES', 'BLOB'),
+        ]
+        for source, target in cases:
+            with self.subTest(source=source, target=target):
+                existing = Schema(fields=[DataField(7, 'value', 
AtomicType(source))])
+                provided = Schema(fields=[DataField(0, 'value', 
AtomicType(target))])
+                with self.assertRaisesRegex(ValueError, 'External table 
fields'):
+                    SchemaManager.check_schema_for_external_table(existing, 
provided)
+
+    def test_rejects_conflicting_fields(self):
+        cases = [
+            ('count', lambda s: s.fields.pop()),
+            ('order', lambda s: s.fields.reverse()),
+            ('name', lambda s: setattr(s.fields[0], 'name', 'other')),
+            ('type', lambda s: setattr(s.fields[0], 'type', 
AtomicType('BIGINT', False))),
+            ('nullable', lambda s: setattr(s.fields[0].type, 'nullable', 
True)),
+            ('description', lambda s: setattr(s.fields[0], 'description', 
'changed')),
+            ('default', lambda s: setattr(s.fields[0], 'default_value', '1')),
+            ('map-key', lambda s: setattr(s.fields[2].type.key.fields[0], 
'name', 'other')),
+            ('nested', lambda s: setattr(
+                s.fields[2].type.value.element.element.fields[0].type, 
'nullable', False)),
+            ('vector-length', lambda s: setattr(s.fields[3].type, 'length', 
4)),
+            ('vector-element', lambda s: setattr(s.fields[3].type, 'element', 
AtomicType('DOUBLE'))),
+        ]
+        for name, change in cases:
+            with self.subTest(change=name):
+                existing, provided = self._schema(), self._schema(100)
+                change(provided)
+                with self.assertRaisesRegex(ValueError, 'External table 
fields'):
+                    SchemaManager.check_schema_for_external_table(existing, 
provided)
+
+    def test_rejects_conflicting_keys_and_options(self):
+        cases = [
+            (Schema(partition_keys=['id']), 'partition keys'),
+            (Schema(primary_keys=['pt', 'id']), 'primary keys'),
+            (Schema(options={'file.format': 'orc'}), "option 'file.format'"),
+            (Schema(options={'new.option': 'value'}), "option 'new.option'"),
+        ]
+        for provided, message in cases:
+            with self.subTest(message=message):
+                with self.assertRaisesRegex(ValueError, message):
+                    
SchemaManager.check_schema_for_external_table(self._schema(), provided)
+
+
 if __name__ == '__main__':
     unittest.main()

Reply via email to