use crate::catalog::names::normalize_table_name;
use crate::fx::{FxHashMap, FxHashSet};
pub(super) fn column_splits(selector: &str) -> impl Iterator<Item = (&str, &str)> {
let mut quoted = false;
selector
.char_indices()
.filter_map(move |(index, character)| {
if character == '"' {
quoted = !quoted;
}
if quoted || character != '.' {
return None;
}
let (table, separator_and_column) = selector.split_at(index);
let column = &separator_and_column[1..];
(!table.trim().is_empty() && !column.trim().is_empty()).then_some((table, column))
})
}
pub(super) fn matches_column(entry: &str, table: &str, column: &str) -> bool {
entry
.strip_prefix("column:")
.and_then(|entry| entry.strip_suffix(column))
.and_then(|prefix| prefix.strip_suffix('.'))
.is_some_and(|prefix| {
prefix
.bytes()
.filter(|&byte| byte == b'"')
.count()
.is_multiple_of(2)
&& normalize_table_name(prefix) == normalize_table_name(table)
})
}
pub(super) fn ambiguous_columns<'a, 'b>(
selectors: impl Iterator<Item = &'a str>,
candidates: impl IntoIterator<Item = (&'b str, &'b str)>,
) -> Vec<bool> {
let mut columns = FxHashMap::<String, FxHashSet<&str>>::default();
for (table, column) in candidates {
columns
.entry(normalize_table_name(table))
.or_default()
.insert(column);
}
selectors
.map(|selector| {
let Some(selector) = selector.strip_prefix("column:") else {
return false;
};
column_splits(selector)
.filter(|(table, column)| {
columns
.get(&normalize_table_name(table))
.is_some_and(|names| names.contains(column))
})
.nth(1)
.is_some()
})
.collect()
}
pub(super) fn duplicate_key<'a>(selector: &'a str, canonical: &str) -> (String, &'a str) {
selector
.strip_prefix("column:")
.and_then(|selector| column_splits(selector).next())
.map_or_else(
|| (canonical.to_owned(), ""),
|(table, column)| (normalize_table_name(table), column),
)
}
#[cfg(all(test, any(nm_shard_all, nm_shard_0)))]
mod tests {
#[test]
fn duplicate_key_borrows_dotted_suffix() {
let selector = format!("column:orders.{}id", "x.".repeat(4096));
let (table, column) = super::duplicate_key(&selector, "");
let suffix = selector.strip_prefix("column:orders.").unwrap();
assert_eq!(table, "orders");
assert_eq!(column, suffix);
assert_eq!(column.as_ptr(), suffix.as_ptr());
}
}