sql_saga
sql_saga · C and PL/pgSQL extension for valid-time temporal tables, temporal foreign keys, history-preserving views, and bulk temporal merge operations.
Overview
PostgreSQL · 18
| Relationships | |
|---|---|
| Requires | btree_gist plpgsql |
Usage
Sources:
sql_saga adds valid-time eras, temporal uniqueness and foreign keys, updatable current/portion views, system-versioned history, and set-based temporal merge operations. Version 1.0 targets PostgreSQL 18 and uses its native WITHOUT OVERLAPS constraints. Use it when an entity must retain non-overlapping historical versions rather than only its latest row.
Core Workflow
Install the btree_gist dependency, define a range-based temporal primary key, and register the table as an era:
Validity uses half-open [) periods. A current row is one whose period contains the current date/time, including a row with a known future end.
Main API
add_era(...)/drop_era(...): register or remove temporal metadata, checks, and synchronization triggers.add_unique_key(...): add natural, primary, or predicated temporal uniqueness.add_foreign_key(...): inspect the participating tables and create a regular-to-temporal or temporal-to-temporal key, with a supporting index by default.add_current_view(...): expose current rows through an updatable view; default delete behavior cuts off validity rather than physically erasing history.add_for_portion_of_view(...): expose SQL:2011-style changes to a selected validity portion.temporal_merge(target_table, source_table, ...): plan and execute set-based inserts, updates, splits, coalescing, and optional deletes from a staging table.add_system_versioning(...): create transaction-time history in addition to valid time.
temporal_merge defaults to non-destructive MERGE_ENTITY_PATCH. Its destructive behavior is controlled separately by delete_mode; the source needs a unique/orderable row_id column by default. The procedure creates session-local pg_temp.temporal_merge_plan and pg_temp.temporal_merge_feedback tables, dropped at transaction end.
Caveats
Temporal history needs a stable entity identifier plus the temporal range in a composite WITHOUT OVERLAPS key. A simple primary key or GENERATED ALWAYS AS IDENTITY prevents storing multiple historical versions; use a compatible composite key and, if needed, GENERATED BY DEFAULT. The extension creates constraints, indexes, triggers, views, helper functions, and metadata, so run registration as the table owner and review every generated object.
temporal_merge is SECURITY INVOKER; table privileges and RLS still apply. Avoid switching roles between calls in one session, because its temporary tables retain their creator’s ownership. Debug GUCs sql_saga.temporal_merge.log_plan, .log_feedback, and .log_sql can expose plans, row feedback, or generated SQL in server logs. Exercise destructive merge/delete modes only after rehearsing them with a transactionally isolated copy.