Skip to main content

an5_adapters/base/
dialect.rs

1//! Dialect detection, identifier quoting and vector math.
2//!
3//! Mirrors the Go `an5adapters/base` package.
4
5/// Supported database engines.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum Dialect {
8    Mssql,
9    Postgres,
10    Sqlite,
11}
12
13impl Dialect {
14    /// Detect the dialect from a connection string.
15    pub fn detect(conn_str: &str) -> Self {
16        let l = conn_str.trim().to_lowercase();
17        if l.starts_with("postgres://")
18            || l.starts_with("postgresql://")
19            || l.contains("port=5432")
20        {
21            return Dialect::Postgres;
22        }
23        if l.starts_with("sqlite://")
24            || l.starts_with("sqlite:")
25            || l.starts_with("file:")
26            || l.ends_with(".db")
27            || l.ends_with(".sqlite")
28            || l.ends_with(".sqlite3")
29            || l == ":memory:"
30        {
31            return Dialect::Sqlite;
32        }
33        Dialect::Mssql
34    }
35
36    /// Quote a single identifier (column or table part).
37    pub fn quote_identifier(&self, name: &str) -> String {
38        let raw = strip_wrapping(strip_wrapping(name, "[", "]"), "\"", "\"");
39        match self {
40            Dialect::Postgres | Dialect::Sqlite => {
41                format!("\"{}\"", raw.replace('"', "\"\""))
42            }
43            Dialect::Mssql => format!("[{}]", raw.replace(']', "]]")),
44        }
45    }
46
47    /// Quote a possibly schema-qualified table name (`dbo.users`).
48    pub fn quote_table(&self, table: &str) -> String {
49        let t = table.trim();
50        // Already quoted by the generator: `[dbo].[User]`.
51        if t.starts_with('[') || t.starts_with('"') {
52            return t.to_string();
53        }
54        t.split('.')
55            .map(|p| self.quote_identifier(p))
56            .collect::<Vec<_>>()
57            .join(".")
58    }
59
60    /// Positional placeholder: `$N` for Postgres, `?` otherwise.
61    pub fn placeholder(&self, n: usize) -> String {
62        match self {
63            Dialect::Postgres => format!("${}", n),
64            _ => "?".to_string(),
65        }
66    }
67
68    /// MSSQL read hint used on every SELECT.
69    pub fn nolock(&self) -> &'static str {
70        match self {
71            Dialect::Mssql => " WITH (NOLOCK)",
72            _ => "",
73        }
74    }
75
76    /// Dialects that use `LIMIT` / `OFFSET` instead of `TOP` / `FETCH NEXT`.
77    pub fn supports_limit_offset(&self) -> bool {
78        matches!(self, Dialect::Postgres | Dialect::Sqlite)
79    }
80}
81
82fn strip_wrapping<'a>(name: &'a str, left: &str, right: &str) -> &'a str {
83    if name.starts_with(left) && name.ends_with(right) && name.len() >= left.len() + right.len() {
84        &name[left.len()..name.len() - right.len()]
85    } else {
86        name
87    }
88}
89
90/// Cosine similarity between two vectors (1.0 = identical direction).
91pub fn cosine_similarity(a: &[f64], b: &[f64]) -> f64 {
92    if a.len() != b.len() || a.is_empty() {
93        return 0.0;
94    }
95    let mut dot = 0.0;
96    let mut m1 = 0.0;
97    let mut m2 = 0.0;
98    for i in 0..a.len() {
99        dot += a[i] * b[i];
100        m1 += a[i] * a[i];
101        m2 += b[i] * b[i];
102    }
103    if m1 == 0.0 || m2 == 0.0 {
104        return 0.0;
105    }
106    dot / (m1.sqrt() * m2.sqrt())
107}
108
109/// Euclidean distance between two vectors.
110pub fn euclidean_distance(a: &[f64], b: &[f64]) -> f64 {
111    a.iter()
112        .zip(b.iter())
113        .map(|(x, y)| (x - y) * (x - y))
114        .sum::<f64>()
115        .sqrt()
116}
117
118/// Dot product of two vectors.
119pub fn dot_product(a: &[f64], b: &[f64]) -> f64 {
120    a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
121}
122
123/// Distance honouring the AN5 metric names (`cosine` / `euclidean` / `dot`).
124pub fn vector_distance(a: &[f64], b: &[f64], metric: &str) -> f64 {
125    match metric.to_lowercase().as_str() {
126        "euclidean" => euclidean_distance(a, b),
127        "dot" => -dot_product(a, b),
128        _ => 1.0 - cosine_similarity(a, b),
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn detects_dialects() {
138        assert_eq!(
139            Dialect::detect("postgres://localhost/db"),
140            Dialect::Postgres
141        );
142        assert_eq!(Dialect::detect("app.db"), Dialect::Sqlite);
143        assert_eq!(
144            Dialect::detect("Server=localhost;Database=master;"),
145            Dialect::Mssql
146        );
147    }
148
149    #[test]
150    fn quotes_identifiers_per_dialect() {
151        assert_eq!(Dialect::Mssql.quote_identifier("id"), "[id]");
152        assert_eq!(Dialect::Postgres.quote_identifier("id"), "\"id\"");
153    }
154
155    #[test]
156    fn keeps_generator_quoted_table() {
157        assert_eq!(Dialect::Mssql.quote_table("[dbo].[User]"), "[dbo].[User]");
158        assert_eq!(Dialect::Postgres.quote_table("dbo.users"), "\"dbo\".\"users\"");
159    }
160
161    #[test]
162    fn placeholders_per_dialect() {
163        assert_eq!(Dialect::Postgres.placeholder(2), "$2");
164        assert_eq!(Dialect::Mssql.placeholder(2), "?");
165    }
166
167    #[test]
168    fn cosine_identical_is_one() {
169        let v = vec![1.0, 0.0];
170        assert!((cosine_similarity(&v, &v) - 1.0).abs() < 1e-9);
171    }
172}