Search in sources :

Example 6 with Expression

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

the class AggregationExpressionVisitor method endVisitMath.

@Override
public void endVisitMath(MathOperator mathOperator) {
    Object rightOperand = this.conditionOperands.pop();
    Object leftOperand = this.conditionOperands.pop();
    if (!(rightOperand instanceof String) && !(leftOperand instanceof String)) {
        Expression expression = null;
        switch(mathOperator) {
            case ADD:
                expression = Expression.add(((Expression) leftOperand), ((Expression) rightOperand));
                break;
            case SUBTRACT:
                expression = Expression.subtract(((Expression) leftOperand), ((Expression) rightOperand));
                break;
            case MULTIPLY:
                expression = Expression.multiply(((Expression) leftOperand), ((Expression) rightOperand));
                break;
            case DIVIDE:
                expression = Expression.divide(((Expression) leftOperand), ((Expression) rightOperand));
                break;
            case MOD:
                expression = Expression.mod(((Expression) leftOperand), ((Expression) rightOperand));
                break;
            default:
                this.conditionOperands.push("true");
        }
        this.conditionOperands.push(expression);
    } else {
        this.conditionOperands.push("true");
    }
}
Also used : Expression(io.siddhi.query.api.expression.Expression)

Example 7 with Expression

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

the class SelectorParser method parse.

/**
 * Parse Selector portion of a query and return corresponding QuerySelector.
 *
 * @param selector                    selector to be parsed
 * @param outputStream                output stream
 * @param metaComplexEvent            Meta event used to collect execution info of stream associated with query
 * @param tableMap                    Table Map
 * @param variableExpressionExecutors variable expression executors
 * @param metaPosition                helps to identify the meta position of aggregates
 * @param processingMode              processing mode of the query
 * @param outputExpectsExpiredEvents  is expired events sent as output
 * @param siddhiQueryContext          current siddhi query context
 * @return QuerySelector
 */
public static QuerySelector parse(Selector selector, OutputStream outputStream, MetaComplexEvent metaComplexEvent, Map<String, Table> tableMap, List<VariableExpressionExecutor> variableExpressionExecutors, int metaPosition, ProcessingMode processingMode, boolean outputExpectsExpiredEvents, SiddhiQueryContext siddhiQueryContext) {
    boolean currentOn = false;
    boolean expiredOn = false;
    String id = null;
    if (outputStream.getOutputEventType() == OutputStream.OutputEventType.CURRENT_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
        currentOn = true;
    }
    if (outputStream.getOutputEventType() == OutputStream.OutputEventType.EXPIRED_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
        expiredOn = true;
    }
    boolean groupBy = !selector.getGroupByList().isEmpty();
    id = outputStream.getId();
    containsAggregatorThreadLocal.remove();
    QuerySelector querySelector = new QuerySelector(id, selector, currentOn, expiredOn, siddhiQueryContext);
    List<AttributeProcessor> attributeProcessors = getAttributeProcessors(selector, id, metaComplexEvent, tableMap, variableExpressionExecutors, outputStream, metaPosition, processingMode, outputExpectsExpiredEvents, groupBy, siddhiQueryContext);
    querySelector.setAttributeProcessorList(attributeProcessors, "true".equals(containsAggregatorThreadLocal.get()));
    containsAggregatorThreadLocal.remove();
    ConditionExpressionExecutor havingCondition = generateHavingExecutor(selector.getHavingExpression(), metaComplexEvent, tableMap, variableExpressionExecutors, siddhiQueryContext);
    querySelector.setHavingConditionExecutor(havingCondition, "true".equals(containsAggregatorThreadLocal.get()));
    containsAggregatorThreadLocal.remove();
    if (!selector.getGroupByList().isEmpty()) {
        List<Expression> groupByExpressionList = selector.getGroupByList().stream().map(groupByVariable -> (Expression) groupByVariable).collect(Collectors.toList());
        querySelector.setGroupByKeyGenerator(new GroupByKeyGenerator(groupByExpressionList, metaComplexEvent, SiddhiConstants.UNKNOWN_STATE, null, variableExpressionExecutors, siddhiQueryContext));
    }
    if (!selector.getOrderByList().isEmpty()) {
        querySelector.setOrderByEventComparator(new OrderByEventComparator(selector.getOrderByList(), metaComplexEvent, SiddhiConstants.HAVING_STATE, null, variableExpressionExecutors, siddhiQueryContext));
    }
    if (selector.getLimit() != null) {
        ExpressionExecutor expressionExecutor = ExpressionParser.parseExpression((Expression) selector.getLimit(), metaComplexEvent, SiddhiConstants.HAVING_STATE, tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        containsAggregatorThreadLocal.remove();
        querySelector.setLimit(((Number) (((ConstantExpressionExecutor) expressionExecutor).getValue())).longValue());
    }
    if (selector.getOffset() != null) {
        ExpressionExecutor expressionExecutor = ExpressionParser.parseExpression((Expression) selector.getOffset(), metaComplexEvent, SiddhiConstants.HAVING_STATE, tableMap, variableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        containsAggregatorThreadLocal.remove();
        querySelector.setOffset(((Number) (((ConstantExpressionExecutor) expressionExecutor).getValue())).longValue());
    }
    return querySelector;
}
Also used : Selector(io.siddhi.query.api.execution.query.selection.Selector) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) Variable(io.siddhi.query.api.expression.Variable) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SiddhiConstants(io.siddhi.core.util.SiddhiConstants) QuerySelector(io.siddhi.core.query.selector.QuerySelector) Expression(io.siddhi.query.api.expression.Expression) ArrayList(java.util.ArrayList) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) AttributeProcessor(io.siddhi.core.query.selector.attribute.processor.AttributeProcessor) Table(io.siddhi.core.table.Table) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) MetaComplexEvent(io.siddhi.core.event.MetaComplexEvent) MetaStateEventAttribute(io.siddhi.core.event.state.MetaStateEventAttribute) Map(java.util.Map) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) ProcessingMode(io.siddhi.core.query.processor.ProcessingMode) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) OrderByEventComparator(io.siddhi.core.query.selector.OrderByEventComparator) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) Attribute(io.siddhi.query.api.definition.Attribute) DuplicateAttributeException(io.siddhi.query.api.exception.DuplicateAttributeException) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) Collectors(java.util.stream.Collectors) List(java.util.List) OutputStream(io.siddhi.query.api.execution.query.output.stream.OutputStream) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) Expression(io.siddhi.query.api.expression.Expression) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) QuerySelector(io.siddhi.core.query.selector.QuerySelector) AttributeProcessor(io.siddhi.core.query.selector.attribute.processor.AttributeProcessor) ConditionExpressionExecutor(io.siddhi.core.executor.condition.ConditionExpressionExecutor) OrderByEventComparator(io.siddhi.core.query.selector.OrderByEventComparator)

Example 8 with Expression

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

the class SingleInputStreamParser method generateProcessor.

public static Processor generateProcessor(StreamHandler streamHandler, MetaComplexEvent metaEvent, List<VariableExpressionExecutor> variableExpressionExecutors, Map<String, Table> tableMap, boolean supportsBatchProcessing, boolean outputExpectsExpiredEvents, boolean findToBeExecuted, SiddhiQueryContext siddhiQueryContext) {
    Expression[] parameters = streamHandler.getParameters();
    MetaStreamEvent metaStreamEvent;
    int stateIndex = SiddhiConstants.UNKNOWN_STATE;
    if (metaEvent instanceof MetaStateEvent) {
        stateIndex = ((MetaStateEvent) metaEvent).getStreamEventCount() - 1;
        metaStreamEvent = ((MetaStateEvent) metaEvent).getMetaStreamEvent(stateIndex);
    } else {
        metaStreamEvent = (MetaStreamEvent) metaEvent;
    }
    if (streamHandler instanceof Window) {
        metaStreamEvent.initializeOnAfterWindowData();
    }
    ExpressionExecutor[] attributeExpressionExecutors;
    if (parameters != null) {
        if (parameters.length > 0) {
            attributeExpressionExecutors = new ExpressionExecutor[parameters.length];
            for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) {
                attributeExpressionExecutors[i] = ExpressionParser.parseExpression(parameters[i], metaEvent, stateIndex, tableMap, variableExpressionExecutors, false, SiddhiConstants.CURRENT, ProcessingMode.BATCH, false, siddhiQueryContext);
            }
        } else {
            List<Attribute> attributeList = metaStreamEvent.getLastInputDefinition().getAttributeList();
            int parameterSize = attributeList.size();
            attributeExpressionExecutors = new ExpressionExecutor[parameterSize];
            for (int i = 0; i < parameterSize; i++) {
                attributeExpressionExecutors[i] = ExpressionParser.parseExpression(new Variable(attributeList.get(i).getName()), metaEvent, stateIndex, tableMap, variableExpressionExecutors, false, SiddhiConstants.CURRENT, ProcessingMode.BATCH, false, siddhiQueryContext);
            }
        }
    } else {
        attributeExpressionExecutors = new ExpressionExecutor[0];
    }
    ConfigReader configReader;
    if (streamHandler instanceof Filter) {
        return new FilterProcessor(attributeExpressionExecutors[0]);
    } else if (streamHandler instanceof Window) {
        WindowProcessor windowProcessor = (WindowProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, WindowProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
        configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((Window) streamHandler).getNamespace(), ((Window) streamHandler).getName());
        windowProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, findToBeExecuted, false, streamHandler, siddhiQueryContext);
        return windowProcessor;
    } else if (streamHandler instanceof StreamFunction) {
        AbstractStreamProcessor abstractStreamProcessor;
        configReader = siddhiQueryContext.getSiddhiContext().getConfigManager().generateConfigReader(((StreamFunction) streamHandler).getNamespace(), ((StreamFunction) streamHandler).getName());
        if (supportsBatchProcessing) {
            try {
                abstractStreamProcessor = (StreamProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, StreamProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
                abstractStreamProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, false, false, streamHandler, siddhiQueryContext);
                return abstractStreamProcessor;
            } catch (SiddhiAppCreationException e) {
                if (!e.isClassLoadingIssue()) {
                    ExceptionUtil.populateQueryContext(e, streamHandler, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
                    throw e;
                }
            }
        }
        abstractStreamProcessor = (StreamFunctionProcessor) SiddhiClassLoader.loadExtensionImplementation((Extension) streamHandler, StreamFunctionProcessorExtensionHolder.getInstance(siddhiQueryContext.getSiddhiAppContext()));
        abstractStreamProcessor.initProcessor(metaStreamEvent, attributeExpressionExecutors, configReader, outputExpectsExpiredEvents, false, false, streamHandler, siddhiQueryContext);
        return abstractStreamProcessor;
    } else {
        throw new SiddhiAppCreationException(streamHandler.getClass().getName() + " is not supported", streamHandler.getQueryContextStartIndex(), streamHandler.getQueryContextEndIndex());
    }
}
Also used : Window(io.siddhi.query.api.execution.query.input.handler.Window) Variable(io.siddhi.query.api.expression.Variable) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) AbstractStreamProcessor(io.siddhi.core.query.processor.stream.AbstractStreamProcessor) Attribute(io.siddhi.query.api.definition.Attribute) FilterProcessor(io.siddhi.core.query.processor.filter.FilterProcessor) StreamFunction(io.siddhi.query.api.execution.query.input.handler.StreamFunction) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) ConfigReader(io.siddhi.core.util.config.ConfigReader) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) Expression(io.siddhi.query.api.expression.Expression) Filter(io.siddhi.query.api.execution.query.input.handler.Filter) WindowProcessor(io.siddhi.core.query.processor.stream.window.WindowProcessor) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 9 with Expression

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

the class JoinInputStreamParser method parseInputStream.

public static StreamRuntime parseInputStream(JoinInputStream joinInputStream, Query query, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap, List<VariableExpressionExecutor> executors, boolean outputExpectsExpiredEvents, SiddhiQueryContext siddhiQueryContext) {
    try {
        ProcessStreamReceiver leftProcessStreamReceiver;
        ProcessStreamReceiver rightProcessStreamReceiver;
        MetaStreamEvent leftMetaStreamEvent = new MetaStreamEvent();
        MetaStreamEvent rightMetaStreamEvent = new MetaStreamEvent();
        String leftInputStreamId = ((SingleInputStream) joinInputStream.getLeftInputStream()).getStreamId();
        String rightInputStreamId = ((SingleInputStream) joinInputStream.getRightInputStream()).getStreamId();
        boolean leftOuterJoinProcessor = false;
        boolean rightOuterJoinProcessor = false;
        if (joinInputStream.getAllStreamIds().size() == 2) {
            setEventType(streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, leftMetaStreamEvent, leftInputStreamId);
            setEventType(streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, rightMetaStreamEvent, rightInputStreamId);
            leftProcessStreamReceiver = new ProcessStreamReceiver(leftInputStreamId, siddhiQueryContext);
            rightProcessStreamReceiver = new ProcessStreamReceiver(rightInputStreamId, siddhiQueryContext);
            if ((leftMetaStreamEvent.getEventType() == TABLE || leftMetaStreamEvent.getEventType() == AGGREGATE) && (rightMetaStreamEvent.getEventType() == TABLE || rightMetaStreamEvent.getEventType() == AGGREGATE)) {
                throw new SiddhiAppCreationException("Both inputs of join " + leftInputStreamId + " and " + rightInputStreamId + " are from static sources");
            }
            if (leftMetaStreamEvent.getEventType() != AGGREGATE && rightMetaStreamEvent.getEventType() != AGGREGATE) {
                if (joinInputStream.getPer() != null) {
                    throw new SiddhiAppCreationException("When joining " + leftInputStreamId + " and " + rightInputStreamId + " 'per' cannot be used as neither of them is an aggregation ");
                } else if (joinInputStream.getWithin() != null) {
                    throw new SiddhiAppCreationException("When joining " + leftInputStreamId + " and " + rightInputStreamId + " 'within' cannot be used as neither of them is an aggregation ");
                }
            }
        } else {
            if (windowDefinitionMap.containsKey(joinInputStream.getAllStreamIds().get(0))) {
                leftMetaStreamEvent.setEventType(WINDOW);
                rightMetaStreamEvent.setEventType(WINDOW);
                rightProcessStreamReceiver = new MultiProcessStreamReceiver(joinInputStream.getAllStreamIds().get(0), 1, new Object(), siddhiQueryContext);
                leftProcessStreamReceiver = rightProcessStreamReceiver;
            } else if (streamDefinitionMap.containsKey(joinInputStream.getAllStreamIds().get(0))) {
                rightProcessStreamReceiver = new MultiProcessStreamReceiver(joinInputStream.getAllStreamIds().get(0), 2, new Object(), siddhiQueryContext);
                leftProcessStreamReceiver = rightProcessStreamReceiver;
            } else {
                throw new SiddhiAppCreationException("Input of join is from static source " + leftInputStreamId + " and " + rightInputStreamId);
            }
        }
        SingleStreamRuntime leftStreamRuntime = SingleInputStreamParser.parseInputStream((SingleInputStream) joinInputStream.getLeftInputStream(), executors, streamDefinitionMap, leftMetaStreamEvent.getEventType() != TABLE ? null : tableDefinitionMap, leftMetaStreamEvent.getEventType() != WINDOW ? null : windowDefinitionMap, leftMetaStreamEvent.getEventType() != AGGREGATE ? null : aggregationDefinitionMap, tableMap, leftMetaStreamEvent, leftProcessStreamReceiver, true, outputExpectsExpiredEvents, true, false, siddhiQueryContext);
        for (VariableExpressionExecutor variableExpressionExecutor : executors) {
            variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = 0;
        }
        int size = executors.size();
        SingleStreamRuntime rightStreamRuntime = SingleInputStreamParser.parseInputStream((SingleInputStream) joinInputStream.getRightInputStream(), executors, streamDefinitionMap, rightMetaStreamEvent.getEventType() != TABLE ? null : tableDefinitionMap, rightMetaStreamEvent.getEventType() != WINDOW ? null : windowDefinitionMap, rightMetaStreamEvent.getEventType() != AGGREGATE ? null : aggregationDefinitionMap, tableMap, rightMetaStreamEvent, rightProcessStreamReceiver, true, outputExpectsExpiredEvents, true, false, siddhiQueryContext);
        for (int i = size; i < executors.size(); i++) {
            VariableExpressionExecutor variableExpressionExecutor = executors.get(i);
            variableExpressionExecutor.getPosition()[SiddhiConstants.STREAM_EVENT_CHAIN_INDEX] = 1;
        }
        setStreamRuntimeProcessorChain(leftMetaStreamEvent, leftStreamRuntime, leftInputStreamId, tableMap, windowMap, aggregationMap, executors, outputExpectsExpiredEvents, joinInputStream.getWithin(), joinInputStream.getPer(), query.getSelector().getGroupByList(), siddhiQueryContext, joinInputStream.getLeftInputStream());
        setStreamRuntimeProcessorChain(rightMetaStreamEvent, rightStreamRuntime, rightInputStreamId, tableMap, windowMap, aggregationMap, executors, outputExpectsExpiredEvents, joinInputStream.getWithin(), joinInputStream.getPer(), query.getSelector().getGroupByList(), siddhiQueryContext, joinInputStream.getRightInputStream());
        MetaStateEvent metaStateEvent = new MetaStateEvent(2);
        metaStateEvent.addEvent(leftMetaStreamEvent);
        metaStateEvent.addEvent(rightMetaStreamEvent);
        switch(joinInputStream.getType()) {
            case FULL_OUTER_JOIN:
                leftOuterJoinProcessor = true;
                rightOuterJoinProcessor = true;
                break;
            case RIGHT_OUTER_JOIN:
                rightOuterJoinProcessor = true;
                break;
            case LEFT_OUTER_JOIN:
                leftOuterJoinProcessor = true;
                break;
        }
        JoinProcessor leftPreJoinProcessor = new JoinProcessor(true, true, leftOuterJoinProcessor, 0, siddhiQueryContext.getSiddhiAppContext().getName(), siddhiQueryContext.getName());
        JoinProcessor leftPostJoinProcessor = new JoinProcessor(true, false, leftOuterJoinProcessor, 0, siddhiQueryContext.getSiddhiAppContext().getName(), siddhiQueryContext.getName());
        FindableProcessor leftFindableProcessor = insertJoinProcessorsAndGetFindable(leftPreJoinProcessor, leftPostJoinProcessor, leftStreamRuntime, outputExpectsExpiredEvents, joinInputStream.getLeftInputStream(), siddhiQueryContext);
        JoinProcessor rightPreJoinProcessor = new JoinProcessor(false, true, rightOuterJoinProcessor, 1, siddhiQueryContext.getSiddhiAppContext().getName(), siddhiQueryContext.getName());
        JoinProcessor rightPostJoinProcessor = new JoinProcessor(false, false, rightOuterJoinProcessor, 1, siddhiQueryContext.getSiddhiAppContext().getName(), siddhiQueryContext.getName());
        FindableProcessor rightFindableProcessor = insertJoinProcessorsAndGetFindable(rightPreJoinProcessor, rightPostJoinProcessor, rightStreamRuntime, outputExpectsExpiredEvents, joinInputStream.getRightInputStream(), siddhiQueryContext);
        leftPreJoinProcessor.setFindableProcessor(rightFindableProcessor);
        leftPostJoinProcessor.setFindableProcessor(rightFindableProcessor);
        rightPreJoinProcessor.setFindableProcessor(leftFindableProcessor);
        rightPostJoinProcessor.setFindableProcessor(leftFindableProcessor);
        Expression compareCondition = joinInputStream.getOnCompare();
        if (compareCondition == null) {
            compareCondition = Expression.value(true);
        }
        QuerySelector querySelector = null;
        if (!(rightFindableProcessor instanceof TableWindowProcessor || rightFindableProcessor instanceof AggregateWindowProcessor) && (joinInputStream.getTrigger() != JoinInputStream.EventTrigger.LEFT)) {
            MatchingMetaInfoHolder leftMatchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(metaStateEvent, 1, leftMetaStreamEvent.getLastInputDefinition(), SiddhiConstants.UNKNOWN_STATE);
            CompiledCondition rightCompiledCondition = leftFindableProcessor.compileCondition(compareCondition, leftMatchingMetaInfoHolder, executors, tableMap, siddhiQueryContext);
            List<Attribute> expectedOutputAttributes = new ArrayList<>();
            CompiledSelection rightCompiledSelection = null;
            if (leftFindableProcessor instanceof TableWindowProcessor && ((TableWindowProcessor) leftFindableProcessor).isOptimisableLookup()) {
                querySelector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), metaStateEvent, tableMap, executors, SiddhiConstants.UNKNOWN_STATE, ProcessingMode.BATCH, outputExpectsExpiredEvents, siddhiQueryContext);
                expectedOutputAttributes = metaStateEvent.getOutputStreamDefinition().getAttributeList();
                try {
                    rightCompiledSelection = ((QueryableProcessor) leftFindableProcessor).compileSelection(query.getSelector(), expectedOutputAttributes, leftMatchingMetaInfoHolder, executors, tableMap, siddhiQueryContext);
                } catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Performing select clause in databases failed for query: '" + siddhiQueryContext.getName() + "' within Siddhi app '" + siddhiQueryContext.getSiddhiAppContext().getName() + "' hence reverting back to " + "querying only with where clause. Reason for failure: " + e.getMessage(), e);
                    }
                // Nothing to override
                }
            }
            populateJoinProcessors(rightMetaStreamEvent, rightInputStreamId, rightPreJoinProcessor, rightPostJoinProcessor, rightCompiledCondition, rightCompiledSelection, expectedOutputAttributes);
        }
        if (!(leftFindableProcessor instanceof TableWindowProcessor || leftFindableProcessor instanceof AggregateWindowProcessor) && (joinInputStream.getTrigger() != JoinInputStream.EventTrigger.RIGHT)) {
            MatchingMetaInfoHolder rightMatchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(metaStateEvent, 0, rightMetaStreamEvent.getLastInputDefinition(), SiddhiConstants.UNKNOWN_STATE);
            CompiledCondition leftCompiledCondition = rightFindableProcessor.compileCondition(compareCondition, rightMatchingMetaInfoHolder, executors, tableMap, siddhiQueryContext);
            List<Attribute> expectedOutputAttributes = new ArrayList<>();
            CompiledSelection leftCompiledSelection = null;
            if (rightFindableProcessor instanceof TableWindowProcessor && ((TableWindowProcessor) rightFindableProcessor).isOptimisableLookup()) {
                querySelector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), metaStateEvent, tableMap, executors, SiddhiConstants.UNKNOWN_STATE, ProcessingMode.BATCH, outputExpectsExpiredEvents, siddhiQueryContext);
                expectedOutputAttributes = metaStateEvent.getOutputStreamDefinition().getAttributeList();
                try {
                    leftCompiledSelection = ((QueryableProcessor) rightFindableProcessor).compileSelection(query.getSelector(), expectedOutputAttributes, rightMatchingMetaInfoHolder, executors, tableMap, siddhiQueryContext);
                } catch (SiddhiAppCreationException | SiddhiAppValidationException | QueryableRecordTableException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Performing select clause in databases failed for query: '" + siddhiQueryContext.getName() + "' within Siddhi app '" + siddhiQueryContext.getSiddhiAppContext().getName() + "' hence reverting back to " + "querying only with where clause. Reason for failure: " + e.getMessage(), e);
                    }
                // Nothing to override
                }
            }
            populateJoinProcessors(leftMetaStreamEvent, leftInputStreamId, leftPreJoinProcessor, leftPostJoinProcessor, leftCompiledCondition, leftCompiledSelection, expectedOutputAttributes);
        }
        JoinStreamRuntime joinStreamRuntime = new JoinStreamRuntime(siddhiQueryContext, metaStateEvent);
        joinStreamRuntime.addRuntime(leftStreamRuntime);
        joinStreamRuntime.addRuntime(rightStreamRuntime);
        joinStreamRuntime.setQuerySelector(querySelector);
        return joinStreamRuntime;
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, joinInputStream, siddhiQueryContext.getSiddhiAppContext(), siddhiQueryContext);
        throw t;
    }
}
Also used : ProcessStreamReceiver(io.siddhi.core.query.input.ProcessStreamReceiver) MultiProcessStreamReceiver(io.siddhi.core.query.input.MultiProcessStreamReceiver) TableWindowProcessor(io.siddhi.core.query.processor.stream.window.TableWindowProcessor) Attribute(io.siddhi.query.api.definition.Attribute) ArrayList(java.util.ArrayList) AggregateWindowProcessor(io.siddhi.core.query.processor.stream.window.AggregateWindowProcessor) SingleInputStream(io.siddhi.query.api.execution.query.input.stream.SingleInputStream) QueryableRecordTableException(io.siddhi.core.exception.QueryableRecordTableException) JoinProcessor(io.siddhi.core.query.input.stream.join.JoinProcessor) FindableProcessor(io.siddhi.core.query.processor.stream.window.FindableProcessor) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(io.siddhi.core.query.input.stream.join.JoinStreamRuntime) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) MultiProcessStreamReceiver(io.siddhi.core.query.input.MultiProcessStreamReceiver) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) QuerySelector(io.siddhi.core.query.selector.QuerySelector) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent) 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) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 10 with Expression

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

the class AggregationParser method initAggregateQueryExecutor.

private static Map<TimePeriod.Duration, Processor> initAggregateQueryExecutor(List<TimePeriod.Duration> aggregationDurations, Map<TimePeriod.Duration, List<ExpressionExecutor>> processExpressionExecutorsMap, StreamDefinition incomingOutputStreamDefinition, boolean isDistributed, String shardID, boolean isProcessingOnExternalTime, SiddhiQueryContext siddhiQueryContext, AggregationDefinition aggregationDefinition, ConfigManager configManager, Map<TimePeriod.Duration, Table> aggregationTables, List<Variable> groupByVariableList) {
    Map<TimePeriod.Duration, Processor> cudProcessors = new LinkedHashMap<>();
    String datasourceName = AnnotationHelper.getAnnotationElement(SiddhiConstants.NAMESPACE_STORE, "datasource", aggregationDefinition.getAnnotations()).getValue();
    if (datasourceName == null || datasourceName.isEmpty()) {
        throw new SiddhiAppCreationException("Datasource configuration must be provided inorder to use persisted " + "aggregation mode");
    }
    Database databaseType = getDatabaseType(configManager, datasourceName);
    if (log.isDebugEnabled()) {
        log.debug("Database type " + databaseType);
    }
    SiddhiAppContext cudSiddhiAppContext = new SiddhiAppContext();
    SiddhiContext context = new SiddhiContext();
    context.setConfigManager(configManager);
    cudSiddhiAppContext.setSiddhiContext(context);
    StringConstant datasource = new StringConstant(datasourceName);
    ConstantExpressionExecutor datasourceExecutor = new ConstantExpressionExecutor(datasource.getValue(), Attribute.Type.STRING);
    Expression[] streamHandler;
    ExpressionExecutor[] cudStreamProcessorInputVariables;
    if (isProcessingOnExternalTime) {
        streamHandler = new Expression[7];
    } else {
        streamHandler = new Expression[5];
    }
    try {
        DBAggregationQueryConfigurationEntry dbAggregationQueryConfigurationEntry = DBAggregationQueryUtil.lookupCurrentQueryConfigurationEntry(databaseType);
        if (log.isDebugEnabled()) {
            log.debug("CUD queries for aggregation " + aggregationDefinition.getId());
        }
        for (int i = aggregationDurations.size() - 1; i > 0; i--) {
            if (aggregationDurations.get(i).ordinal() >= 3) {
                if (log.isDebugEnabled()) {
                    log.debug(" Initializing cudProcessors for duration " + aggregationDurations.get(i));
                }
                String databaseSelectQuery = generateDatabaseQuery(processExpressionExecutorsMap.get(aggregationDurations.get(i)), dbAggregationQueryConfigurationEntry, incomingOutputStreamDefinition, isDistributed, shardID, isProcessingOnExternalTime, aggregationTables.get(aggregationDurations.get(i)), aggregationTables.get(aggregationDurations.get(i - 1)), groupByVariableList, aggregationDurations.get(i));
                StringConstant selectQuery = new StringConstant(databaseSelectQuery);
                if (log.isDebugEnabled()) {
                    log.debug(selectQuery);
                }
                ConstantExpressionExecutor selectExecutor = new ConstantExpressionExecutor(selectQuery.getValue(), Attribute.Type.STRING);
                Map<Attribute, int[]> cudInputStreamAttributesMap = generateCUDInputStreamAttributes(isProcessingOnExternalTime);
                if (isProcessingOnExternalTime) {
                    cudStreamProcessorInputVariables = new ExpressionExecutor[7];
                } else {
                    cudStreamProcessorInputVariables = new ExpressionExecutor[5];
                }
                cudStreamProcessorInputVariables[0] = datasourceExecutor;
                cudStreamProcessorInputVariables[1] = selectExecutor;
                streamHandler[0] = datasource;
                streamHandler[1] = selectQuery;
                MetaStreamEvent metaStreamEvent = generateCUDMetaStreamEvent(isProcessingOnExternalTime);
                StreamDefinition outputStream = new StreamDefinition();
                VariableExpressionExecutor variableExpressionExecutor;
                int j = 0;
                for (Map.Entry<Attribute, int[]> entry : cudInputStreamAttributesMap.entrySet()) {
                    Attribute attribute = entry.getKey();
                    Variable timestampVariable = new Variable(attribute.getName());
                    for (int position : entry.getValue()) {
                        streamHandler[position + 2] = timestampVariable;
                        variableExpressionExecutor = new VariableExpressionExecutor(attribute, 0, 0);
                        variableExpressionExecutor.setPosition(new int[] { 2, j });
                        cudStreamProcessorInputVariables[position + 2] = variableExpressionExecutor;
                    }
                    outputStream.attribute(attribute.getName(), attribute.getType());
                    j++;
                }
                StreamFunction cudStreamFunction = new StreamFunction(NAMESPACE_RDBMS, FUNCTION_NAME_CUD, streamHandler);
                cudProcessors.put(aggregationDurations.get(i), getCudProcessor(cudStreamFunction, siddhiQueryContext, metaStreamEvent, cudStreamProcessorInputVariables, aggregationDurations.get(i)));
            }
        }
        return cudProcessors;
    } catch (CannotLoadConfigurationException e) {
        throw new SiddhiAppCreationException("Error occurred while initializing the persisted incremental " + "aggregation. Could not load the db quires for database type " + databaseType);
    }
}
Also used : PersistedAggregationResultsProcessor(io.siddhi.core.aggregation.persistedaggregation.config.PersistedAggregationResultsProcessor) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) AbstractStreamProcessor(io.siddhi.core.query.processor.stream.AbstractStreamProcessor) QueuedCudStreamProcessor(io.siddhi.core.aggregation.persistedaggregation.QueuedCudStreamProcessor) StreamProcessor(io.siddhi.core.query.processor.stream.StreamProcessor) Processor(io.siddhi.core.query.processor.Processor) IncrementalAggregationProcessor(io.siddhi.core.aggregation.IncrementalAggregationProcessor) Variable(io.siddhi.query.api.expression.Variable) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) SiddhiContext(io.siddhi.core.config.SiddhiContext) LinkedHashMap(java.util.LinkedHashMap) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) DBAggregationQueryConfigurationEntry(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationQueryConfigurationEntry) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) StreamFunction(io.siddhi.query.api.execution.query.input.handler.StreamFunction) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) CannotLoadConfigurationException(io.siddhi.core.exception.CannotLoadConfigurationException) Expression(io.siddhi.query.api.expression.Expression) SiddhiAppContext(io.siddhi.core.config.SiddhiAppContext) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Aggregations

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