\c postgres;

DO $$
DECLARE
    view_exists BOOLEAN;
BEGIN
    -- 检查视图是否已存在
    SELECT EXISTS (
        SELECT 1 FROM information_schema.views 
        WHERE table_name = 'user_account_password_view'
    ) INTO view_exists;

    -- 创建或更新视图
    CREATE OR REPLACE VIEW user_account_password_view AS
    SELECT 
        u.id AS user_id,
        ua.account AS account,
        up.password AS password,
        u.deleted AS deleted
    FROM 
        "user" u
    JOIN 
        user_account ua ON u.id = ua.user_id
    JOIN 
        user_password up ON u.id = up.user_id;

    -- 根据视图是否已存在输出不同提示
    IF view_exists THEN
        RAISE NOTICE '视图 user_account_password_view 已更新';
    ELSE
        RAISE NOTICE '视图 user_account_password_view 已创建';
    END IF;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE '处理视图时发生错误: %', SQLERRM;
END $$;
