52 lines
2.5 KiB
PL/PgSQL
52 lines
2.5 KiB
PL/PgSQL
-- SPDX-License-Identifier: LicenseRef-ConusAI-Template-1.0
|
|
create table "kit_live_change_log" (
|
|
"org_id" uuid not null,
|
|
"txid" xid8 not null default pg_current_xact_id(),
|
|
"seq" bigint generated always as identity,
|
|
"entity" text not null,
|
|
"entity_id" text not null,
|
|
"op" "char" not null,
|
|
"version" bigint,
|
|
"workspace_id" uuid,
|
|
"project_id" uuid,
|
|
"at" timestamptz not null default now(),
|
|
constraint "kit_live_change_log_op_known" check ("op" in ('u', 'd')),
|
|
primary key ("org_id", "txid", "seq")
|
|
);
|
|
|
|
create index "kit_live_change_log_at_idx" on "kit_live_change_log" ("at");
|
|
|
|
alter table "kit_live_change_log" enable row level security;
|
|
|
|
alter table "kit_live_change_log" force row level security;
|
|
|
|
create policy "kit_live_change_log_tenant" on "kit_live_change_log" using ("org_id" = nullif(current_setting('app.org_id', true), '')::uuid) with check ("org_id" = nullif(current_setting('app.org_id', true), '')::uuid);
|
|
|
|
create function "kit_live_capture"() returns trigger language plpgsql as $$
|
|
begin
|
|
if TG_OP = 'DELETE' then
|
|
insert into "kit_live_change_log" ("org_id", "entity", "entity_id", "op", "version", "workspace_id", "project_id")
|
|
select (r->>'org_id')::uuid, TG_ARGV[0], r->>'id', 'd', null,
|
|
nullif(r->>'workspace_id', '')::uuid, nullif(r->>'project_id', '')::uuid
|
|
from (select to_jsonb(o) as r from old_rows o) changed;
|
|
perform pg_notify('kit_live', org) from (select distinct to_jsonb(o)->>'org_id' as org from old_rows o) orgs;
|
|
else
|
|
insert into "kit_live_change_log" ("org_id", "entity", "entity_id", "op", "version", "workspace_id", "project_id")
|
|
select (r->>'org_id')::uuid, TG_ARGV[0], r->>'id', 'u', (r->>'version')::bigint,
|
|
nullif(r->>'workspace_id', '')::uuid, nullif(r->>'project_id', '')::uuid
|
|
from (select to_jsonb(n) as r from new_rows n) changed;
|
|
perform pg_notify('kit_live', org) from (select distinct to_jsonb(n)->>'org_id' as org from new_rows n) orgs;
|
|
end if;
|
|
return null;
|
|
end
|
|
$$;
|
|
|
|
do $$ begin execute format('create policy "kit_live_change_log_prune" on "kit_live_change_log" for delete to %I using (true)', current_user); end $$;
|
|
|
|
do $$ begin execute format('create policy "kit_live_change_log_prune_read" on "kit_live_change_log" for select to %I using (true)', current_user); end $$;
|
|
|
|
create function "kit_live_prune"(hours integer) returns bigint language sql security definer set search_path = public as $$
|
|
with gone as (delete from "kit_live_change_log" where "at" < now() - make_interval(hours => hours) returning 1)
|
|
select count(*) from gone
|
|
$$;
|