Skip to content

after-restore.sql

Download after-restore.sql as it is.

after-restore.sql
-- Run once after restoring a backup, before any instance starts:
--
-- psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f after-restore.sql
--
-- A restored database numbers what it stores from where the backup left
-- off, and numbers the events, audit entries and registry changes stored
-- since the backup (lost with the old database) a second time. A reader
-- that pages by a sequence number (`after=<next>` on the events, the audit
-- trail or the sync rows, the same for Time and Attendance's events) holds
-- the highest number it was given, which is past the restored database's,
-- and would skip everything stored under a number it has already seen,
-- silently, until the numbers passed its place.
--
-- This moves each of those sequences to a number nothing can have been
-- given: the time now in microseconds since 1970 (about 1.8e15 in 2026,
-- far under the 9e18 a sequence holds, and under 2^53, which is as far as
-- JSON numbers read by JavaScript are exact), because a database that
-- hands out fewer than a million numbers a second from the day it was
-- made has not passed it. A sequence already past it stays where it is,
-- so running this twice does no harm. Everything stored from here on is
-- numbered above anything a reader was handed before the restore.
SELECT setval('event_seq',
greatest((SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END FROM event_seq),
(extract(epoch FROM clock_timestamp()) * 1000000)::bigint)) AS event_seq;
SELECT setval('attend_event_seq',
greatest((SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END FROM attend_event_seq),
(extract(epoch FROM clock_timestamp()) * 1000000)::bigint)) AS attend_event_seq;
SELECT setval('audit_seq_seq',
greatest((SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END
FROM audit_seq_seq),
(extract(epoch FROM clock_timestamp()) * 1000000)::bigint)) AS audit_seq;
-- A sync group numbers its registry changes in a row of its own.
UPDATE sync_seq SET seq = greatest(seq, (extract(epoch FROM clock_timestamp()) * 1000000)::bigint);