Compare commits

...

19 Commits

Author SHA1 Message Date
6ca00f27e9 version: 1.0.13 2025-04-15 23:30:57 -04:00
520be66035 better error messaging 2025-04-15 23:30:47 -04:00
c3146ca433 flow update 2025-04-15 01:52:12 -04:00
b4d9628b05 version: 1.0.12 2025-04-15 00:25:39 -04:00
635d31d723 more validation fixes 2025-04-15 00:25:29 -04:00
08efcb92db version: 1.0.11 2025-04-14 21:53:39 -04:00
dad1216e1f more validation fixes 2025-04-14 21:53:30 -04:00
2fcf8613b8 version: 1.0.10 2025-04-14 20:23:23 -04:00
f88c27aa70 fixed naming, added back json_schema_cached 2025-04-14 20:23:18 -04:00
48e74815d3 version: 1.0.9 2025-04-14 18:08:45 -04:00
23235d4b9d -m switched to boon 2025-04-14 18:08:36 -04:00
67406c0b96 version: 1.0.8 2025-04-14 16:11:49 -04:00
28fff3be11 validation error fixes 2025-04-14 16:11:44 -04:00
70f3d30258 version: 1.0.7 2025-04-14 12:03:07 -04:00
406466454e excluding flows from jspg release 2025-04-14 12:03:01 -04:00
2a9d51fa77 version: 1.0.6 2025-04-14 11:24:22 -04:00
ae90137308 updated flows 2025-04-14 11:24:18 -04:00
d22a8669ef version: 1.0.5 2025-04-14 11:19:38 -04:00
b32c17a4f5 updated flow 2025-04-14 11:19:28 -04:00
9 changed files with 497 additions and 112 deletions

10
.editorconfig Normal file
View File

@ -0,0 +1,10 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
[*.{json,toml,control,rs}]
charset = utf-8
indent_style = space
indent_size = 2

13
.env Normal file
View File

@ -0,0 +1,13 @@
ENVIRONMENT=local
DATABASE_PASSWORD=QgSvstSjoc6fKphMzNgT3SliNY10eSRS
DATABASE_ROLE=agreego_admin
DATABASE_HOST=127.1.27.9
DATABASE_PORT=5432
POSTGRES_PASSWORD=xzIq5JT0xY3F+2m1GtnrKDdK29sNSXVVYZHPKJVh8pI=
DATABASE_NAME=agreego
DEV_DATABASE_NAME=agreego_dev
GITEA_TOKEN=3d70c23673517330623a5122998fb304e3c73f0a
MOOV_ACCOUNT_ID=69a0d2f6-77a2-4e26-934f-d869134f87d3
MOOV_PUBLIC_KEY=9OMhK5qGnh7Tmk2Z
MOOV_SECRET_KEY=DrRox7B-YWfO9IheiUUX7lGP8-7VY-Ni
MOOV_DOMAIN=http://localhost

27
Cargo.lock generated
View File

@ -68,6 +68,12 @@ version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f"
[[package]]
name = "appendlist"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e149dc73cd30538307e7ffa2acd3d2221148eaeed4871f246657b1c3eaa1cbd2"
[[package]]
name = "async-trait"
version = "0.1.88"
@ -177,6 +183,26 @@ dependencies = [
"generic-array",
]
[[package]]
name = "boon"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa187da765010b70370368c49f08244b1ae5cae1d5d33072f76c8cb7112fe3e"
dependencies = [
"ahash",
"appendlist",
"base64",
"fluent-uri",
"idna",
"once_cell",
"percent-encoding",
"regex",
"regex-syntax",
"serde",
"serde_json",
"url",
]
[[package]]
name = "borrow-or-share"
version = "0.2.2"
@ -1015,6 +1041,7 @@ dependencies = [
name = "jspg"
version = "0.1.0"
dependencies = [
"boon",
"jsonschema",
"lazy_static",
"pgrx",

View File

@ -9,6 +9,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
jsonschema = "0.29.1"
lazy_static = "1.5.0"
boon = "0.6.1"
[dev-dependencies]
pgrx-tests = "0.14.0"
@ -22,6 +23,7 @@ path = "src/bin/pgrx_embed.rs"
[features]
pg17 = ["pgrx/pg17", "pgrx-tests/pg17" ]
# Local feature flag used by `cargo pgrx test`
pg_test = []
[profile.dev]

38
flow
View File

@ -11,7 +11,6 @@ POSTGRES_VERSION="17"
POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
DEPENDENCIES=(cargo git icu4c pkg-config "postgresql@${POSTGRES_VERSION}")
CARGO_DEPENDENCIES=(cargo-pgrx==0.14.0)
PACKAGE_NAME="jspg"
GITEA_ORGANIZATION="cellular"
GITEA_REPOSITORY="jspg"
@ -64,7 +63,7 @@ build() {
# Create the source tarball excluding specified patterns
echo -e " ${CYAN}Creating tarball: ${tarball_path}${RESET}"
if tar --exclude='.git*' --exclude='./target' --exclude='./package' -czf "${tarball_path}" .; then
if tar --exclude='.git*' --exclude='./target' --exclude='./package' --exclude='./flows' --exclude='./flow' -czf "${tarball_path}" .; then
echo -e "✨ ${GREEN}Successfully created source tarball: ${tarball_path}${RESET}"
else
echo -e "❌ ${RED}Failed to create source tarball.${RESET}" >&2
@ -77,15 +76,41 @@ install() {
version=$(get-version) || return 1
echo -e "🔧 ${CYAN}Building and installing PGRX extension v$version into local PostgreSQL...${RESET}"
# Run the pgrx install command
# It implicitly uses --release unless --debug is passed
# It finds pg_config or you can add flags like --pg-config if needed
if ! cargo pgrx install "$@"; then # Pass any extra args like --debug
if ! cargo pgrx install; then
echo -e "❌ ${RED}cargo pgrx install command failed.${RESET}" >&2
return 1
fi
echo -e "✨ ${GREEN}PGRX extension v$version successfully built and installed.${RESET}"
# Post-install modification to allow non-superuser usage
# Get the installation path dynamically using pg_config
local pg_sharedir
pg_sharedir=$("$POSTGRES_CONFIG_PATH" --sharedir)
if [ -z "$pg_sharedir" ]; then
echo -e "❌ ${RED}Failed to determine PostgreSQL shared directory using pg_config.${RESET}" >&2
return 1
fi
local installed_control_path="${pg_sharedir}/extension/jspg.control"
# Modify the control file
if [ ! -f "$installed_control_path" ]; then
echo -e "❌ ${RED}Installed control file not found: '$installed_control_path'${RESET}" >&2
return 1
fi
echo -e "🔧 ${CYAN}Modifying control file for non-superuser access: ${installed_control_path}${RESET}"
# Use sed -i '' for macOS compatibility
if sed -i '' '/^superuser = false/d' "$installed_control_path" && \
echo 'trusted = true' >> "$installed_control_path"; then
echo -e "✨ ${GREEN}Control file modified successfully.${RESET}"
else
echo -e "❌ ${RED}Failed to modify control file: ${installed_control_path}${RESET}" >&2
return 1
fi
}
test() {
@ -113,10 +138,11 @@ jspg-usage() {
jspg-flow() {
case "$1" in
env) env; return 0;;
prepare) base prepare; cargo-prepare; pgrx-prepare; return 0;;
build) build; return 0;;
install) base prepare; cargo-prepare; pgrx-prepare; install "$@"; return 0;;
reinstall) base prepare; cargo-prepare; pgrx-prepare; install "$@"; return 0;;
install) install; return 0;;
reinstall) clean; install; return 0;;
test) test; return 0;;
package) env; package; return 0;;
release) env; release; return 0;;

2
flows

Submodule flows updated: 6eab4783f3...9d758d581e

View File

@ -1,126 +1,169 @@
use pgrx::*;
use jsonschema::{Draft, Validator};
use serde_json::json;
use std::collections::HashMap;
use std::sync::RwLock;
use lazy_static::lazy_static;
use jsonschema;
pg_module_magic!();
// Global, thread-safe schema cache using the correct Validator type
use serde_json::{json, Value};
use std::{collections::HashMap, sync::RwLock};
use boon::{Compiler, Schemas, ValidationError, SchemaIndex, CompileError};
use lazy_static::lazy_static;
struct BoonCache {
schemas: Schemas,
id_to_index: HashMap<String, SchemaIndex>,
}
lazy_static! {
static ref SCHEMA_CACHE: RwLock<HashMap<String, Validator>> = RwLock::new(HashMap::new());
static ref SCHEMA_CACHE: RwLock<BoonCache> = RwLock::new(BoonCache {
schemas: Schemas::new(),
id_to_index: HashMap::new(),
});
}
// Cache a schema explicitly with a provided ID
#[pg_extern(immutable, strict, parallel_safe)]
fn cache_schema(schema_id: &str, schema: JsonB) -> bool {
match jsonschema::options()
.with_draft(Draft::Draft7)
.should_validate_formats(true)
.build(&schema.0)
{
Ok(compiled) => {
SCHEMA_CACHE.write().unwrap().insert(schema_id.to_string(), compiled);
true
},
Err(e) => {
notice!("Failed to cache schema '{}': {}", schema_id, e);
false
}
#[pg_extern(strict)]
fn cache_json_schema(schema_id: &str, schema: JsonB) -> JsonB {
let mut cache = SCHEMA_CACHE.write().unwrap();
let schema_value: Value = schema.0;
let schema_path = format!("urn:{}", schema_id);
let mut compiler = Compiler::new();
compiler.enable_format_assertions();
// Use schema_path when adding the resource
if let Err(e) = compiler.add_resource(&schema_path, schema_value.clone()) {
return JsonB(json!({
"success": false,
"error": {
"message": format!("Failed to add schema resource '{}': {}", schema_id, e),
"schema_path": schema_path
}
}));
}
// Use schema_path when compiling
match compiler.compile(&schema_path, &mut cache.schemas) {
Ok(sch_index) => {
// Store the index using the original schema_id as the key
cache.id_to_index.insert(schema_id.to_string(), sch_index);
JsonB(json!({ "success": true }))
}
}
// Check if a schema is cached
#[pg_extern(immutable, strict, parallel_safe)]
fn schema_cached(schema_id: &str) -> bool {
SCHEMA_CACHE.read().unwrap().contains_key(schema_id)
}
// Validate JSONB instance against a cached schema by ID
#[pg_extern(immutable, strict, parallel_safe)]
fn validate_schema(schema_id: &str, instance: JsonB) -> JsonB {
let cache = SCHEMA_CACHE.read().unwrap();
let compiled_schema: &Validator = match cache.get(schema_id) {
Some(schema) => schema,
None => {
return JsonB(json!({
"valid": false,
"errors": [format!("Schema ID '{}' not cached", schema_id)]
}));
Err(e) => {
let error = match &e {
CompileError::ValidationError { url: _url, src } => { // Prefix url with _
json!({
"message": format!("Schema '{}' failed validation against its metaschema: {}", schema_id, src),
"schema_path": schema_path,
"error": format!("{:?}", src),
})
}
};
_ => {
let _error_type = format!("{:?}", e).split('(').next().unwrap_or("Unknown").to_string(); // Prefix error_type with _
json!({
"message": format!("Schema '{}' compilation failed: {}", schema_id, e),
"schema_path": schema_path,
"error": format!("{:?}", e),
})
}
};
JsonB(json!({
"success": false,
"error": error
}))
}
}
}
if compiled_schema.is_valid(&instance.0) {
JsonB(json!({ "valid": true }))
#[pg_extern(strict, parallel_safe)]
fn validate_json_schema(schema_id: &str, instance: JsonB) -> JsonB {
let cache = SCHEMA_CACHE.read().unwrap();
// Lookup uses the original schema_id
match cache.id_to_index.get(schema_id) {
None => JsonB(json!({
"success": false,
"error": {
"message": format!("Schema with id '{}' not found in cache", schema_id)
}
})),
Some(sch_index) => {
let instance_value: Value = instance.0;
match cache.schemas.validate(&instance_value, *sch_index) {
Ok(_) => JsonB(json!({ "success": true })),
Err(validation_error) => {
let error = format_validation_error(&validation_error);
JsonB(json!({
"success": false,
"error": error
}))
}
}
}
}
}
fn format_validation_error(error: &ValidationError) -> Value {
let nested_errors: Vec<Value> = error.causes.iter().map(format_validation_error).collect();
// Use specific message for leaf errors, generic for containers
let message = if error.causes.is_empty() {
let default_message = format!("{}", error); // Use boon's default message for specific errors
// Try to strip the "at '<path>': " prefix
if let Some(start_index) = default_message.find("': ") {
default_message[start_index + 3..].to_string()
} else {
let errors: Vec<String> = compiled_schema
.iter_errors(&instance.0)
.map(|e| e.to_string())
.collect();
JsonB(json!({ "valid": false, "errors": errors }))
default_message // Fallback if pattern not found
}
} else {
"Validation failed due to nested errors".to_string() // Generic message for container errors
};
json!({
"message": message,
"schema_path": error.schema_url.to_string(), // Use schema_url directly
"instance_path": error.instance_location.to_string(),
"error": nested_errors // Recursively format nested errors
})
}
// Clear the entire schema cache explicitly
#[pg_extern(immutable, parallel_safe)]
fn clear_schema_cache() -> bool {
SCHEMA_CACHE.write().unwrap().clear();
true
#[pg_extern(strict, parallel_safe)]
fn json_schema_cached(schema_id: &str) -> bool {
let cache = SCHEMA_CACHE.read().unwrap();
cache.id_to_index.contains_key(schema_id)
}
#[pg_schema]
#[cfg(any(test, feature = "pg_test"))]
mod tests {
use pgrx::*;
use serde_json::json;
#[pg_test]
fn test_cache_and_validate_schema() {
assert!(crate::cache_schema("test_schema", JsonB(json!({ "type": "object" }))));
assert!(crate::schema_cached("test_schema"));
let result_valid = crate::validate_schema("test_schema", JsonB(json!({ "foo": "bar" })));
assert_eq!(result_valid.0["valid"], true);
let result_invalid = crate::validate_schema("test_schema", JsonB(json!(42)));
assert_eq!(result_invalid.0["valid"], false);
assert!(result_invalid.0["errors"][0].as_str().unwrap().contains("not of type"));
}
#[pg_test]
fn test_schema_not_cached() {
let result = crate::validate_schema("unknown_schema", JsonB(json!({})));
assert_eq!(result.0["valid"], false);
assert!(result.0["errors"][0].as_str().unwrap().contains("not cached"));
}
#[pg_test]
fn test_clear_schema_cache() {
crate::cache_schema("clear_test", JsonB(json!({ "type": "object" })));
assert!(crate::schema_cached("clear_test"));
crate::clear_schema_cache();
assert!(!crate::schema_cached("clear_test"));
}
#[pg_test]
fn test_invalid_schema_cache() {
let result = crate::cache_schema("bad_schema", JsonB(json!({ "type": "unknown_type" })));
assert!(!result);
assert!(!crate::schema_cached("bad_schema"));
}
#[pg_extern(strict)]
fn clear_json_schemas() {
let mut cache = SCHEMA_CACHE.write().unwrap();
*cache = BoonCache {
schemas: Schemas::new(),
id_to_index: HashMap::new(),
};
}
#[pg_extern(strict, parallel_safe)]
fn show_json_schemas() -> Vec<String> {
let cache = SCHEMA_CACHE.read().unwrap();
let ids: Vec<String> = cache.id_to_index.keys().cloned().collect();
ids
}
/// This module is required by `cargo pgrx test` invocations.
/// It must be visible at the root of your extension crate.
#[cfg(test)]
pub mod pg_test {
pub fn setup(_options: Vec<&str>) {
// Initialization if needed
}
pub fn setup(_options: Vec<&str>) {
// perform one-off initialization when the pg_test framework starts
}
pub fn postgresql_conf_options() -> Vec<&'static str> {
vec![]
}
#[must_use]
pub fn postgresql_conf_options() -> Vec<&'static str> {
// return any postgresql.conf settings that are required for your tests
vec![]
}
}
#[cfg(any(test, feature = "pg_test"))]
#[pg_schema]
mod tests {
include!("tests.rs");
}

264
src/tests.rs Normal file
View File

@ -0,0 +1,264 @@
use crate::*;
use serde_json::{json, Value};
// Helper macro for asserting success with pretty JSON output on failure
macro_rules! assert_success_with_json {
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => {
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
if condition_result != Some(true) {
let base_msg = format!($fmt $(, $($args)*)?);
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
// Construct the full message string first
let panic_msg = format!("Assertion Failed (expected success): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("{}", panic_msg); // Use the constructed string
}
};
}
// Helper macro for asserting failure with pretty JSON output on failure
macro_rules! assert_failure_with_json {
($result_jsonb:expr, $fmt:literal $(, $($args:tt)*)?) => {
let condition_result: Option<bool> = $result_jsonb.0.get("success").and_then(Value::as_bool);
if condition_result != Some(false) {
let base_msg = format!($fmt $(, $($args)*)?);
let pretty_json = serde_json::to_string_pretty(&$result_jsonb.0)
.unwrap_or_else(|_| format!("(Failed to pretty-print JSON: {:?})", $result_jsonb.0));
// Construct the full message string first
let panic_msg = format!("Assertion Failed (expected failure): {}\nResult JSON:\n{}", base_msg, pretty_json);
panic!("{}", panic_msg); // Use the constructed string
}
};
}
fn jsonb(val: Value) -> JsonB {
JsonB(val)
}
fn setup_test() {
clear_json_schemas();
}
#[pg_test]
fn test_cache_and_validate_json_schema() {
setup_test();
let schema_id = "my_schema";
let schema = json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer", "minimum": 0 }
},
"required": ["name", "age"]
});
let valid_instance = json!({ "name": "Alice", "age": 30 });
let invalid_instance_type = json!({ "name": "Bob", "age": -5 });
let invalid_instance_missing = json!({ "name": "Charlie" });
let cache_result = cache_json_schema(schema_id, jsonb(schema.clone()));
assert_success_with_json!(cache_result, "Cache operation should succeed.");
let valid_result = validate_json_schema(schema_id, jsonb(valid_instance));
assert_success_with_json!(valid_result, "Validation of valid instance should succeed.");
let invalid_result_type = validate_json_schema(schema_id, jsonb(invalid_instance_type));
assert_failure_with_json!(invalid_result_type, "Validation with invalid type should fail.");
let error_obj_type = invalid_result_type.0.get("error").expect("Expected top-level 'error' object");
let causes_age = error_obj_type.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert!(!causes_age.is_empty(), "Expected causes for invalid age");
let age_error = causes_age.iter().find(|e| e["instance_path"].as_str() == Some("/age")).expect("Missing cause for /age instance path");
let age_error_message = age_error["message"].as_str().expect("Expected string message for age error");
assert_eq!(age_error_message, "must be >=0, but got -5", "Age error message mismatch: '{}'", age_error_message);
let invalid_result_missing = validate_json_schema(schema_id, jsonb(invalid_instance_missing));
assert_failure_with_json!(invalid_result_missing, "Validation with missing field should fail.");
let error_obj_missing = invalid_result_missing.0.get("error").expect("Expected 'error' object for missing field");
let causes_missing = error_obj_missing.get("error").and_then(Value::as_array).expect("Expected nested 'error' array (causes)");
assert!(!causes_missing.is_empty(), "Expected causes for missing field");
let missing_prop_error = causes_missing.iter().find(|e| e["instance_path"].as_str() == Some("")).expect("Missing cause for root instance path");
let expected_missing_message = "missing properties 'age'";
assert_eq!(missing_prop_error["message"].as_str().expect("Expected string message for missing prop error"), expected_missing_message, "Missing property error message mismatch: '{}'", missing_prop_error["message"].as_str().unwrap_or("null"));
let non_existent_id = "non_existent_schema";
let invalid_schema_result = validate_json_schema(non_existent_id, jsonb(json!({})));
assert_failure_with_json!(invalid_schema_result, "Validation with non-existent schema should fail.");
let error_obj = invalid_schema_result.0.get("error").expect("Expected top-level 'error' object");
assert_eq!(error_obj["message"].as_str().expect("Expected message for cleared schema"), "Schema with id 'non_existent_schema' not found in cache");
}
#[pg_test]
fn test_validate_json_schema_not_cached() {
setup_test();
let instance = json!({ "foo": "bar" });
let result = validate_json_schema("non_existent_schema", jsonb(instance));
assert_failure_with_json!(result, "Validation with non-existent schema should fail.");
assert_eq!(result.0.get("success"), Some(&Value::Bool(false)), "Expected 'success': false for non-existent schema");
let error_obj = result.0.get("error").expect("Expected nested 'error' object for non-existent schema failure");
let error_message = error_obj["message"].as_str().expect("Expected message string for non-existent schema");
assert!(error_message.contains("non_existent_schema") && error_message.contains("not found"), "Error message mismatch for non-existent schema: '{}'", error_message);
}
#[pg_test]
fn test_cache_invalid_json_schema() {
setup_test();
let schema_id = "invalid_schema";
let invalid_schema = json!({ "type": "invalid" });
let cache_result = cache_json_schema(schema_id, jsonb(invalid_schema));
assert_failure_with_json!(cache_result, "Caching invalid schema should fail.");
let error_obj = cache_result.0.get("error").expect("Expected 'error' object for failed cache");
let message = error_obj.get("message").and_then(Value::as_str).expect("Message field missing");
let expected_message_start = &format!("Schema '{}' failed validation against its metaschema: ", schema_id);
assert!(message.starts_with(expected_message_start), "Compile error message start mismatch: {}", message);
}
#[pg_test]
fn test_validate_json_schema_detailed_validation_errors() {
setup_test();
let schema_id = "detailed_errors";
let schema = json!({
"type": "object",
"properties": {
"address": {
"type": "object",
"properties": {
"street": { "type": "string" },
"city": { "type": "string", "maxLength": 10 }
},
"required": ["street", "city"]
}
},
"required": ["address"]
});
let _ = cache_json_schema(schema_id, jsonb(schema));
let invalid_instance = json!({
"address": {
"street": 123,
"city": "Supercalifragilisticexpialidocious"
}
});
let result = validate_json_schema(schema_id, jsonb(invalid_instance));
assert_failure_with_json!(result, "Validation should fail for detailed errors test.");
let error_obj = result.0.get("error").expect("Expected top-level 'error' object");
assert_eq!(error_obj["message"].as_str(), Some("Validation failed due to nested errors"));
let causes_array = error_obj.get("error").and_then(Value::as_array).expect("Expected nested error array");
assert_eq!(causes_array.len(), 2, "Expected exactly 2 top-level errors (street type, city length)");
let street_error = causes_array.iter().find(|e| e["instance_path"].as_str() == Some("/address/street")).expect("Missing street error");
assert_eq!(street_error["message"].as_str().expect("Expected string message for street error"), "want string, but got number", "Street error message mismatch");
let city_error = causes_array.iter().find(|e| e["instance_path"].as_str() == Some("/address/city")).expect("Missing city error");
let expected_city_error_message = "length must be <=10, but got 34";
assert_eq!(city_error["message"].as_str().expect("Expected string message for city error"), expected_city_error_message, "City error message mismatch");
}
#[pg_test]
fn test_validate_json_schema_oneof_validation_errors() {
setup_test();
let schema_id = "oneof_schema";
let schema = json!({
"oneOf": [
{
"type": "object",
"properties": {
"string_prop": { "type": "string", "maxLength": 5 }
},
"required": ["string_prop"]
},
{
"type": "object",
"properties": {
"number_prop": { "type": "number", "minimum": 10 }
},
"required": ["number_prop"]
}
]
});
let _ = cache_json_schema(schema_id, jsonb(schema));
let expected_urn = format!("urn:{}#", schema_id);
// --- Test case 1: String length failure ---
let invalid_string_instance = json!({ "string_prop": "toolongstring" });
let result_invalid_string = validate_json_schema(schema_id, jsonb(invalid_string_instance));
assert_failure_with_json!(result_invalid_string, "Validation with invalid string length should fail");
let error_obj_string = result_invalid_string.0.get("error").expect("Expected error object (string case)");
// Check the top-level error object directly: Input matches Branch 0 type, fails maxLength validation within it.
assert_eq!(error_obj_string["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (string case)");
assert_eq!(error_obj_string["instance_path"].as_str(), Some(""), "Incorrect instance_path for string fail (string case)");
let actual_string_schema_fail_message = error_obj_string["message"].as_str().expect("Expected string message for string schema fail");
let expected_string_schema_fail_message = "Validation failed due to nested errors";
assert_eq!(actual_string_schema_fail_message, expected_string_schema_fail_message, "String schema fail message mismatch: '{}'", actual_string_schema_fail_message);
// --- Test case 2: Number type failure ---
let invalid_number_instance = json!({ "number_prop": 5 });
let result_invalid_number = validate_json_schema(schema_id, jsonb(invalid_number_instance));
assert_failure_with_json!(result_invalid_number, "Validation with invalid number should fail");
let error_obj_number = result_invalid_number.0.get("error").expect("Expected error object (number case)");
// Check the top-level error object directly: Input matches Branch 1 type, fails minimum validation within it.
assert_eq!(error_obj_number["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (number case)");
assert_eq!(error_obj_number["instance_path"].as_str(), Some(""), "Incorrect instance_path for number fail (number case)");
let actual_number_schema_fail_message_num = error_obj_number["message"].as_str().expect("Expected string message for number schema fail (number case)");
let expected_number_schema_fail_message_num = "Validation failed due to nested errors";
assert_eq!(actual_number_schema_fail_message_num, expected_number_schema_fail_message_num, "Number schema fail message mismatch (number case): '{}'", actual_number_schema_fail_message_num);
// --- Test case 3: Bool type failure ---
let invalid_bool_instance = json!({ "bool_prop": 123 });
let result_invalid_bool = validate_json_schema(schema_id, jsonb(invalid_bool_instance));
assert_failure_with_json!(result_invalid_bool, "Validation with invalid bool should fail");
let error_obj_bool = result_invalid_bool.0.get("error").expect("Expected error object (bool case)");
// Boon reports the failure for the first branch checked (Branch 0).
assert_eq!(error_obj_bool["schema_path"].as_str(), Some(expected_urn.as_str()), "Schema path mismatch (bool case)");
// Instance path is empty because the failure is at the root of the object being checked against Branch 0
assert_eq!(error_obj_bool["instance_path"].as_str(), Some(""), "Incorrect instance_path for bool fail");
let actual_bool_fail_message_0 = error_obj_bool["message"].as_str().expect("Expected string message for branch 0 type fail");
let expected_bool_fail_message_0 = "Validation failed due to nested errors";
assert_eq!(actual_bool_fail_message_0, expected_bool_fail_message_0, "Branch 0 type fail message mismatch: '{}'", actual_bool_fail_message_0);
}
#[pg_test]
fn test_clear_json_schemas() {
setup_test();
let schema_id = "schema_to_clear";
let schema = json!({ "type": "string" });
cache_json_schema(schema_id, jsonb(schema.clone()));
let show_result1 = show_json_schemas();
assert!(show_result1.contains(&schema_id.to_string()));
clear_json_schemas();
let show_result2 = show_json_schemas();
assert!(show_result2.is_empty());
let instance = json!("test");
let validate_result = validate_json_schema(schema_id, jsonb(instance));
assert_failure_with_json!(validate_result, "Validation should fail after clearing schemas.");
let error_obj = validate_result.0.get("error").expect("Expected top-level 'error' object");
assert_eq!(error_obj["message"].as_str().expect("Expected message for cleared schema"), "Schema with id 'schema_to_clear' not found in cache");
}
#[pg_test]
fn test_show_json_schemas() {
setup_test();
let schema_id1 = "schema1";
let schema_id2 = "schema2";
let schema = json!({ "type": "boolean" });
cache_json_schema(schema_id1, jsonb(schema.clone()));
cache_json_schema(schema_id2, jsonb(schema.clone()));
let result = show_json_schemas();
assert!(result.contains(&schema_id1.to_string()));
assert!(result.contains(&schema_id2.to_string()));
}

View File

@ -1 +1 @@
1.0.4
1.0.13