\c postgres;

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 $$;
