Search in sources :

Example 6 with Selector

use of org.wso2.siddhi.query.api.execution.query.selection.Selector in project siddhi by wso2.

the class SiddhiQLBaseVisitorImpl method visitQuery.

/**
 * {@inheritDoc}
 * <p>The default implementation returns the result of calling
 * {@link #visitChildren} on {@code ctx}.</p>
 *
 * @param ctx
 */
@Override
public Query visitQuery(@NotNull SiddhiQLParser.QueryContext ctx) {
    try {
        Query query = Query.query().from((InputStream) visit(ctx.query_input()));
        if (ctx.query_section() != null) {
            query.select((Selector) visit(ctx.query_section()));
        }
        if (ctx.output_rate() != null) {
            query.output((OutputRate) visit(ctx.output_rate()));
        }
        for (SiddhiQLParser.AnnotationContext annotationContext : ctx.annotation()) {
            query.annotation((Annotation) visit(annotationContext));
        }
        if (ctx.query_output() != null) {
            query.outStream((OutputStream) visit(ctx.query_output()));
        }
        populateQueryContext(query, ctx);
        return query;
    } finally {
        activeStreams.clear();
    }
}
Also used : SiddhiQLParser(org.wso2.siddhi.query.compiler.SiddhiQLParser) StoreQuery(org.wso2.siddhi.query.api.execution.query.StoreQuery) Query(org.wso2.siddhi.query.api.execution.query.Query)

Example 7 with Selector

use of org.wso2.siddhi.query.api.execution.query.selection.Selector in project siddhi by wso2.

the class QueryParser method parse.

/**
 * Parse a query and return corresponding QueryRuntime.
 *
 * @param query                    query to be parsed.
 * @param siddhiAppContext         associated Siddhi app context.
 * @param streamDefinitionMap      keyvalue containing user given stream definitions.
 * @param tableDefinitionMap       keyvalue containing table definitions.
 * @param windowDefinitionMap      keyvalue containing window definition map.
 * @param aggregationDefinitionMap keyvalue containing aggregation definition map.
 * @param tableMap                 keyvalue containing event tables.
 * @param aggregationMap           keyvalue containing aggrigation runtimes.
 * @param windowMap                keyvalue containing event window map.
 * @param lockSynchronizer         Lock synchronizer for sync the lock across queries.
 * @param queryIndex               query index to identify unknown query by number
 * @return queryRuntime
 */
public static QueryRuntime parse(Query query, SiddhiAppContext siddhiAppContext, Map<String, AbstractDefinition> streamDefinitionMap, Map<String, AbstractDefinition> tableDefinitionMap, Map<String, AbstractDefinition> windowDefinitionMap, Map<String, AbstractDefinition> aggregationDefinitionMap, Map<String, Table> tableMap, Map<String, AggregationRuntime> aggregationMap, Map<String, Window> windowMap, LockSynchronizer lockSynchronizer, String queryIndex) {
    List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
    QueryRuntime queryRuntime;
    Element nameElement = null;
    LatencyTracker latencyTracker = null;
    LockWrapper lockWrapper = null;
    try {
        nameElement = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
        String queryName = null;
        if (nameElement != null) {
            queryName = nameElement.getValue();
        } else {
            queryName = "query_" + queryIndex + "_" + UUID.randomUUID().toString();
        }
        latencyTracker = QueryParserHelper.createLatencyTracker(siddhiAppContext, queryName, SiddhiConstants.METRIC_INFIX_QUERIES, null);
        OutputStream.OutputEventType outputEventType = query.getOutputStream().getOutputEventType();
        boolean outputExpectsExpiredEvents = false;
        if (outputEventType != OutputStream.OutputEventType.CURRENT_EVENTS) {
            outputExpectsExpiredEvents = true;
        }
        StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(), siddhiAppContext, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap, aggregationDefinitionMap, tableMap, windowMap, aggregationMap, executors, latencyTracker, outputExpectsExpiredEvents, queryName);
        QuerySelector selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(), siddhiAppContext, streamRuntime.getMetaComplexEvent(), tableMap, executors, queryName, SiddhiConstants.UNKNOWN_STATE);
        boolean isWindow = query.getInputStream() instanceof JoinInputStream;
        if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
            for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
                if (streamHandler instanceof org.wso2.siddhi.query.api.execution.query.input.handler.Window) {
                    isWindow = true;
                    break;
                }
            }
        }
        Element synchronizedElement = AnnotationHelper.getAnnotationElement("synchronized", null, query.getAnnotations());
        if (synchronizedElement != null) {
            if (!("false".equalsIgnoreCase(synchronizedElement.getValue()))) {
                // Query LockWrapper does not need a unique
                lockWrapper = new LockWrapper("");
                // id since it will
                // not be passed to the LockSynchronizer.
                // LockWrapper does not have a default lock
                lockWrapper.setLock(new ReentrantLock());
            }
        } else {
            if (isWindow || !(streamRuntime instanceof SingleStreamRuntime)) {
                if (streamRuntime instanceof JoinStreamRuntime) {
                    // If at least one Window is involved in the join, use the LockWrapper of that window
                    // for the query as well.
                    // If join is between two EventWindows, sync the locks of the LockWrapper of those windows
                    // and use either of them for query.
                    MetaStateEvent metaStateEvent = (MetaStateEvent) streamRuntime.getMetaComplexEvent();
                    MetaStreamEvent[] metaStreamEvents = metaStateEvent.getMetaStreamEvents();
                    if (metaStreamEvents[0].getEventType() == EventType.WINDOW && metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                        LockWrapper leftLockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
                        LockWrapper rightLockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
                        if (!leftLockWrapper.equals(rightLockWrapper)) {
                            // Sync the lock across both wrappers
                            lockSynchronizer.sync(leftLockWrapper, rightLockWrapper);
                        }
                        // Can use either leftLockWrapper or rightLockWrapper since both of them will hold the
                        // same lock internally
                        // If either of their lock is updated later, the other lock also will be update by the
                        // LockSynchronizer.
                        lockWrapper = leftLockWrapper;
                    } else if (metaStreamEvents[0].getEventType() == EventType.WINDOW) {
                        // Share the same wrapper as the query lock wrapper
                        lockWrapper = windowMap.get(metaStreamEvents[0].getLastInputDefinition().getId()).getLock();
                    } else if (metaStreamEvents[1].getEventType() == EventType.WINDOW) {
                        // Share the same wrapper as the query lock wrapper
                        lockWrapper = windowMap.get(metaStreamEvents[1].getLastInputDefinition().getId()).getLock();
                    } else {
                        // Join does not contain any Window
                        // Query LockWrapper does not need a unique
                        lockWrapper = new LockWrapper("");
                        // id since
                        // it will not be passed to the LockSynchronizer.
                        // LockWrapper does not have a default lock
                        lockWrapper.setLock(new ReentrantLock());
                    }
                } else {
                    lockWrapper = new LockWrapper("");
                    lockWrapper.setLock(new ReentrantLock());
                }
            }
        }
        OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(query.getOutputStream().getId(), query.getOutputRate(), query.getSelector().getGroupByList().size() != 0, isWindow, siddhiAppContext.getScheduledExecutorService(), siddhiAppContext, queryName);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
        }
        siddhiAppContext.addEternalReferencedHolder(outputRateLimiter);
        OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(), streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), tableMap, windowMap, siddhiAppContext, !(streamRuntime instanceof SingleStreamRuntime), queryName);
        QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
        QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
        QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent(), lockWrapper, queryName);
        selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
        queryRuntime = new QueryRuntime(query, siddhiAppContext, streamRuntime, selector, outputRateLimiter, outputCallback, streamRuntime.getMetaComplexEvent(), lockWrapper != null, queryName);
        if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
            selector.setBatchingEnabled(false);
            ((WrappedSnapshotOutputRateLimiter) outputRateLimiter).init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(), selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
        }
        outputRateLimiter.init(siddhiAppContext, lockWrapper, queryName);
    } catch (DuplicateDefinitionException e) {
        if (nameElement != null) {
            throw new DuplicateDefinitionException(e.getMessageWithOutContext() + ", when creating query " + nameElement.getValue(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
        } else {
            throw new DuplicateDefinitionException(e.getMessage(), e, e.getQueryContextStartIndex(), e.getQueryContextEndIndex(), siddhiAppContext.getName(), siddhiAppContext.getSiddhiAppString());
        }
    } catch (Throwable t) {
        ExceptionUtil.populateQueryContext(t, query, siddhiAppContext);
        throw t;
    }
    return queryRuntime;
}
Also used : Element(org.wso2.siddhi.query.api.annotation.Element) OutputStream(org.wso2.siddhi.query.api.execution.query.output.stream.OutputStream) ArrayList(java.util.ArrayList) OutputCallback(org.wso2.siddhi.core.query.output.callback.OutputCallback) QueryRuntime(org.wso2.siddhi.core.query.QueryRuntime) JoinInputStream(org.wso2.siddhi.query.api.execution.query.input.stream.JoinInputStream) SingleInputStream(org.wso2.siddhi.query.api.execution.query.input.stream.SingleInputStream) WrappedSnapshotOutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) OutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.OutputRateLimiter) StreamHandler(org.wso2.siddhi.query.api.execution.query.input.handler.StreamHandler) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) StreamRuntime(org.wso2.siddhi.core.query.input.stream.StreamRuntime) JoinStreamRuntime(org.wso2.siddhi.core.query.input.stream.join.JoinStreamRuntime) Window(org.wso2.siddhi.core.window.Window) ReentrantLock(java.util.concurrent.locks.ReentrantLock) DuplicateDefinitionException(org.wso2.siddhi.query.api.exception.DuplicateDefinitionException) SingleStreamRuntime(org.wso2.siddhi.core.query.input.stream.single.SingleStreamRuntime) JoinStreamRuntime(org.wso2.siddhi.core.query.input.stream.join.JoinStreamRuntime) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) QuerySelector(org.wso2.siddhi.core.query.selector.QuerySelector) LockWrapper(org.wso2.siddhi.core.util.lock.LockWrapper) MetaStateEvent(org.wso2.siddhi.core.event.state.MetaStateEvent) LatencyTracker(org.wso2.siddhi.core.util.statistics.LatencyTracker) WrappedSnapshotOutputRateLimiter(org.wso2.siddhi.core.query.output.ratelimit.snapshot.WrappedSnapshotOutputRateLimiter) MetaStreamEvent(org.wso2.siddhi.core.event.stream.MetaStreamEvent)

Example 8 with Selector

use of org.wso2.siddhi.query.api.execution.query.selection.Selector in project siddhi by wso2.

the class SelectorParser method parse.

/**
 * Parse Selector portion of a query and return corresponding QuerySelector.
 *
 * @param selector                    selector to be parsed
 * @param outputStream                output stream
 * @param siddhiAppContext            query to be parsed
 * @param metaComplexEvent            Meta event used to collect execution info of stream associated with query
 * @param tableMap                    Table Map
 * @param variableExpressionExecutors variable expression executors
 * @param queryName                   query name of selector belongs to.
 * @param metaPosition                helps to identify the meta position of aggregates
 * @return QuerySelector
 */
public static QuerySelector parse(Selector selector, OutputStream outputStream, SiddhiAppContext siddhiAppContext, MetaComplexEvent metaComplexEvent, Map<String, Table> tableMap, List<VariableExpressionExecutor> variableExpressionExecutors, String queryName, int metaPosition) {
    boolean currentOn = false;
    boolean expiredOn = false;
    String id = null;
    if (outputStream.getOutputEventType() == OutputStream.OutputEventType.CURRENT_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
        currentOn = true;
    }
    if (outputStream.getOutputEventType() == OutputStream.OutputEventType.EXPIRED_EVENTS || outputStream.getOutputEventType() == OutputStream.OutputEventType.ALL_EVENTS) {
        expiredOn = true;
    }
    id = outputStream.getId();
    containsAggregatorThreadLocal.remove();
    QuerySelector querySelector = new QuerySelector(id, selector, currentOn, expiredOn, siddhiAppContext);
    List<AttributeProcessor> attributeProcessors = getAttributeProcessors(selector, id, siddhiAppContext, metaComplexEvent, tableMap, variableExpressionExecutors, outputStream, queryName, metaPosition);
    querySelector.setAttributeProcessorList(attributeProcessors, "true".equals(containsAggregatorThreadLocal.get()));
    containsAggregatorThreadLocal.remove();
    ConditionExpressionExecutor havingCondition = generateHavingExecutor(selector.getHavingExpression(), metaComplexEvent, siddhiAppContext, tableMap, variableExpressionExecutors, queryName);
    querySelector.setHavingConditionExecutor(havingCondition, "true".equals(containsAggregatorThreadLocal.get()));
    containsAggregatorThreadLocal.remove();
    if (!selector.getGroupByList().isEmpty()) {
        querySelector.setGroupByKeyGenerator(new GroupByKeyGenerator(selector.getGroupByList(), metaComplexEvent, SiddhiConstants.UNKNOWN_STATE, null, variableExpressionExecutors, siddhiAppContext, queryName));
    }
    if (!selector.getOrderByList().isEmpty()) {
        querySelector.setOrderByEventComparator(new OrderByEventComparator(selector.getOrderByList(), metaComplexEvent, SiddhiConstants.HAVING_STATE, null, variableExpressionExecutors, siddhiAppContext, queryName));
    }
    if (selector.getLimit() != null) {
        ExpressionExecutor expressionExecutor = ExpressionParser.parseExpression((Expression) selector.getLimit(), metaComplexEvent, SiddhiConstants.HAVING_STATE, tableMap, variableExpressionExecutors, siddhiAppContext, false, 0, queryName);
        containsAggregatorThreadLocal.remove();
        querySelector.setLimit(((Number) (((ConstantExpressionExecutor) expressionExecutor).getValue())).longValue());
    }
    return querySelector;
}
Also used : ConditionExpressionExecutor(org.wso2.siddhi.core.executor.condition.ConditionExpressionExecutor) VariableExpressionExecutor(org.wso2.siddhi.core.executor.VariableExpressionExecutor) ExpressionExecutor(org.wso2.siddhi.core.executor.ExpressionExecutor) ConstantExpressionExecutor(org.wso2.siddhi.core.executor.ConstantExpressionExecutor) GroupByKeyGenerator(org.wso2.siddhi.core.query.selector.GroupByKeyGenerator) QuerySelector(org.wso2.siddhi.core.query.selector.QuerySelector) AttributeProcessor(org.wso2.siddhi.core.query.selector.attribute.processor.AttributeProcessor) ConditionExpressionExecutor(org.wso2.siddhi.core.executor.condition.ConditionExpressionExecutor) OrderByEventComparator(org.wso2.siddhi.core.query.selector.OrderByEventComparator)

Example 9 with Selector

use of org.wso2.siddhi.query.api.execution.query.selection.Selector in project siddhi by wso2.

the class FindStoreQueryRuntime method execute.

@Override
public Event[] execute() {
    try {
        StateEvent stateEvent = new StateEvent(1, 0);
        StreamEvent streamEvents = null;
        switch(eventType) {
            case TABLE:
                streamEvents = table.find(stateEvent, compiledCondition);
                break;
            case WINDOW:
                streamEvents = window.find(stateEvent, compiledCondition);
                break;
            case AGGREGATE:
                stateEvent = new StateEvent(2, 0);
                StreamEvent streamEvent = new StreamEvent(0, 2, 0);
                stateEvent.addEvent(0, streamEvent);
                streamEvents = aggregation.find(stateEvent, compiledCondition);
                break;
            case DEFAULT:
                break;
        }
        if (streamEvents == null) {
            return null;
        } else {
            if (selector != null) {
                return executeSelector(streamEvents, eventType);
            } else {
                List<Event> events = new ArrayList<Event>();
                while (streamEvents != null) {
                    events.add(new Event(streamEvents.getTimestamp(), streamEvents.getOutputData()));
                    streamEvents = streamEvents.getNext();
                }
                return events.toArray(new Event[0]);
            }
        }
    } catch (Throwable t) {
        throw new StoreQueryRuntimeException("Error executing '" + queryName + "', " + t.getMessage(), t);
    }
}
Also used : MetaStreamEvent(org.wso2.siddhi.core.event.stream.MetaStreamEvent) StreamEvent(org.wso2.siddhi.core.event.stream.StreamEvent) StoreQueryRuntimeException(org.wso2.siddhi.core.exception.StoreQueryRuntimeException) ArrayList(java.util.ArrayList) StateEvent(org.wso2.siddhi.core.event.state.StateEvent) MetaStreamEvent(org.wso2.siddhi.core.event.stream.MetaStreamEvent) StreamEvent(org.wso2.siddhi.core.event.stream.StreamEvent) ComplexEvent(org.wso2.siddhi.core.event.ComplexEvent) Event(org.wso2.siddhi.core.event.Event) StateEvent(org.wso2.siddhi.core.event.state.StateEvent)

Example 10 with Selector

use of org.wso2.siddhi.query.api.execution.query.selection.Selector in project siddhi by wso2.

the class SiddhiQLBaseVisitorImpl method visitQuery_section.

/**
 * {@inheritDoc}
 * <p>The default implementation returns the result of calling
 * {@link #visitChildren} on {@code ctx}.</p>
 *
 * @param ctx
 */
@Override
public Selector visitQuery_section(@NotNull SiddhiQLParser.Query_sectionContext ctx) {
    // query_section
    // :(SELECT ('*'| (output_attribute (',' output_attribute)* ))) group_by? having?
    // ;
    Selector selector = new Selector();
    List<OutputAttribute> attributeList = new ArrayList<OutputAttribute>(ctx.output_attribute().size());
    for (SiddhiQLParser.Output_attributeContext output_attributeContext : ctx.output_attribute()) {
        attributeList.add((OutputAttribute) visit(output_attributeContext));
    }
    selector.addSelectionList(attributeList);
    if (ctx.group_by() != null) {
        selector.addGroupByList((List<Variable>) visit(ctx.group_by()));
    }
    if (ctx.having() != null) {
        selector.having((Expression) visit(ctx.having()));
    }
    if (ctx.order_by() != null) {
        selector.addOrderByList((List<OrderByAttribute>) visit(ctx.order_by()));
    }
    if (ctx.limit() != null) {
        selector.limit((Constant) visit(ctx.limit()));
    }
    populateQueryContext(selector, ctx);
    return selector;
}
Also used : SiddhiQLParser(org.wso2.siddhi.query.compiler.SiddhiQLParser) Variable(org.wso2.siddhi.query.api.expression.Variable) ArrayList(java.util.ArrayList) OrderByAttribute(org.wso2.siddhi.query.api.execution.query.selection.OrderByAttribute) OutputAttribute(org.wso2.siddhi.query.api.execution.query.selection.OutputAttribute) BasicSelector(org.wso2.siddhi.query.api.execution.query.selection.BasicSelector) Selector(org.wso2.siddhi.query.api.execution.query.selection.Selector)

Aggregations

ArrayList (java.util.ArrayList)7 Variable (org.wso2.siddhi.query.api.expression.Variable)5 MetaStreamEvent (org.wso2.siddhi.core.event.stream.MetaStreamEvent)4 VariableExpressionExecutor (org.wso2.siddhi.core.executor.VariableExpressionExecutor)4 BasicSelector (org.wso2.siddhi.query.api.execution.query.selection.BasicSelector)4 OutputAttribute (org.wso2.siddhi.query.api.execution.query.selection.OutputAttribute)4 SiddhiQLParser (org.wso2.siddhi.query.compiler.SiddhiQLParser)4 ConstantExpressionExecutor (org.wso2.siddhi.core.executor.ConstantExpressionExecutor)3 ExpressionExecutor (org.wso2.siddhi.core.executor.ExpressionExecutor)3 QuerySelector (org.wso2.siddhi.core.query.selector.QuerySelector)3 AttributeProcessor (org.wso2.siddhi.core.query.selector.attribute.processor.AttributeProcessor)3 StoreQuery (org.wso2.siddhi.query.api.execution.query.StoreQuery)3 MetaStateEvent (org.wso2.siddhi.core.event.state.MetaStateEvent)2 ConditionExpressionExecutor (org.wso2.siddhi.core.executor.condition.ConditionExpressionExecutor)2 Attribute (org.wso2.siddhi.query.api.definition.Attribute)2 Query (org.wso2.siddhi.query.api.execution.query.Query)2 ReturnStream (org.wso2.siddhi.query.api.execution.query.output.stream.ReturnStream)2 Selector (org.wso2.siddhi.query.api.execution.query.selection.Selector)2 HashMap (java.util.HashMap)1 ReentrantLock (java.util.concurrent.locks.ReentrantLock)1