Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#9528] feat(storage): support function management (Service) (part-3) (#9856)

mchades3786a9c392b6
diff --git a/AGENTS.md b/AGENTS.md
index ce35d9b614..b28d6329dc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -39,6 +39,10 @@
4. Constructors.
5. Methods (Group by visibility, putting `private` methods at the end).
+## Issue and PR Guidelines
+- **Issue Templates**: Use the appropriate template from `.github/ISSUE_TEMPLATE/`
+- **PR Description**: Follow the template in `.github/PULL_REQUEST_TEMPLATE`
+
## Project Structure
- `api/`: Public interfaces.
- `common/`: Shared utilities/DTOs.
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
index 47c3a39f59..4ea63ba9ff 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/JDBCBackend.java
@@ -44,6 +44,7 @@ import org.apache.gravitino.exceptions.NoSuchEntityException;
import org.apache.gravitino.meta.BaseMetalake;
import org.apache.gravitino.meta.CatalogEntity;
import org.apache.gravitino.meta.FilesetEntity;
+import org.apache.gravitino.meta.FunctionEntity;
import org.apache.gravitino.meta.GroupEntity;
import org.apache.gravitino.meta.JobEntity;
import org.apache.gravitino.meta.JobTemplateEntity;
@@ -61,6 +62,7 @@ import org.apache.gravitino.storage.relational.converters.SQLExceptionConverterF
import org.apache.gravitino.storage.relational.database.H2Database;
import org.apache.gravitino.storage.relational.service.CatalogMetaService;
import org.apache.gravitino.storage.relational.service.FilesetMetaService;
+import org.apache.gravitino.storage.relational.service.FunctionMetaService;
import org.apache.gravitino.storage.relational.service.GroupMetaService;
import org.apache.gravitino.storage.relational.service.JobMetaService;
import org.apache.gravitino.storage.relational.service.JobTemplateMetaService;
@@ -134,6 +136,8 @@ public class JDBCBackend implements RelationalBackend {
case MODEL_VERSION:
return (List<E>)
ModelVersionMetaService.getInstance().listModelVersionsByNamespace(namespace);
+ case FUNCTION:
+ return (List<E>) FunctionMetaService.getInstance().listFunctionsByNamespace(namespace);
case POLICY:
return (List<E>) PolicyMetaService.getInstance().listPoliciesByNamespace(namespace);
case JOB_TEMPLATE:
@@ -194,6 +198,8 @@ public class JDBCBackend implements RelationalBackend {
+ "inserting the new model version.");
}
ModelVersionMetaService.getInstance().insertModelVersion((ModelVersionEntity) e);
+ } else if (e instanceof FunctionEntity) {
+ FunctionMetaService.getInstance().insertFunction((FunctionEntity) e, overwritten);
} else if (e instanceof PolicyEntity) {
PolicyMetaService.getInstance().insertPolicy((PolicyEntity) e, overwritten);
} else if (e instanceof JobTemplateEntity) {
@@ -235,6 +241,8 @@ public class JDBCBackend implements RelationalBackend {
return (E) ModelMetaService.getInstance().updateModel(ident, updater);
case MODEL_VERSION:
return (E) ModelVersionMetaService.getInstance().updateModelVersion(ident, updater);
+ case FUNCTION:
+ throw new UnsupportedOperationException("updateFunction not implemented yet");
case POLICY:
return (E) PolicyMetaService.getInstance().updatePolicy(ident, updater);
case JOB_TEMPLATE:
@@ -274,6 +282,8 @@ public class JDBCBackend implements RelationalBackend {
return (E) ModelMetaService.getInstance().getModelByIdentifier(ident);
case MODEL_VERSION:
return (E) ModelVersionMetaService.getInstance().getModelVersionByIdentifier(ident);
+ case FUNCTION:
+ return (E) FunctionMetaService.getInstance().getFunctionByIdentifier(ident);
case POLICY:
return (E) PolicyMetaService.getInstance().getPolicyByIdentifier(ident);
case JOB_TEMPLATE:
@@ -326,6 +336,8 @@ public class JDBCBackend implements RelationalBackend {
return ModelMetaService.getInstance().deleteModel(ident);
case MODEL_VERSION:
return ModelVersionMetaService.getInstance().deleteModelVersion(ident);
+ case FUNCTION:
+ throw new UnsupportedOperationException("deleteFunction not implemented yet");
case POLICY:
return PolicyMetaService.getInstance().deletePolicy(ident);
case JOB_TEMPLATE:
@@ -397,6 +409,9 @@ public class JDBCBackend implements RelationalBackend {
return ModelVersionMetaService.getInstance()
.deleteModelVersionMetasByLegacyTimeline(
legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
+ case FUNCTION:
+ // TODO: implement deleteFunctionMetasByLegacyTimeline
+ return 0;
case TABLE_STATISTIC:
return StatisticMetaService.getInstance()
.deleteStatisticsByLegacyTimeline(
@@ -409,7 +424,6 @@ public class JDBCBackend implements RelationalBackend {
return JobMetaService.getInstance()
.deleteJobsByLegacyTimeline(legacyTimeline, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
case AUDIT:
- case FUNCTION:
case VIEW:
return 0;
// TODO: Implement hard delete logic for these entity types.
@@ -440,7 +454,6 @@ public class JDBCBackend implements RelationalBackend {
case TABLE_STATISTIC:
case JOB_TEMPLATE:
case JOB:
- case FUNCTION: // todo: remove once function versioning is supported
case VIEW:
// These entity types have not implemented multi-versions, so we can skip.
return 0;
@@ -455,6 +468,10 @@ public class JDBCBackend implements RelationalBackend {
.deletePolicyVersionsByRetentionCount(
versionRetentionCount, GARBAGE_COLLECTOR_SINGLE_DELETION_LIMIT);
+ case FUNCTION:
+ // TODO: implement deleteFunctionVersionsByRetentionCount
+ return 0;
+
default:
throw new IllegalArgumentException(
"Unsupported entity type when collectAndRemoveOldVersionData: " + entityType);
diff --git a/core/src/main/java/org/apache/gravitino/storage/relational/po/FunctionPO.java b/core/src/main/java/org/apache/gravitino/storage/relational/po/FunctionPO.java
index 35f7d00cf3..5fc23337b8 100644
--- a/core/src/main/java/org/apache/gravitino/storage/relational/po/FunctionPO.java
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/po/FunctionPO.java
@@ -18,12 +18,30 @@
*/
package org.apache.gravitino.storage.relational.po;
+import static org.apache.gravitino.storage.relational.utils.POConverters.DEFAULT_DELETED_AT;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Preconditions;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.dto.function.FunctionDefinitionDTO;
+import org.apache.gravitino.function.FunctionDefinition;
+import org.apache.gravitino.function.FunctionType;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.FunctionEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.rel.types.Type;
+import org.apache.gravitino.storage.relational.service.EntityIdService;
@EqualsAndHashCode
@Getter
@@ -31,6 +49,8 @@ import org.apache.commons.lang3.StringUtils;
@Accessors(fluent = true)
public class FunctionPO {
+ private static final Integer INITIAL_VERSION = 1;
+
private Long functionId;
private String functionName;
@@ -59,6 +79,10 @@ public class FunctionPO {
public FunctionPO() {}
+ public static class FunctionPOBuilder {
+ // Lombok will generate builder methods
+ }
+
@lombok.Builder(setterPrefix = "with")
private FunctionPO(
Long functionId,
@@ -103,4 +127,90 @@ public class FunctionPO {
this.deletedAt = deletedAt;
this.functionVersionPO = functionVersionPO;
}
+
+ // ============================ PO Converters ============================
+
+ public static FunctionEntity fromFunctionPO(FunctionPO functionPO, Namespace namespace) {
+ try {
+ FunctionVersionPO versionPO = functionPO.functionVersionPO();
+ List<FunctionDefinitionDTO> definitionDTOs =
+ JsonUtils.anyFieldMapper()
+ .readValue(
+ versionPO.definitions(),
+ JsonUtils.anyFieldMapper()
+ .getTypeFactory()
+ .constructCollectionType(List.class, FunctionDefinitionDTO.class));
+ FunctionDefinition[] definitions =
+ definitionDTOs.stream()
+ .map(FunctionDefinitionDTO::toFunctionDefinition)
+ .toArray(FunctionDefinition[]::new);
+ return FunctionEntity.builder()
+ .withId(functionPO.functionId())
+ .withName(functionPO.functionName())
+ .withNamespace(namespace)
+ .withComment(versionPO.functionComment())
+ .withFunctionType(FunctionType.valueOf(functionPO.functionType()))
+ .withDeterministic(functionPO.deterministic() != null && functionPO.deterministic() == 1)
+ .withReturnType(JsonUtils.anyFieldMapper().readValue(functionPO.returnType(), Type.class))
+ .withDefinitions(definitions)
+ .withAuditInfo(
+ JsonUtils.anyFieldMapper().readValue(functionPO.auditInfo(), AuditInfo.class))
+ .build();
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to deserialize json object:", e);
+ }
+ }
+
+ public static FunctionPO initializeFunctionPO(
+ FunctionEntity functionEntity, FunctionPO.FunctionPOBuilder builder) {
+ builder.withFunctionLatestVersion(INITIAL_VERSION).withFunctionCurrentVersion(INITIAL_VERSION);
+ return buildFunctionPO(functionEntity, builder);
+ }
+
+ public static FunctionVersionPO initializeFunctionVersionPO(
+ FunctionEntity functionEntity, NamespacedEntityId namespacedEntityId, Integer version) {
+ try {
+ List<FunctionDefinitionDTO> definitionDTOs =
+ Arrays.stream(functionEntity.definitions())
+ .map(FunctionDefinitionDTO::fromFunctionDefinition)
+ .collect(Collectors.toList());
+ return FunctionVersionPO.builder()
+ .withFunctionId(functionEntity.id())
+ .withMetalakeId(namespacedEntityId.namespaceIds()[0])
+ .withCatalogId(namespacedEntityId.namespaceIds()[1])
+ .withSchemaId(namespacedEntityId.entityId())
+ .withFunctionVersion(version)
+ .withFunctionComment(functionEntity.comment())
+ .withDefinitions(JsonUtils.anyFieldMapper().writeValueAsString(definitionDTOs))
+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(functionEntity.auditInfo()))
+ .withDeletedAt(DEFAULT_DELETED_AT)
+ .build();
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to serialize json object:", e);
+ }
+ }
+
+ public static FunctionPO buildFunctionPO(
+ FunctionEntity functionEntity, FunctionPO.FunctionPOBuilder builder) {
+ try {
+ NamespacedEntityId namespacedEntityId =
+ EntityIdService.getEntityIds(
+ NameIdentifier.of(functionEntity.namespace().levels()), Entity.EntityType.SCHEMA);
+ FunctionVersionPO versionPO =
+ initializeFunctionVersionPO(functionEntity, namespacedEntityId, INITIAL_VERSION);
+ return builder
+ .withFunctionId(functionEntity.id())
+ .withFunctionName(functionEntity.name())
+ .withFunctionType(functionEntity.functionType().name())
+ .withDeterministic(functionEntity.deterministic() ? 1 : 0)
+ .withReturnType(
+ JsonUtils.anyFieldMapper().writeValueAsString(functionEntity.returnType()))
+ .withFunctionVersionPO(versionPO)
+ .withAuditInfo(JsonUtils.anyFieldMapper().writeValueAsString(functionEntity.auditInfo()))
+ .withDeletedAt(DEFAULT_DELETED_AT)
+ .build();
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException("Failed to serialize json object:", e);
+ }
+ }
}
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
new file mode 100644
index 0000000000..4a5bfe36d8
--- /dev/null
+++ b/core/src/main/java/org/apache/gravitino/storage/relational/service/FunctionMetaService.java
@@ -0,0 +1,216 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;
+import static org.apache.gravitino.storage.relational.po.FunctionPO.fromFunctionPO;
+import static org.apache.gravitino.storage.relational.po.FunctionPO.initializeFunctionPO;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Locale;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+import org.apache.gravitino.meta.FunctionEntity;
+import org.apache.gravitino.meta.NamespacedEntityId;
+import org.apache.gravitino.metrics.Monitored;
+import org.apache.gravitino.storage.relational.mapper.FunctionMetaMapper;
+import org.apache.gravitino.storage.relational.mapper.FunctionVersionMetaMapper;
+import org.apache.gravitino.storage.relational.po.FunctionPO;
+import org.apache.gravitino.storage.relational.utils.ExceptionUtils;
+import org.apache.gravitino.storage.relational.utils.SessionUtils;
+import org.apache.gravitino.utils.NameIdentifierUtil;
+import org.apache.gravitino.utils.NamespaceUtil;
+
+public class FunctionMetaService {
+ public static FunctionMetaService getInstance() {
+ return INSTANCE;
+ }
+
+ private static final FunctionMetaService INSTANCE = new FunctionMetaService();
+
+ private FunctionMetaService() {}
+
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "listFunctionsByNamespace")
+ public List<FunctionEntity> listFunctionsByNamespace(Namespace ns) {
+ NamespaceUtil.checkFunction(ns);
+
+ List<FunctionPO> functionPOs = listFunctionPOs(ns);
+ return functionPOs.stream().map(f -> fromFunctionPO(f, ns)).collect(Collectors.toList());
+ }
+
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "getFunctionByIdentifier")
+ public FunctionEntity getFunctionByIdentifier(NameIdentifier ident) {
+ FunctionPO functionPO = getFunctionPOByIdentifier(ident);
+ return fromFunctionPO(functionPO, ident.namespace());
+ }
+
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "insertFunction")
+ public void insertFunction(FunctionEntity functionEntity, boolean overwrite) throws IOException {
+ NameIdentifierUtil.checkFunction(functionEntity.nameIdentifier());
+
+ FunctionPO.FunctionPOBuilder builder = FunctionPO.builder();
+ try {
+ fillFunctionPOBuilderParentEntityId(builder, functionEntity.namespace());
+ FunctionPO po = initializeFunctionPO(functionEntity, builder);
+
+ SessionUtils.doMultipleWithCommit(
+ () ->
+ SessionUtils.doWithoutCommit(
+ FunctionMetaMapper.class,
+ mapper -> {
+ if (overwrite) {
+ mapper.insertFunctionMetaOnDuplicateKeyUpdate(po);
+ } else {
+ mapper.insertFunctionMeta(po);
+ }
+ }),
+ () ->
+ SessionUtils.doWithoutCommit(
+ FunctionVersionMetaMapper.class,
+ mapper -> {
+ if (overwrite) {
+ mapper.insertFunctionVersionMetaOnDuplicateKeyUpdate(po.functionVersionPO());
+ } else {
+ mapper.insertFunctionVersionMeta(po.functionVersionPO());
+ }
+ }));
+ } catch (RuntimeException re) {
+ ExceptionUtils.checkSQLException(
+ re, Entity.EntityType.FUNCTION, functionEntity.nameIdentifier().toString());
+ throw re;
+ }
+ }
+
+ @Monitored(
+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,
+ baseMetricName = "getFunctionPOByIdentifier")
+ FunctionPO getFunctionPOByIdentifier(NameIdentifier ident) {
+ NameIdentifierUtil.checkFunction(ident);
+
+ return functionPOFetcher().apply(ident);
+ }
+
+ private Function<NameIdentifier, FunctionPO> functionPOFetcher() {
+ return GravitinoEnv.getInstance().cacheEnabled()
+ ? this::getFunctionPOBySchemaId
+ : this::getFunctionPOByFullQualifiedName;
+ }
+
+ private FunctionPO getFunctionPOBySchemaId(NameIdentifier ident) {
+ Long schemaId =
+ EntityIdService.getEntityId(
+ NameIdentifier.of(ident.namespace().levels()), Entity.EntityType.SCHEMA);
+
+ FunctionPO functionPO =
+ SessionUtils.getWithoutCommit(
+ FunctionMetaMapper.class,
+ mapper -> mapper.selectFunctionMetaBySchemaIdAndName(schemaId, ident.name()));
+
+ if (functionPO == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.FUNCTION.name().toLowerCase(Locale.ROOT),
+ ident.toString());
+ }
+ return functionPO;
+ }
+
+ private FunctionPO getFunctionPOByFullQualifiedName(NameIdentifier ident) {
+ String[] namespaceLevels = ident.namespace().levels();
+ FunctionPO functionPO =
+ SessionUtils.getWithoutCommit(
+ FunctionMetaMapper.class,
+ mapper ->
+ mapper.selectFunctionMetaByFullQualifiedName(
+ namespaceLevels[0], namespaceLevels[1], namespaceLevels[2], ident.name()));
+
+ if (functionPO == null || functionPO.functionId() == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.FUNCTION.name().toLowerCase(Locale.ROOT),
+ ident.name());
+ }
+
+ if (functionPO.schemaId() == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.SCHEMA.name().toLowerCase(),
+ namespaceLevels[2]);
+ }
+ return functionPO;
+ }
+
+ private List<FunctionPO> listFunctionPOs(Namespace namespace) {
+ return functionListFetcher().apply(namespace);
+ }
+
+ private List<FunctionPO> listFunctionPOsBySchemaId(Namespace namespace) {
+ Long schemaId =
+ EntityIdService.getEntityId(
+ NameIdentifier.of(namespace.levels()), Entity.EntityType.SCHEMA);
+ return SessionUtils.getWithoutCommit(
+ FunctionMetaMapper.class, mapper -> mapper.listFunctionPOsBySchemaId(schemaId));
+ }
+
+ private Function<Namespace, List<FunctionPO>> functionListFetcher() {
+ return GravitinoEnv.getInstance().cacheEnabled()
+ ? this::listFunctionPOsBySchemaId
+ : this::listFunctionPOsByFullQualifiedName;
+ }
+
+ private List<FunctionPO> listFunctionPOsByFullQualifiedName(Namespace namespace) {
+ String[] namespaceLevels = namespace.levels();
+ List<FunctionPO> functionPOs =
+ SessionUtils.getWithoutCommit(
+ FunctionMetaMapper.class,
+ mapper ->
+ mapper.listFunctionPOsByFullQualifiedName(
+ namespaceLevels[0], namespaceLevels[1], namespaceLevels[2]));
+ if (functionPOs.isEmpty() || functionPOs.get(0).schemaId() == null) {
+ throw new NoSuchEntityException(
+ NoSuchEntityException.NO_SUCH_ENTITY_MESSAGE,
+ Entity.EntityType.SCHEMA.name().toLowerCase(),
+ namespaceLevels[2]);
+ }
+ return functionPOs.stream().filter(po -> po.functionId() != null).collect(Collectors.toList());
+ }
+
+ private void fillFunctionPOBuilderParentEntityId(
+ FunctionPO.FunctionPOBuilder builder, Namespace ns) {
+ NamespaceUtil.checkFunction(ns);
+ NamespacedEntityId namespacedEntityId =
+ EntityIdService.getEntityIds(NameIdentifier.of(ns.levels()), Entity.EntityType.SCHEMA);
+ builder.withMetalakeId(namespacedEntityId.namespaceIds()[0]);
+ builder.withCatalogId(namespacedEntityId.namespaceIds()[1]);
+ builder.withSchemaId(namespacedEntityId.entityId());
+ }
+}
diff --git a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
index 32523b9725..75f6718f6f 100644
--- a/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/NameIdentifierUtil.java
@@ -560,6 +560,17 @@ public class NameIdentifierUtil {
NamespaceUtil.checkModelVersion(ident.namespace());
}
+ /**
+ * Check the given {@link NameIdentifier} is a function identifier. Throw an {@link
+ * IllegalNameIdentifierException} if it's not.
+ *
+ * @param ident The function {@link NameIdentifier} to check.
+ */
+ public static void checkFunction(NameIdentifier ident) {
+ NameIdentifier.check(ident != null, "Function identifier must not be null");
+ NamespaceUtil.checkFunction(ident.namespace());
+ }
+
/**
* Check the given {@link NameIdentifier} is a job identifier. Throw an {@link
* IllegalNameIdentifierException} if it's not.
diff --git a/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java b/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
index d774c26bf3..13b380a81b 100644
--- a/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
+++ b/core/src/main/java/org/apache/gravitino/utils/NamespaceUtil.java
@@ -374,6 +374,19 @@ public class NamespaceUtil {
namespace);
}
+ /**
+ * Check if the given function namespace is legal, throw an {@link IllegalNamespaceException} if
+ * it's illegal.
+ *
+ * @param namespace The function namespace
+ */
+ public static void checkFunction(Namespace namespace) {
+ check(
+ namespace != null && namespace.length() == 3,
+ "Function namespace must be non-null and have 3 levels, the input namespace is %s",
+ namespace);
+ }
+
/**
* Check if the given job template namespace is legal, throw an {@link IllegalNamespaceException}
*
diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java
index 5faa1a71ee..892d25f0d9 100644
--- a/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/TestJDBCBackend.java
@@ -225,6 +225,10 @@ public abstract class TestJDBCBackend {
tableName = "policy_meta";
idColumnName = "policy_id";
break;
+ case FUNCTION:
+ tableName = "function_meta";
+ idColumnName = "function_id";
+ break;
default:
throw new IllegalArgumentException("Unsupported entity type: " + entityType);
}
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
new file mode 100644
index 0000000000..63f6d15989
--- /dev/null
+++ b/core/src/test/java/org/apache/gravitino/storage/relational/service/TestFunctionMetaService.java
@@ -0,0 +1,219 @@
+/*
+ * 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.storage.relational.service;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+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.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.apache.gravitino.EntityAlreadyExistsException;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Namespace;
+import org.apache.gravitino.exceptions.NoSuchEntityException;
+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.util.GravitinoITUtils;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.FunctionEntity;
+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.NamespaceUtil;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.TestTemplate;
+
+public class TestFunctionMetaService extends TestJDBCBackend {
+ private final String metalakeName = GravitinoITUtils.genRandomName("tst_metalake");
+ private final String catalogName = GravitinoITUtils.genRandomName("tst_fn_catalog");
+ private final String schemaName = GravitinoITUtils.genRandomName("tst_fn_schema");
+
+ @BeforeEach
+ public void prepare() throws IOException {
+ createAndInsertMakeLake(metalakeName);
+ createAndInsertCatalog(metalakeName, catalogName);
+ createAndInsertSchema(metalakeName, catalogName, schemaName);
+ }
+
+ @TestTemplate
+ public void testInsertAlreadyExistsException() throws IOException {
+ FunctionEntity function =
+ createFunctionEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofFunction(metalakeName, catalogName, schemaName),
+ "test_function",
+ AUDIT_INFO);
+ FunctionEntity functionCopy =
+ createFunctionEntity(
+ RandomIdGenerator.INSTANCE.nextId(),
+ NamespaceUtil.ofFunction(metalakeName, catalogName, schemaName),
+ "test_function",
+ AUDIT_INFO);
+
+ FunctionMetaService.getInstance().insertFunction(function, false);
+ assertThrows(
+ EntityAlreadyExistsException.class,
+ () -> FunctionMetaService.getInstance().insertFunction(functionCopy, false));
+ }
+
+ @TestTemplate
+ public void testInsertAndGetFunction() throws IOException {
+ String functionName = GravitinoITUtils.genRandomName("test_function");
+ Namespace ns = NamespaceUtil.ofFunction(metalakeName, catalogName, schemaName);
+ FunctionEntity function =
+ createFunctionEntity(RandomIdGenerator.INSTANCE.nextId(), ns, functionName, AUDIT_INFO);
+
+ FunctionMetaService.getInstance().insertFunction(function, false);
+
+ // Get function using standard identifier (always returns latest version)
+ NameIdentifier functionIdent =
+ NameIdentifier.of(metalakeName, catalogName, schemaName, functionName);
+ FunctionEntity loadedFunction =
+ FunctionMetaService.getInstance().getFunctionByIdentifier(functionIdent);
+
+ assertNotNull(loadedFunction);
+ assertEquals(function.id(), loadedFunction.id());
+ assertEquals(function.name(), loadedFunction.name());
+ assertEquals(function.comment(), loadedFunction.comment());
+ assertEquals(function.functionType(), loadedFunction.functionType());
+ assertEquals(function.deterministic(), loadedFunction.deterministic());
+ }
+
+ @TestTemplate
+ public void testListFunctions() throws IOException {
+ Namespace ns = NamespaceUtil.ofFunction(metalakeName, catalogName, schemaName);
+
+ String functionName1 = GravitinoITUtils.genRandomName("test_function1");
+ FunctionEntity function1 =
+ createFunctionEntity(RandomIdGenerator.INSTANCE.nextId(), ns, functionName1, AUDIT_INFO);
+
+ String functionName2 = GravitinoITUtils.genRandomName("test_function2");
+ FunctionEntity function2 =
+ createFunctionEntity(RandomIdGenerator.INSTANCE.nextId(), ns, functionName2, AUDIT_INFO);
+
+ FunctionMetaService.getInstance().insertFunction(function1, false);
+ FunctionMetaService.getInstance().insertFunction(function2, false);
+
+ List<FunctionEntity> functions = FunctionMetaService.getInstance().listFunctionsByNamespace(ns);
+
+ assertEquals(2, functions.size());
+ assertTrue(functions.stream().anyMatch(f -> f.name().equals(functionName1)));
+ assertTrue(functions.stream().anyMatch(f -> f.name().equals(functionName2)));
+ }
+
+ @TestTemplate
+ public void testGetNonExistentFunction() {
+ NameIdentifier functionIdent =
+ NameIdentifier.of(metalakeName, catalogName, schemaName, "non_existent_function");
+ assertThrows(
+ NoSuchEntityException.class,
+ () -> FunctionMetaService.getInstance().getFunctionByIdentifier(functionIdent));
+ }
+
+ @TestTemplate
+ public void testInsertFunctionWithOverwrite() throws IOException {
+ String functionName = GravitinoITUtils.genRandomName("test_function");
+ Namespace ns = NamespaceUtil.ofFunction(metalakeName, catalogName, schemaName);
+ FunctionEntity function =
+ createFunctionEntity(RandomIdGenerator.INSTANCE.nextId(), ns, functionName, AUDIT_INFO);
+
+ FunctionMetaService.getInstance().insertFunction(function, false);
+
+ NameIdentifier functionIdent =
+ NameIdentifier.of(metalakeName, catalogName, schemaName, functionName);
+
+ // Insert with overwrite=true should succeed
+ FunctionEntity newFunction =
+ FunctionEntity.builder()
+ .withId(function.id())
+ .withName(function.name())
+ .withNamespace(ns)
+ .withComment("overwritten comment")
+ .withFunctionType(function.functionType())
+ .withDeterministic(true)
+ .withReturnType(function.returnType())
+ .withDefinitions(function.definitions())
+ .withAuditInfo(AUDIT_INFO)
+ .build();
+
+ FunctionMetaService.getInstance().insertFunction(newFunction, true);
+
+ // Verify the function was updated
+ FunctionEntity loadedFunction =
+ FunctionMetaService.getInstance().getFunctionByIdentifier(functionIdent);
+ assertEquals("overwritten comment", loadedFunction.comment());
+ assertTrue(loadedFunction.deterministic());
+ }
+
+ private FunctionEntity createFunctionEntity(
+ Long id, Namespace namespace, String name, AuditInfo auditInfo) {
+ FunctionParam param1 = FunctionParams.of("param1", Types.IntegerType.get());
+ FunctionParam param2 = FunctionParams.of("param2", Types.StringType.get());
+ FunctionImpl impl = FunctionImpls.ofSql(FunctionImpl.RuntimeType.SPARK, "SELECT param1 + 1");
+ FunctionDefinition definition =
+ FunctionDefinitions.of(new FunctionParam[] {param1, param2}, new FunctionImpl[] {impl});
+
+ return FunctionEntity.builder()
+ .withId(id)
+ .withName(name)
+ .withNamespace(namespace)
+ .withComment("test function comment")
+ .withFunctionType(FunctionType.SCALAR)
+ .withDeterministic(false)
+ .withReturnType(Types.IntegerType.get())
+ .withDefinitions(new FunctionDefinition[] {definition})
+ .withAuditInfo(auditInfo)
+ .build();
+ }
+
+ private Map<Integer, Long> listFunctionVersions(Long functionId) {
+ Map<Integer, Long> versionDeletedTime = new HashMap<>();
+ try (SqlSession sqlSession =
+ SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true);
+ Connection connection = sqlSession.getConnection();
+ Statement statement = connection.createStatement();
+ ResultSet rs =
+ statement.executeQuery(
+ String.format(
+ "SELECT version, deleted_at FROM function_version_info WHERE function_id = %d",
+ functionId))) {
+ while (rs.next()) {
+ versionDeletedTime.put(rs.getInt("version"), rs.getLong("deleted_at"));
+ }
+ } catch (SQLException e) {
+ throw new RuntimeException("SQL execution failed", e);
+ }
+ return versionDeletedTime;
+ }
+}