Skip to content

Commit d5ff668

Browse files
[+] add admin.drop_source_partitions, closes #1340 (#1364)
* [+] implement admin.drop_source_partitions for proactive decommission cleanup, fixes #1340 * align drop_source_partitions with drop_old_time_partitions pattern - Use oid::regclass for schema-qualified identifiers instead of relname with hardcoded schema prefixes. - Remove unnecessary CASCADE from DROP TABLE after DETACH. - Check parent table comment (pgwatch-generated-metric-lvl) instead of requiring a separate comment on each child partition. - Trim verbose inline comments. - Move to admin_functions.sql --------- Co-authored-by: Pavlo Golub <[email protected]>
1 parent 06347e7 commit d5ff668

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

internal/sinks/sql/admin_functions.sql

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,53 @@ BEGIN
167167
END;
168168
$SQL$ LANGUAGE plpgsql;
169169

170+
/*
171+
drop_source_partitions removes all metric data for a decommissioned source
172+
p_source_name - the dbname (source) whose partitions should be dropped
173+
Returns the number of patritions dropped
174+
*/
175+
CREATE OR REPLACE FUNCTION admin.drop_source_partitions(p_source_name text)
176+
RETURNS int AS
177+
$SQL$
178+
DECLARE
179+
r record;
180+
v_dropped_count int := 0;
181+
BEGIN
182+
FOR r IN
183+
SELECT
184+
c.oid::regclass::text AS partition_name,
185+
parent.oid::regclass::text AS metric_table,
186+
parent.relname AS metric_name
187+
FROM pg_catalog.pg_class c
188+
JOIN pg_catalog.pg_inherits i ON c.oid = i.inhrelid
189+
JOIN pg_catalog.pg_class parent ON parent.oid = i.inhparent
190+
WHERE c.relnamespace = 'subpartitions'::regnamespace
191+
AND pg_catalog.obj_description(parent.oid, 'pg_class') = 'pgwatch-generated-metric-lvl'
192+
AND (regexp_match(
193+
pg_catalog.pg_get_expr(c.relpartbound, c.oid),
194+
E'FOR VALUES IN \\(''(.+?)''\\)'
195+
))[1] = p_source_name
196+
LOOP
197+
-- advisory lock matching ensure_partition_metric_dbname_time
198+
PERFORM pg_advisory_xact_lock(
199+
regexp_replace(md5(r.metric_name), E'\\D', '', 'g')::varchar(10)::int8
200+
);
201+
202+
RAISE NOTICE 'detaching partition: % from %', r.partition_name, r.metric_table;
203+
EXECUTE 'ALTER TABLE ' || r.metric_table || ' DETACH PARTITION ' || r.partition_name;
204+
205+
RAISE NOTICE 'dropping partition: %', r.partition_name;
206+
EXECUTE 'DROP TABLE IF EXISTS ' || r.partition_name;
207+
208+
v_dropped_count := v_dropped_count + 1;
209+
END LOOP;
210+
211+
DELETE FROM admin.all_distinct_dbname_metrics WHERE dbname = p_source_name;
212+
213+
RETURN v_dropped_count;
214+
END;
215+
$SQL$ LANGUAGE plpgsql;
216+
170217
/*
171218
maintain_unique_sources() maintains a mapping of unique sources in each metric table
172219
in admin.all_distinct_dbname_metrics. This is used to avoid listing the same source

0 commit comments

Comments
 (0)