You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by js...@apache.org on 2026/08/28 11:42:33 UTC

(gravitino) branch branch-1.3 updated (810777fce7 -> 50261f1383)

This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a change to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git


    from 810777fce7 [Cherry-pick to branch-1.3] [#12269] fix(authz): Allow catalog owners to grant schema privileges (#12673) (#12701)
     new 07d5936d0a [#11844] feat(tag): Support tags for views and functions (#11897)
     new 666b3b01d4 [#11902] feat(client-java): Support tags for views and functions (#11903)
     new 071bb7c9d7 [#12039] feat(client-python): Add view API definitions (#12040)
     new 50aa8e3651 [#12089] improvement(client-python): Implement client-side view models (#12090)
     new 561bb566b6 [#12116] improvement(client-python): Add view create/drop operations (#12117)
     new 17fb105c56 [#12158] improvement(client-python): Add view query/alter operations (#12159)
     new 50261f1383 [#12181] feat(client-python): Support tags for views and functions (#12182)

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../org/apache/gravitino/function/Function.java    |   9 +
 .../main/java/org/apache/gravitino/rel/View.java   |   9 +
 .../client/FunctionCatalogOperations.java          |  10 +-
 .../{GenericColumn.java => GenericFunction.java}   |  97 +++----
 .../{GenericColumn.java => GenericView.java}       | 105 ++++----
 .../apache/gravitino/client/RelationalCatalog.java |   6 +-
 .../gravitino/client/TestFunctionCatalog.java      |  46 ++++
 .../apache/gravitino/client/TestSupportTags.java   | 107 ++++++++
 .../gravitino/client/integration/test/TagIT.java   | 227 ++++++++++++++++
 clients/client-python/gravitino/api/catalog.py     |  10 +
 .../gravitino/api/function/function.py             |  13 +
 .../client-python/gravitino/api/rel/dialects.py    |   9 +-
 .../rel/representation.py}                         |  12 +-
 .../rel/sql_representation.py}                     |  35 ++-
 clients/client-python/gravitino/api/rel/view.py    |  81 ++++++
 .../gravitino/api/rel/view_catalog.py              | 149 +++++++++++
 .../client-python/gravitino/api/rel/view_change.py | 214 +++++++++++++++
 .../client/function_catalog_operations.py          |  17 +-
 .../gravitino/client/generic_function.py           |  56 +++-
 .../client/{generic_column.py => generic_view.py}  |  87 +++---
 .../client/metadata_object_tag_operations.py       |   5 +-
 .../gravitino/client/relational_catalog.py         | 224 ++++++++++++++--
 .../dto/rel/json_serdes/representation_serdes.py   |  49 ++++
 .../auditable.py => dto/rel/representation_dto.py} |  17 +-
 .../sql_representation_dto.py}                     |  40 ++-
 .../client-python/gravitino/dto/rel/view_dto.py    | 105 ++++++++
 .../gravitino/dto/requests/view_create_request.py  |  96 +++++++
 .../gravitino/dto/requests/view_update_request.py  | 166 ++++++++++++
 ..._updates_request.py => view_updates_request.py} |  26 +-
 ...{function_list_response.py => view_response.py} |  34 +--
 .../gravitino/dto/util/dto_converters.py           |  54 +++-
 clients/client-python/gravitino/exceptions/base.py |   8 +
 ...able_error_handler.py => view_error_handler.py} |  20 +-
 .../tests/integration/test_relational_catalog.py   | 171 ++++++++++++
 .../tests/integration/test_supports_tags.py        | 107 ++++++++
 .../unittests/api/function}/__init__.py            |   0
 .../unittests/api/function/test_function.py}       |  23 +-
 .../unittests/api/rel/test_sql_representation.py   |  54 ++++
 .../tests/unittests/api/rel/test_view.py           |  76 ++++++
 .../tests/unittests/api/rel/test_view_change.py    | 150 +++++++++++
 .../dto/rel/test_representation_serdes.py          |  54 ++++
 .../dto/rel/test_sql_representation_dto.py         |  55 ++++
 .../tests/unittests/dto/rel/test_view_dto.py       | 293 +++++++++++++++++++++
 .../dto/requests/test_view_create_request.py       | 144 ++++++++++
 .../dto/requests/test_view_update_request.py       | 197 ++++++++++++++
 .../unittests/dto/responses/test_view_response.py  |  51 ++++
 .../unittests/dto/util/test_dto_converters.py      |  52 ++++
 .../tests/unittests/test_error_handler.py          |  83 ++++++
 .../tests/unittests/test_generic_function.py       |  79 ++++++
 .../tests/unittests/test_generic_view.py           |  85 ++++++
 .../tests/unittests/test_relational_catalog.py     | 251 ++++++++++++++++++
 .../base/TagMetadataObjectRelBaseSQLProvider.java  |  28 ++
 .../TagMetadataObjectRelPostgreSQLProvider.java    |  28 ++
 .../relational/service/FunctionMetaService.java    |   6 +
 .../java/org/apache/gravitino/tag/TagManager.java  |   4 +-
 .../relational/service/TestCatalogMetaService.java | 157 +++++++++++
 .../service/TestFunctionMetaService.java           |  42 +++
 .../relational/service/TestSchemaMetaService.java  | 146 ++++++++++
 .../relational/service/TestViewMetaService.java    |  41 +++
 .../org/apache/gravitino/tag/TestTagManager.java   | 167 +++++++++++-
 .../gravitino/utils/TestMetadataObjectUtil.java    |  11 +
 docs/open-api/openapi.yaml                         |   3 +-
 docs/open-api/tags.yaml                            |   4 +-
 .../web/rest/TestMetadataObjectTagOperations.java  | 262 +++++++++++++++++-
 64 files changed, 4691 insertions(+), 276 deletions(-)
 copy clients/client-java/src/main/java/org/apache/gravitino/client/{GenericColumn.java => GenericFunction.java} (57%)
 copy clients/client-java/src/main/java/org/apache/gravitino/client/{GenericColumn.java => GenericView.java} (58%)
 copy mcp-server/mcp_server/client/plain/exception.py => clients/client-python/gravitino/api/rel/dialects.py (84%)
 copy clients/client-python/gravitino/{auth/auth_constants.py => api/rel/representation.py} (77%)
 copy clients/client-python/gravitino/{dto/requests/user_add_request.py => api/rel/sql_representation.py} (55%)
 create mode 100644 clients/client-python/gravitino/api/rel/view.py
 create mode 100644 clients/client-python/gravitino/api/rel/view_catalog.py
 create mode 100644 clients/client-python/gravitino/api/rel/view_change.py
 copy clients/client-python/gravitino/client/{generic_column.py => generic_view.py} (50%)
 create mode 100644 clients/client-python/gravitino/dto/rel/json_serdes/representation_serdes.py
 copy clients/client-python/gravitino/{api/auditable.py => dto/rel/representation_dto.py} (70%)
 copy clients/client-python/gravitino/dto/{responses/table_response.py => rel/sql_representation_dto.py} (50%)
 create mode 100644 clients/client-python/gravitino/dto/rel/view_dto.py
 create mode 100644 clients/client-python/gravitino/dto/requests/view_create_request.py
 create mode 100644 clients/client-python/gravitino/dto/requests/view_update_request.py
 copy clients/client-python/gravitino/dto/requests/{metalake_updates_request.py => view_updates_request.py} (61%)
 copy clients/client-python/gravitino/dto/responses/{function_list_response.py => view_response.py} (55%)
 copy clients/client-python/gravitino/exceptions/handlers/{table_error_handler.py => view_error_handler.py} (83%)
 copy clients/client-python/{gravitino/api => tests/unittests/api/function}/__init__.py (100%)
 copy clients/client-python/{gravitino/dto/responses/catalog_list_response.py => tests/unittests/api/function/test_function.py} (59%)
 create mode 100644 clients/client-python/tests/unittests/api/rel/test_sql_representation.py
 create mode 100644 clients/client-python/tests/unittests/api/rel/test_view.py
 create mode 100644 clients/client-python/tests/unittests/api/rel/test_view_change.py
 create mode 100644 clients/client-python/tests/unittests/dto/rel/test_representation_serdes.py
 create mode 100644 clients/client-python/tests/unittests/dto/rel/test_sql_representation_dto.py
 create mode 100644 clients/client-python/tests/unittests/dto/rel/test_view_dto.py
 create mode 100644 clients/client-python/tests/unittests/dto/requests/test_view_create_request.py
 create mode 100644 clients/client-python/tests/unittests/dto/requests/test_view_update_request.py
 create mode 100644 clients/client-python/tests/unittests/dto/responses/test_view_response.py
 create mode 100644 clients/client-python/tests/unittests/test_generic_function.py
 create mode 100644 clients/client-python/tests/unittests/test_generic_view.py


(gravitino) 01/07: [#11844] feat(tag): Support tags for views and functions (#11897)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 07d5936d0a6111f32dbf7dde41c3e032eacbd064
Author: Zhiguo Wu <wu...@apache.org>
AuthorDate: Mon Jul 13 15:19:43 2026 +0800

    [#11844] feat(tag): Support tags for views and functions (#11897)
    
    ### What changes were proposed in this pull request?
    
    This PR adds tag support for VIEW and FUNCTION metadata objects.
    
    The changes include:
    - Allowing VIEW and FUNCTION in `TagManager` supported metadata object
    types.
    - Updating OpenAPI definitions for metadata object tag operations.
    - Cleaning up function tag relations when functions are dropped.
    - Cleaning up view/function tag relations during catalog and schema
    cascade deletion, including PostgreSQL-specific SQL providers.
    - Adding unit tests for tag association and cascade cleanup behavior.
    
    ### Why are the changes needed?
    
    Views and functions are first-class metadata objects in Gravitino, but
    they were excluded from tag association support. Users could not
    organize, classify, or discover views and functions through tags like
    other metadata objects.
    
    Fix: #11844
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    
    Users can now associate, list, get, and remove tags for VIEW and
    FUNCTION metadata objects through the existing metadata object tag REST
    APIs.
    
    ### How was this patch tested?
    
    Added unit tests covering:
    - TagManager support for VIEW and FUNCTION.
    - REST metadata object tag operations for VIEW and FUNCTION.
    - Tag relation cleanup when views/functions are dropped.
    - Catalog/schema cascade cleanup for view/function tag relations.
    - PostgreSQL tag relation cascade SQL provider coverage.
    
    Ran:
    
    ```bash
    ./gradlew :core:test --tests org.apache.gravitino.storage.relational.mapper.provider.postgresql.TestTagMetadataObjectRelPostgreSQLProvider --tests org.apache.gravitino.storage.relational.service.TestSchemaMetaService --tests org.apache.gravitino.storage.relational.service.TestCatalogMetaService
    ```
    
    (cherry picked from commit b464820eb0ca1d51ec954a368c7e6e256a8fceb5)
---
 .../base/TagMetadataObjectRelBaseSQLProvider.java  |  28 +++
 .../TagMetadataObjectRelPostgreSQLProvider.java    |  28 +++
 .../relational/service/FunctionMetaService.java    |   6 +
 .../java/org/apache/gravitino/tag/TagManager.java  |   4 +-
 .../relational/service/TestCatalogMetaService.java | 157 ++++++++++++
 .../service/TestFunctionMetaService.java           |  42 ++++
 .../relational/service/TestSchemaMetaService.java  | 146 ++++++++++++
 .../relational/service/TestViewMetaService.java    |  41 ++++
 .../org/apache/gravitino/tag/TestTagManager.java   | 167 ++++++++++++-
 .../gravitino/utils/TestMetadataObjectUtil.java    |  11 +
 docs/open-api/openapi.yaml                         |   3 +-
 docs/open-api/tags.yaml                            |   4 +-
 .../web/rest/TestMetadataObjectTagOperations.java  | 262 ++++++++++++++++++++-
 13 files changed, 891 insertions(+), 8 deletions(-)

diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
index ed6aca6f11..1f3a727066 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/base/TagMetadataObjectRelBaseSQLProvider.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.storage.relational.mapper.provider.base;
 import java.util.List;
 import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
@@ -29,6 +30,7 @@ import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
 import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
 import org.apache.gravitino.storage.relational.po.TagMetadataObjectRelPO;
 import org.apache.ibatis.annotations.Param;
 
@@ -204,6 +206,16 @@ public class TagMetadataObjectRelBaseSQLProvider {
         + ModelMetaMapper.TABLE_NAME
         + " mt WHERE mt.catalog_id = #{catalogId} AND"
         + " mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+        + " UNION"
+        + " SELECT vt.catalog_id FROM "
+        + ViewMetaMapper.TABLE_NAME
+        + " vt WHERE vt.catalog_id = #{catalogId} AND"
+        + " vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+        + " UNION"
+        + " SELECT fnt.catalog_id FROM "
+        + FunctionMetaMapper.TABLE_NAME
+        + " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+        + " fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
         + ")";
   }
 
@@ -262,6 +274,22 @@ public class TagMetadataObjectRelBaseSQLProvider {
         + "#{schemaId}"
         + "</foreach>"
         + " AND mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+        + " UNION"
+        + " SELECT vt.schema_id FROM "
+        + ViewMetaMapper.TABLE_NAME
+        + " vt WHERE vt.schema_id IN "
+        + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+        + "#{schemaId}"
+        + "</foreach>"
+        + " AND vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+        + " UNION"
+        + " SELECT fnt.schema_id FROM "
+        + FunctionMetaMapper.TABLE_NAME
+        + " fnt WHERE fnt.schema_id IN "
+        + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+        + "#{schemaId}"
+        + "</foreach>"
+        + " AND fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
         + ")"
         + "</script>";
   }
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
index 1bb6a7559c..992e105ee6 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/mapper/provider/postgresql/TagMetadataObjectRelPostgreSQLProvider.java
@@ -23,6 +23,7 @@ import static org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRe
 import java.util.List;
 import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.FilesetMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.ModelMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;
@@ -31,6 +32,7 @@ import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.TagMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
 import org.apache.gravitino.storage.relational.mapper.TopicMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.ViewMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.provider.base.TagMetadataObjectRelBaseSQLProvider;
 import org.apache.ibatis.annotations.Param;
 
@@ -111,6 +113,16 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
         + ModelMetaMapper.TABLE_NAME
         + " mt WHERE mt.catalog_id = #{catalogId} AND"
         + " mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+        + " UNION"
+        + " SELECT vt.catalog_id FROM "
+        + ViewMetaMapper.TABLE_NAME
+        + " vt WHERE vt.catalog_id = #{catalogId} AND"
+        + " vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+        + " UNION"
+        + " SELECT fnt.catalog_id FROM "
+        + FunctionMetaMapper.TABLE_NAME
+        + " fnt WHERE fnt.catalog_id = #{catalogId} AND"
+        + " fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
         + ")";
   }
 
@@ -169,6 +181,22 @@ public class TagMetadataObjectRelPostgreSQLProvider extends TagMetadataObjectRel
         + "#{schemaId}"
         + "</foreach>"
         + " AND mt.model_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'MODEL'"
+        + " UNION"
+        + " SELECT vt.schema_id FROM "
+        + ViewMetaMapper.TABLE_NAME
+        + " vt WHERE vt.schema_id IN "
+        + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+        + "#{schemaId}"
+        + "</foreach>"
+        + " AND vt.view_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'VIEW'"
+        + " UNION"
+        + " SELECT fnt.schema_id FROM "
+        + FunctionMetaMapper.TABLE_NAME
+        + " fnt WHERE fnt.schema_id IN "
+        + "<foreach collection='schemaIds' item='schemaId' open='(' close=')' separator=','>"
+        + "#{schemaId}"
+        + "</foreach>"
+        + " AND fnt.function_id = tmt.metadata_object_id AND tmt.metadata_object_type = 'FUNCTION'"
         + ")"
         + "</script>";
   }
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java b/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
index 33532edad2..2c582dc8c0 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
@@ -45,6 +45,7 @@ import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.FunctionVersionMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.OwnerMetaMapper;
 import org.apache.gravitino.storage.relational.mapper.SecurableObjectMapper;
+import org.apache.gravitino.storage.relational.mapper.TagMetadataObjectRelMapper;
 import org.apache.gravitino.storage.relational.po.FunctionMaxVersionPO;
 import org.apache.gravitino.storage.relational.po.FunctionPO;
 import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
@@ -166,6 +167,11 @@ public class FunctionMetaService {
                 mapper ->
                     mapper.softDeleteObjectRelsByMetadataObject(
                         functionId, MetadataObject.Type.FUNCTION.name()));
+            SessionUtils.doWithoutCommit(
+                TagMetadataObjectRelMapper.class,
+                mapper ->
+                    mapper.softDeleteTagMetadataObjectRelsByMetadataObject(
+                        functionId, MetadataObject.Type.FUNCTION.name()));
           }
         });
 
diff --git a/core/src/main/java/org/apache/gravitino/tag/TagManager.java b/core/src/main/java/org/apache/gravitino/tag/TagManager.java
index eb26cf37e9..49b8e112b4 100644
--- a/core/src/main/java/org/apache/gravitino/tag/TagManager.java
+++ b/core/src/main/java/org/apache/gravitino/tag/TagManager.java
@@ -69,10 +69,12 @@ public class TagManager implements TagDispatcher {
           MetadataObject.Type.CATALOG,
           MetadataObject.Type.SCHEMA,
           MetadataObject.Type.TABLE,
+          MetadataObject.Type.VIEW,
           MetadataObject.Type.FILESET,
           MetadataObject.Type.TOPIC,
           MetadataObject.Type.COLUMN,
-          MetadataObject.Type.MODEL);
+          MetadataObject.Type.MODEL,
+          MetadataObject.Type.FUNCTION);
 
   public TagManager(IdGenerator idGenerator, EntityStore entityStore) {
     this.idGenerator = idGenerator;
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java
index 589dbec14e..de5520908a 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestCatalogMetaService.java
@@ -24,19 +24,37 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
 import java.time.Instant;
 import java.util.List;
 import org.apache.gravitino.Catalog;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
 import org.apache.gravitino.meta.AuditInfo;
 import org.apache.gravitino.meta.CatalogEntity;
+import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.FunctionEntity;
+import org.apache.gravitino.meta.ModelEntity;
+import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
+import org.apache.gravitino.meta.TopicEntity;
+import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.storage.RandomIdGenerator;
 import org.apache.gravitino.storage.relational.TestJDBCBackend;
 import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
 import org.apache.gravitino.storage.relational.utils.SessionUtils;
 import org.apache.gravitino.utils.NameIdentifierUtil;
 import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.TestTemplate;
@@ -176,4 +194,143 @@ public class TestCatalogMetaService extends TestJDBCBackend {
     backend.hardDeleteLegacyData(Entity.EntityType.CATALOG, Instant.now().toEpochMilli() + 3000);
     assertFalse(legacyRecordExistsInDB(catalog.id(), Entity.EntityType.CATALOG));
   }
+
+  @TestTemplate
+  public void testDeleteCatalogCascadeRemovesTagRelations() throws IOException {
+    CatalogEntity catalog =
+        createCatalog(
+            RandomIdGenerator.INSTANCE.nextId(),
+            NamespaceUtil.ofCatalog(metalakeName),
+            "catalog_with_tags",
+            auditInfo);
+    backend.insert(catalog, false);
+
+    SchemaEntity schema =
+        createSchemaEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            NamespaceUtil.ofSchema(metalakeName, catalog.name()),
+            "schema_with_tags",
+            AUDIT_INFO);
+    backend.insert(schema, false);
+
+    Namespace objectNamespace = Namespace.of(metalakeName, catalog.name(), schema.name());
+    ColumnEntity column =
+        ColumnEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("column_with_tag")
+            .withPosition(0)
+            .withAutoIncrement(false)
+            .withNullable(false)
+            .withDataType(Types.IntegerType.get())
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TableEntity table =
+        TableEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("table_with_tag")
+            .withNamespace(objectNamespace)
+            .withColumns(List.of(column))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TableMetaService.getInstance().insertTable(table, false);
+    TopicEntity topic =
+        createTopicEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "topic_with_tag", AUDIT_INFO);
+    TopicMetaService.getInstance().insertTopic(topic, false);
+    FilesetEntity fileset =
+        createFilesetEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "fileset_with_tag", AUDIT_INFO);
+    FilesetMetaService.getInstance().insertFileset(fileset, false);
+    ModelEntity model =
+        createModelEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            objectNamespace,
+            "model_with_tag",
+            "comment",
+            1,
+            null,
+            AUDIT_INFO);
+    ModelMetaService.getInstance().insertModel(model, false);
+    ViewEntity view =
+        createViewEntity(RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "view_with_tag");
+    FunctionEntity function =
+        createFunctionEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "function_with_tag", AUDIT_INFO);
+    ViewMetaService.getInstance().insertView(view, false);
+    FunctionMetaService.getInstance().insertFunction(function, false);
+
+    TagEntity tag =
+        TagEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("tag1")
+            .withNamespace(NamespaceUtil.ofTag(metalakeName))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TagMetaService.getInstance().insertTag(tag, false);
+    associateTag(tag, catalog.nameIdentifier(), catalog.type());
+    associateTag(tag, schema.nameIdentifier(), schema.type());
+    associateTag(tag, table.nameIdentifier(), table.type());
+    associateTag(
+        tag,
+        NameIdentifier.of(Namespace.fromString(table.nameIdentifier().toString()), column.name()),
+        column.type());
+    associateTag(tag, topic.nameIdentifier(), topic.type());
+    associateTag(tag, fileset.nameIdentifier(), fileset.type());
+    associateTag(tag, model.nameIdentifier(), model.type());
+    associateTag(tag, view.nameIdentifier(), view.type());
+    associateTag(tag, function.nameIdentifier(), function.type());
+
+    assertEquals(1, countActiveTagRelForMetadataObject(catalog.id(), "CATALOG"));
+    assertEquals(1, countActiveTagRelForMetadataObject(schema.id(), "SCHEMA"));
+    assertEquals(1, countActiveTagRelForMetadataObject(table.id(), "TABLE"));
+    assertEquals(1, countActiveTagRelForMetadataObject(column.id(), "COLUMN"));
+    assertEquals(1, countActiveTagRelForMetadataObject(topic.id(), "TOPIC"));
+    assertEquals(1, countActiveTagRelForMetadataObject(fileset.id(), "FILESET"));
+    assertEquals(1, countActiveTagRelForMetadataObject(model.id(), "MODEL"));
+    assertEquals(1, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
+    assertEquals(1, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
+
+    assertTrue(CatalogMetaService.getInstance().deleteCatalog(catalog.nameIdentifier(), true));
+
+    assertEquals(0, countActiveTagRelForMetadataObject(catalog.id(), "CATALOG"));
+    assertEquals(0, countActiveTagRelForMetadataObject(schema.id(), "SCHEMA"));
+    assertEquals(0, countActiveTagRelForMetadataObject(table.id(), "TABLE"));
+    assertEquals(0, countActiveTagRelForMetadataObject(column.id(), "COLUMN"));
+    assertEquals(0, countActiveTagRelForMetadataObject(topic.id(), "TOPIC"));
+    assertEquals(0, countActiveTagRelForMetadataObject(fileset.id(), "FILESET"));
+    assertEquals(0, countActiveTagRelForMetadataObject(model.id(), "MODEL"));
+    assertEquals(0, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
+    assertEquals(0, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
+  }
+
+  private void associateTag(TagEntity tag, NameIdentifier ident, Entity.EntityType type)
+      throws IOException {
+    TagMetaService.getInstance()
+        .associateTagsWithMetadataObject(
+            ident,
+            type,
+            new NameIdentifier[] {NameIdentifierUtil.ofTag(metalakeName, tag.name())},
+            new NameIdentifier[0]);
+  }
+
+  private int countActiveTagRelForMetadataObject(Long metadataObjectId, String metadataObjectType) {
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet rs =
+            statement.executeQuery(
+                String.format(
+                    "SELECT count(*) FROM tag_relation_meta"
+                        + " WHERE metadata_object_id = %d AND metadata_object_type = '%s'"
+                        + " AND deleted_at = 0",
+                    metadataObjectId, metadataObjectType))) {
+      if (rs.next()) {
+        return rs.getInt(1);
+      }
+      throw new RuntimeException("No result for countActiveTagRelForMetadataObject");
+    } catch (SQLException e) {
+      throw new RuntimeException("SQL execution failed", e);
+    }
+  }
 }
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionMetaService.java
index 5d2471c9f3..fe5d46db8b 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionMetaService.java
@@ -47,6 +47,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
 import org.apache.gravitino.integration.test.util.GravitinoITUtils;
 import org.apache.gravitino.meta.FunctionEntity;
 import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.TagEntity;
 import org.apache.gravitino.meta.UserEntity;
 import org.apache.gravitino.storage.RandomIdGenerator;
 import org.apache.gravitino.storage.relational.TestJDBCBackend;
@@ -280,6 +281,23 @@ public class TestFunctionMetaService extends TestJDBCBackend {
             ImmutableMap.of());
     RoleMetaService.getInstance().insertRole(role, false);
 
+    // Set up tag relation
+    TagEntity tag =
+        TagEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("tag1")
+            .withNamespace(NamespaceUtil.ofTag(metalakeName))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TagMetaService.getInstance().insertTag(tag, false);
+    TagMetaService.getInstance()
+        .associateTagsWithMetadataObject(
+            function.nameIdentifier(),
+            function.type(),
+            new NameIdentifier[] {NameIdentifierUtil.ofTag(metalakeName, tag.name())},
+            new NameIdentifier[0]);
+    assertEquals(1, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
+
     NameIdentifier functionIdent =
         NameIdentifier.of(metalakeName, catalogName, schemaName, functionName);
     assertTrue(FunctionMetaService.getInstance().deleteFunction(functionIdent));
@@ -294,6 +312,9 @@ public class TestFunctionMetaService extends TestJDBCBackend {
 
     // Verify securable object (role) relation is cleaned up
     assertEquals(0, countActiveObjectRelForRole(role.id()));
+
+    // Verify tag relation is cleaned up
+    assertEquals(0, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
   }
 
   @TestTemplate
@@ -568,6 +589,27 @@ public class TestFunctionMetaService extends TestJDBCBackend {
     }
   }
 
+  private int countActiveTagRelForMetadataObject(Long metadataObjectId, String metadataObjectType) {
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet rs =
+            statement.executeQuery(
+                String.format(
+                    "SELECT count(*) FROM tag_relation_meta"
+                        + " WHERE metadata_object_id = %d AND metadata_object_type = '%s'"
+                        + " AND deleted_at = 0",
+                    metadataObjectId, metadataObjectType))) {
+      if (rs.next()) {
+        return rs.getInt(1);
+      }
+      throw new RuntimeException("No result for countActiveTagRelForMetadataObject");
+    } catch (SQLException e) {
+      throw new RuntimeException("SQL execution failed", e);
+    }
+  }
+
   private Map<Integer, Long> listFunctionVersions(Long functionId) {
     Map<Integer, Long> versionDeletedTime = new HashMap<>();
     try (SqlSession sqlSession =
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
index d11efa6950..a1e43144ec 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestSchemaMetaService.java
@@ -23,6 +23,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
 import java.time.Instant;
 import java.util.Collections;
 import java.util.List;
@@ -31,13 +35,24 @@ import java.util.stream.Collectors;
 import org.apache.gravitino.Entity;
 import org.apache.gravitino.EntityAlreadyExistsException;
 import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
 import org.apache.gravitino.exceptions.NonEmptyEntityException;
+import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.FunctionEntity;
+import org.apache.gravitino.meta.ModelEntity;
 import org.apache.gravitino.meta.SchemaEntity;
+import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.TagEntity;
 import org.apache.gravitino.meta.TopicEntity;
+import org.apache.gravitino.meta.ViewEntity;
+import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.storage.RandomIdGenerator;
 import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
 import org.apache.gravitino.utils.NameIdentifierUtil;
 import org.apache.gravitino.utils.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.TestTemplate;
 
@@ -323,6 +338,106 @@ public class TestSchemaMetaService extends TestJDBCBackend {
             NameIdentifier.of(metalakeName, catalogName, "anc_a"), Entity.EntityType.SCHEMA));
   }
 
+  @TestTemplate
+  public void testDeleteSchemaCascadeRemovesTagRelations() throws IOException {
+    createAndInsertMakeLake(metalakeName);
+    createAndInsertCatalog(metalakeName, catalogName);
+
+    SchemaEntity schema =
+        createSchemaEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            NamespaceUtil.ofSchema(metalakeName, catalogName),
+            "schema_with_tags",
+            AUDIT_INFO);
+    SchemaMetaService.getInstance().insertSchema(schema, false);
+
+    Namespace objectNamespace = Namespace.of(metalakeName, catalogName, schema.name());
+    ColumnEntity column =
+        ColumnEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("column_with_tag")
+            .withPosition(0)
+            .withAutoIncrement(false)
+            .withNullable(false)
+            .withDataType(Types.IntegerType.get())
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TableEntity table =
+        TableEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("table_with_tag")
+            .withNamespace(objectNamespace)
+            .withColumns(List.of(column))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TableMetaService.getInstance().insertTable(table, false);
+    TopicEntity topic =
+        createTopicEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "topic_with_tag", AUDIT_INFO);
+    TopicMetaService.getInstance().insertTopic(topic, false);
+    FilesetEntity fileset =
+        createFilesetEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "fileset_with_tag", AUDIT_INFO);
+    FilesetMetaService.getInstance().insertFileset(fileset, false);
+    ModelEntity model =
+        createModelEntity(
+            RandomIdGenerator.INSTANCE.nextId(),
+            objectNamespace,
+            "model_with_tag",
+            "comment",
+            1,
+            null,
+            AUDIT_INFO);
+    ModelMetaService.getInstance().insertModel(model, false);
+    ViewEntity view =
+        createViewEntity(RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "view_with_tag");
+    FunctionEntity function =
+        createFunctionEntity(
+            RandomIdGenerator.INSTANCE.nextId(), objectNamespace, "function_with_tag", AUDIT_INFO);
+    ViewMetaService.getInstance().insertView(view, false);
+    FunctionMetaService.getInstance().insertFunction(function, false);
+
+    TagEntity tag =
+        TagEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("tag1")
+            .withNamespace(NamespaceUtil.ofTag(metalakeName))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TagMetaService.getInstance().insertTag(tag, false);
+    associateTag(tag, schema.nameIdentifier(), schema.type());
+    associateTag(tag, table.nameIdentifier(), table.type());
+    associateTag(
+        tag,
+        NameIdentifier.of(Namespace.fromString(table.nameIdentifier().toString()), column.name()),
+        column.type());
+    associateTag(tag, topic.nameIdentifier(), topic.type());
+    associateTag(tag, fileset.nameIdentifier(), fileset.type());
+    associateTag(tag, model.nameIdentifier(), model.type());
+    associateTag(tag, view.nameIdentifier(), view.type());
+    associateTag(tag, function.nameIdentifier(), function.type());
+
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(schema.id(), "SCHEMA"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(table.id(), "TABLE"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(column.id(), "COLUMN"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(topic.id(), "TOPIC"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(fileset.id(), "FILESET"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(model.id(), "MODEL"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
+    Assertions.assertEquals(1, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
+
+    assertTrue(SchemaMetaService.getInstance().deleteSchema(schema.nameIdentifier(), true));
+
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(schema.id(), "SCHEMA"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(table.id(), "TABLE"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(column.id(), "COLUMN"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(topic.id(), "TOPIC"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(fileset.id(), "FILESET"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(model.id(), "MODEL"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
+    Assertions.assertEquals(0, countActiveTagRelForMetadataObject(function.id(), "FUNCTION"));
+  }
+
   @TestTemplate
   public void testDeleteHierarchicalSchemaCascadeEscapesLikeMetacharacters() throws IOException {
     createAndInsertMakeLake(metalakeName);
@@ -423,4 +538,35 @@ public class TestSchemaMetaService extends TestJDBCBackend {
             .getSchemaByIdentifier(NameIdentifier.of(metalakeName, catalogName, ancestorAB))
             .id());
   }
+
+  private void associateTag(TagEntity tag, NameIdentifier ident, Entity.EntityType type)
+      throws IOException {
+    TagMetaService.getInstance()
+        .associateTagsWithMetadataObject(
+            ident,
+            type,
+            new NameIdentifier[] {NameIdentifierUtil.ofTag(metalakeName, tag.name())},
+            new NameIdentifier[0]);
+  }
+
+  private int countActiveTagRelForMetadataObject(Long metadataObjectId, String metadataObjectType) {
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet rs =
+            statement.executeQuery(
+                String.format(
+                    "SELECT count(*) FROM tag_relation_meta"
+                        + " WHERE metadata_object_id = %d AND metadata_object_type = '%s'"
+                        + " AND deleted_at = 0",
+                    metadataObjectId, metadataObjectType))) {
+      if (rs.next()) {
+        return rs.getInt(1);
+      }
+      throw new RuntimeException("No result for countActiveTagRelForMetadataObject");
+    } catch (SQLException e) {
+      throw new RuntimeException("SQL execution failed", e);
+    }
+  }
 }
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java
index 2c6488e329..edeaff2565 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestViewMetaService.java
@@ -39,6 +39,7 @@ import org.apache.gravitino.Namespace;
 import org.apache.gravitino.exceptions.NoSuchEntityException;
 import org.apache.gravitino.integration.test.util.GravitinoITUtils;
 import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.TagEntity;
 import org.apache.gravitino.meta.ViewEntity;
 import org.apache.gravitino.rel.Column;
 import org.apache.gravitino.rel.Representation;
@@ -47,6 +48,7 @@ import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.storage.RandomIdGenerator;
 import org.apache.gravitino.storage.relational.TestJDBCBackend;
 import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.gravitino.utils.NameIdentifierUtil;
 import org.apache.gravitino.utils.NamespaceUtil;
 import org.apache.ibatis.session.SqlSession;
 import org.junit.jupiter.api.BeforeEach;
@@ -208,12 +210,30 @@ public class TestViewMetaService extends TestJDBCBackend {
 
     ViewMetaService.getInstance().insertView(view, false);
 
+    // Set up tag relation
+    TagEntity tag =
+        TagEntity.builder()
+            .withId(RandomIdGenerator.INSTANCE.nextId())
+            .withName("tag1")
+            .withNamespace(NamespaceUtil.ofTag(metalakeName))
+            .withAuditInfo(AUDIT_INFO)
+            .build();
+    TagMetaService.getInstance().insertTag(tag, false);
+    TagMetaService.getInstance()
+        .associateTagsWithMetadataObject(
+            view.nameIdentifier(),
+            view.type(),
+            new NameIdentifier[] {NameIdentifierUtil.ofTag(metalakeName, tag.name())},
+            new NameIdentifier[0]);
+    assertEquals(1, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
+
     NameIdentifier viewIdent = NameIdentifier.of(metalakeName, catalogName, schemaName, viewName);
     assertTrue(ViewMetaService.getInstance().deleteView(viewIdent));
 
     assertThrows(
         NoSuchEntityException.class,
         () -> ViewMetaService.getInstance().getViewByIdentifier(viewIdent));
+    assertEquals(0, countActiveTagRelForMetadataObject(view.id(), "VIEW"));
   }
 
   @TestTemplate
@@ -333,4 +353,25 @@ public class TestViewMetaService extends TestJDBCBackend {
     }
     return versionDeletedTime;
   }
+
+  private int countActiveTagRelForMetadataObject(Long metadataObjectId, String metadataObjectType) {
+    try (SqlSession sqlSession =
+            SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+        Connection connection = sqlSession.getConnection();
+        Statement statement = connection.createStatement();
+        ResultSet rs =
+            statement.executeQuery(
+                String.format(
+                    "SELECT count(*) FROM tag_relation_meta"
+                        + " WHERE metadata_object_id = %d AND metadata_object_type = '%s'"
+                        + " AND deleted_at = 0",
+                    metadataObjectId, metadataObjectType))) {
+      if (rs.next()) {
+        return rs.getInt(1);
+      }
+      throw new RuntimeException("No result for countActiveTagRelForMetadataObject");
+    } catch (SQLException e) {
+      throw new RuntimeException("SQL execution failed", e);
+    }
+  }
 }
diff --git a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
index ae377b8ad0..593e42f5ad 100644
--- a/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
+++ b/core/src/test/java/org/apache/gravitino/tag/TestTagManager.java
@@ -62,22 +62,36 @@ import org.apache.gravitino.GravitinoEnv;
 import org.apache.gravitino.MetadataObject;
 import org.apache.gravitino.Namespace;
 import org.apache.gravitino.catalog.CatalogDispatcher;
+import org.apache.gravitino.catalog.FunctionDispatcher;
 import org.apache.gravitino.catalog.SchemaDispatcher;
 import org.apache.gravitino.catalog.TableDispatcher;
+import org.apache.gravitino.catalog.ViewDispatcher;
 import org.apache.gravitino.exceptions.NoSuchMetalakeException;
 import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.exceptions.NotFoundException;
 import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
 import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.function.FunctionDefinition;
+import org.apache.gravitino.function.FunctionDefinitions;
+import org.apache.gravitino.function.FunctionImpl;
+import org.apache.gravitino.function.FunctionImpls;
+import org.apache.gravitino.function.FunctionParam;
+import org.apache.gravitino.function.FunctionParams;
+import org.apache.gravitino.function.FunctionType;
 import org.apache.gravitino.lock.LockManager;
 import org.apache.gravitino.meta.AuditInfo;
 import org.apache.gravitino.meta.BaseMetalake;
 import org.apache.gravitino.meta.CatalogEntity;
 import org.apache.gravitino.meta.ColumnEntity;
+import org.apache.gravitino.meta.FunctionEntity;
 import org.apache.gravitino.meta.SchemaEntity;
 import org.apache.gravitino.meta.SchemaVersion;
 import org.apache.gravitino.meta.TableEntity;
+import org.apache.gravitino.meta.ViewEntity;
 import org.apache.gravitino.metalake.MetalakeDispatcher;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Representation;
+import org.apache.gravitino.rel.SQLRepresentation;
 import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.storage.IdGenerator;
 import org.apache.gravitino.storage.RandomIdGenerator;
@@ -107,10 +121,16 @@ public class TestTagManager {
 
   private static final String COLUMN = "column_for_tag_test";
 
+  private static final String VIEW = "view_for_tag_test";
+
+  private static final String FUNCTION = "function_for_tag_test";
+
   private static final MetalakeDispatcher metalakeDispatcher = mock(MetalakeDispatcher.class);
   private static final CatalogDispatcher catalogDispatcher = mock(CatalogDispatcher.class);
   private static final SchemaDispatcher schemaDispatcher = mock(SchemaDispatcher.class);
   private static final TableDispatcher tableDispatcher = mock(TableDispatcher.class);
+  private static final ViewDispatcher viewDispatcher = mock(ViewDispatcher.class);
+  private static final FunctionDispatcher functionDispatcher = mock(FunctionDispatcher.class);
 
   private static EntityStore entityStore;
 
@@ -211,6 +231,37 @@ public class TestTagManager {
             .build();
     entityStore.put(table, false /* overwritten */);
 
+    ViewEntity view =
+        ViewEntity.builder()
+            .withId(idGenerator.nextId())
+            .withName(VIEW)
+            .withNamespace(Namespace.of(METALAKE, CATALOG, SCHEMA))
+            .withColumns(new Column[0])
+            .withRepresentations(
+                new Representation[] {
+                  SQLRepresentation.builder().withDialect("unknown").withSql("SELECT 1").build()
+                })
+            .withAuditInfo(audit)
+            .build();
+    entityStore.put(view, false /* overwritten */);
+
+    FunctionParam param = FunctionParams.of("param", Types.IntegerType.get());
+    FunctionImpl impl = FunctionImpls.ofJava(FunctionImpl.RuntimeType.SPARK, "mock.udf.class.name");
+    FunctionDefinition definition =
+        FunctionDefinitions.of(
+            new FunctionParam[] {param}, Types.IntegerType.get(), new FunctionImpl[] {impl});
+    FunctionEntity function =
+        FunctionEntity.builder()
+            .withId(idGenerator.nextId())
+            .withName(FUNCTION)
+            .withNamespace(Namespace.of(METALAKE, CATALOG, SCHEMA))
+            .withFunctionType(FunctionType.SCALAR)
+            .withDeterministic(false)
+            .withDefinitions(new FunctionDefinition[] {definition})
+            .withAuditInfo(audit)
+            .build();
+    entityStore.put(function, false /* overwritten */);
+
     tagManager = new TagManager(idGenerator, entityStore);
 
     FieldUtils.writeField(
@@ -218,11 +269,16 @@ public class TestTagManager {
     FieldUtils.writeField(GravitinoEnv.getInstance(), "catalogDispatcher", catalogDispatcher, true);
     FieldUtils.writeField(GravitinoEnv.getInstance(), "schemaDispatcher", schemaDispatcher, true);
     FieldUtils.writeField(GravitinoEnv.getInstance(), "tableDispatcher", tableDispatcher, true);
+    FieldUtils.writeField(GravitinoEnv.getInstance(), "viewDispatcher", viewDispatcher, true);
+    FieldUtils.writeField(
+        GravitinoEnv.getInstance(), "functionDispatcher", functionDispatcher, true);
 
     when(metalakeDispatcher.metalakeExists(any())).thenReturn(true);
     when(catalogDispatcher.catalogExists(any())).thenReturn(true);
     when(schemaDispatcher.schemaExists(any())).thenReturn(true);
     when(tableDispatcher.tableExists(any())).thenReturn(true);
+    when(viewDispatcher.viewExists(any())).thenReturn(true);
+    when(functionDispatcher.functionExists(any())).thenReturn(true);
   }
 
   @AfterAll
@@ -262,6 +318,19 @@ public class TestTagManager {
     String[] columnTags = tagManager.listTagsForMetadataObject(METALAKE, columnObject);
     tagManager.associateTagsForMetadataObject(METALAKE, columnObject, null, columnTags);
 
+    MetadataObject viewObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
+    String[] viewTags = tagManager.listTagsForMetadataObject(METALAKE, viewObject);
+    tagManager.associateTagsForMetadataObject(METALAKE, viewObject, null, viewTags);
+
+    MetadataObject functionObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
+            Entity.EntityType.FUNCTION);
+    String[] functionTags = tagManager.listTagsForMetadataObject(METALAKE, functionObject);
+    tagManager.associateTagsForMetadataObject(METALAKE, functionObject, null, functionTags);
+
     Arrays.stream(tagManager.listTags(METALAKE)).forEach(n -> tagManager.deleteTag(METALAKE, n));
   }
 
@@ -501,6 +570,44 @@ public class TestTagManager {
     Assertions.assertEquals(2, tags6.length);
     Assertions.assertEquals(ImmutableSet.of("tag1", "tag3"), ImmutableSet.copyOf(tags6));
 
+    // Test associate tags for view
+    MetadataObject viewObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
+    String[] tagsForView =
+        tagManager.associateTagsForMetadataObject(METALAKE, viewObject, tagsToAdd1, null);
+
+    Assertions.assertEquals(1, tagsForView.length);
+    Assertions.assertEquals(ImmutableSet.of("tag1"), ImmutableSet.copyOf(tagsForView));
+
+    // Test associate and disassociate same tags for view
+    String[] tagsForViewAfterUpdate =
+        tagManager.associateTagsForMetadataObject(METALAKE, viewObject, tagsToAdd2, tagsToRemove1);
+
+    Assertions.assertEquals(2, tagsForViewAfterUpdate.length);
+    Assertions.assertEquals(
+        ImmutableSet.of("tag1", "tag3"), ImmutableSet.copyOf(tagsForViewAfterUpdate));
+
+    // Test associate tags for function
+    MetadataObject functionObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
+            Entity.EntityType.FUNCTION);
+    String[] tagsForFunction =
+        tagManager.associateTagsForMetadataObject(METALAKE, functionObject, tagsToAdd1, null);
+
+    Assertions.assertEquals(1, tagsForFunction.length);
+    Assertions.assertEquals(ImmutableSet.of("tag1"), ImmutableSet.copyOf(tagsForFunction));
+
+    // Test associate and disassociate same tags for function
+    String[] tagsForFunctionAfterUpdate =
+        tagManager.associateTagsForMetadataObject(
+            METALAKE, functionObject, tagsToAdd2, tagsToRemove1);
+
+    Assertions.assertEquals(2, tagsForFunctionAfterUpdate.length);
+    Assertions.assertEquals(
+        ImmutableSet.of("tag1", "tag3"), ImmutableSet.copyOf(tagsForFunctionAfterUpdate));
+
     // Test associate and disassociate same tags for column
     MetadataObject columnObject =
         NameIdentifierUtil.toMetadataObject(
@@ -552,6 +659,13 @@ public class TestTagManager {
         NameIdentifierUtil.toMetadataObject(
             NameIdentifierUtil.ofColumn(METALAKE, CATALOG, SCHEMA, TABLE, COLUMN),
             Entity.EntityType.COLUMN);
+    MetadataObject viewObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
+    MetadataObject functionObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
+            Entity.EntityType.FUNCTION);
 
     tagManager.associateTagsForMetadataObject(
         METALAKE, catalogObject, new String[] {tag1.name(), tag2.name(), tag3.name()}, null);
@@ -561,11 +675,16 @@ public class TestTagManager {
         METALAKE, tableObject, new String[] {tag1.name()}, null);
     tagManager.associateTagsForMetadataObject(
         METALAKE, columnObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, viewObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, functionObject, new String[] {tag1.name()}, null);
 
     MetadataObject[] objects = tagManager.listMetadataObjectsForTag(METALAKE, tag1.name());
-    Assertions.assertEquals(4, objects.length);
+    Assertions.assertEquals(6, objects.length);
     Assertions.assertEquals(
-        ImmutableSet.of(catalogObject, schemaObject, tableObject, columnObject),
+        ImmutableSet.of(
+            catalogObject, schemaObject, tableObject, columnObject, viewObject, functionObject),
         ImmutableSet.copyOf(objects));
 
     MetadataObject[] objects1 = tagManager.listMetadataObjectsForTag(METALAKE, tag2.name());
@@ -607,6 +726,13 @@ public class TestTagManager {
         NameIdentifierUtil.toMetadataObject(
             NameIdentifierUtil.ofColumn(METALAKE, CATALOG, SCHEMA, TABLE, COLUMN),
             Entity.EntityType.COLUMN);
+    MetadataObject viewObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
+    MetadataObject functionObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
+            Entity.EntityType.FUNCTION);
 
     tagManager.associateTagsForMetadataObject(
         METALAKE, catalogObject, new String[] {tag1.name(), tag2.name(), tag3.name()}, null);
@@ -616,6 +742,10 @@ public class TestTagManager {
         METALAKE, tableObject, new String[] {tag1.name()}, null);
     tagManager.associateTagsForMetadataObject(
         METALAKE, columnObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, viewObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, functionObject, new String[] {tag1.name()}, null);
 
     String[] tags = tagManager.listTagsForMetadataObject(METALAKE, catalogObject);
     Assertions.assertEquals(3, tags.length);
@@ -649,6 +779,22 @@ public class TestTagManager {
     Assertions.assertEquals(1, tagsInfo3.length);
     Assertions.assertEquals(ImmutableSet.of(tag1), ImmutableSet.copyOf(tagsInfo3));
 
+    String[] tags4 = tagManager.listTagsForMetadataObject(METALAKE, viewObject);
+    Assertions.assertEquals(1, tags4.length);
+    Assertions.assertEquals(ImmutableSet.of("tag1"), ImmutableSet.copyOf(tags4));
+
+    Tag[] tagsInfo4 = tagManager.listTagsInfoForMetadataObject(METALAKE, viewObject);
+    Assertions.assertEquals(1, tagsInfo4.length);
+    Assertions.assertEquals(ImmutableSet.of(tag1), ImmutableSet.copyOf(tagsInfo4));
+
+    String[] tags5 = tagManager.listTagsForMetadataObject(METALAKE, functionObject);
+    Assertions.assertEquals(1, tags5.length);
+    Assertions.assertEquals(ImmutableSet.of("tag1"), ImmutableSet.copyOf(tags5));
+
+    Tag[] tagsInfo5 = tagManager.listTagsInfoForMetadataObject(METALAKE, functionObject);
+    Assertions.assertEquals(1, tagsInfo5.length);
+    Assertions.assertEquals(ImmutableSet.of(tag1), ImmutableSet.copyOf(tagsInfo5));
+
     // List tags for non-existent metadata object
     MetadataObject nonExistentObject =
         NameIdentifierUtil.toMetadataObject(
@@ -681,6 +827,13 @@ public class TestTagManager {
         NameIdentifierUtil.toMetadataObject(
             NameIdentifierUtil.ofColumn(METALAKE, CATALOG, SCHEMA, TABLE, COLUMN),
             Entity.EntityType.COLUMN);
+    MetadataObject viewObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofView(METALAKE, CATALOG, SCHEMA, VIEW), Entity.EntityType.VIEW);
+    MetadataObject functionObject =
+        NameIdentifierUtil.toMetadataObject(
+            NameIdentifierUtil.ofFunction(METALAKE, CATALOG, SCHEMA, FUNCTION),
+            Entity.EntityType.FUNCTION);
 
     tagManager.associateTagsForMetadataObject(
         METALAKE, catalogObject, new String[] {tag1.name(), tag2.name(), tag3.name()}, null);
@@ -690,6 +843,10 @@ public class TestTagManager {
         METALAKE, tableObject, new String[] {tag1.name()}, null);
     tagManager.associateTagsForMetadataObject(
         METALAKE, columnObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, viewObject, new String[] {tag1.name()}, null);
+    tagManager.associateTagsForMetadataObject(
+        METALAKE, functionObject, new String[] {tag1.name()}, null);
 
     Tag result = tagManager.getTagForMetadataObject(METALAKE, catalogObject, tag1.name());
     Assertions.assertEquals(tag1, result);
@@ -706,6 +863,12 @@ public class TestTagManager {
     Tag result4 = tagManager.getTagForMetadataObject(METALAKE, tableObject, tag1.name());
     Assertions.assertEquals(tag1, result4);
 
+    Tag result5 = tagManager.getTagForMetadataObject(METALAKE, viewObject, tag1.name());
+    Assertions.assertEquals(tag1, result5);
+
+    Tag result6 = tagManager.getTagForMetadataObject(METALAKE, functionObject, tag1.name());
+    Assertions.assertEquals(tag1, result6);
+
     // Test get non-existent tag for metadata object
     Throwable e =
         Assertions.assertThrows(
diff --git a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
index 94e93bba66..97a7fef4a4 100644
--- a/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
+++ b/core/src/test/java/org/apache/gravitino/utils/TestMetadataObjectUtil.java
@@ -80,6 +80,11 @@ public class TestMetadataObjectUtil {
         Entity.EntityType.VIEW,
         MetadataObjectUtil.toEntityType(
             MetadataObjects.of("catalog.schema", "view", MetadataObject.Type.VIEW)));
+
+    Assertions.assertEquals(
+        Entity.EntityType.FUNCTION,
+        MetadataObjectUtil.toEntityType(
+            MetadataObjects.of("catalog.schema", "function", MetadataObject.Type.FUNCTION)));
   }
 
   @Test
@@ -147,6 +152,12 @@ public class TestMetadataObjectUtil {
         NameIdentifier.of("metalake", "catalog", "schema", "view"),
         MetadataObjectUtil.toEntityIdent(
             "metalake", MetadataObjects.of("catalog.schema", "view", MetadataObject.Type.VIEW)));
+
+    Assertions.assertEquals(
+        NameIdentifier.of("metalake", "catalog", "schema", "function"),
+        MetadataObjectUtil.toEntityIdent(
+            "metalake",
+            MetadataObjects.of("catalog.schema", "function", MetadataObject.Type.FUNCTION)));
   }
 
   @Test
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index 6b17b53a8a..c5d80ac388 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -594,10 +594,12 @@ components:
           - "CATALOG"
           - "SCHEMA"
           - "TABLE"
+          - "VIEW"
           - "COLUMN"
           - "FILESET"
           - "TOPIC"
           - "MODEL"
+          - "FUNCTION"
           - "ROLE"
     metadataObjectFullName:
       name: metadataObjectFullName
@@ -634,4 +636,3 @@ components:
     KerberosAuth:
       type: http
       scheme: negotiate
-
diff --git a/docs/open-api/tags.yaml b/docs/open-api/tags.yaml
index a8b3ac053c..c2e39cd489 100644
--- a/docs/open-api/tags.yaml
+++ b/docs/open-api/tags.yaml
@@ -222,7 +222,7 @@ paths:
       tags:
         - tag
       summary: Associate tags with metadata object
-      description: Associate and disassociate tags with metadata object, please be aware that supported metadata objects are CATALOG, SCHEMA, TABLE, FILESET, TOPIC, COLUMN
+      description: Associate and disassociate tags with metadata object, please be aware that supported metadata objects are CATALOG, SCHEMA, TABLE, VIEW, FILESET, TOPIC, COLUMN, MODEL, FUNCTION
       operationId: associateTags
       requestBody:
         content:
@@ -392,9 +392,11 @@ components:
             - "CATALOG"
             - "SCHEMA"
             - "TABLE"
+            - "VIEW"
             - "FILESET"
             - "TOPIC"
             - "MODEL"
+            - "FUNCTION"
             - "COLUMN"
 
 
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectTagOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectTagOperations.java
index 158324bb4b..e9e7796521 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectTagOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectTagOperations.java
@@ -108,6 +108,9 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
         MetadataObjects.parse("object1.object2.object3", MetadataObject.Type.TABLE);
     MetadataObject column =
         MetadataObjects.parse("object1.object2.object3.object4", MetadataObject.Type.COLUMN);
+    MetadataObject view = MetadataObjects.parse("object1.object2.view1", MetadataObject.Type.VIEW);
+    MetadataObject function =
+        MetadataObjects.parse("object1.object2.function1", MetadataObject.Type.FUNCTION);
 
     Tag[] catalogTagInfos =
         new Tag[] {
@@ -133,6 +136,18 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
         };
     when(tagManager.listTagsInfoForMetadataObject(metalake, column)).thenReturn(columnTagInfos);
 
+    Tag[] viewTagInfos =
+        new Tag[] {
+          TagEntity.builder().withName("tag9").withId(1L).withAuditInfo(testAuditInfo1).build()
+        };
+    when(tagManager.listTagsInfoForMetadataObject(metalake, view)).thenReturn(viewTagInfos);
+
+    Tag[] functionTagInfos =
+        new Tag[] {
+          TagEntity.builder().withName("tag11").withId(1L).withAuditInfo(testAuditInfo1).build()
+        };
+    when(tagManager.listTagsInfoForMetadataObject(metalake, function)).thenReturn(functionTagInfos);
+
     // Test catalog tags
     Response response =
         target(basePath(metalake))
@@ -275,6 +290,113 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
     Assertions.assertTrue(resultNames1.contains("tag3"));
     Assertions.assertTrue(resultNames1.contains("tag5"));
 
+    // Test view tags
+    Response viewResponse =
+        target(basePath(metalake))
+            .path(view.type().toString())
+            .path(view.fullName())
+            .path("tags")
+            .queryParam("details", true)
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), viewResponse.getStatus());
+
+    TagListResponse viewTagListResponse = viewResponse.readEntity(TagListResponse.class);
+    Assertions.assertEquals(0, viewTagListResponse.getCode());
+    Assertions.assertEquals(
+        schemaTagInfos.length + catalogTagInfos.length + viewTagInfos.length,
+        viewTagListResponse.getTags().length);
+
+    Map<String, Tag> viewResultTags =
+        Arrays.stream(viewTagListResponse.getTags())
+            .collect(Collectors.toMap(Tag::name, Function.identity()));
+
+    Assertions.assertTrue(viewResultTags.containsKey("tag1"));
+    Assertions.assertTrue(viewResultTags.containsKey("tag3"));
+    Assertions.assertTrue(viewResultTags.containsKey("tag9"));
+
+    Assertions.assertTrue(viewResultTags.get("tag1").inherited().get());
+    Assertions.assertTrue(viewResultTags.get("tag3").inherited().get());
+    Assertions.assertFalse(viewResultTags.get("tag9").inherited().get());
+
+    Response viewNameResponse =
+        target(basePath(metalake))
+            .path(view.type().toString())
+            .path(view.fullName())
+            .path("tags")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), viewNameResponse.getStatus());
+
+    NameListResponse viewNameListResponse = viewNameResponse.readEntity(NameListResponse.class);
+    Assertions.assertEquals(0, viewNameListResponse.getCode());
+    Assertions.assertEquals(
+        schemaTagInfos.length + catalogTagInfos.length + viewTagInfos.length,
+        viewNameListResponse.getNames().length);
+
+    Set<String> viewResultNames = Sets.newHashSet(viewNameListResponse.getNames());
+    Assertions.assertTrue(viewResultNames.contains("tag1"));
+    Assertions.assertTrue(viewResultNames.contains("tag3"));
+    Assertions.assertTrue(viewResultNames.contains("tag9"));
+
+    // Test function tags
+    Response functionResponse =
+        target(basePath(metalake))
+            .path(function.type().toString())
+            .path(function.fullName())
+            .path("tags")
+            .queryParam("details", true)
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), functionResponse.getStatus());
+
+    TagListResponse functionTagListResponse = functionResponse.readEntity(TagListResponse.class);
+    Assertions.assertEquals(0, functionTagListResponse.getCode());
+    Assertions.assertEquals(
+        schemaTagInfos.length + catalogTagInfos.length + functionTagInfos.length,
+        functionTagListResponse.getTags().length);
+
+    Map<String, Tag> functionResultTags =
+        Arrays.stream(functionTagListResponse.getTags())
+            .collect(Collectors.toMap(Tag::name, Function.identity()));
+
+    Assertions.assertTrue(functionResultTags.containsKey("tag1"));
+    Assertions.assertTrue(functionResultTags.containsKey("tag3"));
+    Assertions.assertTrue(functionResultTags.containsKey("tag11"));
+
+    Assertions.assertTrue(functionResultTags.get("tag1").inherited().get());
+    Assertions.assertTrue(functionResultTags.get("tag3").inherited().get());
+    Assertions.assertFalse(functionResultTags.get("tag11").inherited().get());
+
+    Response functionNameResponse =
+        target(basePath(metalake))
+            .path(function.type().toString())
+            .path(function.fullName())
+            .path("tags")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), functionNameResponse.getStatus());
+
+    NameListResponse functionNameListResponse =
+        functionNameResponse.readEntity(NameListResponse.class);
+    Assertions.assertEquals(0, functionNameListResponse.getCode());
+    Assertions.assertEquals(
+        schemaTagInfos.length + catalogTagInfos.length + functionTagInfos.length,
+        functionNameListResponse.getNames().length);
+
+    Set<String> functionResultNames = Sets.newHashSet(functionNameListResponse.getNames());
+    Assertions.assertTrue(functionResultNames.contains("tag1"));
+    Assertions.assertTrue(functionResultNames.contains("tag3"));
+    Assertions.assertTrue(functionResultNames.contains("tag11"));
+
     // Test column tags
     Response response6 =
         target(basePath(metalake))
@@ -510,6 +632,17 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
         MetadataObjects.parse("object1.object2.object3.object4", MetadataObject.Type.COLUMN);
     when(tagManager.getTagForMetadataObject(metalake, column, "tag4")).thenReturn(tag4);
 
+    TagEntity tag5 =
+        TagEntity.builder().withName("tag5").withId(1L).withAuditInfo(testAuditInfo1).build();
+    MetadataObject view = MetadataObjects.parse("object1.object2.view1", MetadataObject.Type.VIEW);
+    when(tagManager.getTagForMetadataObject(metalake, view, "tag5")).thenReturn(tag5);
+
+    TagEntity tag6 =
+        TagEntity.builder().withName("tag6").withId(1L).withAuditInfo(testAuditInfo1).build();
+    MetadataObject function =
+        MetadataObjects.parse("object1.object2.function1", MetadataObject.Type.FUNCTION);
+    when(tagManager.getTagForMetadataObject(metalake, function, "tag6")).thenReturn(tag6);
+
     // Test catalog tag
     Response response =
         target(basePath(metalake))
@@ -657,6 +790,92 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
     Assertions.assertEquals(tag3.comment(), respTag6.comment());
     Assertions.assertTrue(respTag6.inherited().get());
 
+    // Test view tag
+    Response viewResponse =
+        target(basePath(metalake))
+            .path(view.type().toString())
+            .path(view.fullName())
+            .path("tags")
+            .path("tag5")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), viewResponse.getStatus());
+
+    TagResponse viewTagResponse = viewResponse.readEntity(TagResponse.class);
+    Assertions.assertEquals(0, viewTagResponse.getCode());
+
+    Tag viewRespTag = viewTagResponse.getTag();
+    Assertions.assertEquals(tag5.name(), viewRespTag.name());
+    Assertions.assertEquals(tag5.comment(), viewRespTag.comment());
+    Assertions.assertFalse(viewRespTag.inherited().get());
+
+    // Test get view inherited tag
+    Response viewInheritedResponse =
+        target(basePath(metalake))
+            .path(view.type().toString())
+            .path(view.fullName())
+            .path("tags")
+            .path("tag2")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), viewInheritedResponse.getStatus());
+
+    TagResponse viewInheritedTagResponse = viewInheritedResponse.readEntity(TagResponse.class);
+    Assertions.assertEquals(0, viewInheritedTagResponse.getCode());
+
+    Tag viewInheritedRespTag = viewInheritedTagResponse.getTag();
+    Assertions.assertEquals(tag2.name(), viewInheritedRespTag.name());
+    Assertions.assertEquals(tag2.comment(), viewInheritedRespTag.comment());
+    Assertions.assertTrue(viewInheritedRespTag.inherited().get());
+
+    // Test function tag
+    Response functionResponse =
+        target(basePath(metalake))
+            .path(function.type().toString())
+            .path(function.fullName())
+            .path("tags")
+            .path("tag6")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), functionResponse.getStatus());
+
+    TagResponse functionTagResponse = functionResponse.readEntity(TagResponse.class);
+    Assertions.assertEquals(0, functionTagResponse.getCode());
+
+    Tag functionRespTag = functionTagResponse.getTag();
+    Assertions.assertEquals(tag6.name(), functionRespTag.name());
+    Assertions.assertEquals(tag6.comment(), functionRespTag.comment());
+    Assertions.assertFalse(functionRespTag.inherited().get());
+
+    // Test get function inherited tag
+    Response functionInheritedResponse =
+        target(basePath(metalake))
+            .path(function.type().toString())
+            .path(function.fullName())
+            .path("tags")
+            .path("tag2")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .get();
+
+    Assertions.assertEquals(
+        Response.Status.OK.getStatusCode(), functionInheritedResponse.getStatus());
+
+    TagResponse functionInheritedTagResponse =
+        functionInheritedResponse.readEntity(TagResponse.class);
+    Assertions.assertEquals(0, functionInheritedTagResponse.getCode());
+
+    Tag functionInheritedRespTag = functionInheritedTagResponse.getTag();
+    Assertions.assertEquals(tag2.name(), functionInheritedRespTag.name());
+    Assertions.assertEquals(tag2.comment(), functionInheritedRespTag.comment());
+    Assertions.assertTrue(functionInheritedRespTag.inherited().get());
+
     // Test catalog tag throw NoSuchTagException
     Response response7 =
         target(basePath(metalake))
@@ -758,12 +977,49 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
     Assertions.assertEquals(
         TagAlreadyAssociatedException.class.getSimpleName(), errorResponse.getType());
 
+    // Test associate tags for view
+    MetadataObject view = MetadataObjects.parse("object1.object2.view1", MetadataObject.Type.VIEW);
+    when(tagManager.associateTagsForMetadataObject(metalake, view, tagsToAdd, tagsToRemove))
+        .thenReturn(tagsToAdd);
+
+    Response response3 =
+        target(basePath(metalake))
+            .path(view.type().toString())
+            .path(view.fullName())
+            .path("tags")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), response3.getStatus());
+    Assertions.assertArrayEquals(
+        tagsToAdd, response3.readEntity(NameListResponse.class).getNames());
+
+    // Test associate tags for function
+    MetadataObject function =
+        MetadataObjects.parse("object1.object2.function1", MetadataObject.Type.FUNCTION);
+    when(tagManager.associateTagsForMetadataObject(metalake, function, tagsToAdd, tagsToRemove))
+        .thenReturn(tagsToAdd);
+
+    Response response4 =
+        target(basePath(metalake))
+            .path(function.type().toString())
+            .path(function.fullName())
+            .path("tags")
+            .request(MediaType.APPLICATION_JSON_TYPE)
+            .accept("application/vnd.gravitino.v1+json")
+            .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
+
+    Assertions.assertEquals(Response.Status.OK.getStatusCode(), response4.getStatus());
+    Assertions.assertArrayEquals(
+        tagsToAdd, response4.readEntity(NameListResponse.class).getNames());
+
     // Test throw RuntimeException
     doThrow(new RuntimeException("mock error"))
         .when(tagManager)
         .associateTagsForMetadataObject(any(), any(), any(), any());
 
-    Response response3 =
+    Response response5 =
         target(basePath(metalake))
             .path(catalog.type().toString())
             .path(catalog.fullName())
@@ -773,9 +1029,9 @@ public class TestMetadataObjectTagOperations extends BaseOperationsTest {
             .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
 
     Assertions.assertEquals(
-        Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response3.getStatus());
+        Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response5.getStatus());
 
-    ErrorResponse errorResponse1 = response3.readEntity(ErrorResponse.class);
+    ErrorResponse errorResponse1 = response5.readEntity(ErrorResponse.class);
     Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse1.getCode());
     Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse1.getType());
   }


(gravitino) 07/07: [#12181] feat(client-python): Support tags for views and functions (#12182)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 50261f1383f596021c9b026c6b7e5fbc032c4379
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Mon Jul 27 14:36:40 2026 +0800

    [#12181] feat(client-python): Support tags for views and functions (#12182)
    
    ### What changes were proposed in this pull request?
    
    This PR adds Python client support for tag operations on views and
    functions.
    
    Changes include:
    
    - Add default `supports_tags()` methods to the `View` and `Function` API
    classes.
    - Extend `GenericView` and `GenericFunction` with tag operations backed
    by `MetadataObjectTagOperations`.
    - Return tag-capable wrappers from Python client view and function
    operations.
    - Add Python client unit and integration tests for view/function tag
    support.
    
    ### Why are the changes needed?
    
    #11844 enables server-side tag association for `VIEW` and `FUNCTION`
    metadata objects. The Python client should expose the same capability so
    users can manage tags for views and functions through the typed client
    API, consistent with other tag-capable metadata objects.
    
    Fix: #12181
    Related: #11844
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes.
    
    Python client users can now call `supports_tags()` on `View` and
    `Function` objects returned by the client, for example:
    
    ```python
    view.supports_tags().associate_tags(...)
    function.supports_tags().list_tags()
    ```
    
    ### How was this patch tested?
    
    - `./gradlew :clients:client-python:black :clients:client-python:pylint
    :clients:client-python:unitTests`
    - `./gradlew :clients:client-python:integrationTest`
    
    (cherry picked from commit a7d221cd0a33fbce27931bb7889bee7ba32385c2)
---
 .../gravitino/api/function/function.py             |  13 +++
 clients/client-python/gravitino/api/rel/view.py    |  13 +++
 .../client/function_catalog_operations.py          |  17 +++-
 .../gravitino/client/generic_function.py           |  56 ++++++++++-
 .../client-python/gravitino/client/generic_view.py |  46 ++++++++-
 .../client/metadata_object_tag_operations.py       |   5 +-
 .../gravitino/client/relational_catalog.py         |   6 +-
 .../tests/integration/test_supports_tags.py        | 107 +++++++++++++++++++++
 .../tests/unittests/api/function/__init__.py       |  16 +++
 .../tests/unittests/api/function/test_function.py  |  35 +++++++
 .../tests/unittests/api/rel/test_view.py           |   7 ++
 .../tests/unittests/test_generic_function.py       |  79 +++++++++++++++
 .../tests/unittests/test_generic_view.py           |  24 +++++
 13 files changed, 411 insertions(+), 13 deletions(-)

diff --git a/clients/client-python/gravitino/api/function/function.py b/clients/client-python/gravitino/api/function/function.py
index 4aec6550f4..8eff5dc546 100644
--- a/clients/client-python/gravitino/api/function/function.py
+++ b/clients/client-python/gravitino/api/function/function.py
@@ -21,6 +21,8 @@ from typing import List, Optional
 from gravitino.api.auditable import Auditable
 from gravitino.api.function.function_definition import FunctionDefinition
 from gravitino.api.function.function_type import FunctionType
+from gravitino.api.tag.supports_tags import SupportsTags
+from gravitino.exceptions.base import UnsupportedOperationException
 
 
 class Function(Auditable):
@@ -61,3 +63,14 @@ class Function(Auditable):
     def definitions(self) -> List[FunctionDefinition]:
         """Returns the definitions of the function."""
         pass
+
+    def supports_tags(self) -> SupportsTags:
+        """Return tag operations if the function supports tags.
+
+        Raises:
+            UnsupportedOperationException: If the function does not support tag operations.
+
+        Returns:
+            SupportsTags: The tag operations supported by the function.
+        """
+        raise UnsupportedOperationException("Function does not support tag operations.")
diff --git a/clients/client-python/gravitino/api/rel/view.py b/clients/client-python/gravitino/api/rel/view.py
index 7db72a6750..fd495f0342 100644
--- a/clients/client-python/gravitino/api/rel/view.py
+++ b/clients/client-python/gravitino/api/rel/view.py
@@ -22,6 +22,8 @@ from gravitino.api.auditable import Auditable
 from gravitino.api.rel.column import Column
 from gravitino.api.rel.representation import Representation
 from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.tag.supports_tags import SupportsTags
+from gravitino.exceptions.base import UnsupportedOperationException
 
 
 class View(Auditable):
@@ -66,3 +68,14 @@ class View(Auditable):
     def properties(self) -> dict[str, str]:
         """Returns the view properties."""
         return {}
+
+    def supports_tags(self) -> SupportsTags:
+        """Return tag operations if the view supports tags.
+
+        Raises:
+            UnsupportedOperationException: If the view does not support tag operations.
+
+        Returns:
+            SupportsTags: The tag operations supported by the view.
+        """
+        raise UnsupportedOperationException("View does not support tag operations.")
diff --git a/clients/client-python/gravitino/client/function_catalog_operations.py b/clients/client-python/gravitino/client/function_catalog_operations.py
index 46050c7812..1d2e533ff5 100644
--- a/clients/client-python/gravitino/client/function_catalog_operations.py
+++ b/clients/client-python/gravitino/client/function_catalog_operations.py
@@ -132,7 +132,10 @@ class FunctionCatalogOperations(FunctionCatalog):
         function_list_response = FunctionListResponse.from_json(resp.body)
         function_list_response.validate()
 
-        return [GenericFunction(func) for func in function_list_response.functions()]
+        return [
+            GenericFunction(func, self._rest_client, full_namespace)
+            for func in function_list_response.functions()
+        ]
 
     def get_function(self, ident: NameIdentifier) -> Function:
         """Get a function by NameIdentifier from the catalog.
@@ -158,7 +161,9 @@ class FunctionCatalogOperations(FunctionCatalog):
         function_response = FunctionResponse.from_json(resp.body)
         function_response.validate()
 
-        return GenericFunction(function_response.function())
+        return GenericFunction(
+            function_response.function(), self._rest_client, full_namespace
+        )
 
     def register_function(
         self,
@@ -211,7 +216,9 @@ class FunctionCatalogOperations(FunctionCatalog):
         function_response = FunctionResponse.from_json(resp.body)
         function_response.validate()
 
-        return GenericFunction(function_response.function())
+        return GenericFunction(
+            function_response.function(), self._rest_client, full_namespace
+        )
 
     def alter_function(
         self, ident: NameIdentifier, *changes: FunctionChange
@@ -250,7 +257,9 @@ class FunctionCatalogOperations(FunctionCatalog):
         function_response = FunctionResponse.from_json(resp.body)
         function_response.validate()
 
-        return GenericFunction(function_response.function())
+        return GenericFunction(
+            function_response.function(), self._rest_client, full_namespace
+        )
 
     def drop_function(self, ident: NameIdentifier) -> bool:
         """Drop a function from the catalog.
diff --git a/clients/client-python/gravitino/client/generic_function.py b/clients/client-python/gravitino/client/generic_function.py
index 634084b291..2ef6bdfd72 100644
--- a/clients/client-python/gravitino/client/generic_function.py
+++ b/clients/client-python/gravitino/client/generic_function.py
@@ -20,20 +20,47 @@ from typing import List, Optional
 from gravitino.api.function.function import Function
 from gravitino.api.function.function_definition import FunctionDefinition
 from gravitino.api.function.function_type import FunctionType
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.metadata_objects import MetadataObjects
+from gravitino.api.tag.supports_tags import SupportsTags
+from gravitino.api.tag.tag import Tag
+from gravitino.client.metadata_object_tag_operations import MetadataObjectTagOperations
 from gravitino.dto.audit_dto import AuditDTO
 from gravitino.dto.function.function_dto import FunctionDTO
+from gravitino.namespace import Namespace
+from gravitino.utils.http_client import HTTPClient
 
 
-class GenericFunction(Function):
+class GenericFunction(Function, SupportsTags):
     """A generic implementation of the Function interface."""
 
-    def __init__(self, function_dto: FunctionDTO):
+    def __init__(
+        self,
+        function_dto: FunctionDTO,
+        rest_client: HTTPClient,
+        function_namespace: Namespace,
+    ):
         """Create a GenericFunction from a FunctionDTO.
 
         Args:
             function_dto: The function DTO.
+            rest_client: The REST client for tag operations.
+            function_namespace: The full function namespace in metalake.catalog.schema format.
         """
         self._function_dto = function_dto
+        function_object: MetadataObject = MetadataObjects.of(
+            [
+                function_namespace.level(1),
+                function_namespace.level(2),
+                function_dto.name(),
+            ],
+            MetadataObject.Type.FUNCTION,
+        )
+        self._object_tag_operations = MetadataObjectTagOperations(
+            function_namespace.level(0),
+            function_object,
+            rest_client,
+        )
 
     def name(self) -> str:
         """Returns the function name."""
@@ -58,3 +85,28 @@ class GenericFunction(Function):
     def audit_info(self) -> Optional[AuditDTO]:
         """Returns the audit information."""
         return self._function_dto.audit_info()
+
+    def list_tags(self) -> list[str]:
+        """List the tag names associated with the function."""
+        return self._object_tag_operations.list_tags()
+
+    def list_tags_info(self) -> list[Tag]:
+        """List the tags associated with the function."""
+        return self._object_tag_operations.list_tags_info()
+
+    def get_tag(self, name: str) -> Tag:
+        """Get an associated tag by name."""
+        return self._object_tag_operations.get_tag(name)
+
+    def associate_tags(
+        self, tags_to_add: list[str], tags_to_remove: list[str]
+    ) -> list[str]:
+        """Associate or disassociate tags with the function."""
+        return self._object_tag_operations.associate_tags(
+            tags_to_add,
+            tags_to_remove,
+        )
+
+    def supports_tags(self) -> SupportsTags:
+        """Return the function's tag operations."""
+        return self
diff --git a/clients/client-python/gravitino/client/generic_view.py b/clients/client-python/gravitino/client/generic_view.py
index ce4e2a765c..991a2e4ce0 100644
--- a/clients/client-python/gravitino/client/generic_view.py
+++ b/clients/client-python/gravitino/client/generic_view.py
@@ -18,25 +18,49 @@
 from typing import Optional
 
 from gravitino.api.audit import Audit
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.metadata_objects import MetadataObjects
 from gravitino.api.rel.column import Column
 from gravitino.api.rel.representation import Representation
 from gravitino.api.rel.view import View
+from gravitino.api.tag.supports_tags import SupportsTags
+from gravitino.api.tag.tag import Tag
+from gravitino.client.metadata_object_tag_operations import MetadataObjectTagOperations
 from gravitino.dto.rel.view_dto import ViewDTO
+from gravitino.namespace import Namespace
+from gravitino.utils.http_client import HTTPClient
 
 
-class GenericView(View):
+class GenericView(View, SupportsTags):
     """A generic implementation of the View interface."""
 
     def __init__(
         self,
         view_dto: ViewDTO,
+        rest_client: HTTPClient,
+        view_namespace: Namespace,
     ):
         """Create a GenericView from a ViewDTO.
 
         Args:
             view_dto: The view DTO.
+            rest_client: The REST client for tag operations.
+            view_namespace: The full view namespace in metalake.catalog.schema format.
         """
         self._view_dto = view_dto
+        view_object: MetadataObject = MetadataObjects.of(
+            [
+                view_namespace.level(1),
+                view_namespace.level(2),
+                view_dto.name(),
+            ],
+            MetadataObject.Type.VIEW,
+        )
+        self._object_tag_operations = MetadataObjectTagOperations(
+            view_namespace.level(0),
+            view_object,
+            rest_client,
+        )
 
     def name(self) -> str:
         return self._view_dto.name()
@@ -61,3 +85,23 @@ class GenericView(View):
 
     def audit_info(self) -> Audit:
         return self._view_dto.audit_info()
+
+    def list_tags(self) -> list[str]:
+        return self._object_tag_operations.list_tags()
+
+    def list_tags_info(self) -> list[Tag]:
+        return self._object_tag_operations.list_tags_info()
+
+    def get_tag(self, name: str) -> Tag:
+        return self._object_tag_operations.get_tag(name)
+
+    def associate_tags(
+        self, tags_to_add: list[str], tags_to_remove: list[str]
+    ) -> list[str]:
+        return self._object_tag_operations.associate_tags(
+            tags_to_add,
+            tags_to_remove,
+        )
+
+    def supports_tags(self) -> SupportsTags:
+        return self
diff --git a/clients/client-python/gravitino/client/metadata_object_tag_operations.py b/clients/client-python/gravitino/client/metadata_object_tag_operations.py
index 499486019c..8f46ed0c6d 100644
--- a/clients/client-python/gravitino/client/metadata_object_tag_operations.py
+++ b/clients/client-python/gravitino/client/metadata_object_tag_operations.py
@@ -36,9 +36,8 @@ from gravitino.utils.string_utils import StringUtils
 
 class MetadataObjectTagOperations(SupportsTags):
     """
-    The implementation of SupportsTags. This helper is composed into metadata objects,
-    including catalog, schema, table, column, fileset, and topic, to provide tag
-    operations for these objects.
+    The implementation of SupportsTags. This helper is composed into supported metadata
+    objects to provide tag operations.
     """
 
     TAG_REQUEST_PATH = "api/metalakes/{}/objects/{}/{}/tags"
diff --git a/clients/client-python/gravitino/client/relational_catalog.py b/clients/client-python/gravitino/client/relational_catalog.py
index d42af35804..c8cffbe662 100644
--- a/clients/client-python/gravitino/client/relational_catalog.py
+++ b/clients/client-python/gravitino/client/relational_catalog.py
@@ -381,7 +381,7 @@ class RelationalCatalog(
         )
         view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
         view_resp.validate()
-        return GenericView(view_resp.view())
+        return GenericView(view_resp.view(), self.rest_client, full_namespace)
 
     def create_view(
         self,
@@ -412,7 +412,7 @@ class RelationalCatalog(
         )
         view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
         view_resp.validate()
-        return GenericView(view_resp.view())
+        return GenericView(view_resp.view(), self.rest_client, full_namespace)
 
     def alter_view(self, identifier: NameIdentifier, *changes: ViewChange) -> View:
         self._check_view_name_identifier(identifier)
@@ -429,7 +429,7 @@ class RelationalCatalog(
         )
         view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
         view_resp.validate()
-        return GenericView(view_resp.view())
+        return GenericView(view_resp.view(), self.rest_client, full_namespace)
 
     def drop_view(self, identifier: NameIdentifier) -> bool:
         self._check_view_name_identifier(identifier)
diff --git a/clients/client-python/tests/integration/test_supports_tags.py b/clients/client-python/tests/integration/test_supports_tags.py
index 2e13aad2db..39bbe4e75d 100644
--- a/clients/client-python/tests/integration/test_supports_tags.py
+++ b/clients/client-python/tests/integration/test_supports_tags.py
@@ -19,10 +19,18 @@ from random import randint
 
 from gravitino import Catalog, GravitinoAdminClient, GravitinoClient, GravitinoMetalake
 from gravitino.api.file.fileset import Fileset
+from gravitino.api.function.function import Function
+from gravitino.api.function.function_definition import FunctionDefinitions
+from gravitino.api.function.function_type import FunctionType
+from gravitino.api.function.sql_impl import SQLImpl
 from gravitino.api.model.model import Model
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_catalog import TableCatalog
 from gravitino.api.rel.types.types import Types
+from gravitino.api.rel.view import View
 from gravitino.api.tag import Tag
 from gravitino.api.tag.supports_tags import SupportsTags
 from gravitino.dto.rel.column_dto import ColumnDTO
@@ -60,6 +68,8 @@ class TestSupportsTags(IntegrationTestEnv):
     _schema_name = "tag_it_schema" + str(randint(0, 1000))
     # OTHER
     _table_name: str = "tag_it_table" + str(randint(0, 1000))
+    _view_name: str = "tag_it_view" + str(randint(0, 1000))
+    _function_name: str = "tag_it_function" + str(randint(0, 1000))
     _fileset_name: str = "tag_it_fileset" + str(randint(0, 1000))
     _model_name: str = "tag_it_model" + str(randint(0, 1000))
 
@@ -81,6 +91,8 @@ class TestSupportsTags(IntegrationTestEnv):
     _tag4: Tag
 
     _table_ident: NameIdentifier
+    _view_ident: NameIdentifier
+    _function_ident: NameIdentifier
     _fileset_ident: NameIdentifier
     _model_ident: NameIdentifier
     _hdfs_container: HDFSContainer
@@ -161,6 +173,14 @@ class TestSupportsTags(IntegrationTestEnv):
             self._schema_name,
             self._table_name,
         )
+        self._view_ident: NameIdentifier = NameIdentifier.of(
+            self._schema_name,
+            self._view_name,
+        )
+        self._function_ident: NameIdentifier = NameIdentifier.of(
+            self._schema_name,
+            self._function_name,
+        )
         self._fileset_ident: NameIdentifier = NameIdentifier.of(
             self._schema_name,
             self._fileset_name,
@@ -325,6 +345,93 @@ class TestSupportsTags(IntegrationTestEnv):
         )
         self._check_no_tag_associated(relational_table.supports_tags())
 
+    def test_view_tag_operations(self) -> None:
+        """Test tag operations (associate, list, get, dissociate) on view."""
+        self._relational_catalog.as_schemas().create_schema(
+            schema_name=self._schema_name,
+            comment="view it schema",
+            properties={},
+        )
+        table = self.create_test_table()
+        view: View = self._relational_catalog.as_view_catalog().create_view(
+            identifier=self._view_ident,
+            columns=[
+                Column.of("dt", Types.DateType.get()),
+                Column.of("country", Types.StringType.get()),
+            ],
+            representations=[
+                SQLRepresentation(
+                    Dialects.HIVE,
+                    f"SELECT dt, country FROM {table.name()}",
+                )
+            ],
+            comment="view for tag operations",
+            properties={},
+        )
+
+        view.supports_tags().associate_tags(
+            tags_to_add=[self._tag_name3, self._tag_name4],
+            tags_to_remove=[],
+        )
+        view.supports_tags().associate_tags(
+            tags_to_add=[self._tag_name1, self._tag_name2],
+            tags_to_remove=[self._tag_name3, self._tag_name4],
+        )
+        self._test_list_tags(view.supports_tags())
+        self._test_list_tags_info(view.supports_tags())
+        self._test_get_tag(view.supports_tags())
+
+        view.supports_tags().associate_tags(
+            tags_to_add=[],
+            tags_to_remove=[self._tag_name1, self._tag_name2],
+        )
+        self._check_no_tag_associated(view.supports_tags())
+
+    def test_function_tag_operations(self) -> None:
+        """Test tag operations (associate, list, get, dissociate) on function."""
+        self._relational_catalog.as_schemas().create_schema(
+            schema_name=self._schema_name,
+            comment="function it schema",
+            properties={},
+        )
+        implementation = (
+            SQLImpl.builder()
+            .with_runtime_type(SQLImpl.RuntimeType.SPARK)
+            .with_sql("SELECT 1")
+            .build()
+        )
+        definition = FunctionDefinitions.of(
+            [],
+            Types.IntegerType.get(),
+            [implementation],
+        )
+        function_catalog = self._relational_catalog.as_function_catalog()
+        function: Function = function_catalog.register_function(
+            ident=self._function_ident,
+            comment="function for tag operations",
+            function_type=FunctionType.SCALAR,
+            deterministic=True,
+            definitions=[definition],
+        )
+
+        function.supports_tags().associate_tags(
+            tags_to_add=[self._tag_name3, self._tag_name4],
+            tags_to_remove=[],
+        )
+        function.supports_tags().associate_tags(
+            tags_to_add=[self._tag_name1, self._tag_name2],
+            tags_to_remove=[self._tag_name3, self._tag_name4],
+        )
+        self._test_list_tags(function.supports_tags())
+        self._test_list_tags_info(function.supports_tags())
+        self._test_get_tag(function.supports_tags())
+
+        function.supports_tags().associate_tags(
+            tags_to_add=[],
+            tags_to_remove=[self._tag_name1, self._tag_name2],
+        )
+        self._check_no_tag_associated(function.supports_tags())
+
     def test_column_tag_operations(self) -> None:
         """Test tag operations (associate, list, get, dissociate) on column."""
         self._relational_catalog.as_schemas().create_schema(
diff --git a/clients/client-python/tests/unittests/api/function/__init__.py b/clients/client-python/tests/unittests/api/function/__init__.py
new file mode 100644
index 0000000000..13a83393a9
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/function/__init__.py
@@ -0,0 +1,16 @@
+# 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.
diff --git a/clients/client-python/tests/unittests/api/function/test_function.py b/clients/client-python/tests/unittests/api/function/test_function.py
new file mode 100644
index 0000000000..202d4a8dc0
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/function/test_function.py
@@ -0,0 +1,35 @@
+# 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 unittest
+from unittest.mock import Mock
+
+from gravitino.api.function.function import Function
+from gravitino.exceptions.base import UnsupportedOperationException
+
+
+class TestFunction(unittest.TestCase):
+    def test_default_comment(self):
+        function = Mock(spec=Function)
+
+        self.assertIsNone(Function.comment(function))
+
+    def test_supports_tags_raises_exception(self):
+        function = Mock(spec=Function)
+
+        with self.assertRaises(UnsupportedOperationException):
+            Function.supports_tags(function)
diff --git a/clients/client-python/tests/unittests/api/rel/test_view.py b/clients/client-python/tests/unittests/api/rel/test_view.py
index 19fa1769d7..54f30d3c9b 100644
--- a/clients/client-python/tests/unittests/api/rel/test_view.py
+++ b/clients/client-python/tests/unittests/api/rel/test_view.py
@@ -22,6 +22,7 @@ from gravitino.api.rel.dialects import Dialects
 from gravitino.api.rel.representation import Representation
 from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.view import View
+from gravitino.exceptions.base import UnsupportedOperationException
 
 
 class TestView(unittest.TestCase):
@@ -67,3 +68,9 @@ class TestView(unittest.TestCase):
         self.assertIsNone(View.default_catalog(view))
         self.assertIsNone(View.default_schema(view))
         self.assertEqual({}, View.properties(view))
+
+    def test_supports_tags_raises_exception(self):
+        view = Mock(spec=View)
+
+        with self.assertRaises(UnsupportedOperationException):
+            View.supports_tags(view)
diff --git a/clients/client-python/tests/unittests/test_generic_function.py b/clients/client-python/tests/unittests/test_generic_function.py
new file mode 100644
index 0000000000..85ad00af1e
--- /dev/null
+++ b/clients/client-python/tests/unittests/test_generic_function.py
@@ -0,0 +1,79 @@
+# 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 unittest
+
+from gravitino.api.function.function_type import FunctionType
+from gravitino.api.rel.types.types import Types
+from gravitino.api.tag.supports_tags import SupportsTags
+from gravitino.client.generic_function import GenericFunction
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.function.function_definition_dto import FunctionDefinitionDTO
+from gravitino.dto.function.function_dto import FunctionDTO
+from gravitino.namespace import Namespace
+from gravitino.utils.http_client import HTTPClient
+
+
+class TestGenericFunction(unittest.TestCase):
+    _rest_client = HTTPClient("http://localhost:8080")
+    _function_namespace = Namespace.of(
+        "demo_metalake",
+        "demo_catalog",
+        "demo_schema",
+    )
+
+    def _generic_function(self) -> GenericFunction:
+        return GenericFunction(
+            FunctionDTO(
+                _name="demo_function",
+                _function_type=FunctionType.SCALAR,
+                _deterministic=True,
+                _definitions=[
+                    FunctionDefinitionDTO(
+                        _parameters=[],
+                        _return_type=Types.IntegerType.get(),
+                        _impls=[],
+                    )
+                ],
+                _comment="comment",
+                _audit=AuditDTO("creator"),
+            ),
+            self._rest_client,
+            self._function_namespace,
+        )
+
+    def test_generic_function(self) -> None:
+        generic_function = self._generic_function()
+
+        self.assertEqual("demo_function", generic_function.name())
+        self.assertEqual(FunctionType.SCALAR, generic_function.function_type())
+        self.assertTrue(generic_function.deterministic())
+        self.assertEqual("comment", generic_function.comment())
+        self.assertEqual(1, len(generic_function.definitions()))
+        self.assertEqual("creator", generic_function.audit_info().creator())
+
+    def test_extends_supports_tags_class(self) -> None:
+        generic_function = self._generic_function()
+
+        self.assertTrue(issubclass(GenericFunction, SupportsTags))
+        expected_methods = ["list_tags", "list_tags_info", "get_tag", "associate_tags"]
+        self.assertTrue(
+            all(
+                callable(getattr(generic_function, method, None))
+                for method in expected_methods
+            )
+        )
diff --git a/clients/client-python/tests/unittests/test_generic_view.py b/clients/client-python/tests/unittests/test_generic_view.py
index a07c15be05..6eac593f5e 100644
--- a/clients/client-python/tests/unittests/test_generic_view.py
+++ b/clients/client-python/tests/unittests/test_generic_view.py
@@ -18,13 +18,23 @@
 import unittest
 
 from gravitino.api.rel.dialects import Dialects
+from gravitino.api.tag.supports_tags import SupportsTags
 from gravitino.client.generic_view import GenericView
 from gravitino.dto.audit_dto import AuditDTO
 from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
 from gravitino.dto.rel.view_dto import ViewDTO
+from gravitino.namespace import Namespace
+from gravitino.utils.http_client import HTTPClient
 
 
 class TestGenericView(unittest.TestCase):
+    _rest_client = HTTPClient("http://localhost:8080")
+    _view_namespace = Namespace.of(
+        "demo_metalake",
+        "demo_catalog",
+        "demo_schema",
+    )
+
     def _generic_view(
         self,
         name: str = "demo_view",
@@ -45,6 +55,8 @@ class TestGenericView(unittest.TestCase):
                 _properties={"key": "value"},
                 _audit=AuditDTO("creator"),
             ),
+            self._rest_client,
+            self._view_namespace,
         )
 
     def test_generic_view(self) -> None:
@@ -59,3 +71,15 @@ class TestGenericView(unittest.TestCase):
         self.assertEqual(1, len(generic_view.representations()))
         self.assertEqual("SELECT 1", generic_view.sql_for(Dialects.TRINO).sql())
         self.assertEqual("creator", generic_view.audit_info().creator())
+
+    def test_extends_supports_tags_class(self) -> None:
+        generic_view = self._generic_view()
+
+        self.assertTrue(issubclass(GenericView, SupportsTags))
+        expected_methods = ["list_tags", "list_tags_info", "get_tag", "associate_tags"]
+        self.assertTrue(
+            all(
+                callable(getattr(generic_view, method, None))
+                for method in expected_methods
+            )
+        )


(gravitino) 04/07: [#12089] improvement(client-python): Implement client-side view models (#12090)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 50aa8e36510d01fdacd5d2a2d2a8259f569eb628
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Mon Jul 20 21:22:50 2026 +0800

    [#12089] improvement(client-python): Implement client-side view models (#12090)
    
    ### What changes were proposed in this pull request?
    
    - Add `GenericView` as the client-side implementation of `View`.
    - Add DTOs for views and SQL representations.
    - Add polymorphic JSON serialization for view representations.
    - Extend `DTOConverters` with representation conversions.
    - Add unit tests for the new models, serialization, and conversions.
    
    ### Why are the changes needed?
    
    The Python client needs concrete view models and serialization support
    before view catalog operations can consume and return view metadata.
    
    Fix: #12089
    
    ### Does this PR introduce _any_ user-facing change?
    
    No. This PR adds the supporting client-side models. View catalog
    operations will be added separately.
    
    ### How was this patch tested?
    
    Added unit tests covering `GenericView`, view and representation DTOs,
    representation serialization, and DTO conversions. Python client
    formatting, lint, and unit tests pass.
    
    (cherry picked from commit 648fdd7c1a869f798d05e471420de6cf56e74957)
---
 .../client-python/gravitino/client/generic_view.py |  63 +++++
 .../dto/rel/json_serdes/representation_serdes.py   |  49 ++++
 .../gravitino/dto/rel/representation_dto.py        |  30 +++
 .../gravitino/dto/rel/sql_representation_dto.py    |  58 ++++
 .../client-python/gravitino/dto/rel/view_dto.py    | 105 ++++++++
 .../gravitino/dto/util/dto_converters.py           |  54 +++-
 .../dto/rel/test_representation_serdes.py          |  54 ++++
 .../dto/rel/test_sql_representation_dto.py         |  55 ++++
 .../tests/unittests/dto/rel/test_view_dto.py       | 293 +++++++++++++++++++++
 .../unittests/dto/util/test_dto_converters.py      |  52 ++++
 .../tests/unittests/test_generic_view.py           |  61 +++++
 11 files changed, 868 insertions(+), 6 deletions(-)

diff --git a/clients/client-python/gravitino/client/generic_view.py b/clients/client-python/gravitino/client/generic_view.py
new file mode 100644
index 0000000000..ce4e2a765c
--- /dev/null
+++ b/clients/client-python/gravitino/client/generic_view.py
@@ -0,0 +1,63 @@
+# 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 typing import Optional
+
+from gravitino.api.audit import Audit
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.view import View
+from gravitino.dto.rel.view_dto import ViewDTO
+
+
+class GenericView(View):
+    """A generic implementation of the View interface."""
+
+    def __init__(
+        self,
+        view_dto: ViewDTO,
+    ):
+        """Create a GenericView from a ViewDTO.
+
+        Args:
+            view_dto: The view DTO.
+        """
+        self._view_dto = view_dto
+
+    def name(self) -> str:
+        return self._view_dto.name()
+
+    def comment(self) -> Optional[str]:
+        return self._view_dto.comment()
+
+    def columns(self) -> list[Column]:
+        return self._view_dto.columns()
+
+    def representations(self) -> list[Representation]:
+        return self._view_dto.representations()
+
+    def default_catalog(self) -> Optional[str]:
+        return self._view_dto.default_catalog()
+
+    def default_schema(self) -> Optional[str]:
+        return self._view_dto.default_schema()
+
+    def properties(self) -> dict[str, str]:
+        return self._view_dto.properties()
+
+    def audit_info(self) -> Audit:
+        return self._view_dto.audit_info()
diff --git a/clients/client-python/gravitino/dto/rel/json_serdes/representation_serdes.py b/clients/client-python/gravitino/dto/rel/json_serdes/representation_serdes.py
new file mode 100644
index 0000000000..1414633df2
--- /dev/null
+++ b/clients/client-python/gravitino/dto/rel/json_serdes/representation_serdes.py
@@ -0,0 +1,49 @@
+# 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 typing import Optional
+
+from gravitino.api.rel.representation import Representation
+from gravitino.dto.rel.representation_dto import RepresentationDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.exceptions.base import IllegalArgumentException
+from gravitino.utils.precondition import Precondition
+
+
+class RepresentationSerdes:
+    """Serdes for view representation DTOs."""
+
+    @staticmethod
+    def serialize(value: Optional[RepresentationDTO]) -> Optional[dict]:
+        """Encode a representation DTO to a dictionary."""
+        if value is None:
+            return None
+        return value.to_dict()
+
+    @staticmethod
+    def deserialize(value: Optional[dict]) -> Optional[RepresentationDTO]:
+        """Decode a representation DTO from a dictionary."""
+        if value is None:
+            return None
+        Precondition.check_argument(
+            isinstance(value, dict) and len(value) > 0,
+            f"Cannot parse representation from invalid JSON: {value}",
+        )
+        if value.get("type") == Representation.TYPE_SQL:
+            return SQLRepresentationDTO.from_dict(value)
+        raise IllegalArgumentException(
+            f"Unsupported representation type: {value.get('type')}"
+        )
diff --git a/clients/client-python/gravitino/dto/rel/representation_dto.py b/clients/client-python/gravitino/dto/rel/representation_dto.py
new file mode 100644
index 0000000000..dab099399a
--- /dev/null
+++ b/clients/client-python/gravitino/dto/rel/representation_dto.py
@@ -0,0 +1,30 @@
+# 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 abstractmethod
+
+from dataclasses_json import DataClassJsonMixin
+
+from gravitino.api.rel.representation import Representation
+
+
+class RepresentationDTO(Representation, DataClassJsonMixin):
+    """DTO base class for view representations."""
+
+    @abstractmethod
+    def validate(self) -> None:
+        """Validates the representation DTO."""
diff --git a/clients/client-python/gravitino/dto/rel/sql_representation_dto.py b/clients/client-python/gravitino/dto/rel/sql_representation_dto.py
new file mode 100644
index 0000000000..45f7974b33
--- /dev/null
+++ b/clients/client-python/gravitino/dto/rel/sql_representation_dto.py
@@ -0,0 +1,58 @@
+# 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 dataclasses import dataclass, field
+
+from dataclasses_json import config
+
+from gravitino.api.rel.representation import Representation
+from gravitino.dto.rel.representation_dto import RepresentationDTO
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class SQLRepresentationDTO(RepresentationDTO):
+    """DTO for SQL view representations."""
+
+    _dialect: str = field(metadata=config(field_name="dialect"))
+    _sql: str = field(metadata=config(field_name="sql"))
+    _type: str = field(
+        default=Representation.TYPE_SQL, metadata=config(field_name="type")
+    )
+
+    def type(self) -> str:
+        """Returns the representation type."""
+        return self._type
+
+    def dialect(self) -> str:
+        """Returns the SQL dialect."""
+        return self._dialect
+
+    def sql(self) -> str:
+        """Returns the SQL text."""
+        return self._sql
+
+    def validate(self) -> None:
+        Precondition.check_string_not_empty(
+            self._dialect, '"dialect" field is required and cannot be empty'
+        )
+        Precondition.check_string_not_empty(
+            self._sql, '"sql" field is required and cannot be empty'
+        )
+
+    def __hash__(self) -> int:
+        return hash((self._type, self._dialect, self._sql))
diff --git a/clients/client-python/gravitino/dto/rel/view_dto.py b/clients/client-python/gravitino/dto/rel/view_dto.py
new file mode 100644
index 0000000000..3606217cab
--- /dev/null
+++ b/clients/client-python/gravitino/dto/rel/view_dto.py
@@ -0,0 +1,105 @@
+# 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 dataclasses import dataclass, field
+from typing import Optional
+
+from dataclasses_json import DataClassJsonMixin, config
+
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.view import View
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.json_serdes.representation_serdes import RepresentationSerdes
+from gravitino.dto.rel.representation_dto import RepresentationDTO
+from gravitino.dto.util.dto_converters import DTOConverters
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class ViewDTO(View, DataClassJsonMixin):  # pylint: disable=too-many-instance-attributes
+    """Represents a View DTO."""
+
+    _name: str = field(metadata=config(field_name="name"))
+    _columns: Optional[list[ColumnDTO]] = field(
+        default=None, metadata=config(field_name="columns")
+    )
+    _representations: Optional[list[RepresentationDTO]] = field(
+        default=None,
+        metadata=config(
+            field_name="representations",
+            encoder=lambda items: [
+                RepresentationSerdes.serialize(item) for item in items
+            ],
+            decoder=lambda values: [
+                RepresentationSerdes.deserialize(value) for value in values
+            ],
+        ),
+    )
+    _audit: Optional[AuditDTO] = field(
+        default=None, metadata=config(field_name="audit")
+    )
+    _comment: Optional[str] = field(default=None, metadata=config(field_name="comment"))
+    _default_catalog: Optional[str] = field(
+        default=None, metadata=config(field_name="defaultCatalog")
+    )
+    _default_schema: Optional[str] = field(
+        default=None, metadata=config(field_name="defaultSchema")
+    )
+    _properties: Optional[dict[str, str]] = field(
+        default=None, metadata=config(field_name="properties")
+    )
+
+    def __post_init__(self):
+        if self._columns is None:
+            self._columns = []
+        Precondition.check_string_not_empty(self._name, "name cannot be null or empty")
+        Precondition.check_argument(self._audit is not None, "audit cannot be null")
+        Precondition.check_argument(
+            self._representations is not None and len(self._representations) > 0,
+            "representations cannot be null or empty",
+        )
+        for representation in self._representations:
+            Precondition.check_argument(
+                representation is not None, "representation must not be null"
+            )
+            representation.validate()
+
+    def name(self) -> str:
+        return self._name
+
+    def comment(self) -> Optional[str]:
+        return self._comment
+
+    def columns(self) -> list[Column]:
+        return self._columns
+
+    def representations(self) -> list[Representation]:
+        return DTOConverters.from_dtos(self._representations)
+
+    def default_catalog(self) -> Optional[str]:
+        return self._default_catalog
+
+    def default_schema(self) -> Optional[str]:
+        return self._default_schema
+
+    def properties(self) -> dict[str, str]:
+        return self._properties or {}
+
+    def audit_info(self) -> AuditDTO:
+        return self._audit
diff --git a/clients/client-python/gravitino/dto/util/dto_converters.py b/clients/client-python/gravitino/dto/util/dto_converters.py
index 1aa128e179..9aedba7f40 100644
--- a/clients/client-python/gravitino/dto/util/dto_converters.py
+++ b/clients/client-python/gravitino/dto/util/dto_converters.py
@@ -41,6 +41,8 @@ from gravitino.api.rel.partitions.identity_partition import IdentityPartition
 from gravitino.api.rel.partitions.list_partition import ListPartition
 from gravitino.api.rel.partitions.partition import Partition
 from gravitino.api.rel.partitions.range_partition import RangePartition
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_change import (
     AddColumn,
@@ -87,7 +89,9 @@ from gravitino.dto.rel.partitions.identity_partition_dto import IdentityPartitio
 from gravitino.dto.rel.partitions.list_partition_dto import ListPartitionDTO
 from gravitino.dto.rel.partitions.partition_dto import PartitionDTO
 from gravitino.dto.rel.partitions.range_partition_dto import RangePartitionDTO
+from gravitino.dto.rel.representation_dto import RepresentationDTO
 from gravitino.dto.rel.sort_order_dto import SortOrderDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
 from gravitino.dto.rel.table_dto import TableDTO
 from gravitino.dto.requests.table_update_request import (
     TableUpdateRequest,
@@ -227,6 +231,19 @@ class DTOConverters:
             DTOConverters.from_function_arg(dto.default_value()),
         )
 
+    @from_dto.register
+    @staticmethod
+    def _(dto: SQLRepresentationDTO) -> SQLRepresentation:
+        """Converts a SQLRepresentationDTO to a SQLRepresentation.
+
+        Args:
+            dto (SQLRepresentationDTO): The SQLRepresentation DTO to be converted.
+
+        Returns:
+            SQLRepresentation: The SQLRepresentation.
+        """
+        return SQLRepresentation(_dialect=dto.dialect(), _sql=dto.sql())
+
     @from_dto.register
     @staticmethod
     def _(dto: Partitioning) -> Transform:  # pylint: disable=too-many-return-statements
@@ -375,22 +392,25 @@ class DTOConverters:
     @staticmethod
     def from_dtos(dtos: list[SortOrderDTO]) -> list[SortOrder]: ...  # pragma: no cover
 
+    @overload
+    @staticmethod
+    def from_dtos(
+        dtos: list[RepresentationDTO],
+    ) -> list[Representation]: ...  # pragma: no cover
+
     @overload
     @staticmethod
     def from_dtos(dtos: list[Partitioning]) -> list[Transform]: ...  # pragma: no cover
 
     @staticmethod
     def from_dtos(dtos):
-        """Converts list of `ColumnDTO`, `IndexDTO`, `SortOrderDTO`, or `Partitioning`
-        to the corresponding list of `Column`s, `Index`es, `SortOrder`s, or `Transform`s.
+        """Converts a list of DTOs to the corresponding API objects.
 
         Args:
-            dtos (list[ColumnDTO] | list[IndexDTO] | list[SortOrderDTO] | list[Partitioning]):
-                The DTOs to be converted.
+            dtos: The DTOs to be converted.
 
         Returns:
-            list[Column] | list[Index] | list[SortOrder] | list[Transform]:
-                The list of Columns, Indexes, SortOrders, or Transforms depends on the input DTOs.
+            The converted objects.
         """
         if not dtos:
             return []
@@ -557,6 +577,16 @@ class DTOConverters:
             field_names=obj.field_names(),
         )
 
+    @to_dto.register
+    @staticmethod
+    def _(obj: RepresentationDTO) -> RepresentationDTO:
+        return obj
+
+    @to_dto.register
+    @staticmethod
+    def _(obj: SQLRepresentation) -> SQLRepresentationDTO:
+        return SQLRepresentationDTO(_dialect=obj.dialect(), _sql=obj.sql())
+
     @to_dto.register
     @staticmethod
     def _(obj: Partitioning) -> Partitioning:
@@ -646,6 +676,18 @@ class DTOConverters:
     @staticmethod
     def to_dtos(dtos: list[SortOrderDTO]) -> list[SortOrderDTO]: ...  # pragma: no cover
 
+    @overload
+    @staticmethod
+    def to_dtos(
+        dtos: list[Representation],
+    ) -> list[RepresentationDTO]: ...  # pragma: no cover
+
+    @overload
+    @staticmethod
+    def to_dtos(
+        dtos: list[RepresentationDTO],
+    ) -> list[RepresentationDTO]: ...  # pragma: no cover
+
     @overload
     @staticmethod
     def to_dtos(dtos: list[Transform]) -> list[Partitioning]: ...  # pragma: no cover
diff --git a/clients/client-python/tests/unittests/dto/rel/test_representation_serdes.py b/clients/client-python/tests/unittests/dto/rel/test_representation_serdes.py
new file mode 100644
index 0000000000..e75fc0829c
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/rel/test_representation_serdes.py
@@ -0,0 +1,54 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.representation import Representation
+from gravitino.dto.rel.json_serdes.representation_serdes import RepresentationSerdes
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+class TestRepresentationSerdes(unittest.TestCase):
+    def test_representation_serdes(self):
+        representation = SQLRepresentationDTO(
+            _dialect=Dialects.TRINO, _sql="SELECT id FROM table"
+        )
+        serialized = RepresentationSerdes.serialize(representation)
+
+        self.assertEqual(Representation.TYPE_SQL, serialized["type"])
+        self.assertEqual(Dialects.TRINO, serialized["dialect"])
+        self.assertEqual("SELECT id FROM table", serialized["sql"])
+        self.assertEqual(representation, RepresentationSerdes.deserialize(serialized))
+
+    def test_representation_serdes_none(self):
+        self.assertIsNone(RepresentationSerdes.serialize(None))
+        self.assertIsNone(RepresentationSerdes.deserialize(None))
+
+    def test_representation_serdes_invalid_json(self):
+        for invalid_json in ("invalid", {}):
+            with self.subTest(invalid_json=invalid_json):
+                with self.assertRaisesRegex(
+                    IllegalArgumentException,
+                    "Cannot parse representation from invalid JSON",
+                ):
+                    RepresentationSerdes.deserialize(invalid_json)
+
+    def test_representation_serdes_unknown_type(self):
+        with self.assertRaises(IllegalArgumentException):
+            RepresentationSerdes.deserialize({"type": "unknown"})
diff --git a/clients/client-python/tests/unittests/dto/rel/test_sql_representation_dto.py b/clients/client-python/tests/unittests/dto/rel/test_sql_representation_dto.py
new file mode 100644
index 0000000000..7cdcb85d09
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/rel/test_sql_representation_dto.py
@@ -0,0 +1,55 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.representation import Representation
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+
+
+class TestSQLRepresentationDTO(unittest.TestCase):
+    def test_sql_representation_dto(self):
+        representation = SQLRepresentationDTO(
+            _dialect=Dialects.TRINO, _sql="SELECT id FROM table"
+        )
+
+        self.assertEqual(Representation.TYPE_SQL, representation.type())
+        self.assertEqual(Dialects.TRINO, representation.dialect())
+        self.assertEqual("SELECT id FROM table", representation.sql())
+        self.assertEqual(
+            representation,
+            SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql="SELECT id FROM table"),
+        )
+        self.assertEqual(
+            hash(representation),
+            hash(
+                SQLRepresentationDTO(
+                    _dialect=Dialects.TRINO, _sql="SELECT id FROM table"
+                )
+            ),
+        )
+        self.assertNotEqual(
+            representation,
+            SQLRepresentationDTO(_dialect=Dialects.SPARK, _sql="SELECT id FROM table"),
+        )
+
+    def test_sql_representation_dto_validate(self):
+        with self.assertRaises(ValueError):
+            SQLRepresentationDTO(_dialect="", _sql="SELECT 1").validate()
+        with self.assertRaises(ValueError):
+            SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql="").validate()
diff --git a/clients/client-python/tests/unittests/dto/rel/test_view_dto.py b/clients/client-python/tests/unittests/dto/rel/test_view_dto.py
new file mode 100644
index 0000000000..c568646594
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/rel/test_view_dto.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.
+
+import unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.rel.types.types import Types
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.dto.rel.view_dto import ViewDTO
+
+
+class TestViewDTO(unittest.TestCase):
+    @staticmethod
+    def _column(name: str = "id") -> ColumnDTO:
+        return ColumnDTO(
+            _name=name,
+            _data_type=Types.IntegerType.get(),
+            _comment="column comment",
+            _nullable=False,
+        )
+
+    @staticmethod
+    def _representation(
+        dialect: str = Dialects.TRINO, sql: str = "SELECT id FROM table"
+    ) -> SQLRepresentationDTO:
+        return SQLRepresentationDTO(_dialect=dialect, _sql=sql)
+
+    def _view_dto(
+        self,
+        name: str = "test_view",
+        columns: list[ColumnDTO] = None,
+        representations: list[SQLRepresentationDTO] = None,
+        comment: str = "view comment",
+        properties: dict[str, str] = None,
+    ) -> ViewDTO:
+        return ViewDTO(
+            _name=name,
+            _columns=columns if columns is not None else [self._column()],
+            _representations=(
+                representations
+                if representations is not None
+                else [self._representation()]
+            ),
+            _comment=comment,
+            _default_catalog="catalog",
+            _default_schema="schema",
+            _properties=properties if properties is not None else {"k1": "v1"},
+            _audit=AuditDTO(
+                "creator", "2022-01-01T00:00:00Z", "modifier", "2022-01-02T00:00:00Z"
+            ),
+        )
+
+    def test_view_dto_serialization(self):
+        view = self._view_dto()
+
+        deserialized = ViewDTO.from_json(view.to_json())
+
+        self.assertEqual(view, deserialized)
+        self.assertEqual("test_view", deserialized.name())
+        self.assertEqual("view comment", deserialized.comment())
+        self.assertEqual("catalog", deserialized.default_catalog())
+        self.assertEqual("schema", deserialized.default_schema())
+        self.assertEqual({"k1": "v1"}, deserialized.properties())
+        self.assertEqual("creator", deserialized.audit_info().creator())
+        self.assertEqual(1, len(deserialized.columns()))
+        self.assertEqual(1, len(deserialized.representations()))
+        self.assertIsInstance(deserialized.representations()[0], SQLRepresentation)
+        self.assertEqual(
+            "SELECT id FROM table",
+            deserialized.representations()[0].sql(),
+        )
+
+    def test_view_dto_deserialize_from_raw_json(self):
+        raw_json = """
+        {
+            "name": "raw_view",
+            "comment": "raw comment",
+            "columns": [
+                {
+                    "name": "id",
+                    "type": "integer",
+                    "comment": "id column",
+                    "nullable": false,
+                    "autoIncrement": false
+                }
+            ],
+            "representations": [
+                {
+                    "type": "sql",
+                    "dialect": "spark",
+                    "sql": "SELECT id FROM table"
+                }
+            ],
+            "defaultCatalog": "catalog",
+            "defaultSchema": "schema",
+            "properties": {
+                "k1": "v1"
+            },
+            "audit": {
+                "creator": "creator"
+            }
+        }
+        """
+
+        view = ViewDTO.from_json(raw_json)
+
+        self.assertEqual("raw_view", view.name())
+        self.assertEqual("raw comment", view.comment())
+        self.assertEqual("catalog", view.default_catalog())
+        self.assertEqual("schema", view.default_schema())
+        self.assertEqual({"k1": "v1"}, view.properties())
+        self.assertEqual("creator", view.audit_info().creator())
+        self.assertEqual(1, len(view.columns()))
+        self.assertEqual("id", view.columns()[0].name())
+        self.assertEqual(1, len(view.representations()))
+        self.assertIsInstance(view.representations()[0], SQLRepresentation)
+        self.assertEqual("spark", view.representations()[0].dialect())
+        self.assertEqual("SELECT id FROM table", view.representations()[0].sql())
+
+    def test_view_dto_defaults(self):
+        view = ViewDTO(
+            _name="test_view",
+            _representations=[self._representation()],
+            _audit=AuditDTO("creator"),
+        )
+
+        self.assertEqual([], view.columns())
+        self.assertEqual([], view.to_dict()["columns"])
+        self.assertEqual({}, view.properties())
+        self.assertIsNone(view.comment())
+        self.assertIsNone(view.default_catalog())
+        self.assertIsNone(view.default_schema())
+
+    def test_view_dto_deserialize_invalid_name(self):
+        raw_json = """
+        {
+            "name": "",
+            "representations": [
+                {
+                    "type": "sql",
+                    "dialect": "spark",
+                    "sql": "SELECT 1"
+                }
+            ],
+            "audit": {
+                "creator": "creator"
+            }
+        }
+        """
+
+        with self.assertRaisesRegex(ValueError, "name cannot be null or empty"):
+            ViewDTO.from_json(raw_json)
+
+    def test_view_dto_deserialize_missing_audit(self):
+        raw_json = """
+        {
+            "name": "test_view",
+            "representations": [
+                {
+                    "type": "sql",
+                    "dialect": "spark",
+                    "sql": "SELECT 1"
+                }
+            ]
+        }
+        """
+
+        with self.assertRaisesRegex(ValueError, "audit cannot be null"):
+            ViewDTO.from_json(raw_json)
+
+    def test_view_dto_deserialize_missing_representations(self):
+        raw_json = """
+        {
+            "name": "test_view",
+            "audit": {
+                "creator": "creator"
+            }
+        }
+        """
+
+        with self.assertRaisesRegex(
+            ValueError, "representations cannot be null or empty"
+        ):
+            ViewDTO.from_json(raw_json)
+
+    def test_view_dto_deserialize_invalid_representations(self):
+        raw_json_strings = [
+            """
+            {
+                "name": "test_view",
+                "representations": [],
+                "audit": {
+                    "creator": "creator"
+                }
+            }
+            """,
+            """
+            {
+                "name": "test_view",
+                "representations": [null],
+                "audit": {
+                    "creator": "creator"
+                }
+            }
+            """,
+            """
+            {
+                "name": "test_view",
+                "representations": [
+                    {
+                        "type": "sql",
+                        "dialect": "",
+                        "sql": "SELECT 1"
+                    }
+                ],
+                "audit": {
+                    "creator": "creator"
+                }
+            }
+            """,
+            """
+            {
+                "name": "test_view",
+                "representations": [
+                    {
+                        "type": "sql",
+                        "dialect": "spark",
+                        "sql": ""
+                    }
+                ],
+                "audit": {
+                    "creator": "creator"
+                }
+            }
+            """,
+        ]
+
+        for raw_json in raw_json_strings:
+            with self.assertRaises(ValueError):
+                ViewDTO.from_json(raw_json)
+
+    def test_view_dto_validate_constructor_arguments(self):
+        with self.assertRaises(ValueError):
+            ViewDTO(
+                _name="",
+                _representations=[self._representation()],
+                _audit=AuditDTO("creator"),
+            )
+        with self.assertRaises(ValueError):
+            ViewDTO(_name="test_view", _representations=[], _audit=AuditDTO("creator"))
+        with self.assertRaises(ValueError):
+            ViewDTO(
+                _name="test_view", _representations=[None], _audit=AuditDTO("creator")
+            )
+        with self.assertRaises(ValueError):
+            ViewDTO(
+                _name="test_view",
+                _representations=[self._representation()],
+                _audit=None,
+            )
+
+    def test_view_dto_sql_for(self):
+        view = self._view_dto(
+            representations=[
+                self._representation(Dialects.TRINO, "SELECT 1"),
+                self._representation(Dialects.SPARK, "SELECT 2"),
+            ]
+        )
+        deserialized = ViewDTO.from_json(view.to_json())
+
+        self.assertEqual("SELECT 1", deserialized.sql_for("trino").sql())
+        self.assertEqual("SELECT 1", deserialized.sql_for("TRINO").sql())
+        self.assertEqual("SELECT 1", deserialized.sql_for("Trino").sql())
+        self.assertEqual("SELECT 2", deserialized.sql_for(Dialects.SPARK).sql())
+        self.assertIsNone(deserialized.sql_for("hive"))
+        self.assertIsNone(deserialized.sql_for(None))
diff --git a/clients/client-python/tests/unittests/dto/util/test_dto_converters.py b/clients/client-python/tests/unittests/dto/util/test_dto_converters.py
index 51ebf0bdd9..f9199d28d9 100644
--- a/clients/client-python/tests/unittests/dto/util/test_dto_converters.py
+++ b/clients/client-python/tests/unittests/dto/util/test_dto_converters.py
@@ -23,6 +23,7 @@ from typing import Dict, cast
 from unittest.mock import MagicMock, patch
 
 from gravitino.api.rel.column import Column
+from gravitino.api.rel.dialects import Dialects
 from gravitino.api.rel.expressions.distributions.distributions import Distributions
 from gravitino.api.rel.expressions.distributions.strategy import Strategy
 from gravitino.api.rel.expressions.expression import Expression
@@ -41,6 +42,7 @@ from gravitino.api.rel.indexes.indexes import Indexes
 from gravitino.api.rel.partitions.partition import Partition
 from gravitino.api.rel.partitions.partitions import Partitions
 from gravitino.api.rel.table import Table
+from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.types.types import Types
 from gravitino.dto.rel.column_dto import ColumnDTO
 from gravitino.dto.rel.distribution_dto import DistributionDTO
@@ -71,6 +73,7 @@ from gravitino.dto.rel.partitions.identity_partition_dto import IdentityPartitio
 from gravitino.dto.rel.partitions.list_partition_dto import ListPartitionDTO
 from gravitino.dto.rel.partitions.range_partition_dto import RangePartitionDTO
 from gravitino.dto.rel.sort_order_dto import SortOrderDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
 from gravitino.dto.rel.table_dto import TableDTO
 from gravitino.dto.util.dto_converters import DTOConverters
 from gravitino.exceptions.base import IllegalArgumentException
@@ -386,6 +389,16 @@ class TestDTOConverters(unittest.TestCase):
         converted = DTOConverters.from_dto(sort_order_dto)
         self.assertTrue(converted == expected)
 
+    def test_from_dto_sql_representation(self):
+        representation_dto = SQLRepresentationDTO(Dialects.TRINO, "SELECT 1")
+
+        converted = DTOConverters.from_dto(representation_dto)
+
+        self.assertEqual(
+            SQLRepresentation(Dialects.TRINO, "SELECT 1"),
+            converted,
+        )
+
     def test_from_dto_column(self):
         column_name = "test_column"
         column_data_type = Types.IntegerType.get()
@@ -537,6 +550,20 @@ class TestDTOConverters(unittest.TestCase):
         converted = DTOConverters.from_dtos(sort_order_dtos)
         self.assertListEqual(converted, expected)
 
+    def test_from_dtos_representations(self):
+        representation_dtos = [
+            SQLRepresentationDTO(Dialects.TRINO, "SELECT 1"),
+            SQLRepresentationDTO(Dialects.SPARK, "SELECT 2"),
+        ]
+        expected = [
+            SQLRepresentation(Dialects.TRINO, "SELECT 1"),
+            SQLRepresentation(Dialects.SPARK, "SELECT 2"),
+        ]
+
+        converted = DTOConverters.from_dtos(representation_dtos)
+
+        self.assertListEqual(converted, expected)
+
     def test_from_dtos_partitioning(self):
         field_name = ["score"]
         field_names = [field_name]
@@ -668,6 +695,16 @@ class TestDTOConverters(unittest.TestCase):
         with self.assertRaisesRegex(IllegalArgumentException, "Unsupported type"):
             DTOConverters.to_dto("test")
 
+    def test_to_dto_sql_representation(self):
+        representation = SQLRepresentation(Dialects.TRINO, "SELECT 1")
+
+        dto = DTOConverters.to_dto(representation)
+
+        self.assertIsInstance(dto, SQLRepresentationDTO)
+        self.assertEqual(Dialects.TRINO, dto.dialect())
+        self.assertEqual("SELECT 1", dto.sql())
+        self.assertIs(dto, DTOConverters.to_dto(dto))
+
     def test_to_dto_range_partition(self):
         converted = DTOConverters.to_dto(
             Partitions.range(
@@ -858,6 +895,21 @@ class TestDTOConverters(unittest.TestCase):
 
         self.assertListEqual(DTOConverters.to_dtos(converted_dtos), converted_dtos)
 
+    def test_to_dtos_representations(self):
+        representations = [
+            SQLRepresentation(Dialects.TRINO, "SELECT 1"),
+            SQLRepresentation(Dialects.SPARK, "SELECT 2"),
+        ]
+        expected_dtos = [
+            SQLRepresentationDTO(Dialects.TRINO, "SELECT 1"),
+            SQLRepresentationDTO(Dialects.SPARK, "SELECT 2"),
+        ]
+
+        converted_dtos = DTOConverters.to_dtos(representations)
+
+        self.assertListEqual(converted_dtos, expected_dtos)
+        self.assertListEqual(DTOConverters.to_dtos(converted_dtos), converted_dtos)
+
     def test_to_dtos_single_field_transforms(self):
         converted_dtos = DTOConverters.to_dtos(self.single_field_transforms.values())
         for key, converted in zip(self.single_field_transforms.keys(), converted_dtos):
diff --git a/clients/client-python/tests/unittests/test_generic_view.py b/clients/client-python/tests/unittests/test_generic_view.py
new file mode 100644
index 0000000000..a07c15be05
--- /dev/null
+++ b/clients/client-python/tests/unittests/test_generic_view.py
@@ -0,0 +1,61 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.client.generic_view import GenericView
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.dto.rel.view_dto import ViewDTO
+
+
+class TestGenericView(unittest.TestCase):
+    def _generic_view(
+        self,
+        name: str = "demo_view",
+        comment: str = "comment",
+        sql: str = "SELECT 1",
+        default_catalog: str = "demo_catalog",
+        default_schema: str = "demo_schema",
+    ) -> GenericView:
+        return GenericView(
+            ViewDTO(
+                _name=name,
+                _representations=[
+                    SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql=sql)
+                ],
+                _comment=comment,
+                _default_catalog=default_catalog,
+                _default_schema=default_schema,
+                _properties={"key": "value"},
+                _audit=AuditDTO("creator"),
+            ),
+        )
+
+    def test_generic_view(self) -> None:
+        generic_view = self._generic_view()
+
+        self.assertEqual("demo_view", generic_view.name())
+        self.assertEqual("comment", generic_view.comment())
+        self.assertEqual("demo_catalog", generic_view.default_catalog())
+        self.assertEqual("demo_schema", generic_view.default_schema())
+        self.assertEqual({"key": "value"}, generic_view.properties())
+        self.assertEqual(0, len(generic_view.columns()))
+        self.assertEqual(1, len(generic_view.representations()))
+        self.assertEqual("SELECT 1", generic_view.sql_for(Dialects.TRINO).sql())
+        self.assertEqual("creator", generic_view.audit_info().creator())


(gravitino) 05/07: [#12116] improvement(client-python): Add view create/drop operations (#12117)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 561bb566b6ab951de66d467932cc4786334ba920
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Wed Jul 22 12:53:39 2026 +0800

    [#12116] improvement(client-python): Add view create/drop operations (#12117)
    
    ### What changes were proposed in this pull request?
    
    - Extend `RelationalCatalog` with `ViewCatalog`.
    - Add `as_view_catalog`, `create_view`, and `drop_view`.
    - Add request and response DTOs for view creation.
    - Add view-specific REST error handling.
    - Generalize the entity namespace helper for table and view operations.
    - Add corresponding unit and integration tests.
    
    ### Why are the changes needed?
    
    The Python client currently lacks support for view create/drop
    operations. These changes allow users to create and drop views through
    the Python client.
    
    Fix: #12116
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Python client users can now create and drop views through
    `RelationalCatalog.as_view_catalog()`.
    
    ### How was this patch tested?
    
    Added unit tests for request and response validation, REST error
    handling, and view create/drop operations.
    
    Added integration tests covering view creation, duplicate creation, view
    deletion, and deletion of nonexistent views.
    
    (cherry picked from commit 941f030f3e0f624351fda392f39fd969c081c893)
---
 .../gravitino/client/relational_catalog.py         | 151 ++++++++++++++++++---
 .../gravitino/dto/requests/view_create_request.py  |  96 +++++++++++++
 .../gravitino/dto/responses/view_response.py       |  49 +++++++
 .../exceptions/handlers/view_error_handler.py      |  78 +++++++++++
 .../tests/integration/test_relational_catalog.py   |  86 ++++++++++++
 .../dto/requests/test_view_create_request.py       | 144 ++++++++++++++++++++
 .../unittests/dto/responses/test_view_response.py  |  51 +++++++
 .../tests/unittests/test_error_handler.py          |  83 +++++++++++
 .../tests/unittests/test_relational_catalog.py     |  93 +++++++++++++
 9 files changed, 811 insertions(+), 20 deletions(-)

diff --git a/clients/client-python/gravitino/client/relational_catalog.py b/clients/client-python/gravitino/client/relational_catalog.py
index 40fbc9914c..26562e1e9a 100644
--- a/clients/client-python/gravitino/client/relational_catalog.py
+++ b/clients/client-python/gravitino/client/relational_catalog.py
@@ -24,19 +24,28 @@ from gravitino.api.rel.expressions.distributions.distribution import Distributio
 from gravitino.api.rel.expressions.sorts.sort_order import SortOrder
 from gravitino.api.rel.expressions.transforms.transform import Transform
 from gravitino.api.rel.indexes.index import Index
+from gravitino.api.rel.representation import Representation
 from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_catalog import TableCatalog
+from gravitino.api.rel.view import View
+from gravitino.api.rel.view_catalog import ViewCatalog
+from gravitino.api.rel.view_change import ViewChange
 from gravitino.client.base_schema_catalog import BaseSchemaCatalog
+from gravitino.client.generic_view import GenericView
 from gravitino.client.relational_table import RelationalTable
 from gravitino.dto.audit_dto import AuditDTO
 from gravitino.dto.rel.distribution_dto import DistributionDTO
 from gravitino.dto.requests.table_create_request import TableCreateRequest
 from gravitino.dto.requests.table_updates_request import TableUpdatesRequest
+from gravitino.dto.requests.view_create_request import ViewCreateRequest
 from gravitino.dto.responses.drop_response import DropResponse
 from gravitino.dto.responses.entity_list_response import EntityListResponse
 from gravitino.dto.responses.table_response import TableResponse
+from gravitino.dto.responses.view_response import ViewResponse
 from gravitino.dto.util.dto_converters import DTOConverters
+from gravitino.exceptions.base import UnsupportedOperationException
 from gravitino.exceptions.handlers.table_error_handler import TABLE_ERROR_HANDLER
+from gravitino.exceptions.handlers.view_error_handler import VIEW_ERROR_HANDLER
 from gravitino.name_identifier import NameIdentifier
 from gravitino.namespace import Namespace
 from gravitino.rest.rest_utils import encode_string
@@ -44,13 +53,13 @@ from gravitino.utils import HTTPClient
 
 
 class RelationalCatalog(
-    BaseSchemaCatalog, TableCatalog
+    BaseSchemaCatalog, TableCatalog, ViewCatalog
 ):  # pylint: disable=too-many-ancestors
     """Relational catalog is a catalog implementation
 
-    The `RelationalCatalog` supports relational database like metadata operations,
-    for example, schemas and tables list, creation, update and deletion. A Relational
-    catalog is under the metalake.
+    The `RelationalCatalog` supports relational metadata operations such as listing,
+    creating, updating, and deleting schemas, tables, and views. A relational catalog
+    belongs to a metalake.
     """
 
     PRIVILEGES: Final[str] = "privileges"
@@ -88,6 +97,32 @@ class RelationalCatalog(
         """
         return self
 
+    def as_view_catalog(self) -> ViewCatalog:
+        """Return this relational catalog as a :class:`ViewCatalog`.
+
+        This method returns ``self`` to provide access to view-related
+        operations defined by the :class:`ViewCatalog` interface.
+
+        Returns:
+            ViewCatalog: The current catalog instance as a ``ViewCatalog``.
+        """
+        return self
+
+    def _get_entity_full_namespace(self, entity_namespace: Namespace) -> Namespace:
+        """Get the full namespace of an entity with the given short namespace.
+
+        Args:
+            entity_namespace (Namespace): The entity's short namespace, which is the schema name.
+
+        Returns:
+            Namespace: full namespace of the entity, which is "metalake.catalog.schema" format.
+        """
+        return Namespace.of(
+            self._catalog_namespace.level(0),
+            self._name,
+            entity_namespace.level(0),
+        )
+
     def _check_table_name_identifier(self, identifier: NameIdentifier) -> None:
         """Check whether the `NameIdentifier` of a table is valid.
 
@@ -119,27 +154,51 @@ class RelationalCatalog(
             f"Table namespace must be non-null and have 1 level, the input namespace is {namespace}",
         )
 
-    def _get_table_full_namespace(self, table_namespace: Namespace) -> Namespace:
-        """Get the full namespace of the table with the given table's short namespace (schema name).
+    def _format_table_request_path(self, ns: Namespace) -> str:
+        schema_ns = Namespace.of(ns.level(0), ns.level(1))
+        return (
+            f"{BaseSchemaCatalog.format_schema_request_path(schema_ns)}"
+            f"/{encode_string(ns.level(2))}"
+            "/tables"
+        )
+
+    def _check_view_name_identifier(self, identifier: NameIdentifier) -> None:
+        """Check whether the `NameIdentifier` of a view is valid.
 
         Args:
-            table_namespace (Namespace): The table's short namespace, which is the schema name.
+            identifier (NameIdentifier):
+                The NameIdentifier to check, which should be "schema.view" format.
 
-        Returns:
-            Namespace: full namespace of the table, which is "metalake.catalog.schema" format.
+        Raises:
+            IllegalNameIdentifierException: If the Namespace is not valid.
         """
-        return Namespace.of(
-            self._catalog_namespace.level(0),
-            self._name,
-            table_namespace.level(0),
+        NameIdentifier.check(identifier is not None, "NameIdentifier must not be null")
+        NameIdentifier.check(
+            identifier.name() is not None and identifier.name() != "",
+            "NameIdentifier name must not be empty",
         )
+        self._check_view_namespace(identifier.namespace())
 
-    def _format_table_request_path(self, ns: Namespace) -> str:
+    def _check_view_namespace(self, namespace: Namespace) -> None:
+        """Check whether the namespace of a view is valid, which should be "schema".
+
+        Args:
+            namespace (Namespace): The namespace to check.
+
+        Raises:
+            IllegalNamespaceException: If the Namespace is not valid.
+        """
+        Namespace.check(
+            namespace is not None and namespace.length() == 1,
+            f"View namespace must be non-null and have 1 level, the input namespace is {namespace}",
+        )
+
+    def _format_view_request_path(self, ns: Namespace) -> str:
         schema_ns = Namespace.of(ns.level(0), ns.level(1))
         return (
             f"{BaseSchemaCatalog.format_schema_request_path(schema_ns)}"
             f"/{encode_string(ns.level(2))}"
-            "/tables"
+            "/views"
         )
 
     def create_table(
@@ -169,7 +228,7 @@ class RelationalCatalog(
             _indexes=DTOConverters.to_dtos(indexes),
         )
         req.validate()
-        full_namespace = self._get_table_full_namespace(identifier.namespace())
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
         resp = self.rest_client.post(
             self._format_table_request_path(full_namespace),
             json=req,
@@ -181,7 +240,7 @@ class RelationalCatalog(
 
     def list_tables(self, namespace: Namespace) -> list[NameIdentifier]:
         self._check_table_namespace(namespace)
-        full_namespace = self._get_table_full_namespace(namespace)
+        full_namespace = self._get_entity_full_namespace(namespace)
         resp = self.rest_client.get(
             self._format_table_request_path(full_namespace),
             error_handler=TABLE_ERROR_HANDLER,
@@ -207,7 +266,7 @@ class RelationalCatalog(
         required_privilege_names: Optional[set[Privilege.Name]] = None,
     ) -> Table:
         self._check_table_name_identifier(identifier)
-        full_namespace = self._get_table_full_namespace(identifier.namespace())
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
         query_params = (
             {
                 RelationalCatalog.PRIVILEGES: ",".join(
@@ -244,7 +303,7 @@ class RelationalCatalog(
 
     def alter_table(self, identifier: NameIdentifier, *changes) -> Table:
         self._check_table_name_identifier(identifier)
-        full_namespace = self._get_table_full_namespace(identifier.namespace())
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
         updates_request = TableUpdatesRequest(
             updates=[
                 DTOConverters.to_table_update_request(change) for change in changes
@@ -276,7 +335,7 @@ class RelationalCatalog(
 
     def _drop_table(self, identifier: NameIdentifier, purge: bool) -> bool:
         self._check_table_name_identifier(identifier)
-        full_namespace = self._get_table_full_namespace(identifier.namespace())
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
         resp = self.rest_client.delete(
             f"{self._format_table_request_path(full_namespace)}"
             f"/{encode_string(identifier.name())}",
@@ -286,3 +345,55 @@ class RelationalCatalog(
         drop_resp = DropResponse.from_json(resp.body, infer_missing=True)
         drop_resp.validate()
         return drop_resp.dropped()
+
+    def list_views(self, namespace: Namespace) -> list[NameIdentifier]:
+        raise UnsupportedOperationException("Listing views is not supported")
+
+    def load_view(self, identifier: NameIdentifier) -> View:
+        raise UnsupportedOperationException("Loading views is not supported")
+
+    def create_view(
+        self,
+        identifier: NameIdentifier,
+        columns: list[Column],
+        representations: list[Representation],
+        comment: Optional[str] = None,
+        default_catalog: Optional[str] = None,
+        default_schema: Optional[str] = None,
+        properties: Optional[dict[str, str]] = None,
+    ) -> View:
+        self._check_view_name_identifier(identifier)
+        req = ViewCreateRequest(
+            _name=identifier.name(),
+            _columns=DTOConverters.to_dtos(columns),
+            _representations=DTOConverters.to_dtos(representations),
+            _comment=comment,
+            _default_catalog=default_catalog,
+            _default_schema=default_schema,
+            _properties=properties,
+        )
+        req.validate()
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
+        resp = self.rest_client.post(
+            self._format_view_request_path(full_namespace),
+            json=req,
+            error_handler=VIEW_ERROR_HANDLER,
+        )
+        view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
+        view_resp.validate()
+        return GenericView(view_resp.view())
+
+    def alter_view(self, identifier: NameIdentifier, *changes: ViewChange) -> View:
+        raise UnsupportedOperationException("View alteration is not supported")
+
+    def drop_view(self, identifier: NameIdentifier) -> bool:
+        self._check_view_name_identifier(identifier)
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
+        resp = self.rest_client.delete(
+            f"{self._format_view_request_path(full_namespace)}"
+            f"/{encode_string(identifier.name())}",
+            error_handler=VIEW_ERROR_HANDLER,
+        )
+        drop_resp = DropResponse.from_json(resp.body, infer_missing=True)
+        drop_resp.validate()
+        return drop_resp.dropped()
diff --git a/clients/client-python/gravitino/dto/requests/view_create_request.py b/clients/client-python/gravitino/dto/requests/view_create_request.py
new file mode 100644
index 0000000000..700ac5b9a6
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/view_create_request.py
@@ -0,0 +1,96 @@
+# 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 dataclasses import dataclass, field
+from typing import Optional
+
+from dataclasses_json import config
+
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.json_serdes.representation_serdes import RepresentationSerdes
+from gravitino.dto.rel.representation_dto import RepresentationDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class ViewCreateRequest(RESTRequest):
+    """Represents a request to create a view."""
+
+    _name: str = field(metadata=config(field_name="name"))
+    _columns: Optional[list[ColumnDTO]] = field(
+        default=None, metadata=config(field_name="columns")
+    )
+    _representations: Optional[list[RepresentationDTO]] = field(
+        default=None,
+        metadata=config(
+            field_name="representations",
+            encoder=lambda items: [
+                RepresentationSerdes.serialize(item) for item in items
+            ],
+            decoder=lambda values: [
+                RepresentationSerdes.deserialize(value) for value in values
+            ],
+            exclude=lambda value: value is None,
+        ),
+    )
+    _comment: Optional[str] = field(default=None, metadata=config(field_name="comment"))
+    _default_catalog: Optional[str] = field(
+        default=None, metadata=config(field_name="defaultCatalog")
+    )
+    _default_schema: Optional[str] = field(
+        default=None, metadata=config(field_name="defaultSchema")
+    )
+    _properties: Optional[dict[str, str]] = field(
+        default=None, metadata=config(field_name="properties")
+    )
+
+    def validate(self) -> None:
+        Precondition.check_string_not_empty(
+            self._name, '"name" field is required and cannot be empty'
+        )
+        Precondition.check_argument(
+            self._representations is not None and len(self._representations) > 0,
+            '"representations" field is required and cannot be empty',
+        )
+        for representation in self._representations:
+            Precondition.check_argument(
+                representation is not None, "representation must not be null"
+            )
+            representation.validate()
+        if self._columns:
+            for column in self._columns:
+                Precondition.check_argument(
+                    column is not None, "column must not be null"
+                )
+                column.validate()
+        ViewCreateRequest.validate_no_duplicate_dialects(self._representations)
+
+    @staticmethod
+    def validate_no_duplicate_dialects(
+        representations: list[RepresentationDTO],
+    ) -> None:
+        """Validate that SQL representations do not use duplicate dialects."""
+        seen_dialects = set()
+        for representation in representations:
+            if isinstance(representation, SQLRepresentationDTO):
+                Precondition.check_argument(
+                    representation.dialect() not in seen_dialects,
+                    f"Duplicate SQL representation dialect: {representation.dialect()}",
+                )
+                seen_dialects.add(representation.dialect())
diff --git a/clients/client-python/gravitino/dto/responses/view_response.py b/clients/client-python/gravitino/dto/responses/view_response.py
new file mode 100644
index 0000000000..63d2d2ca22
--- /dev/null
+++ b/clients/client-python/gravitino/dto/responses/view_response.py
@@ -0,0 +1,49 @@
+# 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 dataclasses import dataclass, field
+
+from dataclasses_json import config
+
+from gravitino.dto.rel.view_dto import ViewDTO
+from gravitino.dto.responses.base_response import BaseResponse
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+@dataclass
+class ViewResponse(BaseResponse):
+    """Response object for view-related operations."""
+
+    _view: ViewDTO = field(metadata=config(field_name="view"))
+
+    def view(self) -> ViewDTO:
+        """Returns the view DTO."""
+        return self._view
+
+    def validate(self):
+        """Validates the response data."""
+        super().validate()
+        if self._view is None:
+            raise IllegalArgumentException("view must not be null")
+        if not self._view.name():
+            raise IllegalArgumentException("view 'name' must not be null or empty")
+        if self._view.audit_info() is None:
+            raise IllegalArgumentException("view 'audit' must not be null")
+        if not self._view.representations():
+            raise IllegalArgumentException(
+                "view 'representations' must not be null or empty"
+            )
diff --git a/clients/client-python/gravitino/exceptions/handlers/view_error_handler.py b/clients/client-python/gravitino/exceptions/handlers/view_error_handler.py
new file mode 100644
index 0000000000..674438c144
--- /dev/null
+++ b/clients/client-python/gravitino/exceptions/handlers/view_error_handler.py
@@ -0,0 +1,78 @@
+# 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.constants.error import ErrorConstants
+from gravitino.dto.responses.error_response import ErrorResponse
+from gravitino.exceptions.base import (
+    CatalogNotInUseException,
+    ForbiddenException,
+    IllegalArgumentException,
+    MetalakeNotInUseException,
+    NoSuchCatalogException,
+    NoSuchSchemaException,
+    NoSuchViewException,
+    NotFoundException,
+    NotInUseException,
+    UnsupportedOperationException,
+    ViewAlreadyExistsException,
+)
+from gravitino.exceptions.handlers.rest_error_handler import RestErrorHandler
+
+
+class ViewErrorHandler(RestErrorHandler):
+    """Error handler for view operations."""
+
+    def handle(self, error_response: ErrorResponse):
+        error_message = error_response.format_error_message()
+        code = ErrorConstants(error_response.code())
+        exception_type = error_response.type()
+
+        if code is ErrorConstants.ILLEGAL_ARGUMENTS_CODE:
+            raise IllegalArgumentException(error_message)
+
+        if code is ErrorConstants.NOT_FOUND_CODE:
+            if exception_type == NoSuchCatalogException.__name__:
+                raise NoSuchCatalogException(error_message)
+            if exception_type == NoSuchSchemaException.__name__:
+                raise NoSuchSchemaException(error_message)
+            if exception_type == NoSuchViewException.__name__:
+                raise NoSuchViewException(error_message)
+            raise NotFoundException(error_message)
+
+        if code is ErrorConstants.ALREADY_EXISTS_CODE:
+            raise ViewAlreadyExistsException(error_message)
+
+        if code is ErrorConstants.INTERNAL_ERROR_CODE:
+            raise RuntimeError(error_message)
+
+        if code is ErrorConstants.UNSUPPORTED_OPERATION_CODE:
+            raise UnsupportedOperationException(error_message)
+
+        if code is ErrorConstants.FORBIDDEN_CODE:
+            raise ForbiddenException(error_message)
+
+        if code is ErrorConstants.NOT_IN_USE_CODE:
+            if exception_type == CatalogNotInUseException.__name__:
+                raise CatalogNotInUseException(error_message)
+            if exception_type == MetalakeNotInUseException.__name__:
+                raise MetalakeNotInUseException(error_message)
+            raise NotInUseException(error_message)
+
+        super().handle(error_response)
+
+
+VIEW_ERROR_HANDLER = ViewErrorHandler()
diff --git a/clients/client-python/tests/integration/test_relational_catalog.py b/clients/client-python/tests/integration/test_relational_catalog.py
index 0dd75eb838..1723025514 100644
--- a/clients/client-python/tests/integration/test_relational_catalog.py
+++ b/clients/client-python/tests/integration/test_relational_catalog.py
@@ -17,6 +17,7 @@
 
 import logging
 from random import randint
+from uuid import uuid4
 
 from gravitino import (
     Catalog,
@@ -25,17 +26,21 @@ from gravitino import (
     NameIdentifier,
 )
 from gravitino.api.rel.column import Column
+from gravitino.api.rel.dialects import Dialects
 from gravitino.api.rel.expressions.distributions.distributions import Distributions
 from gravitino.api.rel.expressions.transforms.transforms import Transforms
 from gravitino.api.rel.indexes.indexes import Indexes
+from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_change import TableChange
 from gravitino.api.rel.types.types import Types
+from gravitino.api.rel.view import View
 from gravitino.client.relational_table import RelationalTable
 from gravitino.exceptions.base import (
     NoSuchSchemaException,
     NoSuchTableException,
     TableAlreadyExistsException,
+    ViewAlreadyExistsException,
 )
 from gravitino.namespace import Namespace
 from tests.integration.containers.hdfs_container import HDFSContainer
@@ -53,6 +58,8 @@ class TestRelationalCatalog(IntegrationTestEnv):
     TABLE_IDENT: NameIdentifier = NameIdentifier.of(SCHEMA_NAME, TABLE_NAME)
     TABLE_COMMENT: str = "Test table for relational catalog"
     TABLE_PROPERTIES = {"property1": "value1", "property2": "value2"}
+    VIEW_COMMENT: str = "Test view for relational catalog"
+    VIEW_PROPERTIES = {"view_property1": "value1", "view_property2": "value2"}
 
     @classmethod
     def setUpClass(cls):
@@ -94,6 +101,10 @@ class TestRelationalCatalog(IntegrationTestEnv):
         super().tearDownClass()
 
     def setUp(self):
+        self.view_name = f"test_view_{uuid4().hex}"
+        self.view_ident = NameIdentifier.of(
+            TestRelationalCatalog.SCHEMA_NAME, self.view_name
+        )
         # Create schema for each test
         TestRelationalCatalog.schema = (
             TestRelationalCatalog.catalog.as_schemas().create_schema(
@@ -137,6 +148,28 @@ class TestRelationalCatalog(IntegrationTestEnv):
             indexes=Indexes.EMPTY_INDEXES,
         )
 
+    def _create_test_view(self) -> View:
+        """Create a test view with basic columns."""
+
+        view_catalog = self.catalog.as_view_catalog()
+        columns = [
+            Column.of("id", Types.LongType.get(), "Primary key"),
+            Column.of("name", Types.StringType.get(), "Name column"),
+        ]
+
+        return view_catalog.create_view(
+            identifier=self.view_ident,
+            columns=columns,
+            representations=[
+                SQLRepresentation(
+                    Dialects.HIVE,
+                    f"SELECT id, name FROM {TestRelationalCatalog.TABLE_NAME}",
+                )
+            ],
+            comment=TestRelationalCatalog.VIEW_COMMENT,
+            properties=TestRelationalCatalog.VIEW_PROPERTIES,
+        )
+
     def test_relational_catalog_create_table(self):
         """Test creating a table in the relational catalog."""
         table = self._create_test_table()
@@ -311,3 +344,56 @@ class TestRelationalCatalog(IntegrationTestEnv):
             new_property_value,
         )
         self.assertNotIn("property2", altered_table.properties())
+
+    def test_relational_catalog_create_view(self):
+        """Test creating a view in the relational catalog."""
+        self._create_test_table()
+        view = self._create_test_view()
+        self.assertIsNotNone(view)
+        self.assertEqual(view.name(), self.view_name)
+        self.assertEqual(view.comment(), TestRelationalCatalog.VIEW_COMMENT)
+        self.assertEqual(view.properties().get("view_property1"), "value1")
+        self.assertEqual(view.properties().get("view_property2"), "value2")
+        self.assertEqual(len(view.columns()), 2)
+        self.assertEqual(view.columns()[0].name(), "id")
+        self.assertEqual(view.columns()[0].data_type(), Types.LongType.get())
+        self.assertEqual(view.columns()[1].name(), "name")
+        self.assertEqual(view.columns()[1].data_type(), Types.StringType.get())
+        self.assertEqual(
+            view.sql_for(Dialects.HIVE).sql(),
+            f"SELECT id, name FROM {TestRelationalCatalog.TABLE_NAME}",
+        )
+
+    def test_relational_catalog_create_view_already_exists(self):
+        """Test creating a view that already exists should raise exception."""
+        self._create_test_table()
+        self._create_test_view()
+        view_catalog = self.catalog.as_view_catalog()
+
+        with self.assertRaises(ViewAlreadyExistsException):
+            view_catalog.create_view(
+                identifier=self.view_ident,
+                columns=[Column.of("id", Types.LongType.get(), "Primary key")],
+                representations=[
+                    SQLRepresentation(
+                        Dialects.HIVE,
+                        f"SELECT id FROM {TestRelationalCatalog.TABLE_NAME}",
+                    )
+                ],
+            )
+
+    def test_relational_catalog_drop_view(self):
+        """Test dropping a view from the relational catalog."""
+        self._create_test_table()
+        self._create_test_view()
+        view_catalog = self.catalog.as_view_catalog()
+
+        is_dropped = view_catalog.drop_view(self.view_ident)
+        self.assertTrue(is_dropped)
+
+    def test_relational_catalog_drop_view_not_exists(self):
+        """Test dropping a view that doesn't exist should return False."""
+        view_catalog = self.catalog.as_view_catalog()
+
+        is_dropped = view_catalog.drop_view(self.view_ident)
+        self.assertFalse(is_dropped)
diff --git a/clients/client-python/tests/unittests/dto/requests/test_view_create_request.py b/clients/client-python/tests/unittests/dto/requests/test_view_create_request.py
new file mode 100644
index 0000000000..358dc6c195
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/requests/test_view_create_request.py
@@ -0,0 +1,144 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.types.types import Types
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.dto.requests.view_create_request import ViewCreateRequest
+
+
+class TestViewCreateRequest(unittest.TestCase):
+    @staticmethod
+    def _request(
+        name: str = "test_view",
+        columns: list[ColumnDTO] = None,
+        representations: list[SQLRepresentationDTO] = None,
+    ) -> ViewCreateRequest:
+        return ViewCreateRequest(
+            _name=name,
+            _columns=(
+                columns
+                if columns is not None
+                else [
+                    ColumnDTO(
+                        _name="id",
+                        _data_type=Types.IntegerType.get(),
+                        _nullable=False,
+                    )
+                ]
+            ),
+            _representations=(
+                representations
+                if representations is not None
+                else [
+                    SQLRepresentationDTO(
+                        _dialect=Dialects.TRINO,
+                        _sql="SELECT id FROM test_table",
+                    )
+                ]
+            ),
+            _comment="comment",
+            _default_catalog="catalog",
+            _default_schema="schema",
+            _properties={"k1": "v1"},
+        )
+
+    def test_validate_and_serialize(self):
+        request = self._request()
+
+        request.validate()
+        json_str = request.to_json()
+        deserialized = ViewCreateRequest.from_json(json_str)
+        deserialized.validate()
+
+        self.assertEqual(request, deserialized)
+        self.assertIn('"name": "test_view"', json_str)
+        self.assertIn('"columns"', json_str)
+        self.assertIn('"representations"', json_str)
+        self.assertIn(f'"type": "{Representation.TYPE_SQL}"', json_str)
+        self.assertIn(f'"dialect": "{Dialects.TRINO}"', json_str)
+        self.assertIn('"sql": "SELECT id FROM test_table"', json_str)
+        self.assertIn('"defaultCatalog": "catalog"', json_str)
+        self.assertIn('"defaultSchema": "schema"', json_str)
+
+    def test_validate_rejects_invalid_name(self):
+        request = self._request(name="")
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_validate_rejects_empty_representations(self):
+        request = self._request(representations=[])
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_serialize_excludes_missing_representations(self):
+        request = ViewCreateRequest(_name="test_view")
+
+        self.assertNotIn('"representations"', request.to_json())
+
+    def test_validate_rejects_missing_representations(self):
+        request = ViewCreateRequest(_name="test_view")
+
+        with self.assertRaisesRegex(
+            ValueError, '"representations" field is required and cannot be empty'
+        ):
+            request.validate()
+
+    def test_validate_rejects_null_representation(self):
+        request = self._request(representations=[None])
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_validate_rejects_invalid_representation(self):
+        request = self._request(
+            representations=[SQLRepresentationDTO(_dialect="", _sql="SELECT 1")]
+        )
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_validate_rejects_null_column(self):
+        request = self._request(columns=[None])
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_validate_rejects_invalid_column(self):
+        request = self._request(
+            columns=[ColumnDTO(_name="", _data_type=Types.IntegerType.get())]
+        )
+
+        with self.assertRaises(ValueError):
+            request.validate()
+
+    def test_validate_rejects_duplicate_dialect(self):
+        request = self._request(
+            representations=[
+                SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql="SELECT 1"),
+                SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql="SELECT 2"),
+            ]
+        )
+
+        with self.assertRaises(ValueError):
+            request.validate()
diff --git a/clients/client-python/tests/unittests/dto/responses/test_view_response.py b/clients/client-python/tests/unittests/dto/responses/test_view_response.py
new file mode 100644
index 0000000000..210383c57b
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/responses/test_view_response.py
@@ -0,0 +1,51 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.dto.rel.view_dto import ViewDTO
+from gravitino.dto.responses.view_response import ViewResponse
+from gravitino.exceptions.base import IllegalArgumentException
+
+
+class TestViewResponse(unittest.TestCase):
+    @staticmethod
+    def _view_dto() -> ViewDTO:
+        return ViewDTO(
+            _name="test_view",
+            _representations=[
+                SQLRepresentationDTO(_dialect=Dialects.TRINO, _sql="SELECT 1")
+            ],
+            _audit=AuditDTO("creator"),
+        )
+
+    def test_view_response(self):
+        response = ViewResponse(_code=0, _view=self._view_dto())
+
+        response.validate()
+        deserialized = ViewResponse.from_json(response.to_json())
+
+        self.assertEqual("test_view", deserialized.view().name())
+        self.assertEqual("creator", deserialized.view().audit_info().creator())
+        self.assertEqual(1, len(deserialized.view().representations()))
+
+    def test_view_response_validate(self):
+        with self.assertRaises(IllegalArgumentException):
+            ViewResponse(_code=0, _view=None).validate()
diff --git a/clients/client-python/tests/unittests/test_error_handler.py b/clients/client-python/tests/unittests/test_error_handler.py
index a7e52b443f..64c190e43d 100644
--- a/clients/client-python/tests/unittests/test_error_handler.py
+++ b/clients/client-python/tests/unittests/test_error_handler.py
@@ -43,6 +43,7 @@ from gravitino.exceptions.base import (
     NoSuchSchemaException,
     NoSuchTableException,
     NoSuchUserException,
+    NoSuchViewException,
     NotEmptyException,
     NotFoundException,
     NotInUseException,
@@ -53,6 +54,7 @@ from gravitino.exceptions.base import (
     TableAlreadyExistsException,
     UnsupportedOperationException,
     UserAlreadyExistsException,
+    ViewAlreadyExistsException,
     GroupAlreadyExistsException,
 )
 from gravitino.exceptions.handlers.catalog_error_handler import CATALOG_ERROR_HANDLER
@@ -73,6 +75,7 @@ from gravitino.exceptions.handlers.role_error_handler import ROLE_ERROR_HANDLER
 from gravitino.exceptions.handlers.schema_error_handler import SCHEMA_ERROR_HANDLER
 from gravitino.exceptions.handlers.table_error_handler import TABLE_ERROR_HANDLER
 from gravitino.exceptions.handlers.user_error_handler import USER_ERROR_HANDLER
+from gravitino.exceptions.handlers.view_error_handler import VIEW_ERROR_HANDLER
 
 
 class TestErrorHandler(unittest.TestCase):
@@ -435,6 +438,86 @@ class TestErrorHandler(unittest.TestCase):
                 ErrorResponse.generate_error_response(Exception, "mock error")
             )
 
+    def test_view_error_handler(self):
+        with self.assertRaises(IllegalArgumentException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    IllegalArgumentException, "mock error"
+                )
+            )
+
+        with self.assertRaises(NoSuchCatalogException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    NoSuchCatalogException, "mock error"
+                )
+            )
+
+        with self.assertRaises(NoSuchSchemaException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    NoSuchSchemaException, "mock error"
+                )
+            )
+
+        with self.assertRaises(NoSuchViewException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(NoSuchViewException, "mock error")
+            )
+
+        with self.assertRaises(NotFoundException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(NotFoundException, "mock error")
+            )
+
+        with self.assertRaises(ViewAlreadyExistsException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    ViewAlreadyExistsException, "mock error"
+                )
+            )
+
+        with self.assertRaises(RuntimeError):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(RuntimeError, "mock error")
+            )
+
+        with self.assertRaises(UnsupportedOperationException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    UnsupportedOperationException, "mock error"
+                )
+            )
+
+        with self.assertRaises(ForbiddenException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(ForbiddenException, "mock error")
+            )
+
+        with self.assertRaises(CatalogNotInUseException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    CatalogNotInUseException, "mock error"
+                )
+            )
+
+        with self.assertRaises(MetalakeNotInUseException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(
+                    MetalakeNotInUseException, "mock error"
+                )
+            )
+
+        with self.assertRaises(NotInUseException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(NotInUseException, "mock error")
+            )
+
+        with self.assertRaises(RESTException):
+            VIEW_ERROR_HANDLER.handle(
+                ErrorResponse.generate_error_response(Exception, "mock error")
+            )
+
     def test_user_error_handler(self):
         with self.assertRaises(NoSuchMetalakeException):
             USER_ERROR_HANDLER.handle(
diff --git a/clients/client-python/tests/unittests/test_relational_catalog.py b/clients/client-python/tests/unittests/test_relational_catalog.py
index abb80509b9..5cfe5528b7 100644
--- a/clients/client-python/tests/unittests/test_relational_catalog.py
+++ b/clients/client-python/tests/unittests/test_relational_catalog.py
@@ -20,19 +20,28 @@ from http.client import HTTPResponse
 from unittest.mock import Mock, patch
 
 from gravitino.api.authorization.privileges import Privilege
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.table_change import TableChange
+from gravitino.api.rel.types.types import Types
 from gravitino.client.relational_catalog import RelationalCatalog
 from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.rel.column_dto import ColumnDTO
 from gravitino.dto.rel.distribution_dto import DistributionDTO
+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.dto.responses.drop_response import DropResponse
 from gravitino.dto.responses.entity_list_response import EntityListResponse
 from gravitino.dto.responses.table_response import TableResponse
+from gravitino.dto.responses.view_response import ViewResponse
 from gravitino.dto.util.dto_converters import DTOConverters
 from gravitino.exceptions.base import (
     NoSuchSchemaException,
     NoSuchTableException,
     TableAlreadyExistsException,
+    ViewAlreadyExistsException,
 )
 from gravitino.name_identifier import NameIdentifier
 from gravitino.namespace import Namespace
@@ -48,6 +57,8 @@ class TestRelationalCatalog(unittest.TestCase):
         cls.table_name = "test_table"
         cls.catalog_namespace = Namespace.of(cls.metalake_name)
         cls.table_identifier = NameIdentifier.of(cls.schema_name, cls.table_name)
+        cls.view_name = "test_view"
+        cls.view_identifier = NameIdentifier.of(cls.schema_name, cls.view_name)
         cls.rest_client = HTTPClient("http://localhost:8090")
         cls.catalog = RelationalCatalog(
             catalog_namespace=cls.catalog_namespace,
@@ -185,6 +196,30 @@ class TestRelationalCatalog(unittest.TestCase):
         }
         """
         cls.table_dto = TableDTO.from_json(cls.TABLE_DTO_JSON_STRING)
+        cls.view_dto = ViewDTO(
+            _name=cls.view_name,
+            _columns=[
+                ColumnDTO(
+                    _name="id",
+                    _data_type=Types.IntegerType.get(),
+                    _comment="id column",
+                    _nullable=False,
+                )
+            ],
+            _representations=[
+                SQLRepresentationDTO(
+                    _dialect=Dialects.TRINO,
+                    _sql="SELECT id FROM test_table",
+                )
+            ],
+            _comment="test view comment",
+            _default_catalog="test_catalog",
+            _default_schema="test_schema",
+            _properties={"k1": "v1"},
+            _audit=AuditDTO(
+                "creator", "2022-01-01T00:00:00Z", "modifier", "2022-01-01T00:00:00Z"
+            ),
+        )
 
     def _get_mock_http_resp(self, json_str: str, return_code: int = 200):
         mock_http_resp = Mock(HTTPResponse)
@@ -199,6 +234,10 @@ class TestRelationalCatalog(unittest.TestCase):
         table_catalog = self.catalog.as_table_catalog()
         self.assertIs(table_catalog, self.catalog)
 
+    def test_as_view_catalog(self):
+        view_catalog = self.catalog.as_view_catalog()
+        self.assertIs(view_catalog, self.catalog)
+
     def test_create_table(self):
         resp_body = TableResponse(0, self.table_dto)
         mock_resp = self._get_mock_http_resp(resp_body.to_json())
@@ -452,3 +491,57 @@ class TestRelationalCatalog(unittest.TestCase):
                 TableChange.update_column_nullability(["id"], nullable=True),
             )
             self.assertEqual(table.name(), self.table_dto.name())
+
+    def test_create_view(self):
+        resp_body = ViewResponse(0, self.view_dto)
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.post",
+            return_value=mock_resp,
+        ):
+            view = self.catalog.as_view_catalog().create_view(
+                self.view_identifier,
+                [Column.of("id", Types.IntegerType.get(), nullable=False)],
+                [SQLRepresentation(Dialects.TRINO, "SELECT id FROM test_table")],
+                comment="test view comment",
+                default_catalog="test_catalog",
+                default_schema="test_schema",
+                properties={"k1": "v1"},
+            )
+            self.assertEqual(self.view_name, view.name())
+            self.assertEqual("test view comment", view.comment())
+
+    def test_create_view_already_exists(self):
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.post",
+            side_effect=ViewAlreadyExistsException("View already exists"),
+        ):
+            with self.assertRaises(ViewAlreadyExistsException):
+                self.catalog.as_view_catalog().create_view(
+                    self.view_identifier,
+                    [Column.of("id", Types.IntegerType.get())],
+                    [SQLRepresentation(Dialects.TRINO, "SELECT id FROM test_table")],
+                )
+
+    def test_drop_view(self):
+        resp_body = DropResponse(0, True)
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.delete",
+            return_value=mock_resp,
+        ):
+            is_dropped = self.catalog.as_view_catalog().drop_view(self.view_identifier)
+            self.assertTrue(is_dropped)
+
+    def test_drop_view_not_exists(self):
+        resp_body = DropResponse(0, False)
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.delete",
+            return_value=mock_resp,
+        ):
+            is_dropped = self.catalog.as_view_catalog().drop_view(self.view_identifier)
+            self.assertFalse(is_dropped)


(gravitino) 06/07: [#12158] improvement(client-python): Add view query/alter operations (#12159)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 17fb105c566a139661ade15982924be417066d05
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Fri Jul 24 11:13:54 2026 +0800

    [#12158] improvement(client-python): Add view query/alter operations (#12159)
    
    ### What changes were proposed in this pull request?
    
    - Add view list, load, existence check, and alter operations to
    `RelationalCatalog`.
    - Add request DTOs for view updates.
    - Support rename, set/remove property, and replace view changes.
    - Add corresponding unit and integration tests.
    
    ### Why are the changes needed?
    
    The Python client currently supports view create/drop operations but
    lacks view query/alter operations. These changes complete the basic view
    management workflow through the Python client.
    
    Fix: #12158
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Python client users can now list, load, check, and alter views
    through `RelationalCatalog.as_view_catalog()`.
    
    ### How was this patch tested?
    
    Added unit tests for view query operations, update request conversion,
    serialization, validation, and error handling.
    
    Added integration tests covering view listing, loading, existence
    checks, property updates, and related error cases.
    
    (cherry picked from commit 2214a29dcc3d6091b52f0ee4ad8eedee92615393)
---
 .../gravitino/client/relational_catalog.py         |  83 ++++++++-
 .../gravitino/dto/requests/view_update_request.py  | 166 +++++++++++++++++
 .../gravitino/dto/requests/view_updates_request.py |  38 ++++
 .../tests/integration/test_relational_catalog.py   |  85 +++++++++
 .../dto/requests/test_view_update_request.py       | 197 +++++++++++++++++++++
 .../tests/unittests/test_relational_catalog.py     | 158 +++++++++++++++++
 6 files changed, 722 insertions(+), 5 deletions(-)

diff --git a/clients/client-python/gravitino/client/relational_catalog.py b/clients/client-python/gravitino/client/relational_catalog.py
index 26562e1e9a..d42af35804 100644
--- a/clients/client-python/gravitino/client/relational_catalog.py
+++ b/clients/client-python/gravitino/client/relational_catalog.py
@@ -29,7 +29,13 @@ from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_catalog import TableCatalog
 from gravitino.api.rel.view import View
 from gravitino.api.rel.view_catalog import ViewCatalog
-from gravitino.api.rel.view_change import ViewChange
+from gravitino.api.rel.view_change import (
+    RemoveProperty,
+    RenameView,
+    ReplaceView,
+    SetProperty,
+    ViewChange,
+)
 from gravitino.client.base_schema_catalog import BaseSchemaCatalog
 from gravitino.client.generic_view import GenericView
 from gravitino.client.relational_table import RelationalTable
@@ -38,12 +44,17 @@ from gravitino.dto.rel.distribution_dto import DistributionDTO
 from gravitino.dto.requests.table_create_request import TableCreateRequest
 from gravitino.dto.requests.table_updates_request import TableUpdatesRequest
 from gravitino.dto.requests.view_create_request import ViewCreateRequest
+from gravitino.dto.requests.view_update_request import (
+    ViewUpdateRequest,
+    ViewUpdateRequestBase,
+)
+from gravitino.dto.requests.view_updates_request import ViewUpdatesRequest
 from gravitino.dto.responses.drop_response import DropResponse
 from gravitino.dto.responses.entity_list_response import EntityListResponse
 from gravitino.dto.responses.table_response import TableResponse
 from gravitino.dto.responses.view_response import ViewResponse
 from gravitino.dto.util.dto_converters import DTOConverters
-from gravitino.exceptions.base import UnsupportedOperationException
+from gravitino.exceptions.base import IllegalArgumentException
 from gravitino.exceptions.handlers.table_error_handler import TABLE_ERROR_HANDLER
 from gravitino.exceptions.handlers.view_error_handler import VIEW_ERROR_HANDLER
 from gravitino.name_identifier import NameIdentifier
@@ -347,10 +358,30 @@ class RelationalCatalog(
         return drop_resp.dropped()
 
     def list_views(self, namespace: Namespace) -> list[NameIdentifier]:
-        raise UnsupportedOperationException("Listing views is not supported")
+        self._check_view_namespace(namespace)
+        full_namespace = self._get_entity_full_namespace(namespace)
+        resp = self.rest_client.get(
+            self._format_view_request_path(full_namespace),
+            error_handler=VIEW_ERROR_HANDLER,
+        )
+        entity_list_resp = EntityListResponse.from_json(resp.body, infer_missing=True)
+        entity_list_resp.validate()
+        return [
+            NameIdentifier.of(ident.namespace().level(2), ident.name())
+            for ident in entity_list_resp.identifiers()
+        ]
 
     def load_view(self, identifier: NameIdentifier) -> View:
-        raise UnsupportedOperationException("Loading views is not supported")
+        self._check_view_name_identifier(identifier)
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
+        resp = self.rest_client.get(
+            f"{self._format_view_request_path(full_namespace)}"
+            f"/{encode_string(identifier.name())}",
+            error_handler=VIEW_ERROR_HANDLER,
+        )
+        view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
+        view_resp.validate()
+        return GenericView(view_resp.view())
 
     def create_view(
         self,
@@ -384,7 +415,21 @@ class RelationalCatalog(
         return GenericView(view_resp.view())
 
     def alter_view(self, identifier: NameIdentifier, *changes: ViewChange) -> View:
-        raise UnsupportedOperationException("View alteration is not supported")
+        self._check_view_name_identifier(identifier)
+        updates_request = ViewUpdatesRequest(
+            _updates=[self._to_view_update_request(change) for change in changes]
+        )
+        updates_request.validate()
+        full_namespace = self._get_entity_full_namespace(identifier.namespace())
+        resp = self.rest_client.put(
+            f"{self._format_view_request_path(full_namespace)}"
+            f"/{encode_string(identifier.name())}",
+            json=updates_request,
+            error_handler=VIEW_ERROR_HANDLER,
+        )
+        view_resp = ViewResponse.from_json(resp.body, infer_missing=True)
+        view_resp.validate()
+        return GenericView(view_resp.view())
 
     def drop_view(self, identifier: NameIdentifier) -> bool:
         self._check_view_name_identifier(identifier)
@@ -397,3 +442,31 @@ class RelationalCatalog(
         drop_resp = DropResponse.from_json(resp.body, infer_missing=True)
         drop_resp.validate()
         return drop_resp.dropped()
+
+    @staticmethod
+    def _to_view_update_request(change: ViewChange) -> ViewUpdateRequestBase:
+        if isinstance(change, RenameView):
+            return ViewUpdateRequest.RenameViewRequest(_new_name=change.new_name())
+
+        if isinstance(change, SetProperty):
+            return ViewUpdateRequest.SetViewPropertyRequest(
+                _property=change.property(), _value=change.value()
+            )
+
+        if isinstance(change, RemoveProperty):
+            return ViewUpdateRequest.RemoveViewPropertyRequest(
+                _property=change.property()
+            )
+
+        if isinstance(change, ReplaceView):
+            return ViewUpdateRequest.ReplaceViewRequest(
+                _columns=DTOConverters.to_dtos(change.columns()),
+                _representations=DTOConverters.to_dtos(change.representations()),
+                _default_catalog=change.default_catalog(),
+                _default_schema=change.default_schema(),
+                _comment=change.comment(),
+            )
+
+        raise IllegalArgumentException(
+            f"Unknown change type: {change.__class__.__name__}"
+        )
diff --git a/clients/client-python/gravitino/dto/requests/view_update_request.py b/clients/client-python/gravitino/dto/requests/view_update_request.py
new file mode 100644
index 0000000000..81d747384c
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/view_update_request.py
@@ -0,0 +1,166 @@
+# 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 dataclasses import dataclass, field
+from typing import Optional
+
+from dataclasses_json import config, dataclass_json
+
+from gravitino.api.rel.view_change import ViewChange
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.json_serdes.representation_serdes import RepresentationSerdes
+from gravitino.dto.rel.representation_dto import RepresentationDTO
+from gravitino.dto.requests.view_create_request import ViewCreateRequest
+from gravitino.dto.util.dto_converters import DTOConverters
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass_json
+@dataclass
+class ViewUpdateRequestBase(RESTRequest, ABC):
+    """Base class for all view update requests."""
+
+    _type: str = field(init=False, metadata=config(field_name="@type"))
+
+    @abstractmethod
+    def view_change(self) -> ViewChange:
+        """Convert to view change operation."""
+
+
+class ViewUpdateRequest:
+    """Namespace for all view update request types."""
+
+    @dataclass_json
+    @dataclass
+    class RenameViewRequest(ViewUpdateRequestBase):
+        """Update request to rename a view."""
+
+        _new_name: str = field(metadata=config(field_name="newName"))
+
+        def __post_init__(self):
+            self._type = "rename"
+
+        def validate(self):
+            Precondition.check_string_not_empty(
+                self._new_name, '"newName" field is required and cannot be empty'
+            )
+
+        def view_change(self) -> ViewChange:
+            return ViewChange.rename(self._new_name)
+
+    @dataclass_json
+    @dataclass
+    class SetViewPropertyRequest(ViewUpdateRequestBase):
+        """Update request to set a view property."""
+
+        _property: str = field(metadata=config(field_name="property"))
+        _value: str = field(metadata=config(field_name="value"))
+
+        def __post_init__(self):
+            self._type = "setProperty"
+
+        def validate(self):
+            Precondition.check_string_not_empty(
+                self._property, '"property" field is required and cannot be empty'
+            )
+            Precondition.check_argument(
+                self._value is not None, '"value" field is required and cannot be null'
+            )
+
+        def view_change(self) -> ViewChange:
+            return ViewChange.set_property(self._property, self._value)
+
+    @dataclass_json
+    @dataclass
+    class RemoveViewPropertyRequest(ViewUpdateRequestBase):
+        """Update request to remove a view property."""
+
+        _property: str = field(metadata=config(field_name="property"))
+
+        def __post_init__(self):
+            self._type = "removeProperty"
+
+        def validate(self):
+            Precondition.check_string_not_empty(
+                self._property, '"property" field is required and cannot be empty'
+            )
+
+        def view_change(self) -> ViewChange:
+            return ViewChange.remove_property(self._property)
+
+    @dataclass_json
+    @dataclass
+    class ReplaceViewRequest(ViewUpdateRequestBase):
+        """Update request to replace the view body."""
+
+        _columns: Optional[list[ColumnDTO]] = field(
+            default=None, metadata=config(field_name="columns")
+        )
+        _representations: Optional[list[RepresentationDTO]] = field(
+            default=None,
+            metadata=config(
+                field_name="representations",
+                encoder=lambda items: [
+                    RepresentationSerdes.serialize(item) for item in items
+                ],
+                decoder=lambda values: [
+                    RepresentationSerdes.deserialize(value) for value in values
+                ],
+                exclude=lambda value: value is None,
+            ),
+        )
+        _default_catalog: Optional[str] = field(
+            default=None, metadata=config(field_name="defaultCatalog")
+        )
+        _default_schema: Optional[str] = field(
+            default=None, metadata=config(field_name="defaultSchema")
+        )
+        _comment: Optional[str] = field(
+            default=None, metadata=config(field_name="comment")
+        )
+
+        def __post_init__(self):
+            self._type = "replaceView"
+
+        def validate(self):
+            Precondition.check_argument(
+                self._representations is not None and len(self._representations) > 0,
+                '"representations" field is required and cannot be empty',
+            )
+            for representation in self._representations:
+                Precondition.check_argument(
+                    representation is not None, "representation must not be null"
+                )
+                representation.validate()
+            if self._columns:
+                for column in self._columns:
+                    Precondition.check_argument(
+                        column is not None, "column must not be null"
+                    )
+                    column.validate()
+            ViewCreateRequest.validate_no_duplicate_dialects(self._representations)
+
+        def view_change(self) -> ViewChange:
+            return ViewChange.replace_view(
+                self._columns or [],
+                DTOConverters.from_dtos(self._representations),
+                self._default_catalog,
+                self._default_schema,
+                self._comment,
+            )
diff --git a/clients/client-python/gravitino/dto/requests/view_updates_request.py b/clients/client-python/gravitino/dto/requests/view_updates_request.py
new file mode 100644
index 0000000000..5c026f73b9
--- /dev/null
+++ b/clients/client-python/gravitino/dto/requests/view_updates_request.py
@@ -0,0 +1,38 @@
+# 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 dataclasses import dataclass, field
+
+from dataclasses_json import config
+
+from gravitino.dto.requests.view_update_request import ViewUpdateRequestBase
+from gravitino.rest.rest_message import RESTRequest
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass
+class ViewUpdatesRequest(RESTRequest):
+    """Represents a request to update a view with multiple changes."""
+
+    _updates: list[ViewUpdateRequestBase] = field(metadata=config(field_name="updates"))
+
+    def validate(self):
+        Precondition.check_argument(self._updates is not None, "updates cannot be null")
+        Precondition.check_argument(len(self._updates) > 0, "updates cannot be empty")
+        for update in self._updates:
+            Precondition.check_argument(update is not None, "update cannot be null")
+            update.validate()
diff --git a/clients/client-python/tests/integration/test_relational_catalog.py b/clients/client-python/tests/integration/test_relational_catalog.py
index 1723025514..a9f02e5235 100644
--- a/clients/client-python/tests/integration/test_relational_catalog.py
+++ b/clients/client-python/tests/integration/test_relational_catalog.py
@@ -35,10 +35,12 @@ from gravitino.api.rel.table import Table
 from gravitino.api.rel.table_change import TableChange
 from gravitino.api.rel.types.types import Types
 from gravitino.api.rel.view import View
+from gravitino.api.rel.view_change import ViewChange
 from gravitino.client.relational_table import RelationalTable
 from gravitino.exceptions.base import (
     NoSuchSchemaException,
     NoSuchTableException,
+    NoSuchViewException,
     TableAlreadyExistsException,
     ViewAlreadyExistsException,
 )
@@ -382,6 +384,61 @@ class TestRelationalCatalog(IntegrationTestEnv):
                 ],
             )
 
+    def test_relational_catalog_list_views(self):
+        """Test listing views in the relational catalog."""
+        self._create_test_table()
+        self._create_test_view()
+        view_catalog = self.catalog.as_view_catalog()
+
+        view_identifiers = view_catalog.list_views(
+            Namespace.of(TestRelationalCatalog.SCHEMA_NAME)
+        )
+        self.assertEqual(len(view_identifiers), 1)
+        self.assertEqual(view_identifiers[0], self.view_ident)
+
+    def test_relational_catalog_list_views_invalid_namespace(self):
+        """Test listing views with invalid namespace."""
+        view_catalog = self.catalog.as_view_catalog()
+        invalid_namespace = NameIdentifier.of(
+            "non_existent_schema", "dummy"
+        ).namespace()
+
+        with self.assertRaises(NoSuchSchemaException):
+            view_catalog.list_views(namespace=invalid_namespace)
+
+    def test_relational_catalog_load_view(self):
+        """Test loading a view from the relational catalog."""
+        self._create_test_table()
+        self._create_test_view()
+        view_catalog = self.catalog.as_view_catalog()
+
+        view = view_catalog.load_view(identifier=self.view_ident)
+        self.assertEqual(view.name(), self.view_name)
+        self.assertEqual(view.comment(), TestRelationalCatalog.VIEW_COMMENT)
+
+    def test_relational_catalog_load_view_not_exists(self):
+        """Test loading a view that doesn't exist should raise exception."""
+        view_catalog = self.catalog.as_view_catalog()
+        non_existent_view = NameIdentifier.of(
+            TestRelationalCatalog.SCHEMA_NAME, "non_existent_view"
+        )
+
+        with self.assertRaises(NoSuchViewException):
+            view_catalog.load_view(identifier=non_existent_view)
+
+    def test_relational_catalog_view_exists(self):
+        """Test checking if a view exists."""
+        self._create_test_table()
+        view_catalog = self.catalog.as_view_catalog()
+
+        self.assertFalse(view_catalog.view_exists(identifier=self.view_ident))
+
+        self._create_test_view()
+
+        self.assertTrue(view_catalog.view_exists(identifier=self.view_ident))
+        view_catalog.drop_view(self.view_ident)
+        self.assertFalse(view_catalog.view_exists(self.view_ident))
+
     def test_relational_catalog_drop_view(self):
         """Test dropping a view from the relational catalog."""
         self._create_test_table()
@@ -397,3 +454,31 @@ class TestRelationalCatalog(IntegrationTestEnv):
 
         is_dropped = view_catalog.drop_view(self.view_ident)
         self.assertFalse(is_dropped)
+
+    def test_relational_catalog_alter_view(self):
+        """Test altering a view from the relational catalog."""
+        self._create_test_table()
+        self._create_test_view()
+        view_catalog = self.catalog.as_view_catalog()
+
+        new_property_value = "new_property_value"
+        changes = [
+            ViewChange.set_property("view_property1", new_property_value),
+            ViewChange.remove_property("view_property2"),
+        ]
+
+        altered_view = view_catalog.alter_view(self.view_ident, *changes)
+
+        self.assertEqual(
+            altered_view.properties().get("view_property1"),
+            new_property_value,
+        )
+        self.assertNotIn("view_property2", altered_view.properties())
+
+    def test_relational_catalog_alter_view_not_exists(self):
+        """Test altering a view that doesn't exist should raise NoSuchViewException."""
+        view_catalog = self.catalog.as_view_catalog()
+        ident = NameIdentifier.of(TestRelationalCatalog.SCHEMA_NAME, "invalid_view")
+
+        with self.assertRaises(NoSuchViewException):
+            view_catalog.alter_view(ident, ViewChange.set_property("property", "value"))
diff --git a/clients/client-python/tests/unittests/dto/requests/test_view_update_request.py b/clients/client-python/tests/unittests/dto/requests/test_view_update_request.py
new file mode 100644
index 0000000000..fa2f8eea70
--- /dev/null
+++ b/clients/client-python/tests/unittests/dto/requests/test_view_update_request.py
@@ -0,0 +1,197 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.rel.types.types import Types
+from gravitino.dto.rel.column_dto import ColumnDTO
+from gravitino.dto.rel.sql_representation_dto import SQLRepresentationDTO
+from gravitino.dto.requests.view_update_request import ViewUpdateRequest
+from gravitino.dto.requests.view_updates_request import ViewUpdatesRequest
+
+
+class TestViewUpdateRequest(unittest.TestCase):
+    @staticmethod
+    def _column() -> ColumnDTO:
+        return ColumnDTO(
+            _name="id",
+            _data_type=Types.IntegerType.get(),
+            _nullable=False,
+        )
+
+    @staticmethod
+    def _representation(
+        dialect: str = Dialects.TRINO, sql: str = "SELECT id FROM table"
+    ) -> SQLRepresentationDTO:
+        return SQLRepresentationDTO(_dialect=dialect, _sql=sql)
+
+    def test_rename_view_request(self):
+        request = ViewUpdateRequest.RenameViewRequest(_new_name="new_view")
+
+        request.validate()
+        json_str = request.to_json()
+        deserialized = ViewUpdateRequest.RenameViewRequest.from_json(json_str)
+        deserialized.validate()
+
+        self.assertEqual(request, deserialized)
+        self.assertIn('"@type": "rename"', json_str)
+        self.assertEqual("new_view", deserialized.view_change().new_name())
+
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.RenameViewRequest(_new_name="").validate()
+
+    def test_set_view_property_request(self):
+        request = ViewUpdateRequest.SetViewPropertyRequest(
+            _property="key", _value="value"
+        )
+
+        request.validate()
+        json_str = request.to_json()
+        deserialized = ViewUpdateRequest.SetViewPropertyRequest.from_json(json_str)
+        deserialized.validate()
+
+        self.assertEqual(request, deserialized)
+        self.assertIn('"@type": "setProperty"', json_str)
+        self.assertEqual("key", deserialized.view_change().property())
+        self.assertEqual("value", deserialized.view_change().value())
+
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.SetViewPropertyRequest(
+                _property="", _value="value"
+            ).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.SetViewPropertyRequest(
+                _property="key", _value=None
+            ).validate()
+
+    def test_remove_view_property_request(self):
+        request = ViewUpdateRequest.RemoveViewPropertyRequest(_property="key")
+
+        request.validate()
+        json_str = request.to_json()
+        deserialized = ViewUpdateRequest.RemoveViewPropertyRequest.from_json(json_str)
+        deserialized.validate()
+
+        self.assertEqual(request, deserialized)
+        self.assertIn('"@type": "removeProperty"', json_str)
+        self.assertEqual("key", deserialized.view_change().property())
+
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.RemoveViewPropertyRequest(_property="").validate()
+
+    def test_replace_view_request(self):
+        request = ViewUpdateRequest.ReplaceViewRequest(
+            _columns=[self._column()],
+            _representations=[self._representation()],
+            _default_catalog="catalog",
+            _default_schema="schema",
+            _comment="comment",
+        )
+
+        request.validate()
+        json_str = request.to_json()
+        deserialized = ViewUpdateRequest.ReplaceViewRequest.from_json(json_str)
+        deserialized.validate()
+        change = deserialized.view_change()
+
+        self.assertEqual(request, deserialized)
+        self.assertIn('"@type": "replaceView"', json_str)
+        self.assertIn('"representations"', json_str)
+        self.assertEqual("catalog", change.default_catalog())
+        self.assertEqual("schema", change.default_schema())
+        self.assertEqual("comment", change.comment())
+        self.assertEqual(1, len(change.columns()))
+        self.assertEqual(1, len(change.representations()))
+        self.assertIsInstance(change.representations()[0], SQLRepresentation)
+        self.assertEqual(Dialects.TRINO, change.representations()[0].dialect())
+        self.assertEqual("SELECT id FROM table", change.representations()[0].sql())
+
+    def test_replace_view_request_defaults_empty_columns(self):
+        request = ViewUpdateRequest.ReplaceViewRequest(
+            _representations=[self._representation()]
+        )
+
+        request.validate()
+        self.assertEqual([], request.view_change().columns())
+
+    def test_replace_view_request_excludes_missing_representations(self):
+        request = ViewUpdateRequest.ReplaceViewRequest()
+
+        self.assertNotIn('"representations"', request.to_json())
+
+    def test_replace_view_request_validate(self):
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(_representations=[]).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(_representations=[None]).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(
+                _representations=[self._representation("", "SELECT 1")]
+            ).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(
+                _columns=[None], _representations=[self._representation()]
+            ).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(
+                _columns=[ColumnDTO(_name="", _data_type=Types.IntegerType.get())],
+                _representations=[self._representation()],
+            ).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdateRequest.ReplaceViewRequest(
+                _representations=[
+                    self._representation(Dialects.TRINO, "SELECT 1"),
+                    self._representation(Dialects.TRINO, "SELECT 2"),
+                ]
+            ).validate()
+
+    def test_view_updates_request(self):
+        updates = ViewUpdatesRequest(
+            _updates=[
+                ViewUpdateRequest.RenameViewRequest(_new_name="new_view"),
+                ViewUpdateRequest.SetViewPropertyRequest(
+                    _property="key", _value="value"
+                ),
+                ViewUpdateRequest.RemoveViewPropertyRequest(_property="key"),
+                ViewUpdateRequest.ReplaceViewRequest(
+                    _representations=[self._representation()]
+                ),
+            ]
+        )
+
+        updates.validate()
+        json_str = updates.to_json()
+
+        self.assertIn('"updates"', json_str)
+        self.assertIn('"@type": "rename"', json_str)
+        self.assertIn('"@type": "setProperty"', json_str)
+        self.assertIn('"@type": "removeProperty"', json_str)
+        self.assertIn('"@type": "replaceView"', json_str)
+
+    def test_view_updates_request_validate(self):
+        with self.assertRaises(ValueError):
+            ViewUpdatesRequest(_updates=None).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdatesRequest(_updates=[]).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdatesRequest(_updates=[None]).validate()
+        with self.assertRaises(ValueError):
+            ViewUpdatesRequest(
+                _updates=[ViewUpdateRequest.RenameViewRequest(_new_name="")]
+            ).validate()
diff --git a/clients/client-python/tests/unittests/test_relational_catalog.py b/clients/client-python/tests/unittests/test_relational_catalog.py
index 5cfe5528b7..6058e4226e 100644
--- a/clients/client-python/tests/unittests/test_relational_catalog.py
+++ b/clients/client-python/tests/unittests/test_relational_catalog.py
@@ -25,6 +25,7 @@ from gravitino.api.rel.dialects import Dialects
 from gravitino.api.rel.sql_representation import SQLRepresentation
 from gravitino.api.rel.table_change import TableChange
 from gravitino.api.rel.types.types import Types
+from gravitino.api.rel.view_change import ViewChange
 from gravitino.client.relational_catalog import RelationalCatalog
 from gravitino.dto.audit_dto import AuditDTO
 from gravitino.dto.rel.column_dto import ColumnDTO
@@ -32,14 +33,17 @@ from gravitino.dto.rel.distribution_dto import DistributionDTO
 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.dto.requests.view_update_request import ViewUpdateRequest
 from gravitino.dto.responses.drop_response import DropResponse
 from gravitino.dto.responses.entity_list_response import EntityListResponse
 from gravitino.dto.responses.table_response import TableResponse
 from gravitino.dto.responses.view_response import ViewResponse
 from gravitino.dto.util.dto_converters import DTOConverters
 from gravitino.exceptions.base import (
+    IllegalArgumentException,
     NoSuchSchemaException,
     NoSuchTableException,
+    NoSuchViewException,
     TableAlreadyExistsException,
     ViewAlreadyExistsException,
 )
@@ -492,6 +496,64 @@ class TestRelationalCatalog(unittest.TestCase):
             )
             self.assertEqual(table.name(), self.table_dto.name())
 
+    def test_list_views(self):
+        view1 = NameIdentifier.of(
+            self.metalake_name, self.catalog_name, self.schema_name, "view1"
+        )
+        view2 = NameIdentifier.of(
+            self.metalake_name, self.catalog_name, self.schema_name, "view2"
+        )
+
+        resp_body = EntityListResponse(0, [view1, view2])
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.get",
+            return_value=mock_resp,
+        ):
+            views = self.catalog.as_view_catalog().list_views(
+                Namespace.of(self.schema_name)
+            )
+            self.assertEqual(2, len(views))
+            self.assertEqual("view1", views[0].name())
+            self.assertEqual("view2", views[1].name())
+
+    def test_list_views_invalid_namespace(self):
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.get",
+            side_effect=NoSuchSchemaException("Schema not found"),
+        ):
+            with self.assertRaises(NoSuchSchemaException):
+                self.catalog.as_view_catalog().list_views(
+                    Namespace.of("invalid_schema")
+                )
+
+    def test_load_view(self):
+        resp_body = ViewResponse(0, self.view_dto)
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.get",
+            return_value=mock_resp,
+        ):
+            view = self.catalog.as_view_catalog().load_view(self.view_identifier)
+            self.assertEqual(self.view_name, view.name())
+            self.assertEqual("test view comment", view.comment())
+            self.assertEqual("test_catalog", view.default_catalog())
+            self.assertEqual("test_schema", view.default_schema())
+            self.assertEqual("v1", view.properties()["k1"])
+            self.assertEqual(
+                "SELECT id FROM test_table", view.sql_for(Dialects.TRINO).sql()
+            )
+
+    def test_load_view_not_exists(self):
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.get",
+            side_effect=NoSuchViewException("View not found"),
+        ):
+            with self.assertRaises(NoSuchViewException):
+                self.catalog.as_view_catalog().load_view(self.view_identifier)
+
     def test_create_view(self):
         resp_body = ViewResponse(0, self.view_dto)
         mock_resp = self._get_mock_http_resp(resp_body.to_json())
@@ -524,6 +586,55 @@ class TestRelationalCatalog(unittest.TestCase):
                     [SQLRepresentation(Dialects.TRINO, "SELECT id FROM test_table")],
                 )
 
+    def test_alter_view(self):
+        updated_view_dto = ViewDTO(
+            _name="new_view",
+            _columns=[
+                ColumnDTO(
+                    _name="id",
+                    _data_type=Types.IntegerType.get(),
+                    _comment="id column",
+                    _nullable=False,
+                )
+            ],
+            _representations=[
+                SQLRepresentationDTO(
+                    _dialect=Dialects.TRINO,
+                    _sql="SELECT id FROM test_table",
+                )
+            ],
+            _comment="test view comment",
+            _default_catalog="test_catalog",
+            _default_schema="test_schema",
+            _properties={"k1": "v1"},
+            _audit=AuditDTO(
+                "creator", "2022-01-01T00:00:00Z", "modifier", "2022-01-01T00:00:00Z"
+            ),
+        )
+        resp_body = ViewResponse(0, updated_view_dto)
+        mock_resp = self._get_mock_http_resp(resp_body.to_json())
+
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.put",
+            return_value=mock_resp,
+        ):
+            view = self.catalog.as_view_catalog().alter_view(
+                self.view_identifier,
+                ViewChange.rename("new_view"),
+            )
+            self.assertEqual("new_view", view.name())
+
+    def test_alter_view_not_exists(self):
+        with patch(
+            "gravitino.utils.http_client.HTTPClient.put",
+            side_effect=NoSuchViewException("View not found"),
+        ):
+            with self.assertRaises(NoSuchViewException):
+                self.catalog.as_view_catalog().alter_view(
+                    self.view_identifier,
+                    ViewChange.rename("new_view"),
+                )
+
     def test_drop_view(self):
         resp_body = DropResponse(0, True)
         mock_resp = self._get_mock_http_resp(resp_body.to_json())
@@ -545,3 +656,50 @@ class TestRelationalCatalog(unittest.TestCase):
         ):
             is_dropped = self.catalog.as_view_catalog().drop_view(self.view_identifier)
             self.assertFalse(is_dropped)
+
+    def test_to_view_update_request(self):
+        to_request = (
+            RelationalCatalog._to_view_update_request  # pylint: disable=protected-access
+        )
+
+        rename_request = to_request(ViewChange.rename("new_view"))
+        set_property_request = to_request(ViewChange.set_property("key", "value"))
+        remove_property_request = to_request(ViewChange.remove_property("key"))
+        replace_view_request = to_request(
+            ViewChange.replace_view(
+                [Column.of("id", Types.IntegerType.get())],
+                [SQLRepresentation(Dialects.TRINO, "SELECT id FROM table")],
+                "catalog",
+                "schema",
+                "comment",
+            )
+        )
+
+        self.assertIsInstance(rename_request, ViewUpdateRequest.RenameViewRequest)
+        self.assertEqual("new_view", rename_request.view_change().new_name())
+        self.assertIsInstance(
+            set_property_request, ViewUpdateRequest.SetViewPropertyRequest
+        )
+        self.assertEqual("key", set_property_request.view_change().property())
+        self.assertEqual("value", set_property_request.view_change().value())
+        self.assertIsInstance(
+            remove_property_request, ViewUpdateRequest.RemoveViewPropertyRequest
+        )
+        self.assertEqual("key", remove_property_request.view_change().property())
+        self.assertIsInstance(
+            replace_view_request, ViewUpdateRequest.ReplaceViewRequest
+        )
+        self.assertEqual(
+            "catalog", replace_view_request.view_change().default_catalog()
+        )
+        self.assertEqual("schema", replace_view_request.view_change().default_schema())
+        self.assertEqual("comment", replace_view_request.view_change().comment())
+
+    def test_to_view_update_request_unsupported_change(self):
+        class UnsupportedViewChange(ViewChange):
+            pass
+
+        with self.assertRaisesRegex(IllegalArgumentException, "Unknown change type"):
+            RelationalCatalog._to_view_update_request(  # pylint: disable=protected-access
+                UnsupportedViewChange()
+            )


(gravitino) 02/07: [#11902] feat(client-java): Support tags for views and functions (#11903)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 666b3b01d4222ac29762578d80c51fb2ebc05e59
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Tue Jul 14 14:24:28 2026 +0800

    [#11902] feat(client-java): Support tags for views and functions (#11903)
    
    This PR adds Java client support for tag operations on views and
    functions.
    
    Changes include:
    
    - Add default `supportsTags()` methods to the `View` and `Function` API
    interfaces.
    - Add `GenericView` and `GenericFunction` client wrappers backed by
    `MetadataObjectTagOperations`.
    - Return tag-capable wrappers from Java client view and function
    operations.
    - Add Java client tests for view/function tag support.
    
    metadata objects. The Java client should expose the same capability so
    users can manage tags for views and functions through the typed client
    API, consistent with other tag-capable metadata objects.
    
    Fix: #11902
    Related: #11844
    
    Yes.
    
    Java client users can now call `supportsTags()` on `View` and `Function`
    objects returned by the client, for example:
    
    ```java
    view.supportsTags().associateTags(...);
    function.supportsTags().listTags();
    ```
    
    - `./gradlew :clients:client-java:test -PskipITs`
    
    ---------
    
    Co-authored-by: Jerry Shao <je...@datastrato.com>
    (cherry picked from commit e71af9ca988f70b0f11c76c4bbc5416343ddcbb5)
---
 .../org/apache/gravitino/function/Function.java    |   9 +
 .../main/java/org/apache/gravitino/rel/View.java   |   9 +
 .../client/FunctionCatalogOperations.java          |  10 +-
 .../apache/gravitino/client/GenericFunction.java   | 131 ++++++++++++
 .../org/apache/gravitino/client/GenericView.java   | 141 +++++++++++++
 .../apache/gravitino/client/RelationalCatalog.java |   6 +-
 .../gravitino/client/TestFunctionCatalog.java      |  46 +++++
 .../apache/gravitino/client/TestSupportTags.java   | 107 ++++++++++
 .../gravitino/client/integration/test/TagIT.java   | 227 +++++++++++++++++++++
 9 files changed, 679 insertions(+), 7 deletions(-)

diff --git a/api/src/main/java/org/apache/gravitino/function/Function.java b/api/src/main/java/org/apache/gravitino/function/Function.java
index a55c9eab69..536c520d12 100644
--- a/api/src/main/java/org/apache/gravitino/function/Function.java
+++ b/api/src/main/java/org/apache/gravitino/function/Function.java
@@ -22,6 +22,7 @@ import javax.annotation.Nullable;
 import org.apache.gravitino.Auditable;
 import org.apache.gravitino.Namespace;
 import org.apache.gravitino.annotation.Evolving;
+import org.apache.gravitino.tag.SupportsTags;
 
 /**
  * An interface representing a user-defined function under a schema {@link Namespace}. A function is
@@ -65,4 +66,12 @@ public interface Function extends Auditable {
    * @return The definitions of the function.
    */
   FunctionDefinition[] definitions();
+
+  /**
+   * @return The {@link SupportsTags} if the function supports tag operations.
+   * @throws UnsupportedOperationException If the function does not support tag operations.
+   */
+  default SupportsTags supportsTags() {
+    throw new UnsupportedOperationException("Function does not support tag operations.");
+  }
 }
diff --git a/api/src/main/java/org/apache/gravitino/rel/View.java b/api/src/main/java/org/apache/gravitino/rel/View.java
index c4bf41440d..5b6d91a431 100644
--- a/api/src/main/java/org/apache/gravitino/rel/View.java
+++ b/api/src/main/java/org/apache/gravitino/rel/View.java
@@ -25,6 +25,7 @@ import javax.annotation.Nullable;
 import org.apache.gravitino.Auditable;
 import org.apache.gravitino.Namespace;
 import org.apache.gravitino.annotation.Unstable;
+import org.apache.gravitino.tag.SupportsTags;
 
 /**
  * An interface representing a logical view in a {@link Namespace}. A view is a named query whose
@@ -123,4 +124,12 @@ public interface View extends Auditable {
   default Map<String, String> properties() {
     return Collections.emptyMap();
   }
+
+  /**
+   * @return The {@link SupportsTags} if the view supports tag operations.
+   * @throws UnsupportedOperationException If the view does not support tag operations.
+   */
+  default SupportsTags supportsTags() {
+    throw new UnsupportedOperationException("View does not support tag operations.");
+  }
 }
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/FunctionCatalogOperations.java b/clients/client-java/src/main/java/org/apache/gravitino/client/FunctionCatalogOperations.java
index b7dc36d1ed..d8d8b6381e 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/FunctionCatalogOperations.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/FunctionCatalogOperations.java
@@ -110,7 +110,9 @@ class FunctionCatalogOperations implements FunctionCatalog {
             Collections.emptyMap(),
             ErrorHandlers.functionErrorHandler());
     resp.validate();
-    return resp.getFunctions();
+    return Arrays.stream(resp.getFunctions())
+        .map(function -> new GenericFunction(function, restClient, fullNamespace))
+        .toArray(Function[]::new);
   }
 
   /**
@@ -134,7 +136,7 @@ class FunctionCatalogOperations implements FunctionCatalog {
             ErrorHandlers.functionErrorHandler());
     resp.validate();
 
-    return resp.getFunction();
+    return new GenericFunction(resp.getFunction(), restClient, fullNamespace);
   }
 
   /**
@@ -180,7 +182,7 @@ class FunctionCatalogOperations implements FunctionCatalog {
             ErrorHandlers.functionErrorHandler());
     resp.validate();
 
-    return resp.getFunction();
+    return new GenericFunction(resp.getFunction(), restClient, fullNamespace);
   }
 
   /**
@@ -214,7 +216,7 @@ class FunctionCatalogOperations implements FunctionCatalog {
             ErrorHandlers.functionErrorHandler());
     resp.validate();
 
-    return resp.getFunction();
+    return new GenericFunction(resp.getFunction(), restClient, fullNamespace);
   }
 
   /**
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFunction.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFunction.java
new file mode 100644
index 0000000000..fd3bcb459b
--- /dev/null
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericFunction.java
@@ -0,0 +1,131 @@
+/*
+ * 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.
+ */
+package org.apache.gravitino.client;
+
+import com.google.common.collect.Lists;
+import java.util.List;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.dto.function.FunctionDTO;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
+import org.apache.gravitino.function.Function;
+import org.apache.gravitino.function.FunctionDefinition;
+import org.apache.gravitino.function.FunctionType;
+import org.apache.gravitino.tag.SupportsTags;
+import org.apache.gravitino.tag.Tag;
+
+/** Represents a generic function. */
+class GenericFunction implements Function, SupportsTags {
+
+  private final FunctionDTO functionDTO;
+
+  private final MetadataObjectTagOperations objectTagOperations;
+
+  GenericFunction(FunctionDTO functionDTO, RESTClient restClient, Namespace functionNs) {
+    this.functionDTO = functionDTO;
+    List<String> functionFullName =
+        Lists.newArrayList(functionNs.level(1), functionNs.level(2), functionDTO.name());
+    MetadataObject functionObject =
+        MetadataObjects.of(functionFullName, MetadataObject.Type.FUNCTION);
+    this.objectTagOperations =
+        new MetadataObjectTagOperations(functionNs.level(0), functionObject, restClient);
+  }
+
+  @Override
+  public Audit auditInfo() {
+    return functionDTO.auditInfo();
+  }
+
+  @Override
+  public String name() {
+    return functionDTO.name();
+  }
+
+  @Override
+  public FunctionType functionType() {
+    return functionDTO.functionType();
+  }
+
+  @Override
+  public boolean deterministic() {
+    return functionDTO.deterministic();
+  }
+
+  @Override
+  public String comment() {
+    return functionDTO.comment();
+  }
+
+  @Override
+  public FunctionDefinition[] definitions() {
+    return functionDTO.definitions();
+  }
+
+  @Override
+  public SupportsTags supportsTags() {
+    return this;
+  }
+
+  @Override
+  public String[] listTags() {
+    return objectTagOperations.listTags();
+  }
+
+  @Override
+  public Tag[] listTagsInfo() {
+    return objectTagOperations.listTagsInfo();
+  }
+
+  @Override
+  public Tag getTag(String name) throws NoSuchTagException {
+    return objectTagOperations.getTag(name);
+  }
+
+  @Override
+  public String[] associateTags(String[] tagsToAdd, String[] tagsToRemove)
+      throws TagAlreadyAssociatedException {
+    return objectTagOperations.associateTags(tagsToAdd, tagsToRemove);
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof GenericFunction)) {
+      return false;
+    }
+
+    GenericFunction that = (GenericFunction) obj;
+    return functionDTO.equals(that.functionDTO);
+  }
+
+  @Override
+  public int hashCode() {
+    return functionDTO.hashCode();
+  }
+
+  @Override
+  public String toString() {
+    return "GenericFunction{" + "functionDTO=" + functionDTO.toString() + '}';
+  }
+}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GenericView.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericView.java
new file mode 100644
index 0000000000..a38228806a
--- /dev/null
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GenericView.java
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+package org.apache.gravitino.client;
+
+import com.google.common.collect.Lists;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.dto.rel.ViewDTO;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Representation;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.tag.SupportsTags;
+import org.apache.gravitino.tag.Tag;
+
+/** Represents a generic view. */
+class GenericView implements View, SupportsTags {
+
+  private final ViewDTO viewDTO;
+
+  private final MetadataObjectTagOperations objectTagOperations;
+
+  GenericView(ViewDTO viewDTO, RESTClient restClient, Namespace viewNs) {
+    this.viewDTO = viewDTO;
+    List<String> viewFullName =
+        Lists.newArrayList(viewNs.level(1), viewNs.level(2), viewDTO.name());
+    MetadataObject viewObject = MetadataObjects.of(viewFullName, MetadataObject.Type.VIEW);
+    this.objectTagOperations =
+        new MetadataObjectTagOperations(viewNs.level(0), viewObject, restClient);
+  }
+
+  @Override
+  public Audit auditInfo() {
+    return viewDTO.auditInfo();
+  }
+
+  @Override
+  public String name() {
+    return viewDTO.name();
+  }
+
+  @Override
+  public String comment() {
+    return viewDTO.comment();
+  }
+
+  @Override
+  public Column[] columns() {
+    return viewDTO.columns();
+  }
+
+  @Override
+  public Representation[] representations() {
+    return viewDTO.representations();
+  }
+
+  @Override
+  public String defaultCatalog() {
+    return viewDTO.defaultCatalog();
+  }
+
+  @Override
+  public String defaultSchema() {
+    return viewDTO.defaultSchema();
+  }
+
+  @Override
+  public Map<String, String> properties() {
+    return viewDTO.properties();
+  }
+
+  @Override
+  public SupportsTags supportsTags() {
+    return this;
+  }
+
+  @Override
+  public String[] listTags() {
+    return objectTagOperations.listTags();
+  }
+
+  @Override
+  public Tag[] listTagsInfo() {
+    return objectTagOperations.listTagsInfo();
+  }
+
+  @Override
+  public Tag getTag(String name) throws NoSuchTagException {
+    return objectTagOperations.getTag(name);
+  }
+
+  @Override
+  public String[] associateTags(String[] tagsToAdd, String[] tagsToRemove)
+      throws TagAlreadyAssociatedException {
+    return objectTagOperations.associateTags(tagsToAdd, tagsToRemove);
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof GenericView)) {
+      return false;
+    }
+
+    GenericView that = (GenericView) obj;
+    return viewDTO.equals(that.viewDTO);
+  }
+
+  @Override
+  public int hashCode() {
+    return viewDTO.hashCode();
+  }
+
+  @Override
+  public String toString() {
+    return "GenericView{" + "viewDTO=" + viewDTO.toString() + '}';
+  }
+}
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java
index c94d3bba2c..1ae0df08b5 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/RelationalCatalog.java
@@ -359,7 +359,7 @@ class RelationalCatalog extends BaseSchemaCatalog
             ErrorHandlers.viewErrorHandler());
     resp.validate();
 
-    return resp.getView();
+    return new GenericView(resp.getView(), restClient, fullNamespace);
   }
 
   /**
@@ -415,7 +415,7 @@ class RelationalCatalog extends BaseSchemaCatalog
             ErrorHandlers.viewErrorHandler());
     resp.validate();
 
-    return resp.getView();
+    return new GenericView(resp.getView(), restClient, fullNamespace);
   }
 
   /**
@@ -449,7 +449,7 @@ class RelationalCatalog extends BaseSchemaCatalog
             ErrorHandlers.viewErrorHandler());
     resp.validate();
 
-    return resp.getView();
+    return new GenericView(resp.getView(), restClient, fullNamespace);
   }
 
   /**
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestFunctionCatalog.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestFunctionCatalog.java
index 8786c98945..c5644c5e1a 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestFunctionCatalog.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestFunctionCatalog.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.dto.responses.CatalogResponse;
 import org.apache.gravitino.dto.responses.DropResponse;
 import org.apache.gravitino.dto.responses.EntityListResponse;
 import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.FunctionListResponse;
 import org.apache.gravitino.dto.responses.FunctionResponse;
 import org.apache.gravitino.exceptions.FunctionAlreadyExistsException;
 import org.apache.gravitino.exceptions.NoSuchFunctionException;
@@ -151,6 +152,51 @@ public class TestFunctionCatalog extends TestBase {
         "internal error");
   }
 
+  @Test
+  public void testListFunctionInfos() throws JsonProcessingException {
+    NameIdentifier func1 = NameIdentifier.of("schema1", "func1");
+    String functionPath =
+        withSlash(formatFunctionRequestPath(Namespace.of(metalakeName, catalogName, "schema1")));
+    FunctionDTO[] mockFunctions =
+        new FunctionDTO[] {
+          mockFunctionDTO("func1", FunctionType.SCALAR, "mock comment1", true),
+          mockFunctionDTO("func2", FunctionType.SCALAR, "mock comment2", true)
+        };
+
+    FunctionListResponse resp = new FunctionListResponse(mockFunctions);
+    buildMockResource(
+        Method.GET, functionPath, ImmutableMap.of("details", "true"), null, resp, SC_OK);
+
+    Function[] functions = catalog.asFunctionCatalog().listFunctionInfos(func1.namespace());
+    Assertions.assertEquals(2, functions.length);
+    assertFunction(mockFunctions[0], functions[0]);
+    assertFunction(mockFunctions[1], functions[1]);
+
+    // Throw schema not found exception
+    ErrorResponse errResp =
+        ErrorResponse.notFound(NoSuchSchemaException.class.getSimpleName(), "schema not found");
+    buildMockResource(
+        Method.GET, functionPath, ImmutableMap.of("details", "true"), null, errResp, SC_NOT_FOUND);
+    Assertions.assertThrows(
+        NoSuchSchemaException.class,
+        () -> catalog.asFunctionCatalog().listFunctionInfos(func1.namespace()),
+        "schema not found");
+
+    // Throw Runtime exception
+    ErrorResponse errResp2 = ErrorResponse.internalError("internal error");
+    buildMockResource(
+        Method.GET,
+        functionPath,
+        ImmutableMap.of("details", "true"),
+        null,
+        errResp2,
+        SC_SERVER_ERROR);
+    Assertions.assertThrows(
+        RuntimeException.class,
+        () -> catalog.asFunctionCatalog().listFunctionInfos(func1.namespace()),
+        "internal error");
+  }
+
   @Test
   public void testGetFunction() throws JsonProcessingException {
     NameIdentifier func = NameIdentifier.of("schema1", "func1");
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java
index 157f69191e..7ee356ebae 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestSupportTags.java
@@ -35,9 +35,13 @@ import org.apache.gravitino.Schema;
 import org.apache.gravitino.dto.AuditDTO;
 import org.apache.gravitino.dto.SchemaDTO;
 import org.apache.gravitino.dto.file.FilesetDTO;
+import org.apache.gravitino.dto.function.FunctionDTO;
+import org.apache.gravitino.dto.function.FunctionDefinitionDTO;
 import org.apache.gravitino.dto.messaging.TopicDTO;
 import org.apache.gravitino.dto.rel.ColumnDTO;
+import org.apache.gravitino.dto.rel.SQLRepresentationDTO;
 import org.apache.gravitino.dto.rel.TableDTO;
+import org.apache.gravitino.dto.rel.ViewDTO;
 import org.apache.gravitino.dto.requests.TagsAssociateRequest;
 import org.apache.gravitino.dto.responses.ErrorResponse;
 import org.apache.gravitino.dto.responses.NameListResponse;
@@ -47,9 +51,13 @@ import org.apache.gravitino.dto.tag.TagDTO;
 import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.exceptions.NotFoundException;
 import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.function.Function;
+import org.apache.gravitino.function.FunctionType;
 import org.apache.gravitino.messaging.Topic;
 import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Dialects;
 import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.View;
 import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.tag.SupportsTags;
 import org.apache.gravitino.tag.Tag;
@@ -78,6 +86,10 @@ public class TestSupportTags extends TestBase {
 
   private static Topic genericTopic;
 
+  private static View genericView;
+
+  private static Function genericFunction;
+
   @BeforeAll
   public static void setUp() throws Exception {
     TestBase.setUp();
@@ -171,6 +183,41 @@ public class TestSupportTags extends TestBase {
                 .build(),
             client.restClient(),
             Namespace.of(METALAKE_NAME, "catalog1", "schema1"));
+
+    genericView =
+        new GenericView(
+            ViewDTO.builder()
+                .withName("view1")
+                .withComment("comment1")
+                .withColumns(new ColumnDTO[0])
+                .withRepresentations(
+                    new SQLRepresentationDTO[] {
+                      SQLRepresentationDTO.builder()
+                          .withDialect(Dialects.TRINO)
+                          .withSql("SELECT 1")
+                          .build()
+                    })
+                .withProperties(Collections.emptyMap())
+                .withAudit(AuditDTO.builder().withCreator("test").build())
+                .build(),
+            client.restClient(),
+            Namespace.of(METALAKE_NAME, "catalog1", "schema1"));
+
+    genericFunction =
+        new GenericFunction(
+            FunctionDTO.builder()
+                .withName("function1")
+                .withFunctionType(FunctionType.SCALAR)
+                .withComment("comment1")
+                .withDeterministic(true)
+                .withDefinitions(
+                    new FunctionDefinitionDTO[] {
+                      FunctionDefinitionDTO.builder().withReturnType(Types.StringType.get()).build()
+                    })
+                .withAudit(AuditDTO.builder().withCreator("test").build())
+                .build(),
+            client.restClient(),
+            Namespace.of(METALAKE_NAME, "catalog1", "schema1"));
   }
 
   @Test
@@ -224,6 +271,21 @@ public class TestSupportTags extends TestBase {
         MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
   }
 
+  @Test
+  public void testListTagsForView() throws JsonProcessingException {
+    testListTags(
+        genericView.supportsTags(),
+        MetadataObjects.of("catalog1.schema1", genericView.name(), MetadataObject.Type.VIEW));
+  }
+
+  @Test
+  public void testListTagsForFunction() throws JsonProcessingException {
+    testListTags(
+        genericFunction.supportsTags(),
+        MetadataObjects.of(
+            "catalog1.schema1", genericFunction.name(), MetadataObject.Type.FUNCTION));
+  }
+
   @Test
   public void testListTagsInfoForCatalog() throws JsonProcessingException {
     testListTagsInfo(
@@ -275,6 +337,21 @@ public class TestSupportTags extends TestBase {
         MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
   }
 
+  @Test
+  public void testListTagsInfoForView() throws JsonProcessingException {
+    testListTagsInfo(
+        genericView.supportsTags(),
+        MetadataObjects.of("catalog1.schema1", genericView.name(), MetadataObject.Type.VIEW));
+  }
+
+  @Test
+  public void testListTagsInfoForFunction() throws JsonProcessingException {
+    testListTagsInfo(
+        genericFunction.supportsTags(),
+        MetadataObjects.of(
+            "catalog1.schema1", genericFunction.name(), MetadataObject.Type.FUNCTION));
+  }
+
   @Test
   public void testGetTagForCatalog() throws JsonProcessingException {
     testGetTag(
@@ -326,6 +403,21 @@ public class TestSupportTags extends TestBase {
         MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
   }
 
+  @Test
+  public void testGetTagForView() throws JsonProcessingException {
+    testGetTag(
+        genericView.supportsTags(),
+        MetadataObjects.of("catalog1.schema1", genericView.name(), MetadataObject.Type.VIEW));
+  }
+
+  @Test
+  public void testGetTagForFunction() throws JsonProcessingException {
+    testGetTag(
+        genericFunction.supportsTags(),
+        MetadataObjects.of(
+            "catalog1.schema1", genericFunction.name(), MetadataObject.Type.FUNCTION));
+  }
+
   @Test
   public void testAssociateTagsForCatalog() throws JsonProcessingException {
     testAssociateTags(
@@ -377,6 +469,21 @@ public class TestSupportTags extends TestBase {
         MetadataObjects.of("catalog1.schema1", genericTopic.name(), MetadataObject.Type.TOPIC));
   }
 
+  @Test
+  public void testAssociateTagsForView() throws JsonProcessingException {
+    testAssociateTags(
+        genericView.supportsTags(),
+        MetadataObjects.of("catalog1.schema1", genericView.name(), MetadataObject.Type.VIEW));
+  }
+
+  @Test
+  public void testAssociateTagsForFunction() throws JsonProcessingException {
+    testAssociateTags(
+        genericFunction.supportsTags(),
+        MetadataObjects.of(
+            "catalog1.schema1", genericFunction.name(), MetadataObject.Type.FUNCTION));
+  }
+
   private void testListTags(SupportsTags supportsTags, MetadataObject metadataObject)
       throws JsonProcessingException {
     String path =
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/TagIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/TagIT.java
index bea92fde3f..ffa59da404 100644
--- a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/TagIT.java
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/TagIT.java
@@ -33,13 +33,24 @@ import org.apache.gravitino.dto.tag.MetadataObjectDTO;
 import org.apache.gravitino.exceptions.NoSuchTagException;
 import org.apache.gravitino.exceptions.TagAlreadyAssociatedException;
 import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.function.Function;
+import org.apache.gravitino.function.FunctionDefinition;
+import org.apache.gravitino.function.FunctionDefinitions;
+import org.apache.gravitino.function.FunctionImpl;
+import org.apache.gravitino.function.FunctionImpls;
+import org.apache.gravitino.function.FunctionParam;
+import org.apache.gravitino.function.FunctionParams;
+import org.apache.gravitino.function.FunctionType;
 import org.apache.gravitino.integration.test.container.ContainerSuite;
 import org.apache.gravitino.integration.test.container.HiveContainer;
 import org.apache.gravitino.integration.test.util.BaseIT;
 import org.apache.gravitino.integration.test.util.GravitinoITUtils;
 import org.apache.gravitino.model.Model;
 import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Dialects;
+import org.apache.gravitino.rel.SQLRepresentation;
 import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.View;
 import org.apache.gravitino.rel.types.Types;
 import org.apache.gravitino.tag.Tag;
 import org.apache.gravitino.tag.TagChange;
@@ -60,6 +71,8 @@ public class TagIT extends BaseIT {
   private static Catalog relationalCatalog;
   private static Schema schema;
   private static Table table;
+  private static View view;
+  private static Function function;
 
   private static Catalog modelCatalog;
   private static Schema modelSchema;
@@ -114,6 +127,51 @@ public class TagIT extends BaseIT {
                 Collections.emptyMap());
     column = Arrays.stream(table.columns()).filter(c -> c.name().equals("col1")).findFirst().get();
 
+    // Create view
+    String viewName = GravitinoITUtils.genRandomName("tag_it_view");
+    Assertions.assertFalse(
+        relationalCatalog.asViewCatalog().viewExists(NameIdentifier.of(schemaName, viewName)));
+    view =
+        relationalCatalog
+            .asViewCatalog()
+            .createView(
+                NameIdentifier.of(schemaName, viewName),
+                "comment",
+                new Column[] {
+                  Column.of("col1", Types.IntegerType.get()),
+                  Column.of("col2", Types.StringType.get())
+                },
+                new SQLRepresentation[] {
+                  SQLRepresentation.builder()
+                      .withDialect(Dialects.HIVE)
+                      .withSql("SELECT col1, col2 FROM " + table.name())
+                      .build()
+                },
+                null,
+                null,
+                Collections.emptyMap());
+
+    // Create function
+    String functionName = GravitinoITUtils.genRandomName("tag_it_function");
+    Assertions.assertFalse(
+        relationalCatalog
+            .asFunctionCatalog()
+            .functionExists(NameIdentifier.of(schemaName, functionName)));
+    FunctionParam param = FunctionParams.of("x", Types.IntegerType.get());
+    FunctionImpl impl = FunctionImpls.ofSql(FunctionImpl.RuntimeType.SPARK, "SELECT x + 1");
+    FunctionDefinition definition =
+        FunctionDefinitions.of(
+            new FunctionParam[] {param}, Types.IntegerType.get(), new FunctionImpl[] {impl});
+    function =
+        relationalCatalog
+            .asFunctionCatalog()
+            .registerFunction(
+                NameIdentifier.of(schemaName, functionName),
+                "comment",
+                FunctionType.SCALAR,
+                true,
+                new FunctionDefinition[] {definition});
+
     // Create model catalog
     String modelCatalogName = GravitinoITUtils.genRandomName("tag_it_model_catalog");
     Assertions.assertFalse(metalake.catalogExists(modelCatalogName));
@@ -140,7 +198,11 @@ public class TagIT extends BaseIT {
 
   @AfterAll
   public void tearDown() {
+    relationalCatalog.asViewCatalog().dropView(NameIdentifier.of(schema.name(), view.name()));
     relationalCatalog.asTableCatalog().dropTable(NameIdentifier.of(schema.name(), table.name()));
+    relationalCatalog
+        .asFunctionCatalog()
+        .dropFunction(NameIdentifier.of(schema.name(), function.name()));
     relationalCatalog.asSchemas().dropSchema(schema.name(), true);
     metalake.dropCatalog(relationalCatalog.name(), true);
 
@@ -164,6 +226,12 @@ public class TagIT extends BaseIT {
 
   @AfterEach
   public void cleanUp() {
+    String[] viewTags = view.supportsTags().listTags();
+    view.supportsTags().associateTags(null, viewTags);
+
+    String[] functionTags = function.supportsTags().listTags();
+    function.supportsTags().associateTags(null, functionTags);
+
     String[] tableTags = table.supportsTags().listTags();
     table.supportsTags().associateTags(null, tableTags);
 
@@ -552,6 +620,82 @@ public class TagIT extends BaseIT {
         MetadataObject.Type.TABLE, tag3.associatedObjects().objects()[0].type());
   }
 
+  @Test
+  public void testAssociateTagsToView() {
+    Tag tag1 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_view_tag1"), "comment1", Collections.emptyMap());
+    Tag tag2 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_view_tag2"), "comment2", Collections.emptyMap());
+    Tag tag3 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_view_tag3"), "comment3", Collections.emptyMap());
+
+    // Associate tags to catalog
+    relationalCatalog.supportsTags().associateTags(new String[] {tag1.name()}, null);
+
+    // Associate tags to schema
+    schema.supportsTags().associateTags(new String[] {tag2.name()}, null);
+
+    // Associate tags to view
+    String[] tags = view.supportsTags().associateTags(new String[] {tag3.name()}, null);
+
+    Assertions.assertEquals(1, tags.length);
+    Assertions.assertEquals(tag3.name(), tags[0]);
+
+    // Test list associated tags for view
+    String[] tags1 = view.supportsTags().listTags();
+    Assertions.assertEquals(3, tags1.length);
+    Set<String> tagNames = Sets.newHashSet(tags1);
+    Assertions.assertTrue(tagNames.contains(tag1.name()));
+    Assertions.assertTrue(tagNames.contains(tag2.name()));
+    Assertions.assertTrue(tagNames.contains(tag3.name()));
+
+    // Test list associated tags with details for view
+    Tag[] tags2 = view.supportsTags().listTagsInfo();
+    Assertions.assertEquals(3, tags2.length);
+
+    Set<Tag> nonInheritedTags =
+        Arrays.stream(tags2).filter(tag -> !tag.inherited().get()).collect(Collectors.toSet());
+    Set<Tag> inheritedTags =
+        Arrays.stream(tags2).filter(tag -> tag.inherited().get()).collect(Collectors.toSet());
+
+    Assertions.assertEquals(1, nonInheritedTags.size());
+    Assertions.assertEquals(2, inheritedTags.size());
+    Assertions.assertTrue(nonInheritedTags.contains(tag3));
+    Assertions.assertTrue(inheritedTags.contains(tag1));
+    Assertions.assertTrue(inheritedTags.contains(tag2));
+
+    // Test get associated tag for view
+    Tag resultTag1 = view.supportsTags().getTag(tag1.name());
+    Assertions.assertEquals(tag1, resultTag1);
+    Assertions.assertTrue(resultTag1.inherited().get());
+
+    Tag resultTag2 = view.supportsTags().getTag(tag2.name());
+    Assertions.assertEquals(tag2, resultTag2);
+    Assertions.assertTrue(resultTag2.inherited().get());
+
+    Tag resultTag3 = view.supportsTags().getTag(tag3.name());
+    Assertions.assertEquals(tag3, resultTag3);
+    Assertions.assertFalse(resultTag3.inherited().get());
+
+    // Test get objects associated with tag
+    Assertions.assertEquals(1, tag1.associatedObjects().count());
+    Assertions.assertEquals(relationalCatalog.name(), tag1.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(
+        MetadataObject.Type.CATALOG, tag1.associatedObjects().objects()[0].type());
+
+    Assertions.assertEquals(1, tag2.associatedObjects().count());
+    Assertions.assertEquals(schema.name(), tag2.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(
+        MetadataObject.Type.SCHEMA, tag2.associatedObjects().objects()[0].type());
+
+    Assertions.assertEquals(1, tag3.associatedObjects().count());
+    Assertions.assertEquals(view.name(), tag3.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(MetadataObject.Type.VIEW, tag3.associatedObjects().objects()[0].type());
+  }
+
   @Test
   public void testAssociateTagsToColumn() {
     Tag tag1 =
@@ -765,4 +909,87 @@ public class TagIT extends BaseIT {
     Assertions.assertEquals(
         MetadataObject.Type.MODEL, tag3.associatedObjects().objects()[0].type());
   }
+
+  @Test
+  public void testAssociateTagsToFunction() {
+    Tag tag1 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_function_tag1"),
+            "comment1",
+            Collections.emptyMap());
+    Tag tag2 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_function_tag2"),
+            "comment2",
+            Collections.emptyMap());
+    Tag tag3 =
+        metalake.createTag(
+            GravitinoITUtils.genRandomName("tag_it_function_tag3"),
+            "comment3",
+            Collections.emptyMap());
+
+    // Associate tags to catalog
+    relationalCatalog.supportsTags().associateTags(new String[] {tag1.name()}, null);
+
+    // Associate tags to schema
+    schema.supportsTags().associateTags(new String[] {tag2.name()}, null);
+
+    // Associate tags to function
+    String[] tags = function.supportsTags().associateTags(new String[] {tag3.name()}, null);
+
+    Assertions.assertEquals(1, tags.length);
+    Assertions.assertEquals(tag3.name(), tags[0]);
+
+    // Test list associated tags for function
+    String[] tags1 = function.supportsTags().listTags();
+    Assertions.assertEquals(3, tags1.length);
+    Set<String> tagNames = Sets.newHashSet(tags1);
+    Assertions.assertTrue(tagNames.contains(tag1.name()));
+    Assertions.assertTrue(tagNames.contains(tag2.name()));
+    Assertions.assertTrue(tagNames.contains(tag3.name()));
+
+    // Test list associated tags with details for function
+    Tag[] tags2 = function.supportsTags().listTagsInfo();
+    Assertions.assertEquals(3, tags2.length);
+
+    Set<Tag> nonInheritedTags =
+        Arrays.stream(tags2).filter(tag -> !tag.inherited().get()).collect(Collectors.toSet());
+    Set<Tag> inheritedTags =
+        Arrays.stream(tags2).filter(tag -> tag.inherited().get()).collect(Collectors.toSet());
+
+    Assertions.assertEquals(1, nonInheritedTags.size());
+    Assertions.assertEquals(2, inheritedTags.size());
+    Assertions.assertTrue(nonInheritedTags.contains(tag3));
+    Assertions.assertTrue(inheritedTags.contains(tag1));
+    Assertions.assertTrue(inheritedTags.contains(tag2));
+
+    // Test get associated tag for function
+    Tag resultTag1 = function.supportsTags().getTag(tag1.name());
+    Assertions.assertEquals(tag1, resultTag1);
+    Assertions.assertTrue(resultTag1.inherited().get());
+
+    Tag resultTag2 = function.supportsTags().getTag(tag2.name());
+    Assertions.assertEquals(tag2, resultTag2);
+    Assertions.assertTrue(resultTag2.inherited().get());
+
+    Tag resultTag3 = function.supportsTags().getTag(tag3.name());
+    Assertions.assertEquals(tag3, resultTag3);
+    Assertions.assertFalse(resultTag3.inherited().get());
+
+    // Test get objects associated with tag
+    Assertions.assertEquals(1, tag1.associatedObjects().count());
+    Assertions.assertEquals(relationalCatalog.name(), tag1.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(
+        MetadataObject.Type.CATALOG, tag1.associatedObjects().objects()[0].type());
+
+    Assertions.assertEquals(1, tag2.associatedObjects().count());
+    Assertions.assertEquals(schema.name(), tag2.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(
+        MetadataObject.Type.SCHEMA, tag2.associatedObjects().objects()[0].type());
+
+    Assertions.assertEquals(1, tag3.associatedObjects().count());
+    Assertions.assertEquals(function.name(), tag3.associatedObjects().objects()[0].name());
+    Assertions.assertEquals(
+        MetadataObject.Type.FUNCTION, tag3.associatedObjects().objects()[0].type());
+  }
 }


(gravitino) 03/07: [#12039] feat(client-python): Add view API definitions (#12040)

Posted by js...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jerryshao pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 071bb7c9d7c1c5fb1c98b3549f4e7adb641a192c
Author: Zhiguo Wu <wz...@gmail.com>
AuthorDate: Fri Jul 17 16:53:52 2026 +0800

    [#12039] feat(client-python): Add view API definitions (#12040)
    
    ### What changes were proposed in this pull request?
    
    This PR adds the public Python API definitions required for view
    support.
    
    The changes include:
    
    - Add `View`, `ViewCatalog`, and `ViewChange`.
    - Add `Representation`, `SQLRepresentation`, and predefined SQL
    dialects.
    - Add `Catalog.as_view_catalog()`.
    - Add view-specific exception types.
    - Add unit tests for view representations and changes.
    
    ### Why are the changes needed?
    
    The Python client currently lacks the public API contracts required to
    represent and manage views.
    
    Fix: #12039
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. It adds public Python API definitions for views.
    
    ### How was this patch tested?
    
    Added unit tests for `View`, `ViewChange`, and `SQLRepresentation`. The
    formatting, lint, and unit test checks passed.
    
    (cherry picked from commit c10925adb789d5f9c1ed9519faad4bcfc46bc15a)
---
 clients/client-python/gravitino/api/catalog.py     |  10 +
 .../client-python/gravitino/api/rel/dialects.py    |  25 +++
 .../gravitino/api/rel/representation.py            |  28 +++
 .../gravitino/api/rel/sql_representation.py        |  47 +++++
 clients/client-python/gravitino/api/rel/view.py    |  68 +++++++
 .../gravitino/api/rel/view_catalog.py              | 149 ++++++++++++++
 .../client-python/gravitino/api/rel/view_change.py | 214 +++++++++++++++++++++
 clients/client-python/gravitino/exceptions/base.py |   8 +
 .../unittests/api/rel/test_sql_representation.py   |  54 ++++++
 .../tests/unittests/api/rel/test_view.py           |  69 +++++++
 .../tests/unittests/api/rel/test_view_change.py    | 150 +++++++++++++++
 11 files changed, 822 insertions(+)

diff --git a/clients/client-python/gravitino/api/catalog.py b/clients/client-python/gravitino/api/catalog.py
index 5e97fe8455..27d6688415 100644
--- a/clients/client-python/gravitino/api/catalog.py
+++ b/clients/client-python/gravitino/api/catalog.py
@@ -158,6 +158,16 @@ class Catalog(Auditable):
         """
         raise UnsupportedOperationException("Catalog does not support table operations")
 
+    def as_view_catalog(self) -> "ViewCatalog":  # noqa: F821
+        """
+        Raises:
+            UnsupportedOperationException if the catalog does not support view operations.
+
+        Returns:
+            the {@link ViewCatalog} if the catalog supports view operations.
+        """
+        raise UnsupportedOperationException("Catalog does not support view operations")
+
     def as_fileset_catalog(self) -> "FilesetCatalog":  # noqa: F821
         """
         Raises:
diff --git a/clients/client-python/gravitino/api/rel/dialects.py b/clients/client-python/gravitino/api/rel/dialects.py
new file mode 100644
index 0000000000..7588a81f09
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/dialects.py
@@ -0,0 +1,25 @@
+# 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.
+
+
+class Dialects:
+    """Predefined SQL dialect identifiers."""
+
+    TRINO = "trino"
+    SPARK = "spark"
+    HIVE = "hive"
+    FLINK = "flink"
diff --git a/clients/client-python/gravitino/api/rel/representation.py b/clients/client-python/gravitino/api/rel/representation.py
new file mode 100644
index 0000000000..1803185a58
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/representation.py
@@ -0,0 +1,28 @@
+# 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
+
+
+class Representation(ABC):
+    """A representation of a view definition."""
+
+    TYPE_SQL = "sql"
+
+    @abstractmethod
+    def type(self) -> str:
+        """Returns the representation type."""
diff --git a/clients/client-python/gravitino/api/rel/sql_representation.py b/clients/client-python/gravitino/api/rel/sql_representation.py
new file mode 100644
index 0000000000..00d5fb8e4a
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/sql_representation.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 dataclasses import dataclass
+
+from gravitino.api.rel.representation import Representation
+from gravitino.utils.precondition import Precondition
+
+
+@dataclass(frozen=True)
+class SQLRepresentation(Representation):
+    """A SQL-based representation of a view definition."""
+
+    _dialect: str
+    _sql: str
+
+    def __post_init__(self):
+        Precondition.check_string_not_empty(
+            self._dialect, "dialect must not be null or empty"
+        )
+        Precondition.check_string_not_empty(self._sql, "sql must not be null or empty")
+
+    def type(self) -> str:
+        """Returns the representation type."""
+        return Representation.TYPE_SQL
+
+    def dialect(self) -> str:
+        """Returns the SQL dialect."""
+        return self._dialect
+
+    def sql(self) -> str:
+        """Returns the SQL text."""
+        return self._sql
diff --git a/clients/client-python/gravitino/api/rel/view.py b/clients/client-python/gravitino/api/rel/view.py
new file mode 100644
index 0000000000..7db72a6750
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/view.py
@@ -0,0 +1,68 @@
+# 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 abstractmethod
+from typing import Optional
+
+from gravitino.api.auditable import Auditable
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.sql_representation import SQLRepresentation
+
+
+class View(Auditable):
+    """An interface representing a logical view in a namespace."""
+
+    @abstractmethod
+    def name(self) -> str:
+        """Returns the view name."""
+
+    def comment(self) -> Optional[str]:
+        """Returns the view comment."""
+        return None
+
+    @abstractmethod
+    def columns(self) -> list[Column]:
+        """Returns the output columns of the view."""
+
+    @abstractmethod
+    def representations(self) -> list[Representation]:
+        """Returns the representations of the view."""
+
+    def default_catalog(self) -> Optional[str]:
+        """Returns the default catalog used to resolve unqualified identifiers."""
+        return None
+
+    def default_schema(self) -> Optional[str]:
+        """Returns the default schema used to resolve unqualified identifiers."""
+        return None
+
+    def sql_for(self, dialect: Optional[str]) -> Optional[SQLRepresentation]:
+        """Returns the SQL representation for the given dialect."""
+        if dialect is None:
+            return None
+        for representation in self.representations():
+            if (
+                isinstance(representation, SQLRepresentation)
+                and representation.dialect().lower() == dialect.lower()
+            ):
+                return representation
+        return None
+
+    def properties(self) -> dict[str, str]:
+        """Returns the view properties."""
+        return {}
diff --git a/clients/client-python/gravitino/api/rel/view_catalog.py b/clients/client-python/gravitino/api/rel/view_catalog.py
new file mode 100644
index 0000000000..39da01e85c
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/view_catalog.py
@@ -0,0 +1,149 @@
+# 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 typing import Optional
+
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.view import View
+from gravitino.api.rel.view_change import ViewChange
+from gravitino.exceptions.base import NoSuchViewException
+from gravitino.name_identifier import NameIdentifier
+from gravitino.namespace import Namespace
+
+
+class ViewCatalog(ABC):
+    """The `ViewCatalog` interface defines the public API for managing views in a schema.
+
+    If the catalog implementation supports views, it must implement this interface.
+    """
+
+    @abstractmethod
+    def list_views(self, namespace: Namespace) -> list[NameIdentifier]:
+        """List the views in a namespace from the catalog.
+
+        Args:
+            namespace (Namespace): A namespace.
+
+        Returns:
+            list[NameIdentifier]: An array of view identifiers in the namespace.
+
+        Raises:
+            NoSuchSchemaException: If the schema does not exist.
+        """
+
+    @abstractmethod
+    def load_view(self, identifier: NameIdentifier) -> View:
+        """Load view metadata by `NameIdentifier` from the catalog.
+
+        Args:
+            identifier (NameIdentifier): A view identifier.
+
+        Returns:
+            View: The view metadata.
+
+        Raises:
+            NoSuchViewException: If the view does not exist.
+        """
+
+    def view_exists(self, identifier: NameIdentifier) -> bool:
+        """Check if a view with the given name exists in the catalog.
+
+        Args:
+            identifier: The view identifier.
+
+        Returns:
+            True if the view exists, False otherwise.
+        """
+        try:
+            self.load_view(identifier)
+            return True
+        except NoSuchViewException:
+            return False
+
+    @abstractmethod
+    def create_view(
+        self,
+        identifier: NameIdentifier,
+        columns: list[Column],
+        representations: list[Representation],
+        comment: Optional[str] = None,
+        default_catalog: Optional[str] = None,
+        default_schema: Optional[str] = None,
+        properties: Optional[dict[str, str]] = None,
+    ) -> View:
+        """Create a view in the catalog.
+
+        Args:
+            identifier (NameIdentifier):
+                A view identifier.
+            columns (list[Column]):
+                The columns of the new view.
+            representations (list[Representation]):
+                The representations of the view. At least one representation is expected.
+            comment (str, optional):
+                The view comment. Defaults to `None`.
+            default_catalog (str, optional):
+                The default catalog name used to resolve unqualified objects in the view.
+                Defaults to `None`.
+            default_schema (str, optional):
+                The default schema name used to resolve unqualified objects in the view.
+                Defaults to `None`.
+            properties (dict[str, str], optional):
+                The view properties. Defaults to `None`.
+
+        Returns:
+            View:
+                The created view metadata.
+
+        Raises:
+            NoSuchSchemaException:
+                If the schema does not exist.
+            ViewAlreadyExistsException:
+                If the view already exists.
+        """
+
+    @abstractmethod
+    def alter_view(self, identifier: NameIdentifier, *changes: ViewChange) -> View:
+        """Alter a view in the catalog.
+
+        Args:
+            identifier (NameIdentifier): A view identifier.
+            *changes:
+                View changes to apply to the view.
+
+        Returns:
+            View: The updated view metadata.
+
+        Raises:
+            NoSuchViewException:
+                If the view does not exist.
+            IllegalArgumentException:
+                If the change is rejected by the implementation.
+        """
+
+    @abstractmethod
+    def drop_view(self, identifier: NameIdentifier) -> bool:
+        """Drop a view from the catalog.
+
+        Args:
+            identifier (NameIdentifier): A view identifier.
+
+        Returns:
+            bool: `True` if the view is dropped, `False` if the view does not exist.
+        """
diff --git a/clients/client-python/gravitino/api/rel/view_change.py b/clients/client-python/gravitino/api/rel/view_change.py
new file mode 100644
index 0000000000..7397b5f9fc
--- /dev/null
+++ b/clients/client-python/gravitino/api/rel/view_change.py
@@ -0,0 +1,214 @@
+# 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
+from dataclasses import dataclass
+from typing import Optional
+
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.representation import Representation
+from gravitino.utils.precondition import Precondition
+
+
+class ViewChange(ABC):
+    """Defines changes that can be applied to a view."""
+
+    @staticmethod
+    def rename(new_name: str) -> "RenameView":
+        """Create a change for renaming a view."""
+        return RenameView(new_name)
+
+    @staticmethod
+    def set_property(property_name: str, value: str) -> "SetProperty":
+        """Create a change for setting a view property."""
+        return SetProperty(property_name, value)
+
+    @staticmethod
+    def remove_property(property_name: str) -> "RemoveProperty":
+        """Create a change for removing a view property."""
+        return RemoveProperty(property_name)
+
+    @staticmethod
+    def replace_view(
+        columns: list[Column],
+        representations: list[Representation],
+        default_catalog: Optional[str] = None,
+        default_schema: Optional[str] = None,
+        comment: Optional[str] = None,
+    ) -> "ReplaceView":
+        """Create a change for replacing the view body."""
+        return ReplaceView(
+            columns, representations, default_catalog, default_schema, comment
+        )
+
+
+@dataclass(frozen=True)
+class RenameView(ViewChange):
+    """A ViewChange to rename a view."""
+
+    _new_name: str
+
+    def __post_init__(self):
+        Precondition.check_string_not_empty(
+            self._new_name, "newName must not be null or empty"
+        )
+
+    def new_name(self) -> str:
+        """Returns the new view name."""
+        return self._new_name
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, RenameView):
+            return False
+        return self._new_name == other.new_name()
+
+    def __hash__(self) -> int:
+        return hash(self._new_name)
+
+    def __str__(self) -> str:
+        return f"RENAMEVIEW {self._new_name}"
+
+
+@dataclass(frozen=True)
+class SetProperty(ViewChange):
+    """A ViewChange to set a view property."""
+
+    _property: str
+    _value: str
+
+    def __post_init__(self):
+        Precondition.check_string_not_empty(
+            self._property, "property must not be null or empty"
+        )
+
+    def property(self) -> str:
+        """Returns the property name."""
+        return self._property
+
+    def value(self) -> str:
+        """Returns the property value."""
+        return self._value
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, SetProperty):
+            return False
+        return self._property == other.property() and self._value == other.value()
+
+    def __hash__(self) -> int:
+        return hash((self._property, self._value))
+
+    def __str__(self) -> str:
+        return f"SETPROPERTY {self._property} {self._value}"
+
+
+@dataclass(frozen=True)
+class RemoveProperty(ViewChange):
+    """A ViewChange to remove a view property."""
+
+    _property: str
+
+    def __post_init__(self):
+        Precondition.check_string_not_empty(
+            self._property, "property must not be null or empty"
+        )
+
+    def property(self) -> str:
+        """Returns the property name."""
+        return self._property
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, RemoveProperty):
+            return False
+        return self._property == other.property()
+
+    def __hash__(self) -> int:
+        return hash(self._property)
+
+    def __str__(self) -> str:
+        return f"REMOVEPROPERTY {self._property}"
+
+
+@dataclass(frozen=True)
+class ReplaceView(ViewChange):
+    """A ViewChange to replace the view body."""
+
+    _columns: list[Column]
+    _representations: list[Representation]
+    _default_catalog: Optional[str] = None
+    _default_schema: Optional[str] = None
+    _comment: Optional[str] = None
+
+    def __post_init__(self):
+        Precondition.check_argument(
+            self._columns is not None, "columns must not be null"
+        )
+        Precondition.check_argument(
+            self._representations is not None and len(self._representations) > 0,
+            "representations must not be null or empty",
+        )
+        object.__setattr__(self, "_columns", list(self._columns))
+        object.__setattr__(self, "_representations", list(self._representations))
+
+    def columns(self) -> list[Column]:
+        """Returns the new output columns."""
+        return list(self._columns)
+
+    def representations(self) -> list[Representation]:
+        """Returns the new representations."""
+        return list(self._representations)
+
+    def default_catalog(self) -> Optional[str]:
+        """Returns the new default catalog."""
+        return self._default_catalog
+
+    def default_schema(self) -> Optional[str]:
+        """Returns the new default schema."""
+        return self._default_schema
+
+    def comment(self) -> Optional[str]:
+        """Returns the new comment."""
+        return self._comment
+
+    def __eq__(self, other: object) -> bool:
+        if not isinstance(other, ReplaceView):
+            return False
+        return (
+            self._columns == other.columns()
+            and self._representations == other.representations()
+            and self._default_catalog == other.default_catalog()
+            and self._default_schema == other.default_schema()
+            and self._comment == other.comment()
+        )
+
+    def __hash__(self) -> int:
+        return hash(
+            (
+                tuple(self._columns),
+                tuple(self._representations),
+                self._default_catalog,
+                self._default_schema,
+                self._comment,
+            )
+        )
+
+    def __str__(self) -> str:
+        return (
+            f"REPLACEVIEW columns={self._columns}, "
+            f"representations={self._representations}, "
+            f"defaultCatalog={self._default_catalog}, "
+            f"defaultSchema={self._default_schema}, comment={self._comment}"
+        )
diff --git a/clients/client-python/gravitino/exceptions/base.py b/clients/client-python/gravitino/exceptions/base.py
index 023f5d490e..b22c59c443 100644
--- a/clients/client-python/gravitino/exceptions/base.py
+++ b/clients/client-python/gravitino/exceptions/base.py
@@ -217,6 +217,10 @@ class NoSuchTableException(NotFoundException):
     """An exception thrown when a table with specified name is not existed."""
 
 
+class NoSuchViewException(NotFoundException):
+    """An exception thrown when a view with specified name is not found."""
+
+
 class NoSuchPartitionException(NotFoundException):
     """An exception thrown when a partition with specified name is not existed."""
 
@@ -229,6 +233,10 @@ class TableAlreadyExistsException(AlreadyExistsException):
     """An exception thrown when a table already exists."""
 
 
+class ViewAlreadyExistsException(AlreadyExistsException):
+    """An exception thrown when a view already exists."""
+
+
 class NoSuchFunctionException(NotFoundException):
     """An exception thrown when a function with specified name is not found."""
 
diff --git a/clients/client-python/tests/unittests/api/rel/test_sql_representation.py b/clients/client-python/tests/unittests/api/rel/test_sql_representation.py
new file mode 100644
index 0000000000..af7c64fb2e
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/rel/test_sql_representation.py
@@ -0,0 +1,54 @@
+# 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 unittest
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.sql_representation import SQLRepresentation
+
+
+class TestSQLRepresentation(unittest.TestCase):
+    def test_predefined_dialects(self):
+        self.assertEqual("trino", Dialects.TRINO)
+        self.assertEqual("spark", Dialects.SPARK)
+        self.assertEqual("hive", Dialects.HIVE)
+        self.assertEqual("flink", Dialects.FLINK)
+
+    def test_sql_representation(self):
+        representation = SQLRepresentation(Dialects.TRINO, "SELECT 1")
+
+        self.assertEqual(Representation.TYPE_SQL, representation.type())
+        self.assertEqual(Dialects.TRINO, representation.dialect())
+        self.assertEqual("SELECT 1", representation.sql())
+
+    def test_sql_representation_equal_and_hash(self):
+        representation = SQLRepresentation(Dialects.TRINO, "SELECT 1")
+        equal_representation = SQLRepresentation(Dialects.TRINO, "SELECT 1")
+
+        self.assertEqual(representation, equal_representation)
+        self.assertEqual(hash(representation), hash(equal_representation))
+        self.assertNotEqual(
+            representation, SQLRepresentation(Dialects.SPARK, "SELECT 1")
+        )
+        self.assertNotEqual(representation, "invalid_representation")
+
+    def test_sql_representation_validation(self):
+        with self.assertRaisesRegex(ValueError, "dialect must not be null or empty"):
+            SQLRepresentation("", "SELECT 1")
+        with self.assertRaisesRegex(ValueError, "sql must not be null or empty"):
+            SQLRepresentation(Dialects.TRINO, "")
diff --git a/clients/client-python/tests/unittests/api/rel/test_view.py b/clients/client-python/tests/unittests/api/rel/test_view.py
new file mode 100644
index 0000000000..19fa1769d7
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/rel/test_view.py
@@ -0,0 +1,69 @@
+# 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 unittest
+from unittest.mock import Mock
+
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.representation import Representation
+from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.rel.view import View
+
+
+class TestView(unittest.TestCase):
+    def test_sql_for_returns_matching_representation(self):
+        trino_representation = SQLRepresentation(Dialects.TRINO, "SELECT 1")
+        spark_representation = SQLRepresentation(Dialects.SPARK, "SELECT 2")
+        view = Mock(spec=View)
+        view.representations.return_value = [
+            trino_representation,
+            spark_representation,
+        ]
+
+        self.assertEqual(
+            trino_representation,
+            View.sql_for(view, Dialects.TRINO.upper()),
+        )
+
+    def test_sql_for_returns_none_when_dialect_is_missing(self):
+        view = Mock(spec=View)
+        view.representations.return_value = [
+            SQLRepresentation(Dialects.SPARK, "SELECT 1")
+        ]
+
+        self.assertIsNone(View.sql_for(view, Dialects.TRINO))
+
+    def test_sql_for_returns_none_when_dialect_is_none(self):
+        view = Mock(spec=View)
+
+        self.assertIsNone(View.sql_for(view, None))
+        view.representations.assert_not_called()
+
+    def test_sql_for_ignores_non_sql_representations(self):
+        representation = Mock(spec=Representation)
+        view = Mock(spec=View)
+        view.representations.return_value = [representation]
+
+        self.assertIsNone(View.sql_for(view, Dialects.TRINO))
+
+    def test_default_values(self):
+        view = Mock(spec=View)
+
+        self.assertIsNone(View.comment(view))
+        self.assertIsNone(View.default_catalog(view))
+        self.assertIsNone(View.default_schema(view))
+        self.assertEqual({}, View.properties(view))
diff --git a/clients/client-python/tests/unittests/api/rel/test_view_change.py b/clients/client-python/tests/unittests/api/rel/test_view_change.py
new file mode 100644
index 0000000000..77eda67ed7
--- /dev/null
+++ b/clients/client-python/tests/unittests/api/rel/test_view_change.py
@@ -0,0 +1,150 @@
+# 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 unittest
+
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.dialects import Dialects
+from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.rel.types.types import Types
+from gravitino.api.rel.view_change import (
+    RemoveProperty,
+    RenameView,
+    ReplaceView,
+    SetProperty,
+    ViewChange,
+)
+
+
+class TestViewChange(unittest.TestCase):
+    def test_rename_view(self):
+        change = ViewChange.rename("new_view")
+        equal_change = ViewChange.rename("new_view")
+
+        self.assertIsInstance(change, RenameView)
+        self.assertEqual("new_view", change.new_name())
+        self.assertEqual("RENAMEVIEW new_view", str(change))
+        self.assertEqual(change, equal_change)
+        self.assertEqual(hash(change), hash(equal_change))
+        self.assertNotEqual(change, ViewChange.rename("another_view"))
+        self.assertNotEqual(change, "invalid_change")
+
+        with self.assertRaisesRegex(ValueError, "newName must not be null or empty"):
+            ViewChange.rename("")
+
+    def test_set_property(self):
+        change = ViewChange.set_property("key", "value")
+        equal_change = ViewChange.set_property("key", "value")
+
+        self.assertIsInstance(change, SetProperty)
+        self.assertEqual("key", change.property())
+        self.assertEqual("value", change.value())
+        self.assertEqual("SETPROPERTY key value", str(change))
+        self.assertEqual(change, equal_change)
+        self.assertEqual(hash(change), hash(equal_change))
+        self.assertNotEqual(change, ViewChange.set_property("key", "another_value"))
+        self.assertNotEqual(change, "invalid_change")
+
+        with self.assertRaisesRegex(ValueError, "property must not be null or empty"):
+            ViewChange.set_property("", "value")
+
+    def test_remove_property(self):
+        change = ViewChange.remove_property("key")
+        equal_change = ViewChange.remove_property("key")
+
+        self.assertIsInstance(change, RemoveProperty)
+        self.assertEqual("key", change.property())
+        self.assertEqual("REMOVEPROPERTY key", str(change))
+        self.assertEqual(change, equal_change)
+        self.assertEqual(hash(change), hash(equal_change))
+        self.assertNotEqual(change, ViewChange.remove_property("another_key"))
+        self.assertNotEqual(change, "invalid_change")
+
+        with self.assertRaisesRegex(ValueError, "property must not be null or empty"):
+            ViewChange.remove_property("")
+
+    def test_replace_view(self):
+        columns = [Column.of("id", Types.IntegerType.get())]
+        representations = [SQLRepresentation(Dialects.TRINO, "SELECT id FROM tbl")]
+        change = ViewChange.replace_view(
+            columns,
+            representations,
+            default_catalog="catalog",
+            default_schema="schema",
+            comment="comment",
+        )
+        equal_change = ViewChange.replace_view(
+            [Column.of("id", Types.IntegerType.get())],
+            [SQLRepresentation(Dialects.TRINO, "SELECT id FROM tbl")],
+            "catalog",
+            "schema",
+            "comment",
+        )
+
+        self.assertIsInstance(change, ReplaceView)
+        self.assertEqual(columns, change.columns())
+        self.assertEqual(representations, change.representations())
+        self.assertEqual("catalog", change.default_catalog())
+        self.assertEqual("schema", change.default_schema())
+        self.assertEqual("comment", change.comment())
+        self.assertEqual(
+            f"REPLACEVIEW columns={columns}, representations={representations}, "
+            "defaultCatalog=catalog, defaultSchema=schema, comment=comment",
+            str(change),
+        )
+        self.assertEqual(change, equal_change)
+        self.assertEqual(hash(change), hash(equal_change))
+        self.assertNotEqual(
+            change,
+            ViewChange.replace_view(
+                columns, representations, "another_catalog", "schema", "comment"
+            ),
+        )
+        self.assertNotEqual(change, "invalid_change")
+
+    def test_replace_view_defensively_copies_lists(self):
+        columns = [Column.of("id", Types.IntegerType.get())]
+        representations = [SQLRepresentation(Dialects.TRINO, "SELECT id FROM tbl")]
+        change = ViewChange.replace_view(columns, representations)
+        original_hash = hash(change)
+
+        columns[0] = Column.of("name", Types.StringType.get())
+        representations[0] = SQLRepresentation(Dialects.SPARK, "SELECT name FROM tbl")
+
+        self.assertEqual("id", change.columns()[0].name())
+        self.assertEqual(Dialects.TRINO, change.representations()[0].dialect())
+
+        returned_columns = change.columns()
+        returned_representations = change.representations()
+        returned_columns[0] = Column.of("age", Types.IntegerType.get())
+        returned_representations[0] = SQLRepresentation(
+            Dialects.HIVE, "SELECT age FROM tbl"
+        )
+
+        self.assertEqual("id", change.columns()[0].name())
+        self.assertEqual(Dialects.TRINO, change.representations()[0].dialect())
+        self.assertEqual(original_hash, hash(change))
+
+    def test_replace_view_validation(self):
+        representations = [SQLRepresentation(Dialects.TRINO, "SELECT 1")]
+
+        with self.assertRaisesRegex(ValueError, "columns must not be null"):
+            ViewChange.replace_view(None, representations)
+        with self.assertRaisesRegex(
+            ValueError, "representations must not be null or empty"
+        ):
+            ViewChange.replace_view([], [])