use std::collections::BTreeMap;
use crate::contract::_helpers::compare::is_own;
use crate::contract::constants::{
FILES_EXTRA_COLUMN, FILES_MISSING_COLUMN, FILES_TYPE_MISMATCH, NAMED_FILES,
};
use crate::contract::models::ContractFinding;
use crate::load_naming::models::Compat;
use crate::loader::models::FileSchema;
use crate::schema_plan::models::LiveColumn;
pub(crate) fn file_drift(
compat: Compat,
live: &[LiveColumn],
files: &[FileSchema],
) -> Vec<ContractFinding> {
let mut found: Vec<ContractFinding> = Vec::new();
for column in live.iter().filter(|column| !is_own(compat, &column.name)) {
let expected = column.column_type.to_string();
let mut other_types: BTreeMap<String, Vec<&str>> = BTreeMap::new();
let mut missing: Vec<&str> = Vec::new();
for file in files {
let key = file.key.as_str();
match file.columns.iter().find(|held| held.name == column.name) {
Some(held) if held.column_type != column.column_type => other_types
.entry(held.column_type.to_string())
.or_default()
.push(key),
Some(_) => {}
None => missing.push(key),
}
}
found.extend(other_types.into_iter().map(|(held, keys)| ContractFinding {
column: Some(column.name.clone()),
declared_type: None,
kind: FILES_TYPE_MISMATCH,
message: format!(
"column '{}' is {expected} in the newest load but {held} in {}",
column.name,
named(&keys)
),
physical_type: Some(held),
source_type: None,
}));
found.extend((!missing.is_empty()).then(|| ContractFinding {
column: Some(column.name.clone()),
declared_type: None,
kind: FILES_MISSING_COLUMN,
message: format!(
"column '{}' is absent from {}",
column.name,
named(&missing)
),
physical_type: None,
source_type: None,
}));
}
found.extend(extra_columns(compat, live, files));
found
}
fn extra_columns(
compat: Compat,
live: &[LiveColumn],
files: &[FileSchema],
) -> Vec<ContractFinding> {
let mut extra: BTreeMap<&str, (String, Vec<&str>)> = BTreeMap::new();
for file in files {
let key = file.key.as_str();
for column in file
.columns
.iter()
.filter(|column| is_extra(compat, live, column))
{
extra
.entry(&column.name)
.or_insert_with(|| (column.column_type.to_string(), Vec::new()))
.1
.push(key);
}
}
extra
.into_iter()
.map(|(name, (held, keys))| ContractFinding {
column: Some(name.to_owned()),
declared_type: None,
kind: FILES_EXTRA_COLUMN,
message: format!(
"column '{name}' ({held}) is in {} but not in the newest load",
named(&keys)
),
physical_type: Some(held),
source_type: None,
})
.collect()
}
fn is_extra(compat: Compat, live: &[LiveColumn], column: &LiveColumn) -> bool {
!is_own(compat, &column.name) && !live.iter().any(|newest| newest.name == column.name)
}
fn named(keys: &[&str]) -> String {
let count = match keys.len() {
1 => "1 file".to_owned(),
many => format!("{many} files"),
};
let shown = keys[..keys.len().min(NAMED_FILES)].join(", ");
match keys.len().saturating_sub(NAMED_FILES) {
0 => format!("{count}: {shown}"),
more => format!("{count}: {shown} and {more} more"),
}
}