pg_jsonschema
提供JSON Schema校验能力
仓库
supabase/pg_jsonschema
https://github.com/supabase/pg_jsonschema
源码
pg_jsonschema-0.3.4.tar.gz
pg_jsonschema-0.3.4.tar.gz
概览
| 扩展包名 | 版本 | 分类 | 许可证 | 语言 |
|---|---|---|---|---|
pg_jsonschema | 0.3.4 | FEAT | Apache-2.0 | Rust |
| ID | 扩展名 | Bin | Lib | Load | Create | Trust | Reloc | 模式 |
|---|---|---|---|---|---|---|---|---|
| 2760 | pg_jsonschema | 否 | 否 | 否 | 是 | 否 | 否 | - |
| 相关扩展 | pg_graphql jsquery plv8 jsonb_plperl http pg_net pg_summarize pg_tiktoken |
|---|
manual update from 0.16.0 by Vonng
版本
| 类型 | 仓库 | 版本 | PG 大版本 | 包名 | 依赖 |
|---|---|---|---|---|---|
| EXT | PIGSTY | 0.3.4 | 1817161514 | pg_jsonschema | - |
| RPM | PIGSTY | 0.3.4 | 1817161514 | pg_jsonschema_$v | - |
| DEB | PIGSTY | 0.3.4 | 1817161514 | postgresql-$v-pg-jsonschema | - |
构建
您可以使用 pig build 命令构建 pg_jsonschema 扩展的 RPM / DEB 包:
pig build pkg pg_jsonschema # 构建 RPM / DEB 包
安装
您可以直接安装 pg_jsonschema 扩展包的预置二进制包,首先确保 PGDG 和 PIGSTY 仓库已经添加并启用:
pig repo add pgsql -u # 添加仓库并更新缓存
使用 pig 或者是 apt/yum/dnf 安装扩展:
pig install pg_jsonschema; # 当前活跃 PG 版本安装
pig ext install -y pg_jsonschema -v 18 # PG 18
pig ext install -y pg_jsonschema -v 17 # PG 17
pig ext install -y pg_jsonschema -v 16 # PG 16
pig ext install -y pg_jsonschema -v 15 # PG 15
pig ext install -y pg_jsonschema -v 14 # PG 14
dnf install -y pg_jsonschema_18 # PG 18
dnf install -y pg_jsonschema_17 # PG 17
dnf install -y pg_jsonschema_16 # PG 16
dnf install -y pg_jsonschema_15 # PG 15
dnf install -y pg_jsonschema_14 # PG 14
apt install -y postgresql-18-pg-jsonschema # PG 18
apt install -y postgresql-17-pg-jsonschema # PG 17
apt install -y postgresql-16-pg-jsonschema # PG 16
apt install -y postgresql-15-pg-jsonschema # PG 15
apt install -y postgresql-14-pg-jsonschema # PG 14
创建扩展:
CREATE EXTENSION pg_jsonschema;
用法
pg_jsonschema 为 PostgreSQL 添加了 JSON Schema 校验函数,可通过检查约束对 JSON/JSONB 列实施模式验证。
函数
| 函数 | 描述 |
|---|---|
json_matches_schema(schema json, instance json) | 验证 JSON 实例是否符合 schema,返回布尔值 |
jsonb_matches_schema(schema json, instance jsonb) | 验证 JSONB 实例是否符合 schema,返回布尔值 |
jsonschema_is_valid(schema json) | 检查 JSON schema 本身是否合法 |
jsonschema_validation_errors(schema json, instance json) | 返回校验错误消息数组 |
表约束
使用检查约束强制文档结构:
CREATE TABLE customer (
id serial PRIMARY KEY,
metadata json,
CHECK (
json_matches_schema(
'{
"type": "object",
"properties": {
"tags": {
"type": "array",
"items": {
"type": "string",
"maxLength": 16
}
}
}
}',
metadata
)
)
);
-- 有效插入(通过检查约束)
INSERT INTO customer(metadata) VALUES ('{"tags": ["vip", "darkmode-ui"]}');
-- 无效插入(被检查约束拒绝)
INSERT INTO customer(metadata) VALUES ('{"tags": [1, 3]}');
-- ERROR: new row violates check constraint
错误检查
获取详细的校验错误信息:
SELECT jsonschema_validation_errors('{"maxLength": 4}', '"123456789"');
-- 返回: {"\"123456789\" is longer than 4 characters"}
模式校验
使用前验证 schema 是否格式正确:
SELECT jsonschema_is_valid('{
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}');
-- 返回: true