gen_random_uuid UUID Primary Keys

Give tables random UUID primary keys with the built-in gen_random_uuid default, and validate external identifiers with ::uuid casts.

SqlData Integrity

Code

snippet
-- 随机 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

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with api_keys among the objects involved.

Breaking the statements into their working parts: a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

Run it in the api_keys database context.

Statements that matter

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;
CREATE INDEX idx_api_keys_created ON api_keys (created_at);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `api_keys`.