private AggSvcGroupByReclaimAgedEvalFuncFactory GetEvaluationFunction(VariableService variableService, String hintValue, String optionalContextName)
        {
            VariableMetaData variableMetaData = variableService.GetVariableMetaData(hintValue);

            if (variableMetaData != null)
            {
                if (!variableMetaData.VariableType.IsNumeric())
                {
                    throw new ExprValidationException("Variable type of variable '" + variableMetaData.VariableName + "' is not numeric");
                }
                String message = VariableServiceUtil.CheckVariableContextName(optionalContextName, variableMetaData);
                if (message != null)
                {
                    throw new ExprValidationException(message);
                }
                return(new ProxyAggSvcGroupByReclaimAgedEvalFuncFactory
                {
                    ProcMake = agentInstanceContext =>
                    {
                        VariableReader reader = variableService.GetReader(
                            variableMetaData.VariableName, agentInstanceContext.AgentInstanceId);
                        return new AggSvcGroupByReclaimAgedEvalFuncVariable(reader);
                    }
                });
            }
            else
            {
                double valueDouble;
                try {
                    valueDouble = DoubleValue.ParseString(hintValue);
                }
                catch (Exception) {
                    throw new ExprValidationException("Failed to parse hint parameter value '" + hintValue + "' as a double-typed seconds value or variable name");
                }
                if (valueDouble <= 0)
                {
                    throw new ExprValidationException("Hint parameter value '" + hintValue + "' is an invalid value, expecting a double-typed seconds value or variable name");
                }
                return(new ProxyAggSvcGroupByReclaimAgedEvalFuncFactory
                {
                    ProcMake = agentInstanceContext => new AggSvcGroupByReclaimAgedEvalFuncConstant(valueDouble)
                });
            }
        }
Ejemplo n.º 2
0
        public static ExprNode ResolvePropertyOrVariableIdentifier(String identifier, VariableService variableService, StatementSpecRaw spec)
        {
            var metaData = variableService.GetVariableMetaData(identifier);

            if (metaData != null)
            {
                var exprNode = new ExprVariableNodeImpl(metaData, null);
                spec.HasVariables = true;
                AddVariableReference(spec, metaData.VariableName);
                var message = VariableServiceUtil.CheckVariableContextName(spec.OptionalContextName, metaData);
                if (message != null)
                {
                    throw ASTWalkException.From(message);
                }
                return(exprNode);
            }
            else
            {
                return(new ExprIdentNodeImpl(identifier));
            }
        }
        public override EPStatementStartResult StartInternal(
            EPServicesContext services,
            StatementContext statementContext,
            bool isNewStatement,
            bool isRecoveringStatement,
            bool isRecoveringResilient)
        {
            var createDesc = _statementSpec.CreateVariableDesc;

            VariableServiceUtil.CheckAlreadyDeclaredTable(createDesc.VariableName, services.TableService);

            // Get assignment value
            object value = null;

            if (createDesc.Assignment != null)
            {
                // Evaluate assignment expression
                StreamTypeService typeService = new StreamTypeServiceImpl(
                    new EventType[0], new string[0], new bool[0], services.EngineURI, false);
                var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);
                var validationContext    = new ExprValidationContext(
                    typeService,
                    statementContext.MethodResolutionService, null,
                    statementContext.SchedulingService,
                    statementContext.VariableService,
                    statementContext.TableService, evaluatorContextStmt,
                    statementContext.EventAdapterService,
                    statementContext.StatementName, statementContext.StatementId,
                    statementContext.Annotations,
                    statementContext.ContextDescriptor,
                    statementContext.ScriptingService,
                    false, false, false, false, null, false);
                var validated = ExprNodeUtility.GetValidatedSubtree(
                    ExprNodeOrigin.VARIABLEASSIGN, createDesc.Assignment, validationContext);
                value = validated.ExprEvaluator.Evaluate(new EvaluateParams(null, true, evaluatorContextStmt));
            }

            // Create variable
            try
            {
                services.VariableService.CreateNewVariable(
                    _statementSpec.OptionalContextName, createDesc.VariableName, createDesc.VariableType, createDesc.IsConstant,
                    createDesc.IsArray, createDesc.IsArrayOfPrimitive, value, services.EngineImportService);
            }
            catch (VariableExistsException ex)
            {
                // for new statement we don't allow creating the same variable
                if (isNewStatement)
                {
                    throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
                }
            }
            catch (VariableDeclarationException ex)
            {
                throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
            }

            var destroyMethod = new EPStatementDestroyCallbackList();

            destroyMethod.AddCallback(new ProxyDestroyCallback(() =>
            {
                try
                {
                    services.StatementVariableRefService.RemoveReferencesStatement(statementContext.StatementName);
                }
                catch (Exception ex)
                {
                    Log.Error("Error removing variable '" + createDesc.VariableName + "': " + ex.Message);
                }
            }));

            var stopMethod = new ProxyEPStatementStopMethod(() => { });

            var      variableMetaData = services.VariableService.GetVariableMetaData(createDesc.VariableName);
            Viewable outputView;
            var      eventType = CreateVariableView.GetEventType(
                statementContext.StatementId, services.EventAdapterService, variableMetaData);
            var contextFactory =
                new StatementAgentInstanceFactoryCreateVariable(
                    createDesc, _statementSpec, statementContext, services, variableMetaData, eventType);

            statementContext.StatementAgentInstanceFactory = contextFactory;

            if (_statementSpec.OptionalContextName != null)
            {
                var mergeView = new ContextMergeView(eventType);
                outputView = mergeView;
                var statement =
                    new ContextManagedStatementCreateVariableDesc(_statementSpec, statementContext, mergeView, contextFactory);
                services.ContextManagementService.AddStatement(
                    _statementSpec.OptionalContextName, statement, isRecoveringResilient);

                var contextManagementService = services.ContextManagementService;
                destroyMethod.AddCallback(new ProxyDestroyCallback(() => contextManagementService.DestroyedStatement(
                                                                       _statementSpec.OptionalContextName, statementContext.StatementName,
                                                                       statementContext.StatementId)));
            }
            else
            {
                var resultOfStart =
                    (StatementAgentInstanceFactoryCreateVariableResult)
                    contextFactory.NewContext(GetDefaultAgentInstanceContext(statementContext), isRecoveringResilient);
                outputView = resultOfStart.FinalView;

                if (statementContext.StatementExtensionServicesContext != null &&
                    statementContext.StatementExtensionServicesContext.StmtResources != null)
                {
                    var holder =
                        statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(resultOfStart);
                    statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                    statementContext.StatementExtensionServicesContext.PostProcessStart(resultOfStart, isRecoveringResilient);
                }
            }

            services.StatementVariableRefService.AddReferences(
                statementContext.StatementName, Collections.SingletonList(createDesc.VariableName), null);
            return(new EPStatementStartResult(outputView, stopMethod, destroyMethod));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="rowLimitSpec">specification for row limit, or null if no row limit is defined</param>
        /// <param name="variableService">for retrieving variable state for use with row limiting</param>
        /// <param name="optionalContextName">Name of the optional context.</param>
        /// <exception cref="ExprValidationException">
        /// Limit clause variable by name '" + rowLimitSpec.NumRowsVariable + "' has not been declared
        /// or
        /// or
        /// Limit clause requires a variable of numeric type
        /// or
        /// Limit clause variable by name '" + rowLimitSpec.OptionalOffsetVariable + "' has not been declared
        /// or
        /// or
        /// Limit clause requires a variable of numeric type
        /// or
        /// Limit clause requires a positive offset
        /// </exception>
        /// <throws>com.espertech.esper.epl.expression.core.ExprValidationException if row limit specification validation fails</throws>
        public RowLimitProcessorFactory(RowLimitSpec rowLimitSpec, VariableService variableService, string optionalContextName)
        {
            if (rowLimitSpec.NumRowsVariable != null)
            {
                _numRowsVariableMetaData = variableService.GetVariableMetaData(rowLimitSpec.NumRowsVariable);
                if (_numRowsVariableMetaData == null)
                {
                    throw new ExprValidationException("Limit clause variable by name '" + rowLimitSpec.NumRowsVariable + "' has not been declared");
                }
                string message = VariableServiceUtil.CheckVariableContextName(optionalContextName, _numRowsVariableMetaData);
                if (message != null)
                {
                    throw new ExprValidationException(message);
                }
                if (!TypeHelper.IsNumeric(_numRowsVariableMetaData.VariableType))
                {
                    throw new ExprValidationException("Limit clause requires a variable of numeric type");
                }
            }
            else
            {
                _numRowsVariableMetaData = null;
                _currentRowLimit         = rowLimitSpec.NumRows.GetValueOrDefault();

                if (_currentRowLimit < 0)
                {
                    _currentRowLimit = int.MaxValue;
                }
            }

            if (rowLimitSpec.OptionalOffsetVariable != null)
            {
                _offsetVariableMetaData = variableService.GetVariableMetaData(rowLimitSpec.OptionalOffsetVariable);
                if (_offsetVariableMetaData == null)
                {
                    throw new ExprValidationException("Limit clause variable by name '" + rowLimitSpec.OptionalOffsetVariable + "' has not been declared");
                }
                string message = VariableServiceUtil.CheckVariableContextName(optionalContextName, _offsetVariableMetaData);
                if (message != null)
                {
                    throw new ExprValidationException(message);
                }
                if (!TypeHelper.IsNumeric(_offsetVariableMetaData.VariableType))
                {
                    throw new ExprValidationException("Limit clause requires a variable of numeric type");
                }
            }
            else
            {
                _offsetVariableMetaData = null;
                if (rowLimitSpec.OptionalOffset != null)
                {
                    _currentOffset = rowLimitSpec.OptionalOffset.GetValueOrDefault();

                    if (_currentOffset <= 0)
                    {
                        throw new ExprValidationException("Limit clause requires a positive offset");
                    }
                }
                else
                {
                    _currentOffset = 0;
                }
            }
        }
Ejemplo n.º 5
0
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            var createDesc = _statementSpec.CreateTableDesc;

            // determine whether already declared
            VariableServiceUtil.CheckAlreadyDeclaredVariable(createDesc.TableName, services.VariableService);
            if (isNewStatement)
            {
                VariableServiceUtil.CheckAlreadyDeclaredTable(createDesc.TableName, services.TableService);
            }
            if (services.EventAdapterService.GetEventTypeByName(createDesc.TableName) != null)
            {
                throw new ExprValidationException("An event type or schema by name '" + createDesc.TableName + "' already exists");
            }

            // Determine event type names
            var internalTypeName = "table_" + createDesc.TableName + "__internal";
            var publicTypeName   = "table_" + createDesc.TableName + "__public";

            TableMetadata metadata;

            try
            {
                // determine key types
                var keyTypes = GetKeyTypes(createDesc.Columns, services.EngineImportService);

                // check column naming, interpret annotations
                var columnDescs = ValidateExpressions(createDesc.Columns, services, statementContext);

                // analyze and plan the state holders
                var plan = AnalyzePlanAggregations(createDesc.TableName, statementContext, columnDescs, services, internalTypeName, publicTypeName);
                var tableStateRowFactory = plan.StateRowFactory;

                // register new table
                var queryPlanLogging = services.ConfigSnapshot.EngineDefaults.Logging.IsEnableQueryPlan;
                metadata = services.TableService.AddTable(createDesc.TableName, statementContext.Expression, statementContext.StatementName, keyTypes, plan.TableColumns, tableStateRowFactory, plan.NumberMethodAggregations, statementContext, plan.InternalEventType,
                                                          plan.PublicEventType, plan.EventToPublic, queryPlanLogging);
            }
            catch (ExprValidationException ex)
            {
                services.EventAdapterService.RemoveType(internalTypeName);
                services.EventAdapterService.RemoveType(publicTypeName);
                throw ex;
            }

            // allocate context factory
            var contextFactory = new StatementAgentInstanceFactoryCreateTable(metadata);

            statementContext.StatementAgentInstanceFactory = contextFactory;
            Viewable outputView;
            EPStatementStopMethod    stopStatementMethod;
            EPStatementDestroyMethod destroyStatementMethod;

            if (_statementSpec.OptionalContextName != null)
            {
                var contextName = _statementSpec.OptionalContextName;
                var mergeView   = new ContextMergeView(metadata.PublicEventType);
                outputView = mergeView;
                var statement = new ContextManagedStatementCreateAggregationVariableDesc(_statementSpec, statementContext, mergeView, contextFactory);
                services.ContextManagementService.AddStatement(_statementSpec.OptionalContextName, statement, isRecoveringResilient);

                stopStatementMethod = new ProxyEPStatementStopMethod(() =>
                                                                     services.ContextManagementService.StoppedStatement(
                                                                         contextName, statementContext.StatementName, statementContext.StatementId,
                                                                         statementContext.Expression, statementContext.ExceptionHandlingService));

                destroyStatementMethod = new ProxyEPStatementDestroyMethod(() =>
                {
                    services.ContextManagementService.DestroyedStatement(contextName, statementContext.StatementName, statementContext.StatementId);
                    services.StatementVariableRefService.RemoveReferencesStatement(statementContext.StatementName);
                });
            }
            else
            {
                var defaultAgentInstanceContext = GetDefaultAgentInstanceContext(statementContext);
                var result = contextFactory.NewContext(defaultAgentInstanceContext, false);
                if (statementContext.StatementExtensionServicesContext != null && statementContext.StatementExtensionServicesContext.StmtResources != null)
                {
                    var holder = statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(result);
                    statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                }
                outputView = result.FinalView;

                stopStatementMethod    = new ProxyEPStatementStopMethod(() => { });
                destroyStatementMethod = new ProxyEPStatementDestroyMethod(() =>
                                                                           services.StatementVariableRefService.RemoveReferencesStatement(statementContext.StatementName));
            }

            services.StatementVariableRefService.AddReferences(statementContext.StatementName, createDesc.TableName);

            return(new EPStatementStartResult(outputView, stopStatementMethod, destroyStatementMethod));
        }
Ejemplo n.º 6
0
        public static OutputConditionFactory CreateCondition(
            OutputLimitSpec outputLimitSpec,
            StatementContext statementContext,
            bool isGrouped,
            bool isWithHavingClause,
            bool isStartConditionOnCreation,
            ResultSetProcessorHelperFactory resultSetProcessorHelperFactory)
        {
            if (outputLimitSpec == null)
            {
                return new OutputConditionNullFactory();
            }

            // Check if a variable is present
            VariableMetaData variableMetaData = null;
            if (outputLimitSpec.VariableName != null)
            {
                variableMetaData = statementContext.VariableService.GetVariableMetaData(outputLimitSpec.VariableName);
                if (variableMetaData == null)
                {
                    throw new ExprValidationException(
                        "Variable named '" + outputLimitSpec.VariableName + "' has not been declared");
                }
                string message = VariableServiceUtil.CheckVariableContextName(
                    statementContext.ContextDescriptor, variableMetaData);
                if (message != null)
                {
                    throw new ExprValidationException(message);
                }
            }

            if (outputLimitSpec.DisplayLimit == OutputLimitLimitType.FIRST && isGrouped)
            {
                return new OutputConditionNullFactory();
            }

            if (outputLimitSpec.RateType == OutputLimitRateType.CRONTAB)
            {
                return resultSetProcessorHelperFactory.MakeOutputConditionCrontab(
                    outputLimitSpec.CrontabAtSchedule, statementContext, isStartConditionOnCreation);
            }
            else if (outputLimitSpec.RateType == OutputLimitRateType.WHEN_EXPRESSION)
            {
                return resultSetProcessorHelperFactory.MakeOutputConditionExpression(
                    outputLimitSpec.WhenExpressionNode, outputLimitSpec.ThenExpressions, statementContext,
                    outputLimitSpec.AndAfterTerminateExpr, outputLimitSpec.AndAfterTerminateThenExpressions,
                    isStartConditionOnCreation);
            }
            else if (outputLimitSpec.RateType == OutputLimitRateType.EVENTS)
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug(".createCondition creating OutputConditionCount with event rate " + outputLimitSpec);
                }

                if ((variableMetaData != null) && (!variableMetaData.VariableType.IsNumericNonFP()))
                {
                    throw new ArgumentException(
                        "Variable named '" + outputLimitSpec.VariableName + "' must be type integer, long or short");
                }

                int rate = -1;
                if (outputLimitSpec.Rate != null)
                {
                    rate = outputLimitSpec.Rate.AsInt();
                }
                return resultSetProcessorHelperFactory.MakeOutputConditionCount(
                    rate, variableMetaData, statementContext);
            }
            else if (outputLimitSpec.RateType == OutputLimitRateType.TERM)
            {
                if (outputLimitSpec.AndAfterTerminateExpr == null &&
                    (outputLimitSpec.AndAfterTerminateThenExpressions == null ||
                     outputLimitSpec.AndAfterTerminateThenExpressions.IsEmpty()))
                {
                    return new OutputConditionTermFactory();
                }
                else
                {
                    return resultSetProcessorHelperFactory.MakeOutputConditionExpression(
                        new ExprConstantNodeImpl(false), Collections.GetEmptyList<OnTriggerSetAssignment>(),
                        statementContext, outputLimitSpec.AndAfterTerminateExpr,
                        outputLimitSpec.AndAfterTerminateThenExpressions, isStartConditionOnCreation);
                }
            }
            else
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug(
                        ".createCondition creating OutputConditionTime with interval length " + outputLimitSpec.Rate);
                }
                if ((variableMetaData != null) && (!variableMetaData.VariableType.IsNumeric()))
                {
                    throw new ArgumentException(
                        "Variable named '" + outputLimitSpec.VariableName + "' must be of numeric type");
                }

                return resultSetProcessorHelperFactory.MakeOutputConditionTime(
                    outputLimitSpec.TimePeriodExpr, isStartConditionOnCreation);
            }
        }
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            var createDesc = StatementSpec.CreateVariableDesc;

            VariableServiceUtil.CheckAlreadyDeclaredTable(createDesc.VariableName, services.TableService);

            // Get assignment value
            Object value = null;

            if (createDesc.Assignment != null)
            {
                // Evaluate assignment expression
                var typeService          = new StreamTypeServiceImpl(new EventType[0], new String[0], new bool[0], services.EngineURI, false);
                var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);
                var validationContext    = new ExprValidationContext(
                    typeService,
                    statementContext.MethodResolutionService, null,
                    statementContext.SchedulingService,
                    statementContext.VariableService,
                    statementContext.TableService, evaluatorContextStmt,
                    statementContext.EventAdapterService,
                    statementContext.StatementName,
                    statementContext.StatementId,
                    statementContext.Annotations,
                    statementContext.ContextDescriptor,
                    statementContext.ScriptingService,
                    false, false, false, false, null, false);
                var validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.VARIABLEASSIGN, createDesc.Assignment, validationContext);
                value = validated.ExprEvaluator.Evaluate(new EvaluateParams(null, true, evaluatorContextStmt));
            }

            // Create variable
            try
            {
                services.VariableService.CreateNewVariable(
                    StatementSpec.OptionalContextName,
                    createDesc.VariableName,
                    createDesc.VariableType,
                    createDesc.IsConstant,
                    createDesc.IsArray,
                    createDesc.IsArrayOfPrimitive,
                    value,
                    services.EngineImportService);
            }
            catch (VariableExistsException ex)
            {
                // for new statement we don't allow creating the same variable
                if (isNewStatement)
                {
                    throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
                }
            }
            catch (VariableDeclarationException ex)
            {
                throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
            }

            var destroyMethod = new EPStatementDestroyCallbackList();

            destroyMethod.AddCallback(
                () =>
            {
                try
                {
                    services.StatementVariableRefService.RemoveReferencesStatement(statementContext.StatementName);
                }
                catch (Exception ex)
                {
                    Log.Error("Error removing variable '" + createDesc.VariableName + "': " + ex.Message);
                }
            });

            var stopMethod = new EPStatementStopMethod(() => { });

            VariableMetaData variableMetaData = services.VariableService.GetVariableMetaData(createDesc.VariableName);
            Viewable         outputView;

            if (StatementSpec.OptionalContextName != null)
            {
                EventType eventType      = CreateVariableView.GetEventType(statementContext.StatementId, services.EventAdapterService, variableMetaData);
                var       contextFactory = new StatementAgentInstanceFactoryCreateVariable(statementContext, services, variableMetaData, eventType);
                var       mergeView      = new ContextMergeView(eventType);
                outputView = mergeView;
                var statement = new ContextManagedStatementCreateVariableDesc(StatementSpec, statementContext, mergeView, contextFactory);
                services.ContextManagementService.AddStatement(StatementSpec.OptionalContextName, statement, isRecoveringResilient);

                ContextManagementService contextManagementService = services.ContextManagementService;
                destroyMethod.AddCallback(() => contextManagementService.DestroyedStatement(StatementSpec.OptionalContextName, statementContext.StatementName, statementContext.StatementId));
            }
            else
            {
                // allocate
                services.VariableService.AllocateVariableState(createDesc.VariableName, VariableServiceConstants.NOCONTEXT_AGENTINSTANCEID, statementContext.StatementExtensionServicesContext);
                var createView = new CreateVariableView(statementContext.StatementId, services.EventAdapterService, services.VariableService, createDesc.VariableName, statementContext.StatementResultService);

                services.VariableService.RegisterCallback(createDesc.VariableName, 0, createView.Update);
                statementContext.StatementStopService.StatementStopped +=
                    () => services.VariableService.UnregisterCallback(createDesc.VariableName, 0, createView.Update);

                // Create result set processor, use wildcard selection
                StatementSpec.SelectClauseSpec.SetSelectExprList(new SelectClauseElementWildcard());
                StatementSpec.SelectStreamDirEnum = SelectClauseStreamSelectorEnum.RSTREAM_ISTREAM_BOTH;
                StreamTypeService typeService   = new StreamTypeServiceImpl(new EventType[] { createView.EventType }, new String[] { "create_variable" }, new bool[] { true }, services.EngineURI, false);
                var agentInstanceContext        = GetDefaultAgentInstanceContext(statementContext);
                var resultSetProcessorPrototype = ResultSetProcessorFactoryFactory.GetProcessorPrototype(
                    StatementSpec, statementContext, typeService, null, new bool[0], true, ContextPropertyRegistryImpl.EMPTY_REGISTRY, null, services.ConfigSnapshot);
                var resultSetProcessor = EPStatementStartMethodHelperAssignExpr.GetAssignResultSetProcessor(agentInstanceContext, resultSetProcessorPrototype);

                // Attach output view
                var outputViewFactory = OutputProcessViewFactoryFactory.Make(StatementSpec, services.InternalEventRouter, agentInstanceContext.StatementContext, resultSetProcessor.ResultEventType, null, services.TableService, resultSetProcessorPrototype.ResultSetProcessorFactory.ResultSetProcessorType);
                var outputViewBase    = outputViewFactory.MakeView(resultSetProcessor, agentInstanceContext);
                createView.AddView(outputViewBase);
                outputView = outputViewBase;
            }

            services.StatementVariableRefService.AddReferences(statementContext.StatementName, Collections.SingletonList(createDesc.VariableName), null);

            return(new EPStatementStartResult(outputView, stopMethod, destroyMethod.Destroy));
        }