实现说明
一个文件里不止一条语句:INSERT / CREATE,device_profiles 都在涉及之列。
device_profiles 是本文件运行时创建的会话级临时表——不用先建表,会话收尾时一并回收。
用到的 SQL 构件:CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。
常见问题
这个文件引用了哪些表?
引用的是 device_profiles。
核心语句
CREATE TEMP TABLE device_profiles (
device_id integer PRIMARY KEY,
config jsonb NOT NULL,
CHECK (jsonb_typeof(config) = 'object'),
CHECK (config ? 'firmware'),
CHECK (jsonb_typeof(config -> 'firmware') = 'string')
);
INSERT INTO device_profiles (device_id, config)
VALUES (1, '{"firmware": "2.4.1", "flags": {"ota": true}}');
INSERT INTO device_profiles (device_id, config)
VALUES (3, '{"firmware": 12}');
代码示例
-- jsonb alone does not constrain the top-level shape: objects, arrays, and strings all store fine
-- lock the contract at write time with CHECK instead of defending all over the reading code
CREATE TEMP TABLE device_profiles (
device_id integer PRIMARY KEY,
config jsonb NOT NULL,
-- top level must be an object: array or string shapes are rejected outright
CHECK (jsonb_typeof(config) = 'object'),
-- the ? operator checks that a top-level key exists
CHECK (config ? 'firmware'),
-- pin nested value types too, so 12 and "1.2" cannot mix
CHECK (jsonb_typeof(config -> 'firmware') = 'string')
);
INSERT INTO device_profiles (device_id, config)
VALUES (1, '{"firmware": "2.4.1", "flags": {"ota": true}}');
-- an array at the top level: rejected by the first CHECK
INSERT INTO device_profiles (device_id, config)
VALUES (2, '[1, 2, 3]');
-- firmware is a number instead of a string: rejected by the type CHECK
INSERT INTO device_profiles (device_id, config)
VALUES (3, '{"firmware": 12}');