use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use elinvar_engine::logic::{
Error, FormulaKind, Instance, Place, TemporalOp, Trace, Universe, evaluate_trace_at,
};
use serde_json::{Value, json};
use crate::cli::verbs::{Output, error_output};
#[derive(Clone, Debug, Default)]
pub struct AuditOptions {
pub tables: Vec<String>,
pub with_referencing: bool,
pub extra_als: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum DumpVal {
Null,
Bool(bool),
Int(i64),
Str(String),
}
impl DumpVal {
fn display(&self) -> String {
match self {
DumpVal::Null => "NULL".to_string(),
DumpVal::Bool(b) => b.to_string(),
DumpVal::Int(n) => n.to_string(),
DumpVal::Str(s) => format!("'{s}'"),
}
}
}
#[derive(Clone, Debug)]
struct RawInsertStmt {
line: usize,
sql: String,
}
#[derive(Clone, Debug)]
struct RuleViolation {
rule: String,
table: Option<String>,
detail: String,
line: Option<usize>,
}
fn audit_parse_error(msg: String) -> Output {
let text = format!("elinvar audit: {msg}\n");
Output {
status: 3,
text: text.clone(),
json: json!({
"elinvar": 1,
"command": "audit",
"errors": [{
"code": "audit.parse",
"message": msg,
"fix": "pass a SQL dump containing standard INSERT INTO ... VALUES (...) statements",
}],
"story": text,
}),
}
}
fn split_dump_statements(src: &str) -> Vec<RawInsertStmt> {
let mut out = Vec::new();
let mut cur = String::new();
let mut cur_line: Option<usize> = None;
let mut in_str = false;
let mut in_block_comment = false;
for (idx, raw_line) in src.lines().enumerate() {
let line_no = idx + 1;
let trimmed_start = raw_line.trim_start();
if !in_str && !in_block_comment && trimmed_start.starts_with('\\') {
continue;
}
let mut chars = raw_line.chars().peekable();
while let Some(c) = chars.next() {
if in_block_comment {
if c == '*' && chars.peek() == Some(&'/') {
chars.next();
in_block_comment = false;
}
continue;
}
if in_str {
cur.push(c);
if c == '\'' {
if chars.peek() == Some(&'\'') {
cur.push(chars.next().expect("peeked"));
} else {
in_str = false;
}
}
continue;
}
if c == '-' && chars.peek() == Some(&'-') {
break;
}
if c == '/' && chars.peek() == Some(&'*') {
chars.next();
in_block_comment = true;
continue;
}
if c == '\'' {
if cur_line.is_none() {
cur_line = Some(line_no);
}
in_str = true;
cur.push(c);
} else if c == ';' {
let s = cur.trim().to_string();
if !s.is_empty() {
out.push(RawInsertStmt {
line: cur_line.unwrap_or(line_no),
sql: s,
});
}
cur.clear();
cur_line = None;
} else {
if !c.is_whitespace() && cur_line.is_none() {
cur_line = Some(line_no);
}
cur.push(c);
}
}
if !cur.is_empty() {
cur.push(' ');
}
}
let tail = cur.trim().to_string();
if !tail.is_empty() {
out.push(RawInsertStmt {
line: cur_line.unwrap_or(1),
sql: tail,
});
}
out
}
fn split_once_kw_top<'a>(s: &'a str, kw: &str) -> Option<(&'a str, &'a str)> {
let bytes = s.as_bytes();
let klen = kw.len();
let mut i = 0;
let mut in_str = false;
let mut depth = 0usize;
while i < bytes.len() {
let b = bytes[i];
if in_str {
if b == b'\'' {
if bytes.get(i + 1) == Some(&b'\'') {
i += 2;
continue;
}
in_str = false;
}
i += 1;
continue;
}
if b == b'\'' {
in_str = true;
i += 1;
continue;
}
if b == b'(' {
depth += 1;
i += 1;
continue;
}
if b == b')' {
depth = depth.saturating_sub(1);
i += 1;
continue;
}
if depth == 0 && i + klen <= bytes.len() {
let before_ok =
i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
let after_ok = i + klen == bytes.len()
|| !(bytes[i + klen].is_ascii_alphanumeric() || bytes[i + klen] == b'_');
if before_ok && after_ok && s[i..i + klen].eq_ignore_ascii_case(kw) {
return Some((&s[..i], &s[i + klen..]));
}
}
i += 1;
}
None
}
fn split_value_tuples(s: &str) -> Option<Vec<&str>> {
let bytes = s.as_bytes();
let mut i = 0;
let mut out = Vec::new();
while i < bytes.len() {
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= bytes.len() {
break;
}
if bytes[i] != b'(' {
return None;
}
let start = i + 1;
let mut depth = 1usize;
let mut in_str = false;
i += 1;
while i < bytes.len() && depth > 0 {
let b = bytes[i];
if in_str {
if b == b'\'' {
if bytes.get(i + 1) == Some(&b'\'') {
i += 2;
continue;
}
in_str = false;
}
i += 1;
continue;
}
if b == b'\'' {
in_str = true;
} else if b == b'(' {
depth += 1;
} else if b == b')' {
depth -= 1;
if depth == 0 {
out.push(&s[start..i]);
i += 1;
break;
}
}
i += 1;
}
if depth != 0 {
return None;
}
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i < bytes.len() {
if bytes[i] == b',' {
i += 1;
} else {
return None;
}
}
}
Some(out)
}
fn split_csv(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut in_str = false;
let mut depth = 0usize;
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if in_str {
cur.push(c);
if c == '\'' {
if chars.peek() == Some(&'\'') {
cur.push(chars.next().expect("peeked"));
} else {
in_str = false;
}
}
} else if c == '\'' {
in_str = true;
cur.push(c);
} else if c == '(' {
depth += 1;
cur.push(c);
} else if c == ')' {
depth = depth.saturating_sub(1);
cur.push(c);
} else if c == ',' && depth == 0 {
out.push(cur.trim().to_string());
cur.clear();
} else {
cur.push(c);
}
}
if !cur.trim().is_empty() {
out.push(cur.trim().to_string());
}
out
}
fn strip_pg_cast(raw: &str) -> &str {
let bytes = raw.as_bytes();
let mut in_str = false;
let mut depth = 0usize;
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if in_str {
if b == b'\'' {
if bytes.get(i + 1) == Some(&b'\'') {
i += 2;
continue;
}
in_str = false;
}
i += 1;
continue;
}
if b == b'\'' {
in_str = true;
} else if b == b'(' {
depth += 1;
} else if b == b')' {
depth = depth.saturating_sub(1);
} else if depth == 0 && b == b':' && bytes.get(i + 1) == Some(&b':') {
return raw[..i].trim();
}
i += 1;
}
raw.trim()
}
fn parse_dump_val(raw: &str, line: usize) -> Result<DumpVal, String> {
let mut t = strip_pg_cast(raw);
while t.starts_with('(') && t.ends_with(')') && t.len() >= 2 {
let inner = t[1..t.len() - 1].trim();
t = strip_pg_cast(inner);
}
if t.eq_ignore_ascii_case("null") {
Ok(DumpVal::Null)
} else if t.eq_ignore_ascii_case("true") {
Ok(DumpVal::Bool(true))
} else if t.eq_ignore_ascii_case("false") {
Ok(DumpVal::Bool(false))
} else if t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2 {
let inner = &t[1..t.len() - 1];
let mut chars = inner.chars().peekable();
let mut out = String::new();
while let Some(c) = chars.next() {
if c == '\'' {
if chars.peek() == Some(&'\'') {
chars.next();
out.push('\'');
} else {
return Err(format!("line {line}: malformed string literal `{t}`"));
}
} else {
out.push(c);
}
}
Ok(DumpVal::Str(out))
} else if (t.starts_with("x'") || t.starts_with("X'")) && t.ends_with('\'') && t.len() >= 3 {
let hex = &t[2..t.len() - 1];
if hex.len().is_multiple_of(2) && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
Ok(DumpVal::Str(format!("x'{}'", hex.to_ascii_lowercase())))
} else {
Err(format!(
"line {line}: invalid hex BLOB literal `{t}` in SQL dump"
))
}
} else if let Ok(n) = t.parse::<i64>() {
Ok(DumpVal::Int(n))
} else {
Err(format!("line {line}: unsupported value `{t}` in SQL dump"))
}
}
fn clean_sql_ident(raw: &str) -> String {
let t = raw.trim();
let part = t.rsplit('.').next().unwrap_or(t).trim();
part.trim_matches('"')
.trim_matches('`')
.trim_matches('\'')
.to_ascii_lowercase()
}
fn default_to_dump_val(d: &elinvar_als::SqlDefault) -> DumpVal {
match d {
elinvar_als::SqlDefault::Int(n) => DumpVal::Int(*n),
elinvar_als::SqlDefault::Str(s) => DumpVal::Str(s.clone()),
elinvar_als::SqlDefault::Bool(b) => DumpVal::Bool(*b),
elinvar_als::SqlDefault::Null | _ => DumpVal::Null,
}
}
type TableRow = (usize, BTreeMap<String, DumpVal>);
type RowsByTable = BTreeMap<String, Vec<TableRow>>;
const DUMP_BOILERPLATE: &[&str] = &[
"ALTER",
"ANALYZE",
"BEGIN",
"COMMENT",
"COMMIT",
"CREATE",
"DROP",
"END",
"GRANT",
"LOCK",
"PRAGMA",
"RELEASE",
"REVOKE",
"ROLLBACK",
"SAVEPOINT",
"SELECT",
"SET",
"START",
"UNLOCK",
"USE",
"VACUUM",
];
fn dump_warning(code: &'static str, message: String, file: &str, line: usize) -> Error {
let fix = crate::cli::verbs::CLI_CODES
.iter()
.find(|c| c.code == code)
.map_or("", |c| c.fix);
Error::with_fix(code, message, fix).at(Place::new(
file,
u32::try_from(line).unwrap_or(u32::MAX),
1,
))
}
fn parse_dump_rows(
data_file: &str,
data_sql: &str,
imp: &elinvar_als::SqlImport,
) -> Result<(RowsByTable, Vec<Error>), String> {
let mut cols_by_table: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (tname, cols) in &imp.table_columns {
cols_by_table.insert(
tname.to_ascii_lowercase(),
cols.iter()
.map(|c| c.sql_name.to_ascii_lowercase())
.collect(),
);
}
let mut rows_by_table: BTreeMap<String, Vec<TableRow>> = BTreeMap::new();
for t in cols_by_table.keys() {
rows_by_table.insert(t.clone(), Vec::new());
}
let mut warnings = Vec::new();
let mut inserts = 0usize;
let mut dropped: BTreeMap<String, (usize, usize)> = BTreeMap::new();
for stmt in split_dump_statements(data_sql) {
let up = stmt.sql.to_ascii_uppercase();
if !up.starts_with("INSERT") {
let word: String = up
.trim_start()
.chars()
.take_while(char::is_ascii_alphabetic)
.collect();
if !DUMP_BOILERPLATE.contains(&word.as_str()) {
let shown: String = stmt.sql.trim().chars().take(60).collect();
let message = if word == "COPY" {
format!(
"a `COPY` statement was not read, and its rows were not audited; \
dump with `pg_dump --inserts`: `{shown}`"
)
} else {
format!("a statement that is not an INSERT was not read: `{shown}`")
};
warnings.push(dump_warning(
"audit.ignored_statement",
message,
data_file,
stmt.line,
));
}
continue;
}
inserts += 1;
let after_into = split_once_kw_top(&stmt.sql, "INTO")
.map(|(_, r)| r.trim())
.ok_or_else(|| format!("line {}: malformed INSERT statement", stmt.line))?;
let Some((before_vals, vals_part)) = split_once_kw_top(after_into, "VALUES") else {
return Err(format!(
"line {}: INSERT is missing VALUES clause",
stmt.line
));
};
let (tname, explicit_cols) = if let Some((tn, rest)) = before_vals.split_once('(') {
let clist: Vec<String> = rest
.trim()
.trim_end_matches(')')
.split(',')
.map(clean_sql_ident)
.filter(|c| !c.is_empty())
.collect();
(clean_sql_ident(tn), Some(clist))
} else {
(clean_sql_ident(before_vals), None)
};
let Some(schema_cols) = cols_by_table.get(&tname) else {
let rows = split_value_tuples(vals_part).map_or(1, |t| t.len());
let e = dropped.entry(tname).or_insert((0, stmt.line));
e.0 += rows;
continue;
};
let target_cols: &[String] = match explicit_cols.as_deref() {
Some(c) => c,
None => schema_cols.as_slice(),
};
let vals_clean = split_once_kw_top(vals_part, "ON")
.map_or(vals_part.trim(), |(before, _)| before.trim());
let tuples = split_value_tuples(vals_clean)
.ok_or_else(|| format!("line {}: malformed VALUES list in INSERT", stmt.line))?;
for tup in tuples {
let raw_vals = split_csv(tup);
if raw_vals.len() != target_cols.len() {
return Err(format!(
"line {}: INSERT into `{tname}` has {} column(s) but {} value(s)",
stmt.line,
target_cols.len(),
raw_vals.len()
));
}
let mut row = BTreeMap::new();
for (c, rv) in target_cols.iter().zip(raw_vals.iter()) {
row.insert(c.clone(), parse_dump_val(rv, stmt.line)?);
}
for ((dt, dc), def) in &imp.col_defaults {
if dt == &tname && !row.contains_key(dc) {
row.insert(dc.clone(), default_to_dump_val(def));
}
}
rows_by_table
.entry(tname.clone())
.or_default()
.push((stmt.line, row));
}
}
for (table, (rows, line)) in dropped {
warnings.push(dump_warning(
"audit.dropped_rows",
format!(
"{rows} row(s) inserted into `{table}` were not audited: the table is not in \
the schema, or not in its `--tables` slice"
),
data_file,
line,
));
}
if inserts == 0 {
if let Some(first) = warnings.first() {
return Err(format!(
"`{data_file}` has no INSERT statement, so it is not a SQL dump (line {}: {})",
first.place.as_ref().map_or(1, |p| p.line),
first.message
));
}
warnings.push(dump_warning(
"audit.no_rows",
"the dump has no INSERT statement, so no row was audited".to_string(),
data_file,
1,
));
}
Ok((rows_by_table, warnings))
}
fn check_structural_rules(
imp: &elinvar_als::SqlImport,
rows_by_table: &BTreeMap<String, Vec<TableRow>>,
) -> Vec<RuleViolation> {
let mut out = Vec::new();
for (tname, cols) in &imp.table_columns {
let t_low = tname.to_ascii_lowercase();
let Some(rows) = rows_by_table.get(&t_low) else {
continue;
};
let pk_cols: Vec<String> = cols
.iter()
.filter(|c| c.primary_key)
.map(|c| c.sql_name.to_ascii_lowercase())
.collect();
let mut seen_pk: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
let mut seen_unique: BTreeMap<String, BTreeSet<DumpVal>> = BTreeMap::new();
for (line, row) in rows {
for col in cols {
let c_low = col.sql_name.to_ascii_lowercase();
let val = row.get(&c_low).unwrap_or(&DumpVal::Null);
if col.not_null && matches!(val, DumpVal::Null) {
out.push(RuleViolation {
rule: format!("NOT NULL {t_low}.{c_low}"),
table: Some(tname.clone()),
detail: format!("row at line {line} has NULL in NOT NULL column `{c_low}`"),
line: Some(*line),
});
}
if col.unique && !matches!(val, DumpVal::Null) {
let set = seen_unique.entry(c_low.clone()).or_default();
if !set.insert(val.clone()) {
out.push(RuleViolation {
rule: format!("UNIQUE {t_low}.{c_low}"),
table: Some(tname.clone()),
detail: format!(
"duplicate value {} in UNIQUE column `{t_low}.{c_low}` at line {line}",
val.display()
),
line: Some(*line),
});
}
}
if !matches!(val, DumpVal::Null)
&& let Some(allowed) = imp.enum_values.get(&(t_low.clone(), c_low.clone()))
{
let s = match val {
DumpVal::Str(v) => v.clone(),
DumpVal::Int(n) => n.to_string(),
DumpVal::Bool(b) => b.to_string(),
DumpVal::Null => unreachable!(),
};
if !allowed.iter().any(|a| a == &s) {
out.push(RuleViolation {
rule: format!("CHECK enum {t_low}.{c_low}"),
table: Some(tname.clone()),
detail: format!(
"value '{}' at line {line} is outside allowed enum values [{}]",
s,
allowed.join(", ")
),
line: Some(*line),
});
}
}
}
if !pk_cols.is_empty() {
let key: Vec<DumpVal> = pk_cols
.iter()
.map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
.collect();
if !seen_pk.insert(key) {
out.push(RuleViolation {
rule: format!("PRIMARY KEY {t_low}({})", pk_cols.join(", ")),
table: Some(tname.clone()),
detail: format!("duplicate primary key at line {line}"),
line: Some(*line),
});
}
}
}
}
for (tname, ulist) in &imp.table_uniques {
let t_low = tname.to_ascii_lowercase();
let Some(rows) = rows_by_table.get(&t_low) else {
continue;
};
for ucols in ulist {
let key_cols: Vec<String> = ucols.iter().map(|c| c.to_ascii_lowercase()).collect();
let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
for (line, row) in rows {
let key: Vec<DumpVal> = key_cols
.iter()
.map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
.collect();
if key.iter().any(|v| matches!(v, DumpVal::Null)) {
continue;
}
if !seen.insert(key) {
out.push(RuleViolation {
rule: format!("UNIQUE {t_low}({})", ucols.join(", ")),
table: Some(tname.clone()),
detail: format!(
"duplicate key ({}) in UNIQUE constraint on `{t_low}` at line {line}",
ucols.join(", ")
),
line: Some(*line),
});
}
}
}
}
for (tname, idx_name, ucols) in &imp.unique_indexes {
let t_low = tname.to_ascii_lowercase();
let Some(rows) = rows_by_table.get(&t_low) else {
continue;
};
let key_cols: Vec<String> = ucols.iter().map(|c| c.to_ascii_lowercase()).collect();
let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
for (line, row) in rows {
let key: Vec<DumpVal> = key_cols
.iter()
.map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
.collect();
if key.iter().any(|v| matches!(v, DumpVal::Null)) {
continue;
}
if !seen.insert(key) {
out.push(RuleViolation {
rule: format!("UNIQUE INDEX {idx_name}"),
table: Some(tname.clone()),
detail: format!(
"duplicate key ({}) in UNIQUE INDEX `{idx_name}` at line {line}",
ucols.join(", ")
),
line: Some(*line),
});
}
}
}
for idx in &imp.partial_unique_indexes {
let t_low = idx.table.to_ascii_lowercase();
let Some(rows) = rows_by_table.get(&t_low) else {
continue;
};
let null_col = idx.null_col.to_ascii_lowercase();
let key_cols: Vec<String> = idx.cols.iter().map(|c| c.to_ascii_lowercase()).collect();
let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
for (line, row) in rows {
if !matches!(row.get(&null_col), None | Some(DumpVal::Null)) {
continue;
}
let key: Vec<DumpVal> = key_cols
.iter()
.map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
.collect();
if key.iter().any(|v| matches!(v, DumpVal::Null)) {
continue;
}
if !seen.insert(key) {
out.push(RuleViolation {
rule: format!("UNIQUE INDEX {}", idx.name),
table: Some(idx.table.clone()),
detail: format!(
"duplicate open key ({}) with `{null_col}` IS NULL at line {line}",
idx.cols.join(", ")
),
line: Some(*line),
});
}
}
}
let mut target_index: BTreeMap<(String, String), BTreeSet<DumpVal>> = BTreeMap::new();
for fk in imp.fk_targets.values() {
let key = (fk.target_table.clone(), fk.target_col.clone());
target_index.entry(key).or_insert_with(|| {
let mut vals = BTreeSet::new();
if let Some(trows) = rows_by_table.get(&fk.target_table) {
for (_, r) in trows {
if let Some(v) = r.get(&fk.target_col)
&& !matches!(v, DumpVal::Null)
{
vals.insert(v.clone());
}
}
}
vals
});
}
for ((src_t, src_c), fk) in &imp.fk_targets {
let Some(rows) = rows_by_table.get(src_t) else {
continue;
};
let valid_targets = target_index
.get(&(fk.target_table.clone(), fk.target_col.clone()))
.expect("populated above");
for (line, row) in rows {
if let Some(val) = row.get(src_c)
&& !matches!(val, DumpVal::Null)
&& !valid_targets.contains(val)
{
out.push(RuleViolation {
rule: format!(
"FOREIGN KEY {src_t}.{src_c} -> {}.{}",
fk.target_table, fk.target_col
),
table: Some(src_t.clone()),
detail: format!(
"value {} at line {line} does not exist in `{}.{}`",
val.display(),
fk.target_table,
fk.target_col
),
line: Some(*line),
});
}
}
}
out
}
#[allow(clippy::type_complexity)]
fn evaluate_dump_on_model(
model: &elinvar_als::AlsModel,
imp: &elinvar_als::SqlImport,
rows_by_table: &BTreeMap<String, Vec<TableRow>>,
) -> Result<
(
Vec<RuleViolation>,
Vec<(String, bool)>,
Vec<(String, String)>,
),
Vec<elinvar_engine::logic::Error>,
> {
let mut structural_facts_done: BTreeSet<String> = BTreeSet::new();
structural_facts_done.insert("fact SqlOrdFn_monotone".to_string());
for t in &imp.tables {
let tid = imp
.sql_to_alloy_table
.get(t)
.map(String::as_str)
.unwrap_or(t.as_str());
structural_facts_done.insert(format!("fact {tid}_domain"));
structural_facts_done.insert(format!("fact {tid}_retired_disjoint"));
let row_count = rows_by_table
.get(&t.to_ascii_lowercase())
.map_or(0, Vec::len);
if row_count == 0 {
structural_facts_done.insert(format!("fact {tid}_checks"));
}
if let Some(cols) = imp.table_columns.get(t) {
for c in cols {
if c.unique {
structural_facts_done.insert(format!("fact {tid}_unique_{}", c.alloy_name));
}
}
}
if let Some(ulist) = imp.table_uniques.get(t) {
for idx in 0..ulist.len() {
structural_facts_done.insert(format!("fact {tid}_unique_{}", idx + 1));
}
}
}
for (tname, idx_name, _) in &imp.unique_indexes {
let tid = imp
.sql_to_alloy_table
.get(tname)
.map(String::as_str)
.unwrap_or(tname.as_str());
structural_facts_done.insert(format!("fact {tid}_uniq_{idx_name}"));
}
for idx in &imp.partial_unique_indexes {
let tid = imp
.sql_to_alloy_table
.get(&idx.table)
.map(String::as_str)
.unwrap_or(idx.table.as_str());
structural_facts_done.insert(format!("fact {tid}_uniq_{}", idx.name));
structural_facts_done.insert(format!("fact {}", idx.name));
}
let mut active_facts: Vec<(String, elinvar_engine::logic::Formula)> = Vec::new();
for (fname, formula) in model.model.all_facts_named() {
if fname == "fact trace"
|| fname == "fact StartEmpty"
|| fname.ends_with("_no_row_reuse")
|| fname.starts_with("sig ")
|| fname.starts_with("field ")
|| structural_facts_done.contains(&fname)
|| crate::cli::dates::is_synthetic_date_fn_rule(&fname)
{
continue;
}
let inner = match formula.kind() {
FormulaKind::Temporal(TemporalOp::Always, sub) => sub.clone(),
_ => formula,
};
if inner.is_temporal() {
continue;
}
active_facts.push((fname, inner));
}
let mut active_promises: Vec<(String, elinvar_engine::logic::Formula)> = Vec::new();
let mut skipped_promises = Vec::new();
for spec in &model.commands {
if !spec.check {
continue;
}
let cmd = model.command(spec);
let f = cmd.formula();
let inner = match f.kind() {
FormulaKind::Temporal(TemporalOp::Always, sub) => sub.clone(),
_ => f.clone(),
};
if inner.is_temporal() {
skipped_promises.push((
spec.name.clone(),
"requires multiple states (uses temporal step operators)".to_string(),
));
continue;
}
active_promises.push((spec.name.clone(), inner));
}
if active_facts.is_empty() && active_promises.is_empty() {
return Ok((Vec::new(), Vec::new(), skipped_promises));
}
let need_date_fn = active_facts
.iter()
.chain(active_promises.iter())
.any(|(_, f)| f.to_string().contains("SqlDateFn"));
let need_ord_fn = active_facts
.iter()
.chain(active_promises.iter())
.any(|(_, f)| f.to_string().contains("SqlOrdFn"));
let schema_bounds = model
.model
.run(&elinvar_engine::logic::Formula::truth())
.scope(2)
.bounds()?;
let su = schema_bounds.universe();
let relations = model.model.relations();
let mut atom_sig_name: BTreeMap<String, String> = BTreeMap::new();
let mut singleton_rel_names: BTreeSet<String> = BTreeSet::new();
let mut ordered_aliases: BTreeMap<String, String> = BTreeMap::new(); let mut sig_children: BTreeMap<String, Vec<String>> = BTreeMap::new();
let is_parent_container = |rname: &str| {
rname == "SqlBool"
|| rname.ends_with("_enum")
|| rname.ends_with("_val")
|| rname.ends_with("_row")
|| rname.ends_with("_ord")
|| rname.starts_with("time_ord_")
|| rname.starts_with("date_ord_")
};
let mut container_atoms: Vec<(String, BTreeSet<String>)> = Vec::new();
for rel in &relations {
if rel.is_changing() || rel.arity() != 1 {
continue;
}
let rname = rel.name();
if rname == "Int" || rname == "first" || rname.ends_with("/first") {
continue;
}
if is_parent_container(rname)
&& let Some(up) = schema_bounds.upper(rel)
{
let mut set = BTreeSet::new();
for idx in up.indices() {
if let Some(aname) = su.atom(idx as usize) {
atom_sig_name.insert(aname.to_string(), rname.to_string());
set.insert(aname.to_string());
}
}
container_atoms.push((rname.to_string(), set));
}
}
let text_check_sig_names: BTreeSet<&str> = imp
.text_checks
.iter()
.map(|tc| tc.sig_name.as_str())
.collect();
for rel in &relations {
if rel.is_changing() || rel.arity() != 1 {
continue;
}
let rname = rel.name();
if rname == "Int"
|| rname == "first"
|| rname.ends_with("/first")
|| is_parent_container(rname)
|| text_check_sig_names.contains(rname)
{
continue;
}
let Some(up) = schema_bounds.upper(rel) else {
continue;
};
let up_atoms: Vec<String> = up
.indices()
.filter_map(|idx| su.atom(idx as usize).map(str::to_string))
.collect();
let parent_match = container_atoms
.iter()
.find(|(_, cset)| !up_atoms.is_empty() && up_atoms.iter().all(|a| cset.contains(a)))
.map(|(pname, _)| pname.clone());
let is_one = up_atoms.len() == 1
|| schema_bounds.lower(rel).is_some_and(|lo| lo.len() == 1)
|| parent_match.is_some();
if is_one {
singleton_rel_names.insert(rname.to_string());
if let Some(pname) = parent_match {
sig_children
.entry(pname)
.or_default()
.push(rname.to_string());
} else {
for a in &up_atoms {
atom_sig_name
.entry(a.clone())
.or_insert_with(|| rname.to_string());
}
}
} else {
for a in &up_atoms {
atom_sig_name
.entry(a.clone())
.or_insert_with(|| rname.to_string());
}
}
}
let mut enum_order_aliases: BTreeMap<String, String> = BTreeMap::new(); for rel in &relations {
if !rel.is_changing()
&& rel.arity() == 1
&& let Some(alias) = rel.name().strip_suffix("/first")
&& let Some(up) = schema_bounds.upper(rel)
&& let Some(idx) = up.indices().next()
&& let Some(aname) = su.atom(idx as usize)
&& let Some(parent_sig) = atom_sig_name.get(aname)
{
if sig_children.contains_key(parent_sig) {
enum_order_aliases.insert(parent_sig.clone(), alias.to_string());
} else {
ordered_aliases.insert(parent_sig.clone(), alias.to_string());
}
}
}
let mut sql_to_alloy_table: BTreeMap<String, String> = BTreeMap::new();
for (a, s) in &imp.alloy_to_sql_table {
sql_to_alloy_table.insert(s.clone(), a.clone());
}
let mut field_range_sig: BTreeMap<String, String> = BTreeMap::new();
let sn = su.size() as u64;
for rel in &relations {
if rel.arity() < 2 || rel.name().ends_with("/next") || rel.name() == "next" {
continue;
}
if let Some(up) = schema_bounds.upper(rel)
&& let Some(flat) = up.indices().next()
&& let Some(ran_atom) = su.atom((flat % sn) as usize)
{
let range_sig = if su.int_of((flat % sn) as usize).is_some() {
"Int".to_string()
} else {
atom_sig_name
.get(ran_atom)
.cloned()
.unwrap_or_else(|| "Unknown".to_string())
};
field_range_sig.insert(rel.name().to_string(), range_sig);
}
}
let mut all_atoms: Vec<String> = Vec::new();
let mut atom_seen: BTreeSet<String> = BTreeSet::new();
let mut add_atom = |a: String| {
if atom_seen.insert(a.clone()) {
all_atoms.push(a);
}
};
let mut table_row_atoms: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut pk_row_lookup: BTreeMap<(String, String, DumpVal), String> = BTreeMap::new();
for (t_sql, rows) in rows_by_table {
let t_alloy = sql_to_alloy_table
.get(t_sql)
.cloned()
.unwrap_or_else(|| t_sql.clone());
let mut ratoms = Vec::with_capacity(rows.len());
for (i, (_, r)) in rows.iter().enumerate() {
let ratom = format!("{t_alloy}_row{i}");
add_atom(ratom.clone());
for (c, v) in r {
if !matches!(v, DumpVal::Null) {
pk_row_lookup
.entry((t_sql.clone(), c.clone(), v.clone()))
.or_insert_with(|| ratom.clone());
}
}
ratoms.push(ratom);
}
table_row_atoms.insert(t_sql.clone(), ratoms);
}
let mut singleton_atoms: BTreeMap<String, String> = BTreeMap::new();
for srel in &singleton_rel_names {
let atom = format!("{srel}0");
add_atom(atom.clone());
singleton_atoms.insert(srel.clone(), atom);
}
let mut ordered_vals: BTreeMap<String, BTreeSet<DumpVal>> = BTreeMap::new();
let mut domain_vals: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut int_vals: BTreeSet<i64> = BTreeSet::from([0]);
for rel in &relations {
if !rel.is_changing() || rel.arity() != 2 {
continue;
}
let rname = rel.name();
let Some(range_sig) = field_range_sig.get(rname) else {
continue;
};
let rname_low = rname.to_ascii_lowercase();
let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
Some((o, c)) => (Some(o), c),
None => (None, rname_low.as_str()),
};
for (t_sql, rows) in rows_by_table {
let t_alloy = sql_to_alloy_table
.get(t_sql)
.map(String::as_str)
.unwrap_or(t_sql.as_str());
if let Some(oh) = owner_hint
&& oh != t_alloy
&& oh != t_sql.as_str()
{
continue;
}
let col_sql = imp
.alloy_to_sql_col
.get(&(t_alloy.to_string(), col_alloy.to_string()))
.map(String::as_str)
.unwrap_or(col_alloy);
for (_, row) in rows {
let Some(val) = row.get(col_sql) else {
continue;
};
if matches!(val, DumpVal::Null) {
continue;
}
if range_sig == "Int" {
if let DumpVal::Int(n) = val {
int_vals.insert(*n);
}
} else if ordered_aliases.contains_key(range_sig) {
ordered_vals
.entry(range_sig.clone())
.or_default()
.insert(val.clone());
} else if range_sig != "SqlBool"
&& !imp.int_regions.iter().any(|r| r.sig_name == *range_sig)
&& !range_sig.ends_with("_row")
&& !imp
.alloy_to_sql_table
.contains_key(&range_sig.to_ascii_lowercase())
{
let sval = match val {
DumpVal::Str(s) => s.clone(),
DumpVal::Int(n) => n.to_string(),
DumpVal::Bool(b) => b.to_string(),
DumpVal::Null => unreachable!(),
};
domain_vals
.entry(range_sig.clone())
.or_default()
.insert(sval);
}
}
}
}
let date_sig_opt =
crate::cli::dates::detect_date_sig_from_relations(&relations, &field_range_sig);
let date_fmt = imp.date_format.as_deref().unwrap_or("%Y-%m");
if let Some(date_sig) = &date_sig_opt {
let mut src_unix_vals: Vec<i64> = Vec::new();
let mut ord_shift_vals: BTreeMap<String, Vec<i64>> = BTreeMap::new();
for rel in &relations {
let short = rel.name().rsplit('.').next().unwrap_or(rel.name());
if let Some(src_sig) = short.strip_prefix("to_date_") {
if src_sig == "Int" {
src_unix_vals.extend(int_vals.iter().copied());
} else if let Some(vs) = ordered_vals.get(src_sig) {
for v in vs {
if let DumpVal::Int(n) = v {
src_unix_vals.push(*n);
}
}
}
} else if let Some(ord_sig) = short.strip_prefix("add_")
&& rel.arity() == 4
&& ord_sig != "Int"
&& let Some(vs) = ordered_vals.get(ord_sig)
{
let nums: Vec<i64> = vs
.iter()
.filter_map(|v| match v {
DumpVal::Int(n) => Some(*n),
_ => None,
})
.collect();
ord_shift_vals.insert(ord_sig.to_string(), nums);
}
}
let mut base_dates: BTreeSet<String> = ordered_vals
.get(date_sig)
.map(|vs| {
vs.iter()
.filter_map(|v| match v {
DumpVal::Str(s) => Some(s.clone()),
_ => None,
})
.collect()
})
.unwrap_or_default();
crate::cli::dates::expand_date_domain(
date_fmt,
&imp.date_shifts,
&src_unix_vals,
&int_vals,
&ord_shift_vals,
&mut base_dates,
);
let entry = ordered_vals.entry(date_sig.clone()).or_default();
for d in base_dates {
entry.insert(DumpVal::Str(d));
}
}
for sh in &imp.ord_shifts {
let base_ints: Vec<i64> = ordered_vals
.get(&sh.ordered_sig)
.map(|vals| {
vals.iter()
.filter_map(|v| match v {
DumpVal::Int(n) => Some(*n),
_ => None,
})
.collect()
})
.unwrap_or_default();
let entry = ordered_vals.entry(sh.ordered_sig.clone()).or_default();
for n in base_ints {
entry.insert(DumpVal::Int(n.saturating_add(sh.delta)));
}
}
for osig in ordered_aliases.keys() {
ordered_vals
.entry(osig.clone())
.or_default()
.insert(DumpVal::Int(0));
}
let mut ordered_atom_map: BTreeMap<(String, DumpVal), String> = BTreeMap::new();
let mut ordered_chain: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut ordered_int_pairs: BTreeMap<String, Vec<(String, i64)>> = BTreeMap::new();
let mut ordered_str_values: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (osig, vals) in &ordered_vals {
let mut chain = Vec::with_capacity(vals.len());
let mut ipairs = Vec::new();
let mut svals = Vec::new();
for (i, v) in vals.iter().enumerate() {
let atom = format!("{osig}_v{i}");
add_atom(atom.clone());
ordered_atom_map.insert((osig.clone(), v.clone()), atom.clone());
match v {
DumpVal::Int(n) => ipairs.push((atom.clone(), *n)),
DumpVal::Str(s) => svals.push(s.clone()),
_ => {}
}
chain.push(atom);
}
if !ipairs.is_empty() {
ordered_int_pairs.insert(osig.clone(), ipairs);
}
if !svals.is_empty() {
ordered_str_values.insert(osig.clone(), svals);
}
ordered_chain.insert(osig.clone(), chain);
}
let mut domain_atom_map: BTreeMap<(String, String), String> = BTreeMap::new();
let mut domain_extra_atoms: BTreeMap<String, Vec<String>> = BTreeMap::new();
for (dsig, vals) in &domain_vals {
let children = sig_children.get(dsig).cloned().unwrap_or_default();
let mut extra = Vec::new();
for (i, v) in vals.iter().enumerate() {
let v_low = v.to_ascii_lowercase();
let matched_child = children.iter().find(|ch| {
let ch_low = ch.to_ascii_lowercase();
ch_low == v_low || ch_low.ends_with(&format!("_{v_low}"))
});
if let Some(ch) = matched_child
&& let Some(satom) = singleton_atoms.get(ch)
{
domain_atom_map.insert((dsig.clone(), v.clone()), satom.clone());
} else {
let atom = format!("{dsig}_d{i}");
add_atom(atom.clone());
domain_atom_map.insert((dsig.clone(), v.clone()), atom.clone());
extra.push(atom);
}
}
domain_extra_atoms.insert(dsig.clone(), extra);
}
let has_int_rel = relations.iter().any(|r| r.name() == "Int");
let mut int_atom_pairs: Vec<(String, i64)> = Vec::new();
if has_int_rel {
for &n in &int_vals {
if (i32::MIN as i64..=i32::MAX as i64).contains(&n) {
let name = n.to_string();
add_atom(name.clone());
int_atom_pairs.push((name, n));
}
}
}
if all_atoms.is_empty() {
all_atoms.push("_empty".to_string());
}
let base_u = Universe::new(all_atoms.iter().map(String::as_str)).map_err(|e| vec![e])?;
let u = if has_int_rel && !int_atom_pairs.is_empty() {
let refs: Vec<(&str, i64)> = int_atom_pairs
.iter()
.map(|(s, n)| (s.as_str(), *n))
.collect();
base_u.with_ints(32, &refs).map_err(|e| vec![e])?
} else {
base_u
};
let mut fixed = Instance::new(&u);
let mut table_row_sig_to_sql: BTreeMap<String, String> = BTreeMap::new();
for (t_alloy, t_sql) in &imp.alloy_to_sql_table {
table_row_sig_to_sql.insert(format!("{t_alloy}_row"), t_sql.clone());
}
let text_check_sig_names: BTreeSet<&str> = imp
.text_checks
.iter()
.map(|tc| tc.sig_name.as_str())
.collect();
for rel in &relations {
if rel.is_changing() {
continue;
}
let rname = rel.name();
if rel.arity() == 1 && text_check_sig_names.contains(rname) {
continue;
}
if rel.arity() == 1 {
let atoms: Vec<String> = if rname == "Int" {
int_atom_pairs.iter().map(|(s, _)| s.clone()).collect()
} else if let Some(t_sql) = table_row_sig_to_sql.get(&rname.to_ascii_lowercase()) {
table_row_atoms.get(t_sql).cloned().unwrap_or_default()
} else if let Some(satom) = singleton_atoms.get(rname) {
vec![satom.clone()]
} else if let Some(chain) = ordered_chain.get(rname) {
chain.clone()
} else if let Some(alias) = rname.strip_suffix("/first") {
if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
ordered_chain
.get(osig)
.and_then(|c| c.first())
.cloned()
.into_iter()
.collect()
} else if let Some((esig, _)) =
enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
{
sig_children
.get(esig)
.and_then(|chs| chs.first())
.and_then(|ch| singleton_atoms.get(ch))
.cloned()
.into_iter()
.collect()
} else {
Vec::new()
}
} else {
let mut combined = Vec::new();
if let Some(chs) = sig_children.get(rname) {
for ch in chs {
if let Some(a) = singleton_atoms.get(ch) {
combined.push(a.clone());
}
}
}
if let Some(ex) = domain_extra_atoms.get(rname) {
combined.extend(ex.iter().cloned());
}
combined
};
let slices: Vec<[&str; 1]> = atoms.iter().map(|a| [a.as_str()]).collect();
let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
fixed.set(rel, ts).map_err(|e| vec![e])?;
} else if rel.arity() == 2 {
let pairs: Vec<(String, String)> = if let Some(alias) = rname.strip_suffix("/next") {
if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
ordered_chain
.get(osig)
.map(|chain| {
chain
.windows(2)
.map(|w| (w[0].clone(), w[1].clone()))
.collect()
})
.unwrap_or_default()
} else if let Some((esig, _)) =
enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
{
sig_children
.get(esig)
.map(|chs| {
chs.windows(2)
.filter_map(|w| {
Some((
singleton_atoms.get(&w[0])?.clone(),
singleton_atoms.get(&w[1])?.clone(),
))
})
.collect()
})
.unwrap_or_default()
} else {
Vec::new()
}
} else {
Vec::new()
};
let slices: Vec<[&str; 2]> = pairs
.iter()
.map(|(a, b)| [a.as_str(), b.as_str()])
.collect();
let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
let ts = u.tuple_set(2, &refs).map_err(|e| vec![e])?;
fixed.set(rel, ts).map_err(|e| vec![e])?;
} else {
let short = rname.rsplit('.').next().unwrap_or(rname);
let is_date_fn_rel = need_date_fn
&& date_sig_opt.is_some()
&& singleton_atoms.contains_key("SqlDateFn")
&& (rel.arity() == 3 || rel.arity() == 4)
&& (short.starts_with("to_date_") || short.starts_with("add_"));
let is_ord_fn_rel = need_ord_fn
&& singleton_atoms.contains_key("SqlOrdFn")
&& rel.arity() == 3
&& imp.ord_shifts.iter().any(|s| s.field == short);
if !is_date_fn_rel && !is_ord_fn_rel {
let ts = u.tuple_set(rel.arity(), &[]).map_err(|e| vec![e])?;
fixed.set(rel, ts).map_err(|e| vec![e])?;
}
}
}
if need_date_fn
&& let Some(date_sig) = &date_sig_opt
&& let Some(fn_atom) = singleton_atoms.get("SqlDateFn")
{
let date_strings = ordered_str_values
.get(date_sig)
.map(Vec::as_slice)
.unwrap_or(&[]);
let date_atoms = ordered_chain
.get(date_sig)
.map(Vec::as_slice)
.unwrap_or(&[]);
crate::cli::dates::populate_sql_date_fn(
&mut fixed,
&u,
&relations,
fn_atom,
date_fmt,
&imp.date_shifts,
date_strings,
date_atoms,
&ordered_int_pairs,
&int_atom_pairs,
)
.map_err(|e| vec![e])?;
}
if need_ord_fn
&& !imp.ord_shifts.is_empty()
&& let Some(fn_atom) = singleton_atoms.get("SqlOrdFn")
{
crate::cli::dates::populate_sql_ord_fn(
&mut fixed,
&u,
&relations,
fn_atom,
&imp.ord_shifts,
&ordered_int_pairs,
)
.map_err(|e| vec![e])?;
}
for tc in &imp.text_checks {
let Some(rel) = relations.iter().find(|r| r.name() == tc.sig_name) else {
continue;
};
let mut matched: Vec<String> = Vec::new();
for ((dsig, raw), atom) in &domain_atom_map {
if dsig == &tc.domain_sig && elinvar_als::eval_sql_text_check(raw, &tc.kind) {
matched.push(atom.clone());
}
}
if let (Some(strs), Some(atoms)) = (
ordered_str_values.get(&tc.domain_sig),
ordered_chain.get(&tc.domain_sig),
) {
for (raw, atom) in strs.iter().zip(atoms.iter()) {
if elinvar_als::eval_sql_text_check(raw, &tc.kind) {
matched.push(atom.clone());
}
}
}
for lsig in &tc.literal_sigs {
if let Some(atom) = singleton_atoms.get(lsig) {
matched.push(atom.clone());
}
}
matched.sort();
matched.dedup();
let slices: Vec<[&str; 1]> = matched.iter().map(|a| [a.as_str()]).collect();
let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
fixed.set(rel, ts).map_err(|e| vec![e])?;
}
let mut state0 = Instance::new(&u);
for rel in &relations {
if !rel.is_changing() {
continue;
}
let rname = rel.name();
let rname_low = rname.to_ascii_lowercase();
if rel.arity() == 1 {
let atoms: Vec<String> = if imp.alloy_retired_to_sql_table.contains_key(&rname_low) {
Vec::new()
} else {
let t_sql = imp
.alloy_to_sql_table
.get(&rname_low)
.map(String::as_str)
.unwrap_or(rname_low.as_str());
table_row_atoms.get(t_sql).cloned().unwrap_or_default()
};
let slices: Vec<[&str; 1]> = atoms.iter().map(|a| [a.as_str()]).collect();
let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
state0.set(rel, ts).map_err(|e| vec![e])?;
} else if rel.arity() == 2 {
let range_sig = field_range_sig.get(rname).map(String::as_str).unwrap_or("");
let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
Some((o, c)) => (Some(o), c),
None => (None, rname_low.as_str()),
};
let mut pairs: Vec<(String, String)> = Vec::new();
for (t_sql, rows) in rows_by_table {
let t_alloy = sql_to_alloy_table
.get(t_sql)
.map(String::as_str)
.unwrap_or(t_sql.as_str());
if let Some(oh) = owner_hint
&& oh != t_alloy
&& oh != t_sql.as_str()
{
continue;
}
let col_sql = imp
.alloy_to_sql_col
.get(&(t_alloy.to_string(), col_alloy.to_string()))
.map(String::as_str)
.unwrap_or(col_alloy);
let Some(ratoms) = table_row_atoms.get(t_sql) else {
continue;
};
let fk_opt = imp.fk_targets.get(&(t_sql.clone(), col_sql.to_string()));
for (ratom, (_, row)) in ratoms.iter().zip(rows.iter()) {
let Some(val) = row.get(col_sql) else {
continue;
};
if matches!(val, DumpVal::Null) {
continue;
}
let val_atom: Option<String> = if let Some(fk) = fk_opt {
pk_row_lookup
.get(&(fk.target_table.clone(), fk.target_col.clone(), val.clone()))
.cloned()
} else if let Some(region) =
imp.int_regions.iter().find(|r| r.sig_name == range_sig)
{
match val {
DumpVal::Int(n) => region
.intervals
.iter()
.find(|(lo, hi, _)| {
lo.is_none_or(|l| *n >= l) && hi.is_none_or(|h| *n <= h)
})
.and_then(|(_, _, atom_sig)| singleton_atoms.get(atom_sig))
.cloned(),
_ => None,
}
} else if range_sig == "Int" {
match val {
DumpVal::Int(n) => u
.atom_of_int(*n)
.and_then(|i| u.atom(i).map(str::to_string)),
_ => None,
}
} else if range_sig == "SqlBool" {
let is_true = match val {
DumpVal::Bool(b) => *b,
DumpVal::Int(n) => *n != 0,
DumpVal::Str(s) => s == "1" || s.eq_ignore_ascii_case("true"),
DumpVal::Null => false,
};
let key = if is_true { "SqlTrue" } else { "SqlFalse" };
singleton_atoms.get(key).cloned()
} else if ordered_aliases.contains_key(range_sig) {
ordered_atom_map
.get(&(range_sig.to_string(), val.clone()))
.cloned()
} else {
let sval = match val {
DumpVal::Str(s) => s.clone(),
DumpVal::Int(n) => n.to_string(),
DumpVal::Bool(b) => b.to_string(),
DumpVal::Null => unreachable!(),
};
domain_atom_map.get(&(range_sig.to_string(), sval)).cloned()
};
if let Some(va) = val_atom {
pairs.push((ratom.clone(), va));
}
}
}
let slices: Vec<[&str; 2]> = pairs
.iter()
.map(|(a, b)| [a.as_str(), b.as_str()])
.collect();
let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
let ts = u.tuple_set(2, &refs).map_err(|e| vec![e])?;
state0.set(rel, ts).map_err(|e| vec![e])?;
}
}
let trace = Trace::new(fixed, vec![state0], 0).map_err(|e| vec![e])?;
let mut fact_violations = Vec::new();
for (fname, inner) in &active_facts {
match evaluate_trace_at(&trace, inner, 0, &[]) {
Ok(true) => {}
Ok(false) => {
fact_violations.push(RuleViolation {
rule: fname.clone(),
table: None,
detail: "schema rule does not hold on the dumped rows".to_string(),
line: None,
});
}
Err(es) => return Err(es),
}
}
let mut promises = Vec::new();
for (pname, inner) in &active_promises {
let holds = evaluate_trace_at(&trace, inner, 0, &[])?;
promises.push((pname.clone(), holds));
}
Ok((fact_violations, promises, skipped_promises))
}
pub fn audit(
schema_file: &str,
schema_sql: &str,
data_file: &str,
data_sql: &str,
opts: &AuditOptions,
) -> Output {
let imp = match elinvar_als::import_sql_with(
schema_file,
schema_sql,
&elinvar_als::SqlImportOptions::new()
.temporal(true)
.from_empty(false)
.tables(opts.tables.clone())
.with_referencing(opts.with_referencing),
) {
Ok(i) => i,
Err(errors) => return error_output("audit", errors),
};
let (rows_by_table, warnings) = match parse_dump_rows(data_file, data_sql, &imp) {
Ok(r) => r,
Err(msg) => return audit_parse_error(msg),
};
let rows_audited: usize = rows_by_table.values().map(Vec::len).sum();
let table_counts: BTreeMap<String, usize> = rows_by_table
.iter()
.map(|(t, rs)| (t.clone(), rs.len()))
.collect();
let mut rule_violations = check_structural_rules(&imp, &rows_by_table);
let combined = match opts.extra_als.as_deref() {
Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
_ => imp.model.clone(),
};
let model = match elinvar_als::read_with(
schema_file,
&combined,
elinvar_als::ReadOptions::default().default_bitwidth(imp.bitwidth),
) {
Ok(m) => m,
Err(errors) => return error_output("audit", errors),
};
let (fact_violations, promises, skipped_promises) =
match evaluate_dump_on_model(&model, &imp, &rows_by_table) {
Ok(res) => res,
Err(errors) => return error_output("audit", errors),
};
for fv in fact_violations {
if !rule_violations.iter().any(|rv| rv.rule == fv.rule) {
rule_violations.push(fv);
}
}
let broken_promises = promises.iter().filter(|(_, holds)| !holds).count();
let has_violations = !rule_violations.is_empty() || broken_promises > 0;
let verdict = if has_violations {
"violations"
} else {
"clean"
};
let status = if has_violations { 1 } else { 0 };
let mut text = String::new();
let _ = writeln!(
text,
"audit ({data_file} against {schema_file}): {verdict} ({rows_audited} row(s), {} rule violation(s), {broken_promises} broken promise(s))",
rule_violations.len()
);
for rv in &rule_violations {
let _ = writeln!(text, " BROKEN rule {}: {}", rv.rule, rv.detail);
}
for (pname, holds) in &promises {
let word = if *holds { "holds" } else { "BROKEN" };
let _ = writeln!(text, " promise {pname}: {word}");
}
for (pname, reason) in &skipped_promises {
let _ = writeln!(text, " skipped promise {pname}: {reason}");
}
for w in &warnings {
let line = w.place.as_ref().map_or(1, |p| p.line);
let _ = writeln!(text, "warning[{}]: line {line}: {}", w.code, w.message);
}
if !imp.skipped.is_empty() {
let noun = if imp.skipped.len() == 1 {
"rule"
} else {
"rules"
};
let _ = writeln!(
text,
"warning: {} {noun} of the schema were not read and could not be checked",
imp.skipped.len()
);
}
let violations_json: Vec<Value> = rule_violations
.iter()
.map(|rv| {
let mut obj = json!({
"rule": rv.rule,
"detail": rv.detail,
});
if let Some(t) = &rv.table {
obj["table"] = Value::String(t.clone());
}
if let Some(l) = rv.line {
obj["line"] = json!(l);
}
obj
})
.collect();
let promises_json: Vec<Value> = promises
.iter()
.map(|(name, holds)| json!({ "name": name, "holds": holds }))
.collect();
let skipped_json: Vec<Value> = skipped_promises
.iter()
.map(|(name, reason)| json!({ "name": name, "reason": reason }))
.collect();
Output {
status,
text: text.clone(),
json: json!({
"elinvar": 1,
"command": "audit",
"verdict": verdict,
"rows_audited": rows_audited,
"tables": table_counts,
"rule_violations": violations_json,
"promises": promises_json,
"skipped_promises": skipped_json,
"unread_rules": imp.skipped.len(),
"warnings": warnings,
"story": text,
}),
}
}