This commit is contained in:
vipg
2025-11-17 15:10:48 +08:00
parent fcc758dd32
commit 1ebc924efb
5 changed files with 444 additions and 3 deletions

View File

@@ -27,4 +27,79 @@ BEGIN
ELSE
RAISE NOTICE 'country table already exists';
END IF;
END $$;
IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'name') THEN
CREATE TABLE name (
id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
country_id UUID NOT NULL,
name VARCHAR NOT NULL,
deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TRIGGER update_name_updated_at
BEFORE UPDATE ON "name"
FOR EACH ROW
EXECUTE FUNCTION update_name_modified_column();
RAISE NOTICE 'Created name table and trigger';
ELSE
RAISE NOTICE 'name table already exists';
END IF;
IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'code') THEN
CREATE TABLE code (
id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
country_id UUID NOT NULL,
code VARCHAR NOT NULL,
deleted BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TRIGGER update_code_updated_at
BEFORE UPDATE ON "code"
FOR EACH ROW
EXECUTE FUNCTION update_code_modified_column();
RAISE NOTICE 'Created code table and trigger';
ELSE
RAISE NOTICE 'code table already exists';
END IF;
END $$;
DO $$
DECLARE
view_exists BOOLEAN;
BEGIN
-- 检查视图是否已存在
SELECT EXISTS (
SELECT 1 FROM information_schema.views
WHERE table_name = 'country_info_view'
) INTO view_exists;
-- 创建或更新视图
CREATE OR REPLACE VIEW country_info_view AS
SELECT
u.id AS country_id,
n.name AS name,
c.code AS code,
u.deleted AS deleted
FROM
"country" u
JOIN
name n ON u.id = n.country_id
JOIN
code c ON u.id = c.country_id
WHERE
u.deleted = FALSE;
-- 根据视图是否已存在输出不同提示
IF view_exists THEN
RAISE NOTICE '视图 country_info_view 已更新';
ELSE
RAISE NOTICE '视图 country_info_view 已创建';
END IF;
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE '处理视图时发生错误: %', SQLERRM;
END $$;