Compare commits

..

4 Commits

10 changed files with 185 additions and 149 deletions

View File

@ -1260,6 +1260,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"first_name\": \"IncompleteFirst\",",
" \"last_name\": \"IncompleteLast\",",
@ -1358,6 +1359,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"update\",",
" \"complete\": {",
" \"id\": \"{{uuid:mocks.0.id}}\",",
" \"type\": \"person\",",
@ -1461,6 +1463,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"update\",",
" \"complete\": {",
" \"id\": \"{{uuid:mocks.0.id}}\",",
" \"type\": \"person\",",
@ -1526,6 +1529,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"replace\",",
" \"complete\": {",
" \"id\": \"{{uuid:mocks.0.id}}\",",
" \"type\": \"person\",",
@ -1619,6 +1623,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"update\",",
" \"complete\": {",
" \"id\": \"{{uuid:mocks.0.id}}\",",
" \"type\": \"person\",",
@ -1749,6 +1754,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"first_name\": \"John\",",
" \"last_name\": \"Doe\",",
@ -1930,6 +1936,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"total\": 100.0,",
" \"id\": \"{{uuid:generated_3}}\",",
@ -1949,6 +1956,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"first_name\": \"Bob\",",
" \"last_name\": \"Smith\",",
@ -2114,6 +2122,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"total\": 99.0,",
" \"id\": \"abc\",",
@ -2131,6 +2140,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"product\": \"Widget\",",
" \"price\": 99.0,",
@ -2619,6 +2629,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"first_name\": \"Relation\",",
" \"last_name\": \"Test\",",
@ -2638,6 +2649,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"is_primary\": true,",
" \"source_id\": \"{{uuid:generated_0}}\",",
@ -2663,6 +2675,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"number\": \"555-0001\",",
" \"id\": \"{{uuid:generated_1}}\",",
@ -2680,6 +2693,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"is_primary\": false,",
" \"source_id\": \"{{uuid:generated_0}}\",",
@ -2705,6 +2719,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"address\": \"test@example.com\",",
" \"id\": \"{{uuid:generated_5}}\",",
@ -2722,6 +2737,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"is_primary\": false,",
" \"source_id\": \"{{uuid:generated_0}}\",",
@ -2747,6 +2763,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"address\": \"test2@example.com\",",
" \"id\": \"{{uuid:generated_9}}\",",
@ -2830,6 +2847,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"delete\",",
" \"complete\": {",
" \"id\": \"abc-archived\",",
" \"type\": \"person\",",
@ -2943,6 +2961,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"flags\": [",
" \"urgent\",",
@ -3058,6 +3077,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"product\": \"Widget\",",
" \"price\": 99.0,",
@ -3167,6 +3187,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"product\": \"Widget\",",
" \"price\": 99.0,",
@ -3404,6 +3425,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"kind\": \"checking\",",
" \"routing_number\": \"123456789\",",
@ -3698,6 +3720,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"organization_id\": \"parent-org-id\",",
" \"id\": \"{{uuid:generated_3}}\",",
@ -3717,6 +3740,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"first_name\": \"Const\",",
" \"last_name\": \"Person\",",
@ -3738,6 +3762,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"order_id\": \"{{uuid:generated_3}}\",",
" \"id\": \"{{uuid:generated_4}}\",",
@ -3757,6 +3782,7 @@
],
[
"(SELECT pg_notify('entity', '{",
" \"kind\": \"create\",",
" \"complete\": {",
" \"organization_id\": \"explicit-org-id\",",
" \"order_id\": \"{{uuid:generated_3}}\",",

View File

@ -85,7 +85,6 @@ impl DatabaseExecutor for MockExecutor {
Ok("2026-03-10T00:00:00Z".to_string())
}
#[cfg(test)]
fn get_queries(&self) -> Vec<String> {
MOCK_STATE.with(|state| state.borrow().captured_queries.clone())

View File

@ -20,7 +20,6 @@ pub trait DatabaseExecutor: Send + Sync {
/// Returns the current transaction timestamp
fn timestamp(&self) -> Result<String, String>;
#[cfg(test)]
fn get_queries(&self) -> Vec<String>;

View File

@ -150,5 +150,4 @@ impl DatabaseExecutor for SpiExecutor {
})
})
}
}

View File

@ -138,7 +138,9 @@ impl Merger {
is_child: bool,
) -> Result<Value, String> {
match data {
Value::Array(items) => self.merge_array(schema, items, notifications, parent_org_id, is_child),
Value::Array(items) => {
self.merge_array(schema, items, notifications, parent_org_id, is_child)
}
Value::Object(map) => {
if let Some(options) = schema.obj.compiled_options.get() {
if let Some(disc) = schema.obj.compiled_discriminator.get() {
@ -210,7 +212,13 @@ impl Merger {
let mut resolved_items = Vec::new();
for item in items {
let resolved = self.merge_internal(item_schema.clone(), item, notifications, parent_org_id.clone(), is_child)?;
let resolved = self.merge_internal(
item_schema.clone(),
item,
notifications,
parent_org_id.clone(),
is_child,
)?;
resolved_items.push(resolved);
}
Ok(Value::Array(resolved_items))
@ -340,7 +348,10 @@ impl Merger {
if let Some(relation) = self.db.relations.get(&edge.constraint) {
let parent_is_source = edge.forward;
let org_id_to_pass = entity_fields.get("organization_id").and_then(|v| v.as_str()).map(|s| s.to_string());
let org_id_to_pass = entity_fields
.get("organization_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
if parent_is_source {
let mut merged_relative = match self.merge_internal(
rel_schema.clone(),
@ -443,7 +454,10 @@ impl Merger {
}
}
let org_id_to_pass = entity_fields.get("organization_id").and_then(|v| v.as_str()).map(|s| s.to_string());
let org_id_to_pass = entity_fields
.get("organization_id")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let mut relative_responses = Vec::new();
for relative_item_val in relative_arr {
if let Value::Object(mut relative_item) = relative_item_val {
@ -946,9 +960,8 @@ impl Merger {
Value::Object(old_vals)
};
let entity_type_name = type_name.as_str().unwrap_or(&type_obj.name);
let mut notification = serde_json::Map::new();
notification.insert("kind".to_string(), Value::String(change_kind.to_string()));
notification.insert("complete".to_string(), Value::Object(complete));
notification.insert("new".to_string(), new_val_obj.clone());
@ -963,15 +976,14 @@ impl Merger {
let mut notify_sql = None;
if type_obj.historical && change_kind != "replace" {
let change_sql = format!(
"INSERT INTO agreego.change (\"old\", \"new\", entity_id, id, kind, modified_at, modified_by, entity_type) VALUES ({}, {}, {}, {}, {}, {}, {}, {})",
"INSERT INTO agreego.change (\"old\", \"new\", \"entity_id\", \"id\", \"kind\", \"modified_at\", \"modified_by\") VALUES ({}, {}, {}, {}, {}, {}, {})",
Self::quote_literal(&old_val_obj),
Self::quote_literal(&new_val_obj),
Self::quote_literal(id_str),
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(timestamp.to_string())),
Self::quote_literal(&Value::String(user_id.to_string())),
Self::quote_literal(&Value::String(entity_type_name.to_string()))
Self::quote_literal(&Value::String(user_id.to_string()))
);
self.db.execute(&change_sql, None)?;

View File

@ -96,8 +96,10 @@ impl Case {
let queries = db.executor.get_queries();
if std::env::var("UPDATE_EXPECT").is_ok() {
crate::tests::runner::update_sql_fixture(path, suite_idx, case_idx, &queries);
}
Ok(())
} else {
expect.assert_sql(&queries)
}
} else {
Ok(())
}
@ -128,8 +130,10 @@ impl Case {
let queries = db.executor.get_queries();
if std::env::var("UPDATE_EXPECT").is_ok() {
crate::tests::runner::update_sql_fixture(path, suite_idx, case_idx, &queries);
}
Ok(())
} else {
expect.assert_sql(&queries)
}
} else {
Ok(())
}

View File

@ -1,4 +1,3 @@
pub mod pattern;
pub mod sql;
pub mod drop;
pub mod schema;

View File

@ -1,132 +0,0 @@
use super::Expect;
use regex::Regex;
use std::collections::HashMap;
impl Expect {
/// Advanced SQL execution assertion algorithm ported from `assert.go`.
/// This compares two arrays of strings, one containing {{uuid:name}} or {{timestamp}} placeholders,
/// and the other containing actual executed database queries. It ensures that placeholder UUIDs
/// are consistently mapped to the same actual UUIDs across all lines, and strictly validates line-by-line sequences.
pub fn assert_pattern(&self, actual: &[String]) -> Result<(), String> {
let patterns = match &self.sql {
Some(s) => s,
None => return Ok(()),
};
if patterns.len() != actual.len() {
return Err(format!(
"Length mismatch: expected {} SQL executions, got {}.\nActual Execution Log:\n{}",
patterns.len(),
actual.len(),
actual.join("\n")
));
}
let ws_re = Regex::new(r"\s+").unwrap();
let types = HashMap::from([
(
"uuid",
r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
),
(
"timestamp",
r"\d{4}-\d{2}-\d{2}(?:[ T])\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+\d{2}(?::\d{2})?)?",
),
("integer", r"-?\d+"),
("float", r"-?\d+\.\d+"),
("text", r"(?:''|[^'])*"),
("json", r"(?:''|[^'])*"),
]);
let mut seen: HashMap<String, String> = HashMap::new();
let system_uuid = "00000000-0000-0000-0000-000000000000";
// Placeholder regex: {{type:name}} or {{type}}
let ph_rx = Regex::new(r"\{\{([a-z]+)(?:[:]([^}]+))?\}\}").unwrap();
let clean_str = |s: &str| -> String {
let mut s = ws_re.replace_all(s, " ").into_owned();
for token in ["(", ")", ",", "{", "}", "\"", "=", "'"] {
s = s.replace(&format!(" {}", token), token);
s = s.replace(&format!("{} ", token), token);
}
s.trim().to_string()
};
for (i, pattern_expect) in patterns.iter().enumerate() {
let aline_raw = &actual[i];
let aline = clean_str(aline_raw);
let pattern_str_raw = match pattern_expect {
super::SqlExpectation::Single(s) => s.clone(),
super::SqlExpectation::Multi(m) => m.join(" "),
};
let pattern_str = clean_str(&pattern_str_raw);
let mut pp = regex::escape(&pattern_str);
pp = pp.replace(r"\{\{", "{{").replace(r"\}\}", "}}");
let mut cap_names = HashMap::new(); // cg_X -> var_name
let mut group_idx = 0;
let mut final_rx_str = String::new();
let mut last_match = 0;
let pp_clone = pp.clone();
for caps in ph_rx.captures_iter(&pp_clone) {
let full_match = caps.get(0).unwrap();
final_rx_str.push_str(&pp[last_match..full_match.start()]);
let type_name = caps.get(1).unwrap().as_str();
let var_name = caps.get(2).map(|m| m.as_str());
if let Some(name) = var_name {
if let Some(val) = seen.get(name) {
final_rx_str.push_str(&regex::escape(val));
} else {
let type_pattern = types.get(type_name).unwrap_or(&".*?");
let cg_name = format!("cg_{}", group_idx);
final_rx_str.push_str(&format!("(?P<{}>{})", cg_name, type_pattern));
cap_names.insert(cg_name, name.to_string());
group_idx += 1;
}
} else {
let type_pattern = types.get(type_name).unwrap_or(&".*?");
final_rx_str.push_str(&format!("(?:{})", type_pattern));
}
last_match = full_match.end();
}
final_rx_str.push_str(&pp[last_match..]);
let final_rx = match Regex::new(&format!("^{}$", final_rx_str)) {
Ok(r) => r,
Err(e) => return Err(format!("Bad constructed regex: {} -> {}", final_rx_str, e)),
};
if let Some(captures) = final_rx.captures(&aline) {
for (cg_name, var_name) in cap_names {
if let Some(m) = captures.name(&cg_name) {
let matched_str = m.as_str();
if matched_str != system_uuid {
seen.insert(var_name, matched_str.to_string());
}
}
}
} else {
return Err(format!(
"Line mismatched at execution sequence {}.\nExpected Pattern: {}\nActual SQL: {}\nRegex used: {}\nVariables Mapped: {:?}",
i + 1,
pattern_str,
aline,
final_rx_str,
seen
));
}
}
Ok(())
}
}

View File

@ -1,8 +1,9 @@
use super::Expect;
use regex::Regex;
use sqlparser::ast::{Expr, Query, SelectItem, Statement, TableFactor};
use sqlparser::dialect::PostgreSqlDialect;
use sqlparser::parser::Parser;
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
impl Expect {
pub fn assert_sql(&self, actual: &[String]) -> Result<(), String> {
@ -11,6 +12,7 @@ impl Expect {
return Err(e);
}
}
self.assert_pattern(actual)?;
Ok(())
}
@ -203,4 +205,132 @@ impl Expect {
}
Ok(())
}
/// Advanced SQL execution assertion algorithm ported from `assert.go`.
/// This compares two arrays of strings, one containing {{uuid:name}} or {{timestamp}} placeholders,
/// and the other containing actual executed database queries. It ensures that placeholder UUIDs
/// are consistently mapped to the same actual UUIDs across all lines, and strictly validates line-by-line sequences.
pub fn assert_pattern(&self, actual: &[String]) -> Result<(), String> {
let patterns = match &self.sql {
Some(s) => s,
None => return Ok(()),
};
if patterns.len() != actual.len() {
return Err(format!(
"Length mismatch: expected {} SQL executions, got {}.\nActual Execution Log:\n{}",
patterns.len(),
actual.len(),
actual.join("\n")
));
}
let ws_re = Regex::new(r"\s+").unwrap();
let types = HashMap::from([
(
"uuid",
r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
),
(
"timestamp",
r"\d{4}-\d{2}-\d{2}(?:[ T])\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+\d{2}(?::\d{2})?)?",
),
("integer", r"-?\d+"),
("float", r"-?\d+\.\d+"),
("text", r"(?:''|[^'])*"),
("json", r"(?:''|[^'])*"),
]);
let mut seen: HashMap<String, String> = HashMap::new();
let system_uuid = "00000000-0000-0000-0000-000000000000";
// Placeholder regex: {{type:name}} or {{type}}
let ph_rx = Regex::new(r"\{\{([a-z]+)(?:[:]([^}]+))?\}\}").unwrap();
let clean_str = |s: &str| -> String {
let mut s = ws_re.replace_all(s, " ").into_owned();
for token in ["(", ")", ",", "{", "}", "\"", "=", "'"] {
s = s.replace(&format!(" {}", token), token);
s = s.replace(&format!("{} ", token), token);
}
s.trim().to_string()
};
for (i, pattern_expect) in patterns.iter().enumerate() {
let aline_raw = &actual[i];
let formatted_actual = crate::tests::formatter::SqlFormatter::format(aline_raw).join(" ");
let aline = clean_str(&formatted_actual);
let pattern_str_raw = match pattern_expect {
super::SqlExpectation::Single(s) => s.clone(),
super::SqlExpectation::Multi(m) => m.join(" "),
};
let pattern_str = clean_str(&pattern_str_raw);
let mut pp = regex::escape(&pattern_str);
pp = pp.replace(r"\{\{", "{{").replace(r"\}\}", "}}");
let mut cap_names = HashMap::new(); // cg_X -> var_name
let mut group_idx = 0;
let mut final_rx_str = String::new();
let mut last_match = 0;
let pp_clone = pp.clone();
for caps in ph_rx.captures_iter(&pp_clone) {
let full_match = caps.get(0).unwrap();
final_rx_str.push_str(&pp[last_match..full_match.start()]);
let type_name = caps.get(1).unwrap().as_str();
let var_name = caps.get(2).map(|m| m.as_str());
if let Some(name) = var_name {
if let Some(val) = seen.get(name) {
final_rx_str.push_str(&regex::escape(val));
} else {
let type_pattern = types.get(type_name).unwrap_or(&".*?");
let cg_name = format!("cg_{}", group_idx);
final_rx_str.push_str(&format!("(?P<{}>{})", cg_name, type_pattern));
cap_names.insert(cg_name, name.to_string());
group_idx += 1;
}
} else {
let type_pattern = types.get(type_name).unwrap_or(&".*?");
final_rx_str.push_str(&format!("(?:{})", type_pattern));
}
last_match = full_match.end();
}
final_rx_str.push_str(&pp[last_match..]);
let final_rx = match Regex::new(&format!("^{}$", final_rx_str)) {
Ok(r) => r,
Err(e) => return Err(format!("Bad constructed regex: {} -> {}", final_rx_str, e)),
};
if let Some(captures) = final_rx.captures(&aline) {
for (cg_name, var_name) in cap_names {
if let Some(m) = captures.name(&cg_name) {
let matched_str = m.as_str();
if matched_str != system_uuid {
seen.insert(var_name, matched_str.to_string());
}
}
}
} else {
return Err(format!(
"Line mismatched at execution sequence {}.\nExpected Pattern: {}\nActual SQL: {}\nRegex used: {}\nVariables Mapped: {:?}",
i + 1,
pattern_str,
aline,
final_rx_str,
seen
));
}
}
Ok(())
}
}

View File

@ -1 +1 @@
1.0.155
1.0.156