World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14829] feat(python): Expose Semantic Model dataset lookup on sources (#14830)
mchadesc4c2108d7927
diff --git a/clients/client-python/gravitino/api/rel/table.py b/clients/client-python/gravitino/api/rel/table.pyindex 5bb1b27933..b2e5270d48 100644--- a/clients/client-python/gravitino/api/rel/table.py+++ b/clients/client-python/gravitino/api/rel/table.py@@ -29,6 +29,7 @@ from gravitino.api.rel.expressions.transforms.transforms import Transformsfrom gravitino.api.rel.indexes.index import Indexfrom gravitino.api.rel.indexes.indexes import Indexesfrom gravitino.api.secret.supports_secrets import SupportsSecrets+from gravitino.api.semantic.supports_semantic_models import SupportsSemanticModelsfrom gravitino.api.stats.supports_statistics import SupportsStatisticsfrom gravitino.api.policy.supports_policies import SupportsPoliciesfrom gravitino.api.tag.supports_tags import SupportsTags@@ -117,6 +118,19 @@ class Table(Auditable):return {}+ def supports_semantic_models(self) -> SupportsSemanticModels:+ """Return source-scoped Semantic Model dataset lookup operations.++ Returns:+ SupportsSemanticModels: The dataset lookup operations for this source.++ Raises:+ UnsupportedOperationException: If this implementation does not support lookup.+ """+ raise UnsupportedOperationException(+ "Semantic Model dataset lookup is not supported"+ )+def supports_tags(self) -> SupportsTags:raise UnsupportedOperationException("Table does not support tag operations.")diff --git a/clients/client-python/gravitino/api/rel/view.py b/clients/client-python/gravitino/api/rel/view.pyindex 0172491c21..0f184a12a8 100644--- a/clients/client-python/gravitino/api/rel/view.py+++ b/clients/client-python/gravitino/api/rel/view.py@@ -23,6 +23,7 @@ from gravitino.api.rel.column import Columnfrom gravitino.api.rel.representation import Representationfrom gravitino.api.rel.sql_representation import SQLRepresentationfrom gravitino.api.secret.supports_secrets import SupportsSecrets+from gravitino.api.semantic.supports_semantic_models import SupportsSemanticModelsfrom gravitino.api.tag.supports_tags import SupportsTagsfrom gravitino.exceptions.base import UnsupportedOperationException@@ -70,6 +71,19 @@ class View(Auditable):"""Returns the view properties."""return {}+ def supports_semantic_models(self) -> SupportsSemanticModels:+ """Return source-scoped Semantic Model dataset lookup operations.++ Returns:+ SupportsSemanticModels: The dataset lookup operations for this source.++ Raises:+ UnsupportedOperationException: If this implementation does not support lookup.+ """+ raise UnsupportedOperationException(+ "Semantic Model dataset lookup is not supported"+ )+def supports_tags(self) -> SupportsTags:"""Return tag operations if the view supports tags.diff --git a/clients/client-python/gravitino/api/semantic/supports_semantic_models.py b/clients/client-python/gravitino/api/semantic/supports_semantic_models.pynew file mode 100644index 0000000000..9fcfc5ea99--- /dev/null+++ b/clients/client-python/gravitino/api/semantic/supports_semantic_models.py@@ -0,0 +1,46 @@+# 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 abc import ABC, abstractmethod++from gravitino.name_identifier import NameIdentifier+++class SupportsSemanticModels(ABC):+ """Source-scoped discovery of datasets directly associated with tables or views."""++ @abstractmethod+ def list_semantic_model_datasets(self) -> list[NameIdentifier]:+ """List datasets from models the caller can load in the source's metalake.++ Identifiers contain [metalake, catalog, schema, semanticModel] as their+ namespace and the exact dataset name, including any literal dots. Results+ preserve server ordering: namespace components followed by dataset name,+ comparing each component case-sensitively by UTF-16 code units.+ For a returned dataset, ``NameIdentifier.of(*dataset.namespace().levels())``+ identifies its containing model.++ Associations reflect the latest definition write, not execution validity+ or transitive dependencies.++ Returns:+ Fully qualified dataset identifiers, or an empty list.++ Raises:+ NoSuchMetadataObjectException: If the source does not exist.+ """+ raise NotImplementedErrordiff --git a/clients/client-python/gravitino/client/generic_view.py b/clients/client-python/gravitino/client/generic_view.pyindex 0802b6f041..0990a448dd 100644--- a/clients/client-python/gravitino/client/generic_view.py+++ b/clients/client-python/gravitino/client/generic_view.py@@ -24,12 +24,16 @@ from gravitino.api.rel.column import Columnfrom gravitino.api.rel.representation import Representationfrom gravitino.api.rel.view import Viewfrom gravitino.api.secret.supports_secrets import SupportsSecrets+from gravitino.api.semantic.supports_semantic_models import SupportsSemanticModelsfrom gravitino.api.tag.supports_tags import SupportsTagsfrom gravitino.api.tag.tag import Tagfrom gravitino.api.tag.tag_list import TagListfrom gravitino.client.metadata_object_secret_operations import (MetadataObjectSecretOperations,)+from gravitino.client.metadata_object_semantic_model_operations import (+ MetadataObjectSemanticModelOperations,+)from gravitino.client.metadata_object_tag_operations import MetadataObjectTagOperationsfrom gravitino.dto.rel.view_dto import ViewDTOfrom gravitino.namespace import Namespace@@ -61,6 +65,9 @@ class GenericView(View, SupportsTags, SupportsSecrets):],MetadataObject.Type.VIEW,)+ self._object_semantic_model_operations = MetadataObjectSemanticModelOperations(+ view_namespace.level(0), view_object, rest_client+ )self._object_tag_operations = MetadataObjectTagOperations(view_namespace.level(0),view_object,@@ -126,6 +133,9 @@ class GenericView(View, SupportsTags, SupportsSecrets):tags_to_remove,)+ def supports_semantic_models(self) -> SupportsSemanticModels:+ return self._object_semantic_model_operations+def supports_tags(self) -> SupportsTags:return selfdiff --git a/clients/client-python/gravitino/client/metadata_object_semantic_model_operations.py b/clients/client-python/gravitino/client/metadata_object_semantic_model_operations.pynew file mode 100644index 0000000000..86fbb083cf--- /dev/null+++ b/clients/client-python/gravitino/client/metadata_object_semantic_model_operations.py@@ -0,0 +1,47 @@+# 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 gravitino.api.metadata_object import MetadataObject+from gravitino.api.semantic.supports_semantic_models import SupportsSemanticModels+from gravitino.dto.responses.entity_list_response import EntityListResponse+from gravitino.exceptions.handlers.semantic_model_error_handler import (+ SEMANTIC_MODEL_ERROR_HANDLER,+)+from gravitino.name_identifier import NameIdentifier+from gravitino.rest.rest_utils import encode_string+from gravitino.utils.http_client import HTTPClient+++class MetadataObjectSemanticModelOperations(SupportsSemanticModels):+ """Shared relationship request handling for tables and views."""++ def __init__(self, metalake: str, source: MetadataObject, rest_client: HTTPClient):+ self._rest_client = rest_client+ self._request_path = (+ f"api/metalakes/{encode_string(metalake)}/objects/"+ f"{source.type().name.lower()}/{encode_string(source.full_name())}"+ "/semantic-model-datasets"+ )++ def list_semantic_model_datasets(self) -> list[NameIdentifier]:+ response = self._rest_client.get(+ endpoint=self._request_path,+ error_handler=SEMANTIC_MODEL_ERROR_HANDLER,+ )+ result = EntityListResponse.from_json(response.body, infer_missing=True)+ result.validate()+ return result.identifiers()diff --git a/clients/client-python/gravitino/client/relational_table.py b/clients/client-python/gravitino/client/relational_table.pyindex f753158c03..4540d8d120 100644--- a/clients/client-python/gravitino/client/relational_table.py+++ b/clients/client-python/gravitino/client/relational_table.py@@ -32,6 +32,7 @@ from gravitino.api.rel.indexes.index import Indexfrom gravitino.api.rel.partitions.partition import Partitionfrom gravitino.api.rel.table import Tablefrom gravitino.api.secret.supports_secrets import SupportsSecrets+from gravitino.api.semantic.supports_semantic_models import SupportsSemanticModelsfrom gravitino.api.stats.statistic import Statisticfrom gravitino.api.stats.statistic_value import StatisticValuefrom gravitino.api.stats.supports_statistics import SupportsStatistics@@ -48,6 +49,9 @@ from gravitino.client.metadata_object_role_operations import (from gravitino.client.metadata_object_secret_operations import (MetadataObjectSecretOperations,)+from gravitino.client.metadata_object_semantic_model_operations import (+ MetadataObjectSemanticModelOperations,+)from gravitino.client.metadata_object_statistics_operations import (MetadataObjectStatisticsOperations,)@@ -90,6 +94,9 @@ class RelationalTable(RelationalTable.table_full_name(namespace, table_dto.name()),MetadataObject.Type.TABLE,)+ self._object_semantic_model_operations = MetadataObjectSemanticModelOperations(+ namespace.level(0), table_object, rest_client+ )self._object_tag_operations = MetadataObjectTagOperations(namespace.level(0), table_object, rest_client)@@ -297,6 +304,9 @@ class RelationalTable() -> list[str]:return self._object_tag_operations.associate_tags(tags_to_add, tags_to_remove)+ def supports_semantic_models(self) -> SupportsSemanticModels:+ return self._object_semantic_model_operations+def supports_tags(self) -> SupportsTags:return selfdiff --git a/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py b/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.pyindex cc83cdba80..4f5f9ae8ae 100644--- a/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py+++ b/clients/client-python/gravitino/exceptions/handlers/semantic_model_error_handler.py@@ -25,6 +25,7 @@ from gravitino.exceptions.base import (IllegalSemanticModelException,MetalakeNotInUseException,NoSuchCatalogException,+ NoSuchMetadataObjectException,NoSuchMetalakeException,NoSuchSchemaException,NoSuchSemanticModelException,@@ -72,6 +73,8 @@ class SemanticModelErrorHandler(RestErrorHandler):@staticmethoddef _raise_not_found(exception_type: str, error_message: str):+ if exception_type == NoSuchMetadataObjectException.__name__:+ raise NoSuchMetadataObjectException(error_message)if exception_type == NoSuchMetalakeException.__name__:raise NoSuchMetalakeException(error_message)if exception_type == NoSuchCatalogException.__name__:diff --git a/clients/client-python/tests/unittests/client/test_metadata_object_semantic_model_operations.py b/clients/client-python/tests/unittests/client/test_metadata_object_semantic_model_operations.pynew file mode 100644index 0000000000..9015ad2cbc--- /dev/null+++ b/clients/client-python/tests/unittests/client/test_metadata_object_semantic_model_operations.py@@ -0,0 +1,189 @@+# 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.++import json+import unittest+from dataclasses import replace+from io import BytesIO+from unittest.mock import Mock, patch+from urllib.error import HTTPError, URLError++from gravitino.api.rel.table import Table+from gravitino.api.rel.view import View+from gravitino.client.generic_view import GenericView+from gravitino.client.relational_table import RelationalTable+from gravitino.constants.error import ErrorConstants+from gravitino.dto.audit_dto import AuditDTO+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO+from gravitino.dto.rel.table_dto import TableDTO+from gravitino.dto.rel.view_dto import ViewDTO+from gravitino.exceptions.base import (+ ForbiddenException,+ IllegalArgumentException,+ InternalError,+ NoSuchMetadataObjectException,+ NotFoundException,+ UnsupportedOperationException,+)+from gravitino.name_identifier import NameIdentifier+from gravitino.namespace import Namespace+from gravitino.utils import HTTPClient+from tests.unittests.fixtures.table_fixtures import TABLE_DTO_JSON_STRING+++class TestMetadataObjectSemanticModelOperations(unittest.TestCase):+ def setUp(self):+ client = HTTPClient("http://localhost:8090")+ self.addCleanup(client.close)+ namespace = Namespace.of("metalake /%? 测试", "catalog", "schema")+ source_name = "orders /%? 明细"+ table = replace(TableDTO.from_json(TABLE_DTO_JSON_STRING), _name=source_name)+ self.sources = {+ "table": RelationalTable(namespace, table, client),+ "view": GenericView(+ ViewDTO(+ _name=source_name,+ _audit=AuditDTO("creator"),+ _representations=[+ SQLRepresentationDTO(_dialect="trino", _sql="SELECT 1")+ ],+ ),+ client,+ namespace,+ ),+ }+ opener_patch = patch("gravitino.utils.http_client.build_opener")+ self.opener = opener_patch.start().return_value+ self.addCleanup(opener_patch.stop)+ self.opener.open.return_value.getcode.return_value = 200++ def test_one_get_preserves_full_identifiers_and_server_order(self):+ model_namespace = ["metalake /%? 测试", "another_catalog", "schema", "a"]+ identifiers = [+ {"namespace": model_namespace, "name": name}+ for name in ("Orders.raw", "orders.raw")+ ] + [+ {"namespace": model_namespace[:-1] + ["a-b"], "name": name}+ # Supplementary characters precede U+E000 in UTF-16 order.+ for name in ("收入", "\U00010000", "\ue000")+ ]+ expected = [+ NameIdentifier.of(*item["namespace"], item["name"]) for item in identifiers+ ]+ for source_type, source in self.sources.items():+ with self.subTest(source=source_type):+ self._respond({"code": 0, "identifiers": identifiers})+ actual = (+ source.supports_semantic_models().list_semantic_model_datasets()+ )+ self.assertEqual(expected, actual)+ self.assertEqual(4, actual[0].namespace().length())+ self.assertEqual("Orders.raw", actual[0].name())+ self.assertEqual(+ NameIdentifier.of(*model_namespace),+ NameIdentifier.of(*actual[0].namespace().levels()),+ )+ self._assert_request(source_type)++ def test_empty_results(self):+ for source_type, source in self.sources.items():+ with self.subTest(source=source_type):+ self._respond({"code": 0, "identifiers": []})+ self.assertEqual(+ [], source.supports_semantic_models().list_semantic_model_datasets()+ )+ self._assert_request(source_type)++ def test_http_errors_are_not_empty_results(self):+ cases = (+ (404, ErrorConstants.NOT_FOUND_CODE, NoSuchMetadataObjectException),+ (404, ErrorConstants.NOT_FOUND_CODE, NotFoundException),+ (400, ErrorConstants.ILLEGAL_ARGUMENTS_CODE, IllegalArgumentException),+ (403, ErrorConstants.FORBIDDEN_CODE, ForbiddenException),+ (500, ErrorConstants.INTERNAL_ERROR_CODE, InternalError),+ )+ for source_type, source in self.sources.items():+ for status, code, exception_type in cases:+ with self.subTest(source=source_type, error=exception_type):+ self.opener.open.reset_mock()+ payload = json.dumps(+ {+ "code": code,+ "type": exception_type.__name__,+ "message": "lookup failed",+ }+ ).encode("utf-8")+ self.opener.open.side_effect = HTTPError(+ "http://localhost:8090",+ status,+ "lookup failed",+ {},+ BytesIO(payload),+ )+ with self.assertRaises(exception_type) as raised:+ source.supports_semantic_models().list_semantic_model_datasets()+ self.assertIs(exception_type, type(raised.exception))+ self.assertIn("lookup failed", str(raised.exception))+ self._assert_request(source_type)++ def test_transport_failures_are_not_empty_results(self):+ for source_type, source in self.sources.items():+ with self.subTest(source=source_type):+ self.opener.open.reset_mock()+ failure = URLError("source lookup unavailable")+ self.opener.open.side_effect = failure+ with self.assertRaises(URLError) as raised:+ source.supports_semantic_models().list_semantic_model_datasets()+ self.assertIs(failure, raised.exception)+ self._assert_request(source_type)++ def test_invalid_response_is_rejected(self):+ for source_type, source in self.sources.items():+ for payload in ({"code": 0}, {"code": 0, "identifiers": None}):+ with self.subTest(source=source_type, payload=payload):+ self._respond(payload)+ with self.assertRaisesRegex(+ IllegalArgumentException, "identifiers must not be null"+ ):+ source.supports_semantic_models().list_semantic_model_datasets()+ self._assert_request(source_type)++ def test_default_capabilities_remain_optional(self):+ with self.assertRaises(UnsupportedOperationException):+ Table.supports_semantic_models(Mock())+ with self.assertRaises(UnsupportedOperationException):+ View.supports_semantic_models(Mock())++ def _respond(self, body):+ self.opener.open.reset_mock()+ self.opener.open.side_effect = None+ self.opener.open.return_value.read.return_value = json.dumps(body).encode(+ "utf-8"+ )++ def _assert_request(self, source_type):+ self.opener.open.assert_called_once()+ request = self.opener.open.call_args.args[0]+ self.assertEqual("GET", request.get_method())+ self.assertEqual(+ "http://localhost:8090/api/metalakes/"+ "metalake%20%2F%25%3F%20%E6%B5%8B%E8%AF%95/objects/"+ + source_type+ + "/catalog.schema.orders%20%2F%25%3F%20%E6%98%8E%E7%BB%86"+ "/semantic-model-datasets",+ request.full_url,+ )