Search in sources :

Example 1 with Param

use of org.apache.drill.exec.expr.annotations.Param in project drill by apache.

the class InterpreterEvaluator method evaluateFunction.

public static ValueHolder evaluateFunction(DrillSimpleFunc interpreter, ValueHolder[] args, String funcName) throws Exception {
    Preconditions.checkArgument(interpreter != null, "interpreter could not be null when use interpreted model to evaluate function " + funcName);
    // the current input index to assign into the next available parameter, found using the @Param notation
    // the order parameters are declared in the java class for the DrillFunc is meaningful
    int currParameterIndex = 0;
    Field outField = null;
    try {
        Field[] fields = interpreter.getClass().getDeclaredFields();
        for (Field f : fields) {
            // if this is annotated as a parameter to the function
            if (f.getAnnotation(Param.class) != null) {
                f.setAccessible(true);
                if (currParameterIndex < args.length) {
                    f.set(interpreter, args[currParameterIndex]);
                }
                currParameterIndex++;
            } else if (f.getAnnotation(Output.class) != null) {
                f.setAccessible(true);
                outField = f;
                // create an instance of the holder for the output to be stored in
                f.set(interpreter, f.getType().newInstance());
            }
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    if (args.length != currParameterIndex) {
        throw new DrillRuntimeException(String.format("Wrong number of parameters provided to interpreted expression evaluation " + "for function %s, expected %d parameters, but received %d.", funcName, currParameterIndex, args.length));
    }
    if (outField == null) {
        throw new DrillRuntimeException("Malformed DrillFunction without a return type: " + funcName);
    }
    interpreter.setup();
    interpreter.eval();
    ValueHolder out = (ValueHolder) outField.get(interpreter);
    return out;
}
Also used : Field(java.lang.reflect.Field) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) Param(org.apache.drill.exec.expr.annotations.Param) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder)

Example 2 with Param

use of org.apache.drill.exec.expr.annotations.Param in project drill by axbaretto.

the class FunctionConverter method getHolder.

public <T extends DrillFunc> DrillFuncHolder getHolder(AnnotatedClassDescriptor func, ClassLoader classLoader) {
    FunctionTemplate template = func.getAnnotationProxy(FunctionTemplate.class);
    if (template == null) {
        return failure("Class does not declare FunctionTemplate annotation.", func);
    }
    String name = template.name();
    List<String> names = Arrays.asList(template.names());
    if (name.isEmpty() && names.isEmpty()) {
        // none set
        return failure("Must define 'name' or 'names'", func);
    }
    if (!name.isEmpty() && !names.isEmpty()) {
        // both are set
        return failure("Must use only one annotations 'name' or 'names', not both", func);
    }
    // start by getting field information.
    List<ValueReference> params = Lists.newArrayList();
    List<WorkspaceReference> workspaceFields = Lists.newArrayList();
    ValueReference outputField = null;
    for (FieldDescriptor field : func.getFields()) {
        Param param = field.getAnnotationProxy(Param.class);
        Output output = field.getAnnotationProxy(Output.class);
        Workspace workspace = field.getAnnotationProxy(Workspace.class);
        Inject inject = field.getAnnotationProxy(Inject.class);
        Annotation[] annotations = { param, output, workspace, inject };
        int annotationCount = 0;
        for (Annotation annotationDescriptor : annotations) {
            if (annotationDescriptor != null) {
                annotationCount += 1;
            }
        }
        if (annotationCount == 0) {
            return failure("The field must be either a @Param, @Output, @Inject or @Workspace field.", func, field);
        } else if (annotationCount > 1) {
            return failure("The field must be only one of @Param, @Output, @Inject or @Workspace. It currently has more than one of these annotations.", func, field);
        }
        // TODO(Julien): verify there are a few of those and we can load them
        Class<?> fieldClass = field.getFieldClass();
        if (param != null || output != null) {
            // Special processing for @Param FieldReader
            if (param != null && FieldReader.class.isAssignableFrom(fieldClass)) {
                params.add(ValueReference.createFieldReaderRef(field.getName()));
                continue;
            }
            // Special processing for @Output ComplexWriter
            if (output != null && ComplexWriter.class.isAssignableFrom(fieldClass)) {
                if (outputField != null) {
                    return failure("You've declared more than one @Output field.  You must declare one and only @Output field per Function class.", func, field);
                } else {
                    outputField = ValueReference.createComplexWriterRef(field.getName());
                }
                continue;
            }
            // check that param and output are value holders.
            if (!ValueHolder.class.isAssignableFrom(fieldClass)) {
                return failure(String.format("The field doesn't holds value of type %s which does not implement the ValueHolder interface.  All fields of type @Param or @Output must extend this interface..", fieldClass), func, field);
            }
            // get the type field from the value holder.
            MajorType type = null;
            try {
                type = getStaticFieldValue("TYPE", fieldClass, MajorType.class);
            } catch (Exception e) {
                return failure("Failure while trying to access the ValueHolder's TYPE static variable.  All ValueHolders must contain a static TYPE variable that defines their MajorType.", e, func, field);
            }
            ValueReference p = new ValueReference(type, field.getName());
            if (param != null) {
                p.setConstant(param.constant());
                params.add(p);
            } else {
                if (outputField != null) {
                    return failure("You've declared more than one @Output field.  You must declare one and only @Output field per Function class.", func, field);
                } else {
                    outputField = p;
                }
            }
        } else {
            // workspace work.
            boolean isInject = inject != null;
            if (isInject && UdfUtilities.INJECTABLE_GETTER_METHODS.get(fieldClass) == null) {
                return failure(String.format("A %s cannot be injected into a %s," + " available injectable classes are: %s.", fieldClass, DrillFunc.class.getSimpleName(), Joiner.on(",").join(UdfUtilities.INJECTABLE_GETTER_METHODS.keySet())), func, field);
            }
            WorkspaceReference wsReference = new WorkspaceReference(fieldClass, field.getName(), isInject);
            if (!isInject && template.scope() == FunctionScope.POINT_AGGREGATE && !ValueHolder.class.isAssignableFrom(fieldClass)) {
                return failure(String.format("Aggregate function '%s' workspace variable '%s' is of type '%s'. Please change it to Holder type.", func.getClassName(), field.getName(), fieldClass), func, field);
            }
            // If the workspace var is of Holder type, get its MajorType and assign to WorkspaceReference.
            if (ValueHolder.class.isAssignableFrom(fieldClass)) {
                MajorType majorType = null;
                try {
                    majorType = getStaticFieldValue("TYPE", fieldClass, MajorType.class);
                } catch (Exception e) {
                    return failure("Failure while trying to access the ValueHolder's TYPE static variable.  All ValueHolders must contain a static TYPE variable that defines their MajorType.", e, func, field);
                }
                wsReference.setMajorType(majorType);
            }
            workspaceFields.add(wsReference);
        }
    }
    if (outputField == null) {
        return failure("This function declares zero output fields.  A function must declare one output field.", func);
    }
    FunctionInitializer initializer = new FunctionInitializer(func.getClassName(), classLoader);
    try {
        // return holder
        ValueReference[] ps = params.toArray(new ValueReference[params.size()]);
        WorkspaceReference[] works = workspaceFields.toArray(new WorkspaceReference[workspaceFields.size()]);
        FunctionAttributes functionAttributes = new FunctionAttributes(template, ps, outputField, works);
        switch(template.scope()) {
            case POINT_AGGREGATE:
                return new DrillAggFuncHolder(functionAttributes, initializer);
            case SIMPLE:
                return outputField.isComplexWriter() ? new DrillComplexWriterFuncHolder(functionAttributes, initializer) : new DrillSimpleFuncHolder(functionAttributes, initializer);
            case HOLISTIC_AGGREGATE:
            case RANGE_AGGREGATE:
            default:
                return failure("Unsupported Function Type.", func);
        }
    } catch (Exception | NoSuchFieldError | AbstractMethodError ex) {
        return failure("Failure while creating function holder.", ex, func);
    }
}
Also used : ComplexWriter(org.apache.drill.exec.vector.complex.writer.BaseWriter.ComplexWriter) FieldDescriptor(org.apache.drill.common.scanner.persistence.FieldDescriptor) FunctionTemplate(org.apache.drill.exec.expr.annotations.FunctionTemplate) Output(org.apache.drill.exec.expr.annotations.Output) Inject(javax.inject.Inject) MajorType(org.apache.drill.common.types.TypeProtos.MajorType) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder) Annotation(java.lang.annotation.Annotation) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) Param(org.apache.drill.exec.expr.annotations.Param) FieldReader(org.apache.drill.exec.vector.complex.reader.FieldReader) Workspace(org.apache.drill.exec.expr.annotations.Workspace)

Example 3 with Param

use of org.apache.drill.exec.expr.annotations.Param in project drill by axbaretto.

the class InterpreterEvaluator method evaluateFunction.

public static ValueHolder evaluateFunction(DrillSimpleFunc interpreter, ValueHolder[] args, String funcName) throws Exception {
    Preconditions.checkArgument(interpreter != null, "interpreter could not be null when use interpreted model to evaluate function " + funcName);
    // the current input index to assign into the next available parameter, found using the @Param notation
    // the order parameters are declared in the java class for the DrillFunc is meaningful
    int currParameterIndex = 0;
    Field outField = null;
    try {
        Field[] fields = interpreter.getClass().getDeclaredFields();
        for (Field f : fields) {
            // if this is annotated as a parameter to the function
            if (f.getAnnotation(Param.class) != null) {
                f.setAccessible(true);
                if (currParameterIndex < args.length) {
                    f.set(interpreter, args[currParameterIndex]);
                }
                currParameterIndex++;
            } else if (f.getAnnotation(Output.class) != null) {
                f.setAccessible(true);
                outField = f;
                // create an instance of the holder for the output to be stored in
                f.set(interpreter, f.getType().newInstance());
            }
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    if (args.length != currParameterIndex) {
        throw new DrillRuntimeException(String.format("Wrong number of parameters provided to interpreted expression evaluation " + "for function %s, expected %d parameters, but received %d.", funcName, currParameterIndex, args.length));
    }
    if (outField == null) {
        throw new DrillRuntimeException("Malformed DrillFunction without a return type: " + funcName);
    }
    interpreter.setup();
    interpreter.eval();
    ValueHolder out = (ValueHolder) outField.get(interpreter);
    return out;
}
Also used : Field(java.lang.reflect.Field) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) Param(org.apache.drill.exec.expr.annotations.Param) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder)

Example 4 with Param

use of org.apache.drill.exec.expr.annotations.Param in project drill by apache.

the class FunctionConverter method getHolder.

public DrillFuncHolder getHolder(AnnotatedClassDescriptor func, ClassLoader classLoader) {
    FunctionTemplate template = func.getAnnotationProxy(FunctionTemplate.class);
    if (template == null) {
        return failure("Class does not declare FunctionTemplate annotation.", func);
    }
    String name = template.name();
    List<String> names = Arrays.asList(template.names());
    if (name.isEmpty() && names.isEmpty()) {
        // none set
        return failure("Must define 'name' or 'names'", func);
    }
    if (!name.isEmpty() && !names.isEmpty()) {
        // both are set
        return failure("Must use only one annotations 'name' or 'names', not both", func);
    }
    // start by getting field information.
    List<ValueReference> params = Lists.newArrayList();
    List<WorkspaceReference> workspaceFields = Lists.newArrayList();
    ValueReference outputField = null;
    int varArgsCount = 0;
    for (FieldDescriptor field : func.getFields()) {
        Param param = field.getAnnotationProxy(Param.class);
        Output output = field.getAnnotationProxy(Output.class);
        Workspace workspace = field.getAnnotationProxy(Workspace.class);
        Inject inject = field.getAnnotationProxy(Inject.class);
        Annotation[] annotations = { param, output, workspace, inject };
        int annotationCount = 0;
        for (Annotation annotationDescriptor : annotations) {
            if (annotationDescriptor != null) {
                annotationCount += 1;
            }
        }
        if (annotationCount == 0) {
            return failure("The field must be either a @Param, @Output, @Inject or @Workspace field.", func, field);
        } else if (annotationCount > 1) {
            return failure("The field must be only one of @Param, @Output, @Inject or @Workspace. It currently has more than one of these annotations.", func, field);
        }
        // TODO(Julien): verify there are a few of those and we can load them
        Class<?> fieldClass = field.getFieldClass();
        if (param != null || output != null) {
            if (Object[].class.isAssignableFrom(fieldClass)) {
                fieldClass = fieldClass.getComponentType();
                varArgsCount++;
            } else if (varArgsCount > 0 && param != null) {
                return failure("Vararg should be the last argument in the function.", func, field);
            }
            if (varArgsCount > 1) {
                return failure("Function should contain single vararg argument", func, field);
            }
            // Special processing for @Param FieldReader
            if (param != null && FieldReader.class.isAssignableFrom(fieldClass)) {
                ValueReference fieldReaderRef = ValueReference.createFieldReaderRef(field.getName());
                fieldReaderRef.setVarArg(varArgsCount > 0);
                params.add(fieldReaderRef);
                continue;
            }
            // Special processing for @Output ComplexWriter
            if (output != null && ComplexWriter.class.isAssignableFrom(fieldClass)) {
                if (outputField != null) {
                    return failure("You've declared more than one @Output field.\n" + "You must declare one and only @Output field per Function class.", func, field);
                } else {
                    outputField = ValueReference.createComplexWriterRef(field.getName());
                }
                continue;
            }
            // check that param and output are value holders.
            if (!ValueHolder.class.isAssignableFrom(fieldClass)) {
                return failure(String.format("The field doesn't holds value of type %s which does not implement the ValueHolder or ComplexWriter interfaces.\n" + "All fields of type @Param or @Output must extend this interface.", fieldClass), func, field);
            }
            // get the type field from the value holder.
            MajorType type;
            try {
                type = getStaticFieldValue("TYPE", fieldClass, MajorType.class);
            } catch (Exception e) {
                return failure("Failure while trying to access the ValueHolder's TYPE static variable.  All ValueHolders must contain a static TYPE variable that defines their MajorType.", e, func, field);
            }
            ValueReference p = new ValueReference(type, field.getName());
            if (param != null) {
                p.setConstant(param.constant());
                p.setVarArg(varArgsCount > 0);
                params.add(p);
            } else {
                if (outputField != null) {
                    return failure("You've declared more than one @Output field.  You must declare one and only @Output field per Function class.", func, field);
                } else {
                    outputField = p;
                }
            }
        } else {
            // workspace work.
            boolean isInject = inject != null;
            if (isInject && UdfUtilities.INJECTABLE_GETTER_METHODS.get(fieldClass) == null) {
                return failure(String.format("A %s cannot be injected into a %s," + " available injectable classes are: %s.", fieldClass, DrillFunc.class.getSimpleName(), Joiner.on(",").join(UdfUtilities.INJECTABLE_GETTER_METHODS.keySet())), func, field);
            }
            WorkspaceReference wsReference = new WorkspaceReference(fieldClass, field.getName(), isInject);
            if (!isInject && template.scope() == FunctionScope.POINT_AGGREGATE && !ValueHolder.class.isAssignableFrom(fieldClass)) {
                return failure(String.format("Aggregate function '%s' workspace variable '%s' is of type '%s'. Please change it to Holder type.", func.getClassName(), field.getName(), fieldClass), func, field);
            }
            // If the workspace var is of Holder type, get its MajorType and assign to WorkspaceReference.
            if (ValueHolder.class.isAssignableFrom(fieldClass)) {
                MajorType majorType;
                try {
                    majorType = getStaticFieldValue("TYPE", fieldClass, MajorType.class);
                } catch (Exception e) {
                    return failure("Failure while trying to access the ValueHolder's TYPE static variable.  All ValueHolders must contain a static TYPE variable that defines their MajorType.", e, func, field);
                }
                wsReference.setMajorType(majorType);
            }
            workspaceFields.add(wsReference);
        }
    }
    if (outputField == null) {
        return failure("This function declares zero output fields.  A function must declare one output field.", func);
    }
    FunctionInitializer initializer = new FunctionInitializer(func.getClassName(), classLoader);
    try {
        // return holder
        ValueReference[] ps = params.toArray(new ValueReference[0]);
        WorkspaceReference[] works = workspaceFields.toArray(new WorkspaceReference[0]);
        FunctionAttributes functionAttributes = new FunctionAttributes(template, ps, outputField, works);
        switch(template.scope()) {
            case POINT_AGGREGATE:
                return outputField.isComplexWriter() ? new DrillComplexWriterAggFuncHolder(functionAttributes, initializer) : new DrillAggFuncHolder(functionAttributes, initializer);
            case SIMPLE:
                return outputField.isComplexWriter() ? new DrillComplexWriterFuncHolder(functionAttributes, initializer) : new DrillSimpleFuncHolder(functionAttributes, initializer);
            case HOLISTIC_AGGREGATE:
            case RANGE_AGGREGATE:
            default:
                return failure("Unsupported Function Type.", func);
        }
    } catch (Exception | NoSuchFieldError | AbstractMethodError ex) {
        return failure("Failure while creating function holder.", ex, func);
    }
}
Also used : ComplexWriter(org.apache.drill.exec.vector.complex.writer.BaseWriter.ComplexWriter) FieldDescriptor(org.apache.drill.common.scanner.persistence.FieldDescriptor) FunctionTemplate(org.apache.drill.exec.expr.annotations.FunctionTemplate) Output(org.apache.drill.exec.expr.annotations.Output) Inject(javax.inject.Inject) MajorType(org.apache.drill.common.types.TypeProtos.MajorType) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder) Annotation(java.lang.annotation.Annotation) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) Param(org.apache.drill.exec.expr.annotations.Param) FieldReader(org.apache.drill.exec.vector.complex.reader.FieldReader) Workspace(org.apache.drill.exec.expr.annotations.Workspace)

Example 5 with Param

use of org.apache.drill.exec.expr.annotations.Param in project drill by apache.

the class InterpreterEvaluator method evaluateFunction.

/**
 * Assigns specified {@code Object[] args} to the function arguments,
 * evaluates function and returns its result.
 *
 * @param interpreter function to be evaluated
 * @param args        function arguments
 * @param funcName    name of the function
 * @return result of function call stored in {@link ValueHolder}
 * @throws Exception if {@code args} types does not match function input arguments types
 */
public static ValueHolder evaluateFunction(DrillSimpleFunc interpreter, Object[] args, String funcName) throws Exception {
    Preconditions.checkArgument(interpreter != null, "interpreter could not be null when use interpreted model to evaluate function " + funcName);
    // the current input index to assign into the next available parameter, found using the @Param notation
    // the order parameters are declared in the java class for the DrillFunc is meaningful
    int currParameterIndex = 0;
    Field outField = null;
    try {
        Field[] fields = interpreter.getClass().getDeclaredFields();
        for (Field f : fields) {
            // if this is annotated as a parameter to the function
            if (f.getAnnotation(Param.class) != null) {
                f.setAccessible(true);
                if (f.getType().getComponentType() != null) {
                    Object array = Array.newInstance(f.getType().getComponentType(), args.length - currParameterIndex);
                    for (int i = 0; i < args.length - currParameterIndex; i++) {
                        Array.set(array, i, args[currParameterIndex + i]);
                    }
                    currParameterIndex = args.length;
                    f.set(interpreter, array);
                } else if (currParameterIndex < args.length) {
                    f.set(interpreter, args[currParameterIndex]);
                    currParameterIndex++;
                }
            } else if (f.getAnnotation(Output.class) != null) {
                f.setAccessible(true);
                outField = f;
                // create an instance of the holder for the output to be stored in
                f.set(interpreter, f.getType().newInstance());
            }
        }
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    if (args.length != currParameterIndex) {
        throw new DrillRuntimeException(String.format("Wrong number of parameters provided to interpreted expression evaluation " + "for function %s, expected %d parameters, but received %d.", funcName, currParameterIndex, args.length));
    }
    if (outField == null) {
        throw new DrillRuntimeException("Malformed DrillFunction without a return type: " + funcName);
    }
    interpreter.setup();
    interpreter.eval();
    return (ValueHolder) outField.get(interpreter);
}
Also used : Field(java.lang.reflect.Field) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) Param(org.apache.drill.exec.expr.annotations.Param) DrillRuntimeException(org.apache.drill.common.exceptions.DrillRuntimeException) ValueHolder(org.apache.drill.exec.expr.holders.ValueHolder)

Aggregations

DrillRuntimeException (org.apache.drill.common.exceptions.DrillRuntimeException)5 Param (org.apache.drill.exec.expr.annotations.Param)5 ValueHolder (org.apache.drill.exec.expr.holders.ValueHolder)5 Field (java.lang.reflect.Field)3 Annotation (java.lang.annotation.Annotation)2 Inject (javax.inject.Inject)2 FieldDescriptor (org.apache.drill.common.scanner.persistence.FieldDescriptor)2 MajorType (org.apache.drill.common.types.TypeProtos.MajorType)2 FunctionTemplate (org.apache.drill.exec.expr.annotations.FunctionTemplate)2 Output (org.apache.drill.exec.expr.annotations.Output)2 Workspace (org.apache.drill.exec.expr.annotations.Workspace)2 FieldReader (org.apache.drill.exec.vector.complex.reader.FieldReader)2 ComplexWriter (org.apache.drill.exec.vector.complex.writer.BaseWriter.ComplexWriter)2