-- 20260778: 从 legacy_public 回填 notifications 到各 active tenant -- 口径:收件人 profiles.branch_code = 目标分公司;平台账号(branch 空) / user_id 空 → 复制到每个 tenant DO $$ DECLARE r RECORD; n INTEGER; BEGIN IF to_regclass('legacy_public.notifications') IS NULL THEN RAISE NOTICE 'legacy_public.notifications missing, skip backfill'; RETURN; END IF; FOR r IN SELECT branch_code, schema_name FROM public.tenant_schema_registry WHERE status = 'active' AND schema_name ~ '^tenant_[a-z0-9_-]{2,30}$' ORDER BY branch_code LOOP IF to_regclass(format('%I.notifications', r.schema_name)) IS NULL THEN PERFORM public._clone_table_structure('legacy_public', r.schema_name, 'notifications'); END IF; EXECUTE format( 'INSERT INTO %I.notifications SELECT n.* FROM legacy_public.notifications n LEFT JOIN public.profiles p ON p.id = n.user_id WHERE p.branch_code IS NOT DISTINCT FROM %L OR p.branch_code IS NULL OR n.user_id IS NULL ON CONFLICT DO NOTHING', r.schema_name, r.branch_code ); GET DIAGNOSTICS n = ROW_COUNT; RAISE NOTICE 'backfill notifications % -> % rows=%', r.branch_code, r.schema_name, n; END LOOP; END $$; -- 补迁数规则:后续若从 public/legacy 再跑 migrate,notifications 不再被 skip CREATE OR REPLACE FUNCTION public._migrate_notifications_into_tenant( p_schema TEXT, p_branch TEXT, p_source TEXT DEFAULT 'legacy_public' ) RETURNS INTEGER LANGUAGE plpgsql AS $$ DECLARE n INTEGER := 0; v_source TEXT := p_source; BEGIN IF to_regclass(format('%I.notifications', v_source)) IS NULL THEN IF to_regclass('public.notifications') IS NOT NULL THEN v_source := 'public'; ELSE RETURN 0; END IF; END IF; IF to_regclass(format('%I.notifications', p_schema)) IS NULL THEN PERFORM public._clone_table_structure(v_source, p_schema, 'notifications'); END IF; EXECUTE format( 'INSERT INTO %I.notifications SELECT n.* FROM %I.notifications n LEFT JOIN public.profiles p ON p.id = n.user_id WHERE p.branch_code IS NOT DISTINCT FROM %L OR p.branch_code IS NULL OR n.user_id IS NULL ON CONFLICT DO NOTHING', p_schema, v_source, p_branch ); GET DIAGNOSTICS n = ROW_COUNT; RETURN n; END; $$;