/**
  * Indicate statement result.
  *
  * @param newOldEvents result
  */
 public static void indicateEarlyReturn(
     StatementContext statementContext, UniformPair<EventBean[]> newOldEvents) {
   if (newOldEvents == null) {
     return;
   }
   if ((statementContext.getMetricReportingService() != null)
       && (statementContext.getMetricReportingService().getStatementOutputHooks() != null)
       && (!statementContext.getMetricReportingService().getStatementOutputHooks().isEmpty())) {
     for (StatementResultListener listener :
         statementContext.getMetricReportingService().getStatementOutputHooks()) {
       listener.update(
           newOldEvents.getFirst(),
           newOldEvents.getSecond(),
           statementContext.getStatementName(),
           null,
           null);
     }
   }
 }
  public static PriorEventViewFactory getPriorEventViewFactory(
      StatementContext statementContext, int streamNum, int viewFactoryNum, boolean unboundStream) {
    try {
      String namespace = ViewEnum.PRIOR_EVENT_VIEW.getNamespace();
      String name = ViewEnum.PRIOR_EVENT_VIEW.getName();
      ViewFactory factory = statementContext.getViewResolutionService().create(namespace, name);

      ViewFactoryContext context =
          new ViewFactoryContext(statementContext, streamNum, viewFactoryNum, namespace, name);
      factory.setViewParameters(
          context, Arrays.asList((ExprNode) new ExprConstantNodeImpl(unboundStream)));

      return (PriorEventViewFactory) factory;
    } catch (ViewProcessingException ex) {
      String text = "Exception creating prior event view factory";
      throw new EPException(text, ex);
    } catch (ViewParameterException ex) {
      String text = "Exception creating prior event view factory";
      throw new EPException(text, ex);
    }
  }
Esempio n. 3
0
  public TableOnMergeHelper(
      StatementContext statementContext,
      OnTriggerMergeDesc onTriggerDesc,
      EventType triggeringEventType,
      String triggeringStreamName,
      InternalEventRouter internalEventRouter,
      TableMetadata tableMetadata)
      throws ExprValidationException {
    matched = new ArrayList<TableOnMergeMatch>();
    unmatched = new ArrayList<TableOnMergeMatch>();

    int count = 1;
    boolean hasDeleteAction = false;
    boolean hasInsertIntoTableAction = false;
    boolean hasUpdateAction = false;
    for (OnTriggerMergeMatched matchedItem : onTriggerDesc.getItems()) {
      List<TableOnMergeAction> actions = new ArrayList<TableOnMergeAction>();
      for (OnTriggerMergeAction item : matchedItem.getActions()) {
        try {
          if (item instanceof OnTriggerMergeActionInsert) {
            OnTriggerMergeActionInsert insertDesc = (OnTriggerMergeActionInsert) item;
            TableOnMergeActionIns action =
                setupInsert(
                    tableMetadata,
                    internalEventRouter,
                    count,
                    insertDesc,
                    triggeringEventType,
                    triggeringStreamName,
                    statementContext);
            actions.add(action);
            hasInsertIntoTableAction = action.isInsertIntoBinding();
          } else if (item instanceof OnTriggerMergeActionUpdate) {
            OnTriggerMergeActionUpdate updateDesc = (OnTriggerMergeActionUpdate) item;
            EventBeanUpdateHelper updateHelper =
                EventBeanUpdateHelperFactory.make(
                    tableMetadata.getTableName(),
                    tableMetadata.getInternalEventType(),
                    updateDesc.getAssignments(),
                    onTriggerDesc.getOptionalAsName(),
                    triggeringEventType,
                    false);
            ExprEvaluator filterEval =
                updateDesc.getOptionalWhereClause() == null
                    ? null
                    : updateDesc.getOptionalWhereClause().getExprEvaluator();
            TableUpdateStrategy tableUpdateStrategy =
                statementContext
                    .getTableService()
                    .getTableUpdateStrategy(tableMetadata, updateHelper, true);
            TableOnMergeActionUpd upd = new TableOnMergeActionUpd(filterEval, tableUpdateStrategy);
            actions.add(upd);
            statementContext
                .getTableService()
                .addTableUpdateStrategyReceiver(
                    tableMetadata, statementContext.getStatementName(), upd, updateHelper, true);
            hasUpdateAction = true;
          } else if (item instanceof OnTriggerMergeActionDelete) {
            OnTriggerMergeActionDelete deleteDesc = (OnTriggerMergeActionDelete) item;
            ExprEvaluator filterEval =
                deleteDesc.getOptionalWhereClause() == null
                    ? null
                    : deleteDesc.getOptionalWhereClause().getExprEvaluator();
            actions.add(new TableOnMergeActionDel(filterEval));
            hasDeleteAction = true;
          } else {
            throw new IllegalArgumentException(
                "Invalid type of merge item '" + item.getClass() + "'");
          }
          count++;
        } catch (ExprValidationException ex) {
          boolean isNot = item instanceof OnTriggerMergeActionInsert;
          String message =
              "Validation failed in when-"
                  + (isNot ? "not-" : "")
                  + "matched (clause "
                  + count
                  + "): "
                  + ex.getMessage();
          throw new ExprValidationException(message, ex);
        }
      }

      if (matchedItem.isMatchedUnmatched()) {
        matched.add(new TableOnMergeMatch(matchedItem.getOptionalMatchCond(), actions));
      } else {
        unmatched.add(new TableOnMergeMatch(matchedItem.getOptionalMatchCond(), actions));
      }
    }

    // since updates may change future secondary keys
    requiresWriteLock = hasDeleteAction || hasInsertIntoTableAction || hasUpdateAction;
  }
Esempio n. 4
0
  private TableOnMergeActionIns setupInsert(
      TableMetadata tableMetadata,
      InternalEventRouter internalEventRouter,
      int selectClauseNumber,
      OnTriggerMergeActionInsert desc,
      EventType triggeringEventType,
      String triggeringStreamName,
      StatementContext statementContext)
      throws ExprValidationException {

    // Compile insert-into info
    String streamName =
        desc.getOptionalStreamName() != null
            ? desc.getOptionalStreamName()
            : tableMetadata.getTableName();
    InsertIntoDesc insertIntoDesc = InsertIntoDesc.fromColumns(streamName, desc.getColumns());
    EventType insertIntoTargetType =
        streamName.equals(tableMetadata.getTableName())
            ? tableMetadata.getInternalEventType()
            : null;

    // rewrite any wildcards to use "stream.wildcard"
    if (triggeringStreamName == null) {
      triggeringStreamName = UuidGenerator.generate();
    }
    List<SelectClauseElementCompiled> selectNoWildcard =
        NamedWindowOnMergeHelper.compileSelectNoWildcard(
            triggeringStreamName, desc.getSelectClauseCompiled());

    // Set up event types for select-clause evaluation: The first type does not contain anything as
    // its the named window row which is not present for insert
    EventType dummyTypeNoProperties =
        new MapEventType(
            EventTypeMetadata.createAnonymous("merge_named_window_insert"),
            "merge_named_window_insert",
            0,
            null,
            Collections.<String, Object>emptyMap(),
            null,
            null,
            null);
    EventType[] eventTypes = new EventType[] {dummyTypeNoProperties, triggeringEventType};
    String[] streamNames = new String[] {UuidGenerator.generate(), triggeringStreamName};
    StreamTypeService streamTypeService =
        new StreamTypeServiceImpl(
            eventTypes, streamNames, new boolean[1], statementContext.getEngineURI(), false);

    // Get select expr processor
    SelectExprEventTypeRegistry selectExprEventTypeRegistry =
        new SelectExprEventTypeRegistry(
            statementContext.getStatementName(), statementContext.getStatementEventTypeRef());
    ExprEvaluatorContextStatement exprEvaluatorContext =
        new ExprEvaluatorContextStatement(statementContext, false);
    SelectExprProcessor insertHelper =
        SelectExprProcessorFactory.getProcessor(
            Collections.singleton(selectClauseNumber),
            selectNoWildcard.toArray(new SelectClauseElementCompiled[selectNoWildcard.size()]),
            false,
            insertIntoDesc,
            insertIntoTargetType,
            null,
            streamTypeService,
            statementContext.getEventAdapterService(),
            statementContext.getStatementResultService(),
            statementContext.getValueAddEventService(),
            selectExprEventTypeRegistry,
            statementContext.getMethodResolutionService(),
            exprEvaluatorContext,
            statementContext.getVariableService(),
            statementContext.getTableService(),
            statementContext.getTimeProvider(),
            statementContext.getEngineURI(),
            statementContext.getStatementId(),
            statementContext.getStatementName(),
            statementContext.getAnnotations(),
            statementContext.getContextDescriptor(),
            statementContext.getConfigSnapshot(),
            null,
            statementContext.getNamedWindowService(),
            null);
    ExprEvaluator filterEval =
        desc.getOptionalWhereClause() == null
            ? null
            : desc.getOptionalWhereClause().getExprEvaluator();

    InternalEventRouter routerToUser =
        streamName.equals(tableMetadata.getTableName()) ? null : internalEventRouter;
    boolean audit = AuditEnum.INSERT.getAudit(statementContext.getAnnotations()) != null;
    return new TableOnMergeActionIns(
        filterEval,
        insertHelper,
        routerToUser,
        statementContext.getEpStatementHandle(),
        statementContext.getInternalEventEngineRouteDest(),
        audit,
        tableMetadata.getRowFactory());
  }
 public static NamedWindowOnExprFactory make(
     EventType namedWindowEventType,
     String namedWindowName,
     String namedWindowAlias,
     OnTriggerDesc onTriggerDesc,
     EventType filterEventType,
     String filterStreamName,
     boolean addToFront,
     InternalEventRouter internalEventRouter,
     EventType outputEventType,
     StatementContext statementContext,
     StatementMetricHandle createNamedWindowMetricsHandle,
     boolean isDistinct)
     throws ExprValidationException {
   if (onTriggerDesc.getOnTriggerType() == OnTriggerType.ON_DELETE) {
     return new NamedWindowOnDeleteViewFactory(
         namedWindowEventType, statementContext.getStatementResultService());
   } else if (onTriggerDesc.getOnTriggerType() == OnTriggerType.ON_SELECT) {
     EventBeanReader eventBeanReader = null;
     if (isDistinct) {
       if (outputEventType instanceof EventTypeSPI) {
         eventBeanReader = ((EventTypeSPI) outputEventType).getReader();
       }
       if (eventBeanReader == null) {
         eventBeanReader = new EventBeanReaderDefaultImpl(outputEventType);
       }
     }
     OnTriggerWindowDesc windowDesc = (OnTriggerWindowDesc) onTriggerDesc;
     return new NamedWindowOnSelectViewFactory(
         namedWindowEventType,
         internalEventRouter,
         addToFront,
         statementContext.getEpStatementHandle(),
         eventBeanReader,
         isDistinct,
         outputEventType,
         statementContext.getStatementResultService(),
         statementContext.getInternalEventEngineRouteDest(),
         windowDesc.isDeleteAndSelect());
   } else if (onTriggerDesc.getOnTriggerType() == OnTriggerType.ON_UPDATE) {
     OnTriggerWindowUpdateDesc updateDesc = (OnTriggerWindowUpdateDesc) onTriggerDesc;
     NamedWindowUpdateHelper updateHelper =
         NamedWindowUpdateHelper.make(
             namedWindowName,
             (EventTypeSPI) namedWindowEventType,
             updateDesc.getAssignments(),
             namedWindowAlias);
     return new NamedWindowOnUpdateViewFactory(
         namedWindowEventType, statementContext.getStatementResultService(), updateHelper);
   } else if (onTriggerDesc.getOnTriggerType() == OnTriggerType.ON_MERGE) {
     OnTriggerMergeDesc onMergeTriggerDesc = (OnTriggerMergeDesc) onTriggerDesc;
     NamedWindowOnMergeHelper onMergeHelper =
         new NamedWindowOnMergeHelper(
             statementContext,
             onMergeTriggerDesc,
             filterEventType,
             filterStreamName,
             internalEventRouter,
             namedWindowName,
             (EventTypeSPI) namedWindowEventType);
     return new NamedWindowOnMergeViewFactory(
         namedWindowEventType,
         onMergeHelper,
         statementContext.getStatementResultService(),
         createNamedWindowMetricsHandle,
         statementContext.getMetricReportingService());
   } else {
     throw new IllegalStateException("Unknown trigger type " + onTriggerDesc.getOnTriggerType());
   }
 }
  public StatementAgentInstanceFactoryOnTriggerResult newContext(
      final AgentInstanceContext agentInstanceContext, boolean isRecoveringResilient) {
    List<StopCallback> stopCallbacks = new ArrayList<StopCallback>();
    View view;
    Map<ExprSubselectNode, SubSelectStrategyHolder> subselectStrategies;
    AggregationService aggregationService;
    EvalRootState optPatternRoot;
    Map<ExprTableAccessNode, ExprTableAccessEvalStrategy> tableAccessStrategies;
    final ViewableActivationResult activationResult;

    try {
      if (services.getSchedulableAgentInstanceDirectory() != null) {
        services
            .getSchedulableAgentInstanceDirectory()
            .add(agentInstanceContext.getEpStatementAgentInstanceHandle());
      }

      OnExprViewResult onExprViewResult = determineOnExprView(agentInstanceContext, stopCallbacks);
      view = onExprViewResult.getOnExprView();
      aggregationService = onExprViewResult.getOptionalAggregationService();

      // attach stream to view
      activationResult = activator.activate(agentInstanceContext, false, isRecoveringResilient);
      activationResult.getViewable().addView(view);
      stopCallbacks.add(activationResult.getStopCallback());
      optPatternRoot = activationResult.getOptionalPatternRoot();

      // determine final output view
      view = determineFinalOutputView(agentInstanceContext, view);

      // start subselects
      subselectStrategies =
          EPStatementStartMethodHelperSubselect.startSubselects(
              services, subSelectStrategyCollection, agentInstanceContext, stopCallbacks);

      // plan table access
      tableAccessStrategies =
          EPStatementStartMethodHelperTableAccess.attachTableAccess(
              services, agentInstanceContext, statementSpec.getTableNodes());
    } catch (RuntimeException ex) {
      StopCallback stopCallback =
          StatementAgentInstanceUtil.getStopCallback(stopCallbacks, agentInstanceContext);
      StatementAgentInstanceUtil.stopSafe(stopCallback, statementContext);
      throw ex;
    }

    StatementAgentInstanceFactoryOnTriggerResult onTriggerResult =
        new StatementAgentInstanceFactoryOnTriggerResult(
            view,
            null,
            agentInstanceContext,
            aggregationService,
            subselectStrategies,
            optPatternRoot,
            tableAccessStrategies,
            activationResult);
    if (statementContext.getStatementExtensionServicesContext() != null) {
      statementContext
          .getStatementExtensionServicesContext()
          .contributeStopCallback(onTriggerResult, stopCallbacks);
    }

    log.debug(".start Statement start completed");
    StopCallback stopCallback =
        StatementAgentInstanceUtil.getStopCallback(stopCallbacks, agentInstanceContext);
    onTriggerResult.setStopCallback(stopCallback);

    return onTriggerResult;
  }