Examples of StreamTypeService


Examples of com.espertech.esper.epl.core.StreamTypeService

            if (streamsIdsPerStream[i] != i) {
                allStreamIdsMatch = false;
            }
        }

        StreamTypeService streamTypeService = validationContext.getStreamTypeService();
        StreamTypeServiceImpl copyTypes = new StreamTypeServiceImpl(eventTypes, streamNames, isIStreamOnly, streamTypeService.getEngineURIQualifier(), streamTypeService.isOnDemandStreams());
        copyTypes.setRequireStreamNames(true);

        // validate expression body in this context
        try {
            ExprValidationContext expressionBodyContext = new ExprValidationContext(copyTypes, validationContext);
            expressionBodyCopy = ExprNodeUtility.getValidatedSubtree(expressionBodyCopy, expressionBodyContext);
        }
        catch (ExprValidationException ex) {
            String message = "Error validating expression declaration '" + prototype.getName() + "': " + ex.getMessage();
            throw new ExprValidationException(message, ex);
        }

        // add child node
        this.addChildNode(expressionBodyCopy);

        // analyze child node
        ExprNodeSummaryVisitor summaryVisitor = new ExprNodeSummaryVisitor();
        expressionBodyCopy.accept(summaryVisitor);
        boolean isCache;
        if (summaryVisitor.isHasAggregation() || summaryVisitor.isHasPreviousPrior()) {
            isCache = false;
        }
        else {
            isCache = true;
        }

        // determine a suitable evaluation
        if (expressionBodyCopy.isConstantResult()) {
            // pre-evaluated
            exprEvaluator = new ExprDeclaredEvalConstant(expressionBodyCopy.getExprEvaluator().getType(), expressionBodyCopy.getExprEvaluator().evaluate(null, true, null));
        }
        else if (prototype.getParametersNames().isEmpty() ||
                (allStreamIdsMatch && prototype.getParametersNames().size() == streamTypeService.getEventTypes().length)) {
            exprEvaluator = new ExprDeclaredEvalNoRewrite(expressionBodyCopy.getExprEvaluator(), prototype, isCache);
        }
        else {
            exprEvaluator = new ExprDeclaredEvalRewrite(expressionBodyCopy.getExprEvaluator(), prototype, isCache, streamsIdsPerStream);
        }
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

                    }
                }
            }

            EventType[] outerEventTypes;
            StreamTypeService subselectTypeService;

            // Use the override provided by the subselect if applicable
            if (subselect.getFilterSubqueryStreamTypes() != null) {
                subselectTypeService = subselect.getFilterSubqueryStreamTypes();
                outerEventTypes = new EventType[subselectTypeService.getEventTypes().length - 1];
                System.arraycopy(subselectTypeService.getEventTypes(), 1, outerEventTypes, 0, subselectTypeService.getEventTypes().length - 1);
            }
            else {
                // Streams event types are the original stream types with the stream zero the subselect stream
                LinkedHashMap<String, Pair<EventType, String>> namesAndTypes = new LinkedHashMap<String, Pair<EventType, String>>();
                namesAndTypes.put(subexpressionStreamName, new Pair<EventType, String>(eventType, subselecteventTypeName));
                for (int i = 0; i < outerEventTypesSelect.length; i++)
                {
                    Pair<EventType, String> pair = new Pair<EventType, String>(outerEventTypesSelect[i], outerEventTypeNamees[i]);
                    namesAndTypes.put(outerStreamNames[i], pair);
                }
                subselectTypeService = new StreamTypeServiceImpl(namesAndTypes, services.getEngineURI(), true, true);
                outerEventTypes = outerEventTypesSelect;
            }
            ViewResourceDelegateUnverified viewResourceDelegateSubselect = new ViewResourceDelegateUnverified();

            // Validate select expression
            SelectClauseSpecCompiled selectClauseSpec = subselect.getStatementSpecCompiled().getSelectClauseSpec();
            AggregationServiceFactoryDesc aggregationServiceFactoryDesc = null;
            List<ExprNode> selectExpressions = new ArrayList<ExprNode>();
            List<String> assignedNames = new ArrayList<String>();
            boolean isWildcard = false;
            boolean isStreamWildcard = false;
            ExprEvaluator[] groupByEvaluators = null;
            boolean hasNonAggregatedProperties = false;

            if (selectClauseSpec.getSelectExprList().length > 0)
            {
                List<ExprAggregateNode> aggExprNodes = new LinkedList<ExprAggregateNode>();

                ExprEvaluatorContextStatement evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext);
                ExprValidationContext validationContext = new ExprValidationContext(subselectTypeService, statementContext.getMethodResolutionService(), viewResourceDelegateSubselect, statementContext.getSchedulingService(), statementContext.getVariableService(), evaluatorContextStmt, statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);
                for (int i = 0; i < selectClauseSpec.getSelectExprList().length; i++) {
                    SelectClauseElementCompiled element = selectClauseSpec.getSelectExprList()[i];

                    if (element instanceof SelectClauseExprCompiledSpec)
                    {
                        // validate
                        SelectClauseExprCompiledSpec compiled = (SelectClauseExprCompiledSpec) element;
                        ExprNode selectExpression = compiled.getSelectExpression();
                        selectExpression = ExprNodeUtility.getValidatedSubtree(selectExpression, validationContext);

                        selectExpressions.add(selectExpression);
                        if (compiled.getAssignedName() == null) {
                            assignedNames.add(selectExpression.toExpressionString());
                        }
                        else {
                            assignedNames.add(compiled.getAssignedName());
                        }

                        // handle aggregation
                        ExprAggregateNodeUtil.getAggregatesBottomUp(selectExpression, aggExprNodes);

                        if (aggExprNodes.size() > 0)
                        {
                            // This stream (stream 0) properties must either all be under aggregation, or all not be.
                            List<Pair<Integer, String>> propertiesNotAggregated = ExprNodeUtility.getExpressionProperties(selectExpression, false);
                            for (Pair<Integer, String> pair : propertiesNotAggregated)
                            {
                                if (pair.getFirst() == 0)
                                {
                                    throw new ExprValidationException("Subselect properties must all be within aggregation functions");
                                }
                            }
                        }
                    }
                    else if (element instanceof SelectClauseElementWildcard) {
                        isWildcard = true;
                    }
                    else if (element instanceof SelectClauseStreamCompiledSpec) {
                        isStreamWildcard = true;
                    }
                }   // end of for loop

                // Figure out all non-aggregated event properties in the select clause (props not under a sum/avg/max aggregation node)
                Set<Pair<Integer, String>> nonAggregatedPropsSelect = ExprNodeUtility.getNonAggregatedProps(validationContext.getStreamTypeService().getEventTypes(), selectExpressions, contextPropertyRegistry);
                hasNonAggregatedProperties = !nonAggregatedPropsSelect.isEmpty();

                // Validate and set select-clause names and expressions
                if (!selectExpressions.isEmpty()) {
                    if (isWildcard || isStreamWildcard) {
                        throw new ExprValidationException("Subquery multi-column select does not allow wildcard or stream wildcard when selecting multiple columns.");
                    }
                    if (selectExpressions.size() > 1 && !subselect.isAllowMultiColumnSelect()) {
                        throw new ExprValidationException("Subquery multi-column select is not allowed in this context.");
                    }
                    if (statementSpec.getGroupByExpressions().length == 0 && selectExpressions.size() > 1 &&
                        aggExprNodes.size() > 0 && hasNonAggregatedProperties) {
                        throw new ExprValidationException("Subquery with multi-column select requires that either all or none of the selected columns are under aggregation, unless a group-by clause is also specified");
                    }
                    subselect.setSelectClause(selectExpressions.toArray(new ExprNode[selectExpressions.size()]));
                    subselect.setSelectAsNames(assignedNames.toArray(new String[assignedNames.size()]));
                }

                // Handle aggregation
                if (aggExprNodes.size() > 0)
                {
                    boolean hasGroupBy = statementSpec.getGroupByExpressions() != null && statementSpec.getGroupByExpressions().length > 0;
                    if (hasGroupBy) {
                        ExprNode[] groupByNodes = statementSpec.getGroupByExpressions();
                        groupByEvaluators = new ExprEvaluator[groupByNodes.length];

                        // validate group-by
                        for (int i = 0; i < groupByNodes.length; i++) {
                            groupByNodes[i] = ExprNodeUtility.getValidatedSubtree(groupByNodes[i], validationContext);
                            groupByEvaluators[i] = groupByNodes[i].getExprEvaluator();
                            String minimal = ExprNodeUtility.isMinimalExpression(groupByNodes[i]);
                            if (minimal != null) {
                                throw new ExprValidationException("Group-by expressions in a subselect may not have " + minimal);
                            }
                        }

                        // Get a list of event properties being aggregated in the select clause, if any
                        Set<Pair<Integer, String>> propertiesGroupBy = ExprNodeUtility.getGroupByPropertiesValidateHasOne(groupByNodes);

                        // Validated all group-by properties come from stream itself
                        for (Pair<Integer, String> pair : propertiesGroupBy) {
                            if (pair.getFirst() == null || pair.getFirst() != 0) {
                                throw new ExprValidationException("Subselect with group-by requires that group-by properties are provided by the subselect stream only ('" + pair.getSecond() + "' is not)");
                            }
                        }

                        // Validate that this is a grouped full-aggregated case
                        boolean allInGroupBy = true;
                        for (Pair<Integer, String> nonAggregatedProp : nonAggregatedPropsSelect) {
                            if (!propertiesGroupBy.contains(nonAggregatedProp)) {
                                allInGroupBy = false;
                            }
                        }
                        if (!allInGroupBy) {
                            throw new ExprValidationException("Subselect with group-by requires non-aggregated properties in the select-clause to also appear in the group-by clause");
                        }
                    }

                    // Other stream properties, if there is aggregation, cannot be under aggregation.
                    for (ExprAggregateNode aggNode : aggExprNodes) {
                        List<Pair<Integer, String>> propertiesNodesAggregated = ExprNodeUtility.getExpressionProperties(aggNode, true);
                        for (Pair<Integer, String> pair : propertiesNodesAggregated) {
                            if (pair.getFirst() != 0) {
                                throw new ExprValidationException("Subselect aggregation functions cannot aggregate across correlated properties");
                            }
                        }
                    }

                    // determine whether select-clause has grouped-by expressions
                    List<ExprAggregateNodeGroupKey> groupKeyExpressions = null;
                    if (hasGroupBy) {
                        ExprNode[] groupByExpressions = statementSpec.getGroupByExpressions();
                        for (int i = 0; i < selectExpressions.size(); i++) {
                            ExprNode selectExpression = selectExpressions.get(i);
                            boolean revalidate = false;
                            for (int j = 0; j < groupByExpressions.length; j++) {
                                List<Pair<ExprNode, ExprNode>> foundPairs = ExprNodeUtility.findExpression(selectExpression, groupByExpressions[j]);
                                for (Pair<ExprNode, ExprNode> pair : foundPairs) {
                                    ExprAggregateNodeGroupKey replacement = new ExprAggregateNodeGroupKey(j, groupByEvaluators[j].getType());
                                    if (pair.getFirst() == null) {
                                        selectExpressions.set(i, replacement);
                                    }
                                    else {
                                        ExprNodeUtility.replaceChildNode(pair.getFirst(), pair.getSecond(), replacement);
                                        revalidate = true;
                                    }
                                    if (groupKeyExpressions == null) {
                                        groupKeyExpressions = new ArrayList<ExprAggregateNodeGroupKey>();
                                    }
                                    groupKeyExpressions.add(replacement);
                                }
                            }

                            // if the select-clause expression changed, revalidate it
                            if (revalidate) {
                                selectExpression = ExprNodeUtility.getValidatedSubtree(selectExpression, validationContext);
                                selectExpressions.set(i, selectExpression);
                            }
                        }   // end of for loop
                    }

                    List<ExprAggregateNode> havingAgg = Collections.emptyList();
                    List<ExprAggregateNode> orderByAgg = Collections.emptyList();
                    aggregationServiceFactoryDesc = AggregationServiceFactoryFactory.getService(aggExprNodes, statementSpec.getGroupByExpressions(), havingAgg, orderByAgg, groupKeyExpressions, hasGroupBy, evaluatorContextStmt, annotations, statementContext.getVariableService(), false, true, statementSpec.getFilterRootNode(), statementSpec.getHavingExprRootNode(), statementContext.getAggregationServiceFactoryService(), subselectTypeService.getEventTypes(), statementContext.getMethodResolutionService());

                    // assign select-clause
                    if (!selectExpressions.isEmpty()) {
                        subselect.setSelectClause(selectExpressions.toArray(new ExprNode[selectExpressions.size()]));
                        subselect.setSelectAsNames(assignedNames.toArray(new String[assignedNames.size()]));
                    }
                }
            }

            // no aggregation functions allowed in filter
            if (statementSpec.getFilterRootNode() != null)
            {
                List<ExprAggregateNode> aggExprNodesFilter = new LinkedList<ExprAggregateNode>();
                ExprAggregateNodeUtil.getAggregatesBottomUp(statementSpec.getFilterRootNode(), aggExprNodesFilter);
                if (aggExprNodesFilter.size() > 0)
                {
                    throw new ExprValidationException("Aggregation functions are not supported within subquery filters, consider using insert-into instead");
                }
            }

            // Validate filter expression, if there is one
            ExprNode filterExpr = statementSpec.getFilterRootNode();
            boolean correlatedSubquery = false;
            if (filterExpr != null)
            {
                ExprEvaluatorContextStatement evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext);
                ExprValidationContext validationContext = new ExprValidationContext(subselectTypeService, statementContext.getMethodResolutionService(), viewResourceDelegateSubselect, statementContext.getSchedulingService(), statementContext.getVariableService(), evaluatorContextStmt, statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);
                filterExpr = ExprNodeUtility.getValidatedSubtree(filterExpr, validationContext);
                if (JavaClassHelper.getBoxedType(filterExpr.getExprEvaluator().getType()) != Boolean.class)
                {
                    throw new ExprValidationException("Subselect filter expression must return a boolean value");
                }

                // check the presence of a correlated filter, not allowed with aggregation
                ExprNodeIdentifierVisitor visitor = new ExprNodeIdentifierVisitor(true);
                filterExpr.accept(visitor);
                List<Pair<Integer, String>> propertiesNodes = visitor.getExprProperties();
                for (Pair<Integer, String> pair : propertiesNodes)
                {
                    if (pair.getFirst() != 0)
                    {
                        correlatedSubquery = true;
                        break;
                    }
                }
            }

            ViewResourceDelegateVerified viewResourceDelegateVerified = EPStatementStartMethodHelperViewResources.verifyPreviousAndPriorRequirements(new ViewFactoryChain[]{viewFactoryChain}, viewResourceDelegateSubselect);
            List<ExprPriorNode> priorNodes = viewResourceDelegateVerified.getPerStream()[0].getPriorRequestsAsList();
            List<ExprPreviousNode> previousNodes = viewResourceDelegateVerified.getPerStream()[0].getPreviousRequests();

            // Set the aggregated flag
            // This must occur here as some analysis of return type depends on aggregated or not.
            if (aggregationServiceFactoryDesc == null) {
                subselect.setSubselectAggregationType(ExprSubselectNode.SubqueryAggregationType.NONE);
            }
            else {
                subselect.setSubselectAggregationType(hasNonAggregatedProperties ? ExprSubselectNode.SubqueryAggregationType.AGGREGATED : ExprSubselectNode.SubqueryAggregationType.FULLY_AGGREGATED);
            }

            // Set the filter.
            ExprEvaluator filterExprEval = (filterExpr == null) ? null : filterExpr.getExprEvaluator();
            ExprEvaluator assignedFilterExpr = aggregationServiceFactoryDesc != null ? null : filterExprEval;
            subselect.setFilterExpr(assignedFilterExpr);

            // validation for correlated subqueries against named windows contained-event syntax
            if ((filterStreamSpec instanceof NamedWindowConsumerStreamSpec && correlatedSubquery)) {
                NamedWindowConsumerStreamSpec namedSpec = (NamedWindowConsumerStreamSpec) filterStreamSpec;
                if (namedSpec.getOptPropertyEvaluator() != null) {
                    throw new ExprValidationException("Failed to validate named window use in subquery, contained-event is only allowed for named windows when not correlated");
                }
            }

            // Determine strategy factories
            //
            // handle named window index share first
            if (filterStreamSpec instanceof NamedWindowConsumerStreamSpec) {
                NamedWindowConsumerStreamSpec namedSpec = (NamedWindowConsumerStreamSpec) filterStreamSpec;
                if (namedSpec.getFilterExpressions().isEmpty()) {
                    NamedWindowProcessor processor = services.getNamedWindowService().getProcessor(namedSpec.getWindowName());
                    if (processor == null) {
                        throw new ExprValidationException("A named window by name '" + namedSpec.getWindowName() + "' does not exist");
                    }

                    boolean disableIndexShare = HintEnum.DISABLE_WINDOW_SUBQUERY_INDEXSHARE.getHint(annotations) != null;
                    if (disableIndexShare && processor.isVirtualDataWindow()) {
                        disableIndexShare = false;
                    }

                    if (!disableIndexShare && processor.isEnableSubqueryIndexShare()) {
                        String contextName = statementContext.getContextDescriptor() == null ? null :
                                statementContext.getContextDescriptor().getContextName();
                        String msg = processor.validateContextAssociation(contextName);
                        if (msg != null) {
                            throw new ExprValidationException(msg);
                        }
                        if (queryPlanLogging && queryPlanLog.isInfoEnabled()) {
                            queryPlanLog.info("prefering shared index");
                        }
                        boolean fullTableScan = HintEnum.SET_NOINDEX.getHint(annotations) != null;
                        SubordPropPlan joinedPropPlan = QueryPlanIndexBuilder.getJoinProps(filterExpr, outerEventTypes.length, subselectTypeService.getEventTypes());
                        SubSelectStrategyFactory factory = new SubSelectStrategyFactoryNamedWinIndexShare(subqueryNum, outerEventTypesSelect,
                                processor, fullTableScan, indexHint, joinedPropPlan, filterExprEval, aggregationServiceFactoryDesc, groupByEvaluators);
                        SubSelectStrategyFactoryDesc factoryDesc = new SubSelectStrategyFactoryDesc(subSelectActivation, factory, aggregationServiceFactoryDesc, priorNodes, previousNodes);
                        collection.add(subselect, factoryDesc);
                        continue;
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

        {
            // Validate where clause, initializing nodes to the stream ids used
            try
            {
                EventType outputLimitType = OutputConditionExpressionFactory.getBuiltInEventType(statementContext.getEventAdapterService());
                StreamTypeService typeServiceOutputWhen = new StreamTypeServiceImpl(new EventType[] {outputLimitType}, new String[]{null}, new boolean[] {true}, statementContext.getEngineURI(), false);
                ExprValidationContext validationContext = new ExprValidationContext(typeServiceOutputWhen, methodResolutionService, null, statementContext.getSchedulingService(), statementContext.getVariableService(), evaluatorContextStmt, statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);

                ExprNode outputLimitWhenNode = statementSpec.getOutputLimitSpec().getWhenExpressionNode();
                if (outputLimitWhenNode != null) {
                    outputLimitWhenNode = ExprNodeUtility.getValidatedSubtree(outputLimitWhenNode, validationContext);
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

                        arrayCompositeEventTypes.put(tag, pair);
                    }
                }
            }

            StreamTypeService streamTypeService = new StreamTypeServiceImpl(filterTypes, context.getEngineURI(), true, false);
            List<ExprNode> exprNodes = filterNode.getRawFilterSpec().getFilterExpressions();

            FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(resolvedEventType, eventName, exprNodes,
                    filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(),  filterTaggedEventTypes, arrayCompositeEventTypes, streamTypeService,
                   null, context, subexpressionIdStack);
            filterNode.setFilterSpec(spec);
        }
        else if (evalNode instanceof EvalObserverFactoryNode)
        {
            EvalObserverFactoryNode observerNode = (EvalObserverFactoryNode) evalNode;
            try
            {
                ObserverFactory observerFactory = context.getPatternResolutionService().create(observerNode.getPatternObserverSpec());

                StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "observer");
                ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor(), false);
                List<ExprNode> validated = validateExpressions(observerNode.getPatternObserverSpec().getObjectParameters(), validationContext);

                MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

                observerNode.setObserverFactory(observerFactory);
                observerFactory.setObserverParameters(validated, convertor);
            }
            catch (ObserverParameterException e)
            {
                throw new ExprValidationException("Invalid parameter for pattern observer: " + e.getMessage(), e);
            }
            catch (PatternObjectException e)
            {
                throw new ExprValidationException("Failed to resolve pattern observer: " + e.getMessage(), e);
            }
        }
        else if (evalNode instanceof EvalGuardFactoryNode)
        {
            EvalGuardFactoryNode guardNode = (EvalGuardFactoryNode) evalNode;
            try
            {
                GuardFactory guardFactory = context.getPatternResolutionService().create(guardNode.getPatternGuardSpec());

                StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "guard");
                ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor(), false);
                List<ExprNode> validated = validateExpressions(guardNode.getPatternGuardSpec().getObjectParameters(), validationContext);

                MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

                guardNode.setGuardFactory(guardFactory);
                guardFactory.setGuardParameters(validated, convertor);
            }
            catch (GuardParameterException e)
            {
                throw new ExprValidationException("Invalid parameter for pattern guard: " + e.getMessage(), e);
            }
            catch (PatternObjectException e)
            {
                throw new ExprValidationException("Failed to resolve pattern guard: " + e.getMessage(), e);
            }
        }
        else if (evalNode instanceof EvalEveryDistinctFactoryNode)
        {
            EvalEveryDistinctFactoryNode distinctNode = (EvalEveryDistinctFactoryNode) evalNode;
            MatchEventSpec matchEventFromChildNodes = analyzeMatchEvent(distinctNode);
            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), subexpressionIdStack, "every-distinct");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor(), false);
            List<ExprNode> validated;
            try
            {
                validated = validateExpressions(distinctNode.getExpressions(), validationContext);
            }
            catch (ExprValidationPropertyException ex)
            {
                throw new ExprValidationPropertyException(ex.getMessage() + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct", ex.getCause());
            }

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());

            distinctNode.setConvertor(convertor);

            // Determine whether some expressions are constants or time period
            List<ExprNode> distinctExpressions = new ArrayList<ExprNode>();
            Long msecToExpire = null;
            ExprNode expiryTimeExp = null;
            int count = -1;
            int last = validated.size() - 1;
            for (ExprNode expr : validated) {
                count++;
                if (count == last && expr instanceof ExprTimePeriod) {
                    Double secondsExpire = (Double) ((ExprTimePeriod) expr).evaluate(null, true, evaluatorContext);
                    if ((secondsExpire != null) && (secondsExpire > 0)) {
                        msecToExpire = Math.round(1000d * secondsExpire);
                        expiryTimeExp = expr;
                    }
                    log.debug("Setting every-distinct msec-to-expire to " + msecToExpire);
                }
                else if (expr.isConstantResult()) {
                    if (count == last) {
                        Object value = expr.getExprEvaluator().evaluate(null, true, evaluatorContext);
                        if (!(value instanceof Number)) {
                            throw new ExprValidationException("Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                        }
                        Double secondsExpire = ((Number) expr.getExprEvaluator().evaluate(null, true, evaluatorContext)).doubleValue();
                        if ((secondsExpire != null) && (secondsExpire > 0)) {
                            msecToExpire = Math.round(1000d * secondsExpire);
                            expiryTimeExp = expr;
                        }
                        log.debug("Setting every-distinct msec-to-expire to " + msecToExpire);
                    }
                    else {
                        log.warn("Every-distinct node utilizes an expression returning a constant value, please check expression '" + expr.toExpressionString() + "', not adding expression to distinct-value expression list");
                    }
                }
                else {
                    distinctExpressions.add(expr);
                }
            }
            if (distinctExpressions.isEmpty()) {
                throw new ExprValidationException("Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
            }
            distinctNode.setDistinctExpressions(distinctExpressions, msecToExpire, expiryTimeExp);
        }
        else if (evalNode instanceof EvalMatchUntilFactoryNode)
        {
            EvalMatchUntilFactoryNode matchUntilNode = (EvalMatchUntilFactoryNode) evalNode;

            // compile bounds expressions, if any
            MatchEventSpec untilMatchEventSpec = new MatchEventSpec(tags.getTaggedEventTypes(), tags.getArrayEventTypes());
            StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), subexpressionIdStack, "until");
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor(), false);

            ExprNode lower = validateBounds(matchUntilNode.getLowerBounds(), validationContext);
            matchUntilNode.setLowerBounds(lower);

            ExprNode upper = validateBounds(matchUntilNode.getUpperBounds(), validationContext);
            matchUntilNode.setUpperBounds(upper);

            ExprNode single = validateBounds(matchUntilNode.getSingleBound(), validationContext);
            matchUntilNode.setSingleBound(single);

            MatchedEventConvertor convertor = new MatchedEventConvertorImpl(untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService());
            matchUntilNode.setConvertor(convertor);

            // compile new tag lists
            Set<String> arrayTags = null;
            EvalNodeAnalysisResult matchUntilAnalysisResult = EvalNodeUtil.recursiveAnalyzeChildNodes(matchUntilNode.getChildNodes().get(0));
            for (EvalFilterFactoryNode filterNode : matchUntilAnalysisResult.getFilterNodes())
            {
                String optionalTag = filterNode.getEventAsName();
                if (optionalTag != null)
                {
                    if (arrayTags == null)
                    {
                        arrayTags = new HashSet<String>();
                    }
                    arrayTags.add(optionalTag);
                }
            }

            if (arrayTags != null)
            {
                for (String arrayTag : arrayTags)
                {
                    if (!tags.getArrayEventTypes().containsKey(arrayTag))
                    {
                        tags.getArrayEventTypes().put(arrayTag, tags.getTaggedEventTypes().get(arrayTag));
                        tags.getTaggedEventTypes().remove(arrayTag);
                    }
                }
            }
            matchUntilNode.setTagsArrayedSet(getIndexesForTags(allTagNamesOrdered, arrayTags));
        }
        else if (evalNode instanceof EvalFollowedByFactoryNode)
        {
            EvalFollowedByFactoryNode followedByNode = (EvalFollowedByFactoryNode) evalNode;
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.getEngineURI(), false);
            ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor(), false);

            if (followedByNode.getOptionalMaxExpressions() != null) {
                List<ExprNode> validated = new ArrayList<ExprNode>();
                for (ExprNode maxExpr : followedByNode.getOptionalMaxExpressions()) {
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

        }
        // variable assignments
        else if (statementSpec.getOnTriggerDesc() instanceof OnTriggerSetDesc)
        {
            OnTriggerSetDesc desc = (OnTriggerSetDesc) statementSpec.getOnTriggerDesc();
            StreamTypeService typeService = new StreamTypeServiceImpl(new EventType[] {activatorResultEventType}, new String[] {streamSpec.getOptionalStreamName()}, new boolean[] {true}, services.getEngineURI(), false);
            ExprValidationContext validationContext = new ExprValidationContext(typeService, statementContext.getMethodResolutionService(), null, statementContext.getSchedulingService(), statementContext.getVariableService(), getDefaultAgentInstanceContext(statementContext), statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);

            // Materialize sub-select views
            subSelectStrategyCollection = EPStatementStartMethodHelperSubselect.planSubSelect(services, statementContext, isQueryPlanLogging(services), subSelectStreamDesc, new String[]{streamSpec.getOptionalStreamName()}, new EventType[]{activatorResultEventType}, new String[]{triggereventTypeName}, stopCallbacks, statementSpec.getAnnotations(), statementSpec.getDeclaredExpressions(), contextPropertyRegistry);

            for (OnTriggerSetAssignment assignment : desc.getAssignments()) {
                ExprNode validated = ExprNodeUtility.getValidatedAssignment(assignment, validationContext);
                assignment.setExpression(validated);
            }

            try {
                ExprEvaluatorContextStatement exprEvaluatorContext = new ExprEvaluatorContextStatement(statementContext);
                onSetVariableViewFactory = new OnSetVariableViewFactory(statementContext.getStatementId(), desc, statementContext.getEventAdapterService(), statementContext.getVariableService(), statementContext.getStatementResultService(), exprEvaluatorContext);
            }
            catch (VariableValueException ex) {
                throw new ExprValidationException("Error in variable assignment: " + ex.getMessage(), ex);
            }

            outputEventType = onSetVariableViewFactory.getEventType();
        }
        // split-stream use case
        else
        {
            OnTriggerSplitStreamDesc desc = (OnTriggerSplitStreamDesc) statementSpec.getOnTriggerDesc();
            String streamName = streamSpec.getOptionalStreamName();
            if (streamName == null)
            {
                streamName = "stream_0";
            }
            StreamTypeService typeService = new StreamTypeServiceImpl(new EventType[] {activatorResultEventType}, new String[] {streamName}, new boolean[] {true}, services.getEngineURI(), false);
            if (statementSpec.getInsertIntoDesc() == null)
            {
                throw new ExprValidationException("Required insert-into clause is not provided, the clause is required for split-stream syntax");
            }
            if ((statementSpec.getGroupByExpressions().length > 0) || (statementSpec.getHavingExprRootNode() != null) || (statementSpec.getOrderByList().length > 0))
            {
                throw new ExprValidationException("A group-by clause, having-clause or order-by clause is not allowed for the split stream syntax");
            }

            // Materialize sub-select views
            subSelectStrategyCollection = EPStatementStartMethodHelperSubselect.planSubSelect(services, statementContext, isQueryPlanLogging(services), subSelectStreamDesc, new String[]{streamSpec.getOptionalStreamName()}, new EventType[]{activatorResultEventType}, new String[]{triggereventTypeName}, stopCallbacks, statementSpec.getAnnotations(), statementSpec.getDeclaredExpressions(), contextPropertyRegistry);

            EPStatementStartMethodHelperValidate.validateNodes(statementSpec, statementContext, typeService, null);

            ResultSetProcessorFactoryDesc[] processorFactories = new ResultSetProcessorFactoryDesc[desc.getSplitStreams().size() + 1];
            ExprNode[] whereClauses = new ExprNode[desc.getSplitStreams().size() + 1];
            processorFactories[0] = ResultSetProcessorFactoryFactory.getProcessorPrototype(
                    statementSpec, statementContext, typeService, null, new boolean[0], false, contextPropertyRegistry, null);
            whereClauses[0] = statementSpec.getFilterRootNode();
            boolean[] isNamedWindowInsert = new boolean[desc.getSplitStreams().size() + 1];
            isNamedWindowInsert[0] = false;

            int index = 1;
            for (OnTriggerSplitStream splits : desc.getSplitStreams())
            {
                StatementSpecCompiled splitSpec = new StatementSpecCompiled();
                splitSpec.setInsertIntoDesc(splits.getInsertInto());
                splitSpec.setSelectClauseSpec(StatementLifecycleSvcImpl.compileSelectAllowSubselect(splits.getSelectClause()));
                splitSpec.setFilterExprRootNode(splits.getWhereClause());
                EPStatementStartMethodHelperValidate.validateNodes(splitSpec, statementContext, typeService, null);

                processorFactories[index] = ResultSetProcessorFactoryFactory.getProcessorPrototype(
                        splitSpec, statementContext, typeService, null, new boolean[0], false, contextPropertyRegistry, null);
                whereClauses[index] = splitSpec.getFilterRootNode();
                isNamedWindowInsert[index] = statementContext.getNamedWindowService().isNamedWindow(splits.getInsertInto().getEventTypeName());

                index++;
            }

            splitDesc = new StatementAgentInstanceFactoryOnTriggerSplitDesc(processorFactories, whereClauses, isNamedWindowInsert);
        }

        // For on-delete/set/update/merge, create an output processor that passes on as a wildcard the underlying event
        if ((statementSpec.getOnTriggerDesc().getOnTriggerType() == OnTriggerType.ON_DELETE) ||
            (statementSpec.getOnTriggerDesc().getOnTriggerType() == OnTriggerType.ON_SET) ||
            (statementSpec.getOnTriggerDesc().getOnTriggerType() == OnTriggerType.ON_UPDATE) ||
            (statementSpec.getOnTriggerDesc().getOnTriggerType() == OnTriggerType.ON_MERGE))
        {
            StatementSpecCompiled defaultSelectAllSpec = new StatementSpecCompiled();
            defaultSelectAllSpec.getSelectClauseSpec().setSelectExprList(new SelectClauseElementWildcard());

            StreamTypeService streamTypeService = new StreamTypeServiceImpl(new EventType[] {outputEventType}, new String[] {"trigger_stream"}, new boolean[] {true}, services.getEngineURI(), false);
            outputResultSetProcessorPrototype = ResultSetProcessorFactoryFactory.getProcessorPrototype(defaultSelectAllSpec, statementContext, streamTypeService, null, new boolean[0], true, contextPropertyRegistry, null);
        }

        EventType resultEventType = resultSetProcessorPrototype == null ? null : resultSetProcessorPrototype.getResultSetProcessorFactory().getResultEventType();
        OutputProcessViewFactory outputViewFactory = OutputProcessViewFactoryFactory.make(statementSpec, services.getInternalEventRouter(), statementContext, resultEventType, null);
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

        for (OnTriggerMergeMatched matchedItem : mergeDesc.getItems()) {

            EventType dummyTypeNoProperties = new MapEventType(EventTypeMetadata.createAnonymous("merge_named_window_insert"), "merge_named_window_insert", 0, null, Collections.<String, Object>emptyMap(), null, null, null);
            StreamTypeServiceImpl twoStreamTypeSvc = new StreamTypeServiceImpl(new EventType[] {namedWindowType, triggerStreamType},
                    new String[] {namedWindowName, triggerStreamName}, new boolean[] {true, true}, statementContext.getEngineURI(), true);
            StreamTypeService insertOnlyTypeSvc = new StreamTypeServiceImpl(new EventType[] {dummyTypeNoProperties, triggerStreamType},
                    new String[] {UuidGenerator.generate(), triggerStreamName}, new boolean[] {true, true}, statementContext.getEngineURI(), true);

            // we may provide an additional stream "initial" for the prior value, unless already defined
            StreamTypeServiceImpl assignmentStreamTypeSvc;
            if (namedWindowName.equals(INITIAL_VALUE_STREAM_NAME) || triggerStreamName.equals(INITIAL_VALUE_STREAM_NAME)) {
                assignmentStreamTypeSvc = twoStreamTypeSvc;
            }
            else {
                assignmentStreamTypeSvc = new StreamTypeServiceImpl(new EventType[] {namedWindowType, triggerStreamType, namedWindowType},
                        new String[] {namedWindowName, triggerStreamName, INITIAL_VALUE_STREAM_NAME}, new boolean[] {true, true, true}, statementContext.getEngineURI(), false);
                assignmentStreamTypeSvc.setStreamZeroUnambigous(true);
            }

            if (matchedItem.getOptionalMatchCond() != null) {
                StreamTypeService matchValidStreams = matchedItem.isMatchedUnmatched() ? twoStreamTypeSvc : insertOnlyTypeSvc;
                matchedItem.setOptionalMatchCond(EPStatementStartMethodHelperValidate.validateExprNoAgg(matchedItem.getOptionalMatchCond(), matchValidStreams, statementContext, evaluatorContextStmt, exprNodeErrorMessage));
                if (!matchedItem.isMatchedUnmatched()) {
                    EPStatementStartMethodHelperValidate.validateSubqueryExcludeOuterStream(matchedItem.getOptionalMatchCond());
                }
            }

            for (OnTriggerMergeAction item : matchedItem.getActions()) {
                if (item instanceof OnTriggerMergeActionDelete) {
                    OnTriggerMergeActionDelete delete = (OnTriggerMergeActionDelete) item;
                    if (delete.getOptionalWhereClause() != null) {
                        delete.setOptionalWhereClause(EPStatementStartMethodHelperValidate.validateExprNoAgg(delete.getOptionalWhereClause(), twoStreamTypeSvc, statementContext, evaluatorContextStmt, exprNodeErrorMessage));
                    }
                }
                else if (item instanceof OnTriggerMergeActionUpdate) {
                    OnTriggerMergeActionUpdate update = (OnTriggerMergeActionUpdate) item;
                    if (update.getOptionalWhereClause() != null) {
                        update.setOptionalWhereClause(EPStatementStartMethodHelperValidate.validateExprNoAgg(update.getOptionalWhereClause(), twoStreamTypeSvc, statementContext, evaluatorContextStmt, exprNodeErrorMessage));
                    }
                    for (OnTriggerSetAssignment assignment : update.getAssignments())
                    {
                        assignment.setExpression(EPStatementStartMethodHelperValidate.validateExprNoAgg(assignment.getExpression(), assignmentStreamTypeSvc, statementContext, evaluatorContextStmt, exprNodeErrorMessage));
                    }
                }
                else if (item instanceof OnTriggerMergeActionInsert) {
                    OnTriggerMergeActionInsert insert = (OnTriggerMergeActionInsert) item;

                    StreamTypeService insertTypeSvc;
                    if (insert.getOptionalStreamName() == null || insert.getOptionalStreamName().equals(namedWindowName)) {
                        insertTypeSvc = insertOnlyTypeSvc;
                    }
                    else {
                        insertTypeSvc = twoStreamTypeSvc;
                    }

                    List<SelectClauseElementCompiled> compiledSelect = new ArrayList<SelectClauseElementCompiled>();
                    if (insert.getOptionalWhereClause() != null) {
                        insert.setOptionalWhereClause(EPStatementStartMethodHelperValidate.validateExprNoAgg(insert.getOptionalWhereClause(), insertTypeSvc, statementContext, evaluatorContextStmt, exprNodeErrorMessage));
                    }
                    int colIndex = 0;
                    for (SelectClauseElementRaw raw : insert.getSelectClause())
                    {
                        if (raw instanceof SelectClauseStreamRawSpec)
                        {
                            SelectClauseStreamRawSpec rawStreamSpec = (SelectClauseStreamRawSpec) raw;
                            Integer foundStreamNum = null;
                            for (int s = 0; s < insertTypeSvc.getStreamNames().length; s++) {
                                if (rawStreamSpec.getStreamName().equals(insertTypeSvc.getStreamNames()[s])) {
                                    foundStreamNum = s;
                                    break;
                                }
                            }
                            if (foundStreamNum == null) {
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

        }

        LinkedHashMap<String, Pair<EventType, String>> namesAndTypes = new LinkedHashMap<String, Pair<EventType, String>>();
        namesAndTypes.put(namedWindowStreamName, new Pair<EventType, String>(namedWindowType, namedWindowName));
        namesAndTypes.put(filterStreamName, new Pair<EventType, String>(filteredType, filteredTypeName));
        StreamTypeService typeService = new StreamTypeServiceImpl(namesAndTypes, engineURI, false, false);

        ExprEvaluatorContextStatement evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext);
        ExprValidationContext validationContext = new ExprValidationContext(typeService, statementContext.getMethodResolutionService(), null, statementContext.getSchedulingService(), statementContext.getVariableService(), evaluatorContextStmt, statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);
        return ExprNodeUtility.getValidatedSubtree(deleteJoinExpr, validationContext);
    }
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

        // Could be a named window
        if (context.getNamedWindowService().isNamedWindow(eventName))
        {
            EventType namedWindowType = context.getNamedWindowService().getProcessor(eventName).getTailView().getEventType();
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(new EventType[] {namedWindowType}, new String[] {"s0"}, new boolean[] {true}, context.getEngineURI(), false);

            List<ExprNode> validatedNodes = FilterSpecCompiler.validateAllowSubquery(rawFilterSpec.getFilterExpressions(), streamTypeService, context, null, null);

            PropertyEvaluator optionalPropertyEvaluator = null;
            if (rawFilterSpec.getOptionalPropertyEvalSpec() != null) {
                optionalPropertyEvaluator = PropertyEvaluatorFactory.makeEvaluator(rawFilterSpec.getOptionalPropertyEvalSpec(), namedWindowType, this.getOptionalStreamName(), context.getEventAdapterService(), context.getMethodResolutionService(), context.getTimeProvider(), context.getVariableService(), context.getEngineURI(), context.getStatementId(), context.getStatementName(), context.getAnnotations(), assignedTypeNumberStack, context.getConfigSnapshot(), context.getNamedWindowService());
            }
            eventTypeReferences.add(((EventTypeSPI) namedWindowType).getMetadata().getPrimaryName());
            return new NamedWindowConsumerStreamSpec(eventName, this.getOptionalStreamName(), this.getViewSpecs(), validatedNodes, this.getOptions(), optionalPropertyEvaluator);
        }

        EventType eventType = null;

        if (context.getValueAddEventService().isRevisionTypeName(eventName))
        {
            eventType = context.getValueAddEventService().getValueAddUnderlyingType(eventName);
            eventTypeReferences.add(((EventTypeSPI) eventType).getMetadata().getPrimaryName());
        }

        if (eventType == null)
        {
            eventType = resolveType(context.getEngineURI(), eventName, context.getEventAdapterService(), context.getPlugInTypeResolutionURIs());
            if (eventType instanceof EventTypeSPI) {
                eventTypeReferences.add(((EventTypeSPI) eventType).getMetadata().getPrimaryName());
            }
        }

        // Validate all nodes, make sure each returns a boolean and types are good;
        // Also decompose all AND super nodes into individual expressions
        StreamTypeService streamTypeService = new StreamTypeServiceImpl(new EventType[] {eventType}, new String[] {super.getOptionalStreamName()}, new boolean[] {true}, context.getEngineURI(), false);

        FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(eventType, eventName, rawFilterSpec.getFilterExpressions(), rawFilterSpec.getOptionalPropertyEvalSpec(),
                null, null,  // no tags
                streamTypeService, this.getOptionalStreamName(), context, assignedTypeNumberStack);
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

                        String checkMinimal = ExprNodeUtility.isMinimalExpression(insertIntoFilter);
                        if (checkMinimal != null)
                        {
                            throw new ExprValidationException("Create window where-clause may not have " + checkMinimal);
                        }
                        StreamTypeService streamTypeService = new StreamTypeServiceImpl(selectFromType, selectFromTypeName, true, statementContext.getEngineURI());
                        ExprEvaluatorContextStatement evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext);
                        ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, statementContext.getMethodResolutionService(), null, statementContext.getSchedulingService(), statementContext.getVariableService(), evaluatorContextStmt, statementContext.getEventAdapterService(), statementContext.getStatementName(), statementContext.getStatementId(), statementContext.getAnnotations(), statementContext.getContextDescriptor(), false);
                        ExprNode insertFilter = ExprNodeUtility.getValidatedSubtree(spec.getCreateWindowDesc().getInsertFilter(), validationContext);
                        spec.getCreateWindowDesc().setInsertFilter(insertFilter);
                    }
View Full Code Here

Examples of com.espertech.esper.epl.core.StreamTypeService

    }

    private static List<NamedWindowSelectedProps> compileLimitedSelect(SelectClauseSpecRaw spec, String eplStatement, EventType singleType, String selectFromTypeName, String engineURI, ExprEvaluatorContext exprEvaluatorContext, MethodResolutionService methodResolutionService, EventAdapterService eventAdapterService, String statementName, String statementId, Annotation[] annotations)
    {
        List<NamedWindowSelectedProps> selectProps = new LinkedList<NamedWindowSelectedProps>();
        StreamTypeService streams = new StreamTypeServiceImpl(new EventType[] {singleType}, new String[] {"stream_0"}, new boolean[] {false}, engineURI, false);

        ExprValidationContext validationContext = new ExprValidationContext(streams, methodResolutionService, null, null, null, exprEvaluatorContext, eventAdapterService, statementName, statementId, annotations, null, false);
        for (SelectClauseElementRaw raw : spec.getSelectExprList())
        {
            if (!(raw instanceof SelectClauseExprRawSpec))
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.