PostgreSQL 中的 JSON 模式验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22228525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON Schema validation in PostgreSQL?
提问by khorvat
I can't find any information about JSON schema validation in PostgreSQL, is there any way to implement JSON Schema validation on PostgreSQL JSON data type?
我在 PostgreSQL 中找不到任何关于 JSON 模式验证的信息,有什么方法可以在 PostgreSQL JSON 数据类型上实现 JSON 模式验证吗?
采纳答案by Mordae
There is a PostgreSQL extensionthat implements JSON Schema validation in PL/PgSQL.
有一个PostgreSQL 扩展在 PL/PgSQL 中实现了 JSON 模式验证。
It is used like this (taken from the project README file):
它是这样使用的(取自项目 README 文件):
CREATE TABLE example (id serial PRIMARY KEY, data jsonb);
ALTER TABLE example ADD CONSTRAINT data_is_valid CHECK (validate_json_schema('{"type": "object"}', data));
INSERT INTO example (data) VALUES ('{}');
-- INSERT 0 1
INSERT INTO example (data) VALUES ('1');
-- ERROR: new row for relation "example" violates check constraint "data_is_valid"
-- DETAIL: Failing row contains (2, 1).
回答by Gabriel Furstenheim
There is another PostgreSQL extensionthat implements json validation. The usage is almost the same as "Postgres-JSON-schema"
还有另一个PostgreSQL 扩展实现了 json 验证。用法与“Postgres-JSON-schema”几乎相同
CREATE TABLE example (id serial PRIMARY KEY, data jsonb);
-- do is_jsonb_valid instead of validate_json_schema
ALTER TABLE example ADD CONSTRAINT data_is_valid CHECK (is_jsonb_valid('{"type": "object"}', data));
INSERT INTO example (data) VALUES ('{}');
-- INSERT 0 1
INSERT INTO example (data) VALUES ('1');
-- ERROR: new row for relation "example" violates check constraint "data_is_valid"
-- DETAIL: Failing row contains (2, 1).
I've done some benchmarking validating tweets and it is 20x faster than "Postgres-JSON-schema", mostly because it is written in C instead of SQL.
我已经完成了一些验证推文的基准测试,它比“Postgres-JSON-schema”快 20 倍,主要是因为它是用 C 而不是 SQL 编写的。
Disclaimer, I've written this extension.
免责声明,我已经写了这个扩展。
回答by cloudfeet
What you need is something to translate JSON Schema constraints into PostgreSQL ones, e.g.:
您需要的是将 JSON Schema 约束转换为 PostgreSQL 的,例如:
{
"properties": {
"age": {"minimum": 21}
},
"required": ["age"]
}
to:
到:
SELECT FROM ...
WHERE (elem->>'age' >= 21)
I'm not aware of any existing tools. I know of something similar for MySQLwhich might be useful for writing your own, but nothing for using the JSON type in PostgreSQL.
我不知道任何现有的工具。我知道一些类似于MySQL的东西,它可能对编写自己的代码很有用,但对于在 PostgreSQL 中使用 JSON 类型却一无所知。