Triggers, Views, Sequences & Types

Before/after statement and row triggers, views, materialized views, continuous aggregates, sequences, and custom schema objects.

3 min read Programmability

Beyond inline pipelines and callable stored procedures, SpydDB stores reactive and structural catalog objects directly inside the transactional catalog: triggers, views, materialized views, continuous aggregates, atomic sequences, and user-defined composite types.


1. Transactional Triggers (CREATE TRIGGER)#

Triggers execute automatically whenever an insert, update, or delete mutates a target collection. Every trigger executes inside the same ACID transaction as the originating write statement.

Syntax#

In SpydQL, a trigger attaches a single SpydQL pipeline or DML statement directly after as:

sql
create trigger <name>
before | after insert | update | delete
on <collection>
[for each row]
as <single_spydql_statement>

-- Remove a trigger
drop trigger [if exists] <name>;

Statement-Level vs. Row-Level Execution#

GranularitySyntaxWhen it firesPseudo-records available
Statement-levelOmit for each rowOnce per statementNone
Row-level (insert)for each rowOnce per inserted rownew.<field>
Row-level (update)for each rowOnce per updated rowold.<field> and new.<field>
Row-level (delete)for each rowOnce per deleted rowold.<field>

Normalizing Rows (BEFORE ... FOR EACH ROW + new | set) & Audit Logging#

A row-level before insert or before update trigger can inspect and rewrite fields on new before unique constraints, check constraints, foreign keys, and secondary indexes are updated, while after triggers append immutable audit logs or cascade side effects:

sql
create collection accounts {
  id: u64 primary,
  email: string(160) unique,
  balance_cents: i64 check row.balance_cents >= 0,
  version: u64
};

create collection account_audit {
  id: u64 primary auto_increment,
  account_id: u64,
  kind: text,
  delta_cents: i64
};

-- Canonicalize email addresses before unique index lookup and persistence
create trigger normalize_account_email
before insert on accounts for each row as
  new | set { email: lower(trim(email)) };

-- Increment version stamp atomically on update
create trigger touch_account_version
before update on accounts for each row as
  new | set { version: old.version + 1 };

-- Append immutable audit trail after each update
create trigger audit_balance_change
after update on accounts for each row as
  account_audit | insert {
    account_id: new.id,
    kind: "balance_update",
    delta_cents: new.balance_cents - old.balance_cents
  };

Tip: Express unconditional domain invariants directly with collection check row.<field> >= 0 constraints (or multi-step procedural logic inside Stored Procedures), and reserve before row triggers for canonicalization and computed column stamping via new | set { ... }.

Strict Engine Guardrails#

SpydDB enforces static and runtime safety rules on triggers so reactive side effects stay deterministic:

  1. Scoped new / old bindings: Referencing new in a delete trigger, old in an insert trigger, or either record in a statement-level trigger is rejected at DDL time.
  2. new | set restrictions: Modifying new via new | set { ... } is permitted only in row-level before insert and before update triggers, and assignments inside new | set cannot run nested subqueries.
  3. No positional query parameters: Trigger bodies cannot reference $1 or named external parameters.
  4. Self-target cycle prevention: A trigger on collection C is forbidden from writing back into C itself, eliminating infinite self-trigger loops.
  5. Bounded cross-collection recursion & atomic rollback: Triggers on A writing to B may fire B's triggers up to a bounded recursion depth. If any trigger fails a constraint or exceeds the depth limit, the entire originating DML statement and all prior trigger writes roll back together atomically.

2. Views & Materialized Views#

Standard Views#

A standard view stores a named read-only pipeline in the catalog and expands it against live MVCC snapshots on every query:

sql
create or replace view active_vip_accounts as
  accounts
  | where active == true and tier == "vip"
  | pick id, email, balance_cents;

active_vip_accounts | sort balance_cents desc | take 25;

drop view if exists active_vip_accounts;

Materialized Views & Incremental Refresh#

Materialized views persist the computed result on disk for sub-millisecond analytical reads and update on demand with refresh materialized view:

sql
create or replace materialized view daily_revenue as
  orders
  | group by region
  | agg count() as orders, sum(total_cents) as gross;

-- Incremental materialized views track a key column directly
create materialized view inc_order_totals incremental on id as
  orders | where total_cents > 0 | pick id, region, total_cents;

-- Rebuild snapshot atomically from source data
refresh materialized view daily_revenue;

-- Query materialized results directly
daily_revenue | sort gross desc;

drop materialized view if exists daily_revenue;

3. Continuous Aggregates#

Continuous aggregates automatically keep time-series rollups fresh on a background schedule using the refresh every <duration> stage inside create continuous agg:

sql
create collection ca_events {
  id: u64 primary,
  at: timestamp,
  amount: i64
};

create continuous agg ca_totals from ca_events {
  | group by at
  | agg count() as n, sum(amount) as total
  | refresh every 20ms
};

-- Query like any collection; survives database restart
ca_totals | sort at desc | take 50;

drop continuous agg if exists ca_totals;
  • The refresh interval must be a positive duration (10ms, 5s, 1m, etc.); zero or negative intervals are rejected when creating the object.
  • Initial population runs immediately at create continuous agg time so subsequent queries see consistent baseline rows before the background refresh scheduler ticks.

4. Atomic Sequences (CREATE SEQUENCE / nextval)#

Sequences provide persistent, crash-safe, monotonically increasing u64 identifiers across restarts without requiring table scans:

sql
create sequence order_seq;

-- Top-level statement invocation
nextval order_seq;

-- Remove when no longer needed
drop sequence if exists order_seq;

For inline column generation on tables, see Schemas & Data Types for auto_increment primary keys as well as SQL CREATE SEQUENCE compatibility.


5. Named Composite Types (CREATE TYPE)#

Named composite types define reusable structured record schemas that can be nested inside collections, arrays, and other composite types:

sql
-- Schema-qualified or default-schema composite definition
create type address_t as {
  street: text,
  city: text,
  postal_code: string(16)
};

create type customer_profile_t as {
  primary_address: address_t,
  tags: text[]
};

create collection customers {
  id: u64 primary,
  profile: customer_profile_t
};

customers | insert {
  id: 1,
  profile: {
    primary_address: { street: "100 Main St", city: "Austin", postal_code: "78701" },
    tags: ["enterprise", "annual"]
  }
};

-- Filter directly using nested dot notation and 1-based array indexing
customers
| where profile.primary_address.city == "Austin" and profile.tags[1] == "enterprise"
| pick id, profile.primary_address.postal_code;

drop type if exists customer_profile_t;

Empty composite definitions ({}), duplicate field names, built-in type shadowing (for example naming a type text), and missing referenced types are rejected immediately at DDL time.