如何使用 uuid 作为 postgres 的默认 ID?

str*_*rap 5 javascript postgresql bookshelf.js strapi next.js

在宣布放弃 mongodb 之后,目前正在迁移到 postgres 的过程中,刚刚注意到 ID 只是数字并且自动递增。

我努力了:

  1. 使用生命周期挂钩将默认 ID 设置为 UUID - 无效
  2. 安装书架uuid

有人知道怎么做吗?我非常不希望我的帖子的 ID 是一个自动递增的数字。

cle*_*ens 8

自动递增的 ids 和 uuid 通常是不同的概念。对于 uuid 作为主键,通常使用随机值。由于值范围很大,重复几乎是不可能的。

\n

您可以定义自动生成的 uuid 主键,如下所示:

\n
CREATE TABLE my_table (\n    id UUID DEFAULT MD5(RANDOM()::TEXT || CLOCK_TIMESTAMP()::TEXT)::UUID PRIMARY KEY,\n    \xe2\x80\xa6 other column definitions \xe2\x80\xa6\n);\n
Run Code Online (Sandbox Code Playgroud)\n

pgcrypto 扩展还提供了创建随机 uuid 的功能。

\n
CREATE EXTENSION IF NOT EXISTS pgcrypto;\nCREATE TABLE my_table (\n    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,\n    \xe2\x80\xa6 other column definitions \xe2\x80\xa6\n);\n
Run Code Online (Sandbox Code Playgroud)\n

gen_random_uuid()在 Postgres 13 中,不再需要创建 pgcrypto 扩展来使用。

\n

  • 从 postgres 13 开始,gen_random_uuid 无需安装扩展即可使用:https://www.postgresql.org/docs/current/functions-uuid.html (3认同)