razeri-plugin-api 0.1.1

Extension traits and registries for Razeri plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Canonical dialect resolver with alias support and near-miss suggestions.
//!
//! All service crates (CLI, API, MCP, AI, pipeline) should call
//! [`resolve_dialect_by_name`] instead of maintaining their own match blocks.

use crate::PlatformDialect;
use crate::dialect::PlatformRegistry;
use std::sync::Arc;
use thiserror::Error;

/// Error returned when a dialect name cannot be resolved.
#[derive(Debug, Error)]
pub enum ResolveError {
    /// The name did not match any registered dialect or known alias.
    #[error(
        "unknown dialect: '{name}'. {suggestions_text}Registered: {registered}",
        suggestions_text = if suggestions.is_empty() {
            String::new()
        } else {
            format!("Did you mean: {}? ", suggestions.join(", "))
        },
        registered = registered.join(", ")
    )]
    UnknownDialect {
        /// The name that was looked up.
        name: String,
        /// Near-miss suggestions (by edit distance).
        suggestions: Vec<String>,
        /// All registered dialect names.
        registered: Vec<String>,
    },
}

/// Alias table mapping user-facing names to canonical dialect names.
///
/// The canonical name must match `DialectInfo::name` of a registered dialect.
/// Order does not matter — the first match on the left column wins.
const ALIAS_TABLE: &[(&str, &str)] = &[
    // PostgreSQL
    ("postgres", "postgres"),
    ("postgresql", "postgres"),
    ("pg", "postgres"),
    // Snowflake
    ("snowflake", "snowflake"),
    ("sf", "snowflake"),
    // SQL Server / T-SQL
    ("sqlserver", "sqlserver"),
    ("tsql", "sqlserver"),
    ("mssql", "sqlserver"),
    ("sql_server", "sqlserver"),
    // Databricks / Spark
    ("databricks", "databricks"),
    ("dbx", "databricks"),
    ("spark", "databricks"),
    // DuckDB
    ("duckdb", "duckdb"),
    ("duck", "duckdb"),
    // ClickHouse
    ("clickhouse", "clickhouse"),
    ("ch", "clickhouse"),
    // MariaDB / MySQL
    ("mariadb", "mariadb"),
    ("mariadb_columnstore", "mariadb"),
    ("mysql", "mysql"),
    // CitusDB
    ("citusdb", "citus"),
    ("citus", "citus"),
    // Agnostic (Razeri's universal cross-database dialect)
    ("agnostic", "agnostic"),
    // SQLite (extension dialect)
    ("sqlite", "sqlite"),
    // Google BigQuery
    ("bigquery", "bigquery"),
    ("big_query", "bigquery"),
    ("bq", "bigquery"),
    // Amazon Redshift
    ("redshift", "redshift"),
    ("amazon_redshift", "redshift"),
    ("rs", "redshift"),
];

/// Resolve a dialect by user-facing name string.
///
/// Performs case-insensitive matching with alias support. Falls back to the
/// [`PlatformRegistry`] for any name not in the alias table (e.g. third-party
/// extension plugins).
///
/// # Errors
///
/// Returns [`ResolveError::UnknownDialect`] with near-miss suggestions if the
/// name is not recognized.
///
/// # Examples
///
/// ```no_run
/// use razeri_plugin_api::ResolveError;
/// use razeri_plugin_api::resolve::resolve_dialect_by_name;
///
/// # fn main() -> Result<(), ResolveError> {
/// let dialect = resolve_dialect_by_name("pg")?;
/// println!("{}", dialect.info().name);
///
/// let dialect = resolve_dialect_by_name("SNOWFLAKE")?;
/// # Ok(())
/// # }
/// ```
pub fn resolve_dialect_by_name(name: &str) -> Result<Arc<dyn PlatformDialect>, ResolveError> {
    let registry = PlatformRegistry::with_auto_discovered();
    resolve_dialect_by_name_with_registry(name, &registry)
}

/// Resolve using an explicit registry (useful for testing and composition root).
///
/// # Errors
///
/// Returns an error if the operation fails.
pub fn resolve_dialect_by_name_with_registry(
    name: &str,
    registry: &PlatformRegistry,
) -> Result<Arc<dyn PlatformDialect>, ResolveError> {
    let normalized = name.trim().to_lowercase();

    // 1. Try alias table → canonical name → registry
    if let Some(canonical) = alias_lookup(&normalized)
        && let Some(dialect) = registry.get_by_name(canonical)
    {
        return Ok(Arc::clone(dialect));
    }

    // 2. Try direct registry lookup (covers third-party extensions not in alias table)
    if let Some(dialect) = registry.get_by_name(&normalized) {
        return Ok(Arc::clone(dialect));
    }

    // 3. Build error with suggestions
    let all_names = registered_names(registry);
    let suggestions = near_misses(&normalized, &all_names);
    Err(ResolveError::UnknownDialect { name: name.to_string(), suggestions, registered: all_names })
}

/// **The accepted spellings, as `(spelling, canonical name)` pairs.**
///
/// A design names its platform in whatever spelling its author reaches for, and
/// this is the table that turns one into the other. A platform whose own name
/// is missing from it is refused at the CLI door however well its dialect
/// renders.
#[must_use]
pub const fn alias_spellings() -> &'static [(&'static str, &'static str)] {
    ALIAS_TABLE
}

/// List all names accepted by the resolver (alias table + registered names).
#[must_use]
pub fn all_accepted_names() -> Vec<String> {
    let registry = PlatformRegistry::with_auto_discovered();
    let mut names: Vec<String> =
        ALIAS_TABLE.iter().map(|(alias, _)| (*alias).to_string()).collect();
    for info in registry.list() {
        let n = info.name.to_string();
        if !names.contains(&n) {
            names.push(n);
        }
    }
    names.sort();
    names.dedup();
    names
}

// ── Internal helpers ────────────────────────────────────────────────────

/// Look up an alias (already lowercased) in the alias table.
fn alias_lookup(normalized: &str) -> Option<&'static str> {
    ALIAS_TABLE.iter().find(|(alias, _)| *alias == normalized).map(|(_, canonical)| *canonical)
}

/// Collect all registered dialect names from the registry.
fn registered_names(registry: &PlatformRegistry) -> Vec<String> {
    let mut names: Vec<String> = registry.list().iter().map(|info| info.name.to_string()).collect();
    names.sort();
    names
}

/// Find near-miss suggestions using Levenshtein distance ≤ 3.
fn near_misses(input: &str, candidates: &[String]) -> Vec<String> {
    let mut scored: Vec<(&str, usize)> = candidates
        .iter()
        .filter_map(|c| {
            let dist = levenshtein(input, c);
            if dist <= 3 { Some((c.as_str(), dist)) } else { None }
        })
        .collect();
    scored.sort_by_key(|(_, d)| *d);
    scored.into_iter().map(|(name, _)| name.to_string()).collect()
}

/// Simple Levenshtein distance (no allocation beyond the DP row).
fn levenshtein(a: &str, b: &str) -> usize {
    let a_bytes = a.as_bytes();
    let b_bytes = b.as_bytes();
    let m = a_bytes.len();
    let n = b_bytes.len();

    let mut prev: Vec<usize> = (0..=n).collect();
    let mut curr = vec![0; n + 1];

    for i in 1..=m {
        curr[0] = i;
        for j in 1..=n {
            let cost = usize::from(a_bytes[i - 1] != b_bytes[j - 1]);
            curr[j] = (prev[j] + 1).min(curr[j - 1] + 1).min(prev[j - 1] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[n]
}

// ── Also include alias lookup in the ALIAS_TABLE entries ────────────────
/// All known aliases (for documentation and help messages).
#[must_use]
pub fn all_aliases() -> &'static [(&'static str, &'static str)] {
    ALIAS_TABLE
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dialect::{DialectInfo, PlatformDialect, PlatformRegistry};
    use razeri_plugin_contract::DataType;
    use razeri_plugin_contract::DialectFamily;
    use razeri_plugin_contract::{
        DdlRenderer, DialectCapabilities, DmlRenderer, ExpressionRenderer, FormulaRenderer,
        ProcedureRenderer, ReplicationRenderer, SqlRenderer, StorageRenderer, TaskRenderer,
    };

    /// Minimal test dialect.
    struct StubDialect {
        info: DialectInfo,
    }

    impl SqlRenderer for StubDialect {
        fn render_data_type(&self, _dt: &DataType) -> String {
            String::new()
        }
        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }
        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
            self.quote_identifier(name)
        }
        fn render_current_timestamp(&self) -> String {
            String::new()
        }
    }
    impl ExpressionRenderer for StubDialect {}
    impl DdlRenderer for StubDialect {}
    impl DmlRenderer for StubDialect {}
    impl ProcedureRenderer for StubDialect {}
    impl FormulaRenderer for StubDialect {}
    impl TaskRenderer for StubDialect {}
    impl DialectCapabilities for StubDialect {}
    impl ReplicationRenderer for StubDialect {}
    impl StorageRenderer for StubDialect {}
    impl PlatformDialect for StubDialect {
        fn info(&self) -> DialectInfo {
            self.info.clone()
        }
    }

    fn test_registry() -> PlatformRegistry {
        let mut reg = PlatformRegistry::new();
        let entries: &[(&str, &str, DialectFamily, &str, bool, bool, bool)] = &[
            ("postgres", "PostgreSQL", DialectFamily::PostgreSql, "PostgreSQL", false, false, true),
            ("snowflake", "Snowflake", DialectFamily::Snowflake, "Snowflake", true, true, false),
            ("sqlserver", "SQL Server", DialectFamily::TSql, "T-SQL", false, false, false),
            ("databricks", "Databricks", DialectFamily::SparkSql, "Spark SQL", true, true, false),
            (
                "clickhouse",
                "ClickHouse",
                DialectFamily::ClickHouse,
                "ClickHouse SQL",
                false,
                true,
                false,
            ),
            ("duckdb", "DuckDB", DialectFamily::PostgreSql, "PostgreSQL", false, true, true),
            ("citus", "Citus", DialectFamily::PostgreSql, "PostgreSQL", false, false, true),
            ("mariadb", "MariaDB", DialectFamily::MariaDB, "MariaDB", false, true, false),
            ("mysql", "MySQL", DialectFamily::MariaDB, "MariaDB", false, false, false),
            ("agnostic", "Agnostic", DialectFamily::Razeri, "ANSI", false, false, false),
            ("sqlite", "SQLite", DialectFamily::MariaDB, "SQLite", false, false, false),
        ];
        for &(name, display, family, fam_str, cloud, olap, pg_compat) in entries {
            reg.register(
                name.to_string(),
                Arc::new(StubDialect {
                    info: DialectInfo {
                        name,
                        display_name: display,
                        dialect_family: family,
                        family: fam_str,
                        is_cloud_native: cloud,
                        is_olap: olap,
                        is_postgres_compatible: pg_compat,
                    },
                }),
            );
        }
        reg
    }

    #[test]
    fn alias_lookup_finds_canonical_names() {
        assert_eq!(alias_lookup("pg"), Some("postgres"));
        assert_eq!(alias_lookup("postgresql"), Some("postgres"));
        assert_eq!(alias_lookup("tsql"), Some("sqlserver"));
        assert_eq!(alias_lookup("mssql"), Some("sqlserver"));
        assert_eq!(alias_lookup("sf"), Some("snowflake"));
        assert_eq!(alias_lookup("ch"), Some("clickhouse"));
        assert_eq!(alias_lookup("duck"), Some("duckdb"));
        assert_eq!(alias_lookup("dbx"), Some("databricks"));
        assert_eq!(alias_lookup("spark"), Some("databricks"));
        assert_eq!(alias_lookup("citusdb"), Some("citus"));
        assert_eq!(alias_lookup("sqlite"), Some("sqlite"));
        assert_eq!(alias_lookup("agnostic"), Some("agnostic"));
    }

    #[test]
    fn alias_lookup_with_unknown_returns_none() {
        assert_eq!(alias_lookup("nosuchdb"), None);
    }

    #[test]
    fn levenshtein_distance_basic() {
        assert_eq!(levenshtein("postgres", "postgres"), 0);
        assert_eq!(levenshtein("postgre", "postgres"), 1);
        assert_eq!(levenshtein("postgrse", "postgres"), 2);
        assert_eq!(levenshtein("", "abc"), 3);
    }

    #[test]
    fn resolve_with_canonical_name_succeeds() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("postgres", &reg).is_ok());
    }

    #[test]
    fn resolve_with_alias_succeeds() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("pg", &reg).is_ok());
    }

    #[test]
    fn resolve_is_case_insensitive() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("SNOWFLAKE", &reg).is_ok());
    }

    #[test]
    fn resolve_sqlite_extension_succeeds() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("sqlite", &reg).is_ok());
    }

    #[test]
    fn resolve_databricks_succeeds() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("databricks", &reg).is_ok());
    }

    #[test]
    fn resolve_mssql_alias_succeeds() {
        let reg = test_registry();
        assert!(resolve_dialect_by_name_with_registry("mssql", &reg).is_ok());
    }

    #[test]
    fn resolve_unknown_returns_error_with_suggestions() {
        let reg = test_registry();
        let result = resolve_dialect_by_name_with_registry("postres", &reg);
        let Err(err) = result else { panic!("expected error") };
        let msg = err.to_string();
        assert!(msg.contains("unknown dialect"), "error should mention unknown dialect: {msg}");
        assert!(msg.contains("postgres"), "error should suggest postgres: {msg}");
    }

    #[test]
    fn resolve_completely_unknown_returns_registered_list() {
        let reg = test_registry();
        let result = resolve_dialect_by_name_with_registry("zzzznotadb", &reg);
        let Err(err) = result else { panic!("expected error") };
        let msg = err.to_string();
        assert!(msg.contains("Registered:"), "error should list registered: {msg}");
    }

    #[test]
    fn all_accepted_names_includes_aliases_and_registered() {
        let names = all_accepted_names();
        assert!(names.contains(&"pg".to_string()));
        assert!(names.contains(&"postgres".to_string()));
        assert!(names.contains(&"snowflake".to_string()));
    }

    /// The published design schema's `DatabasePlatform` enum must speak the
    /// SAME vocabulary the resolver accepts.
    ///
    /// A design's `design.platforms` / `design.default_platform` strings are
    /// resolved — everywhere they are resolved at all — through
    /// [`resolve_dialect_by_name`], whose left-hand [`ALIAS_TABLE`] column is
    /// the operative accepted set. When the schema's enum is a *subset* of it,
    /// designs that parse and render cleanly fail their own published schema;
    /// when it is a *superset*, the schema advertises a spelling the resolver
    /// refuses. Set equality is the only honest relation, so this test pins it
    /// in the crate that owns the table — the schema cannot drift away from
    /// the resolver, and the resolver cannot grow a spelling the schema never
    /// learned.
    ///
    /// It is *set* equality, not ordered equality, because [`ALIAS_TABLE`]'s
    /// own contract says its order does not matter — an alias moved between
    /// two families is not a drift, and a test that failed on it would be
    /// lying.
    #[test]
    fn design_schema_platform_enum_matches_the_alias_table() {
        let schema_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../schemas/razeri-design.schema.json");
        let text = std::fs::read_to_string(&schema_path)
            .unwrap_or_else(|e| panic!("read {}: {e}", schema_path.display()));
        let schema: serde_json::Value =
            serde_json::from_str(&text).unwrap_or_else(|e| panic!("parse the design schema: {e}"));

        let enum_values = schema["$defs"]["DatabasePlatform"]["enum"]
            .as_array()
            .expect("$defs.DatabasePlatform.enum is an array in the published design schema");
        let mut published: Vec<String> = enum_values
            .iter()
            .map(|v| v.as_str().expect("every DatabasePlatform enum value is a string").to_string())
            .collect();
        published.sort();
        published.dedup();

        let mut accepted: Vec<String> =
            ALIAS_TABLE.iter().map(|(alias, _)| (*alias).to_string()).collect();
        accepted.sort();
        accepted.dedup();

        let advertised_but_refused: Vec<&String> =
            published.iter().filter(|n| !accepted.contains(n)).collect();
        let accepted_but_unpublished: Vec<&String> =
            accepted.iter().filter(|n| !published.contains(n)).collect();

        assert!(
            advertised_but_refused.is_empty() && accepted_but_unpublished.is_empty(),
            "schemas/razeri-design.schema.json $defs.DatabasePlatform has drifted from the \
             canonical resolver's ALIAS_TABLE.\n  advertised by the schema but REFUSED by the \
             resolver: {advertised_but_refused:?}\n  accepted by the resolver but MISSING from \
             the schema: {accepted_but_unpublished:?}\nThe alias table is the authority: add the \
             spelling to the schema's enum, or take it out of the alias table — do not let the \
             two vocabularies differ."
        );
    }
}