use crate::conn::OrFailure;
use crate::error::{Failure, Result};
use crate::sql::ident;
use mysql_async::prelude::Queryable;
use mysql_async::Conn;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameCase {
Sensitive,
InsensitiveStoredLower,
InsensitiveStoredAsWritten,
Unknown,
}
impl NameCase {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Sensitive => "sensitive",
Self::InsensitiveStoredLower => "insensitive_stored_lower",
Self::InsensitiveStoredAsWritten => "insensitive_stored_as_written",
Self::Unknown => "unknown",
}
}
#[must_use]
pub const fn from_setting(setting: i64) -> Self {
match setting {
0 => Self::Sensitive,
1 => Self::InsensitiveStoredLower,
2 => Self::InsensitiveStoredAsWritten,
_ => Self::Unknown,
}
}
}
pub async fn name_case(connection: &mut Conn) -> Result<NameCase> {
let setting: Option<i64> = connection
.query_first("SELECT @@lower_case_table_names")
.await
.or_failure()?;
Ok(setting.map_or(NameCase::Unknown, NameCase::from_setting))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
pub asked: String,
pub actual: String,
}
impl Resolved {
#[must_use]
pub fn differs_only_by_case(&self) -> bool {
self.asked != self.actual && self.asked.eq_ignore_ascii_case(&self.actual)
}
}
const DELIMITER: char = '`';
const MOST_PARTS: usize = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Qualified {
pub database: Option<String>,
pub name: String,
}
impl Qualified {
#[must_use]
pub fn database_or(&self, in_force: Option<String>) -> Option<String> {
self.database.clone().or(in_force)
}
#[must_use]
pub fn overrides(&self, in_force: Option<&str>) -> bool {
match (self.database.as_deref(), in_force) {
(Some(carried), Some(in_force)) => !carried.eq_ignore_ascii_case(in_force),
_ => false,
}
}
}
#[must_use]
pub fn split(asked: &str) -> Qualified {
let whole = || Qualified {
database: None,
name: asked.to_owned(),
};
match parts(asked).as_deref() {
Some([name]) => Qualified {
database: None,
name: name.clone(),
},
Some([database, name]) => Qualified {
database: Some(database.clone()),
name: name.clone(),
},
_ => whole(),
}
}
fn parts(asked: &str) -> Option<Vec<String>> {
let mut found: Vec<String> = Vec::new();
let mut current = String::new();
let mut inside = false;
let mut delimited = false;
let mut characters = asked.chars().peekable();
while let Some(character) = characters.next() {
match character {
DELIMITER if inside => {
if characters.peek() == Some(&DELIMITER) {
characters.next();
current.push(DELIMITER);
} else {
inside = false;
}
}
DELIMITER if current.is_empty() && !delimited => {
inside = true;
delimited = true;
}
DELIMITER => return None,
'.' if !inside => {
if current.is_empty() {
return None;
}
found.push(std::mem::take(&mut current));
delimited = false;
}
_ if delimited && !inside => return None,
other => current.push(other),
}
}
if inside || current.is_empty() {
return None;
}
found.push(current);
(found.len() <= MOST_PARTS).then_some(found)
}
pub async fn resolve_database(connection: &mut Conn, asked: &str) -> Result<Resolved> {
ident::quote(asked)?;
let found: Option<String> = connection
.exec_first(
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA \
WHERE LOWER(SCHEMA_NAME) = LOWER(?) ORDER BY SCHEMA_NAME LIMIT 1",
(asked,),
)
.await
.or_failure()?;
if let Some(actual) = found {
return Ok(Resolved {
asked: asked.to_owned(),
actual,
});
}
let candidates: Vec<String> = connection
.query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA ORDER BY SCHEMA_NAME")
.await
.or_failure()?;
Err(missing("database", asked, &candidates))
}
pub async fn resolve_table(connection: &mut Conn, database: &str, asked: &str) -> Result<Resolved> {
ident::quote(database)?;
ident::quote(asked)?;
let found: Option<String> = connection
.exec_first(
"SELECT TABLE_NAME FROM information_schema.TABLES \
WHERE TABLE_SCHEMA = ? AND LOWER(TABLE_NAME) = LOWER(?) \
ORDER BY TABLE_NAME LIMIT 1",
(database, asked),
)
.await
.or_failure()?;
if let Some(actual) = found {
return Ok(Resolved {
asked: asked.to_owned(),
actual,
});
}
let candidates: Vec<String> = connection
.exec(
"SELECT TABLE_NAME FROM information_schema.TABLES \
WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME",
(database,),
)
.await
.or_failure()?;
Err(missing("table", asked, &candidates))
}
fn missing(kind: &str, asked: &str, candidates: &[String]) -> Failure {
let near = nearest(asked, candidates, near_name_count());
let failure = Failure::absence("schema.unknown_object", format!("`{asked}`"))
.with_detail("detail", format!("`{asked}`"))
.with_detail("kind", kind.to_owned());
if near.is_empty() {
return failure
.with_detail("reason", "alone")
.with_hint("no object of a similar name is visible either");
}
let names = near.join(", ");
failure
.with_detail("reason", "near")
.with_hint(format!("the closest visible names are: {names}"))
.with_detail("names", names)
}
const NEAR_NAME_COUNT: usize = 5;
static IN_FORCE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
pub fn declare_near_name_count(count: usize) {
IN_FORCE.store(count, std::sync::atomic::Ordering::Relaxed);
}
#[must_use]
pub fn near_name_count() -> usize {
match IN_FORCE.load(std::sync::atomic::Ordering::Relaxed) {
0 => NEAR_NAME_COUNT,
settled => settled,
}
}
#[must_use]
pub fn nearest(asked: &str, candidates: &[String], count: usize) -> Vec<String> {
let wanted = asked.to_lowercase();
let mut scored: Vec<(usize, &String)> = candidates
.iter()
.map(|candidate| (distance(&wanted, &candidate.to_lowercase()), candidate))
.collect();
scored.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(right.1)));
scored
.into_iter()
.take(count)
.map(|(_, candidate)| candidate.clone())
.collect()
}
fn distance(left: &str, right: &str) -> usize {
let right_chars: Vec<char> = right.chars().collect();
let mut previous: Vec<usize> = (0..=right_chars.len()).collect();
let mut current = vec![0_usize; right_chars.len() + 1];
for (row, left_char) in left.chars().enumerate() {
current[0] = row + 1;
for (column, right_char) in right_chars.iter().enumerate() {
let substitution = previous[column] + usize::from(left_char != *right_char);
current[column + 1] = substitution
.min(previous[column + 1] + 1)
.min(current[column] + 1);
}
std::mem::swap(&mut previous, &mut current);
}
previous[right_chars.len()]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_case_rule_comes_from_the_server_setting() {
assert_eq!(NameCase::from_setting(0), NameCase::Sensitive);
assert_eq!(NameCase::from_setting(1), NameCase::InsensitiveStoredLower);
assert_eq!(
NameCase::from_setting(2),
NameCase::InsensitiveStoredAsWritten
);
assert_eq!(NameCase::from_setting(9), NameCase::Unknown);
}
#[test]
fn a_name_reached_under_another_case_is_declared() {
let reached = Resolved {
asked: "PEDIDOS".to_owned(),
actual: "pedidos".to_owned(),
};
assert!(reached.differs_only_by_case());
let exact = Resolved {
asked: "pedidos".to_owned(),
actual: "pedidos".to_owned(),
};
assert!(!exact.differs_only_by_case());
}
#[test]
fn a_miss_suggests_the_nearest_visible_names() {
let visible = vec![
"pedidos".to_owned(),
"pedido_item".to_owned(),
"clientes".to_owned(),
];
let near = nearest("pedido", &visible, 2);
assert_eq!(near, vec!["pedidos".to_owned(), "pedido_item".to_owned()]);
let failure = missing("table", "pedido", &visible);
assert_eq!(failure.category(), crate::error::Category::Absence);
assert!(failure.hint().is_some_and(|hint| hint.contains("pedidos")));
}
#[test]
fn a_miss_with_nothing_visible_says_so() {
let failure = missing("database", "shop", &[]);
assert!(failure.hint().is_some_and(|hint| hint.contains("similar")));
}
#[test]
fn the_qualified_name_a_map_writes_comes_apart_again() {
let split = split("shop.events_by_year");
assert_eq!(split.database.as_deref(), Some("shop"));
assert_eq!(split.name, "events_by_year");
}
#[test]
fn a_bare_name_is_left_exactly_as_it_was_written() {
for name in ["orders", "ORDERS", "pedido_item", "t1"] {
let split = split(name);
assert_eq!(split.database, None, "input {name}");
assert_eq!(split.name, name, "input {name}");
}
}
#[test]
fn the_database_the_name_carries_wins_over_the_one_in_force() {
let carried = split("shop.orders");
assert_eq!(
carried.database_or(Some("other".to_owned())).as_deref(),
Some("shop")
);
let bare = split("orders");
assert_eq!(
bare.database_or(Some("other".to_owned())).as_deref(),
Some("other")
);
assert_eq!(bare.database_or(None), None);
}
#[test]
fn a_name_that_overrides_the_database_in_force_says_so() {
assert!(split("shop.orders").overrides(Some("other")));
assert!(!split("shop.orders").overrides(Some("SHOP")));
assert!(!split("shop.orders").overrides(None));
assert!(!split("orders").overrides(Some("shop")));
}
#[test]
fn a_name_written_in_the_delimiter_stays_one_name() {
let literal = split("`a.b`");
assert_eq!(literal.database, None);
assert_eq!(literal.name, "a.b");
let escaped = split("`a``b`");
assert_eq!(escaped.database, None);
assert_eq!(escaped.name, "a`b");
}
#[test]
fn a_fully_delimited_path_comes_apart_into_its_two_parts() {
let split = split("`shop`.`orders`");
assert_eq!(split.database.as_deref(), Some("shop"));
assert_eq!(split.name, "orders");
}
#[test]
fn text_that_is_not_a_path_is_handed_on_whole() {
for name in [
"a.b.c", ".orders", "shop.",
"`orders", "a`b",
"`a`b", "",
] {
let split = split(name);
assert_eq!(split.database, None, "input {name:?}");
assert_eq!(split.name, name, "input {name:?}");
}
}
}