Search in sources :

Example 11 with UserFunctionSignature

use of org.neo4j.internal.kernel.api.procs.UserFunctionSignature in project neo4j by neo4j.

the class ProcedureCompilationTest method shouldExposeUserFunctionSignature.

@Test
void shouldExposeUserFunctionSignature() throws ProcedureException {
    // Given
    UserFunctionSignature signature = functionSignature("test", "foo").out(NTInteger).build();
    // When
    CallableUserFunction function = compileFunction(signature, emptyList(), method("longMethod"));
    // Then
    assertEquals(function.signature(), signature);
}
Also used : CallableUserFunction(org.neo4j.kernel.api.procedure.CallableUserFunction) UserFunctionSignature(org.neo4j.internal.kernel.api.procs.UserFunctionSignature) Test(org.junit.jupiter.api.Test)

Example 12 with UserFunctionSignature

use of org.neo4j.internal.kernel.api.procs.UserFunctionSignature in project neo4j by neo4j.

the class ProcedureCompilation method compileFunction.

/**
 * Generates code for a user-defined function.
 * <p>
 * Given a user-defined function defined by
 *
 * <pre>
 *     class MyClass {
 *       {@literal @}Context
 *        public Log log;
 *
 *       {@literal @}UserFunction
 *        public double addPi(long value) {
 *            return value + Math.PI;
 *        }
 *     }
 * </pre>
 * <p>
 * we will generate something like
 *
 * <pre>
 *     class GeneratedAddPi implements CallableUserFunction {
 *         public static UserFunctionSignature SIGNATURE;
 *         public static FieldSetter SETTER_0;
 *
 *         public AnyValue apply(Context ctx, AnyValue[] input) {
 *              try {
 *                  MyClass userClass = new MyClass();
 *                  userClass.log = (Log) SETTER_0.get(ctx);
 *                  return Values.doubleValue(userClass.addPi( ((NumberValue) input[0]).longValue() );
 *              } catch (Throwable T) {
 *                  throw new ProcedureException([appropriate error msg], T);
 *              }
 *         }
 *
 *         public UserFunctionSignature signature() {return SIGNATURE;}
 *     }
 * </pre>
 * <p>
 * where the static fields are set once during loading via reflection.
 *
 * @param signature the signature of the user-defined function
 * @param fieldSetters the fields to set before each call.
 * @param methodToCall the method to call
 * @return a CallableUserFunction delegating to the underlying user-defined function.
 * @throws ProcedureException if something went wrong when compiling the user-defined function.
 */
static CallableUserFunction compileFunction(UserFunctionSignature signature, List<FieldSetter> fieldSetters, Method methodToCall) throws ProcedureException {
    ClassHandle handle;
    try {
        CodeGenerator codeGenerator = codeGenerator();
        try (ClassGenerator generator = codeGenerator.generateClass(PACKAGE, className(signature), CallableUserFunction.class)) {
            // static fields
            FieldReference signatureField = generator.publicStaticField(typeReference(UserFunctionSignature.class), SIGNATURE_NAME);
            List<FieldReference> fieldsToSet = createContextSetters(fieldSetters, generator);
            // CallableUserFunction::apply
            try (CodeBlock method = generator.generate(USER_FUNCTION)) {
                method.tryCatch(body -> functionBody(body, fieldSetters, fieldsToSet, methodToCall), onError -> onError(onError, format("function `%s`", signature.name())), param(Throwable.class, "T"));
            }
            // CallableUserFunction::signature
            try (CodeBlock method = generator.generateMethod(UserFunctionSignature.class, "signature")) {
                method.returns(getStatic(signatureField));
            }
            handle = generator.handle();
        }
        Class<?> clazz = handle.loadClass();
        // set all static fields
        setAllStaticFields(signature, fieldSetters, methodToCall, clazz);
        return (CallableUserFunction) clazz.getConstructor().newInstance();
    } catch (Throwable e) {
        throw new ProcedureException(Status.Procedure.ProcedureRegistrationFailed, e, "Failed to compile function defined in `%s`: %s", methodToCall.getDeclaringClass().getSimpleName(), e.getMessage());
    }
}
Also used : CallableUserFunction(org.neo4j.kernel.api.procedure.CallableUserFunction) ClassGenerator(org.neo4j.codegen.ClassGenerator) FieldReference(org.neo4j.codegen.FieldReference) CodeBlock(org.neo4j.codegen.CodeBlock) CodeGenerator(org.neo4j.codegen.CodeGenerator) ProcedureException(org.neo4j.internal.kernel.api.exceptions.ProcedureException) UserFunctionSignature(org.neo4j.internal.kernel.api.procs.UserFunctionSignature) ClassHandle(org.neo4j.codegen.ClassHandle)

Example 13 with UserFunctionSignature

use of org.neo4j.internal.kernel.api.procs.UserFunctionSignature in project neo4j by neo4j.

the class ProcedureCompiler method compileFunction.

private CallableUserFunction compileFunction(Class<?> procDefinition, Method method, QualifiedName procName) throws ProcedureException {
    restrictions.verify(procName);
    List<FieldSignature> inputSignature = inputSignatureDeterminer.signatureFor(method);
    Class<?> returnType = method.getReturnType();
    TypeCheckers.TypeChecker typeChecker = typeCheckers.checkerFor(returnType);
    String description = description(method);
    UserFunction function = method.getAnnotation(UserFunction.class);
    String deprecated = deprecated(method, function::deprecatedBy, "Use of @UserFunction(deprecatedBy) without @Deprecated in " + procName);
    List<FieldSetter> setters = allFieldInjections.setters(procDefinition);
    if (!config.fullAccessFor(procName.toString())) {
        try {
            setters = safeFieldInjections.setters(procDefinition);
        } catch (ComponentInjectionException e) {
            description = describeAndLogLoadFailure(procName);
            UserFunctionSignature signature = new UserFunctionSignature(procName, inputSignature, typeChecker.type(), deprecated, config.rolesFor(procName.toString()), description, null, false);
            return new FailedLoadFunction(signature);
        }
    }
    UserFunctionSignature signature = new UserFunctionSignature(procName, inputSignature, typeChecker.type(), deprecated, config.rolesFor(procName.toString()), description, null, false);
    return ProcedureCompilation.compileFunction(signature, setters, method);
}
Also used : FieldSignature(org.neo4j.internal.kernel.api.procs.FieldSignature) UserFunctionSignature(org.neo4j.internal.kernel.api.procs.UserFunctionSignature) FailedLoadFunction(org.neo4j.kernel.api.procedure.FailedLoadFunction) CallableUserFunction(org.neo4j.kernel.api.procedure.CallableUserFunction) UserFunction(org.neo4j.procedure.UserFunction) ComponentInjectionException(org.neo4j.kernel.api.exceptions.ComponentInjectionException)

Example 14 with UserFunctionSignature

use of org.neo4j.internal.kernel.api.procs.UserFunctionSignature in project neo4j by neo4j.

the class ProcedureRegistry method register.

/**
 * Register a new function.
 *
 * @param function the function.
 */
public void register(CallableUserAggregationFunction function, boolean overrideCurrentImplementation, boolean builtIn) throws ProcedureException {
    UserFunctionSignature signature = function.signature();
    QualifiedName name = signature.name();
    if (functions.get(name) != null) {
        throw new ProcedureException(Status.Procedure.ProcedureRegistrationFailed, "Unable to register aggregation function, because the name `%s` is already in use as a function.", name);
    }
    CallableUserAggregationFunction oldImplementation = aggregationFunctions.get(name);
    if (oldImplementation == null) {
        aggregationFunctions.put(name, function, signature.caseInsensitive());
    } else {
        if (overrideCurrentImplementation) {
            aggregationFunctions.put(name, function, signature.caseInsensitive());
        } else {
            throw new ProcedureException(Status.Procedure.ProcedureRegistrationFailed, "Unable to register aggregation function, because the name `%s` is already in use.", name);
        }
    }
    if (builtIn) {
        builtInAggregatingFunctionIds.add(aggregationFunctions.idOf(name));
    }
}
Also used : CallableUserAggregationFunction(org.neo4j.kernel.api.procedure.CallableUserAggregationFunction) QualifiedName(org.neo4j.internal.kernel.api.procs.QualifiedName) ProcedureException(org.neo4j.internal.kernel.api.exceptions.ProcedureException) UserFunctionSignature(org.neo4j.internal.kernel.api.procs.UserFunctionSignature)

Example 15 with UserFunctionSignature

use of org.neo4j.internal.kernel.api.procs.UserFunctionSignature in project neo4j by neo4j.

the class ProcedureCompilation method compileAggregation.

/**
 * Generates code for a user-defined aggregation function.
 * <p>
 * Given a user-defined aggregation function defined by
 *
 * <pre>
 *     class MyClass {
 *       {@literal @}Context
 *        public Log log;
 *
 *       {@literal @}UserAggregationFunction
 *        public Adder create() {
 *            return new Adder;
 *        }
 *     }
 *
 *     class Adder {
 *       private long sum;
 *       {@literal @}UserAggregationUpdate
 *       public void update(long in) {
 *           sum += in;
 *       }
 *       {@literal @}UserAggregationResult
 *       public long result() {
 *         return sum;
 *       }
 *    }
 *     }
 * </pre>
 * <p>
 * we will generate two classe looking something like
 *
 * <pre>
 *     class Generated implements CallableUserAggregationFunction {
 *         public static UserFunctionSignature SIGNATURE;
 *         public static FieldSetter SETTER_0;
 *
 *         public UserAggregator create(Context ctx) {
 *              try {
 *                  MyClass userClass = new MyClass();
 *                  userClass.log = (Log) SETTER_0.get(ctx);
 *                  return new GeneratedAdder(userClass.create());
 *              } catch (Throwable T) {
 *                  throw new ProcedureException([appropriate error msg], T);
 *              }
 *         }
 *
 *         public UserFunctionSignature signature() {return SIGNATURE;}
 *     }
 *     class GeneratedAdder implements UserAggregator {
 *       private Adder adder;
 *
 *       GeneratedAdder(Adder adder) {
 *         this.adder = adder;
 *       }
 *
 *       void update(AnyValue[] in) {
 *          adder.update(((NumberValue) in).longValue());
 *       }
 *
 *       AnyValue result() {
 *          return adder.result(Values.longValue(adder.result());
 *       }
 *     }
 * </pre>
 * <p>
 * where the static fields are set once during loading via reflection.
 *
 * @param signature the signature of the user-defined function
 * @param fieldSetters the fields to set before each call.
 * @param create the method that creates the aggregator
 * @param update the update method of the aggregator
 * @param result the result method of the aggregator
 * @return a CallableUserFunction delegating to the underlying user-defined function.
 * @throws ProcedureException if something went wrong when compiling the user-defined function.
 */
static CallableUserAggregationFunction compileAggregation(UserFunctionSignature signature, List<FieldSetter> fieldSetters, Method create, Method update, Method result) throws ProcedureException {
    ClassHandle handle;
    try {
        CodeGenerator codeGenerator = codeGenerator();
        Class<?> aggregator = generateAggregator(codeGenerator, update, result, signature);
        try (ClassGenerator generator = codeGenerator.generateClass(PACKAGE, className(signature), CallableUserAggregationFunction.class)) {
            // static fields
            FieldReference signatureField = generator.publicStaticField(typeReference(UserFunctionSignature.class), SIGNATURE_NAME);
            List<FieldReference> fieldsToSet = createContextSetters(fieldSetters, generator);
            // CallableUserAggregationFunction::create
            try (CodeBlock method = generator.generate(AGGREGATION_CREATE)) {
                method.tryCatch(body -> createAggregationBody(body, fieldSetters, fieldsToSet, create, aggregator), onError -> onError(onError, format("function `%s`", signature.name())), param(Throwable.class, "T"));
            }
            // CallableUserFunction::signature
            try (CodeBlock method = generator.generateMethod(UserFunctionSignature.class, "signature")) {
                method.returns(getStatic(signatureField));
            }
            handle = generator.handle();
        }
        Class<?> clazz = handle.loadClass();
        // set all static fields
        setAllStaticFields(signature, fieldSetters, create, clazz);
        return (CallableUserAggregationFunction) clazz.getConstructor().newInstance();
    } catch (Throwable e) {
        throw new ProcedureException(Status.Procedure.ProcedureRegistrationFailed, e, "Failed to compile function defined in `%s`: %s", create.getDeclaringClass().getSimpleName(), e.getMessage());
    }
}
Also used : ClassGenerator(org.neo4j.codegen.ClassGenerator) FieldReference(org.neo4j.codegen.FieldReference) CallableUserAggregationFunction(org.neo4j.kernel.api.procedure.CallableUserAggregationFunction) CodeBlock(org.neo4j.codegen.CodeBlock) CodeGenerator(org.neo4j.codegen.CodeGenerator) ProcedureException(org.neo4j.internal.kernel.api.exceptions.ProcedureException) UserFunctionSignature(org.neo4j.internal.kernel.api.procs.UserFunctionSignature) ClassHandle(org.neo4j.codegen.ClassHandle)

Aggregations

UserFunctionSignature (org.neo4j.internal.kernel.api.procs.UserFunctionSignature)22 Test (org.junit.jupiter.api.Test)16 CallableUserFunction (org.neo4j.kernel.api.procedure.CallableUserFunction)13 AnyValue (org.neo4j.values.AnyValue)7 CallableUserAggregationFunction (org.neo4j.kernel.api.procedure.CallableUserAggregationFunction)6 ProcedureException (org.neo4j.internal.kernel.api.exceptions.ProcedureException)5 UserAggregator (org.neo4j.internal.kernel.api.procs.UserAggregator)4 Method (java.lang.reflect.Method)3 NTString (org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTString)3 Arrays.asList (java.util.Arrays.asList)2 Collections.emptyList (java.util.Collections.emptyList)2 Collections.singletonList (java.util.Collections.singletonList)2 List (java.util.List)2 ClassGenerator (org.neo4j.codegen.ClassGenerator)2 ClassHandle (org.neo4j.codegen.ClassHandle)2 CodeBlock (org.neo4j.codegen.CodeBlock)2 CodeGenerator (org.neo4j.codegen.CodeGenerator)2 FieldReference (org.neo4j.codegen.FieldReference)2 FieldSignature (org.neo4j.internal.kernel.api.procs.FieldSignature)2 NTList (org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTList)2