8000 Add ability to validate JSON schema · Issue #109817 · cockroachdb/cockroach · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Add ability to validate JSON schema #109817
Open
@dikshant

Description

@dikshant

pg_jsonschema is a Postgres extension that provides built-in function for JSON schema validation. This allows us to validate a JSON schema against a SQL schema object. We should support the json_matches_schema built-in in CockroachDB that can accomplish this functionality. This is also something that is supported by Oracle DB.

The result of this built-in can be used as part of the check constraint when declaring the schema for a table:

create extension pg_jsonschema;

create table customer(
    id serial primary key,
    metadata json,

    check (
        json_matches_schema(
            '{
                "type": "object",
                "properties": {
                    "tags": {
                        "type": "array",
                        "items": {
                            "type": "string",
                            "maxLength": 16
                        }
                    }
                }
            }'::json,
            metadata
        )
    )
);

-- Example: Valid Payload
insert into customer(metadata) values ('{"tags": ["vip", "darkmode-ui"]}');
-- Result:
--   INSERT 0 1

-- Example: Invalid Payload
insert into customer(metadata) values ('{"tags": [1, 3]}');
-- Result:
--   ERROR:  new row for relation "customer" violates check constraint "customer_metadata_check"
--   DETAIL:  Failing row contains (2, {"tags": [1, 3]}).

There are three built-ins that pg_jsonschema supports and we can do this in phases:

  • jsonb_matches_schema(schema json, instance jsonb) returns bool
  • json_matches_schema(schema json, instance json) returns bool
  • jsonschema_is_valid(schema json) returns bool

Jira issue: CRDB-31110

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-sql-jsonJSON handling in SQL.C-enhancementSolution expected to add code/behavior + preserve backward-compat (pg compat issues are exception)E-starterMight be suitable for a starter project for new employees or team members.T-sql-foundationsSQL Foundations Team (formerly SQL Schema + SQL Sessions)

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0