← 中文资源

简体中文版本

gen_random_uuid 随机 UUID 主键

PG 13+ 内建 gen_random_uuid 作为 uuid 主键默认值,无需扩展;外部标识用 ::uuid 强转校验格式,非法串当场报错而不是静默入库。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 api_keys。 机制上由这些部分组成:RETURNING 把受影响的行交回调用方;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。

常见问题

这个文件引用了哪些表?

引用的是 api_keys。

核心语句

CREATE TABLE api_keys (
    id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    label      text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO api_keys (label) VALUES ('ci-runner') RETURNING id, label;
SELECT 'not-a-uuid'::uuid; -- invalid input syntax for type uuid

代码示例

-- 随机 UUID 主键:gen_random_uuid() 是 PG 13+ 内建函数,无需扩展
CREATE TABLE api_keys (
    id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    label      text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO api_keys (label) VALUES ('ci-runner') RETURNING id, label;

-- 随机键写散在 B 树各处:按时间查询的索引建在 created_at 上
CREATE INDEX idx_api_keys_created ON api_keys (created_at);

-- 解析外部标识:::uuid 强转校验格式,非法串当场报错
SELECT 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d'::uuid;
SELECT 'not-a-uuid'::uuid; -- invalid input syntax for type uuid