Supabaseoli_riceProblem & solution
pg_jsonschema: JSON Schema support for Postgres
Summary
pg_jsonschema is a Postgres extension released on the Supabase platform that adds JSON Schema validation for json and jsonb data types. The post addresses a trade-off in storing complex webhook payloads as documents: JSON simplifies the model and accommodates changing payloads, but an unconstrained column cannot enforce required structure or types. It introduces JSON Schema as a formal, human-readable way to describe those constraints, including an object with a required string foo attribute and no additional properties. The extension provides json_matches_schema and jsonb_matches_schema, which can be used in a Postgres CHECK constraint to validate inserted documents. In the example, the constraint handled all eight test cases correctly, and invalid rows produced a constraint-violation error.
Context
Storing complex webhook data as JSON can simplify the data model and accommodate changing payloads, but an unconstrained json column is more permissive than intended and sacrifices database guarantees such as type and required-field enforcement.
Approach / What changed
pg_jsonschema validates json and jsonb instances against JSON Schema documents through json_matches_schema and jsonb_matches_schema. A CHECK constraint invokes the appropriate function with an inline schema, requiring a string foo property and rejecting additional properties.
Takeaways
The demonstrated JSON Schema requires an object, a string-valued foo property, and no additional properties.
json_matches_schema accepts a JSON Schema and json instance, while jsonb_matches_schema accepts a JSON Schema and jsonb instance.
The extension can be enabled with create extension pg_jsonschema; in the example, failed inserts raise a PostgreSQL check-constraint violation with SQL state 23514.
Source and freshness
- Source
- supabase.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.