Triggers & Events

Define database triggers, event schedulers, and change streams for automated data handling.

Overview

Triggers automatically execute code in response to database events like INSERT, UPDATE, and DELETE. Prax provides a unified API for defining triggers across all supported databases.

Feature PostgreSQL MySQL SQLite MSSQL MongoDB
Row-Level Triggers Change Streams
Statement-Level
INSTEAD OF
Event Scheduler SQL Agent Atlas Triggers

Creating Triggers

Use the Trigger::builder() API to create triggers.

Conditional Triggers

Add conditions to fire triggers only when specific criteria are met.

INSTEAD OF Triggers

Replace the default action for views, enabling them to be updatable.

Built-in Patterns

Common trigger patterns are available out of the box.

Audit Trail

Tracks all changes with who, what, when, and before/after values

Soft Delete

Converts DELETE to UPDATE, preserving data with a deleted_at timestamp

Updated At

Automatically updates a timestamp column on any modification

Validation

Enforce business rules with custom check constraints

MongoDB Change Streams

Change streams provide real-time notifications of data changes in MongoDB. They're the MongoDB equivalent of triggers.

Note: Change streams require a MongoDB replica set. Save resume tokens to recover from disconnections without missing events.

MySQL Event Scheduler

Schedule recurring or one-time tasks with MySQL's EVENT system.

Important: Ensure the event scheduler is enabled: SET GLOBAL event_scheduler = ON;

MSSQL SQL Server Agent

Define SQL Server Agent jobs for scheduled tasks with multiple steps.

MongoDB Atlas Triggers

Cloud-based triggers that run Atlas Functions in response to database changes.

Trigger Migrations

Version control your triggers alongside your schema.

Best Practices

Keep Triggers Fast

Triggers run synchronously within the transaction. Long-running operations should be handled asynchronously via queues or change streams.

Avoid Cascading Triggers

Be careful with triggers that modify tables with their own triggers. This can create hard-to-debug infinite loops.

Test Trigger Behavior

Triggers can have subtle interactions with transactions and constraints. Always test with realistic data volumes.

Document Side Effects

Triggers introduce "invisible" behavior. Document all triggers clearly so developers know what happens automatically.