Search in sources :

Example 56 with Function

use of io.crate.expression.symbol.Function in project crate by crate.

the class RelationAnalyzer method visitValues.

@Override
public AnalyzedRelation visitValues(Values values, StatementAnalysisContext context) {
    var expressionAnalyzer = new ExpressionAnalyzer(context.transactionContext(), nodeCtx, context.paramTyeHints(), FieldProvider.UNSUPPORTED, new SubqueryAnalyzer(this, context));
    var expressionAnalysisContext = new ExpressionAnalysisContext(context.sessionContext());
    // prevent normalization of the values array, otherwise the value literals are converted to an array literal
    // and a special per-value-literal casting logic won't be executed (e.g. FloatLiteral.cast())
    expressionAnalysisContext.allowEagerNormalize(false);
    java.util.function.Function<Expression, Symbol> expressionToSymbol = e -> expressionAnalyzer.convert(e, expressionAnalysisContext);
    // There is a first pass to convert expressions from row oriented format:
    // `[[1, a], [2, b]]` to columns `[[1, 2], [a, b]]`
    // 
    // At the same time we determine the column type with the highest precedence,
    // so that we don't fail with slight type miss-matches (long vs. int)
    List<ValuesList> rows = values.rows();
    assert rows.size() > 0 : "Parser grammar enforces at least 1 row";
    ValuesList firstRow = rows.get(0);
    int numColumns = firstRow.values().size();
    ArrayList<List<Symbol>> columns = new ArrayList<>();
    ArrayList<DataType<?>> targetTypes = new ArrayList<>(numColumns);
    var parentOutputColumns = context.parentOutputColumns();
    for (int c = 0; c < numColumns; c++) {
        ArrayList<Symbol> columnValues = new ArrayList<>();
        DataType<?> targetType;
        boolean usePrecedence = true;
        if (parentOutputColumns.size() > c) {
            targetType = parentOutputColumns.get(c).valueType();
            usePrecedence = false;
        } else {
            targetType = DataTypes.UNDEFINED;
        }
        for (int r = 0; r < rows.size(); r++) {
            List<Expression> row = rows.get(r).values();
            if (row.size() != numColumns) {
                throw new IllegalArgumentException("VALUES lists must all be the same length. " + "Found row with " + numColumns + " items and another with " + columns.size() + " items");
            }
            Symbol cell = expressionToSymbol.apply(row.get(c));
            columnValues.add(cell);
            var cellType = cell.valueType();
            if (// skip first cell, we don't have to check for self-conversion
            r > 0 && !cellType.isConvertableTo(targetType, false) && targetType.id() != DataTypes.UNDEFINED.id()) {
                throw new IllegalArgumentException("The types of the columns within VALUES lists must match. " + "Found `" + targetType + "` and `" + cellType + "` at position: " + c);
            }
            if (usePrecedence && cellType.precedes(targetType)) {
                targetType = cellType;
            } else if (targetType == DataTypes.UNDEFINED) {
                targetType = cellType;
            }
        }
        targetTypes.add(targetType);
        columns.add(columnValues);
    }
    var normalizer = EvaluatingNormalizer.functionOnlyNormalizer(nodeCtx, f -> f.isDeterministic());
    ArrayList<Symbol> arrays = new ArrayList<>(columns.size());
    for (int c = 0; c < numColumns; c++) {
        DataType<?> targetType = targetTypes.get(c);
        ArrayType<?> arrayType = new ArrayType<>(targetType);
        List<Symbol> columnValues = Lists2.map(columns.get(c), s -> normalizer.normalize(s.cast(targetType), context.transactionContext()));
        arrays.add(new Function(ArrayFunction.SIGNATURE, columnValues, arrayType));
    }
    FunctionImplementation implementation = nodeCtx.functions().getQualified(ValuesFunction.SIGNATURE, Symbols.typeView(arrays), RowType.EMPTY);
    Function function = new Function(implementation.signature(), arrays, RowType.EMPTY);
    TableFunctionImplementation<?> tableFunc = TableFunctionFactory.from(implementation);
    TableFunctionRelation relation = new TableFunctionRelation(tableFunc, function);
    context.startRelation();
    context.currentRelationContext().addSourceRelation(relation);
    context.endRelation();
    return relation;
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) JoinCriteria(io.crate.sql.tree.JoinCriteria) UnsupportedFeatureException(io.crate.exceptions.UnsupportedFeatureException) RelationName(io.crate.metadata.RelationName) RowType(io.crate.types.RowType) DefaultTraversalVisitor(io.crate.sql.tree.DefaultTraversalVisitor) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) Node(io.crate.sql.tree.Node) ArrayType(io.crate.types.ArrayType) JoinType(io.crate.planner.node.dql.join.JoinType) JoinOn(io.crate.sql.tree.JoinOn) Locale(java.util.Locale) Map(java.util.Map) SelectAnalysis(io.crate.analyze.relations.select.SelectAnalysis) ValuesList(io.crate.sql.tree.ValuesList) Union(io.crate.sql.tree.Union) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) SortItem(io.crate.sql.tree.SortItem) Collection(java.util.Collection) QuerySpecification(io.crate.sql.tree.QuerySpecification) TableSubquery(io.crate.sql.tree.TableSubquery) Set(java.util.Set) SelectAnalyzer(io.crate.analyze.relations.select.SelectAnalyzer) Intersect(io.crate.sql.tree.Intersect) WhereClauseValidator(io.crate.analyze.where.WhereClauseValidator) Iterables(io.crate.common.collections.Iterables) Lists2(io.crate.common.collections.Lists2) Relation(io.crate.sql.tree.Relation) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) DataTypes(io.crate.types.DataTypes) Singleton(org.elasticsearch.common.inject.Singleton) Values(io.crate.sql.tree.Values) Optional(java.util.Optional) Expression(io.crate.sql.tree.Expression) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) SemanticSortValidator(io.crate.analyze.validator.SemanticSortValidator) AmbiguousColumnAliasException(io.crate.exceptions.AmbiguousColumnAliasException) Tuple(io.crate.common.collections.Tuple) SubqueryAnalyzer(io.crate.analyze.expressions.SubqueryAnalyzer) FunctionCall(io.crate.sql.tree.FunctionCall) QualifiedNameReference(io.crate.sql.tree.QualifiedNameReference) QueriedSelectRelation(io.crate.analyze.QueriedSelectRelation) SearchPath(io.crate.metadata.SearchPath) Operation(io.crate.metadata.table.Operation) HavingSymbolValidator(io.crate.analyze.validator.HavingSymbolValidator) AliasedRelation(io.crate.sql.tree.AliasedRelation) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ValuesFunction(io.crate.expression.tablefunctions.ValuesFunction) Join(io.crate.sql.tree.Join) Symbols(io.crate.expression.symbol.Symbols) SqlParser(io.crate.sql.parser.SqlParser) Query(io.crate.sql.tree.Query) QualifiedName(io.crate.sql.tree.QualifiedName) TableFunction(io.crate.sql.tree.TableFunction) Nullable(javax.annotation.Nullable) RelationValidationException(io.crate.exceptions.RelationValidationException) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) OrderByWithAggregationValidator(io.crate.planner.consumer.OrderByWithAggregationValidator) ViewMetadata(io.crate.metadata.view.ViewMetadata) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) TableFunctionFactory(io.crate.expression.tablefunctions.TableFunctionFactory) Table(io.crate.sql.tree.Table) DataType(io.crate.types.DataType) Function(io.crate.expression.symbol.Function) GroupAndAggregateSemantics(io.crate.expression.symbol.GroupAndAggregateSemantics) JoinUsing(io.crate.sql.tree.JoinUsing) TableFunctionImplementation(io.crate.metadata.tablefunctions.TableFunctionImplementation) Except(io.crate.sql.tree.Except) Literal(io.crate.expression.symbol.Literal) GroupBySymbolValidator(io.crate.analyze.validator.GroupBySymbolValidator) ColumnUnknownException(io.crate.exceptions.ColumnUnknownException) Schemas(io.crate.metadata.Schemas) RelationUnknown(io.crate.exceptions.RelationUnknown) Collections(java.util.Collections) ExpressionAnalysisContext(io.crate.analyze.expressions.ExpressionAnalysisContext) Symbol(io.crate.expression.symbol.Symbol) ExpressionAnalyzer(io.crate.analyze.expressions.ExpressionAnalyzer) ArrayList(java.util.ArrayList) ArrayType(io.crate.types.ArrayType) ValuesFunction(io.crate.expression.tablefunctions.ValuesFunction) TableFunction(io.crate.sql.tree.TableFunction) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) Function(io.crate.expression.symbol.Function) DataType(io.crate.types.DataType) ValuesList(io.crate.sql.tree.ValuesList) List(java.util.List) ArrayList(java.util.ArrayList) FunctionImplementation(io.crate.metadata.FunctionImplementation) TableFunctionImplementation(io.crate.metadata.tablefunctions.TableFunctionImplementation) ValuesList(io.crate.sql.tree.ValuesList) Expression(io.crate.sql.tree.Expression) SubqueryAnalyzer(io.crate.analyze.expressions.SubqueryAnalyzer)

Example 57 with Function

use of io.crate.expression.symbol.Function in project crate by crate.

the class ExpressionAnalyzer method allocateBuiltinOrUdfFunction.

/**
 * Creates a function symbol and tries to normalize the new function's
 * {@link FunctionImplementation} iff only Literals are supplied as arguments.
 * This folds any constant expressions like '1 + 1' => '2'.
 * @param schema The schema for udf functions
 * @param functionName The function name of the new function.
 * @param arguments The arguments to provide to the {@link Function}.
 * @param filter The filter clause to filter {@link Function}'s input values.
 * @param context Context holding the state for the current translation.
 * @param windowDefinition The definition of the window the allocated function will be executed against.
 * @param coordinatorTxnCtx {@link CoordinatorTxnCtx} for this transaction.
 * @param nodeCtx The {@link NodeContext} to normalize constant expressions.
 * @return The supplied {@link Function} or a {@link Literal} in case of constant folding.
 */
private static Symbol allocateBuiltinOrUdfFunction(@Nullable String schema, String functionName, List<Symbol> arguments, @Nullable Symbol filter, @Nullable Boolean ignoreNulls, ExpressionAnalysisContext context, @Nullable WindowDefinition windowDefinition, CoordinatorTxnCtx coordinatorTxnCtx, NodeContext nodeCtx) {
    FunctionImplementation funcImpl = nodeCtx.functions().get(schema, functionName, arguments, coordinatorTxnCtx.sessionContext().searchPath());
    Signature signature = funcImpl.signature();
    Signature boundSignature = funcImpl.boundSignature();
    List<Symbol> castArguments = cast(arguments, boundSignature.getArgumentDataTypes());
    Function newFunction;
    if (windowDefinition == null) {
        if (signature.getKind() == FunctionType.AGGREGATE) {
            context.indicateAggregates();
        } else if (filter != null) {
            throw new UnsupportedOperationException("Only aggregate functions allow a FILTER clause");
        }
        if (ignoreNulls != null) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH, "%s cannot accept RESPECT or IGNORE NULLS flag.", functionName));
        }
        newFunction = new Function(signature, castArguments, boundSignature.getReturnType().createType(), filter);
    } else {
        if (signature.getKind() != FunctionType.WINDOW) {
            if (signature.getKind() != FunctionType.AGGREGATE) {
                throw new IllegalArgumentException(String.format(Locale.ENGLISH, "OVER clause was specified, but %s is neither a window nor an aggregate function.", functionName));
            } else {
                if (ignoreNulls != null) {
                    throw new IllegalArgumentException(String.format(Locale.ENGLISH, "%s cannot accept RESPECT or IGNORE NULLS flag.", functionName));
                }
            }
        }
        newFunction = new WindowFunction(signature, castArguments, boundSignature.getReturnType().createType(), filter, windowDefinition, ignoreNulls);
    }
    return newFunction;
}
Also used : CurrentDateFunction(io.crate.expression.scalar.CurrentDateFunction) MapFunction(io.crate.expression.scalar.arithmetic.MapFunction) CurrentTimestampFunction(io.crate.expression.scalar.timestamp.CurrentTimestampFunction) WindowFunction(io.crate.expression.symbol.WindowFunction) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) CurrentTimeFunction(io.crate.expression.scalar.timestamp.CurrentTimeFunction) IfFunction(io.crate.expression.scalar.conditional.IfFunction) ArraySliceFunction(io.crate.expression.scalar.ArraySliceFunction) Function(io.crate.expression.symbol.Function) SubscriptFunction(io.crate.expression.scalar.SubscriptFunction) WindowFunction(io.crate.expression.symbol.WindowFunction) SelectSymbol(io.crate.expression.symbol.SelectSymbol) ScopedSymbol(io.crate.expression.symbol.ScopedSymbol) Symbol(io.crate.expression.symbol.Symbol) Signature(io.crate.metadata.functions.Signature) FunctionImplementation(io.crate.metadata.FunctionImplementation)

Example 58 with Function

use of io.crate.expression.symbol.Function in project crate by crate.

the class ExpressionAnalyzer method convertFunctionCall.

private Symbol convertFunctionCall(FunctionCall node, ExpressionAnalysisContext context) {
    List<Symbol> arguments = new ArrayList<>(node.getArguments().size());
    for (Expression expression : node.getArguments()) {
        Symbol argSymbol = expression.accept(innerAnalyzer, context);
        arguments.add(argSymbol);
    }
    List<String> parts = node.getName().getParts();
    // We don't set a default schema here because no supplied schema
    // means that we first try to lookup builtin functions, followed
    // by a lookup in the default schema for UDFs.
    String schema = null;
    String name;
    if (parts.size() == 1) {
        name = parts.get(0);
    } else {
        schema = parts.get(0);
        name = parts.get(1);
    }
    Symbol filter = node.filter().map(expression -> convert(expression, context)).orElse(null);
    WindowDefinition windowDefinition = getWindowDefinition(node.getWindow(), context);
    if (node.isDistinct()) {
        if (arguments.size() > 1) {
            throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "%s(DISTINCT x) does not accept more than one argument", node.getName()));
        }
        Symbol collectSetFunction = allocateFunction(CollectSetAggregation.NAME, arguments, filter, context, coordinatorTxnCtx, nodeCtx);
        // define the outer function which contains the inner function as argument.
        String nodeName = "collection_" + name;
        List<Symbol> outerArguments = List.of(collectSetFunction);
        try {
            return allocateBuiltinOrUdfFunction(schema, nodeName, outerArguments, null, node.ignoreNulls(), windowDefinition, context);
        } catch (UnsupportedOperationException ex) {
            throw new UnsupportedOperationException(String.format(Locale.ENGLISH, "unknown function %s(DISTINCT %s)", name, arguments.get(0).valueType()), ex);
        }
    } else {
        return allocateBuiltinOrUdfFunction(schema, name, arguments, filter, node.ignoreNulls(), windowDefinition, context);
    }
}
Also used : ParamTypeHints(io.crate.analyze.ParamTypeHints) NullLiteral(io.crate.sql.tree.NullLiteral) ArrayLikePredicate(io.crate.sql.tree.ArrayLikePredicate) EvaluatingNormalizer(io.crate.expression.eval.EvaluatingNormalizer) LikeOperators(io.crate.expression.operator.LikeOperators) IntervalParser(io.crate.interval.IntervalParser) SubscriptExpression(io.crate.sql.tree.SubscriptExpression) NegateFunctions(io.crate.expression.scalar.arithmetic.NegateFunctions) ExpressionFormatter(io.crate.sql.ExpressionFormatter) BetweenPredicate(io.crate.sql.tree.BetweenPredicate) Map(java.util.Map) ArrayLiteral(io.crate.sql.tree.ArrayLiteral) IntervalLiteral(io.crate.sql.tree.IntervalLiteral) AstVisitor(io.crate.sql.tree.AstVisitor) NotPredicate(io.crate.expression.predicate.NotPredicate) EscapedCharStringLiteral(io.crate.sql.tree.EscapedCharStringLiteral) CastMode(io.crate.expression.scalar.cast.CastMode) UndefinedType(io.crate.types.UndefinedType) TryCast(io.crate.sql.tree.TryCast) CurrentDateFunction(io.crate.expression.scalar.CurrentDateFunction) IfExpression(io.crate.sql.tree.IfExpression) NotExpression(io.crate.sql.tree.NotExpression) ObjectLiteral(io.crate.sql.tree.ObjectLiteral) HOUR(io.crate.sql.tree.IntervalLiteral.IntervalField.HOUR) MINUTE(io.crate.sql.tree.IntervalLiteral.IntervalField.MINUTE) SemanticSortValidator(io.crate.analyze.validator.SemanticSortValidator) FunctionCall(io.crate.sql.tree.FunctionCall) OrderyByAnalyzer(io.crate.analyze.relations.OrderyByAnalyzer) Extract(io.crate.sql.tree.Extract) SearchedCaseExpression(io.crate.sql.tree.SearchedCaseExpression) Operation(io.crate.metadata.table.Operation) InPredicate(io.crate.sql.tree.InPredicate) Operator(io.crate.expression.operator.Operator) ArrayList(java.util.ArrayList) CurrentTime(io.crate.sql.tree.CurrentTime) AndOperator(io.crate.expression.operator.AndOperator) BooleanLiteral(io.crate.sql.tree.BooleanLiteral) WindowFrameDefinition(io.crate.analyze.WindowFrameDefinition) QualifiedName(io.crate.sql.tree.QualifiedName) Nullable(javax.annotation.Nullable) MatchPredicate(io.crate.sql.tree.MatchPredicate) LogicalBinaryExpression(io.crate.sql.tree.LogicalBinaryExpression) CollectSetAggregation(io.crate.execution.engine.aggregation.impl.CollectSetAggregation) IsNullPredicate(io.crate.sql.tree.IsNullPredicate) ArraySliceExpression(io.crate.sql.tree.ArraySliceExpression) SubscriptFunctions(io.crate.expression.scalar.SubscriptFunctions) Reference(io.crate.metadata.Reference) IntegerLiteral(io.crate.sql.tree.IntegerLiteral) RecordSubscript(io.crate.sql.tree.RecordSubscript) Literal(io.crate.expression.symbol.Literal) BitStringType(io.crate.types.BitStringType) RegexpMatchCaseInsensitiveOperator(io.crate.expression.operator.RegexpMatchCaseInsensitiveOperator) AnalyzedRelation(io.crate.analyze.relations.AnalyzedRelation) ConversionException(io.crate.exceptions.ConversionException) ArraySubQueryExpression(io.crate.sql.tree.ArraySubQueryExpression) DoubleLiteral(io.crate.sql.tree.DoubleLiteral) SimpleCaseExpression(io.crate.sql.tree.SimpleCaseExpression) SubscriptContext(io.crate.analyze.SubscriptContext) MapFunction(io.crate.expression.scalar.arithmetic.MapFunction) ExtractFunctions(io.crate.expression.scalar.ExtractFunctions) AllOperator(io.crate.expression.operator.AllOperator) RelationName(io.crate.metadata.RelationName) FieldProvider(io.crate.analyze.relations.FieldProvider) SubqueryExpression(io.crate.sql.tree.SubqueryExpression) IsNotNullPredicate(io.crate.sql.tree.IsNotNullPredicate) Node(io.crate.sql.tree.Node) CurrentTimestampFunction(io.crate.expression.scalar.timestamp.CurrentTimestampFunction) ArrayType(io.crate.types.ArrayType) OrOperator(io.crate.expression.operator.OrOperator) NegateLiterals(io.crate.analyze.NegateLiterals) Locale(java.util.Locale) SelectSymbol(io.crate.expression.symbol.SelectSymbol) ScopedSymbol(io.crate.expression.symbol.ScopedSymbol) InListExpression(io.crate.sql.tree.InListExpression) SECOND(io.crate.sql.tree.IntervalLiteral.IntervalField.SECOND) YEAR(io.crate.sql.tree.IntervalLiteral.IntervalField.YEAR) Window(io.crate.sql.tree.Window) ArrayComparison(io.crate.sql.tree.ArrayComparison) NodeContext(io.crate.metadata.NodeContext) ParameterExpression(io.crate.sql.tree.ParameterExpression) Collection(java.util.Collection) EqOperator(io.crate.expression.operator.EqOperator) Signature(io.crate.metadata.functions.Signature) Lists2(io.crate.common.collections.Lists2) ArrayComparisonExpression(io.crate.sql.tree.ArrayComparisonExpression) BitString(io.crate.sql.tree.BitString) AnyOperator(io.crate.expression.operator.any.AnyOperator) List(java.util.List) OrderBy(io.crate.analyze.OrderBy) Symbol(io.crate.expression.symbol.Symbol) FunctionImplementation(io.crate.metadata.FunctionImplementation) DataTypes(io.crate.types.DataTypes) WindowFunction(io.crate.expression.symbol.WindowFunction) Optional(java.util.Optional) Expression(io.crate.sql.tree.Expression) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) StringLiteral(io.crate.sql.tree.StringLiteral) WindowFrame(io.crate.sql.tree.WindowFrame) LongLiteral(io.crate.sql.tree.LongLiteral) QualifiedNameReference(io.crate.sql.tree.QualifiedNameReference) HashMap(java.util.HashMap) RegexpMatchOperator(io.crate.expression.operator.RegexpMatchOperator) FrameBoundDefinition(io.crate.analyze.FrameBoundDefinition) MatchPredicateColumnIdent(io.crate.sql.tree.MatchPredicateColumnIdent) ComparisonExpression(io.crate.sql.tree.ComparisonExpression) HashSet(java.util.HashSet) SubscriptValidator(io.crate.analyze.SubscriptValidator) ArithmeticExpression(io.crate.sql.tree.ArithmeticExpression) Cast(io.crate.sql.tree.Cast) DAY(io.crate.sql.tree.IntervalLiteral.IntervalField.DAY) MONTH(io.crate.sql.tree.IntervalLiteral.IntervalField.MONTH) Symbols(io.crate.expression.symbol.Symbols) SqlParser(io.crate.sql.parser.SqlParser) Nonnull(javax.annotation.Nonnull) NegativeExpression(io.crate.sql.tree.NegativeExpression) WhenClause(io.crate.sql.tree.WhenClause) ArrayFunction(io.crate.expression.scalar.arithmetic.ArrayFunction) CurrentTimeFunction(io.crate.expression.scalar.timestamp.CurrentTimeFunction) LikePredicate(io.crate.sql.tree.LikePredicate) Period(org.joda.time.Period) IfFunction(io.crate.expression.scalar.conditional.IfFunction) ArraySliceFunction(io.crate.expression.scalar.ArraySliceFunction) DataType(io.crate.types.DataType) Function(io.crate.expression.symbol.Function) SubscriptFunction(io.crate.expression.scalar.SubscriptFunction) Collectors.toList(java.util.stream.Collectors.toList) WindowDefinition(io.crate.analyze.WindowDefinition) FunctionType(io.crate.metadata.FunctionType) DataTypeAnalyzer(io.crate.analyze.DataTypeAnalyzer) ColumnUnknownException(io.crate.exceptions.ColumnUnknownException) FrameBound(io.crate.sql.tree.FrameBound) SubscriptExpression(io.crate.sql.tree.SubscriptExpression) IfExpression(io.crate.sql.tree.IfExpression) NotExpression(io.crate.sql.tree.NotExpression) SearchedCaseExpression(io.crate.sql.tree.SearchedCaseExpression) LogicalBinaryExpression(io.crate.sql.tree.LogicalBinaryExpression) ArraySliceExpression(io.crate.sql.tree.ArraySliceExpression) ArraySubQueryExpression(io.crate.sql.tree.ArraySubQueryExpression) SimpleCaseExpression(io.crate.sql.tree.SimpleCaseExpression) SubqueryExpression(io.crate.sql.tree.SubqueryExpression) InListExpression(io.crate.sql.tree.InListExpression) ParameterExpression(io.crate.sql.tree.ParameterExpression) ArrayComparisonExpression(io.crate.sql.tree.ArrayComparisonExpression) Expression(io.crate.sql.tree.Expression) ComparisonExpression(io.crate.sql.tree.ComparisonExpression) ArithmeticExpression(io.crate.sql.tree.ArithmeticExpression) NegativeExpression(io.crate.sql.tree.NegativeExpression) SelectSymbol(io.crate.expression.symbol.SelectSymbol) ScopedSymbol(io.crate.expression.symbol.ScopedSymbol) Symbol(io.crate.expression.symbol.Symbol) ArrayList(java.util.ArrayList) BitString(io.crate.sql.tree.BitString) WindowDefinition(io.crate.analyze.WindowDefinition)

Example 59 with Function

use of io.crate.expression.symbol.Function in project crate by crate.

the class SelectStatementAnalyzerTest method testWhereInSelect.

@Test
public void testWhereInSelect() throws Exception {
    var executor = SQLExecutor.builder(clusterService).build();
    QueriedSelectRelation relation = executor.analyze("select load from sys.nodes where load['1'] in (1.0, 2.0, 4.0, 8.0, 16.0)");
    Function whereClause = (Function) relation.where();
    assertThat(whereClause.name(), is(AnyEqOperator.NAME));
}
Also used : DistanceFunction(io.crate.expression.scalar.geo.DistanceFunction) SymbolMatchers.isFunction(io.crate.testing.SymbolMatchers.isFunction) TryCastFunction(io.crate.expression.scalar.cast.TryCastFunction) ExplicitCastFunction(io.crate.expression.scalar.cast.ExplicitCastFunction) Function(io.crate.expression.symbol.Function) SubscriptFunction(io.crate.expression.scalar.SubscriptFunction) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Example 60 with Function

use of io.crate.expression.symbol.Function in project crate by crate.

the class SelectStatementAnalyzerTest method testNonDeterministicFunctionsAreNotAllocated.

@Test
public void testNonDeterministicFunctionsAreNotAllocated() throws Exception {
    var executor = SQLExecutor.builder(clusterService).addTable(TableDefinitions.TEST_DOC_TRANSACTIONS_TABLE_DEFINITION).build();
    QueriedSelectRelation relation = executor.analyze("select random(), random(), random() " + "from transactions " + "where random() = 13.2 " + "order by 1, random(), random()");
    List<Symbol> outputs = relation.outputs();
    List<Symbol> orderBySymbols = relation.orderBy().orderBySymbols();
    // non deterministic, all equal
    assertThat(outputs.get(0), allOf(equalTo(outputs.get(2)), equalTo(orderBySymbols.get(1))));
    // different instances
    assertThat(outputs.get(0), allOf(not(Matchers.sameInstance(outputs.get(2))), not(Matchers.sameInstance(orderBySymbols.get(1)))));
    assertThat(outputs.get(1), equalTo(orderBySymbols.get(2)));
    // "order by 1" references output 1, its the same
    assertThat(outputs.get(0), is(equalTo(orderBySymbols.get(0))));
    assertThat(outputs.get(0), is(Matchers.sameInstance(orderBySymbols.get(0))));
    assertThat(orderBySymbols.get(0), is(equalTo(orderBySymbols.get(1))));
    // check where clause
    Function eqFunction = (Function) relation.where();
    Symbol whereClauseSleepFn = eqFunction.arguments().get(0);
    assertThat(outputs.get(0), is(equalTo(whereClauseSleepFn)));
}
Also used : DistanceFunction(io.crate.expression.scalar.geo.DistanceFunction) SymbolMatchers.isFunction(io.crate.testing.SymbolMatchers.isFunction) TryCastFunction(io.crate.expression.scalar.cast.TryCastFunction) ExplicitCastFunction(io.crate.expression.scalar.cast.ExplicitCastFunction) Function(io.crate.expression.symbol.Function) SubscriptFunction(io.crate.expression.scalar.SubscriptFunction) ParameterSymbol(io.crate.expression.symbol.ParameterSymbol) SelectSymbol(io.crate.expression.symbol.SelectSymbol) Symbol(io.crate.expression.symbol.Symbol) AliasSymbol(io.crate.expression.symbol.AliasSymbol) CrateDummyClusterServiceUnitTest(io.crate.test.integration.CrateDummyClusterServiceUnitTest) Test(org.junit.Test)

Aggregations

Function (io.crate.expression.symbol.Function)80 Test (org.junit.Test)56 Symbol (io.crate.expression.symbol.Symbol)43 CrateDummyClusterServiceUnitTest (io.crate.test.integration.CrateDummyClusterServiceUnitTest)43 SymbolMatchers.isFunction (io.crate.testing.SymbolMatchers.isFunction)35 SubscriptFunction (io.crate.expression.scalar.SubscriptFunction)25 TryCastFunction (io.crate.expression.scalar.cast.TryCastFunction)24 ExplicitCastFunction (io.crate.expression.scalar.cast.ExplicitCastFunction)23 DistanceFunction (io.crate.expression.scalar.geo.DistanceFunction)23 AliasSymbol (io.crate.expression.symbol.AliasSymbol)13 ParameterSymbol (io.crate.expression.symbol.ParameterSymbol)13 SelectSymbol (io.crate.expression.symbol.SelectSymbol)13 InputColumn (io.crate.expression.symbol.InputColumn)10 ArrayList (java.util.ArrayList)10 Literal (io.crate.expression.symbol.Literal)9 ArraySliceFunction (io.crate.expression.scalar.ArraySliceFunction)8 FunctionImplementation (io.crate.metadata.FunctionImplementation)8 AnalyzedRelation (io.crate.analyze.relations.AnalyzedRelation)7 ScopedSymbol (io.crate.expression.symbol.ScopedSymbol)6 Reference (io.crate.metadata.Reference)6