Compare commits

..

23 Commits

Author SHA1 Message Date
dd83f301f6 test(jspg): add automated integration test suite for inline validation, Atomic Swap concurrency, and sibling pointer routing 2026-05-26 18:00:22 -04:00
44d36a2997 version: 1.0.151 2026-05-26 16:47:09 -04:00
0091e5c226 feat: support inline json schema validation dynamically 2026-05-26 16:47:04 -04:00
2c18163961 version: 1.0.150 2026-05-25 18:30:01 -04:00
0b241c5227 feat(queryer): support polymorphic inherited queries with IN clause and SQL notices 2026-05-25 18:29:43 -04:00
3736c9d8f0 version: 1.0.149 2026-05-21 19:04:00 -04:00
ccca9129b2 added uuid.condition to filters 2026-05-21 19:03:31 -04:00
333fc69735 version: 1.0.148 2026-05-21 13:26:18 -04:00
b0fc6c12ef fixed queryer issue with nested families 2026-05-21 13:26:07 -04:00
0d14162ef4 version: 1.0.147 2026-05-20 19:12:03 -04:00
b755bc6dbd version: 1.0.146 2026-05-20 19:10:39 -04:00
56775c8c1b added traits and include features with docs 2026-05-20 19:10:29 -04:00
a32cb3a4da version: 1.0.145 2026-05-18 19:46:43 -04:00
9cefc225fc fixed type and page action serialization 2026-05-18 19:46:29 -04:00
4874c09fb5 version: 1.0.144 2026-05-14 18:14:10 -04:00
86d49273bc more ordering fixes 2026-05-14 18:13:59 -04:00
724a9e3e44 version: 1.0.143 2026-05-14 17:35:44 -04:00
5b2feb5ea7 more ordering fixes 2026-05-14 17:35:31 -04:00
473b087d97 version: 1.0.142 2026-05-14 14:48:19 -04:00
6d6745d95d removed all jsonb 2026-05-14 14:48:09 -04:00
146efaa2d9 version: 1.0.141 2026-05-14 14:01:41 -04:00
d0294eec3f last ordering fixes 2026-05-14 13:57:50 -04:00
02ab4b6438 version: 1.0.140 2026-05-14 05:58:58 -04:00
22 changed files with 1345 additions and 169 deletions

View File

@ -179,7 +179,37 @@ In the Punc architecture, filters are automatically synthesized, strongly-typed
* **Inherited Properties**: Filters automatically inherit all valid database columns from their base type schema, immediately converting them to their respective `.condition` schemas.
* **Relational Proxies**: If a table has a foreign key to another table, the filter automatically generates a proxy property pointing to the related entity's filter (e.g., the `person` filter automatically gains an `organization` property that points to `organization.filter`), allowing infinitely deep nested queries natively.
* **Logical Operators (`$and`, `$or`)**: Every filter automatically includes `$and` and `$or` arrays, which recursively accept the exact same filter schema, allowing complex logical grouping.
* **Ad-Hoc Extensions (`ad_hoc`)**: Fields stored purely in JSONB bubbles that lack formal database columns can still be queried using the `ad_hoc` object, which passes standard, unvalidated string conditions.
* Ad-Hoc Extensions (`ad_hoc`)**: Fields stored purely in JSONB bubbles that lack formal database columns can still be queried using the `ad_hoc` object, which passes standard, unvalidated string conditions.
### Trait-Based Schema Composition (`traits` & `include`)
Traits are reusable, non-generating schema fragments used to share properties and relationships horizontally across multiple schemas. They do not generate separate Go/Dart classes.
* **Traits Namespace**: Defined in a sibling `"traits"` block next to `"schemas"` inside table comments:
```json
"traits": {
"emailable": {
"properties": {
"email_addresses": {
"type": "array",
"items": { "type": "contact", "properties": { "target": { "type": "email_address" } } }
}
}
}
}
```
* **Include Keyword**: Schemas or traits can use the `"include"` array to compose traits or other schemas:
```json
"full.person": {
"type": "person",
"include": ["contactable", "owner"]
}
```
* **Resolution and Merging**: During `Database::new()`, includes are resolved and merged at the raw JSON level:
* **`properties` / `patternProperties`**: Map keys from the host schema override/shadow included traits.
* **`required` / `display`**: Lists are merged and deduped.
* **`dependencies`**: Merged by combining and deduping lists.
* **Scalars / Arrays / Items**: Host definitions completely override included traits.
* The `"include"` keyword is stripped, and `"traits"` maps are omitted from serialization.
---

View File

@ -70,6 +70,10 @@
"type": "string",
"format": "date-time"
},
"uuid_field": {
"type": "string",
"format": "uuid"
},
"tags": {
"type": "array",
"items": {
@ -181,6 +185,17 @@
]
}
}
},
"uuid.condition": {
"type": "condition",
"properties": {
"$eq": {
"type": [
"string",
"null"
]
}
}
}
}
}
@ -244,6 +259,7 @@
"billing_address",
"gender",
"birth_date",
"uuid_field",
"tags",
"ad_hoc",
"$and",
@ -258,6 +274,7 @@
"billing_address",
"gender",
"birth_date",
"uuid_field",
"tags",
"ad_hoc",
"$and",
@ -278,6 +295,7 @@
"billing_address",
"gender",
"birth_date",
"uuid_field",
"tags",
"ad_hoc",
"$and",
@ -325,6 +343,12 @@
"null"
]
},
"uuid_field": {
"type": [
"uuid.condition",
"null"
]
},
"first_name": {
"type": [
"string.condition",
@ -396,6 +420,7 @@
"string.condition": {},
"integer.condition": {},
"date.condition": {},
"uuid.condition": {},
"search": {},
"search.filter": {
"type": "filter",

View File

@ -59,6 +59,17 @@
}
}
}
},
{
"name": "get_counterparty_orders",
"schemas": {
"get_counterparty_orders.response": {
"type": "array",
"items": {
"type": "counterparty.order"
}
}
}
}
],
"enums": [],
@ -734,6 +745,14 @@
}
}
},
"counterparty.order": {
"type": "order",
"properties": {
"counterparty": {
"family": "organization"
}
}
},
"light.order": {
"type": "order",
"properties": {
@ -2332,6 +2351,92 @@
]
]
}
},
{
"description": "Order select with nested polymorphic counterparty family relation",
"action": "query",
"schema_id": "get_counterparty_orders.response",
"expect": {
"success": true,
"sql": [
[
"((SELECT jsonb_strip_nulls((",
" SELECT COALESCE(jsonb_agg(jsonb_build_object(",
" 'id', order_1.id,",
" 'type', order_1.type,",
" 'archived', entity_2.archived,",
" 'created_at', entity_2.created_at,",
" 'total', order_1.total,",
" 'customer_id', order_1.customer_id,",
" 'counterparty', (",
" SELECT CASE",
" WHEN organization_3.type = 'bot' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_7.id,",
" 'type', entity_7.type,",
" 'archived', entity_7.archived,",
" 'created_at', entity_7.created_at,",
" 'name', organization_6.name,",
" 'token', bot_5.token,",
" 'role', bot_5.role",
" )",
" FROM agreego.bot bot_5",
" JOIN agreego.organization organization_6 ON organization_6.id = bot_5.id",
" JOIN agreego.entity entity_7 ON entity_7.id = organization_6.id",
" WHERE",
" NOT entity_7.archived",
" AND entity_7.id = entity_4.id",
" ))",
" WHEN organization_3.type = 'organization' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_9.id,",
" 'type', entity_9.type,",
" 'archived', entity_9.archived,",
" 'created_at', entity_9.created_at,",
" 'name', organization_8.name",
" )",
" FROM agreego.organization organization_8",
" JOIN agreego.entity entity_9 ON entity_9.id = organization_8.id",
" WHERE",
" NOT entity_9.archived",
" AND entity_9.id = entity_4.id",
" ))",
" WHEN organization_3.type = 'person' THEN ((",
" SELECT jsonb_build_object(",
" 'id', entity_12.id,",
" 'type', entity_12.type,",
" 'archived', entity_12.archived,",
" 'created_at', entity_12.created_at,",
" 'name', organization_11.name,",
" 'first_name', person_10.first_name,",
" 'last_name', person_10.last_name,",
" 'age', person_10.age",
" )",
" FROM agreego.person person_10",
" JOIN agreego.organization organization_11 ON organization_11.id = person_10.id",
" JOIN agreego.entity entity_12 ON entity_12.id = organization_11.id",
" WHERE",
" NOT entity_12.archived",
" AND entity_12.id = entity_4.id",
" ))",
" ELSE NULL",
" END",
" FROM agreego.organization organization_3",
" JOIN agreego.entity entity_4 ON entity_4.id = organization_3.id",
" WHERE",
" NOT entity_4.archived",
" AND order_1.counterparty_id = entity_4.id",
" )",
" )), '[]'::jsonb)",
" FROM agreego.order order_1",
" JOIN agreego.entity entity_2 ON entity_2.id = order_1.id",
" WHERE",
" NOT entity_2.archived",
" AND order_1.counterparty_type IN ('bot', 'organization', 'person')",
"))))"
]
]
}
}
]
}

191
fixtures/traits.json Normal file
View File

@ -0,0 +1,191 @@
[
{
"description": "Granular trait composition and list merging",
"database": {
"types": [
{
"name": "person",
"schemas": {
"full.person": {
"type": "object",
"include": ["emailable", "phonable"],
"properties": {
"name": { "type": "string" }
},
"required": ["name"]
}
},
"traits": {
"emailable": {
"properties": {
"email": { "type": "string" }
},
"required": ["email"],
"display": ["email"]
},
"phonable": {
"properties": {
"phone": { "type": "string" }
},
"required": ["phone"],
"display": ["phone"]
}
}
}
]
},
"tests": [
{
"description": "valid person with name, email, and phone passes",
"schema_id": "full.person",
"action": "validate",
"data": {
"name": "Jane Doe",
"email": "jane@example.com",
"phone": "555-1234"
},
"expect": {
"success": true
}
},
{
"description": "missing email fails validation",
"schema_id": "full.person",
"action": "validate",
"data": {
"name": "Jane Doe",
"phone": "555-1234"
},
"expect": {
"success": false,
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"details": {
"path": "email"
}
}
]
}
}
]
},
{
"description": "Local property shadowing",
"database": {
"types": [
{
"name": "person",
"schemas": {
"full.person": {
"type": "object",
"include": ["emailable"],
"properties": {
"email": {
"type": "string",
"maxLength": 5
}
}
}
},
"traits": {
"emailable": {
"properties": {
"email": { "type": "string" }
}
}
}
}
]
},
"tests": [
{
"description": "local maxLength overrides trait properties",
"schema_id": "full.person",
"action": "validate",
"data": {
"email": "longerthanfive@example.com"
},
"expect": {
"success": false,
"errors": [
{
"code": "MAX_LENGTH_VIOLATED",
"details": {
"path": "email"
}
}
]
}
}
]
},
{
"description": "Missing trait compiler error",
"database": {
"types": [
{
"name": "person",
"schemas": {
"full.person": {
"type": "object",
"include": ["nonexistent_trait"]
}
}
}
]
},
"tests": [
{
"description": "emits TRAIT_NOT_FOUND compile error",
"action": "compile",
"expect": {
"success": false,
"errors": [
{
"code": "TRAIT_NOT_FOUND"
}
]
}
}
]
},
{
"description": "Circular inclusion compiler error",
"database": {
"types": [
{
"name": "person",
"schemas": {
"full.person": {
"type": "object",
"include": ["trait_a"]
}
},
"traits": {
"trait_a": {
"include": ["trait_b"]
},
"trait_b": {
"include": ["trait_a"]
}
}
}
]
},
"tests": [
{
"description": "emits CIRCULAR_INCLUDE_DETECTED compile error",
"action": "compile",
"expect": {
"success": false,
"errors": [
{
"code": "CIRCULAR_INCLUDE_DETECTED"
}
]
}
}
]
}
]

12
src/database/action.rs Normal file
View File

@ -0,0 +1,12 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Action {
#[serde(skip_serializing_if = "Option::is_none")]
pub punc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub navigate: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub launch: Option<String>,
}

View File

@ -141,6 +141,8 @@ impl Schema {
if let Some(fmt) = &schema.obj.format {
if fmt == "date-time" {
return Some(vec!["date.condition".to_string()]);
} else if fmt == "uuid" {
return Some(vec!["uuid.condition".to_string()]);
}
}
Some(vec!["string.condition".to_string()])

301
src/database/compose/mod.rs Normal file
View File

@ -0,0 +1,301 @@
use std::collections::{HashMap, HashSet};
use serde_json::Value;
pub fn compose(val: &mut Value, errors: &mut Vec<crate::drop::Error>) -> Result<(), String> {
let _ = std::fs::write("/Users/awgneo/Repositories/thoughtpatterns/cellular/jspg/traits_debug_val.json", serde_json::to_string_pretty(val).unwrap());
let mut traits = HashMap::new();
let mut schemas = HashMap::new();
// 1. Gather all traits and schemas from enums, types, and puncs arrays
let arrays = ["enums", "types", "puncs"];
for arr_name in &arrays {
if let Some(arr) = val.get(arr_name).and_then(|v| v.as_array()) {
for item in arr {
if let Some(item_traits) = item.get("traits").and_then(|v| v.as_object()) {
for (name, trait_val) in item_traits {
traits.insert(name.clone(), trait_val.clone());
}
}
if let Some(item_schemas) = item.get("schemas").and_then(|v| v.as_object()) {
for (name, schema_val) in item_schemas {
schemas.insert(name.clone(), schema_val.clone());
}
}
}
}
}
// 2. Resolve inclusions recursively in all schema objects
for arr_name in &arrays {
if let Some(arr) = val.get_mut(arr_name).and_then(|v| v.as_array_mut()) {
for item in arr {
if let Some(item_schemas) = item.get_mut("schemas").and_then(|v| v.as_object_mut()) {
for (schema_id, schema_val) in item_schemas {
let mut visited = HashSet::new();
resolve_in_place(
schema_val,
&traits,
&schemas,
errors,
schema_id,
schema_id,
&mut visited,
);
}
}
}
}
}
// 3. Strip the "traits" block from each item in enums, types, puncs so it doesn't serialize
for arr_name in &arrays {
if let Some(arr) = val.get_mut(arr_name).and_then(|v| v.as_array_mut()) {
for item in arr {
if let Some(obj) = item.as_object_mut() {
obj.remove("traits");
}
}
}
}
Ok(())
}
fn resolve_in_place(
current: &mut Value,
traits: &HashMap<String, Value>,
schemas: &HashMap<String, Value>,
errors: &mut Vec<crate::drop::Error>,
schema_id: &str,
path: &str,
visited: &mut HashSet<String>,
) {
if !current.is_object() {
return;
}
let include_opt = current.as_object_mut().and_then(|obj| obj.remove("include"));
if let Some(include_val) = include_opt {
if let Some(include_arr) = include_val.as_array() {
let mut merged_props = serde_json::Map::new();
let mut merged_required = HashSet::new();
let mut merged_display = HashSet::new();
let mut merged_dependencies = serde_json::Map::new();
let mut merged_pattern_props = serde_json::Map::new();
// Read current values first to let host override included properties
if let Some(req) = current.get("required").and_then(|v| v.as_array()) {
for r in req {
if let Some(s) = r.as_str() {
merged_required.insert(s.to_string());
}
}
}
if let Some(disp) = current.get("display").and_then(|v| v.as_array()) {
for d in disp {
if let Some(s) = d.as_str() {
merged_display.insert(s.to_string());
}
}
}
if let Some(deps) = current.get("dependencies").and_then(|v| v.as_object()) {
for (k, v) in deps {
merged_dependencies.insert(k.clone(), v.clone());
}
}
if let Some(pat_props) = current.get("patternProperties").and_then(|v| v.as_object()) {
for (k, v) in pat_props {
merged_pattern_props.insert(k.clone(), v.clone());
}
}
if let Some(props) = current.get("properties").and_then(|v| v.as_object()) {
for (k, v) in props {
merged_props.insert(k.clone(), v.clone());
}
}
for inc in include_arr {
if let Some(inc_name) = inc.as_str() {
if visited.contains(inc_name) {
errors.push(crate::drop::Error {
code: "CIRCULAR_INCLUDE_DETECTED".to_string(),
message: format!("Circular inclusion detected for '{}'", inc_name),
details: crate::drop::ErrorDetails {
schema: Some(schema_id.to_string()),
path: Some(path.to_string()),
..Default::default()
},
});
continue;
}
let target_opt = traits.get(inc_name).or_else(|| schemas.get(inc_name));
if let Some(target_val) = target_opt {
let mut resolved_target = target_val.clone();
visited.insert(inc_name.to_string());
resolve_in_place(
&mut resolved_target,
traits,
schemas,
errors,
schema_id,
&format!("{}/include/{}", path, inc_name),
visited,
);
visited.remove(inc_name);
// Merge properties (host overrides trait)
if let Some(target_props) = resolved_target.get("properties").and_then(|v| v.as_object()) {
for (k, v) in target_props {
if !merged_props.contains_key(k) {
merged_props.insert(k.clone(), v.clone());
}
}
}
// Merge patternProperties (host overrides trait)
if let Some(target_pat_props) = resolved_target.get("patternProperties").and_then(|v| v.as_object()) {
for (k, v) in target_pat_props {
if !merged_pattern_props.contains_key(k) {
merged_pattern_props.insert(k.clone(), v.clone());
}
}
}
// Merge required
if let Some(target_req) = resolved_target.get("required").and_then(|v| v.as_array()) {
for r in target_req {
if let Some(s) = r.as_str() {
merged_required.insert(s.to_string());
}
}
}
// Merge display
if let Some(target_disp) = resolved_target.get("display").and_then(|v| v.as_array()) {
for d in target_disp {
if let Some(s) = d.as_str() {
merged_display.insert(s.to_string());
}
}
}
// Merge dependencies
if let Some(target_deps) = resolved_target.get("dependencies").and_then(|v| v.as_object()) {
for (dep_prop, dep_val) in target_deps {
if let Some(existing_val) = merged_dependencies.get_mut(dep_prop) {
if let (Some(arr_existing), Some(arr_target)) = (existing_val.as_array_mut(), dep_val.as_array()) {
let mut set: HashSet<String> = arr_existing.iter().filter_map(|x| x.as_str().map(String::from)).collect();
for x in arr_target {
if let Some(s) = x.as_str() {
if set.insert(s.to_string()) {
arr_existing.push(Value::String(s.to_string()));
}
}
}
}
} else {
merged_dependencies.insert(dep_prop.clone(), dep_val.clone());
}
}
}
// Inherit other non-merged schemas/scalars if not defined in host (type, items, cases, family, format, etc.)
if let Some(obj) = current.as_object_mut() {
for (k, v) in resolved_target.as_object().unwrap() {
if k != "properties" && k != "patternProperties" && k != "required" && k != "display" && k != "dependencies" && k != "include" {
if !obj.contains_key(k) {
obj.insert(k.clone(), v.clone());
}
}
}
}
} else {
errors.push(crate::drop::Error {
code: "TRAIT_NOT_FOUND".to_string(),
message: format!("Trait or schema '{}' not found for inclusion", inc_name),
details: crate::drop::ErrorDetails {
schema: Some(schema_id.to_string()),
path: Some(path.to_string()),
..Default::default()
},
});
}
}
}
if let Some(obj) = current.as_object_mut() {
if !merged_props.is_empty() {
obj.insert("properties".to_string(), Value::Object(merged_props));
}
if !merged_pattern_props.is_empty() {
obj.insert("patternProperties".to_string(), Value::Object(merged_pattern_props));
}
if !merged_required.is_empty() {
let mut req_vec: Vec<Value> = merged_required.into_iter().map(Value::String).collect();
req_vec.sort_by(|a, b| a.as_str().unwrap().cmp(b.as_str().unwrap()));
obj.insert("required".to_string(), Value::Array(req_vec));
}
if !merged_display.is_empty() {
let mut disp_vec: Vec<Value> = merged_display.into_iter().map(Value::String).collect();
disp_vec.sort_by(|a, b| a.as_str().unwrap().cmp(b.as_str().unwrap()));
obj.insert("display".to_string(), Value::Array(disp_vec));
}
if !merged_dependencies.is_empty() {
obj.insert("dependencies".to_string(), Value::Object(merged_dependencies));
}
}
}
}
// Recursively process children
if let Some(obj) = current.as_object_mut() {
if let Some(props) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
for (k, v) in props {
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/{}", path, k), visited);
}
}
if let Some(pat_props) = obj.get_mut("patternProperties").and_then(|v| v.as_object_mut()) {
for (k, v) in pat_props {
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/{}", path, k), visited);
}
}
if let Some(items) = obj.get_mut("items") {
resolve_in_place(items, traits, schemas, errors, schema_id, &format!("{}/items", path), visited);
}
if let Some(prefix_items) = obj.get_mut("prefixItems").and_then(|v| v.as_array_mut()) {
for (i, v) in prefix_items.iter_mut().enumerate() {
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/prefixItems/{}", path, i), visited);
}
}
if let Some(additional_props) = obj.get_mut("additionalProperties") {
resolve_in_place(additional_props, traits, schemas, errors, schema_id, &format!("{}/additionalProperties", path), visited);
}
if let Some(one_of) = obj.get_mut("oneOf").and_then(|v| v.as_array_mut()) {
for (i, v) in one_of.iter_mut().enumerate() {
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/oneOf/{}", path, i), visited);
}
}
if let Some(contains) = obj.get_mut("contains") {
resolve_in_place(contains, traits, schemas, errors, schema_id, &format!("{}/contains", path), visited);
}
if let Some(not) = obj.get_mut("not") {
resolve_in_place(not, traits, schemas, errors, schema_id, &format!("{}/not", path), visited);
}
if let Some(cases) = obj.get_mut("cases").and_then(|v| v.as_array_mut()) {
for (i, c_val) in cases.iter_mut().enumerate() {
if let Some(c_obj) = c_val.as_object_mut() {
if let Some(when) = c_obj.get_mut("when") {
resolve_in_place(when, traits, schemas, errors, schema_id, &format!("{}/cases/{}/when", path, i), visited);
}
if let Some(then) = c_obj.get_mut("then") {
resolve_in_place(then, traits, schemas, errors, schema_id, &format!("{}/cases/{}/then", path, i), visited);
}
if let Some(else_) = c_obj.get_mut("else") {
resolve_in_place(else_, traits, schemas, errors, schema_id, &format!("{}/cases/{}/else", path, i), visited);
}
}
}
}
}
}

View File

@ -1,4 +1,6 @@
pub mod action;
pub mod compile;
pub mod compose;
pub mod edge;
pub mod r#enum;
pub mod executors;
@ -40,7 +42,7 @@ pub struct Database {
}
impl Database {
pub fn new(val: &serde_json::Value) -> (Self, crate::drop::Drop) {
pub fn new(mut val: serde_json::Value) -> (Self, crate::drop::Drop) {
let mut db = Self {
enums: IndexMap::new(),
types: IndexMap::new(),
@ -55,101 +57,115 @@ impl Database {
let mut errors = Vec::new();
if let Some(arr) = val.get("enums").and_then(|v| v.as_array()) {
for item in arr {
match serde_json::from_value::<Enum>(item.clone()) {
Ok(def) => {
db.enums.insert(def.name.clone(), def);
}
Err(e) => {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
errors.push(crate::drop::Error {
code: "DATABASE_ENUM_PARSE_FAILED".to_string(),
message: format!("Failed to parse database enum '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
}
if let Err(e) = compose::compose(&mut val, &mut errors) {
errors.push(crate::drop::Error {
code: "COMPOSE_FAILED".to_string(),
message: format!("Fatal error during trait composition: {}", e),
details: crate::drop::ErrorDetails::default(),
});
}
if let Some(arr) = val.get("types").and_then(|v| v.as_array()) {
for item in arr {
match serde_json::from_value::<Type>(item.clone()) {
Ok(def) => {
db.types.insert(def.name.clone(), def);
}
Err(e) => {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
errors.push(crate::drop::Error {
code: "DATABASE_TYPE_PARSE_FAILED".to_string(),
message: format!("Failed to parse database type '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
}
}
if let Some(arr) = val.get("relations").and_then(|v| v.as_array()) {
for item in arr {
match serde_json::from_value::<Relation>(item.clone()) {
Ok(def) => {
if db.types.contains_key(&def.source_type)
&& db.types.contains_key(&def.destination_type)
{
db.relations.insert(def.constraint.clone(), def);
if let serde_json::Value::Object(mut map) = val {
if let Some(serde_json::Value::Array(arr)) = map.remove("enums") {
for item in arr {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
match serde_json::from_value::<Enum>(item) {
Ok(def) => {
db.enums.insert(def.name.clone(), def);
}
Err(e) => {
errors.push(crate::drop::Error {
code: "DATABASE_ENUM_PARSE_FAILED".to_string(),
message: format!("Failed to parse database enum '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
Err(e) => {
let constraint = item
.get("constraint")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
errors.push(crate::drop::Error {
code: "DATABASE_RELATION_PARSE_FAILED".to_string(),
message: format!("Failed to parse database relation '{}': {}", constraint, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(constraint)),
..Default::default()
},
});
}
}
if let Some(serde_json::Value::Array(arr)) = map.remove("types") {
for item in arr {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
match serde_json::from_value::<Type>(item) {
Ok(def) => {
db.types.insert(def.name.clone(), def);
}
Err(e) => {
errors.push(crate::drop::Error {
code: "DATABASE_TYPE_PARSE_FAILED".to_string(),
message: format!("Failed to parse database type '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
}
}
}
if let Some(arr) = val.get("puncs").and_then(|v| v.as_array()) {
for item in arr {
match serde_json::from_value::<Punc>(item.clone()) {
Ok(def) => {
db.puncs.insert(def.name.clone(), def);
if let Some(serde_json::Value::Array(arr)) = map.remove("relations") {
for item in arr {
let constraint = item
.get("constraint")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
match serde_json::from_value::<Relation>(item) {
Ok(def) => {
if db.types.contains_key(&def.source_type)
&& db.types.contains_key(&def.destination_type)
{
db.relations.insert(def.constraint.clone(), def);
}
}
Err(e) => {
errors.push(crate::drop::Error {
code: "DATABASE_RELATION_PARSE_FAILED".to_string(),
message: format!("Failed to parse database relation '{}': {}", constraint, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(constraint)),
..Default::default()
},
});
}
}
Err(e) => {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
errors.push(crate::drop::Error {
code: "DATABASE_PUNC_PARSE_FAILED".to_string(),
message: format!("Failed to parse database punc '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
if let Some(serde_json::Value::Array(arr)) = map.remove("puncs") {
for item in arr {
let name = item
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
match serde_json::from_value::<Punc>(item) {
Ok(def) => {
db.puncs.insert(def.name.clone(), def);
}
Err(e) => {
errors.push(crate::drop::Error {
code: "DATABASE_PUNC_PARSE_FAILED".to_string(),
message: format!("Failed to parse database punc '{}': {}", name, e),
details: crate::drop::ErrorDetails {
context: Some(serde_json::json!(name)),
..Default::default()
},
});
}
}
}
}

View File

@ -1,7 +1,8 @@
use crate::database::action::Action;
use crate::database::schema::Schema;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use indexmap::IndexMap;
use std::sync::Arc;
use std::sync::OnceLock;
@ -219,14 +220,6 @@ pub enum SchemaTypeOrArray {
Multiple(Vec<String>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
#[serde(skip_serializing_if = "Option::is_none")]
pub navigate: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub punc: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Dependency {

View File

@ -1,3 +1,4 @@
use crate::database::action::Action;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
@ -22,14 +23,3 @@ pub struct Sidebar {
#[serde(skip_serializing_if = "Option::is_none")]
pub priority: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct Action {
#[serde(skip_serializing_if = "Option::is_none")]
pub punc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub navigate: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub present: Option<String>,
}

View File

@ -12,7 +12,7 @@ pub struct Jspg {
}
impl Jspg {
pub fn new(database_val: &serde_json::Value) -> (Self, crate::drop::Drop) {
pub fn new(database_val: serde_json::Value) -> (Self, crate::drop::Drop) {
let (database_instance, drop) = Database::new(database_val);
let database = Arc::new(database_instance);
let validator = Validator::new(database.clone());

View File

@ -7,6 +7,9 @@ pg_module_magic!();
#[cfg(test)]
pub struct JsonB(pub serde_json::Value);
#[cfg(test)]
pub struct Json(pub serde_json::Value);
pub mod database;
pub mod drop;
pub mod jspg;
@ -41,8 +44,8 @@ fn jspg_failure() -> JsonB {
}
#[cfg_attr(not(test), pg_extern(strict))]
pub fn jspg_setup(database: JsonB) -> JsonB {
let (new_jspg, drop) = crate::jspg::Jspg::new(&database.0);
pub fn jspg_setup(database: Json) -> Json {
let (new_jspg, drop) = crate::jspg::Jspg::new(database.0);
let new_arc = Arc::new(new_jspg);
// 3. ATOMIC SWAP
@ -51,7 +54,7 @@ pub fn jspg_setup(database: JsonB) -> JsonB {
*lock = Some(new_arc);
}
JsonB(serde_json::to_value(drop).unwrap())
Json(serde_json::to_value(drop).unwrap())
}
#[cfg_attr(not(test), pg_extern)]
@ -71,6 +74,22 @@ pub fn jspg_merge(schema_id: &str, data: JsonB) -> JsonB {
}
}
#[cfg_attr(not(test), pg_extern)]
pub fn jspg_merge_ordered(schema_id: &str, data: Json) -> Json {
let engine_opt = {
let lock = GLOBAL_JSPG.read().unwrap();
lock.clone()
};
match engine_opt {
Some(engine) => {
let drop = engine.merger.merge(schema_id, data.0);
Json(serde_json::to_value(drop).unwrap())
}
None => Json(jspg_failure().0),
}
}
#[cfg_attr(not(test), pg_extern)]
pub fn jspg_query(schema_id: &str, filter: Option<JsonB>) -> JsonB {
let engine_opt = {
@ -109,7 +128,7 @@ pub fn jspg_validate(schema_id: &str, instance: JsonB) -> JsonB {
}
#[cfg_attr(not(test), pg_extern)]
pub fn jspg_database() -> JsonB {
pub fn jspg_database() -> Json {
let engine_opt = {
let lock = GLOBAL_JSPG.read().unwrap();
lock.clone()
@ -120,9 +139,9 @@ pub fn jspg_database() -> JsonB {
let database_json = serde_json::to_value(&engine.database)
.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
let drop = crate::drop::Drop::success_with_val(database_json);
JsonB(serde_json::to_value(drop).unwrap())
Json(serde_json::to_value(drop).unwrap())
}
None => jspg_failure(),
None => Json(jspg_failure().0),
}
}

View File

@ -213,6 +213,7 @@ impl<'a> Compiler<'a> {
let mut case_node = node.clone();
case_node.parent_alias = base_alias.clone();
case_node.property_name = None;
let arc_aliases = std::sync::Arc::new(table_aliases.clone());
case_node.parent_type_aliases = Some(arc_aliases);
case_node.parent_type = Some(r#type);
@ -602,7 +603,7 @@ impl<'a> Compiler<'a> {
if let Some(type_name) = bound_type_name {
// Ensure this type actually exists
if self.db.types.contains_key(&type_name) {
if let Some(type_def) = self.db.types.get(&type_name) {
if let Some(relation) = self.db.relations.get(&edge.constraint) {
let mut poly_col = None;
let mut table_to_alias = "";
@ -620,7 +621,23 @@ impl<'a> Compiler<'a> {
.get(table_to_alias)
.or_else(|| type_aliases.get(&node.parent_alias))
{
where_clauses.push(format!("{}.{} = '{}'", alias, col, type_name));
// DEBUG: See what variations we have for this type
#[cfg(not(test))]
pgrx::notice!("JSPG_POLY_BOUNDS: type={}, col={}, variations_len={}, variations={:?}", type_name, col, type_def.variations.len(), type_def.variations);
// Use IN clause with all variations to support inherited types.
// e.g., "asset" has variations ["asset", "property", "unit", ...]
// so target_type IN ('asset','property','unit') instead of = 'asset'
if type_def.variations.len() > 1 {
let quoted: Vec<String> = type_def.variations.iter()
.map(|v| format!("'{}'", v))
.collect();
where_clauses.push(format!(
"{}.{} IN ({})", alias, col, quoted.join(", ")
));
} else {
where_clauses.push(format!("{}.{} = '{}'", alias, col, type_name));
}
}
}
}

View File

@ -50,6 +50,10 @@ impl Queryer {
Err(drop) => return drop,
};
// DEBUG: Emit compiled SQL as a NOTICE for inspection
#[cfg(not(test))]
pgrx::notice!("JSPG_SQL[{}]: {}", schema_id, sql);
// 3. Execute via Database Executor
self.execute_sql(schema_id, &sql, args)
}

View File

@ -1499,6 +1499,12 @@ fn test_queryer_0_14() {
crate::tests::runner::run_test_case(&path, 0, 14).unwrap();
}
#[test]
fn test_queryer_0_15() {
let path = format!("{}/fixtures/queryer.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 0, 15).unwrap();
}
#[test]
fn test_polymorphism_0_0() {
let path = format!("{}/fixtures/polymorphism.json", env!("CARGO_MANIFEST_DIR"));
@ -2141,6 +2147,36 @@ fn test_items_15_2() {
crate::tests::runner::run_test_case(&path, 15, 2).unwrap();
}
#[test]
fn test_traits_0_0() {
let path = format!("{}/fixtures/traits.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 0, 0).unwrap();
}
#[test]
fn test_traits_0_1() {
let path = format!("{}/fixtures/traits.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 0, 1).unwrap();
}
#[test]
fn test_traits_1_0() {
let path = format!("{}/fixtures/traits.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 1, 0).unwrap();
}
#[test]
fn test_traits_2_0() {
let path = format!("{}/fixtures/traits.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 2, 0).unwrap();
}
#[test]
fn test_traits_3_0() {
let path = format!("{}/fixtures/traits.json", env!("CARGO_MANIFEST_DIR"));
crate::tests::runner::run_test_case(&path, 3, 0).unwrap();
}
#[test]
fn test_enum_0_0() {
let path = format!("{}/fixtures/enum.json", env!("CARGO_MANIFEST_DIR"));

View File

@ -0,0 +1,177 @@
use crate::*;
use serde_json::json;
fn setup_dynamic_pointer_db() {
let db_json = json!({
"puncs": [],
"enums": [],
"relations": [],
"types": [
{
"name": "bid.evaluation_context",
"variations": ["bid.evaluation_context"],
"hierarchy": ["bid.evaluation_context", "entity"],
"schemas": {
"bid.evaluation_context": {
"type": "object",
"properties": {
"amount": { "type": "number" }
},
"required": ["amount"]
}
}
},
{
"name": "work_order.evaluation_context",
"variations": ["work_order.evaluation_context"],
"hierarchy": ["work_order.evaluation_context", "entity"],
"schemas": {
"work_order.evaluation_context": {
"type": "object",
"properties": {
"vendor_id": { "type": "string" }
},
"required": ["vendor_id"]
}
}
},
{
"name": "evaluation_rule",
"variations": ["evaluation_rule"],
"hierarchy": ["evaluation_rule", "entity"],
"schemas": {
"evaluation_rule": {
"type": "object",
"properties": {
"entity_type": { "type": "string" },
"evaluation_context": { "type": "$entity_type.evaluation_context" }
},
"required": ["entity_type", "evaluation_context"]
}
}
}
]
});
let setup_res = jspg_setup(Json(db_json));
assert_eq!(
setup_res.0,
json!({
"type": "drop",
"response": "success"
})
);
}
fn test_structural_inheritance_dynamic_pointer() {
setup_dynamic_pointer_db();
// 1. Happy path: entity_type = bid, evaluation_context matches bid.evaluation_context
let happy_bid = json!({
"entity_type": "bid",
"evaluation_context": {
"amount": 5000
}
});
let res_happy_bid = jspg_validate("evaluation_rule", JsonB(happy_bid));
assert_eq!(
res_happy_bid.0,
json!({
"type": "drop",
"response": "success"
})
);
// 2. Happy path: entity_type = work_order, evaluation_context matches work_order.evaluation_context
let happy_wo = json!({
"entity_type": "work_order",
"evaluation_context": {
"vendor_id": "vendor-123"
}
});
let res_happy_wo = jspg_validate("evaluation_rule", JsonB(happy_wo));
assert_eq!(
res_happy_wo.0,
json!({
"type": "drop",
"response": "success"
})
);
// 3. Unhappy path: entity_type = bid but evaluation_context has invalid schema (missing required field 'amount')
let unhappy_bid = json!({
"entity_type": "bid",
"evaluation_context": {
"vendor_id": "vendor-123"
}
});
let res_unhappy_bid = jspg_validate("evaluation_rule", JsonB(unhappy_bid));
assert_eq!(
res_unhappy_bid.0,
json!({
"type": "drop",
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Missing amount",
"details": { "path": "evaluation_context/amount" }
},
{
"code": "STRICT_PROPERTY_VIOLATION",
"message": "Unexpected property 'vendor_id'",
"details": { "path": "evaluation_context/vendor_id" }
}
]
})
);
// 4. Missing discriminator: dynamic pointer cannot resolve property 'entity_type'
let missing_disc = json!({
"evaluation_context": {}
});
let res_missing_disc = jspg_validate("evaluation_rule", JsonB(missing_disc));
assert_eq!(
res_missing_disc.0,
json!({
"type": "drop",
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Missing entity_type",
"details": { "path": "entity_type" }
},
{
"code": "DYNAMIC_TYPE_RESOLUTION_FAILED",
"message": "Dynamic type pointer '$entity_type.evaluation_context' could not resolve discriminator property 'entity_type' on parent instance",
"details": { "path": "evaluation_context" }
}
]
})
);
// 5. Unregistered discriminator: target not found in registry
let unknown_disc = json!({
"entity_type": "unknown",
"evaluation_context": {}
});
let res_unknown_disc = jspg_validate("evaluation_rule", JsonB(unknown_disc));
assert_eq!(
res_unknown_disc.0,
json!({
"type": "drop",
"errors": [
{
"code": "DYNAMIC_TYPE_RESOLUTION_FAILED",
"message": "Resolved dynamic type pointer 'unknown.evaluation_context' was not found in schema registry",
"details": { "path": "evaluation_context" }
}
]
})
);
let _ = jspg_teardown();
}
pub fn run_all() {
test_structural_inheritance_dynamic_pointer();
}

View File

@ -0,0 +1,124 @@
use crate::*;
use serde_json::json;
fn setup_simple_db() {
let db_json = json!({
"puncs": [],
"enums": [],
"relations": [],
"types": [
{
"name": "person",
"variations": ["person"],
"hierarchy": ["person", "entity"],
"schemas": {
"person": {
"type": "object",
"properties": {
"type": { "type": "string" },
"name": { "type": "string" }
},
"required": ["name"]
}
}
}
]
});
let setup_res = jspg_setup(Json(db_json));
assert_eq!(
setup_res.0,
json!({
"type": "drop",
"response": "success"
})
);
}
fn test_inline_schema_happy_path() {
// 1. Valid instance matching the inline schema
let inline_schema = r#"{"type": "object", "properties": {"age": {"type": "number"}}, "required": ["age"]}"#;
let happy_res = jspg_validate(inline_schema, JsonB(json!({"age": 42})));
assert_eq!(
happy_res.0,
json!({
"type": "drop",
"response": "success"
})
);
// 2. Invalid instance failing the inline schema (missing required field)
let unhappy_res = jspg_validate(inline_schema, JsonB(json!({"name": "Neo"})));
assert_eq!(
unhappy_res.0,
json!({
"type": "drop",
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Missing age",
"details": { "path": "age" }
},
{
"code": "STRICT_PROPERTY_VIOLATION",
"message": "Unexpected property 'name'",
"details": { "path": "name" }
}
]
})
);
// 3. Inline schema referencing registered custom type "person"
let inline_with_ref = r#"{"type": "object", "properties": {"who": {"type": "person"}}, "required": ["who"]}"#;
let happy_ref_res = jspg_validate(inline_with_ref, JsonB(json!({"who": {"type": "person", "name": "Morpheus"}})));
assert_eq!(
happy_ref_res.0,
json!({
"type": "drop",
"response": "success"
})
);
let unhappy_ref_res = jspg_validate(inline_with_ref, JsonB(json!({"who": {"type": "person"}})));
assert_eq!(
unhappy_ref_res.0,
json!({
"type": "drop",
"errors": [
{
"code": "REQUIRED_FIELD_MISSING",
"message": "Missing name",
"details": { "path": "who/name" }
}
]
})
);
}
fn test_inline_schema_syntax_errors() {
let malformed_schema = r#"{"type": "object", "properties": {"name": {"type": "#;
let res = jspg_validate(malformed_schema, JsonB(json!({})));
let errors = res.0.get("errors").expect("Expected errors block");
let err = errors.get(0).expect("Expected at least one error");
assert_eq!(err.get("code").unwrap().as_str().unwrap(), "SCHEMA_PARSE_FAILED");
assert!(err.get("message").unwrap().as_str().unwrap().contains("Failed to parse inline schema"));
}
fn test_inline_schema_ref_compilation_errors() {
// Try to use a custom type that is not defined in the compiled database context.
let invalid_ref_schema = r#"{"type": "object", "properties": {"item": {"type": "non_existent_type"}}}"#;
let res = jspg_validate(invalid_ref_schema, JsonB(json!({"item": {}})));
let errors = res.0.get("errors").expect("Expected errors block");
let err = errors.get(0).expect("Expected compilation error");
assert_eq!(err.get("code").unwrap().as_str().unwrap(), "PROXY_TYPE_RESOLUTION_FAILED");
assert!(err.get("message").unwrap().as_str().unwrap().contains("non_existent_type"));
}
pub fn run_all() {
setup_simple_db();
test_inline_schema_happy_path();
test_inline_schema_syntax_errors();
test_inline_schema_ref_compilation_errors();
let _ = jspg_teardown();
}

View File

@ -2,12 +2,28 @@ use crate::*;
pub mod formatter;
pub mod runner;
pub mod types;
pub mod inline_validator;
pub mod swap_concurrency;
pub mod inheritance_matching;
use serde_json::json;
lazy_static::lazy_static! {
pub static ref TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
// Database module tests moved to src/database/executors/mock.rs
#[test]
fn test_jspg_custom_audit_suite() {
let _guard = TEST_MUTEX.lock().unwrap();
inline_validator::run_all();
inheritance_matching::run_all();
swap_concurrency::run_all();
}
#[test]
fn test_library_api() {
let _guard = TEST_MUTEX.lock().unwrap();
// 1. Initially, schemas are not cached.
// Expected uninitialized drop format: errors + null response
@ -73,7 +89,7 @@ fn test_library_api() {
]
});
let cache_drop = jspg_setup(JsonB(db_json));
let cache_drop = jspg_setup(Json(db_json));
assert_eq!(
cache_drop.0,
json!({
@ -226,7 +242,10 @@ fn test_library_api() {
);
// 4. Validate Happy Path
let happy_drop = jspg_validate("source_schema", JsonB(json!({"type": "source_schema", "name": "Neo"})));
let happy_drop = jspg_validate(
"source_schema",
JsonB(json!({"type": "source_schema", "name": "Neo"})),
);
assert_eq!(
happy_drop.0,
json!({
@ -236,7 +255,10 @@ fn test_library_api() {
);
// 5. Validate Unhappy Path
let unhappy_drop = jspg_validate("source_schema", JsonB(json!({"type": "source_schema", "wrong": "data"})));
let unhappy_drop = jspg_validate(
"source_schema",
JsonB(json!({"type": "source_schema", "wrong": "data"})),
);
assert_eq!(
unhappy_drop.0,
json!({

View File

@ -42,7 +42,7 @@ fn get_cached_file(path: &str) -> CompiledSuite {
let mut compiled_suites = Vec::new();
for suite in suites {
let (db, drop) = crate::database::Database::new(&suite.database);
let (db, drop) = crate::database::Database::new(suite.database.clone());
let compiled_db = if drop.errors.is_empty() {
Ok(Arc::new(db))
} else {

View File

@ -0,0 +1,91 @@
use crate::*;
use serde_json::json;
use std::thread;
use std::sync::Arc;
fn get_concurrency_db() -> serde_json::Value {
json!({
"puncs": [],
"enums": [],
"relations": [],
"types": [
{
"name": "person",
"variations": ["person"],
"hierarchy": ["person", "entity"],
"schemas": {
"person": {
"type": "object",
"properties": {
"type": { "type": "string" },
"name": { "type": "string" }
},
"required": ["name"]
}
}
}
]
})
}
fn test_concurrent_atomic_swap_isolation() {
// 1. Initialize first
let db_json = get_concurrency_db();
let setup_res = jspg_setup(Json(db_json.clone()));
assert_eq!(
setup_res.0,
json!({
"type": "drop",
"response": "success"
})
);
// 2. Spawn 8 parallel reader threads validating schemas
let num_readers = 8;
let mut handles = Vec::new();
for i in 0..num_readers {
handles.push(thread::spawn(move || {
let payload = json!({"type": "person", "name": format!("Neo-{}", i)});
for _ in 0..100 {
let res = jspg_validate("person", JsonB(payload.clone()));
// The validation either succeeds or returns ENGINE_NOT_INITIALIZED (if teardown just swapped it)
// BUT it must NEVER panic, deadlock, or return corrupt memory!
let val = res.0;
let is_success = val.get("response").and_then(|r| r.as_str()) == Some("success");
let is_uninit = val.get("errors")
.and_then(|e| e.as_array())
.and_then(|arr| arr.get(0))
.and_then(|err| err.get("code"))
.and_then(|c| c.as_str()) == Some("ENGINE_NOT_INITIALIZED");
assert!(is_success || is_uninit, "Unexpected validation response: {:?}", val);
thread::yield_now();
}
}));
}
// 3. Spawn a concurrent writer thread constantly calling setup and teardown
let db_json_shared = Arc::new(db_json);
let writer_handle = thread::spawn(move || {
for _ in 0..50 {
let _ = jspg_teardown();
thread::yield_now();
let _ = jspg_setup(Json((*db_json_shared).clone()));
thread::yield_now();
}
});
// 4. Join everyone and verify no thread panicked
for handle in handles {
handle.join().expect("Reader thread panicked or deadlocked!");
}
writer_handle.join().expect("Writer thread panicked or deadlocked!");
// Clean up
let _ = jspg_teardown();
}
pub fn run_all() {
test_concurrent_atomic_swap_isolation();
}

View File

@ -42,62 +42,83 @@ impl Validator {
}
pub fn validate(&self, schema_id: &str, instance: &Value) -> crate::drop::Drop {
let schema_opt = self.db.schemas.get(schema_id);
if let Some(schema) = schema_opt {
let ctx = ValidationContext::new(
&self.db,
&schema,
&schema,
instance,
HashSet::new(),
false,
false,
);
match ctx.validate_scoped() {
Ok(result) => {
if result.is_valid() {
crate::drop::Drop::success()
} else {
let errors: Vec<crate::drop::Error> = result
.errors
.into_iter()
.map(|e| crate::drop::Error {
code: e.code,
message: e.message,
details: crate::drop::ErrorDetails {
path: Some(e.path),
cause: None,
context: None,
schema: None,
},
})
.collect();
crate::drop::Drop::with_errors(errors)
let schema_arc = if schema_id.trim().starts_with('{') {
match serde_json::from_str::<crate::database::schema::Schema>(schema_id) {
Ok(schema) => {
let mut errors = Vec::new();
schema.compile(&self.db, "inline", "inline".to_string(), &mut errors);
if !errors.is_empty() {
return crate::drop::Drop::with_errors(errors);
}
Arc::new(schema)
}
Err(e) => {
return crate::drop::Drop::with_errors(vec![crate::drop::Error {
code: "SCHEMA_PARSE_FAILED".to_string(),
message: format!("Failed to parse inline schema: {}", e),
details: crate::drop::ErrorDetails::default(),
}]);
}
Err(e) => crate::drop::Drop::with_errors(vec![crate::drop::Error {
code: e.code,
message: e.message,
details: crate::drop::ErrorDetails {
path: Some(e.path),
cause: None,
context: None,
schema: None,
},
}]),
}
} else {
crate::drop::Drop::with_errors(vec![crate::drop::Error {
code: "SCHEMA_NOT_FOUND".to_string(),
message: format!("Schema {} not found", schema_id),
match self.db.schemas.get(schema_id) {
Some(schema) => Arc::clone(schema),
None => {
return crate::drop::Drop::with_errors(vec![crate::drop::Error {
code: "SCHEMA_NOT_FOUND".to_string(),
message: format!("Schema {} not found", schema_id),
details: crate::drop::ErrorDetails {
path: Some("/".to_string()),
cause: None,
context: None,
schema: None,
},
}]);
}
}
};
let ctx = ValidationContext::new(
&self.db,
&schema_arc,
&schema_arc,
instance,
HashSet::new(),
false,
false,
);
match ctx.validate_scoped() {
Ok(result) => {
if result.is_valid() {
crate::drop::Drop::success()
} else {
let errors: Vec<crate::drop::Error> = result
.errors
.into_iter()
.map(|e| crate::drop::Error {
code: e.code,
message: e.message,
details: crate::drop::ErrorDetails {
path: Some(e.path),
cause: None,
context: None,
schema: None,
},
})
.collect();
crate::drop::Drop::with_errors(errors)
}
}
Err(e) => crate::drop::Drop::with_errors(vec![crate::drop::Error {
code: e.code,
message: e.message,
details: crate::drop::ErrorDetails {
path: Some("/".to_string()),
path: Some(e.path),
cause: None,
context: None,
schema: None,
},
}])
}]),
}
}
}

View File

@ -1 +1 @@
1.0.139
1.0.151