Keeping a JSON column honest in SQL
A TEXT column will happily store a half-written document unless you stop it.
CREATE TABLE settings (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL CHECK (JSON_VALID(doc)),
owner TEXT NOT NULL
);
CREATE INDEX settings_theme
ON settings (JSON_EXTRACT(doc, '$.theme'));
INSERT INTO settings (doc, owner)
VALUES ('{"theme":"dracula","tabs":4}', 'ada');
SELECT
JSON_TYPE(doc, '$.tabs') AS tabs_type,
doc ->> '$.theme' AS theme
FROM settings;
How it works
json_validreturns 1 or 0, which is exactly what aCHECKwants.json_typenames the kind at a path: object, array, integer, text.- Indexing an extracted path makes a JSON lookup as fast as a column.
Keywords and builtins used here
ASCHECKCREATEFROMINDEXINSERTINTEGERINTOKEYNOTNULLONPRIMARYSELECTTABLETEXTVALUESowner
The run, in numbers
- Lines
- 16
- Characters to type
- 358
- Tokens
- 76
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 48 seconds.
Step 4 of 5 in Writing JSON, step 7 of 14 in JSON & search.