No description
  • PLpgSQL 94.6%
  • Nix 5.2%
  • Makefile 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-11-15 19:31:35 +01:00
benchmarks test: Benchmarks 2026-10-27 19:11:23 +01:00
sql feat: Use SECURITY DEFINER to allow tracking changes without explicit GRANTs 2026-10-31 06:47:05 +01:00
tests test: Composite primary keys 2026-10-31 09:38:50 +01:00
.envrc chore: Init repo with nix flake and PostgreSQL extension set up 2026-10-26 17:19:58 +01:00
.gitignore chore: Init repo with nix flake and PostgreSQL extension set up 2026-10-26 17:19:58 +01:00
flake.lock chore: Flake update + pg_json_patch binary cache 2026-11-15 19:31:35 +01:00
flake.nix chore: Flake update + pg_json_patch binary cache 2026-11-15 19:31:35 +01:00
Makefile chore: Init repo with nix flake and PostgreSQL extension set up 2026-10-26 17:19:58 +01:00
pg_chronicle.control fix: Missed flagging extension untrusted when setting SECURITY DEFINER 2026-10-31 12:25:24 +01:00
README.md docs: README 2026-10-31 09:34:32 +01:00

pg_chronicle

pg_chronicle is a PostgreSQL extension that records row-level changes from any table into an event log, using pg_json_patch to store compact JSON (RFC 6902) deltas. It supports time-travel queries, point-in-time restore, periodic snapshotting, schema versioning, and foreign-key-aware cascade restore.

Installation

Via Nix flake

inputs.pg-chronicle.url = "git+https://forgejo.920301.xyz/dan/pg_chronicle";

The extension requires pg_json_patch (declared in the control file).

Via PGXS

make && make install

Then in your database:

CREATE EXTENSION pg_chronicle CASCADE;

By default, the extension installs into the chronicle schema. To install into a different schema:

CREATE SCHEMA my_schema;
CREATE EXTENSION pg_chronicle SCHEMA my_schema CASCADE;

Basic usage

Attach a table

CREATE TABLE orders (
    order_id   bigint PRIMARY KEY,
    customer_id bigint NOT NULL,
    status     text NOT NULL,
    total      numeric(12,2) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders VALUES
    (1, 101, 'pending',  49.99, now()),
    (2, 102, 'shipped', 120.00, now());

SELECT chronicle.attach('orders'::regclass);

attach backfills a snapshot event for every existing row and installs a generic AFTER INSERT/UPDATE/DELETE trigger. A primary key (or explicit key columns) is required to identify rows:

SELECT chronicle.attach('orders'::regclass, ARRAY['order_id'], 0);  -- snapshot_every = 0 (off)

Detach

SELECT chronicle.detach('orders'::regclass);  -- keeps historical data

Time travel

-- as jsonb
SELECT * FROM chronicle.as_of('orders'::regclass, p_steps => 3);

-- as the table's row type (filterable)
SELECT * FROM chronicle.as_of_typed('orders'::regclass, NULL::orders, p_steps => 3)
WHERE total > 10;

-- cursors: p_at (timestamptz), p_txid, p_event_id, p_steps
SELECT * FROM chronicle.as_of('orders'::regclass, p_txid => 12345);

Create a typed view for ad-hoc querying:

SELECT chronicle.create_as_of_view('orders'::regclass, 'public.orders_hist', p_steps => 3);
SELECT * FROM public.orders_hist WHERE total > 10;
SELECT chronicle.drop_as_of_view('public.orders_hist');

Restore

-- full restore to a cursor
SELECT chronicle.restore_table('orders'::regclass, p_steps => 3);

-- partial: only certain rows
SELECT chronicle.restore_table('orders'::regclass, p_steps => 3,
  p_row_keys => ARRAY['{"order_id":1}'::jsonb]);

-- partial: only certain columns
SELECT chronicle.restore_table('orders'::regclass, p_steps => 3,
  p_row_keys => ARRAY['{"order_id":1}'::jsonb],
  p_columns => ARRAY['total']);

-- cascade foreign keys (restore missing parents automatically)
SELECT chronicle.restore_table('child'::regclass, p_steps => 3, p_cascade => true);

Snapshots

Snapshots bound replay cost. snapshot_every = 0 disables automatic snapshots (the default).

SELECT chronicle.snapshot_table('orders'::regclass);  -- manual
SELECT chronicle.attach('orders'::regclass, NULL, 100); -- every 100th event

Schema changes

SELECT chronicle.record_schema_change('orders'::regclass, NULL, 'add column bar');
SELECT * FROM chronicle.schema_history('orders'::regclass);

-- create a composite type matching an older schema version
SELECT chronicle.create_type_for_version('orders'::regclass, 1, 'orders_v1');
SELECT * FROM chronicle.as_of_typed('orders'::regclass, NULL::orders_v1, p_steps => 10);

Automatic DDL tracking (requires superuser):

SELECT chronicle.enable_ddl_tracking();

Permissions and RLS

Capture runs as SECURITY DEFINER, so users performing DML on an attached table do not need access to the chronicle schema. Management functions (attach, detach, snapshot_table, record_schema_change) are also SECURITY DEFINER.

Querying history

as_of / as_of_typed run as the invoker, so users need:

GRANT USAGE ON SCHEMA chronicle TO my_role;
GRANT SELECT ON chronicle.events, chronicle.streams, chronicle.tables TO my_role;

Immutability and privilege guidance

The event log is append-only. Grant privileges accordingly:

  • chronicle.events: SELECT and INSERT only. Never grant UPDATE or DELETE — events are immutable.
  • chronicle.streams: SELECT and INSERT (and UPDATE of version by the extension). Never grant DELETE — streams are immutable.
  • chronicle.tables: SELECT (and management via the extension's SECURITY DEFINER functions).

Row-Level Security

RLS on the source table is not automatically applied to historical queries, because as_of reads from chronicle.events. To enforce the same restrictions, enable RLS on chronicle.events and add a policy that mirrors source-table visibility, e.g.:

ALTER TABLE chronicle.events ENABLE ROW LEVEL SECURITY;
CREATE POLICY events_rls ON chronicle.events FOR SELECT
USING (EXISTS (
    SELECT 1 FROM chronicle.streams s
    JOIN my_table t ON (s.row_key->>'id')::int = t.id
    WHERE s.stream_id = chronicle.events.stream_id
));

Because as_of is SECURITY INVOKER, the policy is evaluated as the calling user and the source table's own RLS applies inside the subquery.

Do not mark as_of/as_of_typed as SECURITY DEFINER, or RLS policies will be evaluated as the extension owner and bypass restrictions.

Metadata GUC

Set per-session metadata that is recorded on every event:

SET LOCAL chronicle.metadata = '{"source":"app","request_id":42}';

Foreign keys

Use p_cascade => true on restore_table to automatically restore missing parent rows (requires the parent table to be attached to pg_chronicle). Circular foreign keys raise an error.

Performance

  • Snapshots provide large speedups for historical queries far from the present.
  • Use snapshot_every to tune the snapshot frequency.
  • For current-state reads, query the base table directly rather than as_of(..., p_steps => 0).

License

See repository.