pg_jsonschema
What it is
pg_jsonschema validates PostgreSQL json and jsonb values against JSON Schema. Validation can run in a query or become a check constraint that prevents invalid documents from being stored.
What it provides
- JSON and JSONB validation functions
- Validation of the schema document itself
- Validation diagnostics for malformed documents
Use it for flexible metadata columns, webhook payloads, configuration documents, user-defined forms, or event envelopes that need a database-enforced shape.
Use it with Rent
extension pg_jsonschema {
name = "pg_jsonschema"
}The RSL declaration makes installation and migration intent part of the reviewed application schema. Register the typed pack at runtime to call its APIs:
let jsonschema = extensions.register_pack::<PgJsonSchema>()?;
let valid_metadata = jsonschema.validates_jsonb(
post::metadata(),
serde_json::json!({"type": "object", "required": ["email"]}),
);
let posts = client
.post()
.where_raw(valid_metadata)
.all()
.await?;
let valid = jsonschema
.client(&pool)
.validate(schema, document)
.await?;Run the application
cargo run -p rent --example extension_12_pg_jsonschemaSet DATABASE_URL to a disposable PostgreSQL server with pg_jsonschema available and a role permitted to
create databases and install it. The application stores post metadata with a reading_time field,
validates positive and invalid values through the typed client, and filters rows with both JSON and JSONB
predicates. It then adds a database CHECK constraint and proves that an invalid insert is rejected without
changing the stored rows. The isolated database is removed afterward.
Query-time validation only filters a result; it does not protect future writes. Use a CHECK constraint
when every writer must obey the schema. PostgreSQL still needs NOT NULL separately if SQL NULL is forbidden.
Its standalone extension declaration is crates/rent/examples/extension_12_pg_jsonschema/schema.rsl.