Skip to content

Declarative trigger guards in schema YAML (SQLite + PostgreSQL)#85

Open
MelbourneDeveloper wants to merge 5 commits into
mainfrom
fixes
Open

Declarative trigger guards in schema YAML (SQLite + PostgreSQL)#85
MelbourneDeveloper wants to merge 5 commits into
mainfrom
fixes

Conversation

@MelbourneDeveloper

Copy link
Copy Markdown
Collaborator

TLDR

Adds declarative trigger guards to schema YAML — per-table triggers: with LQL raiseWhen predicates that become native BEFORE/AFTER row triggers on SQLite and PostgreSQL, diffed by name exactly like RLS policies. Closes #82.

What Was Added?

  • Model + YAML: TriggerDefinition (Name, Timing, Events, ForEachRow, raiseWhen LQL, ErrorMessage) on TableDefinition.Triggers, with TriggerTiming/TriggerEvent enums and round-trippable YAML (defaults timing: Before, forEachRow: true omitted on write).
  • Diff: SchemaDiff.Triggers — triggers missing from the database produce CreateTriggerOperation; triggers removed from YAML produce DropTriggerOperation only under MigrationOptions.AllowDestructive (logged at Warning), mirroring RLS policy semantics.
  • Guard LQL transpiler (RlsPredicateTranspiler.TriggerGuard.cs): supports old.<col>/new.<col> row references, and/or composition, and [not] exists(pipeline) subqueries. On Postgres, exists-pipeline SQL gets an identifier-quoting pass so mixed-case columns survive case folding. The internal __TRG_ sentinel token is reserved and rejected in user predicates.
  • SQLite emission/inspection: one trigger per event named usr_{event}_{trigger}_{table} using SELECT RAISE(ABORT, '<message>') WHERE <predicate>; read back from sqlite_master and grouped by base name so re-diff is a no-op.
  • Postgres emission/inspection: plpgsql guard function {table}_{trigger}_trgfn + trigger usr_{trigger}. RAISE EXCEPTION USING MESSAGE avoids % format interpretation; the dollar-quote tag is chosen to never occur in the body; identifiers over PostgreSQL's 63-byte limit fail loudly. The inspector reads only usr_-prefixed triggers, so unmanaged triggers (e.g. Sync change tracking) are never dropped by destructive runs, and *_trgfn guard functions are excluded from support-function read-back.
  • Validation (all fail the migration loudly at DDL-gen time): forEachRow: false rejected (guards are row-level on every platform); old. references with an Insert event and new. references with a Delete event rejected.
  • Shared test infrastructure: SqliteTestDb/PostgresTestDb helpers extracted from the RLS tests (moved, not copied).

What Was Changed or Deleted?

  • SqliteRlsSchemaInspector refactored onto the new shared SqliteTriggerNames parsing (behaviour unchanged).
  • SqliteRlsMigrationTests/PostgresRlsE2ETests now use the shared test-db helpers (pure moves; assertions unchanged).
  • MigrationRunner.IsDestructive now includes DropTriggerOperation.
  • PostgresSupportSchemaInspector excludes %_trgfn functions from function read-back (they are owned by the trigger lifecycle).
  • .gitignore: added .deslop-cache/.
  • Lql/LqlExtension/src/test/runTest.ts: the VS Code test host now uses a short --user-data-dir under the OS temp dir. The default dir lives under the repo, and on deep checkouts its IPC socket path exceeds the macOS 103-char AF_UNIX limit (listen EINVAL), making make ci fail on macOS. No test behaviour or assertions changed.

How Do The Automated Tests Prove It Works?

make ci (lint + test + build) is fully green locally, including all 533 Migration tests, Rust coverage 95.27% ≥ 95%, and the 70 VS Code extension tests. Highlights:

  • SqliteDeclarativeTriggerTests (real temp-file SQLite): deleting/demoting the last owner of a tenant fails with the declared errorMessage and the row survives; succeeds when a second owner exists; guard is tenant-scoped; re-diff after apply yields zero operations; removing the trigger from YAML is a no-op without allowDestructive and drops it with; old.-on-Insert, forEachRow: false, and reserved __TRG_ predicates fail loudly.
  • PostgresDeclarativeTriggerE2ETests (Testcontainers, real Postgres): same last-owner guard end-to-end; PgTriggerGuard_PascalCaseIdentifiers_EnforcedAtRuntime proves mixed-case columns work at trigger-fire time; PgTrigger_DestructiveRerun_PreservesUnmanagedTriggerAndGuardFunction proves unmanaged triggers survive destructive re-runs and the guard keeps enforcing.
  • PostgresTriggerDdlTests: dollar-quote tag collision picks an alternate tag; trigger objects get the usr_ managed prefix; identifiers over 63 bytes throw with a clear message.
  • TriggerYamlSerializerTests: YAML round-trip preserves the declaration and omits defaults.

Spec / Doc Changes

New docs/specs/declarative-triggers-spec.md with hierarchical spec IDs ([MIG-TRIGGER-YAML], [MIG-TRIGGER-MODEL], [MIG-TRIGGER-DIFF], [MIG-TRIGGER-GUARD-LQL], [MIG-TRIGGER-SQLITE], [MIG-TRIGGER-PG]), referenced from the implementing code and tests.

Follow-up filed as #84: the core LQL→PostgreSQL transpiler emits unquoted identifiers in pipeline SQL (latent in the RLS exists() path); this PR works around it for trigger guards via a quoting pass.

Breaking Changes

  • None — triggers: is a new optional key; existing schemas are unaffected.

🤖 Generated with Claude Code

MelbourneDeveloper and others added 5 commits July 2, 2026 18:06
The default user-data-dir under the repo produced an IPC socket path over
the macOS 103-char AF_UNIX limit (listen EINVAL), failing make ci locally.
The test host now uses a short dir under the OS temp folder. The trigger
guard tests raised Migration.Core coverage, ratcheting its threshold 86->87.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Declarative trigger support in schema.yaml (BEFORE INSERT/UPDATE/DELETE guards)

1 participant