postgresql函数:定期删除模式下指定天数前的表数据及分区物理表
CREATE OR REPLACE FUNCTION core.delete_records_from_schema_older_than(p_days_old integer, p_schema_name text)
RETURNS void LANGUAGE plpgsql AS $$
DECLARE
v_table_name text;
v_partition_table_name text;
v_delete_sql text;
v_partition_delete_sql text;
BEGIN
-- 删除主表数据
FOR v_table_name IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = p_schema_name
AND table_type = 'BASE TABLE'
LOOP
v_delete_sql := format('DELETE FROM %I.%s WHERE c_time < now() - interval ''%s days''', p_schema_name, v_table_name, p_days_old);
EXECUTE v_delete_sql;
END LOOP;
-- 删除分区表数据
FOR v_partition_table_name IN
SELECT table_name
FROM information_schema.tables
WHERE table_schema = p_schema_name
AND table_type = 'PARTITIONED TABLE'
LOOP
v_partition_delete_sql := format('ALTER TABLE %I.%s DELETE WHERE c_time < now() - interval ''%s days''', p_schema_name, v_partition_table_name, p_days_old);
EXECUTE v_partition_delete_sql;
END LOOP;
END;
$$;
这段代码修复了原始代码中的问题,并使用了format
函数来创建动态SQL语句,这样可以避免SQL注入的风险,并且使得代码更加健壮和可维护。此外,分区表的删除操作也从DROP TABLE
更改为了ALTER TABLE DELETE WHERE
,这是因为直接删除分区表不仅不常见,而且在大多数情况下是不可能的。
评论已关闭