Triggers, Views, Sequences & Types
Before/after statement and row triggers, views, materialized views, continuous aggregates, sequences, and custom schema objects.
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:
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#
| Granularity | Syntax | When it fires | Pseudo-records available |
|---|---|---|---|
| Statement-level | Omit for each row | Once per statement | None |
Row-level (insert) | for each row | Once per inserted row | new.<field> |
Row-level (update) | for each row | Once per updated row | old.<field> and new.<field> |
Row-level (delete) | for each row | Once per deleted row | old.<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:
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> >= 0constraints (or multi-step procedural logic inside Stored Procedures), and reservebeforerow triggers for canonicalization and computed column stamping vianew | set { ... }.
Strict Engine Guardrails#
SpydDB enforces static and runtime safety rules on triggers so reactive side effects stay deterministic:
- Scoped
new/oldbindings: Referencingnewin adeletetrigger,oldin aninserttrigger, or either record in a statement-level trigger is rejected at DDL time. new | setrestrictions: Modifyingnewvianew | set { ... }is permitted only in row-levelbefore insertandbefore updatetriggers, and assignments insidenew | setcannot run nested subqueries.- No positional query parameters: Trigger bodies cannot reference
$1or named external parameters. - Self-target cycle prevention: A trigger on collection
Cis forbidden from writing back intoCitself, eliminating infinite self-trigger loops. - Bounded cross-collection recursion & atomic rollback: Triggers on
Awriting toBmay fireB'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:
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:
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:
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 aggtime 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:
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:
-- 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.