Hacker News new | ask | show | jobs
by timando 1759 days ago
I created a PostgreSQL function to generate a v7 uuid. On my laptop, it is about the same speed as generate_random_uuid

    CREATE OR REPLACE FUNCTION public.new_uuid_v7ish3()
     RETURNS uuid
     LANGUAGE sql
    AS $function$
    SELECT (
        lpad(
            to_hex(
               (
                   (((extract('epoch' from clock_timestamp()) * 4096) )::bigint << (64-36-12)) --36 bit seconds and 12 bit 4096th of a second
                   | (7::bigint << (64-36-12-4)) --Version 7
                   | (random() * 4096)::bigint --12 bit "sequence number"
               )
            ),
        16,'0')
        ||lpad(
            to_hex(
                (2::bigint << 62) --Variant
                + ((random() * x'4000'::bigint)::bigint << 48) --14 bits of randomness
                + ((random() * x'1000000000000'::bigint)::bigint) --48 bits of randomness
            ),
            16,'0'
        )
    )::uuid
    $function$