Copilot commented on code in PR #9560: URL: https://github.com/apache/gravitino/pull/9560#discussion_r2694281834
########## core/src/main/java/org/apache/gravitino/meta/FunctionEntity.java: ########## @@ -0,0 +1,357 @@ +/* + * 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.meta; + +import com.google.common.collect.Maps; +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import lombok.ToString; +import org.apache.gravitino.Auditable; +import org.apache.gravitino.Entity; +import org.apache.gravitino.Field; +import org.apache.gravitino.HasIdentifier; +import org.apache.gravitino.Namespace; +import org.apache.gravitino.function.Function; +import org.apache.gravitino.function.FunctionColumn; +import org.apache.gravitino.function.FunctionDefinition; +import org.apache.gravitino.function.FunctionType; +import org.apache.gravitino.rel.types.Type; + +/** + * A class representing a function entity in the metadata store. + * + * <p>This entity stores both the function metadata and its version information together, avoiding + * the need for separate FunctionEntity and FunctionVersionEntity. When retrieving, if version is + * set to the special value {@link #LATEST_VERSION}, the store should return the latest version. + */ +@ToString +public class FunctionEntity implements Entity, Auditable, HasIdentifier, Function { + + /** Special version value indicating the latest version should be retrieved. */ + public static final int LATEST_VERSION = -1; + + public static final Field ID = + Field.required("id", Long.class, "The unique id of the function entity."); + public static final Field NAME = + Field.required("name", String.class, "The name of the function entity."); + public static final Field COMMENT = + Field.optional("comment", String.class, "The comment or description of the function entity."); + public static final Field FUNCTION_TYPE = + Field.required("function_type", FunctionType.class, "The type of the function."); + public static final Field DETERMINISTIC = + Field.required("deterministic", Boolean.class, "Whether the function is deterministic."); + public static final Field RETURN_TYPE = + Field.optional( + "return_type", Type.class, "The return type for scalar or aggregate functions."); + public static final Field RETURN_COLUMNS = + Field.optional( + "return_columns", + FunctionColumn[].class, + "The output columns for table-valued functions."); + public static final Field DEFINITIONS = + Field.required("definitions", FunctionDefinition[].class, "The definitions of the function."); + public static final Field VERSION = + Field.required("version", Integer.class, "The version of the function entity."); + public static final Field AUDIT_INFO = + Field.required("audit_info", AuditInfo.class, "The audit details of the function entity."); + + private Long id; + private String name; + private Namespace namespace; + private String comment; + private FunctionType functionType; + private boolean deterministic; + private Type returnType; + private FunctionColumn[] returnColumns; + private FunctionDefinition[] definitions; + private Integer version; + private AuditInfo auditInfo; + + private FunctionEntity() {} + + @Override + public Map<Field, Object> fields() { + Map<Field, Object> fields = Maps.newHashMap(); + fields.put(ID, id); + fields.put(NAME, name); + fields.put(COMMENT, comment); + fields.put(FUNCTION_TYPE, functionType); + fields.put(DETERMINISTIC, deterministic); + fields.put(RETURN_TYPE, returnType); + fields.put(RETURN_COLUMNS, returnColumns); + fields.put(DEFINITIONS, definitions); + fields.put(VERSION, version); + fields.put(AUDIT_INFO, auditInfo); + + return Collections.unmodifiableMap(fields); + } + + @Override + public String name() { + return name; + } + + @Override + public Long id() { + return id; + } + + @Override + public Namespace namespace() { + return namespace; + } + + @Override + public String comment() { + return comment; + } + + @Override + public FunctionType functionType() { + return functionType; + } + + @Override + public boolean deterministic() { + return deterministic; + } + + @Override + public Type returnType() { + return returnType; + } + + @Override + public FunctionColumn[] returnColumns() { + return returnColumns != null ? returnColumns : new FunctionColumn[0]; + } + + @Override + public FunctionDefinition[] definitions() { + return definitions; + } + + @Override + public int version() { + return version; + } + + @Override + public AuditInfo auditInfo() { + return auditInfo; + } + + @Override + public EntityType type() { + return EntityType.FUNCTION; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof FunctionEntity)) { + return false; + } + + FunctionEntity that = (FunctionEntity) o; + return Objects.equals(id, that.id) + && Objects.equals(name, that.name) + && Objects.equals(namespace, that.namespace) + && Objects.equals(comment, that.comment) + && functionType == that.functionType + && deterministic == that.deterministic + && Objects.equals(returnType, that.returnType) + && Arrays.equals(returnColumns, that.returnColumns) + && Arrays.equals(definitions, that.definitions) + && Objects.equals(version, that.version) + && Objects.equals(auditInfo, that.auditInfo); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + id, + name, + namespace, + comment, + functionType, + deterministic, + returnType, + version, + auditInfo); + result = 31 * result + Arrays.hashCode(returnColumns); + result = 31 * result + Arrays.hashCode(definitions); + return result; + } + + /** + * Creates a new builder for constructing a FunctionEntity. + * + * @return A new builder instance. + */ + public static Builder builder() { + return new Builder(); + } + + /** Builder class for creating instances of {@link FunctionEntity}. */ + public static class Builder { + private final FunctionEntity functionEntity; + + private Builder() { + functionEntity = new FunctionEntity(); + } + + /** + * Sets the unique id of the function entity. + * + * @param id The unique id. + * @return This builder instance. + */ + public Builder withId(Long id) { + functionEntity.id = id; + return this; + } + + /** + * Sets the name of the function entity. + * + * @param name The name of the function. + * @return This builder instance. + */ + public Builder withName(String name) { + functionEntity.name = name; + return this; + } + + /** + * Sets the namespace of the function entity. + * + * @param namespace The namespace. + * @return This builder instance. + */ + public Builder withNamespace(Namespace namespace) { + functionEntity.namespace = namespace; + return this; + } + + /** + * Sets the comment of the function entity. + * + * @param comment The comment or description. + * @return This builder instance. + */ + public Builder withComment(String comment) { + functionEntity.comment = comment; + return this; + } + + /** + * Sets the function type. + * + * @param functionType The type of the function (SCALAR, AGGREGATE, or TABLE). + * @return This builder instance. + */ + public Builder withFunctionType(FunctionType functionType) { + functionEntity.functionType = functionType; + return this; + } + + /** + * Sets whether the function is deterministic. + * + * @param deterministic True if the function is deterministic, false otherwise. + * @return This builder instance. + */ + public Builder withDeterministic(boolean deterministic) { + functionEntity.deterministic = deterministic; + return this; + } + + /** + * Sets the return type for scalar or aggregate functions. + * + * @param returnType The return type. + * @return This builder instance. + */ + public Builder withReturnType(Type returnType) { + functionEntity.returnType = returnType; + return this; + } + + /** + * Sets the return columns for table-valued functions. + * + * @param returnColumns The output columns. + * @return This builder instance. + */ + public Builder withReturnColumns(FunctionColumn[] returnColumns) { + functionEntity.returnColumns = returnColumns; + return this; + } + + /** + * Sets the function definitions. + * + * @param definitions The definitions (overloads) of the function. + * @return This builder instance. + */ + public Builder withDefinitions(FunctionDefinition[] definitions) { + functionEntity.definitions = definitions; + return this; + } + + /** + * Sets the version of the function entity. + * + * @param version The version number. + * @return This builder instance. + */ + public Builder withVersion(Integer version) { + functionEntity.version = version; + return this; + } + + /** + * Sets the audit information. + * + * @param auditInfo The audit information. + * @return This builder instance. + */ + public Builder withAuditInfo(AuditInfo auditInfo) { + functionEntity.auditInfo = auditInfo; + return this; + } + + /** + * Builds the FunctionEntity instance. + * + * @return The constructed FunctionEntity. + */ + public FunctionEntity build() { + functionEntity.validate(); + return functionEntity; + } + } Review Comment: The `validate()` method is called in the builder but `FunctionEntity` does not override the `validate()` method. While the default implementation from the `Entity` interface will validate fields, there may be additional business logic validation needed (e.g., ensuring that either returnType or returnColumns is set based on functionType). Consider adding an explicit `validate()` method implementation in `FunctionEntity` to validate function-specific constraints, or document that the default field validation is intentionally sufficient. ```suggestion } /** * Validates this {@link FunctionEntity}. * * <p>This implementation currently relies on the default field-level validation provided by * {@link Entity#validate()}. Any function-specific business rules should be added here in the * future. */ @Override public void validate() { Entity.super.validate(); } ``` ########## core/src/test/java/org/apache/gravitino/catalog/TestManagedFunctionOperations.java: ########## @@ -0,0 +1,494 @@ +/* + * 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.catalog; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.gravitino.Entity; +import org.apache.gravitino.EntityAlreadyExistsException; +import org.apache.gravitino.EntityStore; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.Namespace; +import org.apache.gravitino.exceptions.FunctionAlreadyExistsException; +import org.apache.gravitino.exceptions.NoSuchEntityException; +import org.apache.gravitino.exceptions.NoSuchFunctionException; +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.meta.FunctionEntity; +import org.apache.gravitino.rel.expressions.literals.Literals; +import org.apache.gravitino.rel.types.Types; +import org.apache.gravitino.storage.IdGenerator; +import org.apache.gravitino.storage.RandomIdGenerator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestManagedFunctionOperations { + + private static final String METALAKE_NAME = "test_metalake"; + private static final String CATALOG_NAME = "test_catalog"; + private static final String SCHEMA_NAME = "schema1"; + + private final IdGenerator idGenerator = new RandomIdGenerator(); + private final Map<NameIdentifier, FunctionEntity> entityMap = new HashMap<>(); + + private EntityStore store; + private ManagedFunctionOperations functionOperations; + + @BeforeEach + public void setUp() throws Exception { + entityMap.clear(); + store = createMockEntityStore(); + functionOperations = new ManagedFunctionOperations(store, idGenerator); + } + + @Test + public void testRegisterAndListFunctions() { + NameIdentifier func1Ident = getFunctionIdent("func1"); + FunctionParam[] params1 = new FunctionParam[] {FunctionParams.of("a", Types.IntegerType.get())}; + FunctionDefinition[] definitions1 = new FunctionDefinition[] {createSimpleDefinition(params1)}; + + functionOperations.registerFunction( + func1Ident, + "Test function 1", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions1); + + NameIdentifier func2Ident = getFunctionIdent("func2"); + FunctionParam[] params2 = + new FunctionParam[] { + FunctionParams.of("x", Types.StringType.get()), + FunctionParams.of("y", Types.StringType.get()) + }; + FunctionDefinition[] definitions2 = new FunctionDefinition[] {createSimpleDefinition(params2)}; + + functionOperations.registerFunction( + func2Ident, + "Test function 2", + FunctionType.SCALAR, + false, + Types.IntegerType.get(), + definitions2); + + // List functions + NameIdentifier[] functionIdents = functionOperations.listFunctions(getFunctionNamespace()); + Assertions.assertEquals(2, functionIdents.length); + Set<String> functionNames = + Arrays.stream(functionIdents).map(NameIdentifier::name).collect(Collectors.toSet()); + + Assertions.assertTrue(functionNames.contains("func1")); + Assertions.assertTrue(functionNames.contains("func2")); + } + + @Test + public void testRegisterAndGetFunction() { + NameIdentifier funcIdent = getFunctionIdent("my_func"); + FunctionParam[] params = + new FunctionParam[] {FunctionParams.of("input", Types.StringType.get())}; + FunctionDefinition[] definitions = new FunctionDefinition[] {createSimpleDefinition(params)}; + + Function newFunc = + functionOperations.registerFunction( + funcIdent, + "My test function", + FunctionType.SCALAR, + true, + Types.IntegerType.get(), + definitions); + + Assertions.assertEquals("my_func", newFunc.name()); + Assertions.assertEquals("My test function", newFunc.comment()); + Assertions.assertEquals(FunctionType.SCALAR, newFunc.functionType()); + Assertions.assertTrue(newFunc.deterministic()); + Assertions.assertEquals(Types.IntegerType.get(), newFunc.returnType()); + Assertions.assertEquals(0, newFunc.version()); + + // Get function (latest version) + Function loadedFunc = functionOperations.getFunction(funcIdent); + Assertions.assertEquals(newFunc.name(), loadedFunc.name()); + Assertions.assertEquals(newFunc.comment(), loadedFunc.comment()); + + // Test register function that already exists + Assertions.assertThrows( + FunctionAlreadyExistsException.class, + () -> + functionOperations.registerFunction( + funcIdent, + "Another function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions)); + + // Test get non-existing function + NameIdentifier nonExistingIdent = getFunctionIdent("non_existing_func"); + Assertions.assertThrows( + NoSuchFunctionException.class, () -> functionOperations.getFunction(nonExistingIdent)); + } + + @Test + public void testRegisterAndDropFunction() { + NameIdentifier funcIdent = getFunctionIdent("func_to_drop"); + FunctionParam[] params = new FunctionParam[] {FunctionParams.of("a", Types.IntegerType.get())}; + FunctionDefinition[] definitions = new FunctionDefinition[] {createSimpleDefinition(params)}; + + functionOperations.registerFunction( + funcIdent, + "Function to drop", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions); + + // Drop the function + boolean dropped = functionOperations.dropFunction(funcIdent); + Assertions.assertTrue(dropped); + + // Verify the function is dropped + Assertions.assertThrows( + NoSuchFunctionException.class, () -> functionOperations.getFunction(funcIdent)); + + // Test drop non-existing function + Assertions.assertFalse(functionOperations.dropFunction(funcIdent)); + } + + @Test + public void testRegisterFunctionWithOverlappingDefinitions() { + NameIdentifier funcIdent = getFunctionIdent("func_overlap_register"); + + // Try to register with two definitions that have overlapping arities + FunctionParam[] params1 = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get()), + FunctionParams.of("b", Types.FloatType.get(), null, Literals.floatLiteral(1.0f)) + }; + FunctionParam[] params2 = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get()), + FunctionParams.of("c", Types.StringType.get(), null, Literals.stringLiteral("x")) + }; + + FunctionDefinition[] definitions = + new FunctionDefinition[] {createSimpleDefinition(params1), createSimpleDefinition(params2)}; + + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + functionOperations.registerFunction( + funcIdent, + "Test function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions)); + } + + @Test + public void testInvalidParameterOrder() { + // Test that parameters with default values must appear at the end + NameIdentifier funcIdent = getFunctionIdent("func_invalid_params"); + + // Create params with invalid order: (a default 1, b required, c default 2) + FunctionParam[] invalidParams = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get(), "param a", Literals.integerLiteral(1)), + FunctionParams.of("b", Types.StringType.get()), // Required param after optional + FunctionParams.of("c", Types.IntegerType.get(), "param c", Literals.integerLiteral(2)) + }; + FunctionDefinition[] definitions = + new FunctionDefinition[] {createSimpleDefinition(invalidParams)}; + + // Should throw IllegalArgumentException when trying to register + IllegalArgumentException ex = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + functionOperations.registerFunction( + funcIdent, + "Invalid function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions)); + + Assertions.assertTrue( + ex.getMessage().contains("Invalid parameter order"), + "Expected error about invalid parameter order, got: " + ex.getMessage()); + Assertions.assertTrue( + ex.getMessage().contains("required parameter 'b'"), + "Expected error to mention parameter 'b', got: " + ex.getMessage()); + Assertions.assertTrue( + ex.getMessage().contains("position 1"), + "Expected error to mention position 1, got: " + ex.getMessage()); + + // Test with valid order: all optional params at the end + FunctionParam[] validParams = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get()), + FunctionParams.of("b", Types.StringType.get()), + FunctionParams.of("c", Types.IntegerType.get(), "param c", Literals.integerLiteral(1)), + FunctionParams.of("d", Types.IntegerType.get(), "param d", Literals.integerLiteral(2)) + }; + FunctionDefinition[] validDefinitions = + new FunctionDefinition[] {createSimpleDefinition(validParams)}; + + // This should succeed + functionOperations.registerFunction( + funcIdent, + "Valid function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + validDefinitions); + + // Verify the function was registered + Function func = functionOperations.getFunction(funcIdent); + Assertions.assertNotNull(func); + Assertions.assertEquals("Valid function", func.comment()); + } + + @Test + public void testNonOverlappingDefinitions() { + // Test that definitions with different arities can coexist + NameIdentifier funcIdent = getFunctionIdent("func_non_overlap"); + + // Two definitions with completely different parameter types (no overlap) + FunctionParam[] params1 = new FunctionParam[] {FunctionParams.of("a", Types.IntegerType.get())}; + FunctionParam[] params2 = new FunctionParam[] {FunctionParams.of("a", Types.StringType.get())}; + + FunctionDefinition[] definitions = + new FunctionDefinition[] {createSimpleDefinition(params1), createSimpleDefinition(params2)}; + + // Should succeed - no arity overlap + Function func = + functionOperations.registerFunction( + funcIdent, + "Non-overlapping function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions); + + Assertions.assertNotNull(func); + Assertions.assertEquals(2, func.definitions().length); + } + + @Test + public void testNoArgsFunction() { + // Test function with no parameters + NameIdentifier funcIdent = getFunctionIdent("func_no_args"); + + FunctionParam[] params = new FunctionParam[] {}; + FunctionDefinition[] definitions = new FunctionDefinition[] {createSimpleDefinition(params)}; + + Function func = + functionOperations.registerFunction( + funcIdent, + "No args function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions); + + Assertions.assertNotNull(func); + Assertions.assertEquals(0, func.definitions()[0].parameters().length); + } + + @Test + public void testMultipleDefaultParams() { + // Test function with multiple default parameters generates correct arities + NameIdentifier funcIdent = getFunctionIdent("func_multi_default"); + + // foo(int a, float b default 1.0, string c default 'x') + // Should generate arities: ["integer"], ["integer,float"], ["integer,float,string"] + FunctionParam[] params = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get()), + FunctionParams.of("b", Types.FloatType.get(), "param b", Literals.floatLiteral(1.0f)), + FunctionParams.of("c", Types.StringType.get(), "param c", Literals.stringLiteral("x")) + }; + FunctionDefinition[] definitions = new FunctionDefinition[] {createSimpleDefinition(params)}; + + Function func = + functionOperations.registerFunction( + funcIdent, + "Multi default function", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions); + + Assertions.assertNotNull(func); + Assertions.assertEquals(3, func.definitions()[0].parameters().length); + } + + @Test + public void testOverlappingAritiesWithDifferentTypes() { + // Test that two definitions with same arity count but different types don't overlap + NameIdentifier funcIdent = getFunctionIdent("func_same_arity_diff_types"); + + // foo(int, int) and foo(string, string) - same arity count but different types + FunctionParam[] params1 = + new FunctionParam[] { + FunctionParams.of("a", Types.IntegerType.get()), + FunctionParams.of("b", Types.IntegerType.get()) + }; + FunctionParam[] params2 = + new FunctionParam[] { + FunctionParams.of("a", Types.StringType.get()), + FunctionParams.of("b", Types.StringType.get()) + }; + + FunctionDefinition[] definitions = + new FunctionDefinition[] {createSimpleDefinition(params1), createSimpleDefinition(params2)}; + + // Should succeed - arities are "integer,integer" vs "string,string" + Function func = + functionOperations.registerFunction( + funcIdent, + "Same arity different types", + FunctionType.SCALAR, + true, + Types.StringType.get(), + definitions); + + Assertions.assertNotNull(func); + Assertions.assertEquals(2, func.definitions().length); + } + + @SuppressWarnings("unchecked") + private EntityStore createMockEntityStore() throws Exception { + EntityStore mockStore = mock(EntityStore.class); + + // Mock put operation + doAnswer( + invocation -> { + FunctionEntity entity = invocation.getArgument(0); + boolean overwrite = invocation.getArgument(1); + NameIdentifier ident = entity.nameIdentifier(); + + if (!overwrite && entityMap.containsKey(ident)) { + throw new EntityAlreadyExistsException("Entity %s already exists", ident); + } + entityMap.put(ident, entity); + return null; + }) + .when(mockStore) + .put(any(FunctionEntity.class), any(Boolean.class)); + + // Mock get operation + when(mockStore.get( + any(NameIdentifier.class), eq(Entity.EntityType.FUNCTION), eq(FunctionEntity.class))) + .thenAnswer( + invocation -> { + NameIdentifier ident = invocation.getArgument(0); + FunctionEntity entity = findEntityByIdent(ident); + if (entity == null) { + throw new NoSuchEntityException("Entity %s does not exist", ident); + } + return entity; + }); + + // Mock delete operation (2 parameters - default method that calls 3-parameter version) + when(mockStore.delete(any(NameIdentifier.class), eq(Entity.EntityType.FUNCTION))) + .thenAnswer( + invocation -> { + NameIdentifier ident = invocation.getArgument(0); + FunctionEntity entity = findEntityByIdent(ident); + if (entity == null) { + return false; + } + entityMap.remove(entity.nameIdentifier()); + return true; + }); + + // Mock list operation + when(mockStore.list( + any(Namespace.class), eq(FunctionEntity.class), eq(Entity.EntityType.FUNCTION))) + .thenAnswer( + invocation -> { + Namespace namespace = invocation.getArgument(0); + return entityMap.values().stream() + .filter(e -> e.namespace().equals(namespace)) + .collect(Collectors.toList()); + }); + + return mockStore; + } + + /** + * Finds an entity by identifier. This method handles both versioned identifiers (used by + * getFunction) and original identifiers (used by alterFunction and dropFunction). + * + * <p>Versioned identifier format: namespace = original_namespace + function_name, name = version + * Original identifier format: namespace = schema_namespace, name = function_name + */ + private FunctionEntity findEntityByIdent(NameIdentifier ident) { Review Comment: The documentation mentions "versioned identifiers" and "alterFunction" but the current implementation has removed version-based getFunction and alterFunction is not implemented (throws UnsupportedOperationException). This comment appears to be leftover from a previous design. Update the documentation to reflect the current implementation where only the original identifier format is used. ########## core/src/main/java/org/apache/gravitino/catalog/ManagedFunctionOperations.java: ########## @@ -131,7 +160,150 @@ public Function alterFunction(NameIdentifier ident, FunctionChange... changes) @Override public boolean dropFunction(NameIdentifier ident) { - // TODO: Implement when FunctionEntity is available - throw new UnsupportedOperationException("dropFunction: FunctionEntity not yet implemented"); + try { + return store.delete(ident, Entity.EntityType.FUNCTION); + } catch (NoSuchEntityException e) { + return false; + } catch (IOException e) { + throw new RuntimeException("Failed to drop function " + ident, e); + } + } + + private Function doRegisterFunction( + NameIdentifier ident, + String comment, + FunctionType functionType, + boolean deterministic, + Optional<Type> returnType, + Optional<FunctionColumn[]> returnColumns, + FunctionDefinition[] definitions) + throws NoSuchSchemaException, FunctionAlreadyExistsException { + Preconditions.checkArgument( + definitions != null && definitions.length > 0, + "At least one function definition must be provided"); + validateDefinitionsNoArityOverlap(definitions); + + String currentUser = PrincipalUtils.getCurrentUserName(); + Instant now = Instant.now(); + AuditInfo auditInfo = AuditInfo.builder().withCreator(currentUser).withCreateTime(now).build(); + + FunctionEntity functionEntity = + FunctionEntity.builder() + .withId(idGenerator.nextId()) + .withName(ident.name()) + .withNamespace(ident.namespace()) + .withComment(comment) + .withFunctionType(functionType) + .withDeterministic(deterministic) + .withReturnType(returnType.orElse(null)) + .withReturnColumns(returnColumns.orElse(null)) + .withDefinitions(definitions) + .withVersion(INIT_VERSION) + .withAuditInfo(auditInfo) + .build(); + + try { + store.put(functionEntity, false /* overwrite */); + return functionEntity; + + } catch (NoSuchEntityException e) { + throw new NoSuchSchemaException(e, "Schema %s does not exist", ident.namespace()); + } catch (EntityAlreadyExistsException e) { + throw new FunctionAlreadyExistsException(e, "Function %s already exists", ident); + } catch (IOException e) { + throw new RuntimeException("Failed to register function " + ident, e); + } + } + + /** + * Validates that all definitions in the array do not have overlapping arities. This is used when + * registering a function with multiple definitions. + * + * <p>Gravitino enforces strict validation to prevent ambiguity. Operations MUST fail if any + * definition's invocation arities overlap with another. For example, if an existing definition + * {@code foo(int, float default 1.0)} supports arities {@code (int)} and {@code (int, float)}, + * adding a new definition {@code foo(int, string default 'x')} (which supports {@code (int)} and + * {@code (int, string)}) will be REJECTED because both support the call {@code foo(1)}. This + * ensures every function invocation deterministically maps to a single definition. + * + * @param definitions The array of definitions to validate. + * @throws IllegalArgumentException If any two definitions have overlapping arities. + */ + private void validateDefinitionsNoArityOverlap(FunctionDefinition[] definitions) { Review Comment: The validation method has excellent documentation explaining the overlap detection logic. However, the computeArities method (line 268) also has comprehensive documentation. Consider adding a brief reference in this method's JavaDoc pointing to `computeArities` to help readers understand how arities are computed, e.g., "See {@link #computeArities(FunctionDefinition)} for details on how arity signatures are computed." -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
