JSONB Shape Enforced By CHECK Constraint

Lock the JSONB contract at write time: jsonb_typeof pins the top-level type and required keys, and nested values get their own type checks.

SqlData Integrity

Code

snippet
-- 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}');

What the code does

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

device_profiles is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.

Breaking the statements into their working parts: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The file is self-contained: it creates the session-local tables it uses (device_profiles), so run it as a whole against a scratch database.

Statements that matter

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}');

Interactive Tools for This Topic

FAQ

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