public StreamSpecCompiled Compile(StatementContext context, ICollection <String> eventTypeReferences, bool isInsertInto, ICollection <int> assignedTypeNumberStack, bool isJoin, bool isContextDeclaration, bool isOnTrigger, String optionalStreamName) { StreamTypeService streamTypeService; // Determine the event type var eventName = _rawFilterSpec.EventTypeName; if (context.TableService != null && context.TableService.GetTableMetadata(eventName) != null) { if (this.ViewSpecs != null && this.ViewSpecs.Length > 0) { throw new ExprValidationException("Views are not supported with tables"); } if (this.RawFilterSpec.OptionalPropertyEvalSpec != null) { throw new ExprValidationException("Contained-event expressions are not supported with tables"); } var tableMetadata = context.TableService.GetTableMetadata(eventName); var streamTypeServiceX = new StreamTypeServiceImpl(new EventType[] { tableMetadata.InternalEventType }, new String[] { optionalStreamName }, new bool[] { true }, context.EngineURI, false); var validatedNodes = FilterSpecCompiler.ValidateAllowSubquery(ExprNodeOrigin.FILTER, _rawFilterSpec.FilterExpressions, streamTypeServiceX, context, null, null); return(new TableQueryStreamSpec(this.OptionalStreamName, this.ViewSpecs, this.Options, eventName, validatedNodes)); } // Could be a named window if (context.NamedWindowMgmtService.IsNamedWindow(eventName)) { var namedWindowType = context.NamedWindowMgmtService.GetProcessor(eventName).TailView.EventType; streamTypeService = new StreamTypeServiceImpl(new EventType[] { namedWindowType }, new String[] { optionalStreamName }, new bool[] { true }, context.EngineURI, false); var validatedNodes = FilterSpecCompiler.ValidateAllowSubquery( ExprNodeOrigin.FILTER, _rawFilterSpec.FilterExpressions, streamTypeService, context, null, null); PropertyEvaluator optionalPropertyEvaluator = null; if (_rawFilterSpec.OptionalPropertyEvalSpec != null) { optionalPropertyEvaluator = PropertyEvaluatorFactory.MakeEvaluator( _rawFilterSpec.OptionalPropertyEvalSpec, namedWindowType, OptionalStreamName, context.EventAdapterService, context.MethodResolutionService, context.TimeProvider, context.VariableService, context.ScriptingService, context.TableService, context.EngineURI, context.StatementId, context.StatementName, context.Annotations, assignedTypeNumberStack, context.ConfigSnapshot, context.NamedWindowMgmtService); } eventTypeReferences.Add(((EventTypeSPI)namedWindowType).Metadata.PrimaryName); return(new NamedWindowConsumerStreamSpec(eventName, OptionalStreamName, ViewSpecs, validatedNodes, Options, optionalPropertyEvaluator)); } EventType eventType = null; if (context.ValueAddEventService.IsRevisionTypeName(eventName)) { eventType = context.ValueAddEventService.GetValueAddUnderlyingType(eventName); eventTypeReferences.Add(((EventTypeSPI)eventType).Metadata.PrimaryName); } if (eventType == null) { eventType = ResolveType(context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs); if (eventType is EventTypeSPI) { eventTypeReferences.Add(((EventTypeSPI)eventType).Metadata.PrimaryName); } } // Validate all nodes, make sure each returns a bool and types are good; // Also decompose all AND super nodes into individual expressions streamTypeService = new StreamTypeServiceImpl(new EventType[] { eventType }, new String[] { base.OptionalStreamName }, new bool[] { true }, context.EngineURI, false); var spec = FilterSpecCompiler.MakeFilterSpec(eventType, eventName, _rawFilterSpec.FilterExpressions, _rawFilterSpec.OptionalPropertyEvalSpec, null, null, // no tags streamTypeService, OptionalStreamName, context, assignedTypeNumberStack); return(new FilterStreamSpecCompiled(spec, ViewSpecs, OptionalStreamName, Options)); }
private static void RecursiveCompile( EvalFactoryNode evalNode, StatementContext context, ExprEvaluatorContext evaluatorContext, ICollection <string> eventTypeReferences, bool isInsertInto, MatchEventSpec tags, Deque <int> subexpressionIdStack, Stack <EvalFactoryNode> parentNodeStack, ICollection <string> allTagNamesOrdered) { var counter = 0; parentNodeStack.Push(evalNode); foreach (var child in evalNode.ChildNodes) { subexpressionIdStack.AddLast(counter++); RecursiveCompile( child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack, parentNodeStack, allTagNamesOrdered); subexpressionIdStack.RemoveLast(); } parentNodeStack.Pop(); LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null; LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes = null; if (evalNode is EvalFilterFactoryNode) { var filterNode = (EvalFilterFactoryNode)evalNode; var eventName = filterNode.RawFilterSpec.EventTypeName; if (context.TableService.GetTableMetadata(eventName) != null) { throw new ExprValidationException("Tables cannot be used in pattern filter atoms"); } var resolvedEventType = FilterStreamSpecRaw.ResolveType( context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs); var finalEventType = resolvedEventType; var optionalTag = filterNode.EventAsName; var isPropertyEvaluation = false; var isParentMatchUntil = IsParentMatchUntil(evalNode, parentNodeStack); // obtain property event type, if final event type is properties if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null) { var optionalPropertyEvaluator = PropertyEvaluatorFactory.MakeEvaluator( context.Container, filterNode.RawFilterSpec.OptionalPropertyEvalSpec, resolvedEventType, filterNode.EventAsName, context.EventAdapterService, context.EngineImportService, context.SchedulingService, context.VariableService, context.ScriptingService, context.TableService, context.EngineURI, context.StatementId, context.StatementName, context.Annotations, subexpressionIdStack, context.ConfigSnapshot, context.NamedWindowMgmtService, context.StatementExtensionServicesContext); finalEventType = optionalPropertyEvaluator.FragmentEventType; isPropertyEvaluation = true; } if (finalEventType is EventTypeSPI) { eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName); } // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no if (optionalTag != null) { var pair = tags.TaggedEventTypes.Get(optionalTag); EventType existingType = null; if (pair != null) { existingType = pair.First; } if (existingType == null) { pair = tags.ArrayEventTypes.Get(optionalTag); if (pair != null) { throw new ExprValidationException( "Tag '" + optionalTag + "' for event '" + eventName + "' used in the repeat-until operator cannot also appear in other filter expressions"); } } if ((existingType != null) && (existingType != finalEventType)) { throw new ExprValidationException( "Tag '" + optionalTag + "' for event '" + eventName + "' has already been declared for events of type " + existingType.UnderlyingType.FullName); } pair = new Pair <EventType, string>(finalEventType, eventName); // add tagged type if (isPropertyEvaluation || isParentMatchUntil) { newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(); newArrayEventTypes.Put(optionalTag, pair); } else { newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(); newTaggedEventTypes.Put(optionalTag, pair); } } // For this filter, filter types are all known tags at this time, // and additionally stream 0 (self) is our event type. // Stream type service allows resolution by property name event if that name appears in other tags. // by defaulting to stream zero. // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N). var selfStreamName = optionalTag; if (selfStreamName == null) { selfStreamName = "s_" + UuidGenerator.Generate(); } var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >(); var typePair = new Pair <EventType, string>(finalEventType, eventName); filterTypes.Put(selfStreamName, typePair); filterTypes.PutAll(tags.TaggedEventTypes); // for the filter, specify all tags used var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes); filterTaggedEventTypes.Remove(optionalTag); // handle array tags (match-until clause) LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null; if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty()) { arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(); var patternSubexEventType = GetPatternSubexEventType( context.StatementId, "pattern", subexpressionIdStack); foreach (var entry in tags.ArrayEventTypes) { var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >(); specificArrayType.Put(entry.Key, entry.Value); var arrayTagCompositeEventType = context.EventAdapterService.CreateSemiAnonymousMapType( patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(), specificArrayType, isInsertInto); context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType); var tag = entry.Key; if (!filterTypes.ContainsKey(tag)) { var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag); filterTypes.Put(tag, pair); arrayCompositeEventTypes.Put(tag, pair); } } } StreamTypeService streamTypeService = new StreamTypeServiceImpl( filterTypes, context.EngineURI, true, false); var exprNodes = filterNode.RawFilterSpec.FilterExpressions; var spec = FilterSpecCompiler.MakeFilterSpec( resolvedEventType, eventName, exprNodes, filterNode.RawFilterSpec.OptionalPropertyEvalSpec, filterTaggedEventTypes, arrayCompositeEventTypes, streamTypeService, null, context, subexpressionIdStack); filterNode.FilterSpec = spec; } else if (evalNode is EvalObserverFactoryNode) { var observerNode = (EvalObserverFactoryNode)evalNode; try { var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec); var streamTypeService = GetStreamTypeService( context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes, tags.ArrayEventTypes, subexpressionIdStack, "observer", context); var validationContext = new ExprValidationContext( context.Container, streamTypeService, context.EngineImportService, context.StatementExtensionServicesContext, null, context.SchedulingService, context.VariableService, context.TableService, evaluatorContext, context.EventAdapterService, context.StatementName, context.StatementId, context.Annotations, context.ContextDescriptor, context.ScriptingService, false, false, false, false, null, false); var validated = ValidateExpressions( ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters, validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl( tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService); observerNode.ObserverFactory = observerFactory; observerFactory.SetObserverParameters(validated, convertor, validationContext); } catch (ObserverParameterException e) { throw new ExprValidationException( "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message, e); } catch (PatternObjectException e) { throw new ExprValidationException( "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message, e); } } else if (evalNode is EvalGuardFactoryNode) { var guardNode = (EvalGuardFactoryNode)evalNode; try { var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec); var streamTypeService = GetStreamTypeService( context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes, tags.ArrayEventTypes, subexpressionIdStack, "guard", context); var validationContext = new ExprValidationContext( context.Container, streamTypeService, context.EngineImportService, context.StatementExtensionServicesContext, null, context.SchedulingService, context.VariableService, context.TableService, evaluatorContext, context.EventAdapterService, context.StatementName, context.StatementId, context.Annotations, context.ContextDescriptor, context.ScriptingService, false, false, false, false, null, false); var validated = ValidateExpressions( ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl( tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService); guardNode.GuardFactory = guardFactory; guardFactory.SetGuardParameters(validated, convertor); } catch (GuardParameterException e) { throw new ExprValidationException( "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e); } catch (PatternObjectException e) { throw new ExprValidationException( "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e); } } else if (evalNode is EvalEveryDistinctFactoryNode) { var distinctNode = (EvalEveryDistinctFactoryNode)evalNode; var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode); var streamTypeService = GetStreamTypeService( context.EngineURI, context.StatementId, context.EventAdapterService, matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes, subexpressionIdStack, "every-distinct", context); var validationContext = new ExprValidationContext( context.Container, streamTypeService, context.EngineImportService, context.StatementExtensionServicesContext, null, context.SchedulingService, context.VariableService, context.TableService, evaluatorContext, context.EventAdapterService, context.StatementName, context.StatementId, context.Annotations, context.ContextDescriptor, context.ScriptingService, false, false, false, false, null, false); IList <ExprNode> validated; try { validated = ValidateExpressions( ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext); } catch (ExprValidationPropertyException ex) { throw new ExprValidationPropertyException( ex.Message + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct", ex.InnerException); } MatchedEventConvertor convertor = new MatchedEventConvertorImpl( matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService); distinctNode.Convertor = convertor; // Determine whether some expressions are constants or time period IList <ExprNode> distinctExpressions = new List <ExprNode>(); ExprTimePeriodEvalDeltaConst timeDeltaComputation = null; ExprNode expiryTimeExp = null; var count = -1; var last = validated.Count - 1; foreach (var expr in validated) { count++; if (count == last && expr is ExprTimePeriod) { expiryTimeExp = expr; var timePeriodExpr = (ExprTimePeriod)expiryTimeExp; timeDeltaComputation = timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false)); } else if (expr.IsConstantResult) { if (count == last) { var evaluateParams = new EvaluateParams(null, true, evaluatorContext); var value = expr.ExprEvaluator.Evaluate(evaluateParams); if (!(value.IsNumber())) { throw new ExprValidationException( "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)"); } var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams); long?timeExpire; if (secondsExpire == null) { timeExpire = null; } else { timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire); } if (timeExpire != null && timeExpire > 0) { timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value); expiryTimeExp = expr; } else { Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr)); } } else { Log.Warn( "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list", expr.ToExpressionStringMinPrecedenceSafe()); } } 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, timeDeltaComputation, expiryTimeExp); } else if (evalNode is EvalMatchUntilFactoryNode) { var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode; // compile bounds expressions, if any var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes); var streamTypeService = GetStreamTypeService( context.EngineURI, context.StatementId, context.EventAdapterService, untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack, "until", context); var validationContext = new ExprValidationContext( context.Container, streamTypeService, context.EngineImportService, context.StatementExtensionServicesContext, null, context.SchedulingService, context.VariableService, context.TableService, evaluatorContext, context.EventAdapterService, context.StatementName, context.StatementId, context.Annotations, context.ContextDescriptor, context.ScriptingService, false, false, false, false, null, false); var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext); matchUntilNode.LowerBounds = lower; var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext); matchUntilNode.UpperBounds = upper; var single = ValidateBounds(matchUntilNode.SingleBound, validationContext); matchUntilNode.SingleBound = single; var convertor = new MatchedEventConvertorImpl( untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService); matchUntilNode.Convertor = convertor; // compile new tag lists ISet <string> arrayTags = null; var matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]); foreach (var filterNode in matchUntilAnalysisResult.FilterNodes) { var optionalTag = filterNode.EventAsName; if (optionalTag != null) { if (arrayTags == null) { arrayTags = new HashSet <string>(); } arrayTags.Add(optionalTag); } } if (arrayTags != null) { foreach (var arrayTag in arrayTags) { if (!tags.ArrayEventTypes.ContainsKey(arrayTag)) { tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag)); tags.TaggedEventTypes.Remove(arrayTag); } } } matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags); } else if (evalNode is EvalFollowedByFactoryNode) { var followedByNode = (EvalFollowedByFactoryNode)evalNode; StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false); var validationContext = new ExprValidationContext( context.Container, streamTypeService, context.EngineImportService, context.StatementExtensionServicesContext, null, context.SchedulingService, context.VariableService, context.TableService, evaluatorContext, context.EventAdapterService, context.StatementName, context.StatementId, context.Annotations, context.ContextDescriptor, context.ScriptingService, false, false, false, false, null, false); if (followedByNode.OptionalMaxExpressions != null) { IList <ExprNode> validated = new List <ExprNode>(); foreach (var maxExpr in followedByNode.OptionalMaxExpressions) { if (maxExpr == null) { validated.Add(null); } else { var visitor = new ExprNodeSummaryVisitor(); maxExpr.Accept(visitor); if (!visitor.IsPlain) { var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() + " are not allowed within the expression"; Log.Error(errorMessage); throw new ExprValidationException(errorMessage); } var validatedExpr = ExprNodeUtility.GetValidatedSubtree( ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext); validated.Add(validatedExpr); if ((validatedExpr.ExprEvaluator.ReturnType == null) || (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric())) { var message = "Invalid maximum expression in followed-by, the expression must return an integer value"; throw new ExprValidationException(message); } } } followedByNode.OptionalMaxExpressions = validated; } } if (newTaggedEventTypes != null) { tags.TaggedEventTypes.PutAll(newTaggedEventTypes); } if (newArrayEventTypes != null) { tags.ArrayEventTypes.PutAll(newArrayEventTypes); } }
public static FilterSpecCompiled BuildNoStmtCtx( IList <ExprNode> validatedFilterNodes, EventType eventType, string eventTypeName, PropertyEvalSpec optionalPropertyEvalSpec, IDictionary <string, Pair <EventType, string> > taggedEventTypes, IDictionary <string, Pair <EventType, string> > arrayEventTypes, StreamTypeService streamTypeService, string optionalStreamName, ICollection <int> assignedTypeNumberStack, ExprEvaluatorContext exprEvaluatorContext, string statementId, string statementName, Attribute[] annotations, ContextDescriptor contextDescriptor, MethodResolutionService methodResolutionService, EventAdapterService eventAdapterService, TimeProvider timeProvider, VariableService variableService, ScriptingService scriptingService, TableService tableService, ConfigurationInformation configurationInformation, NamedWindowService namedWindowService) { var args = new FilterSpecCompilerArgs( taggedEventTypes, arrayEventTypes, exprEvaluatorContext, statementName, statementId, streamTypeService, methodResolutionService, timeProvider, variableService, tableService, eventAdapterService, scriptingService, annotations, contextDescriptor, configurationInformation); var parameters = FilterSpecCompilerPlanner.PlanFilterParameters(validatedFilterNodes, args); PropertyEvaluator optionalPropertyEvaluator = null; if (optionalPropertyEvalSpec != null) { optionalPropertyEvaluator = PropertyEvaluatorFactory.MakeEvaluator( optionalPropertyEvalSpec, eventType, optionalStreamName, eventAdapterService, methodResolutionService, timeProvider, variableService, scriptingService, tableService, streamTypeService.EngineURIQualifier, statementId, statementName, annotations, assignedTypeNumberStack, configurationInformation, namedWindowService); } var spec = new FilterSpecCompiled(eventType, eventTypeName, parameters, optionalPropertyEvaluator); if (Log.IsDebugEnabled) { Log.Debug(".makeFilterSpec spec=" + spec); } return(spec); }