Search in sources :

Example 1 with BoolConstant

use of io.siddhi.query.api.expression.constant.BoolConstant in project siddhi by wso2.

the class AggregationRuntime method compileExpression.

public CompiledCondition compileExpression(Expression expression, Within within, Expression per, List<Variable> queryGroupByList, MatchingMetaInfoHolder matchingMetaInfoHolder, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, SiddhiQueryContext siddhiQueryContext) {
    String aggregationName = aggregationDefinition.getId();
    boolean isOptimisedTableLookup = isOptimisedLookup;
    Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions = new HashMap<>();
    CompiledCondition withinInMemoryCompileCondition;
    CompiledCondition onCompiledCondition;
    List<Attribute> additionalAttributes = new ArrayList<>();
    // Define additional attribute list
    additionalAttributes.add(new Attribute("_START", Attribute.Type.LONG));
    additionalAttributes.add(new Attribute("_END", Attribute.Type.LONG));
    int lowerGranularitySize = this.activeIncrementalDurations.size() - 1;
    List<String> lowerGranularityAttributes = new ArrayList<>();
    if (isDistributed) {
        // for values calculated in in-memory in the shards
        for (int i = 0; i < lowerGranularitySize; i++) {
            String attributeName = "_AGG_TIMESTAMP_FILTER_" + i;
            additionalAttributes.add(new Attribute(attributeName, Attribute.Type.LONG));
            lowerGranularityAttributes.add(attributeName);
        }
    }
    // Get table definition. Table definitions for all the tables used to persist aggregates are similar.
    // Therefore it's enough to get the definition from one table.
    AbstractDefinition tableDefinition = aggregationTables.get(activeIncrementalDurations.get(0)).getTableDefinition();
    boolean isOnDemandQuery = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length == 1;
    // Alter existing meta stream event or create new one if a meta stream doesn't exist
    // After calling this method the original MatchingMetaInfoHolder's meta stream event would be altered
    // Alter meta info holder to contain stream event and aggregate both when it's a on-demand query
    MetaStreamEvent metaStreamEventForTableLookups;
    if (isOnDemandQuery) {
        metaStreamEventForTableLookups = alterMetaStreamEvent(true, new MetaStreamEvent(), additionalAttributes);
        matchingMetaInfoHolder = alterMetaInfoHolderForOnDemandQuery(metaStreamEventForTableLookups, matchingMetaInfoHolder);
    } else {
        metaStreamEventForTableLookups = alterMetaStreamEvent(false, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(0), additionalAttributes);
    }
    // Create new MatchingMetaInfoHolder containing newMetaStreamEventWithStartEnd and table meta event
    String aggReferenceId = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(1).getInputReferenceId();
    String referenceName = aggReferenceId == null ? aggregationName : aggReferenceId;
    MetaStreamEvent metaStoreEventForTableLookups = createMetaStoreEvent(tableDefinition, referenceName);
    // Create new MatchingMetaInfoHolder containing metaStreamEventForTableLookups and table meta event
    MatchingMetaInfoHolder metaInfoHolderForTableLookups = createNewStreamTableMetaInfoHolder(metaStreamEventForTableLookups, metaStoreEventForTableLookups);
    // Create per expression executor
    ExpressionExecutor perExpressionExecutor;
    if (per != null) {
        perExpressionExecutor = ExpressionParser.parseExpression(per, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        if (perExpressionExecutor.getReturnType() != Attribute.Type.STRING) {
            throw new SiddhiAppCreationException("Query " + siddhiQueryContext.getName() + "'s per value expected a string but found " + perExpressionExecutor.getReturnType(), per.getQueryContextStartIndex(), per.getQueryContextEndIndex());
        }
        // Additional Per time function verification at compile time if it is a constant
        if (perExpressionExecutor instanceof ConstantExpressionExecutor) {
            String perValue = ((ConstantExpressionExecutor) perExpressionExecutor).getValue().toString();
            try {
                normalizeDuration(perValue);
            } catch (SiddhiAppValidationException e) {
                throw new SiddhiAppValidationException("Aggregation Query's per value is expected to be of a valid time function of the " + "following " + TimePeriod.Duration.SECONDS + ", " + TimePeriod.Duration.MINUTES + ", " + TimePeriod.Duration.HOURS + ", " + TimePeriod.Duration.DAYS + ", " + TimePeriod.Duration.MONTHS + ", " + TimePeriod.Duration.YEARS + ".");
            }
        }
    } else {
        throw new SiddhiAppCreationException("Syntax Error: Aggregation join query must contain a `per` " + "definition for granularity");
    }
    // Create start and end time expression
    Expression startEndTimeExpression;
    ExpressionExecutor startTimeEndTimeExpressionExecutor;
    if (within != null) {
        if (within.getTimeRange().size() == 1) {
            startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0));
        } else {
            // within.getTimeRange().size() == 2
            startEndTimeExpression = new AttributeFunction("incrementalAggregator", "startTimeEndTime", within.getTimeRange().get(0), within.getTimeRange().get(1));
        }
        startTimeEndTimeExpressionExecutor = ExpressionParser.parseExpression(startEndTimeExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
    } else {
        throw new SiddhiAppCreationException("Syntax Error : Aggregation read query must contain a `within` " + "definition for filtering of aggregation data.");
    }
    // Create within expression
    Expression timeFilterExpression;
    if (isProcessingOnExternalTime) {
        timeFilterExpression = Expression.variable(AGG_EXTERNAL_TIMESTAMP_COL);
    } else {
        timeFilterExpression = Expression.variable(AGG_START_TIMESTAMP_COL);
    }
    Expression withinExpression;
    Expression start = Expression.variable(additionalAttributes.get(0).getName());
    Expression end = Expression.variable(additionalAttributes.get(1).getName());
    Expression compareWithStartTime = Compare.compare(start, Compare.Operator.LESS_THAN_EQUAL, timeFilterExpression);
    Expression compareWithEndTime = Compare.compare(timeFilterExpression, Compare.Operator.LESS_THAN, end);
    withinExpression = Expression.and(compareWithStartTime, compareWithEndTime);
    List<ExpressionExecutor> timestampFilterExecutors = new ArrayList<>();
    if (isDistributed) {
        for (int i = 0; i < lowerGranularitySize; i++) {
            Expression[] expressionArray = new Expression[] { new AttributeFunction("", "currentTimeMillis", null), Expression.value(this.activeIncrementalDurations.get(i + 1).toString()) };
            Expression filterExpression = new AttributeFunction("incrementalAggregator", "getAggregationStartTime", expressionArray);
            timestampFilterExecutors.add(ExpressionParser.parseExpression(filterExpression, matchingMetaInfoHolder.getMetaStateEvent(), matchingMetaInfoHolder.getCurrentState(), tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext));
        }
    }
    // Create compile condition per each table used to persist aggregates.
    // These compile conditions are used to check whether the aggregates in tables are within the given duration.
    // Combine with and on condition for table query
    boolean shouldApplyReducedCondition = false;
    Expression reducedExpression = null;
    // Check if there is no on conditions
    if (!(expression instanceof BoolConstant)) {
        // For abstract queryable table
        AggregationExpressionBuilder aggregationExpressionBuilder = new AggregationExpressionBuilder(expression);
        AggregationExpressionVisitor expressionVisitor = new AggregationExpressionVisitor(metaStreamEventForTableLookups.getInputReferenceId(), metaStreamEventForTableLookups.getLastInputDefinition().getAttributeList(), this.tableAttributesNameList);
        aggregationExpressionBuilder.build(expressionVisitor);
        shouldApplyReducedCondition = expressionVisitor.applyReducedExpression();
        reducedExpression = expressionVisitor.getReducedExpression();
    }
    Expression withinExpressionTable;
    if (shouldApplyReducedCondition) {
        withinExpressionTable = Expression.and(withinExpression, reducedExpression);
    } else {
        withinExpressionTable = withinExpression;
    }
    List<Variable> queryGroupByListCopy = new ArrayList<>(queryGroupByList);
    Variable timestampVariable = new Variable(AGG_START_TIMESTAMP_COL);
    List<String> queryGroupByNamesList = queryGroupByListCopy.stream().map(Variable::getAttributeName).collect(Collectors.toList());
    boolean queryGroupByContainsTimestamp = queryGroupByNamesList.remove(AGG_START_TIMESTAMP_COL);
    boolean isQueryGroupBySameAsAggGroupBy = queryGroupByListCopy.isEmpty() || (queryGroupByListCopy.contains(timestampVariable) && queryGroupByNamesList.equals(groupByVariablesList));
    List<VariableExpressionExecutor> variableExpExecutorsForTableLookups = new ArrayList<>();
    Map<TimePeriod.Duration, CompiledSelection> withinTableCompiledSelection = new HashMap<>();
    if (isOptimisedTableLookup) {
        Selector selector = Selector.selector();
        List<Variable> groupByList = new ArrayList<>();
        if (!isQueryGroupBySameAsAggGroupBy) {
            if (queryGroupByContainsTimestamp) {
                if (isProcessingOnExternalTime) {
                    groupByList.add(new Variable(AGG_EXTERNAL_TIMESTAMP_COL));
                } else {
                    groupByList.add(new Variable(AGG_START_TIMESTAMP_COL));
                }
                // Remove timestamp to process the rest
                queryGroupByListCopy.remove(timestampVariable);
            }
            for (Variable queryGroupBy : queryGroupByListCopy) {
                String referenceId = queryGroupBy.getStreamId();
                if (referenceId == null) {
                    if (tableAttributesNameList.contains(queryGroupBy.getAttributeName())) {
                        groupByList.add(queryGroupBy);
                    }
                } else if (referenceId.equalsIgnoreCase(referenceName)) {
                    groupByList.add(queryGroupBy);
                }
            }
            // If query group bys are based on joining stream
            if (groupByList.isEmpty()) {
                isQueryGroupBySameAsAggGroupBy = true;
            }
        }
        groupByList.forEach((groupBy) -> groupBy.setStreamId(referenceName));
        selector.addGroupByList(groupByList);
        List<OutputAttribute> selectorList;
        if (!isQueryGroupBySameAsAggGroupBy) {
            selectorList = constructSelectorList(isProcessingOnExternalTime, isDistributed, isLatestEventColAdded, baseAggregatorBeginIndex, groupByVariablesList.size(), finalBaseExpressionsList, tableDefinition, groupByList);
        } else {
            selectorList = defaultSelectorList;
        }
        for (OutputAttribute outputAttribute : selectorList) {
            if (outputAttribute.getExpression() instanceof Variable) {
                ((Variable) outputAttribute.getExpression()).setStreamId(referenceName);
            } else {
                for (Expression parameter : ((AttributeFunction) outputAttribute.getExpression()).getParameters()) {
                    ((Variable) parameter).setStreamId(referenceName);
                }
            }
        }
        selector.addSelectionList(selectorList);
        try {
            aggregationTables.entrySet().forEach((durationTableEntry -> {
                CompiledSelection compiledSelection = ((QueryableProcessor) durationTableEntry.getValue()).compileSelection(selector, tableDefinition.getAttributeList(), metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
                withinTableCompiledSelection.put(durationTableEntry.getKey(), compiledSelection);
            }));
        } catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Aggregation Query optimization failed for aggregation: '" + aggregationName + "'. " + "Creating table lookup query in normal mode. Reason for failure: " + e.getMessage(), e);
            }
            isOptimisedTableLookup = false;
        }
    }
    for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) {
        CompiledCondition withinTableCompileCondition = entry.getValue().compileCondition(withinExpressionTable, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
        withinTableCompiledConditions.put(entry.getKey(), withinTableCompileCondition);
    }
    // Create compile condition for in-memory data.
    // This compile condition is used to check whether the running aggregates (in-memory data)
    // are within given duration
    withinInMemoryCompileCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), withinExpression, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
    // Create compile condition for in-memory data, in case of distributed
    // Look at the lower level granularities
    Map<TimePeriod.Duration, CompiledCondition> withinTableLowerGranularityCompileCondition = new HashMap<>();
    Expression lowerGranularity;
    if (isDistributed) {
        for (int i = 0; i < lowerGranularitySize; i++) {
            if (isProcessingOnExternalTime) {
                lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), withinExpressionTable);
            } else {
                if (shouldApplyReducedCondition) {
                    lowerGranularity = Expression.and(Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i))), reducedExpression);
                } else {
                    lowerGranularity = Expression.compare(Expression.variable("AGG_TIMESTAMP"), Compare.Operator.GREATER_THAN_EQUAL, Expression.variable(lowerGranularityAttributes.get(i)));
                }
            }
            TimePeriod.Duration duration = this.activeIncrementalDurations.get(i);
            String tableName = aggregationName + "_" + duration.toString();
            CompiledCondition compiledCondition = tableMap.get(tableName).compileCondition(lowerGranularity, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups, tableMap, siddhiQueryContext);
            withinTableLowerGranularityCompileCondition.put(duration, compiledCondition);
        }
    }
    QueryParserHelper.reduceMetaComplexEvent(metaInfoHolderForTableLookups.getMetaStateEvent());
    // On compile condition.
    // After finding all the aggregates belonging to within duration, the final on condition (given as
    // "on stream1.name == aggregator.nickName ..." in the join query) must be executed on that data.
    // This condition is used for that purpose.
    onCompiledCondition = OperatorParser.constructOperator(new ComplexEventChunk<>(), expression, matchingMetaInfoHolder, variableExpressionExecutors, tableMap, siddhiQueryContext);
    return new IncrementalAggregateCompileCondition(isOnDemandQuery, aggregationName, isProcessingOnExternalTime, isDistributed, activeIncrementalDurations, aggregationTables, outputExpressionExecutors, isOptimisedTableLookup, withinTableCompiledSelection, withinTableCompiledConditions, withinInMemoryCompileCondition, withinTableLowerGranularityCompileCondition, onCompiledCondition, additionalAttributes, perExpressionExecutor, startTimeEndTimeExpressionExecutor, timestampFilterExecutors, aggregateMetaSteamEvent, matchingMetaInfoHolder, metaInfoHolderForTableLookups, variableExpExecutorsForTableLookups);
}
Also used : MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) Selector(io.siddhi.query.api.execution.query.selection.Selector) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) StreamEvent(io.siddhi.core.event.stream.StreamEvent) MemoryCalculable(io.siddhi.core.util.statistics.MemoryCalculable) Expression(io.siddhi.query.api.expression.Expression) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) Table(io.siddhi.core.table.Table) SnapshotService(io.siddhi.core.util.snapshot.SnapshotService) Map(java.util.Map) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) ProcessingMode(io.siddhi.core.query.processor.ProcessingMode) AGG_START_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL) UNKNOWN_STATE(io.siddhi.core.util.SiddhiConstants.UNKNOWN_STATE) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ExpressionParser(io.siddhi.core.util.parser.ExpressionParser) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Level(io.siddhi.core.util.statistics.metrics.Level) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) AGG_EXTERNAL_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_EXTERNAL_TIMESTAMP_COL) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Variable(io.siddhi.query.api.expression.Variable) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IncrementalAggregateCompileCondition(io.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) QueryableRecordTableException(io.siddhi.core.exception.QueryableRecordTableException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) Within(io.siddhi.query.api.aggregation.Within) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) Compare(io.siddhi.query.api.expression.condition.Compare) ComplexEventChunk(io.siddhi.core.event.ComplexEventChunk) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) Attribute(io.siddhi.query.api.definition.Attribute) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) AGG_LAST_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_LAST_TIMESTAMP_COL) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) OperatorParser(io.siddhi.core.util.parser.OperatorParser) StateEvent(io.siddhi.core.event.state.StateEvent) QueryParserHelper(io.siddhi.core.util.parser.helper.QueryParserHelper) LogManager(org.apache.logging.log4j.LogManager) AGG_SHARD_ID_COL(io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL) AggregationDefinition(io.siddhi.query.api.definition.AggregationDefinition) Variable(io.siddhi.query.api.expression.Variable) ComplexEventChunk(io.siddhi.core.event.ComplexEventChunk) HashMap(java.util.HashMap) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) ArrayList(java.util.ArrayList) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) QueryableRecordTableException(io.siddhi.core.exception.QueryableRecordTableException) Selector(io.siddhi.query.api.execution.query.selection.Selector) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Table(io.siddhi.core.table.Table) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) IncrementalAggregateCompileCondition(io.siddhi.core.util.collection.operator.IncrementalAggregateCompileCondition) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) Expression(io.siddhi.query.api.expression.Expression) MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) CompiledSelection(io.siddhi.core.util.collection.operator.CompiledSelection) Map(java.util.Map) HashMap(java.util.HashMap) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 2 with BoolConstant

use of io.siddhi.query.api.expression.constant.BoolConstant in project siddhi by wso2.

the class ExpressionBuilder method buildVariableExecutors.

private void buildVariableExecutors(Expression expression, ExpressionVisitor expressionVisitor) {
    try {
        if (expression instanceof And) {
            expressionVisitor.beginVisitAnd();
            expressionVisitor.beginVisitAndLeftOperand();
            buildVariableExecutors(((And) expression).getLeftExpression(), expressionVisitor);
            expressionVisitor.endVisitAndLeftOperand();
            expressionVisitor.beginVisitAndRightOperand();
            buildVariableExecutors(((And) expression).getRightExpression(), expressionVisitor);
            expressionVisitor.endVisitAndRightOperand();
            expressionVisitor.endVisitAnd();
        } else if (expression instanceof Or) {
            expressionVisitor.beginVisitOr();
            expressionVisitor.beginVisitOrLeftOperand();
            buildVariableExecutors(((Or) expression).getLeftExpression(), expressionVisitor);
            expressionVisitor.endVisitOrLeftOperand();
            expressionVisitor.beginVisitOrRightOperand();
            buildVariableExecutors(((Or) expression).getRightExpression(), expressionVisitor);
            expressionVisitor.endVisitOrRightOperand();
            expressionVisitor.endVisitOr();
        } else if (expression instanceof Not) {
            expressionVisitor.beginVisitNot();
            buildVariableExecutors(((Not) expression).getExpression(), expressionVisitor);
            expressionVisitor.endVisitNot();
        } else if (expression instanceof Compare) {
            expressionVisitor.beginVisitCompare(((Compare) expression).getOperator());
            expressionVisitor.beginVisitCompareLeftOperand(((Compare) expression).getOperator());
            buildVariableExecutors(((Compare) expression).getLeftExpression(), expressionVisitor);
            expressionVisitor.endVisitCompareLeftOperand(((Compare) expression).getOperator());
            expressionVisitor.beginVisitCompareRightOperand(((Compare) expression).getOperator());
            buildVariableExecutors(((Compare) expression).getRightExpression(), expressionVisitor);
            expressionVisitor.endVisitCompareRightOperand(((Compare) expression).getOperator());
            expressionVisitor.endVisitCompare(((Compare) expression).getOperator());
        } else if (expression instanceof Add) {
            expressionVisitor.beginVisitMath(ExpressionVisitor.MathOperator.ADD);
            expressionVisitor.beginVisitMathLeftOperand(ExpressionVisitor.MathOperator.ADD);
            buildVariableExecutors(((Add) expression).getLeftValue(), expressionVisitor);
            expressionVisitor.endVisitMathLeftOperand(ExpressionVisitor.MathOperator.ADD);
            expressionVisitor.beginVisitMathRightOperand(ExpressionVisitor.MathOperator.ADD);
            buildVariableExecutors(((Add) expression).getRightValue(), expressionVisitor);
            expressionVisitor.endVisitMathRightOperand(ExpressionVisitor.MathOperator.ADD);
            expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.ADD);
        } else if (expression instanceof Subtract) {
            expressionVisitor.beginVisitMath(ExpressionVisitor.MathOperator.SUBTRACT);
            expressionVisitor.beginVisitMathLeftOperand(ExpressionVisitor.MathOperator.SUBTRACT);
            buildVariableExecutors(((Subtract) expression).getLeftValue(), expressionVisitor);
            expressionVisitor.endVisitMathLeftOperand(ExpressionVisitor.MathOperator.SUBTRACT);
            expressionVisitor.beginVisitMathRightOperand(ExpressionVisitor.MathOperator.SUBTRACT);
            buildVariableExecutors(((Subtract) expression).getRightValue(), expressionVisitor);
            expressionVisitor.endVisitMathRightOperand(ExpressionVisitor.MathOperator.SUBTRACT);
            expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.SUBTRACT);
        } else if (expression instanceof Divide) {
            expressionVisitor.beginVisitMath(ExpressionVisitor.MathOperator.DIVIDE);
            expressionVisitor.beginVisitMathLeftOperand(ExpressionVisitor.MathOperator.DIVIDE);
            buildVariableExecutors(((Divide) expression).getLeftValue(), expressionVisitor);
            expressionVisitor.endVisitMathLeftOperand(ExpressionVisitor.MathOperator.DIVIDE);
            expressionVisitor.beginVisitMathRightOperand(ExpressionVisitor.MathOperator.DIVIDE);
            buildVariableExecutors(((Divide) expression).getRightValue(), expressionVisitor);
            expressionVisitor.endVisitMathRightOperand(ExpressionVisitor.MathOperator.DIVIDE);
            expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.DIVIDE);
        } else if (expression instanceof Multiply) {
            expressionVisitor.beginVisitMath(ExpressionVisitor.MathOperator.MULTIPLY);
            expressionVisitor.beginVisitMathLeftOperand(ExpressionVisitor.MathOperator.MULTIPLY);
            buildVariableExecutors(((Multiply) expression).getLeftValue(), expressionVisitor);
            expressionVisitor.endVisitMathLeftOperand(ExpressionVisitor.MathOperator.MULTIPLY);
            expressionVisitor.beginVisitMathRightOperand(ExpressionVisitor.MathOperator.MULTIPLY);
            buildVariableExecutors(((Multiply) expression).getRightValue(), expressionVisitor);
            expressionVisitor.endVisitMathRightOperand(ExpressionVisitor.MathOperator.MULTIPLY);
            expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.MULTIPLY);
        } else if (expression instanceof Mod) {
            expressionVisitor.beginVisitMath(ExpressionVisitor.MathOperator.MOD);
            expressionVisitor.beginVisitMathLeftOperand(ExpressionVisitor.MathOperator.MOD);
            buildVariableExecutors(((Mod) expression).getLeftValue(), expressionVisitor);
            expressionVisitor.endVisitMathLeftOperand(ExpressionVisitor.MathOperator.MOD);
            expressionVisitor.beginVisitMathRightOperand(ExpressionVisitor.MathOperator.MOD);
            buildVariableExecutors(((Mod) expression).getRightValue(), expressionVisitor);
            expressionVisitor.endVisitMathRightOperand(ExpressionVisitor.MathOperator.MOD);
            expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.MOD);
        } else if (expression instanceof IsNull) {
            IsNull isNull = (IsNull) expression;
            if (isNull.getExpression() != null) {
                expressionVisitor.beginVisitIsNull(null);
                buildVariableExecutors(((IsNull) expression).getExpression(), expressionVisitor);
                expressionVisitor.endVisitIsNull(null);
            } else {
                String streamId = isNull.getStreamId();
                MetaStateEvent metaStateEvent = matchingMetaInfoHolder.getMetaStateEvent();
                if (streamId == null) {
                    throw new SiddhiAppCreationException("IsNull does not support streamId being null");
                } else {
                    AbstractDefinition definitionOutput = null;
                    MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
                    for (int i = 0, metaStreamEventsLength = metaStreamEvents.length; i < metaStreamEventsLength; i++) {
                        MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                        AbstractDefinition definition = metaStreamEvent.getLastInputDefinition();
                        if (metaStreamEvent.getInputReferenceId() == null) {
                            if (definition.getId().equals(streamId)) {
                                definitionOutput = definition;
                                break;
                            }
                        } else {
                            if (metaStreamEvent.getInputReferenceId().equals(streamId)) {
                                definitionOutput = definition;
                                break;
                            }
                        }
                    }
                    if (definitionOutput != null) {
                        expressionVisitor.beginVisitIsNull(definitionOutput.getId());
                        expressionVisitor.endVisitIsNull(definitionOutput.getId());
                    } else {
                        expressionVisitor.beginVisitIsNull(null);
                        expressionVisitor.endVisitIsNull(null);
                    }
                }
            }
        } else if (expression instanceof In) {
            expressionVisitor.beginVisitIn(((In) expression).getSourceId());
            buildVariableExecutors(((In) expression).getExpression(), expressionVisitor);
            expressionVisitor.endVisitIn(((In) expression).getSourceId());
        } else if (expression instanceof Constant) {
            if (expression instanceof DoubleConstant) {
                expressionVisitor.beginVisitConstant(((DoubleConstant) expression).getValue(), Attribute.Type.DOUBLE);
                expressionVisitor.endVisitConstant(((DoubleConstant) expression).getValue(), Attribute.Type.DOUBLE);
            } else if (expression instanceof StringConstant) {
                expressionVisitor.beginVisitConstant(((StringConstant) expression).getValue(), Attribute.Type.STRING);
                expressionVisitor.endVisitConstant(((StringConstant) expression).getValue(), Attribute.Type.STRING);
            } else if (expression instanceof IntConstant) {
                expressionVisitor.beginVisitConstant(((IntConstant) expression).getValue(), Attribute.Type.INT);
                expressionVisitor.endVisitConstant(((IntConstant) expression).getValue(), Attribute.Type.INT);
            } else if (expression instanceof BoolConstant) {
                expressionVisitor.beginVisitConstant(((BoolConstant) expression).getValue(), Attribute.Type.BOOL);
                expressionVisitor.endVisitConstant(((BoolConstant) expression).getValue(), Attribute.Type.BOOL);
            } else if (expression instanceof FloatConstant) {
                expressionVisitor.beginVisitConstant(((FloatConstant) expression).getValue(), Attribute.Type.FLOAT);
                expressionVisitor.endVisitConstant(((FloatConstant) expression).getValue(), Attribute.Type.FLOAT);
            } else if (expression instanceof LongConstant) {
                expressionVisitor.beginVisitConstant(((LongConstant) expression).getValue(), Attribute.Type.LONG);
                expressionVisitor.endVisitConstant(((LongConstant) expression).getValue(), Attribute.Type.LONG);
            } else {
                throw new OperationNotSupportedException("No constant exist with type " + expression.getClass().getName());
            }
        } else if (expression instanceof AttributeFunction) {
            expressionVisitor.beginVisitAttributeFunction(((AttributeFunction) expression).getNamespace(), ((AttributeFunction) expression).getName());
            Expression[] expressions = ((AttributeFunction) expression).getParameters();
            if (expressions != null) {
                for (int i = 0; i < expressions.length; i++) {
                    expressionVisitor.beginVisitParameterAttributeFunction(i);
                    buildVariableExecutors(expressions[i], expressionVisitor);
                    expressionVisitor.endVisitParameterAttributeFunction(i);
                }
            }
            expressionVisitor.endVisitAttributeFunction(((AttributeFunction) expression).getNamespace(), ((AttributeFunction) expression).getName());
        } else if (expression instanceof Variable) {
            Variable variable = ((Variable) expression);
            String attributeName = variable.getAttributeName();
            AbstractDefinition definition;
            Attribute.Type type = null;
            int streamEventChainIndex = matchingMetaInfoHolder.getCurrentState();
            if (variable.getStreamId() == null) {
                MetaStreamEvent[] metaStreamEvents = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents();
                if (streamEventChainIndex == UNKNOWN_STATE) {
                    String firstInput = null;
                    for (int i = 0; i < metaStreamEvents.length; i++) {
                        MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                        definition = metaStreamEvent.getLastInputDefinition();
                        if (type == null) {
                            try {
                                type = definition.getAttributeType(attributeName);
                                firstInput = "Input Stream: " + definition.getId() + " with " + "reference: " + metaStreamEvent.getInputReferenceId();
                                streamEventChainIndex = i;
                            } catch (AttributeNotExistException e) {
                            // do nothing
                            }
                        } else {
                            try {
                                definition.getAttributeType(attributeName);
                                throw new SiddhiAppValidationException(firstInput + " and Input Stream: " + definition.getId() + " with " + "reference: " + metaStreamEvent.getInputReferenceId() + " contains attribute " + "with same" + " name '" + attributeName + "'");
                            } catch (AttributeNotExistException e) {
                            // do nothing as its expected
                            }
                        }
                    }
                    if (streamEventChainIndex != UNKNOWN_STATE) {
                        if (matchingMetaInfoHolder.getMatchingStreamEventIndex() == streamEventChainIndex) {
                            buildStreamVariableExecutor(variable, streamEventChainIndex, expressionVisitor, type);
                        } else {
                            buildStoreVariableExecutor(variable, expressionVisitor, type, matchingMetaInfoHolder.getStoreDefinition());
                        }
                    } else {
                        // Having state : i.e attribute is in the select clause
                        definition = matchingMetaInfoHolder.getMetaStateEvent().getOutputStreamDefinition();
                        try {
                            type = definition.getAttributeType(attributeName);
                            buildStoreVariableExecutor(variable, expressionVisitor, type, matchingMetaInfoHolder.getStoreDefinition());
                        } catch (AttributeNotExistException e) {
                        // do nothing as its not expected
                        }
                    }
                } else {
                    MetaStreamEvent metaStreamEvent = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvent(matchingMetaInfoHolder.getCurrentState());
                    definition = metaStreamEvent.getLastInputDefinition();
                    try {
                        type = definition.getAttributeType(attributeName);
                    } catch (AttributeNotExistException e) {
                        // Having state : i.e attribute is in the select clause
                        definition = matchingMetaInfoHolder.getMetaStateEvent().getOutputStreamDefinition();
                        try {
                            type = definition.getAttributeType(attributeName);
                            buildStoreVariableExecutor(variable, expressionVisitor, type, matchingMetaInfoHolder.getStoreDefinition());
                        } catch (AttributeNotExistException e1) {
                            throw new SiddhiAppValidationException(e1.getMessageWithOutContext() + " Input Stream: " + definition.getId() + " with " + "reference: " + metaStreamEvent.getInputReferenceId(), e1.getQueryContextStartIndex(), e1.getQueryContextEndIndex(), siddhiQueryContext.getSiddhiAppContext().getName(), siddhiQueryContext.getSiddhiAppContext().getSiddhiAppString());
                        }
                    }
                    if (matchingMetaInfoHolder.getCurrentState() == matchingMetaInfoHolder.getMatchingStreamEventIndex()) {
                        buildStreamVariableExecutor(variable, streamEventChainIndex, expressionVisitor, type);
                    } else {
                        buildStoreVariableExecutor(variable, expressionVisitor, type, matchingMetaInfoHolder.getStoreDefinition());
                    }
                }
            } else {
                MetaStreamEvent[] metaStreamEvents = matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents();
                for (int i = 0, metaStreamEventsLength = metaStreamEvents.length; i < metaStreamEventsLength; i++) {
                    MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                    definition = metaStreamEvent.getLastInputDefinition();
                    if (metaStreamEvent.getInputReferenceId() == null) {
                        if (definition.getId().equals(variable.getStreamId())) {
                            type = definition.getAttributeType(attributeName);
                            streamEventChainIndex = i;
                            break;
                        }
                    } else {
                        if (metaStreamEvent.getInputReferenceId().equals(variable.getStreamId())) {
                            type = definition.getAttributeType(attributeName);
                            streamEventChainIndex = i;
                            break;
                        }
                    }
                }
                if (matchingMetaInfoHolder.getMatchingStreamEventIndex() == streamEventChainIndex) {
                    buildStreamVariableExecutor(variable, streamEventChainIndex, expressionVisitor, type);
                } else {
                    buildStoreVariableExecutor(variable, expressionVisitor, type, matchingMetaInfoHolder.getStoreDefinition());
                }
            }
        }
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, expression, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
        throw t;
    }
}
Also used : Add(io.siddhi.query.api.expression.math.Add) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) Or(io.siddhi.query.api.expression.condition.Or) Variable(io.siddhi.query.api.expression.Variable) In(io.siddhi.query.api.expression.condition.In) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) Constant(io.siddhi.query.api.expression.constant.Constant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) Divide(io.siddhi.query.api.expression.math.Divide) AttributeNotExistException(io.siddhi.query.api.exception.AttributeNotExistException) Multiply(io.siddhi.query.api.expression.math.Multiply) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) Compare(io.siddhi.query.api.expression.condition.Compare) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) OperationNotSupportedException(io.siddhi.core.exception.OperationNotSupportedException) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Mod(io.siddhi.query.api.expression.math.Mod) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) Not(io.siddhi.query.api.expression.condition.Not) Expression(io.siddhi.query.api.expression.Expression) And(io.siddhi.query.api.expression.condition.And) Subtract(io.siddhi.query.api.expression.math.Subtract) IsNull(io.siddhi.query.api.expression.condition.IsNull) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 3 with BoolConstant

use of io.siddhi.query.api.expression.constant.BoolConstant in project siddhi by wso2.

the class ExpressionParser method parseExpression.

/**
 * Parse the given expression and create the appropriate Executor by recursively traversing the expression
 *
 * @param expression                 Expression to be parsed
 * @param metaEvent                  Meta Event
 * @param currentState               Current state number
 * @param tableMap                   Event Table Map
 * @param executorList               List to hold VariableExpressionExecutors to update after query parsing
 * @param groupBy                    is for groupBy expression
 * @param defaultStreamEventIndex    Default StreamEvent Index
 * @param processingMode             processing mode of the query
 * @param outputExpectsExpiredEvents is expired events sent as output
 * @param siddhiQueryContext         current siddhi query context
 * @return ExpressionExecutor
 */
public static ExpressionExecutor parseExpression(Expression expression, MetaComplexEvent metaEvent, int currentState, Map<String, Table> tableMap, List<VariableExpressionExecutor> executorList, boolean groupBy, int defaultStreamEventIndex, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, SiddhiQueryContext siddhiQueryContext) {
    try {
        if (expression instanceof And) {
            return new AndConditionExpressionExecutor(parseExpression(((And) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((And) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Or) {
            return new OrConditionExpressionExecutor(parseExpression(((Or) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Or) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Not) {
            return new NotConditionExpressionExecutor(parseExpression(((Not) expression).getExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
        } else if (expression instanceof Compare) {
            if (((Compare) expression).getOperator() == Compare.Operator.EQUAL) {
                Expression leftExpression = ((Compare) expression).getLeftExpression();
                Expression rightExpression = ((Compare) expression).getRightExpression();
                ExpressionExecutor leftExpressionExecutor = parseExpression(leftExpression, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                ExpressionExecutor rightExpressionExecutor = parseExpression(rightExpression, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                return parseEqualCompare(leftExpressionExecutor, rightExpressionExecutor);
            } else if (((Compare) expression).getOperator() == Compare.Operator.NOT_EQUAL) {
                return parseNotEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN) {
                return parseGreaterThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN_EQUAL) {
                return parseGreaterThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN) {
                return parseLessThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN_EQUAL) {
                return parseLessThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext));
            }
        } else if (expression instanceof Constant) {
            if (expression instanceof BoolConstant) {
                return new ConstantExpressionExecutor(((BoolConstant) expression).getValue(), Attribute.Type.BOOL);
            } else if (expression instanceof StringConstant) {
                return new ConstantExpressionExecutor(((StringConstant) expression).getValue(), Attribute.Type.STRING);
            } else if (expression instanceof IntConstant) {
                return new ConstantExpressionExecutor(((IntConstant) expression).getValue(), Attribute.Type.INT);
            } else if (expression instanceof LongConstant) {
                return new ConstantExpressionExecutor(((LongConstant) expression).getValue(), Attribute.Type.LONG);
            } else if (expression instanceof FloatConstant) {
                return new ConstantExpressionExecutor(((FloatConstant) expression).getValue(), Attribute.Type.FLOAT);
            } else if (expression instanceof DoubleConstant) {
                return new ConstantExpressionExecutor(((DoubleConstant) expression).getValue(), Attribute.Type.DOUBLE);
            }
        } else if (expression instanceof Variable) {
            return parseVariable((Variable) expression, metaEvent, currentState, executorList, defaultStreamEventIndex, siddhiQueryContext);
        } else if (expression instanceof Multiply) {
            ExpressionExecutor left = parseExpression(((Multiply) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Multiply) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new MultiplyExpressionExecutorInt(left, right);
                case LONG:
                    return new MultiplyExpressionExecutorLong(left, right);
                case FLOAT:
                    return new MultiplyExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new MultiplyExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Add) {
            ExpressionExecutor left = parseExpression(((Add) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Add) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new AddExpressionExecutorInt(left, right);
                case LONG:
                    return new AddExpressionExecutorLong(left, right);
                case FLOAT:
                    return new AddExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new AddExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Subtract) {
            ExpressionExecutor left = parseExpression(((Subtract) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Subtract) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new SubtractExpressionExecutorInt(left, right);
                case LONG:
                    return new SubtractExpressionExecutorLong(left, right);
                case FLOAT:
                    return new SubtractExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new SubtractExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Mod) {
            ExpressionExecutor left = parseExpression(((Mod) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Mod) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new ModExpressionExecutorInt(left, right);
                case LONG:
                    return new ModExpressionExecutorLong(left, right);
                case FLOAT:
                    return new ModExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new ModExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof Divide) {
            ExpressionExecutor left = parseExpression(((Divide) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            ExpressionExecutor right = parseExpression(((Divide) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
            Attribute.Type type = parseArithmeticOperationResultType(left, right);
            switch(type) {
                case INT:
                    return new DivideExpressionExecutorInt(left, right);
                case LONG:
                    return new DivideExpressionExecutorLong(left, right);
                case FLOAT:
                    return new DivideExpressionExecutorFloat(left, right);
                case DOUBLE:
                    return new DivideExpressionExecutorDouble(left, right);
                // Will not happen. Handled in parseArithmeticOperationResultType()
                default:
            }
        } else if (expression instanceof AttributeFunction) {
            // extensions
            Object executor;
            try {
                if ((siddhiQueryContext.getSiddhiAppContext().isFunctionExist(((AttributeFunction) expression).getName())) && (((AttributeFunction) expression).getNamespace()).isEmpty()) {
                    executor = new ScriptFunctionExecutor(((AttributeFunction) expression).getName());
                } else {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, FunctionExecutorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                }
            } catch (SiddhiAppCreationException ex) {
                try {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, AttributeAggregatorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                } catch (SiddhiAppCreationException e) {
                    throw new ExtensionNotFoundException("'" + ((AttributeFunction) expression).getName() + "' is" + " neither a function extension nor an aggregated attribute extension", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                }
            }
            ConfigReader configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((AttributeFunction) expression).getNamespace(), ((AttributeFunction) expression).getName());
            if (executor instanceof FunctionExecutor) {
                FunctionExecutor expressionExecutor = (FunctionExecutor) executor;
                Expression[] innerExpressions = ((AttributeFunction) expression).getParameters();
                ExpressionExecutor[] innerExpressionExecutors = parseInnerExpression(innerExpressions, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                expressionExecutor.initExecutor(innerExpressionExecutors, processingMode, configReader, groupBy, siddhiQueryContext);
                if (expressionExecutor.getReturnType() == Attribute.Type.BOOL) {
                    return new BoolConditionExpressionExecutor(expressionExecutor);
                }
                return expressionExecutor;
            } else {
                AttributeAggregatorExecutor attributeAggregatorExecutor = (AttributeAggregatorExecutor) executor;
                Expression[] innerExpressions = ((AttributeFunction) expression).getParameters();
                ExpressionExecutor[] innerExpressionExecutors = parseInnerExpression(innerExpressions, metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                attributeAggregatorExecutor.initAggregator(innerExpressionExecutors, processingMode, outputExpectsExpiredEvents, configReader, groupBy, siddhiQueryContext);
                // AbstractAggregationAttributeExecutor aggregationAttributeProcessor;
                // if (groupBy) {
                // aggregationAttributeProcessor = new GroupByAggregationAttributeExecutor(attributeAggregatorExecutor,
                // innerExpressionExecutors, configReader, siddhiQueryContext);
                // } else {
                // aggregationAttributeProcessor = new AggregationAttributeExecutor(attributeAggregatorExecutor,
                // innerExpressionExecutors, siddhiQueryContext);
                // }
                SelectorParser.getContainsAggregatorThreadLocal().set("true");
                return attributeAggregatorExecutor;
            }
        } else if (expression instanceof In) {
            Table table = tableMap.get(((In) expression).getSourceId());
            MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(metaEvent, defaultStreamEventIndex, table.getTableDefinition(), defaultStreamEventIndex);
            CompiledCondition compiledCondition = table.compileCondition(((In) expression).getExpression(), matchingMetaInfoHolder, executorList, tableMap, siddhiQueryContext);
            return new InConditionExpressionExecutor(table, compiledCondition, matchingMetaInfoHolder.getMetaStateEvent().getMetaStreamEvents().length, metaEvent instanceof StateEvent, 0);
        } else if (expression instanceof IsNull) {
            IsNull isNull = (IsNull) expression;
            if (isNull.getExpression() != null) {
                ExpressionExecutor innerExpressionExecutor = parseExpression(isNull.getExpression(), metaEvent, currentState, tableMap, executorList, groupBy, defaultStreamEventIndex, processingMode, outputExpectsExpiredEvents, siddhiQueryContext);
                return new IsNullConditionExpressionExecutor(innerExpressionExecutor);
            } else {
                String streamId = isNull.getStreamId();
                Integer streamIndex = isNull.getStreamIndex();
                if (metaEvent instanceof MetaStateEvent) {
                    int[] eventPosition = new int[2];
                    if (streamIndex != null) {
                        if (streamIndex <= SiddhiConstants.LAST) {
                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex + 1;
                        } else {
                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex;
                        }
                    } else {
                        eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = defaultStreamEventIndex;
                    }
                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = SiddhiConstants.UNKNOWN_STATE;
                    MetaStateEvent metaStateEvent = (MetaStateEvent) metaEvent;
                    if (streamId == null) {
                        throw new SiddhiAppCreationException("IsNull does not support streamId being null", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                    } else {
                        MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
                        for (int i = 0, metaStreamEventsLength = metaStreamEvents.length; i < metaStreamEventsLength; i++) {
                            MetaStreamEvent metaStreamEvent = metaStreamEvents[i];
                            AbstractDefinition definition = metaStreamEvent.getLastInputDefinition();
                            if (metaStreamEvent.getInputReferenceId() == null) {
                                if (definition.getId().equals(streamId)) {
                                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                                    break;
                                }
                            } else {
                                if (metaStreamEvent.getInputReferenceId().equals(streamId)) {
                                    eventPosition[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = i;
                                    if (currentState > -1 && metaStreamEvents[currentState].getInputReferenceId() != null && streamIndex != null && streamIndex <= SiddhiConstants.LAST) {
                                        if (streamId.equals(metaStreamEvents[currentState].getInputReferenceId())) {
                                            eventPosition[SiddhiConstants.STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    return new IsNullStreamConditionExpressionExecutor(eventPosition);
                } else {
                    return new IsNullStreamConditionExpressionExecutor(null);
                }
            }
        }
        throw new UnsupportedOperationException(expression.toString() + " not supported!");
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, expression, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
        throw t;
    }
}
Also used : Add(io.siddhi.query.api.expression.math.Add) Or(io.siddhi.query.api.expression.condition.Or) DivideExpressionExecutorFloat(io.siddhi.core.executor.math.divide.DivideExpressionExecutorFloat) ModExpressionExecutorDouble(io.siddhi.core.executor.math.mod.ModExpressionExecutorDouble) ModExpressionExecutorInt(io.siddhi.core.executor.math.mod.ModExpressionExecutorInt) EqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.equal.EqualCompareConditionExpressionExecutorStringString) NotEqualCompareConditionExpressionExecutorStringString(io.siddhi.core.executor.condition.compare.notequal.NotEqualCompareConditionExpressionExecutorStringString) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) Divide(io.siddhi.query.api.expression.math.Divide) MultiplyExpressionExecutorLong(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorLong) AddExpressionExecutorLong(io.siddhi.core.executor.math.add.AddExpressionExecutorLong) Multiply(io.siddhi.query.api.expression.math.Multiply) AddExpressionExecutorInt(io.siddhi.core.executor.math.add.AddExpressionExecutorInt) Compare(io.siddhi.query.api.expression.condition.Compare) DivideExpressionExecutorDouble(io.siddhi.core.executor.math.divide.DivideExpressionExecutorDouble) ExtensionNotFoundException(io.siddhi.core.exception.ExtensionNotFoundException) FunctionExecutor(io.siddhi.core.executor.function.FunctionExecutor) EventVariableFunctionExecutor(io.siddhi.core.executor.EventVariableFunctionExecutor) MultiValueVariableFunctionExecutor(io.siddhi.core.executor.MultiValueVariableFunctionExecutor) ScriptFunctionExecutor(io.siddhi.core.executor.function.ScriptFunctionExecutor) AddExpressionExecutorFloat(io.siddhi.core.executor.math.add.AddExpressionExecutorFloat) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) Not(io.siddhi.query.api.expression.condition.Not) MultiplyExpressionExecutorFloat(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorFloat) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) And(io.siddhi.query.api.expression.condition.And) MatchingMetaInfoHolder(io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) SubtractExpressionExecutorLong(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorLong) IsNullStreamConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) Subtract(io.siddhi.query.api.expression.math.Subtract) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) Variable(io.siddhi.query.api.expression.Variable) MultiplyExpressionExecutorDouble(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorDouble) Attribute(io.siddhi.query.api.definition.Attribute) In(io.siddhi.query.api.expression.condition.In) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) Constant(io.siddhi.query.api.expression.constant.Constant) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) ModExpressionExecutorLong(io.siddhi.core.executor.math.mod.ModExpressionExecutorLong) ScriptFunctionExecutor(io.siddhi.core.executor.function.ScriptFunctionExecutor) InConditionExpressionExecutor(io.siddhi.core.executor.condition.InConditionExpressionExecutor) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) AddExpressionExecutorDouble(io.siddhi.core.executor.math.add.AddExpressionExecutorDouble) AndConditionExpressionExecutor(io.siddhi.core.executor.condition.AndConditionExpressionExecutor) MultiplyExpressionExecutorInt(io.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorInt) IsNullConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) SubtractExpressionExecutorInt(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorInt) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) SubtractExpressionExecutorDouble(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorDouble) AttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.AttributeAggregatorExecutor) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) Mod(io.siddhi.query.api.expression.math.Mod) Table(io.siddhi.core.table.Table) IsNullConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) NotConditionExpressionExecutor(io.siddhi.core.executor.condition.NotConditionExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) OrConditionExpressionExecutor(io.siddhi.core.executor.condition.OrConditionExpressionExecutor) BoolConditionExpressionExecutor(io.siddhi.core.executor.condition.BoolConditionExpressionExecutor) InConditionExpressionExecutor(io.siddhi.core.executor.condition.InConditionExpressionExecutor) AndConditionExpressionExecutor(io.siddhi.core.executor.condition.AndConditionExpressionExecutor) IsNullStreamConditionExpressionExecutor(io.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) ConfigReader(io.siddhi.core.util.config.ConfigReader) OrConditionExpressionExecutor(io.siddhi.core.executor.condition.OrConditionExpressionExecutor) DivideExpressionExecutorLong(io.siddhi.core.executor.math.divide.DivideExpressionExecutorLong) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) DivideExpressionExecutorInt(io.siddhi.core.executor.math.divide.DivideExpressionExecutorInt) SubtractExpressionExecutorFloat(io.siddhi.core.executor.math.subtract.SubtractExpressionExecutorFloat) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) Expression(io.siddhi.query.api.expression.Expression) NotConditionExpressionExecutor(io.siddhi.core.executor.condition.NotConditionExpressionExecutor) ModExpressionExecutorFloat(io.siddhi.core.executor.math.mod.ModExpressionExecutorFloat) StateEvent(io.siddhi.core.event.state.StateEvent) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) IsNull(io.siddhi.query.api.expression.condition.IsNull) BoolConditionExpressionExecutor(io.siddhi.core.executor.condition.BoolConditionExpressionExecutor)

Example 4 with BoolConstant

use of io.siddhi.query.api.expression.constant.BoolConstant in project siddhi by wso2.

the class SiddhiQLBaseVisitorImpl method visitBool_value.

/**
 * {@inheritDoc}
 * <p>The default implementation returns the result of calling
 * {@link #visitChildren} on {@code ctx}.</p>
 *
 * @param ctx
 */
@Override
public BoolConstant visitBool_value(@NotNull SiddhiQLParser.Bool_valueContext ctx) {
    BoolConstant boolConstant = Expression.value("true".equalsIgnoreCase(ctx.getText()));
    populateQueryContext(boolConstant, ctx);
    return boolConstant;
}
Also used : BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant)

Example 5 with BoolConstant

use of io.siddhi.query.api.expression.constant.BoolConstant in project siddhi by wso2.

the class SiddhiQLBaseVisitorImpl method visitConstant_value.

/**
 * {@inheritDoc}
 * <p>The default implementation returns the result of calling
 * {@link #visitChildren} on {@code ctx}.</p>
 *
 * @param ctx
 */
@Override
public Constant visitConstant_value(@NotNull SiddhiQLParser.Constant_valueContext ctx) {
    // constant_value
    // :bool_value
    // |signed_double_value
    // |signed_float_value
    // |signed_long_value
    // |signed_int_value
    // |time_value
    // |string_value
    // ;
    Constant constant;
    if (ctx.bool_value() != null) {
        constant = Expression.value(((BoolConstant) visit(ctx.bool_value())).getValue());
    } else if (ctx.signed_double_value() != null) {
        constant = Expression.value(((DoubleConstant) visit(ctx.signed_double_value())).getValue());
    } else if (ctx.signed_float_value() != null) {
        constant = Expression.value(((FloatConstant) visit(ctx.signed_float_value())).getValue());
    } else if (ctx.signed_long_value() != null) {
        constant = Expression.value(((LongConstant) visit(ctx.signed_long_value())).getValue());
    } else if (ctx.signed_int_value() != null) {
        constant = Expression.value(((IntConstant) visit(ctx.signed_int_value())).getValue());
    } else if (ctx.time_value() != null) {
        constant = (TimeConstant) visit(ctx.time_value());
    } else if (ctx.string_value() != null) {
        constant = Expression.value(((StringConstant) visit(ctx.string_value())).getValue());
    } else {
        throw newSiddhiParserException(ctx);
    }
    populateQueryContext(constant, ctx);
    return constant;
}
Also used : BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) DoubleConstant(io.siddhi.query.api.expression.constant.DoubleConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) Constant(io.siddhi.query.api.expression.constant.Constant) BoolConstant(io.siddhi.query.api.expression.constant.BoolConstant) TimeConstant(io.siddhi.query.api.expression.constant.TimeConstant) LongConstant(io.siddhi.query.api.expression.constant.LongConstant) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) FloatConstant(io.siddhi.query.api.expression.constant.FloatConstant) IntConstant(io.siddhi.query.api.expression.constant.IntConstant) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) TimeConstant(io.siddhi.query.api.expression.constant.TimeConstant)

Aggregations

BoolConstant (io.siddhi.query.api.expression.constant.BoolConstant)5 MetaStateEvent (io.siddhi.core.event.state.MetaStateEvent)3 MetaStreamEvent (io.siddhi.core.event.stream.MetaStreamEvent)3 SiddhiAppCreationException (io.siddhi.core.exception.SiddhiAppCreationException)3 StateEvent (io.siddhi.core.event.state.StateEvent)2 ConstantExpressionExecutor (io.siddhi.core.executor.ConstantExpressionExecutor)2 ExpressionExecutor (io.siddhi.core.executor.ExpressionExecutor)2 VariableExpressionExecutor (io.siddhi.core.executor.VariableExpressionExecutor)2 AbstractDefinition (io.siddhi.query.api.definition.AbstractDefinition)2 SiddhiAppValidationException (io.siddhi.query.api.exception.SiddhiAppValidationException)2 AttributeFunction (io.siddhi.query.api.expression.AttributeFunction)2 Expression (io.siddhi.query.api.expression.Expression)2 Variable (io.siddhi.query.api.expression.Variable)2 Compare (io.siddhi.query.api.expression.condition.Compare)2 Constant (io.siddhi.query.api.expression.constant.Constant)2 DoubleConstant (io.siddhi.query.api.expression.constant.DoubleConstant)2 FloatConstant (io.siddhi.query.api.expression.constant.FloatConstant)2 IntConstant (io.siddhi.query.api.expression.constant.IntConstant)2 LongConstant (io.siddhi.query.api.expression.constant.LongConstant)2 StringConstant (io.siddhi.query.api.expression.constant.StringConstant)2