Search
ctrl/
Ask AI
Light
Dark
System

Triggers

This section describes the SDL declarations pertaining to triggers.

Declare a trigger that inserts a Log object for each new User object:

Copy
type User {
  required name: str;

  trigger log_insert after insert for each do (
    insert Log {
      action := 'insert',
      target_name := __new__.name
    }
  );
}

Declare a trigger that inserts a Log object conditionally when an update query makes a change to a User object:

Copy
type User {
  required name: str;

  trigger log_update after update for each
  when (<json>__old__ {**} != <json>__new__ {**})
  do (
    insert Log {
      action := 'update',
      target_name := __new__.name,
      change := __old__.name ++ '->' ++ __new__.name
    }
  );
}

Define a new trigger corresponding to the more explicit DDL commands.

type type-name "{"
  trigger name
  after
    {insert | update | delete} [, ...]
    for {each | all}
    [ when (condition) ]
    do expr
"}"

This declaration defines a new trigger with the following options:

type-name

The name (optionally module-qualified) of the type to be triggered on.

name

The name of the trigger.

insert | update | delete [, ...]

The query type (or types) to trigger on. Separate multiple values with commas to invoke the same trigger for multiple types of queries.

each

The expression will be evaluated once per modified object. __new__ and __old__ in this context within the expression will refer to a single object.

all

The expression will be evaluted once for the entire query, even if multiple objects were modified. __new__ and __old__ in this context within the expression refer to sets of the modified objects.

when (condition)

Optionally provide a condition for the trigger. If the condition is met, the trigger will run. If not, the trigger is skipped.

expr

The expression to be evaluated when the trigger is invoked.

The trigger name must be distinct from that of any existing trigger on the same type.