Search in sources :

Example 1 with Scalar

use of io.crate.metadata.Scalar in project crate by crate.

the class CurrentSchemaFunctionTest method testEvaluateCurrentSchemaNotSupported.

public void testEvaluateCurrentSchemaNotSupported() throws Exception {
    expectedException.expect(UnsupportedOperationException.class);
    expectedException.expectMessage("Cannot evaluate CURRENT_SCHEMA function.");
    Function function = (Function) sqlExpressions.asSymbol("current_schema()");
    Scalar impl = (Scalar) functions.get(function.info().ident());
    impl.evaluate();
}
Also used : Function(io.crate.analyze.symbol.Function) Scalar(io.crate.metadata.Scalar)

Example 2 with Scalar

use of io.crate.metadata.Scalar in project crate by crate.

the class BaseImplementationSymbolVisitor method visitFunction.

@Override
public Input<?> visitFunction(Function function, C context) {
    final FunctionImplementation functionImplementation = functions.get(function.info().ident());
    if (functionImplementation instanceof Scalar<?, ?>) {
        List<Symbol> arguments = function.arguments();
        Scalar<?, ?> scalarImpl = ((Scalar) functionImplementation).compile(arguments);
        Input[] argumentInputs = new Input[arguments.size()];
        int i = 0;
        for (Symbol argument : function.arguments()) {
            argumentInputs[i++] = process(argument, context);
        }
        return new FunctionExpression<>(scalarImpl, argumentInputs);
    } else {
        throw new IllegalArgumentException(SymbolFormatter.format("Cannot find implementation for function %s", function));
    }
}
Also used : Input(io.crate.data.Input) FunctionExpression(io.crate.operation.aggregation.FunctionExpression) FunctionImplementation(io.crate.metadata.FunctionImplementation) Scalar(io.crate.metadata.Scalar)

Example 3 with Scalar

use of io.crate.metadata.Scalar in project crate by crate.

the class ScalarTestCase method assertEvaluate.

/**
 * asserts that the given functionExpression matches the given matcher.
 * If the functionExpression contains references the inputs will be used in the order the references appear.
 * <p>
 * E.g.
 * <code>
 * assertEvaluate("foo(name, age)", anyOf("expectedValue1", "expectedValue2"), inputForName, inputForAge)
 * </code>
 */
@SuppressWarnings("unchecked")
public <T> void assertEvaluate(String functionExpression, Matcher<T> expectedValue, Literal<?>... literals) {
    if (expectedValue == null) {
        expectedValue = (Matcher<T>) nullValue();
    }
    sqlExpressions.context().allowEagerNormalize(true);
    Symbol functionSymbol = sqlExpressions.asSymbol(functionExpression);
    functionSymbol = sqlExpressions.normalize(functionSymbol);
    if (functionSymbol instanceof Literal) {
        Object value = ((Literal) functionSymbol).value();
        assertThat((T) value, expectedValue);
        return;
    }
    LinkedList<Literal<?>> unusedLiterals = new LinkedList<>(Arrays.asList(literals));
    Function function = (Function) RefReplacer.replaceRefs(functionSymbol, r -> {
        if (unusedLiterals.isEmpty()) {
            throw new IllegalArgumentException("No value literal for reference=" + r + ", please add more literals");
        }
        // Can be null.
        Literal<?> literal = unusedLiterals.pollFirst();
        return literal;
    });
    if (unusedLiterals.size() == literals.length) {
        // Currently it's supposed that literals will be either references or parameters.
        // One of replaceRefs and bindParameters does nothing and doesn't consume unusedLiterals.
        function = (Function) ParameterBinder.bindParameters(function, p -> {
            if (unusedLiterals.isEmpty()) {
                throw new IllegalArgumentException("No value literal for parameter=" + p + ", please add more literals");
            }
            // Can be null.
            Literal<?> literal = unusedLiterals.pollFirst();
            return literal;
        });
    }
    Scalar scalar = (Scalar) sqlExpressions.nodeCtx.functions().getQualified(function, txnCtx.sessionSettings().searchPath());
    assertThat("Function implementation not found using full qualified lookup", scalar, Matchers.notNullValue());
    AssertMax1ValueCallInput[] arguments = new AssertMax1ValueCallInput[function.arguments().size()];
    InputFactory.Context<CollectExpression<Row, ?>> ctx = inputFactory.ctxForInputColumns(txnCtx);
    for (int i = 0; i < function.arguments().size(); i++) {
        Symbol arg = function.arguments().get(i);
        Input<?> input = ctx.add(arg);
        arguments[i] = new AssertMax1ValueCallInput(input);
    }
    Object actualValue = scalar.compile(function.arguments()).evaluate(txnCtx, sqlExpressions.nodeCtx, (Input[]) arguments);
    assertThat((T) actualValue, expectedValue);
    // Reset calls
    for (AssertMax1ValueCallInput argument : arguments) {
        argument.calls = 0;
    }
    actualValue = scalar.evaluate(txnCtx, sqlExpressions.nodeCtx, arguments);
    assertThat((T) actualValue, expectedValue);
}
Also used : Input(io.crate.data.Input) TransactionContext(io.crate.metadata.TransactionContext) SqlExpressions(io.crate.testing.SqlExpressions) InputColumn(io.crate.expression.symbol.InputColumn) Arrays(java.util.Arrays) ParameterBinder(io.crate.expression.symbol.ParameterBinder) RelationName(io.crate.metadata.RelationName) SessionSettings(io.crate.metadata.settings.SessionSettings) CollectExpression(io.crate.execution.engine.collect.CollectExpression) Matchers.not(org.hamcrest.Matchers.not) SearchPath(io.crate.metadata.SearchPath) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) RefReplacer(io.crate.expression.symbol.RefReplacer) Locale(java.util.Locale) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Is.is(org.hamcrest.core.Is.is) SQLExecutor(io.crate.testing.SQLExecutor) LinkedList(java.util.LinkedList) Before(org.junit.Before) DocTableInfo(io.crate.metadata.doc.DocTableInfo) DataType(io.crate.types.DataType) Matchers(org.hamcrest.Matchers) Function(io.crate.expression.symbol.Function) Lists2(io.crate.common.collections.Lists2) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) DocTableRelation(io.crate.analyze.relations.DocTableRelation) Row(io.crate.data.Row) Literal(io.crate.expression.symbol.Literal) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) DocSchemaInfo(io.crate.metadata.doc.DocSchemaInfo) Matcher(org.hamcrest.Matcher) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) InputFactory(io.crate.expression.InputFactory) Scalar(io.crate.metadata.Scalar) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) InputFactory(io.crate.expression.InputFactory) Symbol(io.crate.expression.symbol.Symbol) CollectExpression(io.crate.execution.engine.collect.CollectExpression) LinkedList(java.util.LinkedList) Scalar(io.crate.metadata.Scalar) Function(io.crate.expression.symbol.Function) Input(io.crate.data.Input) Literal(io.crate.expression.symbol.Literal)

Example 4 with Scalar

use of io.crate.metadata.Scalar in project crate by crate.

the class SimpleTopNProjectorTest method testFunctionExpression.

@Test
public void testFunctionExpression() throws Throwable {
    Scalar floor = (Scalar) TestingHelpers.getFunctions().get(new FunctionIdent("floor", Collections.<DataType>singletonList(DataTypes.DOUBLE)));
    FunctionExpression<Number, ?> funcExpr = new FunctionExpression<>(floor, new Input[] { input });
    Projector projector = new SimpleTopNProjector(ImmutableList.<Input<?>>of(funcExpr), COLLECT_EXPRESSIONS, 10, TopN.NO_OFFSET);
    Iterable<Row> rows = RowGenerator.fromSingleColValues(() -> IntStream.range(0, 12).mapToDouble(i -> 42.3d).iterator());
    BatchIterator batchIterator = projector.apply(RowsBatchIterator.newInstance(rows, 1));
    consumer.accept(batchIterator, null);
    Bucket result = consumer.getBucket();
    assertThat(result.size(), is(10));
    assertThat(result.iterator().next(), isRow(42L));
}
Also used : FunctionIdent(io.crate.metadata.FunctionIdent) FunctionExpression(io.crate.operation.aggregation.FunctionExpression) TestingHelpers.isRow(io.crate.testing.TestingHelpers.isRow) Scalar(io.crate.metadata.Scalar) Test(org.junit.Test) CrateUnitTest(io.crate.test.integration.CrateUnitTest)

Example 5 with Scalar

use of io.crate.metadata.Scalar in project crate by crate.

the class AbstractTableFunctionsTest method assertCompile.

public void assertCompile(String functionExpression, java.util.function.Function<Scalar, Matcher<Scalar>> matcher) {
    Symbol functionSymbol = sqlExpressions.asSymbol(functionExpression);
    functionSymbol = sqlExpressions.normalize(functionSymbol);
    assertThat("function expression was normalized, compile would not be hit", functionSymbol, not(instanceOf(Literal.class)));
    Function function = (Function) functionSymbol;
    Scalar scalar = (Scalar) sqlExpressions.nodeCtx.functions().getQualified(function, txnCtx.sessionSettings().searchPath());
    assertThat("Function implementation not found using full qualified lookup", scalar, Matchers.notNullValue());
    Scalar compiled = scalar.compile(function.arguments());
    assertThat(compiled, matcher.apply(scalar));
}
Also used : Function(io.crate.expression.symbol.Function) Symbol(io.crate.expression.symbol.Symbol) Scalar(io.crate.metadata.Scalar)

Aggregations

Scalar (io.crate.metadata.Scalar)10 Input (io.crate.data.Input)6 Symbol (io.crate.expression.symbol.Symbol)5 Function (io.crate.expression.symbol.Function)4 FunctionImplementation (io.crate.metadata.FunctionImplementation)4 TransactionContext (io.crate.metadata.TransactionContext)3 Literal (io.crate.expression.symbol.Literal)2 NodeContext (io.crate.metadata.NodeContext)2 Signature (io.crate.metadata.functions.Signature)2 FunctionExpression (io.crate.operation.aggregation.FunctionExpression)2 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)2 List (java.util.List)2 Map (java.util.Map)2 Matchers (org.hamcrest.Matchers)2 Before (org.junit.Before)2 Test (org.junit.Test)2 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)1 DocTableRelation (io.crate.analyze.relations.DocTableRelation)1 Function (io.crate.analyze.symbol.Function)1 Lists2 (io.crate.common.collections.Lists2)1