//! The column a table already has that a source column loads into under its spelling, rather than beside it.
use crate::adapters::dispatch::main::dialect::sql_adapter::sql_adapter;
use crate::column_types::models::Warehouse;
/// The column of `existing`, the table's columns, that a column with the source name `source` loads into rather than beside under `named`, the name `naming` gives it: the one `source` names ignoring case (the exact one first, as a warehouse that keeps case may hold both). None when no column matches, or when `warehouse` stores `named` as one that does already, so a table loads where it did before. Only a column the warehouse would store under its own spelling counts: one it would store otherwise when written (Snowflake's quoted lower case) is never loaded into by name.
pub fn existing_spelling<'a>(
(existing, warehouse): (&'a [String], Option<Warehouse>),
source: &str,
named: &str,
) -> Option<&'a str> {
let kept = |column: &&String| {
warehouse.is_none_or(|warehouse| sql_adapter(warehouse).stored_name(column) == **column)
};
let matching = || {
existing
.iter()
.filter(|column| column.eq_ignore_ascii_case(source))
.filter(kept)
};
let reached = |column: &&String| match warehouse {
Some(warehouse) => {
let adapter = sql_adapter(warehouse);
adapter.is_stored_as(column, &adapter.stored_name(named))
}
None => *column == named,
};
if matching().any(|column| reached(&column)) {
return None;
}
matching()
.find(|column| *column == source)
.or_else(|| matching().next())
.map(String::as_str)
}