-- 设置数据库会话参数以提高兼容性和稳定性
ALTER SYSTEM SET statement_timeout = '0';
ALTER SYSTEM SET lock_timeout = '0';
ALTER SYSTEM SET idle_in_transaction_session_timeout = '0';
-- 重建物化视图(如果有)
DO
$$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT schemaname, matviewname FROM pg_matviews WHERE schemaname NOT IN ('pg_catalog', 'information_schema') LOOP
EXECUTE format('DROP MATERIALIZED VIEW %I.%I', r.schemaname, r.matviewname);
EXECUTE format('CREATE MATERIALIZED VIEW %I.%I AS ' || pg_get_viewdef(format('%I.%I', r.schemaname, r.matviewname)::regclass, true), r.schemaname, r.matviewname);
END LOOP;
END
$$;
-- 更新所有物化视图统计信息
UPDATE pg_stat_user_tables SET seq_scan = 0, seq_tup_read = 0 WHERE tablename IN (SELECT matviewname FROM pg_matviews WHERE schemaname NOT IN ('pg_catalog', 'information_schema'));
-- 重建所有索引
DO
$$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT indexname, tablename, schemaname FROM pg_indexes WHERE schemaname NOT IN ('pg_catalog', 'information_schema') AND tablename NOT LIKE 'pg_toast%' LOOP
EXECUTE format('DROP INDEX %I.%I', r.schemaname, r.indexname);
EXECUTE format('CREATE INDEX %I ON %I.%I USING ' || pg_indexes.indexdef::text || ' WHERE ' || pg_index.indexdef::text, r.indexname, r.schemaname, r.tablename);
END LOOP;
END
$$;
-- 重建所有外键约束
DO
$$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT conname, connamespace, contable, condeferrable, condeferred, convalidated, confupdtype, confdeltype, confmatchtype, conkey, confkey, conislocal, coninhcount FROM pg_constraint WHERE contype = 'f' AND connamespace NOT IN (11, 10) LOOP
EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', r.connamespace, r.contable, r.conname);
EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%s) REFERENCES %I(%s)%s%s%s%s',
r.connamespace, r.contable, r.conname,
array_to_string(array_agg(pg_attribute.attname) within group (order by pg_attribute.attnum), ', '),
string_to_array(split_part(r.confrelid::text, ' ', 2), '/')[2],
评论已关闭