Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add jsonschema_is_valid function and its tests #34

Merged
merged 3 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,26 @@


## API
Two SQL functions:
Three SQL functions:
- json_matches_schema
- jsonb_matches_schema (note the **jsonb** in front)
- jsonschema_is_valid

With the following signatures
```sql
-- Validates a json *instance* against a *schema*
json_matches_schema(schema json, instance json) returns bool
```
and
and
```sql
-- Validates a jsonb *instance* against a *schema*
jsonb_matches_schema(schema json, instance jsonb) returns bool
```
and
```sql
-- Validates whether a json *schema* is valid
jsonschema_is_valid(schema json) returns bool
```

## Usage
Those functions can be used to constrain `json` and `jsonb` columns to conform to a schema.
Expand Down
31 changes: 31 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ fn jsonb_matches_schema(schema: Json, instance: JsonB) -> bool {
jsonschema::is_valid(&schema.0, &instance.0)
}

#[pg_extern(immutable, strict)]
fn jsonschema_is_valid(schema: Json) -> bool {
match jsonschema::JSONSchema::compile(&schema.0) {
Ok(_) => true,
Err(e) => {
// Only call notice! for a non empty instance_path
if e.instance_path.last().is_some() {
notice!(
"Invalid JSON schema at path: {}",
e.instance_path.to_string()
);
}
false
}
}
}

#[pg_schema]
#[cfg(any(test, feature = "pg_test"))]
mod tests {
Expand Down Expand Up @@ -101,6 +118,20 @@ mod tests {
.unwrap();
assert!(!result);
}

#[pg_test]
fn test_jsonschema_is_valid() {
assert!(crate::jsonschema_is_valid(Json(json!({
"type": "object"
}))));
}

#[pg_test]
fn test_jsonschema_is_not_valid() {
assert!(!crate::jsonschema_is_valid(Json(json!({
"type": "obj"
}))));
}
}

#[cfg(test)]
Expand Down