~hacktivista/pglr

a2384cdbdeb1035f7c47eff904c9b8ccfeb0063d — Felix Freeman 29 days ago c245ef0
Add dendrite_sync stored procedure
1 files changed, 36 insertions(+), 0 deletions(-)

A contrib/dendrite_sync.sql
A contrib/dendrite_sync.sql => contrib/dendrite_sync.sql +36 -0
@@ 0,0 1,36 @@
-- Copyright 2021 Felix Freeman <libsys@hacktivista.org>
--
-- This file is part of "pglr" and licensed under the terms of the GNU General
-- Public License version 3. You should have received a copy of this license
-- along with the software. If not, see <https://www.gnu.org/licenses/>.

-- Dendrite shares syncapi_stream_ids sequence between tables
-- Run this after pglr_seq_sync
CREATE OR REPLACE PROCEDURE
    dendrite_sync(replicas INTEGER, this_replica INTEGER) AS $$
DECLARE
    cur_seq BIGINT; -- current sequence
    next_seq BIGINT; -- next sequence
BEGIN
    LOCK TABLE syncapi_account_data_type IN EXCLUSIVE MODE;
    LOCK TABLE syncapi_output_room_events IN EXCLUSIVE MODE;
    LOCK TABLE syncapi_invite_events IN EXCLUSIVE MODE;
    LOCK TABLE syncapi_peeks IN EXCLUSIVE MODE;

    SELECT MAX(id) FROM (
        SELECT id FROM syncapi_account_data_type
        UNION SELECT id FROM syncapi_output_room_events
        UNION SELECT id FROM syncapi_invite_events
        UNION SELECT id FROM syncapi_peeks
    ) syncapi_stream_ids
    INTO cur_seq;

    next_seq := cur_seq - MOD((cur_seq - 1), replicas) + this_replica
        - 1 + replicas;

    PERFORM SETVAL('syncapi_stream_id', next_seq, false);

    RAISE NOTICE 'syncapi_stream_id => %', next_seq;
    COMMIT;
END;
$$ LANGUAGE plpgsql;