-- +goose Up -- Deleting an organization removes it at once but leaves its check results -- and aggregates, which carry no foreign key, to the background: years of -- results take far longer to delete than a request may last. The purge -- goes a chunk at a time, each in a transaction of its own, so it never -- holds locks for long and resumes where it stopped. CREATE TABLE org_purges ( org_id uuid PRIMARY KEY, requested_at timestamptz NOT NULL DEFAULT now(), -- An API instance purging the organization holds it until then. leased_until timestamptz NOT NULL DEFAULT '-infinity' ); ALTER TABLE org_purges ENABLE ROW LEVEL SECURITY; ALTER TABLE org_purges FORCE ROW LEVEL SECURITY; CREATE POLICY org_purges_system ON org_purges FOR ALL USING (app_scope_system()) WITH CHECK (app_scope_system()); -- +goose StatementBegin -- The chunks holding check data: those of the raw results first, so the -- aggregates' refresh does not materialize again what was purged from them, -- then those of both aggregates, oldest first. Runs with the owner's rights because the application role -- may not reach TimescaleDB's internal schema. CREATE FUNCTION org_check_data_chunks() RETURNS SETOF text LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS $$ SELECT format('%I.%I', c.chunk_schema, c.chunk_name) FROM timescaledb_information.chunks c WHERE (c.hypertable_schema, c.hypertable_name) IN ( SELECT 'public'::name, 'check_results'::name UNION ALL SELECT materialization_hypertable_schema, materialization_hypertable_name FROM timescaledb_information.continuous_aggregates WHERE view_name IN ('check_results_1h', 'check_results_1d')) ORDER BY c.hypertable_name <> 'check_results', c.range_start, 1 $$; -- +goose StatementEnd -- +goose StatementBegin -- Deletes an organization's rows in one chunk of org_check_data_chunks, -- through its hypertable and limited to the chunk's time range, so that -- TimescaleDB handles compressed chunks. Chunks dropped meanwhile, and -- names of anything else, delete nothing. CREATE FUNCTION purge_org_check_chunk(org uuid, chunk text) RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp AS $$ DECLARE r record; n bigint; BEGIN SELECT c.hypertable_schema AS hs, c.hypertable_name AS hn, d.column_name AS col, c.range_start AS lo, c.range_end AS hi INTO r FROM timescaledb_information.chunks c JOIN timescaledb_information.dimensions d ON d.hypertable_schema = c.hypertable_schema AND d.hypertable_name = c.hypertable_name AND d.dimension_number = 1 WHERE format('%I.%I', c.chunk_schema, c.chunk_name) = chunk AND chunk IN (SELECT org_check_data_chunks()); IF NOT FOUND THEN RETURN 0; END IF; EXECUTE format('DELETE FROM %I.%I WHERE org_id = $1 AND %I >= $2 AND %I < $3', r.hs, r.hn, r.col, r.col) USING org, r.lo, r.hi; GET DIAGNOSTICS n = ROW_COUNT; RETURN n; END $$; -- +goose StatementEnd -- +goose Down DROP FUNCTION purge_org_check_chunk(uuid, text); DROP FUNCTION org_check_data_chunks(); DROP TABLE org_purges;