实现说明
实际执行的是 SELECT / INSERT / CREATE——api_tokens 是涉及的对象。
把语句拆开看,工作部件是:ORDER BY 固定了输出顺序;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;把重复值挡在外面的 UNIQUE 约束。
常见问题
这里用到哪些关系?
api_tokens——文件内直接点名使用,不需要连接。
核心语句
INSERT INTO api_tokens (token_id, owner, token_hex)
VALUES (1, 'ci-worker', encode(gen_random_bytes(32), 'hex')),
(2, 'deploy-bot', encode(gen_random_bytes(16), 'hex'));
SELECT owner,
length(token_hex) AS hex_chars,
substring(token_hex, 1, 8) AS prefix
FROM api_tokens
ORDER BY token_id;
CREATE TABLE api_tokens (
token_id int PRIMARY KEY,
owner text NOT NULL,
token_hex text NOT NULL UNIQUE
);
代码示例
-- gen_random_bytes: cryptographic random bytes for API tokens, encoded to hex for storage
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE api_tokens (
token_id int PRIMARY KEY,
owner text NOT NULL,
token_hex text NOT NULL UNIQUE
);
INSERT INTO api_tokens (token_id, owner, token_hex)
VALUES (1, 'ci-worker', encode(gen_random_bytes(32), 'hex')),
(2, 'deploy-bot', encode(gen_random_bytes(16), 'hex'));
-- 32 bytes -> 64 hex characters, 16 bytes -> 32; hex changes only the representation, entropy is untouched
SELECT owner,
length(token_hex) AS hex_chars,
substring(token_hex, 1, 8) AS prefix
FROM api_tokens
ORDER BY token_id;