Search in sources :

Example 41 with MetaStreamEvent

use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.

the class OnDemandQueryParser method parse.

public static OnDemandQueryRuntime parse(OnDemandQuery onDemandQuery, String onDemandQueryString, SiddhiAppContext siddhiAppContext, Map<String, Table> tableMap, Map<String, Window> windowMap, Map<String, AggregationRuntime> aggregationMap) {
    final LockWrapper lockWrapper = new LockWrapper("OnDemandQueryLock");
    lockWrapper.setLock(new ReentrantLock());
    MetaStreamEvent metaStreamEvent = new MetaStreamEvent();
    int metaPosition = SiddhiConstants.UNKNOWN_STATE;
    String queryName;
    Table table;
    SiddhiQueryContext siddhiQueryContext;
    Expression onCondition;
    SnapshotService.getSkipStateStorageThreadLocal().set(true);
    switch(onDemandQuery.getType()) {
        case FIND:
            Within within = null;
            Expression per = null;
            queryName = "store_select_query_" + onDemandQuery.getInputStore().getStoreId();
            siddhiQueryContext = new SiddhiOnDemandQueryContext(siddhiAppContext, queryName, onDemandQueryString);
            InputStore inputStore = onDemandQuery.getInputStore();
            try {
                onCondition = Expression.value(true);
                metaStreamEvent.setInputReferenceId(inputStore.getStoreReferenceId());
                if (inputStore instanceof AggregationInputStore) {
                    AggregationInputStore aggregationInputStore = (AggregationInputStore) inputStore;
                    if (aggregationMap.get(inputStore.getStoreId()) == null) {
                        throw new OnDemandQueryCreationException("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 OnDemandQueryCreationException(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 = tableMap.get(inputStore.getStoreId());
                if (table != null) {
                    return constructOnDemandQueryRuntime(table, onDemandQuery, tableMap, windowMap, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper, siddhiQueryContext);
                } else {
                    AggregationRuntime aggregation = aggregationMap.get(inputStore.getStoreId());
                    if (aggregation != null) {
                        return constructOnDemandQueryRuntime(aggregation, onDemandQuery, tableMap, windowMap, within, per, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper, siddhiQueryContext);
                    } else {
                        Window window = windowMap.get(inputStore.getStoreId());
                        if (window != null) {
                            return constructOnDemandQueryRuntime(window, onDemandQuery, tableMap, windowMap, metaPosition, onCondition, metaStreamEvent, variableExpressionExecutors, lockWrapper, siddhiQueryContext);
                        } else {
                            throw new OnDemandQueryCreationException(inputStore.getStoreId() + " is neither a table, aggregation or window");
                        }
                    }
                }
            } finally {
                SnapshotService.getSkipStateStorageThreadLocal().set(null);
            }
        case INSERT:
            InsertIntoStream inserIntoStreamt = (InsertIntoStream) onDemandQuery.getOutputStream();
            queryName = "store_insert_query_" + inserIntoStreamt.getId();
            siddhiQueryContext = new SiddhiOnDemandQueryContext(siddhiAppContext, queryName, onDemandQueryString);
            onCondition = Expression.value(true);
            return getOnDemandQueryRuntime(onDemandQuery, tableMap, windowMap, metaPosition, lockWrapper, metaStreamEvent, inserIntoStreamt, onCondition, siddhiQueryContext);
        case DELETE:
            DeleteStream deleteStream = (DeleteStream) onDemandQuery.getOutputStream();
            queryName = "store_delete_query_" + deleteStream.getId();
            siddhiQueryContext = new SiddhiOnDemandQueryContext(siddhiAppContext, queryName, onDemandQueryString);
            onCondition = deleteStream.getOnDeleteExpression();
            return getOnDemandQueryRuntime(onDemandQuery, tableMap, windowMap, metaPosition, lockWrapper, metaStreamEvent, deleteStream, onCondition, siddhiQueryContext);
        case UPDATE:
            UpdateStream outputStream = (UpdateStream) onDemandQuery.getOutputStream();
            queryName = "store_update_query_" + outputStream.getId();
            siddhiQueryContext = new SiddhiOnDemandQueryContext(siddhiAppContext, queryName, onDemandQueryString);
            onCondition = outputStream.getOnUpdateExpression();
            return getOnDemandQueryRuntime(onDemandQuery, tableMap, windowMap, metaPosition, lockWrapper, metaStreamEvent, outputStream, onCondition, siddhiQueryContext);
        case UPDATE_OR_INSERT:
            UpdateOrInsertStream onDemandQueryOutputStream = (UpdateOrInsertStream) onDemandQuery.getOutputStream();
            queryName = "store_update_or_insert_query_" + onDemandQueryOutputStream.getId();
            siddhiQueryContext = new SiddhiOnDemandQueryContext(siddhiAppContext, queryName, onDemandQueryString);
            onCondition = onDemandQueryOutputStream.getOnUpdateExpression();
            return getOnDemandQueryRuntime(onDemandQuery, tableMap, windowMap, metaPosition, lockWrapper, metaStreamEvent, onDemandQueryOutputStream, onCondition, siddhiQueryContext);
        default:
            return null;
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Window(io.siddhi.core.window.Window) Table(io.siddhi.core.table.Table) AbstractQueryableRecordTable(io.siddhi.core.table.record.AbstractQueryableRecordTable) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) InsertIntoStream(io.siddhi.query.api.execution.query.output.stream.InsertIntoStream) ArrayList(java.util.ArrayList) UpdateStream(io.siddhi.query.api.execution.query.output.stream.UpdateStream) LockWrapper(io.siddhi.core.util.lock.LockWrapper) SiddhiOnDemandQueryContext(io.siddhi.core.config.SiddhiOnDemandQueryContext) OnDemandQueryCreationException(io.siddhi.core.exception.OnDemandQueryCreationException) AggregationInputStore(io.siddhi.query.api.execution.query.input.store.AggregationInputStore) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) UpdateOrInsertStream(io.siddhi.query.api.execution.query.output.stream.UpdateOrInsertStream) Expression(io.siddhi.query.api.expression.Expression) ConditionInputStore(io.siddhi.query.api.execution.query.input.store.ConditionInputStore) DeleteStream(io.siddhi.query.api.execution.query.output.stream.DeleteStream) Within(io.siddhi.query.api.aggregation.Within) ConditionInputStore(io.siddhi.query.api.execution.query.input.store.ConditionInputStore) AggregationInputStore(io.siddhi.query.api.execution.query.input.store.AggregationInputStore) InputStore(io.siddhi.query.api.execution.query.input.store.InputStore) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime)

Example 42 with MetaStreamEvent

use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.

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) {
    // set timeZone for aggregation
    String timeZone = getTimeZone(siddhiAppContext);
    boolean isDebugEnabled = log.isDebugEnabled();
    boolean isPersistedAggregation = false;
    boolean isReadOnly = false;
    if (!validateTimeZone(timeZone)) {
        throw new SiddhiAppCreationException("Given timeZone '" + timeZone + "' for aggregations is invalid. Please provide a valid time zone.");
    }
    // get aggregation name
    String aggregatorName = aggregationDefinition.getId();
    if (isDebugEnabled) {
        log.debug("Incremental aggregation initialization process started for aggregation " + aggregatorName);
    }
    Annotation aggregationProperties = AnnotationHelper.getAnnotation(ANNOTATION_PERSISTED_AGGREGATION, aggregationDefinition.getAnnotations());
    if (aggregationProperties != null) {
        String persistedAggregationMode = aggregationProperties.getElement(ANNOTATION_ELEMENT_ENABLE);
        isPersistedAggregation = persistedAggregationMode == null || Boolean.parseBoolean(persistedAggregationMode);
        String readOnlyMode = aggregationProperties.getElement(ANNOTATION_ELEMENT_IS_READ_ONLY);
        isReadOnly = Boolean.parseBoolean(readOnlyMode);
    }
    if (isPersistedAggregation) {
        aggregationDefinition.getSelector().getSelectionList().stream().forEach(outputAttribute -> {
            if (outputAttribute.getExpression() instanceof AttributeFunction && ((AttributeFunction) outputAttribute.getExpression()).getName().equals("distinctCount")) {
                throw new SiddhiAppCreationException("Aggregation function 'distinctCount' does not supported " + "with persisted aggregation type please use default incremental aggregation");
            }
        });
    }
    if (isDebugEnabled) {
        log.debug("Aggregation mode is defined as " + (isPersistedAggregation ? "persisted" : "inMemory") + " for aggregation " + aggregatorName);
    }
    if (aggregationDefinition.getTimePeriod() == null) {
        throw new SiddhiAppCreationException("Aggregation Definition '" + 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("Aggregation Definition '" + 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");
    }
    // Check if the user defined primary keys exists for @store annotation on aggregation if yes, an error is
    // is thrown
    Element userDefinedPrimaryKey = AnnotationHelper.getAnnotationElement(SiddhiConstants.ANNOTATION_PRIMARY_KEY, null, aggregationDefinition.getAnnotations());
    if (userDefinedPrimaryKey != null) {
        throw new SiddhiAppCreationException("Aggregation Tables have predefined primary key, but found '" + userDefinedPrimaryKey.getValue() + "' primary key defined though annotation.");
    }
    try {
        List<VariableExpressionExecutor> incomingVariableExpressionExecutors = new ArrayList<>();
        SiddhiQueryContext siddhiQueryContext = new SiddhiQueryContext(siddhiAppContext, aggregatorName);
        StreamRuntime streamRuntime = InputStreamParser.parse(aggregationDefinition.getBasicSingleInputStream(), null, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, incomingVariableExpressionExecutors, false, siddhiQueryContext);
        // 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.initializeOnAfterWindowData();
        // List of all aggregationDurations
        List<TimePeriod.Duration> aggregationDurations = getSortedPeriods(aggregationDefinition.getTimePeriod(), isPersistedAggregation);
        // Incoming executors will be executors for timestamp, externalTimestamp(if used),
        List<ExpressionExecutor> incomingExpressionExecutors = new ArrayList<>();
        List<IncrementalAttributeAggregator> incrementalAttributeAggregators = new ArrayList<>();
        // group by attributes (if given) and the incremental attributes expression executors
        List<Variable> groupByVariableList = aggregationDefinition.getSelector().getGroupByList();
        // Expressions to get final aggregate outputs. e.g for avg the expression is Divide expression with
        // AGG_SUM/ AGG_COUNT
        List<Expression> outputExpressions = new ArrayList<>();
        boolean isProcessingOnExternalTime = aggregationDefinition.getAggregateAttribute() != null;
        boolean isGroupBy = aggregationDefinition.getSelector().getGroupByList().size() != 0;
        final boolean isDistributed;
        ConfigManager configManager = siddhiAppContext.getSiddhiContext().getConfigManager();
        final String shardId = configManager.extractProperty("shardId");
        boolean enablePartitioning = false;
        // check if the setup is Active Active(distributed deployment) by checking availability of partitionById
        // config
        Annotation partitionById = AnnotationHelper.getAnnotation(ANNOTATION_PARTITION_BY_ID, aggregationDefinition.getAnnotations());
        if (partitionById != null) {
            String enableElement = partitionById.getElement(ANNOTATION_ELEMENT_ENABLE);
            enablePartitioning = enableElement == null || Boolean.parseBoolean(enableElement);
        }
        boolean shouldPartitionById = Boolean.parseBoolean(configManager.extractProperty("partitionById"));
        if (enablePartitioning || shouldPartitionById) {
            if (shardId == null) {
                throw new SiddhiAppCreationException("Configuration 'shardId' not provided for @partitionById " + "annotation");
            }
            isDistributed = true;
        } else {
            isDistributed = false;
        }
        if (isDebugEnabled) {
            log.debug("Distributed aggregation processing is " + (isDistributed ? "enabled" : "disabled") + " in " + aggregatorName + " aggregation ");
        }
        populateIncomingAggregatorsAndExecutors(aggregationDefinition, siddhiQueryContext, tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, groupByVariableList, outputExpressions, isProcessingOnExternalTime, isDistributed, shardId);
        // check if the populateIncomingAggregatorsAndExecutors process has been completed successfully
        boolean isLatestEventColAdded = incomingMetaStreamEvent.getOutputData().get(incomingMetaStreamEvent.getOutputData().size() - 1).getName().equals(AGG_LAST_TIMESTAMP_COL);
        int baseAggregatorBeginIndex = incomingMetaStreamEvent.getOutputData().size();
        List<Expression> finalBaseExpressions = new ArrayList<>();
        boolean isOptimisedLookup = populateFinalBaseAggregators(tableMap, incomingVariableExpressionExecutors, incomingMetaStreamEvent, incomingExpressionExecutors, incrementalAttributeAggregators, siddhiQueryContext, finalBaseExpressions);
        if (isDebugEnabled) {
            log.debug("Optimised lookup mode is " + (isOptimisedLookup ? "enabled" : "disabled") + " for " + "aggregation " + aggregatorName);
        }
        // Creating an intermediate stream with aggregated stream and above extracted output variables
        StreamDefinition incomingOutputStreamDefinition = StreamDefinition.id(aggregatorName + "_intermediate");
        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<>();
        Map<TimePeriod.Duration, List<ExpressionExecutor>> processExpressionExecutorsMap = new HashMap<>();
        Map<TimePeriod.Duration, List<ExpressionExecutor>> processExpressionExecutorsMapForFind = new HashMap<>();
        aggregationDurations.forEach(incrementalDuration -> {
            processExpressionExecutorsMap.put(incrementalDuration, constructProcessExpressionExecutors(siddhiQueryContext, tableMap, baseAggregatorBeginIndex, finalBaseExpressions, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, isProcessingOnExternalTime, incrementalDuration, isDistributed, shardId, isLatestEventColAdded));
            processExpressionExecutorsMapForFind.put(incrementalDuration, constructProcessExpressionExecutors(siddhiQueryContext, tableMap, baseAggregatorBeginIndex, finalBaseExpressions, incomingOutputStreamDefinition, processedMetaStreamEvent, processVariableExpressionExecutors, isProcessingOnExternalTime, incrementalDuration, isDistributed, shardId, isLatestEventColAdded));
        });
        ExpressionExecutor shouldUpdateTimestamp = null;
        if (isLatestEventColAdded) {
            Expression shouldUpdateTimestampExp = new Variable(AGG_LAST_TIMESTAMP_COL);
            shouldUpdateTimestamp = ExpressionParser.parseExpression(shouldUpdateTimestampExp, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, false, 0, ProcessingMode.BATCH, false, siddhiQueryContext);
        }
        List<ExpressionExecutor> outputExpressionExecutors = outputExpressions.stream().map(expression -> ExpressionParser.parseExpression(expression, processedMetaStreamEvent, 0, tableMap, processVariableExpressionExecutors, isGroupBy, 0, ProcessingMode.BATCH, false, siddhiQueryContext)).collect(Collectors.toList());
        // Create group by key generator
        Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMap = new HashMap<>();
        aggregationDurations.forEach(incrementalDuration -> {
            GroupByKeyGenerator groupByKeyGenerator = null;
            if (isProcessingOnExternalTime || isGroupBy) {
                List<Expression> groupByExpressionList = new ArrayList<>();
                if (isProcessingOnExternalTime) {
                    Expression externalTimestampExpression = AttributeFunction.function("incrementalAggregator", "getAggregationStartTime", new Variable(AGG_EXTERNAL_TIMESTAMP_COL), new StringConstant(incrementalDuration.name()));
                    groupByExpressionList.add(externalTimestampExpression);
                }
                groupByExpressionList.addAll(groupByVariableList.stream().map(groupByVariable -> (Expression) groupByVariable).collect(Collectors.toList()));
                groupByKeyGenerator = new GroupByKeyGenerator(groupByExpressionList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiQueryContext);
            }
            groupByKeyGeneratorMap.put(incrementalDuration, groupByKeyGenerator);
        });
        // GroupBy for reading
        Map<TimePeriod.Duration, GroupByKeyGenerator> groupByKeyGeneratorMapForReading = new HashMap<>();
        if (isDistributed && !isProcessingOnExternalTime) {
            aggregationDurations.forEach(incrementalDuration -> {
                List<Expression> groupByExpressionList = new ArrayList<>();
                Expression timestampExpression = AttributeFunction.function("incrementalAggregator", "getAggregationStartTime", new Variable(AGG_START_TIMESTAMP_COL), new StringConstant(incrementalDuration.name()));
                groupByExpressionList.add(timestampExpression);
                if (isGroupBy) {
                    groupByExpressionList.addAll(groupByVariableList.stream().map(groupByVariable -> (Expression) groupByVariable).collect(Collectors.toList()));
                }
                GroupByKeyGenerator groupByKeyGenerator = new GroupByKeyGenerator(groupByExpressionList, processedMetaStreamEvent, SiddhiConstants.UNKNOWN_STATE, tableMap, processVariableExpressionExecutors, siddhiQueryContext);
                groupByKeyGeneratorMapForReading.put(incrementalDuration, groupByKeyGenerator);
            });
        } else {
            groupByKeyGeneratorMapForReading.putAll(groupByKeyGeneratorMap);
        }
        // Create new scheduler
        EntryValveExecutor entryValveExecutor = new EntryValveExecutor(siddhiAppContext);
        LockWrapper lockWrapper = new LockWrapper(aggregatorName);
        lockWrapper.setLock(new ReentrantLock());
        Scheduler scheduler = SchedulerParser.parse(entryValveExecutor, siddhiQueryContext);
        scheduler.init(lockWrapper, aggregatorName);
        scheduler.setStreamEventFactory(new StreamEventFactory(processedMetaStreamEvent));
        QueryParserHelper.reduceMetaComplexEvent(incomingMetaStreamEvent);
        QueryParserHelper.reduceMetaComplexEvent(processedMetaStreamEvent);
        QueryParserHelper.updateVariablePosition(incomingMetaStreamEvent, incomingVariableExpressionExecutors);
        QueryParserHelper.updateVariablePosition(processedMetaStreamEvent, processVariableExpressionExecutors);
        Map<TimePeriod.Duration, Table> aggregationTables = initDefaultTables(aggregatorName, aggregationDurations, processedMetaStreamEvent.getOutputStreamDefinition(), siddhiAppRuntimeBuilder, aggregationDefinition.getAnnotations(), groupByVariableList, isProcessingOnExternalTime, isDistributed);
        Map<TimePeriod.Duration, Executor> incrementalExecutorMap = buildIncrementalExecutors(processedMetaStreamEvent, processExpressionExecutorsMap, groupByKeyGeneratorMap, aggregationDurations, aggregationTables, siddhiQueryContext, aggregatorName, shouldUpdateTimestamp, timeZone, isPersistedAggregation, incomingOutputStreamDefinition, isDistributed, shardId, isProcessingOnExternalTime, aggregationDefinition, configManager, groupByVariableList, isReadOnly);
        isOptimisedLookup = isOptimisedLookup && aggregationTables.get(aggregationDurations.get(0)) instanceof QueryableProcessor;
        List<String> groupByVariablesList = groupByVariableList.stream().map(Variable::getAttributeName).collect(Collectors.toList());
        List<OutputAttribute> defaultSelectorList = new ArrayList<>();
        if (isOptimisedLookup) {
            defaultSelectorList = incomingOutputStreamDefinition.getAttributeList().stream().map((attribute) -> new OutputAttribute(new Variable(attribute.getName()))).collect(Collectors.toList());
        }
        IncrementalDataPurger incrementalDataPurger = new IncrementalDataPurger();
        incrementalDataPurger.init(aggregationDefinition, new StreamEventFactory(processedMetaStreamEvent), aggregationTables, isProcessingOnExternalTime, siddhiQueryContext, aggregationDurations, timeZone, windowMap, aggregationMap);
        // Recreate in-memory data from tables
        IncrementalExecutorsInitialiser incrementalExecutorsInitialiser = new IncrementalExecutorsInitialiser(aggregationDurations, aggregationTables, incrementalExecutorMap, isDistributed, shardId, siddhiAppContext, processedMetaStreamEvent, tableMap, windowMap, aggregationMap, timeZone, isReadOnly, isPersistedAggregation);
        IncrementalExecutor rootIncrementalExecutor = (IncrementalExecutor) incrementalExecutorMap.get(aggregationDurations.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(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_FIND);
            latencyTrackerInsert = QueryParserHelper.createLatencyTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_INSERT);
            throughputTrackerFind = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_FIND);
            throughputTrackerInsert = QueryParserHelper.createThroughputTracker(siddhiAppContext, aggregationDefinition.getId(), METRIC_INFIX_AGGREGATIONS, METRIC_TYPE_INSERT);
        }
        AggregationRuntime aggregationRuntime = new AggregationRuntime(aggregationDefinition, isProcessingOnExternalTime, isDistributed, aggregationDurations, incrementalExecutorMap, aggregationTables, outputExpressionExecutors, processExpressionExecutorsMapForFind, shouldUpdateTimestamp, groupByKeyGeneratorMapForReading, isOptimisedLookup, defaultSelectorList, groupByVariablesList, isLatestEventColAdded, baseAggregatorBeginIndex, finalBaseExpressions, incrementalDataPurger, incrementalExecutorsInitialiser, ((SingleStreamRuntime) streamRuntime), processedMetaStreamEvent, latencyTrackerFind, throughputTrackerFind, timeZone);
        streamRuntime.setCommonProcessor(new IncrementalAggregationProcessor(aggregationRuntime, incomingExpressionExecutors, processedMetaStreamEvent, latencyTrackerInsert, throughputTrackerInsert, siddhiAppContext));
        return aggregationRuntime;
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, aggregationDefinition, siddhiAppContext);
        throw t;
    }
}
Also used : AnnotationHelper(io.siddhi.query.api.util.AnnotationHelper) Arrays(java.util.Arrays) PersistedAggregationResultsProcessor(io.siddhi.core.aggregation.persistedaggregation.config.PersistedAggregationResultsProcessor) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) METRIC_TYPE_FIND(io.siddhi.core.util.SiddhiConstants.METRIC_TYPE_FIND) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SiddhiContext(io.siddhi.core.config.SiddhiContext) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) Expression(io.siddhi.query.api.expression.Expression) SUB_SELECT_QUERY_REF_T2(io.siddhi.core.util.SiddhiConstants.SUB_SELECT_QUERY_REF_T2) SUB_SELECT_QUERY_REF_T1(io.siddhi.core.util.SiddhiConstants.SUB_SELECT_QUERY_REF_T1) AbstractStreamProcessor(io.siddhi.core.query.processor.stream.AbstractStreamProcessor) Map(java.util.Map) METRIC_INFIX_AGGREGATIONS(io.siddhi.core.util.SiddhiConstants.METRIC_INFIX_AGGREGATIONS) IncrementalExecutorsInitialiser(io.siddhi.core.aggregation.IncrementalExecutorsInitialiser) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) TableDefinition(io.siddhi.query.api.definition.TableDefinition) ProcessingMode(io.siddhi.core.query.processor.ProcessingMode) DBAggregationQueryConfigurationEntry(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationQueryConfigurationEntry) LockWrapper(io.siddhi.core.util.lock.LockWrapper) SQL_NOT_NULL(io.siddhi.core.util.SiddhiConstants.SQL_NOT_NULL) ComplexEvent(io.siddhi.core.event.ComplexEvent) Set(java.util.Set) ConfigReader(io.siddhi.core.util.config.ConfigReader) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) Element(io.siddhi.query.api.annotation.Element) FunctionExecutorExtensionHolder(io.siddhi.core.util.extension.holder.FunctionExecutorExtensionHolder) MaxAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MaxAttributeAggregatorExecutor) Logger(org.apache.logging.log4j.Logger) Window(io.siddhi.core.window.Window) AGG_EXTERNAL_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_EXTERNAL_TIMESTAMP_COL) INNER_SELECT_QUERY_REF_T3(io.siddhi.core.util.SiddhiConstants.INNER_SELECT_QUERY_REF_T3) StreamHandler(io.siddhi.query.api.execution.query.input.handler.StreamHandler) FUNCTION_NAME_CUD(io.siddhi.core.util.SiddhiConstants.FUNCTION_NAME_CUD) Variable(io.siddhi.query.api.expression.Variable) DBAggregationSelectFunctionTemplate(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationSelectFunctionTemplate) ArrayList(java.util.ArrayList) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) LinkedHashMap(java.util.LinkedHashMap) StreamProcessorExtensionHolder(io.siddhi.core.util.extension.holder.StreamProcessorExtensionHolder) Extension(io.siddhi.query.api.extension.Extension) ANNOTATION_ELEMENT_IS_READ_ONLY(io.siddhi.core.util.SiddhiConstants.ANNOTATION_ELEMENT_IS_READ_ONLY) DBAggregationQueryUtil(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationQueryUtil) IncrementalAggregateBaseTimeFunctionExecutor(io.siddhi.core.executor.incremental.IncrementalAggregateBaseTimeFunctionExecutor) ConfigManager(io.siddhi.core.util.config.ConfigManager) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) DBAggregationTimeConversionDurationMapping(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationTimeConversionDurationMapping) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) AGG_LAST_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_LAST_TIMESTAMP_COL) QueuedCudStreamProcessor(io.siddhi.core.aggregation.persistedaggregation.QueuedCudStreamProcessor) PLACEHOLDER_TABLE_NAME(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_TABLE_NAME) IncrementalAttributeAggregator(io.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) ANNOTATION_PARTITION_BY_ID(io.siddhi.core.util.SiddhiConstants.ANNOTATION_PARTITION_BY_ID) PLACEHOLDER_DURATION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_DURATION) EQUALS(io.siddhi.core.util.SiddhiConstants.EQUALS) SQL_AND(io.siddhi.core.util.SiddhiConstants.SQL_AND) QueryParserHelper(io.siddhi.core.util.parser.helper.QueryParserHelper) PLACEHOLDER_COLUMN(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_COLUMN) AGG_SHARD_ID_COL(io.siddhi.core.util.SiddhiConstants.AGG_SHARD_ID_COL) Scheduler(io.siddhi.core.util.Scheduler) AggregationDefinition(io.siddhi.query.api.definition.AggregationDefinition) SiddhiAppRuntimeBuilder(io.siddhi.core.util.SiddhiAppRuntimeBuilder) PLACEHOLDER_FROM_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_FROM_CONDITION) SiddhiAppContext(io.siddhi.core.config.SiddhiAppContext) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) PLACEHOLDER_SELECTORS(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_SELECTORS) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SiddhiConstants(io.siddhi.core.util.SiddhiConstants) SQL_WHERE(io.siddhi.core.util.SiddhiConstants.SQL_WHERE) Annotation(io.siddhi.query.api.annotation.Annotation) IncrementalDataPurger(io.siddhi.core.aggregation.IncrementalDataPurger) StreamEvent(io.siddhi.core.event.stream.StreamEvent) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) PLACEHOLDER_COLUMNS(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_COLUMNS) Table(io.siddhi.core.table.Table) NAMESPACE_RDBMS(io.siddhi.core.util.SiddhiConstants.NAMESPACE_RDBMS) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime) StreamEventFactory(io.siddhi.core.event.stream.StreamEventFactory) TimeZone(java.util.TimeZone) AGG_START_TIMESTAMP_COL(io.siddhi.core.util.SiddhiConstants.AGG_START_TIMESTAMP_COL) ExceptionUtil(io.siddhi.core.util.ExceptionUtil) SumAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.SumAttributeAggregatorExecutor) PLACEHOLDER_ON_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_ON_CONDITION) StreamProcessor(io.siddhi.core.query.processor.stream.StreamProcessor) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) TO_TIMESTAMP(io.siddhi.core.util.SiddhiConstants.TO_TIMESTAMP) List(java.util.List) SQL_SELECT(io.siddhi.core.util.SiddhiConstants.SQL_SELECT) CudStreamProcessorQueueManager(io.siddhi.core.aggregation.persistedaggregation.CudStreamProcessorQueueManager) Processor(io.siddhi.core.query.processor.Processor) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) PLACEHOLDER_INNER_QUERY_1(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_INNER_QUERY_1) PLACEHOLDER_INNER_QUERY_2(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_INNER_QUERY_2) ANNOTATION_ELEMENT_ENABLE(io.siddhi.core.util.SiddhiConstants.ANNOTATION_ELEMENT_ENABLE) METRIC_TYPE_INSERT(io.siddhi.core.util.SiddhiConstants.METRIC_TYPE_INSERT) Executor(io.siddhi.core.aggregation.Executor) ANNOTATION_PERSISTED_AGGREGATION(io.siddhi.core.util.SiddhiConstants.ANNOTATION_PERSISTED_AGGREGATION) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) SiddhiClassLoader(io.siddhi.core.util.SiddhiClassLoader) IncrementalAttributeAggregatorExtensionHolder(io.siddhi.core.util.extension.holder.IncrementalAttributeAggregatorExtensionHolder) HashMap(java.util.HashMap) HashSet(java.util.HashSet) CannotLoadConfigurationException(io.siddhi.core.exception.CannotLoadConfigurationException) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) DBAggregationSelectQueryTemplate(io.siddhi.core.aggregation.persistedaggregation.config.DBAggregationSelectQueryTemplate) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) PLACEHOLDER_CONDITION(io.siddhi.core.util.SiddhiConstants.PLACEHOLDER_CONDITION) StreamFunction(io.siddhi.query.api.execution.query.input.handler.StreamFunction) ReentrantLock(java.util.concurrent.locks.ReentrantLock) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) Attribute(io.siddhi.query.api.definition.Attribute) IncrementalAggregationProcessor(io.siddhi.core.aggregation.IncrementalAggregationProcessor) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) SQL_FROM(io.siddhi.core.util.SiddhiConstants.SQL_FROM) FROM_TIMESTAMP(io.siddhi.core.util.SiddhiConstants.FROM_TIMESTAMP) TimePeriod(io.siddhi.query.api.aggregation.TimePeriod) MinAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MinAttributeAggregatorExecutor) StringJoiner(java.util.StringJoiner) Comparator(java.util.Comparator) SQL_AS(io.siddhi.core.util.SiddhiConstants.SQL_AS) LogManager(org.apache.logging.log4j.LogManager) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) QueryableProcessor(io.siddhi.core.query.processor.stream.window.QueryableProcessor) AggregationRuntime(io.siddhi.core.aggregation.AggregationRuntime) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ThroughputTracker(io.siddhi.core.util.statistics.ThroughputTracker) StreamDefinition(io.siddhi.query.api.definition.StreamDefinition) SiddhiAppCreationException(io.siddhi.core.exception.SiddhiAppCreationException) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) StreamEventFactory(io.siddhi.core.event.stream.StreamEventFactory) IncrementalAttributeAggregator(io.siddhi.core.query.selector.attribute.aggregator.incremental.IncrementalAttributeAggregator) LatencyTracker(io.siddhi.core.util.statistics.LatencyTracker) StringConstant(io.siddhi.query.api.expression.constant.StringConstant) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) Variable(io.siddhi.query.api.expression.Variable) IncrementalDataPurger(io.siddhi.core.aggregation.IncrementalDataPurger) Attribute(io.siddhi.query.api.definition.Attribute) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) Scheduler(io.siddhi.core.util.Scheduler) Element(io.siddhi.query.api.annotation.Element) GroupByKeyGenerator(io.siddhi.core.query.selector.GroupByKeyGenerator) IncrementalExecutorsInitialiser(io.siddhi.core.aggregation.IncrementalExecutorsInitialiser) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) OutputAttribute(io.siddhi.query.api.execution.query.selection.OutputAttribute) SiddhiQueryContext(io.siddhi.core.config.SiddhiQueryContext) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) MaxAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MaxAttributeAggregatorExecutor) IncrementalAggregateBaseTimeFunctionExecutor(io.siddhi.core.executor.incremental.IncrementalAggregateBaseTimeFunctionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) PersistedIncrementalExecutor(io.siddhi.core.aggregation.persistedaggregation.PersistedIncrementalExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) SumAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.SumAttributeAggregatorExecutor) Executor(io.siddhi.core.aggregation.Executor) IncrementalExecutor(io.siddhi.core.aggregation.IncrementalExecutor) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) MinAttributeAggregatorExecutor(io.siddhi.core.query.selector.attribute.aggregator.MinAttributeAggregatorExecutor) StreamRuntime(io.siddhi.core.query.input.stream.StreamRuntime) SingleStreamRuntime(io.siddhi.core.query.input.stream.single.SingleStreamRuntime) IncrementalAggregationProcessor(io.siddhi.core.aggregation.IncrementalAggregationProcessor) Table(io.siddhi.core.table.Table) ExpressionExecutor(io.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(io.siddhi.core.executor.ConstantExpressionExecutor) VariableExpressionExecutor(io.siddhi.core.executor.VariableExpressionExecutor) EntryValveExecutor(io.siddhi.core.query.input.stream.single.EntryValveExecutor) AttributeFunction(io.siddhi.query.api.expression.AttributeFunction) LockWrapper(io.siddhi.core.util.lock.LockWrapper) Annotation(io.siddhi.query.api.annotation.Annotation) ConfigManager(io.siddhi.core.util.config.ConfigManager) Expression(io.siddhi.query.api.expression.Expression)

Example 43 with MetaStreamEvent

use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.

the class PartitionParser method createMetaEventForPartitioner.

/**
 * Create metaEvent to be used by StreamPartitioner with output attributes
 *
 * @param stateEvent metaStateEvent of the queryRuntime
 * @return metaStateEvent
 */
private static MetaStateEvent createMetaEventForPartitioner(MetaComplexEvent stateEvent) {
    MetaStateEvent metaStateEvent;
    if (stateEvent instanceof MetaStateEvent) {
        metaStateEvent = new MetaStateEvent(((MetaStateEvent) stateEvent).getStreamEventCount());
        for (MetaStreamEvent metaStreamEvent : ((MetaStateEvent) stateEvent).getMetaStreamEvents()) {
            AbstractDefinition definition = metaStreamEvent.getLastInputDefinition();
            MetaStreamEvent newMetaStreamEvent = new MetaStreamEvent();
            for (Attribute attribute : definition.getAttributeList()) {
                newMetaStreamEvent.addOutputData(attribute);
            }
            newMetaStreamEvent.addInputDefinition(definition);
            newMetaStreamEvent.setEventType(metaStreamEvent.getEventType());
            metaStateEvent.addEvent(newMetaStreamEvent);
        }
    } else {
        metaStateEvent = new MetaStateEvent(1);
        AbstractDefinition definition = ((MetaStreamEvent) stateEvent).getLastInputDefinition();
        MetaStreamEvent newMetaStreamEvent = new MetaStreamEvent();
        for (Attribute attribute : definition.getAttributeList()) {
            newMetaStreamEvent.addOutputData(attribute);
        }
        newMetaStreamEvent.addInputDefinition(definition);
        newMetaStreamEvent.setEventType(((MetaStreamEvent) stateEvent).getEventType());
        metaStateEvent.addEvent(newMetaStreamEvent);
    }
    return metaStateEvent;
}
Also used : Attribute(io.siddhi.query.api.definition.Attribute) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent)

Example 44 with MetaStreamEvent

use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.

the class EventHolderPasser method parse.

public static EventHolder parse(AbstractDefinition tableDefinition, StreamEventFactory tableStreamEventFactory, SiddhiAppContext siddhiAppContext, boolean isCacheTable) {
    ZeroStreamEventConverter eventConverter = new ZeroStreamEventConverter();
    PrimaryKeyReferenceHolder[] primaryKeyReferenceHolders = null;
    Map<String, Integer> indexMetaData = new HashMap<String, Integer>();
    // primaryKey.
    Annotation primaryKeyAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_PRIMARY_KEY, tableDefinition.getAnnotations());
    if (primaryKeyAnnotation != null) {
        if (primaryKeyAnnotation.getElements().size() == 0) {
            throw new SiddhiAppValidationException(SiddhiConstants.ANNOTATION_PRIMARY_KEY + " annotation " + "contains " + primaryKeyAnnotation.getElements().size() + " element, at '" + tableDefinition.getId() + "'");
        }
        primaryKeyReferenceHolders = primaryKeyAnnotation.getElements().stream().map(element -> element.getValue().trim()).map(key -> new PrimaryKeyReferenceHolder(key, tableDefinition.getAttributePosition(key))).toArray(PrimaryKeyReferenceHolder[]::new);
    }
    for (Annotation indexAnnotation : AnnotationHelper.getAnnotations(SiddhiConstants.ANNOTATION_INDEX, tableDefinition.getAnnotations())) {
        if (indexAnnotation.getElements().size() == 0) {
            throw new SiddhiAppValidationException(SiddhiConstants.ANNOTATION_INDEX + " annotation of " + "in-memory table should contain only one index element, but found " + indexAnnotation.getElements().size() + " element", indexAnnotation.getQueryContextStartIndex(), indexAnnotation.getQueryContextEndIndex());
        } else if (indexAnnotation.getElements().size() > 1) {
            throw new SiddhiAppValidationException(SiddhiConstants.ANNOTATION_INDEX + " annotation of the " + "in-memory table should only contain one index element but found " + indexAnnotation.getElements().size() + " elements. To use multiple indexes, " + "define multiple '@index(<index key>)' annotations with one index element " + "per each index key", indexAnnotation.getQueryContextStartIndex(), indexAnnotation.getQueryContextEndIndex());
        }
        for (Element element : indexAnnotation.getElements()) {
            Integer previousValue = indexMetaData.put(element.getValue().trim(), tableDefinition.getAttributePosition(element.getValue().trim()));
            if (previousValue != null) {
                throw new SiddhiAppValidationException("Multiple " + SiddhiConstants.ANNOTATION_INDEX + " " + "annotations defined with same attribute '" + element.getValue().trim() + "', at '" + tableDefinition.getId() + "'", indexAnnotation.getQueryContextStartIndex(), indexAnnotation.getQueryContextEndIndex());
            }
        }
    }
    // not support indexBy.
    Annotation indexByAnnotation = AnnotationHelper.getAnnotation(SiddhiConstants.ANNOTATION_INDEX_BY, tableDefinition.getAnnotations());
    if (indexByAnnotation != null) {
        throw new OperationNotSupportedException(SiddhiConstants.ANNOTATION_INDEX_BY + " annotation is not " + "supported anymore, please use @PrimaryKey or @Index annotations instead," + " at '" + tableDefinition.getId() + "'");
    }
    if (primaryKeyReferenceHolders != null || indexMetaData.size() > 0) {
        boolean isNumeric = false;
        if (primaryKeyReferenceHolders != null) {
            if (primaryKeyReferenceHolders.length == 1) {
                Attribute.Type type = tableDefinition.getAttributeType(primaryKeyReferenceHolders[0].getPrimaryKeyAttribute());
                if (type == Attribute.Type.DOUBLE || type == Attribute.Type.FLOAT || type == Attribute.Type.INT || type == Attribute.Type.LONG) {
                    isNumeric = true;
                }
            }
        }
        if (isCacheTable) {
            return new IndexEventHolderForCache(tableStreamEventFactory, eventConverter, primaryKeyReferenceHolders, isNumeric, indexMetaData, tableDefinition, siddhiAppContext);
        } else {
            return new IndexEventHolder(tableStreamEventFactory, eventConverter, primaryKeyReferenceHolders, isNumeric, indexMetaData, tableDefinition, siddhiAppContext);
        }
    } else {
        MetaStreamEvent metaStreamEvent = new MetaStreamEvent();
        for (Attribute attribute : tableDefinition.getAttributeList()) {
            metaStreamEvent.addOutputData(attribute);
        }
        StreamEventCloner streamEventCloner = new StreamEventCloner(metaStreamEvent, tableStreamEventFactory);
        return new ListEventHolder(tableStreamEventFactory, eventConverter, new StreamEventClonerHolder(streamEventCloner));
    }
}
Also used : StreamEventClonerHolder(io.siddhi.core.event.stream.holder.StreamEventClonerHolder) AnnotationHelper(io.siddhi.query.api.util.AnnotationHelper) SiddhiAppContext(io.siddhi.core.config.SiddhiAppContext) StreamEventFactory(io.siddhi.core.event.stream.StreamEventFactory) PrimaryKeyReferenceHolder(io.siddhi.core.table.holder.PrimaryKeyReferenceHolder) StreamEventCloner(io.siddhi.core.event.stream.StreamEventCloner) SiddhiConstants(io.siddhi.core.util.SiddhiConstants) Attribute(io.siddhi.query.api.definition.Attribute) Annotation(io.siddhi.query.api.annotation.Annotation) HashMap(java.util.HashMap) IndexEventHolderForCache(io.siddhi.core.table.holder.IndexEventHolderForCache) Element(io.siddhi.query.api.annotation.Element) IndexEventHolder(io.siddhi.core.table.holder.IndexEventHolder) AbstractDefinition(io.siddhi.query.api.definition.AbstractDefinition) ListEventHolder(io.siddhi.core.table.holder.ListEventHolder) Logger(org.apache.logging.log4j.Logger) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) ZeroStreamEventConverter(io.siddhi.core.event.stream.converter.ZeroStreamEventConverter) OperationNotSupportedException(io.siddhi.core.exception.OperationNotSupportedException) Map(java.util.Map) EventHolder(io.siddhi.core.table.holder.EventHolder) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) LogManager(org.apache.logging.log4j.LogManager) OperationNotSupportedException(io.siddhi.core.exception.OperationNotSupportedException) IndexEventHolder(io.siddhi.core.table.holder.IndexEventHolder) HashMap(java.util.HashMap) Attribute(io.siddhi.query.api.definition.Attribute) Element(io.siddhi.query.api.annotation.Element) SiddhiAppValidationException(io.siddhi.query.api.exception.SiddhiAppValidationException) PrimaryKeyReferenceHolder(io.siddhi.core.table.holder.PrimaryKeyReferenceHolder) Annotation(io.siddhi.query.api.annotation.Annotation) StreamEventClonerHolder(io.siddhi.core.event.stream.holder.StreamEventClonerHolder) ZeroStreamEventConverter(io.siddhi.core.event.stream.converter.ZeroStreamEventConverter) StreamEventCloner(io.siddhi.core.event.stream.StreamEventCloner) ListEventHolder(io.siddhi.core.table.holder.ListEventHolder) IndexEventHolderForCache(io.siddhi.core.table.holder.IndexEventHolderForCache) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent)

Example 45 with MetaStreamEvent

use of io.siddhi.core.event.stream.MetaStreamEvent in project siddhi by wso2.

the class InputStreamParser method parse.

/**
 * Parse an InputStream returning corresponding StreamRuntime
 *
 * @param inputStream                input stream to be parsed
 * @param streamDefinitionMap        map containing user given stream definitions
 * @param tableDefinitionMap         table definition map
 * @param windowDefinitionMap        window definition map
 * @param aggregationDefinitionMap   aggregation definition map
 * @param tableMap                   Table Map
 * @param windowMap                  event window map
 * @param aggregationMap             aggregator map
 * @param executors                  List to hold VariableExpressionExecutors to update after query parsing
 * @param outputExpectsExpiredEvents is expired events sent as output
 * @param siddhiQueryContext         Siddhi query context.
 * @return StreamRuntime
 */
public static StreamRuntime parse(InputStream inputStream, 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) {
    if (inputStream instanceof BasicSingleInputStream || inputStream instanceof SingleInputStream) {
        SingleInputStream singleInputStream = (SingleInputStream) inputStream;
        ProcessStreamReceiver processStreamReceiver = new ProcessStreamReceiver(singleInputStream.getStreamId(), siddhiQueryContext);
        return SingleInputStreamParser.parseInputStream((SingleInputStream) inputStream, executors, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, new MetaStreamEvent(), processStreamReceiver, true, outputExpectsExpiredEvents, false, false, siddhiQueryContext);
    } else if (inputStream instanceof JoinInputStream) {
        return JoinInputStreamParser.parseInputStream(((JoinInputStream) inputStream), query, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, outputExpectsExpiredEvents, siddhiQueryContext);
    } else if (inputStream instanceof StateInputStream) {
        MetaStateEvent metaStateEvent = new MetaStateEvent(inputStream.getAllStreamIds().size());
        return StateInputStreamParser.parseInputStream(((StateInputStream) inputStream), metaStateEvent, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, executors, siddhiQueryContext);
    } else {
        throw new OperationNotSupportedException();
    }
}
Also used : OperationNotSupportedException(io.siddhi.core.exception.OperationNotSupportedException) ProcessStreamReceiver(io.siddhi.core.query.input.ProcessStreamReceiver) SingleInputStream(io.siddhi.query.api.execution.query.input.stream.SingleInputStream) BasicSingleInputStream(io.siddhi.query.api.execution.query.input.stream.BasicSingleInputStream) JoinInputStream(io.siddhi.query.api.execution.query.input.stream.JoinInputStream) BasicSingleInputStream(io.siddhi.query.api.execution.query.input.stream.BasicSingleInputStream) StateInputStream(io.siddhi.query.api.execution.query.input.stream.StateInputStream) MetaStreamEvent(io.siddhi.core.event.stream.MetaStreamEvent) MetaStateEvent(io.siddhi.core.event.state.MetaStateEvent)

Aggregations

MetaStreamEvent (io.siddhi.core.event.stream.MetaStreamEvent)63 Attribute (io.siddhi.query.api.definition.Attribute)35 MetaStateEvent (io.siddhi.core.event.state.MetaStateEvent)34 StreamEvent (io.siddhi.core.event.stream.StreamEvent)21 StreamEventFactory (io.siddhi.core.event.stream.StreamEventFactory)17 VariableExpressionExecutor (io.siddhi.core.executor.VariableExpressionExecutor)17 ArrayList (java.util.ArrayList)17 StreamEventCloner (io.siddhi.core.event.stream.StreamEventCloner)14 MatchingMetaInfoHolder (io.siddhi.core.util.collection.operator.MatchingMetaInfoHolder)14 Variable (io.siddhi.query.api.expression.Variable)14 SiddhiAppCreationException (io.siddhi.core.exception.SiddhiAppCreationException)13 HashMap (java.util.HashMap)13 AbstractDefinition (io.siddhi.query.api.definition.AbstractDefinition)12 Expression (io.siddhi.query.api.expression.Expression)12 ExpressionExecutor (io.siddhi.core.executor.ExpressionExecutor)10 StreamDefinition (io.siddhi.query.api.definition.StreamDefinition)10 Map (java.util.Map)10 Test (org.testng.annotations.Test)10 ConstantExpressionExecutor (io.siddhi.core.executor.ConstantExpressionExecutor)9 TableDefinition (io.siddhi.query.api.definition.TableDefinition)9