Search in sources :

Example 1 with Table

use of org.ballerinalang.siddhi.core.table.Table in project ballerina by ballerina-lang.

the class AggregationParser method initDefaultTables.

private static HashMap<TimePeriod.Duration, Table> initDefaultTables(String aggregatorName, List<TimePeriod.Duration> durations, StreamDefinition streamDefinition, SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder, List<Annotation> annotations, List<Variable> groupByVariableList) {
    HashMap<TimePeriod.Duration, Table> aggregationTableMap = new HashMap<>();
    // Create annotations for primary key
    Annotation primaryKeyAnnotation = new Annotation(SiddhiConstants.ANNOTATION_PRIMARY_KEY);
    primaryKeyAnnotation.element(null, "AGG_TIMESTAMP");
    for (Variable groupByVariable : groupByVariableList) {
        primaryKeyAnnotation.element(null, groupByVariable.getAttributeName());
    }
    annotations.add(primaryKeyAnnotation);
    for (TimePeriod.Duration duration : durations) {
        String tableId = aggregatorName + "_" + duration.toString();
        TableDefinition tableDefinition = TableDefinition.id(tableId);
        for (Attribute attribute : streamDefinition.getAttributeList()) {
            tableDefinition.attribute(attribute.getName(), attribute.getType());
        }
        annotations.forEach(tableDefinition::annotation);
        siddhiAppRuntimeBuilder.defineTable(tableDefinition);
        aggregationTableMap.put(duration, siddhiAppRuntimeBuilder.getTableMap().get(tableId));
    }
    return aggregationTableMap;
}
Also used : Table(org.ballerinalang.siddhi.core.table.Table) Variable(org.ballerinalang.siddhi.query.api.expression.Variable) HashMap(java.util.HashMap) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) OutputAttribute(org.ballerinalang.siddhi.query.api.execution.query.selection.OutputAttribute) TimePeriod(org.ballerinalang.siddhi.query.api.aggregation.TimePeriod) TableDefinition(org.ballerinalang.siddhi.query.api.definition.TableDefinition) Annotation(org.ballerinalang.siddhi.query.api.annotation.Annotation)

Example 2 with Table

use of org.ballerinalang.siddhi.core.table.Table in project ballerina by ballerina-lang.

the class AggregationParser method parse.

public static AggregationRuntime parse(AggregationDefinition aggregationDefinition, SiddhiAppContext siddhiAppContext, 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, SiddhiAppRuntimeBuilder siddhiAppRuntimeBuilder) {
    if (aggregationDefinition == null) {
        throw new SiddhiAppCreationException("AggregationDefinition instance is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'");
    }
    if (aggregationDefinition.getTimePeriod() == null) {
        throw new SiddhiAppCreationException("AggregationDefinition '" + aggregationDefinition.getId() + "'s timePeriod is null. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (aggregationDefinition.getSelector() == null) {
        throw new SiddhiAppCreationException("AggregationDefinition '" + aggregationDefinition.getId() + "'s selection is not defined. " + "Hence, can't create the siddhi app '" + siddhiAppContext.getName() + "'", aggregationDefinition.getQueryContextStartIndex(), aggregationDefinition.getQueryContextEndIndex());
    }
    if (streamDefinitionMap.get(aggregationDefinition.getBasicSingleInputStream().getStreamId()) == null) {
        throw new SiddhiAppCreationException("Stream " + aggregationDefinition.getBasicSingleInputStream().getStreamId() + " has not been defined");
    }
    try {
        List<VariableExpressionExecutor> incomingVariableExpressionExecutors = new ArrayList<>();
        String aggregatorName = aggregationDefinition.getId();
        StreamRuntime streamRuntime = InputStreamParser.parse(aggregationDefinition.getBasicSingleInputStream(), siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, incomingVariableExpressionExecutors, null, false, aggregatorName);
        // Get original meta for later use.
        MetaStreamEvent incomingMetaStreamEvent = (MetaStreamEvent) streamRuntime.getMetaComplexEvent();
        // Create new meta stream event.
        // This must hold the timestamp, group by attributes (if given) and the incremental attributes, in
        // onAfterWindowData array
        // Example format: AGG_TIMESTAMP, groupByAttribute1, groupByAttribute2, AGG_incAttribute1, AGG_incAttribute2
        // AGG_incAttribute1, AGG_incAttribute2 would have the same attribute names as in
        // finalListOfIncrementalAttributes
        // To enter data as onAfterWindowData
        incomingMetaStreamEvent.initializeAfterWindowData();
        List<ExpressionExecutor> incomingExpressionExecutors = new ArrayList<>();
        List<IncrementalAttributeAggregator> incrementalAttributeAggregators = new ArrayList<>();
        List<Variable> groupByVariableList = aggregationDefinition.getSelector().getGroupByList();
        boolean isProcessingOnExternalTime = aggregationDefinition.getAggregateAttribute() != null;
        // Expressions to get
        List<Expression> outputExpressions = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        // Expression executors to get
        List<ExpressionExecutor> outputExpressionExecutors = new ArrayList<>();
        // final aggregate outputs. e.g avg = sum/count
        populateIncomingAggregatorsAndExecutors(aggregationDefinition, siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, groupByVariableList, outputExpressions);
        int baseAggregatorBeginIndex = incomingMetaStreamEvent.getOutputData().size();
        List<Expression> finalBaseAggregators = getFinalBaseAggregators(siddhiAppContext, tableMap, incomingVariableExpressionExecutors, aggregatorName, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators);
        StreamDefinition incomingOutputStreamDefinition = StreamDefinition.id("");
        incomingOutputStreamDefinition.setQueryContextStartIndex(aggregationDefinition.getQueryContextStartIndex());
        incomingOutputStreamDefinition.setQueryContextEndIndex(aggregationDefinition.getQueryContextEndIndex());
        MetaStreamEvent processedMetaStreamEvent = new MetaStreamEvent();
        for (Attribute attribute : incomingMetaStreamEvent.getOutputData()) {
            incomingOutputStreamDefinition.attribute(attribute.getName(), attribute.getType());
            processedMetaStreamEvent.addOutputData(attribute);
        }
        incomingMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.addInputDefinition(incomingOutputStreamDefinition);
        processedMetaStreamEvent.setOutputDefinition(incomingOutputStreamDefinition);
        // Executors of processing meta
        List<VariableExpressionExecutor> processVariableExpressionExecutors = new ArrayList<>();
        boolean groupBy = aggregationDefinition.getSelector().getGroupByList().size() != 0;
        List<ExpressionExecutor> processExpressionExecutors = constructProcessExpressionExecutors(siddhiAppContext, tableMap, aggregatorName, baseAggregatorBeginIndex, finalBaseAggregators, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, groupBy);
        outputExpressionExecutors.addAll(outputExpressions.stream().map(expression -> ExpressionParser.parseExpression(expression, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, siddhiAppContext, groupBy, 0, aggregatorName)).collect(Collectors.toList()));
        // Create group by key generator
        GroupByKeyGenerator groupByKeyGenerator = null;
        if (groupBy) {
            groupByKeyGenerator = new GroupByKeyGenerator(groupByVariableList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiAppContext, aggregatorName);
        }
        // Create new scheduler
        EntryValveExecutor entryValveExecutor = new EntryValveExecutor(siddhiAppContext);
        LockWrapper lockWrapper = new LockWrapper(aggregatorName);
        lockWrapper.setLock(new ReentrantLock());
        Scheduler scheduler = SchedulerParser.parse(siddhiAppContext.getScheduledExecutorService(), entryValveExecutor, siddhiAppContext);
        scheduler.init(lockWrapper, aggregatorName);
        scheduler.setStreamEventPool(new StreamEventPool(processedMetaStreamEvent, 10));
        QueryParserHelper.reduceMetaComplexEvent(incomingMetaStreamEvent);
        QueryParserHelper.reduceMetaComplexEvent(processedMetaStreamEvent);
        QueryParserHelper.updateVariablePosition(incomingMetaStreamEvent, incomingVariableExpressionExecutors);
        QueryParserHelper.updateVariablePosition(processedMetaStreamEvent, processVariableExpressionExecutors);
        List<TimePeriod.Duration> incrementalDurations = getSortedPeriods(aggregationDefinition.getTimePeriod());
        Map<TimePeriod.Duration, Table> aggregationTables = initDefaultTables(aggregatorName, incrementalDurations, processedMetaStreamEvent.getOutputStreamDefinition(), siddhiAppRuntimeBuilder, aggregationDefinition.getAnnotations(), groupByVariableList);
        int bufferSize = 0;
        Element element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_BUFFER_SIZE, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            try {
                bufferSize = Integer.parseInt(element.getValue());
            } catch (NumberFormatException e) {
                throw new SiddhiAppCreationException(e.getMessage() + ": BufferSize must be an integer");
            }
        }
        if (bufferSize > 0) {
            TimePeriod.Duration rootDuration = incrementalDurations.get(0);
            if (rootDuration == TimePeriod.Duration.MONTHS || rootDuration == TimePeriod.Duration.YEARS) {
                throw new SiddhiAppCreationException("A buffer size greater than 0 can be provided, only when the " + "first duration value is seconds, minutes, hours or days");
            }
            if (!isProcessingOnExternalTime) {
                throw new SiddhiAppCreationException("Buffer size cannot be specified when events are aggregated " + "based on event arrival time.");
            // Buffer size is used to process out of order events. However, events would never be out of
            // order if they are processed based on event arrival time.
            }
        } else if (bufferSize < 0) {
            throw new SiddhiAppCreationException("Expected a positive integer as the buffer size, but found " + bufferSize + " as the provided value");
        }
        boolean ignoreEventsOlderThanBuffer = false;
        element = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_IGNORE_EVENTS_OLDER_THAN_BUFFER, null, aggregationDefinition.getAnnotations());
        if (element != null) {
            if (element.getValue().equalsIgnoreCase("true")) {
                ignoreEventsOlderThanBuffer = true;
            } else if (!element.getValue().equalsIgnoreCase("false")) {
                throw new SiddhiAppCreationException("IgnoreEventsOlderThanBuffer value must " + "be true or false");
            }
        }
        Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap = buildIncrementalExecutors(isProcessingOnExternalTime, processedMetaStreamEvent, processExpressionExecutors, groupByKeyGenerator, bufferSize, ignoreEventsOlderThanBuffer, incrementalDurations, aggregationTables, siddhiAppContext, aggregatorName);
        // Recreate in-memory data from tables
        RecreateInMemoryData recreateInMemoryData = new RecreateInMemoryData(incrementalDurations, aggregationTables, incrementalExecutorMap, siddhiAppContext, processedMetaStreamEvent, tableMap, windowMap, aggregationMap);
        IncrementalExecutor rootIncrementalExecutor = incrementalExecutorMap.get(incrementalDurations.get(0));
        rootIncrementalExecutor.setScheduler(scheduler);
        // Connect entry valve to root incremental executor
        entryValveExecutor.setNextExecutor(rootIncrementalExecutor);
        QueryParserHelper.initStreamRuntime(streamRuntime, incomingMetaStreamEvent, lockWrapper, aggregatorName);
        LatencyTracker latencyTrackerFind = null;
        LatencyTracker latencyTrackerInsert = null;
        ThroughputTracker throughputTrackerFind = null;
        ThroughputTracker throughputTrackerInsert = null;
        if (siddhiAppContext.getStatisticsManager() != null) {
            latencyTrackerFind = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            latencyTrackerInsert = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
            throughputTrackerFind = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_FIND);
            throughputTrackerInsert = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), SiddhiConstants.METRIC_INFIX_WINDOWS, SiddhiConstants.METRIC_TYPE_INSERT);
        }
        streamRuntime.setCommonProcessor(new IncrementalAggregationProcessor(rootIncrementalExecutor, incomingExpressionExecutors, processedMetaStreamEvent, latencyTrackerInsert, throughputTrackerInsert, siddhiAppContext));
        List<ExpressionExecutor> baseExecutors = cloneExpressionExecutors(processExpressionExecutors);
        ExpressionExecutor timestampExecutor = baseExecutors.remove(0);
        return new AggregationRuntime(aggregationDefinition, incrementalExecutorMap, aggregationTables, ((SingleStreamRuntime) streamRuntime), entryValveExecutor, incrementalDurations, siddhiAppContext, baseExecutors, timestampExecutor, processedMetaStreamEvent, outputExpressionExecutors, latencyTrackerFind, throughputTrackerFind, recreateInMemoryData);
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, aggregationDefinition, siddhiAppContext);
        throw t;
    }
}
Also used : Variable(org.ballerinalang.siddhi.query.api.expression.Variable) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) OutputAttribute(org.ballerinalang.siddhi.query.api.execution.query.selection.OutputAttribute) Scheduler(org.ballerinalang.siddhi.core.util.Scheduler) GroupByKeyGenerator(org.ballerinalang.siddhi.core.query.selector.GroupByKeyGenerator) Element(org.ballerinalang.siddhi.query.api.annotation.Element) ArrayList(java.util.ArrayList) IncrementalExecutor(org.ballerinalang.siddhi.core.aggregation.IncrementalExecutor) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) StreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) IncrementalAggregationProcessor(org.ballerinalang.siddhi.core.aggregation.IncrementalAggregationProcessor) AggregationRuntime(org.ballerinalang.siddhi.core.aggregation.AggregationRuntime) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ThroughputTracker(org.ballerinalang.siddhi.core.util.statistics.ThroughputTracker) Table(org.ballerinalang.siddhi.core.table.Table) ExpressionExecutor(org.ballerinalang.siddhi.core.executor.ExpressionExecutor) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) StreamDefinition(org.ballerinalang.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) TimePeriod(org.ballerinalang.siddhi.query.api.aggregation.TimePeriod) SingleStreamRuntime(org.ballerinalang.siddhi.core.query.input.stream.single.SingleStreamRuntime) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) EntryValveExecutor(org.ballerinalang.siddhi.core.query.input.stream.single.EntryValveExecutor) LockWrapper(org.ballerinalang.siddhi.core.util.lock.LockWrapper) Expression(org.ballerinalang.siddhi.query.api.expression.Expression) IncrementalAttributeAggregator(org.ballerinalang.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) RecreateInMemoryData(org.ballerinalang.siddhi.core.aggregation.RecreateInMemoryData) LatencyTracker(org.ballerinalang.siddhi.core.util.statistics.LatencyTracker) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 3 with Table

use of org.ballerinalang.siddhi.core.table.Table in project ballerina by ballerina-lang.

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 @return
 * @param siddhiAppContext        SiddhiAppContext
 * @param groupBy                 is for groupBy expression
 * @param defaultStreamEventIndex Default StreamEvent Index
 * @param queryName               query name of expression belongs to.
 * @return ExpressionExecutor
 */
public static ExpressionExecutor parseExpression(Expression expression, MetaComplexEvent metaEvent, int currentState, Map<String, Table> tableMap, List<VariableExpressionExecutor> executorList, SiddhiAppContext siddhiAppContext, boolean groupBy, int defaultStreamEventIndex, String queryName) {
    try {
        if (expression instanceof And) {
            return new AndConditionExpressionExecutor(parseExpression(((And) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((And) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
        } else if (expression instanceof Or) {
            return new OrConditionExpressionExecutor(parseExpression(((Or) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Or) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
        } else if (expression instanceof Not) {
            return new NotConditionExpressionExecutor(parseExpression(((Not) expression).getExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
        } else if (expression instanceof Compare) {
            if (((Compare) expression).getOperator() == Compare.Operator.EQUAL) {
                return parseEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            } else if (((Compare) expression).getOperator() == Compare.Operator.NOT_EQUAL) {
                return parseNotEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN) {
                return parseGreaterThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            } else if (((Compare) expression).getOperator() == Compare.Operator.GREATER_THAN_EQUAL) {
                return parseGreaterThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN) {
                return parseLessThanCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            } else if (((Compare) expression).getOperator() == Compare.Operator.LESS_THAN_EQUAL) {
                return parseLessThanEqualCompare(parseExpression(((Compare) expression).getLeftExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName), parseExpression(((Compare) expression).getRightExpression(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName));
            }
        } 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);
        } else if (expression instanceof Multiply) {
            ExpressionExecutor left = parseExpression(((Multiply) expression).getLeftValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            ExpressionExecutor right = parseExpression(((Multiply) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            ExpressionExecutor right = parseExpression(((Add) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            ExpressionExecutor right = parseExpression(((Subtract) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            ExpressionExecutor right = parseExpression(((Mod) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            ExpressionExecutor right = parseExpression(((Divide) expression).getRightValue(), metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
            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 ((siddhiAppContext.isFunctionExist(((AttributeFunction) expression).getName())) && (((AttributeFunction) expression).getNamespace()).isEmpty()) {
                    executor = new ScriptFunctionExecutor(((AttributeFunction) expression).getName());
                } else {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, FunctionExecutorExtensionHolder.getInstance(siddhiAppContext));
                }
            } catch (SiddhiAppCreationException ex) {
                try {
                    executor = SiddhiClassLoader.loadExtensionImplementation((AttributeFunction) expression, AttributeAggregatorExtensionHolder.getInstance(siddhiAppContext));
                } catch (SiddhiAppCreationException e) {
                    throw new SiddhiAppCreationException("'" + ((AttributeFunction) expression).getName() + "' is" + " neither a function extension nor an aggregated attribute extension", expression.getQueryContextStartIndex(), expression.getQueryContextEndIndex());
                }
            }
            ConfigReader configReader = siddhiAppContext.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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
                expressionExecutor.initExecutor(innerExpressionExecutors, siddhiAppContext, queryName, configReader);
                if (expressionExecutor.getReturnType() == Attribute.Type.BOOL) {
                    return new BoolConditionExpressionExecutor(expressionExecutor);
                }
                return expressionExecutor;
            } else {
                AttributeAggregator attributeAggregator = (AttributeAggregator) executor;
                Expression[] innerExpressions = ((AttributeFunction) expression).getParameters();
                ExpressionExecutor[] innerExpressionExecutors = parseInnerExpression(innerExpressions, metaEvent, currentState, tableMap, executorList, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
                attributeAggregator.initAggregator(innerExpressionExecutors, siddhiAppContext, configReader);
                AbstractAggregationAttributeExecutor aggregationAttributeProcessor;
                if (groupBy) {
                    aggregationAttributeProcessor = new GroupByAggregationAttributeExecutor(attributeAggregator, innerExpressionExecutors, configReader, siddhiAppContext, queryName);
                } else {
                    aggregationAttributeProcessor = new AggregationAttributeExecutor(attributeAggregator, innerExpressionExecutors, siddhiAppContext, queryName);
                }
                SelectorParser.getContainsAggregatorThreadLocal().set("true");
                return aggregationAttributeProcessor;
            }
        } 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, siddhiAppContext, executorList, tableMap, queryName);
            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, siddhiAppContext, groupBy, defaultStreamEventIndex, queryName);
                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 <= LAST) {
                            eventPosition[STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex + 1;
                        } else {
                            eventPosition[STREAM_EVENT_INDEX_IN_CHAIN] = streamIndex;
                        }
                    } else {
                        eventPosition[STREAM_EVENT_INDEX_IN_CHAIN] = defaultStreamEventIndex;
                    }
                    eventPosition[STREAM_EVENT_CHAIN_INDEX] = 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[STREAM_EVENT_CHAIN_INDEX] = i;
                                    break;
                                }
                            } else {
                                if (metaStreamEvent.getInputReferenceId().equals(streamId)) {
                                    eventPosition[STREAM_EVENT_CHAIN_INDEX] = i;
                                    if (currentState > -1 && metaStreamEvents[currentState].getInputReferenceId() != null && streamIndex != null && streamIndex <= LAST) {
                                        if (streamId.equals(metaStreamEvents[currentState].getInputReferenceId())) {
                                            eventPosition[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, siddhiAppContext);
        throw t;
    }
}
Also used : Add(org.ballerinalang.siddhi.query.api.expression.math.Add) Or(org.ballerinalang.siddhi.query.api.expression.condition.Or) DivideExpressionExecutorFloat(org.ballerinalang.siddhi.core.executor.math.divide.DivideExpressionExecutorFloat) ModExpressionExecutorDouble(org.ballerinalang.siddhi.core.executor.math.mod.ModExpressionExecutorDouble) ModExpressionExecutorInt(org.ballerinalang.siddhi.core.executor.math.mod.ModExpressionExecutorInt) EqualCompareConditionExpressionExecutorStringString(org.ballerinalang.siddhi.core.executor.condition.compare.equal.EqualCompareConditionExpressionExecutorStringString) NotEqualCompareConditionExpressionExecutorStringString(org.ballerinalang.siddhi.core.executor.condition.compare.notequal.NotEqualCompareConditionExpressionExecutorStringString) ConstantExpressionExecutor(org.ballerinalang.siddhi.core.executor.ConstantExpressionExecutor) Divide(org.ballerinalang.siddhi.query.api.expression.math.Divide) MultiplyExpressionExecutorLong(org.ballerinalang.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorLong) AddExpressionExecutorLong(org.ballerinalang.siddhi.core.executor.math.add.AddExpressionExecutorLong) Multiply(org.ballerinalang.siddhi.query.api.expression.math.Multiply) AddExpressionExecutorInt(org.ballerinalang.siddhi.core.executor.math.add.AddExpressionExecutorInt) Compare(org.ballerinalang.siddhi.query.api.expression.condition.Compare) DivideExpressionExecutorDouble(org.ballerinalang.siddhi.core.executor.math.divide.DivideExpressionExecutorDouble) ScriptFunctionExecutor(org.ballerinalang.siddhi.core.executor.function.ScriptFunctionExecutor) FunctionExecutor(org.ballerinalang.siddhi.core.executor.function.FunctionExecutor) AddExpressionExecutorFloat(org.ballerinalang.siddhi.core.executor.math.add.AddExpressionExecutorFloat) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) AttributeAggregator(org.ballerinalang.siddhi.core.query.selector.attribute.aggregator.AttributeAggregator) AbstractDefinition(org.ballerinalang.siddhi.query.api.definition.AbstractDefinition) GroupByAggregationAttributeExecutor(org.ballerinalang.siddhi.core.query.selector.attribute.processor.executor.GroupByAggregationAttributeExecutor) Not(org.ballerinalang.siddhi.query.api.expression.condition.Not) MultiplyExpressionExecutorFloat(org.ballerinalang.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorFloat) CompiledCondition(org.ballerinalang.siddhi.core.util.collection.operator.CompiledCondition) And(org.ballerinalang.siddhi.query.api.expression.condition.And) MatchingMetaInfoHolder(org.ballerinalang.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) SubtractExpressionExecutorLong(org.ballerinalang.siddhi.core.executor.math.subtract.SubtractExpressionExecutorLong) IsNullStreamConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) Subtract(org.ballerinalang.siddhi.query.api.expression.math.Subtract) StringConstant(org.ballerinalang.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent) DoubleConstant(org.ballerinalang.siddhi.query.api.expression.constant.DoubleConstant) AbstractAggregationAttributeExecutor(org.ballerinalang.siddhi.core.query.selector.attribute.processor.executor.AbstractAggregationAttributeExecutor) Variable(org.ballerinalang.siddhi.query.api.expression.Variable) MultiplyExpressionExecutorDouble(org.ballerinalang.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorDouble) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) In(org.ballerinalang.siddhi.query.api.expression.condition.In) FloatConstant(org.ballerinalang.siddhi.query.api.expression.constant.FloatConstant) StringConstant(org.ballerinalang.siddhi.query.api.expression.constant.StringConstant) LongConstant(org.ballerinalang.siddhi.query.api.expression.constant.LongConstant) DoubleConstant(org.ballerinalang.siddhi.query.api.expression.constant.DoubleConstant) BoolConstant(org.ballerinalang.siddhi.query.api.expression.constant.BoolConstant) IntConstant(org.ballerinalang.siddhi.query.api.expression.constant.IntConstant) Constant(org.ballerinalang.siddhi.query.api.expression.constant.Constant) ModExpressionExecutorLong(org.ballerinalang.siddhi.core.executor.math.mod.ModExpressionExecutorLong) ScriptFunctionExecutor(org.ballerinalang.siddhi.core.executor.function.ScriptFunctionExecutor) InConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.InConditionExpressionExecutor) FloatConstant(org.ballerinalang.siddhi.query.api.expression.constant.FloatConstant) AddExpressionExecutorDouble(org.ballerinalang.siddhi.core.executor.math.add.AddExpressionExecutorDouble) AndConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.AndConditionExpressionExecutor) MultiplyExpressionExecutorInt(org.ballerinalang.siddhi.core.executor.math.multiply.MultiplyExpressionExecutorInt) IsNullConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) SubtractExpressionExecutorInt(org.ballerinalang.siddhi.core.executor.math.subtract.SubtractExpressionExecutorInt) IntConstant(org.ballerinalang.siddhi.query.api.expression.constant.IntConstant) SubtractExpressionExecutorDouble(org.ballerinalang.siddhi.core.executor.math.subtract.SubtractExpressionExecutorDouble) GroupByAggregationAttributeExecutor(org.ballerinalang.siddhi.core.query.selector.attribute.processor.executor.GroupByAggregationAttributeExecutor) AggregationAttributeExecutor(org.ballerinalang.siddhi.core.query.selector.attribute.processor.executor.AggregationAttributeExecutor) AbstractAggregationAttributeExecutor(org.ballerinalang.siddhi.core.query.selector.attribute.processor.executor.AbstractAggregationAttributeExecutor) LongConstant(org.ballerinalang.siddhi.query.api.expression.constant.LongConstant) BoolConstant(org.ballerinalang.siddhi.query.api.expression.constant.BoolConstant) Mod(org.ballerinalang.siddhi.query.api.expression.math.Mod) Table(org.ballerinalang.siddhi.core.table.Table) InConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.InConditionExpressionExecutor) ExpressionExecutor(org.ballerinalang.siddhi.core.executor.ExpressionExecutor) NotConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.NotConditionExpressionExecutor) ConstantExpressionExecutor(org.ballerinalang.siddhi.core.executor.ConstantExpressionExecutor) BoolConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.BoolConditionExpressionExecutor) IsNullStreamConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.IsNullStreamConditionExpressionExecutor) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) OrConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.OrConditionExpressionExecutor) AndConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.AndConditionExpressionExecutor) IsNullConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.IsNullConditionExpressionExecutor) ConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.ConditionExpressionExecutor) ConfigReader(org.ballerinalang.siddhi.core.util.config.ConfigReader) OrConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.OrConditionExpressionExecutor) DivideExpressionExecutorLong(org.ballerinalang.siddhi.core.executor.math.divide.DivideExpressionExecutorLong) AttributeFunction(org.ballerinalang.siddhi.query.api.expression.AttributeFunction) DivideExpressionExecutorInt(org.ballerinalang.siddhi.core.executor.math.divide.DivideExpressionExecutorInt) SubtractExpressionExecutorFloat(org.ballerinalang.siddhi.core.executor.math.subtract.SubtractExpressionExecutorFloat) MetaStateEvent(org.ballerinalang.siddhi.core.event.state.MetaStateEvent) NotConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.NotConditionExpressionExecutor) ModExpressionExecutorFloat(org.ballerinalang.siddhi.core.executor.math.mod.ModExpressionExecutorFloat) MetaStateEvent(org.ballerinalang.siddhi.core.event.state.MetaStateEvent) StateEvent(org.ballerinalang.siddhi.core.event.state.StateEvent) IsNull(org.ballerinalang.siddhi.query.api.expression.condition.IsNull) BoolConditionExpressionExecutor(org.ballerinalang.siddhi.core.executor.condition.BoolConditionExpressionExecutor)

Example 4 with Table

use of org.ballerinalang.siddhi.core.table.Table in project ballerina by ballerina-lang.

the class OutputParser method constructOutputCallback.

public static OutputCallback constructOutputCallback(final OutputStream outStream, StreamDefinition outputStreamDefinition, Map<String, Table> tableMap, Map<String, Window> eventWindowMap, SiddhiAppContext siddhiAppContext, boolean convertToStreamEvent, String queryName) {
    String id = outStream.getId();
    Table table = null;
    Window window = null;
    if (id != null) {
        table = tableMap.get(id);
        window = eventWindowMap.get(id);
    }
    StreamEventPool streamEventPool = null;
    StreamEventConverter streamEventConverter = null;
    MetaStreamEvent tableMetaStreamEvent = null;
    if (table != null) {
        tableMetaStreamEvent = new MetaStreamEvent();
        tableMetaStreamEvent.setEventType(MetaStreamEvent.EventType.TABLE);
        TableDefinition matchingTableDefinition = TableDefinition.id("");
        for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
            tableMetaStreamEvent.addOutputData(attribute);
            matchingTableDefinition.attribute(attribute.getName(), attribute.getType());
        }
        matchingTableDefinition.setQueryContextStartIndex(outStream.getQueryContextStartIndex());
        matchingTableDefinition.setQueryContextEndIndex(outStream.getQueryContextEndIndex());
        tableMetaStreamEvent.addInputDefinition(matchingTableDefinition);
        streamEventPool = new StreamEventPool(tableMetaStreamEvent, 10);
        streamEventConverter = new ZeroStreamEventConverter();
    }
    // Construct CallBack
    if (outStream instanceof InsertIntoStream) {
        if (window != null) {
            return new InsertIntoWindowCallback(window, outputStreamDefinition, queryName);
        } else if (table != null) {
            DefinitionParserHelper.validateOutputStream(outputStreamDefinition, table.getTableDefinition());
            return new InsertIntoTableCallback(table, outputStreamDefinition, convertToStreamEvent, streamEventPool, streamEventConverter, queryName);
        } else {
            return new InsertIntoStreamCallback(outputStreamDefinition, queryName);
        }
    } else if (outStream instanceof DeleteStream || outStream instanceof UpdateStream || outStream instanceof UpdateOrInsertStream) {
        if (table != null) {
            if (outStream instanceof UpdateStream) {
                if (((UpdateStream) outStream).getUpdateSet() == null) {
                    TableDefinition tableDefinition = table.getTableDefinition();
                    for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
                        if (!tableDefinition.getAttributeList().contains(attribute)) {
                            throw new SiddhiAppCreationException("Attribute " + attribute + " does not exist on " + "Event Table " + tableDefinition, outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
                        }
                    }
                }
            }
            if (outStream instanceof UpdateOrInsertStream) {
                TableDefinition tableDefinition = table.getTableDefinition();
                for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
                    if (!tableDefinition.getAttributeList().contains(attribute)) {
                        throw new SiddhiAppCreationException("Attribute " + attribute + " does not exist on " + "Event Table " + tableDefinition, outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
                    }
                }
            }
            if (outStream instanceof DeleteStream) {
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((DeleteStream) outStream).getOnDeleteExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new DeleteTableCallback(table, compiledCondition, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create delete for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
                }
            } else if (outStream instanceof UpdateStream) {
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((UpdateStream) outStream).getOnUpdateExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    UpdateSet updateSet = ((UpdateStream) outStream).getUpdateSet();
                    if (updateSet == null) {
                        updateSet = new UpdateSet();
                        for (Attribute attribute : matchingMetaInfoHolder.getMatchingStreamDefinition().getAttributeList()) {
                            updateSet.set(new Variable(attribute.getName()), new Variable(attribute.getName()));
                        }
                    }
                    CompiledUpdateSet compiledUpdateSet = table.compileUpdateSet(updateSet, matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new UpdateTableCallback(table, compiledCondition, compiledUpdateSet, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create update for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext);
                }
            } else {
                DefinitionParserHelper.validateOutputStream(outputStreamDefinition, table.getTableDefinition());
                try {
                    MatchingMetaInfoHolder matchingMetaInfoHolder = MatcherParser.constructMatchingMetaStateHolder(tableMetaStreamEvent, 0, table.getTableDefinition(), 0);
                    CompiledCondition compiledCondition = table.compileCondition((((UpdateOrInsertStream) outStream).getOnUpdateExpression()), matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    UpdateSet updateSet = ((UpdateOrInsertStream) outStream).getUpdateSet();
                    if (updateSet == null) {
                        updateSet = new UpdateSet();
                        for (Attribute attribute : matchingMetaInfoHolder.getMatchingStreamDefinition().getAttributeList()) {
                            updateSet.set(new Variable(attribute.getName()), new Variable(attribute.getName()));
                        }
                    }
                    CompiledUpdateSet compiledUpdateSet = table.compileUpdateSet(updateSet, matchingMetaInfoHolder, siddhiAppContext, null, tableMap, queryName);
                    StateEventPool stateEventPool = new StateEventPool(matchingMetaInfoHolder.getMetaStateEvent(), 10);
                    return new UpdateOrInsertTableCallback(table, compiledCondition, compiledUpdateSet, matchingMetaInfoHolder.getMatchingStreamEventIndex(), convertToStreamEvent, stateEventPool, streamEventPool, streamEventConverter, queryName);
                } catch (SiddhiAppValidationException e) {
                    throw new SiddhiAppCreationException("Cannot create update or insert into for table '" + outStream.getId() + "', " + e.getMessageWithOutContext(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext);
                }
            }
        } else {
            throw new SiddhiAppCreationException("Event table with id :" + id + " does not exist", outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
        }
    } else {
        throw new SiddhiAppCreationException(outStream.getClass().getName() + " not supported", outStream.getQueryContextStartIndex(), outStream.getQueryContextEndIndex());
    }
}
Also used : Variable(org.ballerinalang.siddhi.query.api.expression.Variable) Attribute(org.ballerinalang.siddhi.query.api.definition.Attribute) InsertIntoWindowCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoWindowCallback) UpdateStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateStream) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) UpdateTableCallback(org.ballerinalang.siddhi.core.query.output.callback.UpdateTableCallback) DeleteStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.DeleteStream) StreamEventPool(org.ballerinalang.siddhi.core.event.stream.StreamEventPool) UpdateOrInsertTableCallback(org.ballerinalang.siddhi.core.query.output.callback.UpdateOrInsertTableCallback) TableDefinition(org.ballerinalang.siddhi.query.api.definition.TableDefinition) InsertIntoTableCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoTableCallback) Window(org.ballerinalang.siddhi.core.window.Window) Table(org.ballerinalang.siddhi.core.table.Table) StateEventPool(org.ballerinalang.siddhi.core.event.state.StateEventPool) SiddhiAppCreationException(org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException) StreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.StreamEventConverter) ZeroStreamEventConverter(org.ballerinalang.siddhi.core.event.stream.converter.ZeroStreamEventConverter) InsertIntoStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.InsertIntoStream) SiddhiAppValidationException(org.ballerinalang.siddhi.query.api.exception.SiddhiAppValidationException) InsertIntoStreamCallback(org.ballerinalang.siddhi.core.query.output.callback.InsertIntoStreamCallback) CompiledUpdateSet(org.ballerinalang.siddhi.core.table.CompiledUpdateSet) UpdateOrInsertStream(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateOrInsertStream) CompiledCondition(org.ballerinalang.siddhi.core.util.collection.operator.CompiledCondition) MatchingMetaInfoHolder(org.ballerinalang.siddhi.core.util.collection.operator.MatchingMetaInfoHolder) DeleteTableCallback(org.ballerinalang.siddhi.core.query.output.callback.DeleteTableCallback) UpdateSet(org.ballerinalang.siddhi.query.api.execution.query.output.stream.UpdateSet) CompiledUpdateSet(org.ballerinalang.siddhi.core.table.CompiledUpdateSet) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)

Example 5 with Table

use of org.ballerinalang.siddhi.core.table.Table in project ballerina by ballerina-lang.

the class StoreQueryParser method parse.

/**
 * Parse a storeQuery and return corresponding StoreQueryRuntime.
 *
 * @param storeQuery       storeQuery to be parsed.
 * @param siddhiAppContext associated Siddhi app context.
 * @param tableMap         keyvalue containing tables.
 * @param windowMap        keyvalue containing windows.
 * @param aggregationMap   keyvalue containing aggregation runtimes.
 * @return StoreQueryRuntime
 */
public static StoreQueryRuntime parse(StoreQuery storeQuery, SiddhiAppContext siddhiAppContext, Map<String, Table> tableMap, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap) {
    String queryName = "store_query_" + storeQuery.getInputStore().getStoreId();
    InputStore inputStore = storeQuery.getInputStore();
    int metaPosition = SiddhiConstants.UNKNOWN_STATE;
    Within within = null;
    Expression per = null;
    try {
        SnapshotService.getSkipSnapshotableThreadLocal().set(true);
        Expression onCondition = Expression.value(true);
        MetaStreamEvent metaStreamEvent = new MetaStreamEvent();
        metaStreamEvent.setInputReferenceId(inputStore.getStoreReferenceId());
        if (inputStore instanceof AggregationInputStore) {
            AggregationInputStore aggregationInputStore = (AggregationInputStore) inputStore;
            if (aggregationMap.get(inputStore.getStoreId()) == null) {
                throw new StoreQueryCreationException("Aggregation \"" + inputStore.getStoreId() + "\" has not been defined");
            }
            if (aggregationInputStore.getPer() != null && aggregationInputStore.getWithin() != null) {
                within = aggregationInputStore.getWithin();
                per = aggregationInputStore.getPer();
            } else if (aggregationInputStore.getPer() != null || aggregationInputStore.getWithin() != null) {
                throw new StoreQueryCreationException(inputStore.getStoreId() + " should either have both 'within' and 'per' defined or none.");
            }
            if (((AggregationInputStore) inputStore).getOnCondition() != null) {
                onCondition = ((AggregationInputStore) inputStore).getOnCondition();
            }
        } else if (inputStore instanceof ConditionInputStore) {
            if (((ConditionInputStore) inputStore).getOnCondition() != null) {
                onCondition = ((ConditionInputStore) inputStore).getOnCondition();
            }
        }
        List<VariableExpressionExecutor> variableExpressionExecutors = new ArrayList<>();
        Table table = tableMap.get(inputStore.getStoreId());
        if (table != null) {
            return constructStoreQueryRuntime(table, storeQuery, siddhiAppContext, tableMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors);
        } else {
            AggregationRuntime aggregation = aggregationMap.get(inputStore.getStoreId());
            if (aggregation != null) {
                return constructStoreQueryRuntime(aggregation, storeQuery, siddhiAppContext, tableMap, queryName, within, per, onCondition, metaStreamEvent, variableExpressionExecutors);
            } else {
                Window window = windowMap.get(inputStore.getStoreId());
                if (window != null) {
                    return constructStoreQueryRuntime(window, storeQuery, siddhiAppContext, tableMap, queryName, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors);
                } else {
                    throw new StoreQueryCreationException(inputStore.getStoreId() + " is neither a table, aggregation or window");
                }
            }
        }
    } finally {
        SnapshotService.getSkipSnapshotableThreadLocal().set(null);
    }
}
Also used : Window(org.ballerinalang.siddhi.core.window.Window) Table(org.ballerinalang.siddhi.core.table.Table) VariableExpressionExecutor(org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor) ArrayList(java.util.ArrayList) AggregationInputStore(org.ballerinalang.siddhi.query.api.execution.query.input.store.AggregationInputStore) Expression(org.ballerinalang.siddhi.query.api.expression.Expression) ConditionInputStore(org.ballerinalang.siddhi.query.api.execution.query.input.store.ConditionInputStore) AggregationInputStore(org.ballerinalang.siddhi.query.api.execution.query.input.store.AggregationInputStore) InputStore(org.ballerinalang.siddhi.query.api.execution.query.input.store.InputStore) ConditionInputStore(org.ballerinalang.siddhi.query.api.execution.query.input.store.ConditionInputStore) Within(org.ballerinalang.siddhi.query.api.aggregation.Within) StoreQueryCreationException(org.ballerinalang.siddhi.core.exception.StoreQueryCreationException) MetaStreamEvent(org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent) AggregationRuntime(org.ballerinalang.siddhi.core.aggregation.AggregationRuntime)

Aggregations

Table (org.ballerinalang.siddhi.core.table.Table)11 MetaStreamEvent (org.ballerinalang.siddhi.core.event.stream.MetaStreamEvent)9 Attribute (org.ballerinalang.siddhi.query.api.definition.Attribute)6 ArrayList (java.util.ArrayList)4 SiddhiAppCreationException (org.ballerinalang.siddhi.core.exception.SiddhiAppCreationException)4 VariableExpressionExecutor (org.ballerinalang.siddhi.core.executor.VariableExpressionExecutor)4 TimePeriod (org.ballerinalang.siddhi.query.api.aggregation.TimePeriod)4 Variable (org.ballerinalang.siddhi.query.api.expression.Variable)4 HashMap (java.util.HashMap)3 AggregationRuntime (org.ballerinalang.siddhi.core.aggregation.AggregationRuntime)3 ComplexEventChunk (org.ballerinalang.siddhi.core.event.ComplexEventChunk)3 StreamEventPool (org.ballerinalang.siddhi.core.event.stream.StreamEventPool)3 ExpressionExecutor (org.ballerinalang.siddhi.core.executor.ExpressionExecutor)3 CompiledCondition (org.ballerinalang.siddhi.core.util.collection.operator.CompiledCondition)3 MatchingMetaInfoHolder (org.ballerinalang.siddhi.core.util.collection.operator.MatchingMetaInfoHolder)3 Window (org.ballerinalang.siddhi.core.window.Window)3 AbstractDefinition (org.ballerinalang.siddhi.query.api.definition.AbstractDefinition)3 Expression (org.ballerinalang.siddhi.query.api.expression.Expression)3 StreamEvent (org.ballerinalang.siddhi.core.event.stream.StreamEvent)2 Source (org.ballerinalang.siddhi.core.stream.input.source.Source)2