//! 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;
use crate::load_naming::_helpers::spellings::{kept_as_written, reaches};
/// 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, when several do and none is spelled as `source` (see `ambiguous_spellings`), or when `warehouse` stores `named` as one that does already, so a table loads where it did before; on a warehouse resolving names ignoring case (DuckDB), a column `named` reaches in another case keeps its stored spelling, so a `--reload` rebuilding the table keeps it too. 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 matching = || {
existing
.iter()
.filter(|column| column.eq_ignore_ascii_case(source))
.filter(|column| kept_as_written(column, warehouse))
};
let respelled = |column: &&String| {
warehouse.is_some_and(|warehouse| {
let adapter = sql_adapter(warehouse);
adapter.identifiers_ignore_case() && adapter.stored_name(named) != **column
})
};
if let Some(column) = matching().find(|column| reaches(column, named, warehouse)) {
return respelled(&column).then_some(column.as_str());
}
match matching().find(|column| *column == source) {
Some(exact) => Some(exact.as_str()),
None if matching().count() == 1 => matching().next().map(String::as_str),
None => None,
}
}