Compare commits
7 Commits
backup-mai
...
1.0.153
| Author | SHA1 | Date | |
|---|---|---|---|
| 271828ebe9 | |||
| 8c430d42e3 | |||
| 4cc5245336 | |||
| c71e99527d | |||
| 843891f67e | |||
| 8bb7085f76 | |||
| ea03584bbd |
@ -295,6 +295,7 @@ The Queryer transforms Postgres into a pre-compiled Semantic Query Engine, desig
|
|||||||
* **The Dot Convention**: When a schema requests `family: "target.schema"`, the compiler extracts the base type (e.g. `schema`) and looks up its Physical Table definition.
|
* **The Dot Convention**: When a schema requests `family: "target.schema"`, the compiler extracts the base type (e.g. `schema`) and looks up its Physical Table definition.
|
||||||
* **Multi-Table Branching**: If the Physical Table is a parent to other tables (e.g. `organization` has variations `["organization", "bot", "person"]`), the compiler generates a dynamic `CASE WHEN type = '...' THEN ...` query, expanding into sub-queries for each variation. To ensure safe resolution, the compiler dynamically evaluates correlation boundaries: it attempts standard Relational Edge discovery first. If no explicit relational edge exists (indicating pure Table Inheritance rather than a standard foreign-key graph relationship), it safely invokes a **Table Parity Fallback**. This generates an explicit ID correlation constraint (`AND inner.id = outer.id`), perfectly binding the structural variations back to the parent row to eliminate Cartesian products.
|
* **Multi-Table Branching**: If the Physical Table is a parent to other tables (e.g. `organization` has variations `["organization", "bot", "person"]`), the compiler generates a dynamic `CASE WHEN type = '...' THEN ...` query, expanding into sub-queries for each variation. To ensure safe resolution, the compiler dynamically evaluates correlation boundaries: it attempts standard Relational Edge discovery first. If no explicit relational edge exists (indicating pure Table Inheritance rather than a standard foreign-key graph relationship), it safely invokes a **Table Parity Fallback**. This generates an explicit ID correlation constraint (`AND inner.id = outer.id`), perfectly binding the structural variations back to the parent row to eliminate Cartesian products.
|
||||||
* **Single-Table Bypass**: If the Physical Table is a leaf node with only one variation (e.g. `person` has variations `["person"]`), the compiler cleanly bypasses `CASE` generation and compiles a simple `SELECT` across the base table, as all schema extensions (e.g. `light.person`, `full.person`) are guaranteed to reside in the exact same physical row.
|
* **Single-Table Bypass**: If the Physical Table is a leaf node with only one variation (e.g. `person` has variations `["person"]`), the compiler cleanly bypasses `CASE` generation and compiles a simple `SELECT` across the base table, as all schema extensions (e.g. `light.person`, `full.person`) are guaranteed to reside in the exact same physical row.
|
||||||
|
* **Polymorphic Relation Type Filtering**: When a relationship maps to a polymorphic target with variations, the Queryer compiles an `IN` clause containing all allowed table variations (e.g., `counterparty_type IN ('bot', 'organization', 'person')`) rather than matching the base type literal, ensuring all polymorphic types are loaded correctly.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@ -37,6 +37,14 @@
|
|||||||
},
|
},
|
||||||
"filter": {
|
"filter": {
|
||||||
"type": "$kind.filter"
|
"type": "$kind.filter"
|
||||||
|
},
|
||||||
|
"conditions": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"new": { "type": "$kind.filter" },
|
||||||
|
"old": { "type": "$kind.filter" },
|
||||||
|
"complete": { "type": "$kind.filter" }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -149,7 +157,48 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Valid nested filter payload",
|
||||||
|
"data": {
|
||||||
|
"kind": "person",
|
||||||
|
"conditions": {
|
||||||
|
"new": {
|
||||||
|
"age": 30
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"schema_id": "search",
|
||||||
|
"action": "validate",
|
||||||
|
"expect": {
|
||||||
|
"success": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "Invalid nested filter payload (fails constraint)",
|
||||||
|
"data": {
|
||||||
|
"kind": "person",
|
||||||
|
"conditions": {
|
||||||
|
"new": {
|
||||||
|
"age": "thirty"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"schema_id": "search",
|
||||||
|
"action": "validate",
|
||||||
|
"expect": {
|
||||||
|
"success": false,
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": "INVALID_TYPE",
|
||||||
|
"details": {
|
||||||
|
"path": "conditions/new/age"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@ -1,8 +1,7 @@
|
|||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
pub fn compose(val: &mut Value, errors: &mut Vec<crate::drop::Error>) -> Result<(), String> {
|
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 traits = HashMap::new();
|
||||||
let mut schemas = HashMap::new();
|
let mut schemas = HashMap::new();
|
||||||
|
|
||||||
@ -74,7 +73,9 @@ fn resolve_in_place(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let include_opt = current.as_object_mut().and_then(|obj| obj.remove("include"));
|
let include_opt = current
|
||||||
|
.as_object_mut()
|
||||||
|
.and_then(|obj| obj.remove("include"));
|
||||||
if let Some(include_val) = include_opt {
|
if let Some(include_val) = include_opt {
|
||||||
if let Some(include_arr) = include_val.as_array() {
|
if let Some(include_arr) = include_val.as_array() {
|
||||||
let mut merged_props = serde_json::Map::new();
|
let mut merged_props = serde_json::Map::new();
|
||||||
@ -145,7 +146,10 @@ fn resolve_in_place(
|
|||||||
visited.remove(inc_name);
|
visited.remove(inc_name);
|
||||||
|
|
||||||
// Merge properties (host overrides trait)
|
// Merge properties (host overrides trait)
|
||||||
if let Some(target_props) = resolved_target.get("properties").and_then(|v| v.as_object()) {
|
if let Some(target_props) = resolved_target
|
||||||
|
.get("properties")
|
||||||
|
.and_then(|v| v.as_object())
|
||||||
|
{
|
||||||
for (k, v) in target_props {
|
for (k, v) in target_props {
|
||||||
if !merged_props.contains_key(k) {
|
if !merged_props.contains_key(k) {
|
||||||
merged_props.insert(k.clone(), v.clone());
|
merged_props.insert(k.clone(), v.clone());
|
||||||
@ -154,7 +158,10 @@ fn resolve_in_place(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge patternProperties (host overrides trait)
|
// Merge patternProperties (host overrides trait)
|
||||||
if let Some(target_pat_props) = resolved_target.get("patternProperties").and_then(|v| v.as_object()) {
|
if let Some(target_pat_props) = resolved_target
|
||||||
|
.get("patternProperties")
|
||||||
|
.and_then(|v| v.as_object())
|
||||||
|
{
|
||||||
for (k, v) in target_pat_props {
|
for (k, v) in target_pat_props {
|
||||||
if !merged_pattern_props.contains_key(k) {
|
if !merged_pattern_props.contains_key(k) {
|
||||||
merged_pattern_props.insert(k.clone(), v.clone());
|
merged_pattern_props.insert(k.clone(), v.clone());
|
||||||
@ -181,11 +188,19 @@ fn resolve_in_place(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Merge dependencies
|
// Merge dependencies
|
||||||
if let Some(target_deps) = resolved_target.get("dependencies").and_then(|v| v.as_object()) {
|
if let Some(target_deps) = resolved_target
|
||||||
|
.get("dependencies")
|
||||||
|
.and_then(|v| v.as_object())
|
||||||
|
{
|
||||||
for (dep_prop, dep_val) in target_deps {
|
for (dep_prop, dep_val) in target_deps {
|
||||||
if let Some(existing_val) = merged_dependencies.get_mut(dep_prop) {
|
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()) {
|
if let (Some(arr_existing), Some(arr_target)) =
|
||||||
let mut set: HashSet<String> = arr_existing.iter().filter_map(|x| x.as_str().map(String::from)).collect();
|
(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 {
|
for x in arr_target {
|
||||||
if let Some(s) = x.as_str() {
|
if let Some(s) = x.as_str() {
|
||||||
if set.insert(s.to_string()) {
|
if set.insert(s.to_string()) {
|
||||||
@ -203,7 +218,13 @@ fn resolve_in_place(
|
|||||||
// Inherit other non-merged schemas/scalars if not defined in host (type, items, cases, family, format, etc.)
|
// 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() {
|
if let Some(obj) = current.as_object_mut() {
|
||||||
for (k, v) in resolved_target.as_object().unwrap() {
|
for (k, v) in resolved_target.as_object().unwrap() {
|
||||||
if k != "properties" && k != "patternProperties" && k != "required" && k != "display" && k != "dependencies" && k != "include" {
|
if k != "properties"
|
||||||
|
&& k != "patternProperties"
|
||||||
|
&& k != "required"
|
||||||
|
&& k != "display"
|
||||||
|
&& k != "dependencies"
|
||||||
|
&& k != "include"
|
||||||
|
{
|
||||||
if !obj.contains_key(k) {
|
if !obj.contains_key(k) {
|
||||||
obj.insert(k.clone(), v.clone());
|
obj.insert(k.clone(), v.clone());
|
||||||
}
|
}
|
||||||
@ -229,7 +250,10 @@ fn resolve_in_place(
|
|||||||
obj.insert("properties".to_string(), Value::Object(merged_props));
|
obj.insert("properties".to_string(), Value::Object(merged_props));
|
||||||
}
|
}
|
||||||
if !merged_pattern_props.is_empty() {
|
if !merged_pattern_props.is_empty() {
|
||||||
obj.insert("patternProperties".to_string(), Value::Object(merged_pattern_props));
|
obj.insert(
|
||||||
|
"patternProperties".to_string(),
|
||||||
|
Value::Object(merged_pattern_props),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if !merged_required.is_empty() {
|
if !merged_required.is_empty() {
|
||||||
let mut req_vec: Vec<Value> = merged_required.into_iter().map(Value::String).collect();
|
let mut req_vec: Vec<Value> = merged_required.into_iter().map(Value::String).collect();
|
||||||
@ -242,7 +266,10 @@ fn resolve_in_place(
|
|||||||
obj.insert("display".to_string(), Value::Array(disp_vec));
|
obj.insert("display".to_string(), Value::Array(disp_vec));
|
||||||
}
|
}
|
||||||
if !merged_dependencies.is_empty() {
|
if !merged_dependencies.is_empty() {
|
||||||
obj.insert("dependencies".to_string(), Value::Object(merged_dependencies));
|
obj.insert(
|
||||||
|
"dependencies".to_string(),
|
||||||
|
Value::Object(merged_dependencies),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -252,47 +279,138 @@ fn resolve_in_place(
|
|||||||
if let Some(obj) = current.as_object_mut() {
|
if let Some(obj) = current.as_object_mut() {
|
||||||
if let Some(props) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
|
if let Some(props) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
|
||||||
for (k, v) in props {
|
for (k, v) in props {
|
||||||
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/{}", path, k), visited);
|
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()) {
|
if let Some(pat_props) = obj
|
||||||
|
.get_mut("patternProperties")
|
||||||
|
.and_then(|v| v.as_object_mut())
|
||||||
|
{
|
||||||
for (k, v) in pat_props {
|
for (k, v) in pat_props {
|
||||||
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/{}", path, k), visited);
|
resolve_in_place(
|
||||||
|
v,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/{}", path, k),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(items) = obj.get_mut("items") {
|
if let Some(items) = obj.get_mut("items") {
|
||||||
resolve_in_place(items, traits, schemas, errors, schema_id, &format!("{}/items", path), visited);
|
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()) {
|
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() {
|
for (i, v) in prefix_items.iter_mut().enumerate() {
|
||||||
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/prefixItems/{}", path, i), visited);
|
resolve_in_place(
|
||||||
|
v,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/prefixItems/{}", path, i),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(additional_props) = obj.get_mut("additionalProperties") {
|
if let Some(additional_props) = obj.get_mut("additionalProperties") {
|
||||||
resolve_in_place(additional_props, traits, schemas, errors, schema_id, &format!("{}/additionalProperties", path), visited);
|
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()) {
|
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() {
|
for (i, v) in one_of.iter_mut().enumerate() {
|
||||||
resolve_in_place(v, traits, schemas, errors, schema_id, &format!("{}/oneOf/{}", path, i), visited);
|
resolve_in_place(
|
||||||
|
v,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/oneOf/{}", path, i),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(contains) = obj.get_mut("contains") {
|
if let Some(contains) = obj.get_mut("contains") {
|
||||||
resolve_in_place(contains, traits, schemas, errors, schema_id, &format!("{}/contains", path), visited);
|
resolve_in_place(
|
||||||
|
contains,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/contains", path),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(not) = obj.get_mut("not") {
|
if let Some(not) = obj.get_mut("not") {
|
||||||
resolve_in_place(not, traits, schemas, errors, schema_id, &format!("{}/not", path), visited);
|
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()) {
|
if let Some(cases) = obj.get_mut("cases").and_then(|v| v.as_array_mut()) {
|
||||||
for (i, c_val) in cases.iter_mut().enumerate() {
|
for (i, c_val) in cases.iter_mut().enumerate() {
|
||||||
if let Some(c_obj) = c_val.as_object_mut() {
|
if let Some(c_obj) = c_val.as_object_mut() {
|
||||||
if let Some(when) = c_obj.get_mut("when") {
|
if let Some(when) = c_obj.get_mut("when") {
|
||||||
resolve_in_place(when, traits, schemas, errors, schema_id, &format!("{}/cases/{}/when", path, i), visited);
|
resolve_in_place(
|
||||||
|
when,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/cases/{}/when", path, i),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(then) = c_obj.get_mut("then") {
|
if let Some(then) = c_obj.get_mut("then") {
|
||||||
resolve_in_place(then, traits, schemas, errors, schema_id, &format!("{}/cases/{}/then", path, i), visited);
|
resolve_in_place(
|
||||||
|
then,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/cases/{}/then", path, i),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(else_) = c_obj.get_mut("else") {
|
if let Some(else_) = c_obj.get_mut("else") {
|
||||||
resolve_in_place(else_, traits, schemas, errors, schema_id, &format!("{}/cases/{}/else", path, i), visited);
|
resolve_in_place(
|
||||||
|
else_,
|
||||||
|
traits,
|
||||||
|
schemas,
|
||||||
|
errors,
|
||||||
|
schema_id,
|
||||||
|
&format!("{}/cases/{}/else", path, i),
|
||||||
|
visited,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -85,6 +85,14 @@ impl DatabaseExecutor for MockExecutor {
|
|||||||
Ok("2026-03-10T00:00:00Z".to_string())
|
Ok("2026-03-10T00:00:00Z".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn auth_origin(&self) -> Result<Option<Value>, String> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn punc_trigger(&self) -> Result<Option<String>, String> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn get_queries(&self) -> Vec<String> {
|
fn get_queries(&self) -> Vec<String> {
|
||||||
MOCK_STATE.with(|state| state.borrow().captured_queries.clone())
|
MOCK_STATE.with(|state| state.borrow().captured_queries.clone())
|
||||||
|
|||||||
@ -20,6 +20,12 @@ pub trait DatabaseExecutor: Send + Sync {
|
|||||||
/// Returns the current transaction timestamp
|
/// Returns the current transaction timestamp
|
||||||
fn timestamp(&self) -> Result<String, String>;
|
fn timestamp(&self) -> Result<String, String>;
|
||||||
|
|
||||||
|
/// Returns the current auth.origin session context if configured
|
||||||
|
fn auth_origin(&self) -> Result<Option<Value>, String>;
|
||||||
|
|
||||||
|
/// Returns the current punc.name session context if configured
|
||||||
|
fn punc_trigger(&self) -> Result<Option<String>, String>;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn get_queries(&self) -> Vec<String>;
|
fn get_queries(&self) -> Vec<String>;
|
||||||
|
|
||||||
|
|||||||
@ -150,4 +150,46 @@ impl DatabaseExecutor for SpiExecutor {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn auth_origin(&self) -> Result<Option<Value>, String> {
|
||||||
|
self.transact(|| {
|
||||||
|
Spi::connect(|client| {
|
||||||
|
let mut tup_table = client
|
||||||
|
.select(
|
||||||
|
"SELECT NULLIF(current_setting('auth.origin', true), '')::jsonb",
|
||||||
|
None,
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("SPI Select Error: {}", e))?;
|
||||||
|
|
||||||
|
if let Some(row) = tup_table.next() {
|
||||||
|
if let Ok(Some(jsonb)) = row.get::<pgrx::JsonB>(1) {
|
||||||
|
return Ok(Some(jsonb.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn punc_trigger(&self) -> Result<Option<String>, String> {
|
||||||
|
self.transact(|| {
|
||||||
|
Spi::connect(|client| {
|
||||||
|
let mut tup_table = client
|
||||||
|
.select(
|
||||||
|
"SELECT NULLIF(current_setting('punc.name', true), '')",
|
||||||
|
None,
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("SPI Select Error: {}", e))?;
|
||||||
|
|
||||||
|
if let Some(row) = tup_table.next() {
|
||||||
|
if let Ok(val_opt) = row.get::<String>(1) {
|
||||||
|
return Ok(val_opt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -206,6 +206,16 @@ impl Database {
|
|||||||
self.executor.timestamp()
|
self.executor.timestamp()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the current auth.origin session context if configured
|
||||||
|
pub fn auth_origin(&self) -> Result<Option<Value>, String> {
|
||||||
|
self.executor.auth_origin()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the current punc.name session context if configured
|
||||||
|
pub fn punc_trigger(&self) -> Result<Option<String>, String> {
|
||||||
|
self.executor.punc_trigger()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn compile(&mut self, errors: &mut Vec<crate::drop::Error>) {
|
pub fn compile(&mut self, errors: &mut Vec<crate::drop::Error>) {
|
||||||
// Phase 1: Registration
|
// Phase 1: Registration
|
||||||
self.collect_schemas(errors);
|
self.collect_schemas(errors);
|
||||||
|
|||||||
@ -946,7 +946,25 @@ impl Merger {
|
|||||||
Value::Object(old_vals)
|
Value::Object(old_vals)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let origin = match self.db.auth_origin() {
|
||||||
|
Ok(Some(orig)) => orig,
|
||||||
|
_ => serde_json::json!({
|
||||||
|
"kind": "user",
|
||||||
|
"user_id": user_id
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
let trigger = match self.db.punc_trigger() {
|
||||||
|
Ok(Some(trig)) => trig,
|
||||||
|
_ => "merge_entity".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let entity_type_name = type_name.as_str().unwrap_or(&type_obj.name);
|
||||||
|
|
||||||
let mut notification = serde_json::Map::new();
|
let mut notification = serde_json::Map::new();
|
||||||
|
notification.insert("type".to_string(), Value::String(entity_type_name.to_string()));
|
||||||
|
notification.insert("trigger".to_string(), Value::String(trigger));
|
||||||
|
notification.insert("origin".to_string(), origin.clone());
|
||||||
notification.insert("complete".to_string(), Value::Object(complete));
|
notification.insert("complete".to_string(), Value::Object(complete));
|
||||||
notification.insert("new".to_string(), new_val_obj.clone());
|
notification.insert("new".to_string(), new_val_obj.clone());
|
||||||
|
|
||||||
@ -961,14 +979,16 @@ impl Merger {
|
|||||||
let mut notify_sql = None;
|
let mut notify_sql = None;
|
||||||
if type_obj.historical && change_kind != "replace" {
|
if type_obj.historical && change_kind != "replace" {
|
||||||
let change_sql = format!(
|
let change_sql = format!(
|
||||||
"INSERT INTO agreego.change (\"old\", \"new\", entity_id, id, kind, modified_at, modified_by) VALUES ({}, {}, {}, {}, {}, {}, {})",
|
"INSERT INTO agreego.change (\"old\", \"new\", entity_id, id, kind, modified_at, modified_by, origin, entity_type) VALUES ({}, {}, {}, {}, {}, {}, {}, {}, {})",
|
||||||
Self::quote_literal(&old_val_obj),
|
Self::quote_literal(&old_val_obj),
|
||||||
Self::quote_literal(&new_val_obj),
|
Self::quote_literal(&new_val_obj),
|
||||||
Self::quote_literal(id_str),
|
Self::quote_literal(id_str),
|
||||||
Self::quote_literal(&Value::String(uuid::Uuid::new_v4().to_string())),
|
Self::quote_literal(&Value::String(uuid::Uuid::new_v4().to_string())),
|
||||||
Self::quote_literal(&Value::String(change_kind.to_string())),
|
Self::quote_literal(&Value::String(change_kind.to_string())),
|
||||||
Self::quote_literal(&Value::String(timestamp.to_string())),
|
Self::quote_literal(&Value::String(timestamp.to_string())),
|
||||||
Self::quote_literal(&Value::String(user_id.to_string()))
|
Self::quote_literal(&Value::String(user_id.to_string())),
|
||||||
|
Self::quote_literal(&origin),
|
||||||
|
Self::quote_literal(&Value::String(entity_type_name.to_string()))
|
||||||
);
|
);
|
||||||
|
|
||||||
self.db.execute(&change_sql, None)?;
|
self.db.execute(&change_sql, None)?;
|
||||||
|
|||||||
@ -621,19 +621,17 @@ impl<'a> Compiler<'a> {
|
|||||||
.get(table_to_alias)
|
.get(table_to_alias)
|
||||||
.or_else(|| type_aliases.get(&node.parent_alias))
|
.or_else(|| type_aliases.get(&node.parent_alias))
|
||||||
{
|
{
|
||||||
// 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 {
|
if type_def.variations.len() > 1 {
|
||||||
let quoted: Vec<String> = type_def.variations.iter()
|
let quoted: Vec<String> = type_def
|
||||||
|
.variations
|
||||||
|
.iter()
|
||||||
.map(|v| format!("'{}'", v))
|
.map(|v| format!("'{}'", v))
|
||||||
.collect();
|
.collect();
|
||||||
where_clauses.push(format!(
|
where_clauses.push(format!(
|
||||||
"{}.{} IN ({})", alias, col, quoted.join(", ")
|
"{}.{} IN ({})",
|
||||||
|
alias,
|
||||||
|
col,
|
||||||
|
quoted.join(", ")
|
||||||
));
|
));
|
||||||
} else {
|
} else {
|
||||||
where_clauses.push(format!("{}.{} = '{}'", alias, col, type_name));
|
where_clauses.push(format!("{}.{} = '{}'", alias, col, type_name));
|
||||||
|
|||||||
@ -50,10 +50,6 @@ impl Queryer {
|
|||||||
Err(drop) => return drop,
|
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
|
// 3. Execute via Database Executor
|
||||||
self.execute_sql(schema_id, &sql, args)
|
self.execute_sql(schema_id, &sql, args)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1277,6 +1277,18 @@ fn test_dynamic_type_0_4() {
|
|||||||
crate::tests::runner::run_test_case(&path, 0, 4).unwrap();
|
crate::tests::runner::run_test_case(&path, 0, 4).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_dynamic_type_0_5() {
|
||||||
|
let path = format!("{}/fixtures/dynamicType.json", env!("CARGO_MANIFEST_DIR"));
|
||||||
|
crate::tests::runner::run_test_case(&path, 0, 5).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_dynamic_type_0_6() {
|
||||||
|
let path = format!("{}/fixtures/dynamicType.json", env!("CARGO_MANIFEST_DIR"));
|
||||||
|
crate::tests::runner::run_test_case(&path, 0, 6).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_property_names_0_0() {
|
fn test_property_names_0_0() {
|
||||||
let path = format!("{}/fixtures/propertyNames.json", env!("CARGO_MANIFEST_DIR"));
|
let path = format!("{}/fixtures/propertyNames.json", env!("CARGO_MANIFEST_DIR"));
|
||||||
|
|||||||
@ -1,177 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
@ -1,124 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
@ -2,28 +2,12 @@ use crate::*;
|
|||||||
pub mod formatter;
|
pub mod formatter;
|
||||||
pub mod runner;
|
pub mod runner;
|
||||||
pub mod types;
|
pub mod types;
|
||||||
pub mod inline_validator;
|
|
||||||
pub mod swap_concurrency;
|
|
||||||
pub mod inheritance_matching;
|
|
||||||
use serde_json::json;
|
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
|
// 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]
|
#[test]
|
||||||
fn test_library_api() {
|
fn test_library_api() {
|
||||||
let _guard = TEST_MUTEX.lock().unwrap();
|
|
||||||
// 1. Initially, schemas are not cached.
|
// 1. Initially, schemas are not cached.
|
||||||
|
|
||||||
// Expected uninitialized drop format: errors + null response
|
// Expected uninitialized drop format: errors + null response
|
||||||
|
|||||||
@ -1,91 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
@ -15,7 +15,7 @@ pub struct ValidationContext<'a> {
|
|||||||
pub extensible: bool,
|
pub extensible: bool,
|
||||||
pub reporter: bool,
|
pub reporter: bool,
|
||||||
pub overrides: HashSet<String>,
|
pub overrides: HashSet<String>,
|
||||||
pub parent: Option<&'a serde_json::Value>,
|
pub parents: Vec<&'a serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ValidationContext<'a> {
|
impl<'a> ValidationContext<'a> {
|
||||||
@ -39,7 +39,7 @@ impl<'a> ValidationContext<'a> {
|
|||||||
extensible: effective_extensible,
|
extensible: effective_extensible,
|
||||||
reporter,
|
reporter,
|
||||||
overrides,
|
overrides,
|
||||||
parent: None,
|
parents: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,6 +63,11 @@ impl<'a> ValidationContext<'a> {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
let effective_extensible = schema.extensible.unwrap_or(extensible);
|
let effective_extensible = schema.extensible.unwrap_or(extensible);
|
||||||
|
|
||||||
|
let mut parents = self.parents.clone();
|
||||||
|
if let Some(p) = parent_instance {
|
||||||
|
parents.push(p);
|
||||||
|
}
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
db: self.db,
|
db: self.db,
|
||||||
root: self.root,
|
root: self.root,
|
||||||
@ -73,7 +78,7 @@ impl<'a> ValidationContext<'a> {
|
|||||||
extensible: effective_extensible,
|
extensible: effective_extensible,
|
||||||
reporter,
|
reporter,
|
||||||
overrides,
|
overrides,
|
||||||
parent: parent_instance,
|
parents,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,7 +90,7 @@ impl<'a> ValidationContext<'a> {
|
|||||||
HashSet::new(),
|
HashSet::new(),
|
||||||
self.extensible,
|
self.extensible,
|
||||||
reporter,
|
reporter,
|
||||||
self.parent,
|
None,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -42,83 +42,62 @@ impl Validator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn validate(&self, schema_id: &str, instance: &Value) -> crate::drop::Drop {
|
pub fn validate(&self, schema_id: &str, instance: &Value) -> crate::drop::Drop {
|
||||||
let schema_arc = if schema_id.trim().starts_with('{') {
|
let schema_opt = self.db.schemas.get(schema_id);
|
||||||
match serde_json::from_str::<crate::database::schema::Schema>(schema_id) {
|
|
||||||
Ok(schema) => {
|
if let Some(schema) = schema_opt {
|
||||||
let mut errors = Vec::new();
|
let ctx = ValidationContext::new(
|
||||||
schema.compile(&self.db, "inline", "inline".to_string(), &mut errors);
|
&self.db,
|
||||||
if !errors.is_empty() {
|
&schema,
|
||||||
return crate::drop::Drop::with_errors(errors);
|
&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)
|
||||||
}
|
}
|
||||||
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 {
|
} else {
|
||||||
match self.db.schemas.get(schema_id) {
|
crate::drop::Drop::with_errors(vec![crate::drop::Error {
|
||||||
Some(schema) => Arc::clone(schema),
|
code: "SCHEMA_NOT_FOUND".to_string(),
|
||||||
None => {
|
message: format!("Schema {} not found", schema_id),
|
||||||
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 {
|
details: crate::drop::ErrorDetails {
|
||||||
path: Some(e.path),
|
path: Some("/".to_string()),
|
||||||
cause: None,
|
cause: None,
|
||||||
context: None,
|
context: None,
|
||||||
schema: None,
|
schema: None,
|
||||||
},
|
},
|
||||||
}]),
|
}])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -59,12 +59,13 @@ impl<'a> ValidationContext<'a> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut resolved = false;
|
let mut resolved = false;
|
||||||
if let Some(parent) = self.parent {
|
for parent in self.parents.iter().rev() {
|
||||||
if let Some(obj) = parent.as_object() {
|
if let Some(obj) = parent.as_object() {
|
||||||
if let Some(val) = obj.get(var_name) {
|
if let Some(val) = obj.get(var_name) {
|
||||||
if let Some(str_val) = val.as_str() {
|
if let Some(str_val) = val.as_str() {
|
||||||
target_id = format!("{}{}", str_val, suffix);
|
target_id = format!("{}{}", str_val, suffix);
|
||||||
resolved = true;
|
resolved = true;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -97,7 +98,7 @@ impl<'a> ValidationContext<'a> {
|
|||||||
new_overrides,
|
new_overrides,
|
||||||
self.extensible,
|
self.extensible,
|
||||||
true, // Reporter mode
|
true, // Reporter mode
|
||||||
self.parent,
|
None,
|
||||||
);
|
);
|
||||||
shadow.root = &global_schema;
|
shadow.root = &global_schema;
|
||||||
result.merge(shadow.validate()?);
|
result.merge(shadow.validate()?);
|
||||||
|
|||||||
Reference in New Issue
Block a user