使用 postgres uuid_generate_v4 时出现许多重复值

Mat*_*man 5 postgresql uuid activerecord

我们向 8000 万行数据库添加了一个 UUID 列,并使用 postgres 函数生成默认值uuid_generate_v4()

我们使用以下脚本回填 uuid:

current = 1
batch_size = 1000
last_id = 80000000

while current < last_id
  start_id = current
  end_id = current + batch_size
  puts "WORKING ON current: #{current}"
  ActiveRecord::Base.connection.execute <<-SQL.squish
    UPDATE table_name
    SET public_id = uuid_generate_v4()
    WHERE id BETWEEN '#{start_id}' and '#{end_id}' AND public_id IS NULL
  SQL
  current = end_id + 1
end
Run Code Online (Sandbox Code Playgroud)

然而,在脚本的最后,我们发现有 135 个重复项,有些甚至有 3 个。这怎么可能呢?该uuid_generate_v4()函数产生重复的概率是否如此之高?

Jon*_*son 0

您使用哪个操作系统?

根据https://security.stackexchange.com/questions/93902/is-postgress-uuid-generate-v4-securely-random ossp 扩展使用 /dev/urandom 因此它可能无法始终按预期工作。(我还没有检查该声明。)

您尝试过使用gen_random_uuid()它吗?