Search in sources :

Example 1 with Variable

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

the class AggregationRuntime method constructSelectorList.

private static List<OutputAttribute> constructSelectorList(boolean isProcessingOnExternalTime, boolean isDistributed, boolean isLatestEventColAdded, int baseAggregatorBeginIndex, int numGroupByVariables, List<Expression> finalBaseExpressions, AbstractDefinition incomingOutputStreamDefinition, List<Variable> newGroupByList) {
    List<OutputAttribute> selectorList = new ArrayList<>();
    List<Attribute> attributeList = incomingOutputStreamDefinition.getAttributeList();
    List<String> queryGroupByNames = newGroupByList.stream().map(Variable::getAttributeName).collect(Collectors.toList());
    Variable maxVariable;
    if (!isProcessingOnExternalTime) {
        maxVariable = new Variable(AGG_START_TIMESTAMP_COL);
    } else if (isLatestEventColAdded) {
        maxVariable = new Variable(AGG_LAST_TIMESTAMP_COL);
    } else {
        maxVariable = new Variable(AGG_EXTERNAL_TIMESTAMP_COL);
    }
    int i = 0;
    // Add timestamp selector
    OutputAttribute timestampAttribute;
    if (!isProcessingOnExternalTime && queryGroupByNames.contains(AGG_START_TIMESTAMP_COL)) {
        timestampAttribute = new OutputAttribute(new Variable(AGG_START_TIMESTAMP_COL));
    } else {
        timestampAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("max", new Variable(AGG_START_TIMESTAMP_COL)));
    }
    selectorList.add(timestampAttribute);
    i++;
    if (isDistributed) {
        selectorList.add(new OutputAttribute(AGG_SHARD_ID_COL, Expression.function("max", new Variable(AGG_SHARD_ID_COL))));
        i++;
    }
    if (isProcessingOnExternalTime) {
        OutputAttribute externalTimestampAttribute;
        if (queryGroupByNames.contains(AGG_START_TIMESTAMP_COL)) {
            externalTimestampAttribute = new OutputAttribute(new Variable(AGG_EXTERNAL_TIMESTAMP_COL));
        } else {
            externalTimestampAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("max", new Variable(AGG_EXTERNAL_TIMESTAMP_COL)));
        }
        selectorList.add(externalTimestampAttribute);
        i++;
    }
    for (int j = 0; j < numGroupByVariables; j++) {
        OutputAttribute groupByAttribute;
        Variable variable = new Variable(attributeList.get(i).getName());
        if (queryGroupByNames.contains(variable.getAttributeName())) {
            groupByAttribute = new OutputAttribute(variable);
        } else {
            groupByAttribute = new OutputAttribute(variable.getAttributeName(), Expression.function("incrementalAggregator", "last", new Variable(attributeList.get(i).getName()), maxVariable));
        }
        selectorList.add(groupByAttribute);
        i++;
    }
    if (isLatestEventColAdded) {
        baseAggregatorBeginIndex = baseAggregatorBeginIndex - 1;
    }
    for (; i < baseAggregatorBeginIndex; i++) {
        OutputAttribute outputAttribute;
        Variable variable = new Variable(attributeList.get(i).getName());
        if (queryGroupByNames.contains(variable.getAttributeName())) {
            outputAttribute = new OutputAttribute(variable);
        } else {
            outputAttribute = new OutputAttribute(attributeList.get(i).getName(), Expression.function("incrementalAggregator", "last", new Variable(attributeList.get(i).getName()), maxVariable));
        }
        selectorList.add(outputAttribute);
    }
    if (isLatestEventColAdded) {
        OutputAttribute lastTimestampAttribute = new OutputAttribute(AGG_LAST_TIMESTAMP_COL, Expression.function("max", new Variable(AGG_LAST_TIMESTAMP_COL)));
        selectorList.add(lastTimestampAttribute);
        i++;
    }
    for (Expression finalBaseExpression : finalBaseExpressions) {
        OutputAttribute outputAttribute = new OutputAttribute(attributeList.get(i).getName(), finalBaseExpression);
        selectorList.add(outputAttribute);
        i++;
    }
    return selectorList;
}
Also used : Variable(io.siddhi.query.api.expression.Variable) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) Expression(io.siddhi.query.api.expression.Expression) ArrayList(java.util.ArrayList) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute)

Example 2 with Variable

use of io.siddhi.query.api.expression.Variable 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 3 with Variable

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

the class AggregationExpressionBuilder method build.

private void build(Expression expression, AggregationExpressionVisitor expressionVisitor) {
    if (expression instanceof And) {
        build(((And) expression).getLeftExpression(), expressionVisitor);
        build(((And) expression).getRightExpression(), expressionVisitor);
        expressionVisitor.endVisitAnd();
    } else if (expression instanceof Or) {
        build(((Or) expression).getLeftExpression(), expressionVisitor);
        build(((Or) expression).getRightExpression(), expressionVisitor);
        expressionVisitor.endVisitOr();
    } else if (expression instanceof Not) {
        build(((Not) expression).getExpression(), expressionVisitor);
        expressionVisitor.endVisitNot();
    } else if (expression instanceof Compare) {
        build(((Compare) expression).getLeftExpression(), expressionVisitor);
        build(((Compare) expression).getRightExpression(), expressionVisitor);
        expressionVisitor.endVisitCompare(((Compare) expression).getOperator());
    } else if (expression instanceof Constant) {
        expressionVisitor.addConstantExpression(expression);
    } else if (expression instanceof Variable) {
        expressionVisitor.addVariableExpression(expression);
    } else if (expression instanceof IsNull) {
        IsNull isNull = (IsNull) expression;
        if (isNull.getExpression() != null) {
            build(((IsNull) expression).getExpression(), expressionVisitor);
            expressionVisitor.endVisitIsNull(null);
        }
    } else if (expression instanceof AttributeFunction) {
        Expression[] expressions = ((AttributeFunction) expression).getParameters();
        for (Expression value : expressions) {
            build(value, expressionVisitor);
        }
        expressionVisitor.endVisitAttributeFunction(((AttributeFunction) expression).getNamespace(), ((AttributeFunction) expression).getName(), expressions.length);
    } else if (expression instanceof Add) {
        build(((Add) expression).getLeftValue(), expressionVisitor);
        build(((Add) expression).getRightValue(), expressionVisitor);
        expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.ADD);
    } else if (expression instanceof Subtract) {
        build(((Subtract) expression).getLeftValue(), expressionVisitor);
        build(((Subtract) expression).getRightValue(), expressionVisitor);
        expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.SUBTRACT);
    } else if (expression instanceof Divide) {
        build(((Divide) expression).getLeftValue(), expressionVisitor);
        build(((Divide) expression).getRightValue(), expressionVisitor);
        expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.DIVIDE);
    } else if (expression instanceof Multiply) {
        build(((Multiply) expression).getLeftValue(), expressionVisitor);
        build(((Multiply) expression).getRightValue(), expressionVisitor);
        expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.MULTIPLY);
    } else if (expression instanceof Mod) {
        build(((Mod) expression).getLeftValue(), expressionVisitor);
        build(((Mod) expression).getRightValue(), expressionVisitor);
        expressionVisitor.endVisitMath(ExpressionVisitor.MathOperator.MOD);
    } else if (expression instanceof In) {
        build(((In) expression).getExpression(), expressionVisitor);
        expressionVisitor.endVisitIn(((In) expression).getSourceId());
    }
}
Also used : Add(io.siddhi.query.api.expression.math.Add) Or(io.siddhi.query.api.expression.condition.Or) Variable(io.siddhi.query.api.expression.Variable) Mod(io.siddhi.query.api.expression.math.Mod) In(io.siddhi.query.api.expression.condition.In) Constant(io.siddhi.query.api.expression.constant.Constant) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) Divide(io.siddhi.query.api.expression.math.Divide) Not(io.siddhi.query.api.expression.condition.Not) Expression(io.siddhi.query.api.expression.Expression) And(io.siddhi.query.api.expression.condition.And) Multiply(io.siddhi.query.api.expression.math.Multiply) Subtract(io.siddhi.query.api.expression.math.Subtract) Compare(io.siddhi.query.api.expression.condition.Compare) IsNull(io.siddhi.query.api.expression.condition.IsNull)

Example 4 with Variable

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

the class AggregationExpressionVisitor method addVariableExpression.

public void addVariableExpression(Expression expression) {
    Variable variable = (Variable) expression;
    String streamId = variable.getStreamId();
    if (streamId == null) {
        if (this.allAttributesList.contains(variable.getAttributeName())) {
            this.conditionOperands.push(expression);
        } else {
            this.conditionOperands.push("true");
        }
    } else {
        if (streamId.equals(inputStreamRefId)) {
            this.conditionOperands.push(expression);
        } else if (this.tableAttributesNameList.contains(variable.getAttributeName())) {
            this.conditionOperands.push(expression);
        } else {
            this.conditionOperands.push("true");
        }
    }
}
Also used : Variable(io.siddhi.query.api.expression.Variable)

Example 5 with Variable

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

the class IncrementalDataPurger method createCompileConditions.

/**
 * Building the compiled conditions for purge data
 */
private Map<TimePeriod.Duration, CompiledCondition> createCompileConditions(Map<TimePeriod.Duration, Table> aggregationTables, Map<String, Table> tableMap) {
    Map<TimePeriod.Duration, CompiledCondition> compiledConditionMap = new EnumMap<>(TimePeriod.Duration.class);
    CompiledCondition compiledCondition;
    Table table;
    for (Map.Entry<TimePeriod.Duration, Table> entry : aggregationTables.entrySet()) {
        if (!retentionPeriods.get(entry.getKey()).equals(RETAIN_ALL)) {
            table = aggregationTables.get(entry.getKey());
            Variable leftVariable = new Variable(purgingTimestampField);
            leftVariable.setStreamId(entry.getValue().getTableDefinition().getId());
            Compare expression = new Compare(leftVariable, Compare.Operator.LESS_THAN, new Variable(purgingTimestampField));
            compiledCondition = table.compileCondition(expression, matchingMetaInfoHolder(table, aggregatedTimestampAttribute), variableExpressionExecutorList, tableMap, siddhiQueryContext);
            compiledConditionMap.put(entry.getKey(), compiledCondition);
        }
    }
    return compiledConditionMap;
}
Also used : Table(io.siddhi.core.table.Table) Variable(io.siddhi.query.api.expression.Variable) CompiledCondition(io.siddhi.core.util.collection.operator.CompiledCondition) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) Time.normalizeDuration(io.siddhi.query.api.expression.Expression.Time.normalizeDuration) Compare(io.siddhi.query.api.expression.condition.Compare) EnumMap(java.util.EnumMap) HashMap(java.util.HashMap) Map(java.util.Map) EnumMap(java.util.EnumMap)

Aggregations

Variable (io.siddhi.query.api.expression.Variable)30 Attribute (io.siddhi.query.api.definition.Attribute)18 MetaStreamEvent (io.siddhi.core.event.stream.MetaStreamEvent)15 OutputAttribute (io.siddhi.query.api.execution.query.selection.OutputAttribute)14 Expression (io.siddhi.query.api.expression.Expression)14 ArrayList (java.util.ArrayList)14 VariableExpressionExecutor (io.siddhi.core.executor.VariableExpressionExecutor)13 ExpressionExecutor (io.siddhi.core.executor.ExpressionExecutor)11 MetaStateEvent (io.siddhi.core.event.state.MetaStateEvent)10 ConstantExpressionExecutor (io.siddhi.core.executor.ConstantExpressionExecutor)10 SiddhiAppCreationException (io.siddhi.core.exception.SiddhiAppCreationException)9 MatchingMetaInfoHolder (io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder)8 AbstractDefinition (io.siddhi.query.api.definition.AbstractDefinition)8 Table (io.siddhi.core.table.Table)7 AttributeFunction (io.siddhi.query.api.expression.AttributeFunction)7 Compare (io.siddhi.query.api.expression.condition.Compare)7 TableDefinition (io.siddhi.query.api.definition.TableDefinition)6 SiddhiQueryContext (io.siddhi.core.config.SiddhiQueryContext)4 MetaStateEventAttribute (io.siddhi.core.event.state.MetaStateEventAttribute)4 ConditionExpressionExecutor (io.siddhi.core.executor.condition.ConditionExpressionExecutor)4