-- 切换到目标数据库
\c postgres;

-- 检查并创建UUID扩展（如果不存在）
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- 定义检测UUID v7支持的函数
CREATE OR REPLACE FUNCTION check_uuid_v7_support() RETURNS BOOLEAN AS $$
DECLARE
    test_uuid UUID;
BEGIN
    BEGIN
        SELECT gen_random_uuid_v7() INTO test_uuid;
        RETURN TRUE;
    EXCEPTION
        WHEN undefined_function THEN
            RETURN FALSE;
    END;
END;
$$ LANGUAGE plpgsql VOLATILE;

-- 创建UUID v7兼容函数（修复UUID格式长度问题）
CREATE OR REPLACE FUNCTION gen_random_uuid_v7() RETURNS uuid AS $$
DECLARE
    unix_ts_ms BIGINT;
    rand_a BIGINT;
    rand_b BIGINT;
    hex_str TEXT;
BEGIN
    -- 获取当前毫秒级Unix时间戳
    unix_ts_ms := (EXTRACT(EPOCH FROM NOW()) * 1000)::BIGINT;
    
    -- 生成随机数（调整随机数范围以确保总长度正确）
    rand_a := (random() * (2^20 - 1))::BIGINT;
    rand_b := (random() * (2^44 - 1))::BIGINT;  -- 从48位调整为44位，减少2个字节
    
    -- 组合UUID v7格式（确保总长度为32个十六进制字符）
    hex_str := 
        lpad(to_hex(unix_ts_ms >> 12), 8, '0') ||
        lpad(to_hex((unix_ts_ms & 4095) << 4), 4, '0') ||
        '7' || lpad(to_hex(rand_a >> 18), 3, '0') ||
        lpad(to_hex(8 + (rand_a & 16383) >> 12), 2, '0') ||
        lpad(to_hex(rand_a & 4095), 3, '0') ||
        lpad(to_hex(rand_b), 11, '0');  -- 从12位调整为11位
    
    RETURN hex_str::uuid;
END;
$$ LANGUAGE plpgsql VOLATILE;