get_bit And set_bit Toggle Flag Bits

Read and flip individual bits with get_bit and set_bit on a bit column, packing boolean flags where the leftmost bit is bit 0.

SqlData Integrity

Code

snippet
-- 权限打包成 3 位位串:bit 0(最左位)= 读,bit 1 = 写,bit 2 = 删
CREATE TABLE api_keys (
    id    int PRIMARY KEY,
    name  text NOT NULL,
    perms bit(3) NOT NULL DEFAULT B'000'
);

INSERT INTO api_keys VALUES
    (1, 'reporting', B'100'),   -- 只读
    (2, 'uploader',  B'010'),   -- 只写
    (3, 'admin',     B'101');   -- 读 + 删

-- get_bit 单独检查某一位;位串的位号从最左位 0 起算
SELECT name,
       get_bit(perms, 0) AS can_read,
       get_bit(perms, 1) AS can_write,
       get_bit(perms, 2) AS can_delete
FROM api_keys
ORDER BY id;

-- 授予写权限:set_bit 翻开 bit 1,其余位不动
UPDATE api_keys
SET perms = set_bit(perms, 1, 1)
WHERE name = 'reporting'
RETURNING name, perms;

-- 位串字面量与整数二进制书写方向相反:B'101' 的 bit 0 是最左边的 1
SELECT get_bit(B'101', 0) AS leftmost,
       get_bit(B'101', 2) AS rightmost,
       set_bit(B'101', 2, 0) AS cleared;

Inside the snippet

SELECT / INSERT / UPDATE / CREATE statements share the script, touching api_keys.

Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; 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.

Using it

Point it at the api_keys table.

Key statements

UPDATE api_keys
SET perms = set_bit(perms, 1, 1)
WHERE name = 'reporting'
RETURNING name, perms;
SELECT name,
       get_bit(perms, 0) AS can_read,
       get_bit(perms, 1) AS can_write,
       get_bit(perms, 2) AS can_delete
FROM api_keys
ORDER BY id;
INSERT INTO api_keys VALUES
    (1, 'reporting', B'100'),   -- 只读
    (2, 'uploader',  B'010'),   -- 只写
    (3, 'admin',     B'101');   -- 读 + 删

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`api_keys`.