razeri-plugin-api 0.21.0

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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

//! Platform dialect trait and registry for database SQL rendering.
//!
//! [`PlatformDialect`] extends the rendering trait hierarchy from
//! `razeri-plugin-contract` with plugin metadata and registration support.
//! [`PlatformRegistry`] resolves dialects by canonical string name,
//! so built-in and third-party plugins are looked up the same way — there is no
//! closed platform enum, and an unknown name is an error, never a fallback.

use razeri_plugin_contract::DialectFamily;
use razeri_plugin_contract::EngineVersion;
use razeri_plugin_contract::{
    DdlRenderer, DialectCapabilities, DmlRenderer, ExpressionRenderer, FormulaRenderer,
    ProcedureRenderer, ReplicationRenderer, SqlRenderer, StorageRenderer, TaskRenderer,
};
use std::collections::HashMap;
use std::sync::Arc;

// Re-export rendering traits so dialect crates can import from one place.
pub use razeri_plugin_contract;

/// Metadata describing a dialect implementation.
///
/// Serializes to the discovery payload returned by `list_platforms()` across
/// every surface (and consumed by the typed-constants generator), so hosts learn
/// the registered platforms — including third-party plugins — at runtime instead
/// of hard-coding them.
#[derive(Debug, Clone, serde::Serialize)]
pub struct DialectInfo {
    /// Machine-readable name (e.g., "postgres", "redshift").
    pub name: &'static str,
    /// Human-readable display name (e.g., "`PostgreSQL`", "Amazon Redshift").
    pub display_name: &'static str,
    /// The other spellings this dialect answers to (e.g. `["pg", "postgresql"]`).
    ///
    /// A dialect owns its own names. [`name`](Self::name) always resolves; this
    /// is everything else a design or a `--target` may say for the same
    /// platform. Matching ignores case and surrounding whitespace, so
    /// `"PostgreSQL"` needs no separate entry. Declare `&[]` to answer to
    /// `name` alone.
    ///
    /// Two loaded dialects must not claim the same spelling: a spelling that
    /// names two platforms names neither, and resolving it is refused rather
    /// than guessed.
    pub aliases: &'static [&'static str],
    /// Dialect family for shared behavior (e.g., `PostgreSQL`, `TSql`).
    pub dialect_family: DialectFamily,
    /// SQL family label (e.g., "`PostgreSQL`", "T-SQL", "`ClickHouse` SQL").
    pub family: &'static str,
    /// Whether this is a cloud-native platform (e.g. Snowflake, Databricks).
    pub is_cloud_native: bool,
    /// Whether this is primarily an OLAP engine (e.g. `ClickHouse`).
    pub is_olap: bool,
    /// Whether this dialect is PostgreSQL-wire-compatible.
    pub is_postgres_compatible: bool,
    /// **The versions of the engine this dialect answers for**, the floor
    /// first, then each version above it at which an answer changes.
    ///
    /// The floor is the oldest version the dialect is supported at, and a
    /// platform named with no version (`postgres`) is the engine at its floor.
    /// A design opts into a newer server's forms by naming one of the others
    /// (`postgres@17`). Declare `&[]` for a managed service that chooses its
    /// own version, where a version named in a design is refused.
    ///
    /// Each version is one a dialect has been measured at. A dialect whose
    /// answers are the same at every version declares one: its floor.
    pub versions: &'static [EngineVersion],
    /// **Which client a bundle's deploy script drives for this engine**, or
    /// `None` where there is no script.
    ///
    /// A bundle carries one script, written for one client: `psql`, `mysql`,
    /// `sqlplus`. Razeri asks the dialect which one its engine speaks rather
    /// than recognising the engine by name, so an engine that speaks a client
    /// razeri already drives — a PostgreSQL-wire engine and `psql` — gets that
    /// script with no change to razeri. An engine whose client razeri does not
    /// drive describes it with [`DeployScript::Client`], and razeri writes a
    /// script around that description. `None` gets a script that refuses at
    /// the door and prints the run order by hand.
    pub deploy_script: Option<DeployScript>,
}

/// **The client a generated deploy script drives**: one of the clients razeri
/// writes a script for, or one the dialect describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DeployScript {
    /// `deploy.sh` driving the `duckdb` client.
    Duckdb,
    /// `deploy.sh` driving `sqlite3`.
    Sqlite3,
    /// `deploy.sh` driving `sqlplus`, local or in the engine's container.
    Sqlplus,
    /// `deploy.sh` driving `hdbsql`, local or in the engine's container.
    Hdbsql,
    /// `deploy.sh` driving `mysql` or `mariadb`, whichever the engine ships.
    Mysql,
    /// `deploy.sh` driving `psql`, local or in the engine's container.
    Psql,
    /// `deploy.ps1` driving `Invoke-Sqlcmd`.
    InvokeSqlcmd,
    /// `deploy.sh` driving a client razeri writes no script of its own for,
    /// run the way the dialect describes. See [`DeployClient`].
    Client(DeployClient),
}

/// **A client described by the dialect**, so razeri can write a deploy script
/// around it.
///
/// Razeri writes one `deploy.sh` for every such client. It runs the bundle's
/// files in order through the client — the prerequisites, the schema, the
/// staging fill, the loads — stops at the first file the engine refuses, and
/// then reads the reconciliation back and grades it. All it asks of the
/// dialect is how the client is called. Razeri has never run that script
/// against your engine, and the bundle says so: proving it is a run of your
/// own.
///
/// In each argument, `{file}` stands for the file being run and `{target}`
/// for the database the operator names, as the script's first argument or in
/// `RAZERI_TARGET`. The operator can point the script at another copy of the
/// client with `RAZERI_CLIENT`.
///
/// `SQLite`'s own client, described this way:
///
/// ```
/// use razeri_plugin_api::{DeployClient, DeployScript};
///
/// const SQLITE3: DeployScript = DeployScript::Client(DeployClient {
///     command: "sqlite3",
///     run_file: &["-bail", "{target}", ".read {file}"],
///     read_rows: Some(&["-csv", "-noheader", "{target}", ".read {file}"]),
///     block_terminator: None,
/// });
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct DeployClient {
    /// The client's command, as an operator has it on `PATH`.
    pub command: &'static str,
    /// The arguments that run one file of SQL and **stop at the first
    /// statement the engine refuses, exiting non-zero**.
    ///
    /// The script reads nothing but the client's exit code, so a client that
    /// carries on past a refusal, or exits zero after one, deploys part of a
    /// warehouse and reports it done. Name the option that makes yours stop;
    /// `sqlite3` calls it `-bail`.
    pub run_file: &'static [&'static str],
    /// The arguments that run one query file and print its rows as
    /// comma-separated values, one row per line, with no header: how the
    /// script reads the reconciliation back to grade it.
    ///
    /// `None` where the client cannot. The script then stops after the loads,
    /// exits with the code for *nothing was compared*, and says the
    /// reconciliation is the operator's to run.
    pub read_rows: Option<&'static [&'static str]>,
    /// **How this client is told where a routine ends**, or `None` where a
    /// routine ends the way every statement does.
    ///
    /// A routine's body holds statements of its own, each ending in `;`, and
    /// some clients end the routine at the first of them: Firebird's `isql`
    /// needs `SET TERM ^ ;` before a routine, the routine ended with `^`, and
    /// `SET TERM ; ^` after it. Razeri writes these three around each
    /// procedure and function in the files the script runs.
    pub block_terminator: Option<BlockTerminator>,
}

/// **The three lines a client needs around a routine**, so the `;` inside its
/// body does not end it. See [`DeployClient::block_terminator`].
///
/// Firebird's `isql`, described this way:
///
/// ```
/// use razeri_plugin_api::BlockTerminator;
///
/// const SET_TERM: BlockTerminator =
///     BlockTerminator { open: "SET TERM ^ ;", end: "^", close: "SET TERM ; ^" };
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub struct BlockTerminator {
    /// The line written before the routine.
    pub open: &'static str,
    /// What ends the routine, in place of its last `;`.
    pub end: &'static str,
    /// The line written after the routine, which puts the ordinary end back.
    pub close: &'static str,
}

/// Full plugin trait for database platform dialects.
///
/// Extends the rendering trait hierarchy (`SqlRenderer`, `ExpressionRenderer`,
/// `DdlRenderer`, `DmlRenderer`, `ProcedureRenderer`, `FormulaRenderer`,
/// `TaskRenderer`, `ReplicationRenderer`, `StorageRenderer`, `DialectCapabilities`)
/// with plugin-specific metadata and registration support.
///
/// Dialect authors implement the rendering traits plus `PlatformDialect::info()`.
pub trait PlatformDialect:
    SqlRenderer
    + ExpressionRenderer
    + DdlRenderer
    + DmlRenderer
    + ProcedureRenderer
    + FormulaRenderer
    + TaskRenderer
    + DialectCapabilities
    + ReplicationRenderer
    + StorageRenderer
    + DialectHandle
{
    /// Returns metadata about this dialect.
    fn info(&self) -> DialectInfo;

    /// **This dialect, answering for `version`.**
    ///
    /// `version` is one of [`DialectInfo::versions`]; the resolver calls this
    /// after matching the version a design names against that list, so a
    /// version the dialect does not declare never reaches it. A dialect whose
    /// answers change between its versions returns an instance that answers
    /// for `version`, and says so from [`Self::engine_version`].
    ///
    /// The default is a dialect with one answer: it returns itself for a
    /// version it declares, and refuses any other.
    ///
    /// # Errors
    ///
    /// [`UnsupportedVersion`], naming the versions this dialect answers for.
    fn at_version(
        self: Arc<Self>,
        version: &EngineVersion,
    ) -> Result<Arc<dyn PlatformDialect>, UnsupportedVersion> {
        if self.engine_version().as_ref() == Some(version) {
            return Ok(self.into_dialect());
        }
        Err(UnsupportedVersion::of(&self.info(), &version.to_string()))
    }

    /// **The version this dialect answers for**, or `None` for a managed
    /// service that chooses its own.
    ///
    /// The default is the floor, the first of [`DialectInfo::versions`]: right
    /// for a dialect with one answer. A dialect that overrides
    /// [`Self::at_version`] overrides this too.
    fn engine_version(&self) -> Option<EngineVersion> {
        self.info().versions.first().copied()
    }
}

/// **A dialect as a shared handle**, so [`PlatformDialect::at_version`] can
/// hand back the dialect it was called on.
///
/// Every dialect has it, through the implementation below; there is nothing
/// to write.
pub trait DialectHandle {
    /// This dialect, as the shared handle the registry holds.
    fn into_dialect(self: Arc<Self>) -> Arc<dyn PlatformDialect>;
}

impl<T: PlatformDialect + 'static> DialectHandle for T {
    fn into_dialect(self: Arc<Self>) -> Arc<dyn PlatformDialect> {
        self
    }
}

/// **A version this dialect does not answer for**, with the ones it does.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{}", self.sentence())]
pub struct UnsupportedVersion {
    /// The engine's name, as a design writes it (`postgres`).
    pub engine: String,
    /// The engine's name as its vendor writes it (`PostgreSQL`).
    pub display_name: String,
    /// The version that was asked for, as it was written.
    pub asked: String,
    /// The versions the dialect answers for, the floor first.
    pub answers_for: Vec<EngineVersion>,
}

impl UnsupportedVersion {
    /// The refusal of `asked`, for the dialect `info` describes.
    #[must_use]
    pub fn of(info: &DialectInfo, asked: &str) -> Self {
        Self {
            engine: info.name.to_owned(),
            display_name: info.display_name.to_owned(),
            asked: asked.to_owned(),
            answers_for: info.versions.to_vec(),
        }
    }

    /// The refusal, in one sentence that names the versions to write instead.
    #[must_use]
    pub fn sentence(&self) -> String {
        let Self { engine, display_name, asked, answers_for } = self;
        let Some(floor) = answers_for.first() else {
            return format!(
                "razeri renders {display_name} for no version a design names, and not at \
                 {asked}: write `{engine}`"
            );
        };
        let versions: Vec<String> = answers_for.iter().map(ToString::to_string).collect();
        let names: Vec<String> = versions.iter().map(|v| format!("`{engine}@{v}`")).collect();
        if versions.len() == 1 {
            return format!(
                "razeri renders {display_name} at {floor} alone, and not at {asked}: write \
                 `{engine}`"
            );
        }
        format!(
            "razeri renders {display_name} at {}, and not at {asked}: write {}, or `{engine}` \
             for {floor}, the oldest",
            in_words(&versions, "and"),
            in_words(&names, "or"),
        )
    }
}

/// `15, 16 and 17`: a list in a sentence.
fn in_words(items: &[String], last: &str) -> String {
    match items {
        [] => String::new(),
        [only] => only.clone(),
        [rest @ .., tail] => format!("{} {last} {tail}", rest.join(", ")),
    }
}

impl DialectInfo {
    /// Every spelling this dialect answers to: its own name, then its aliases.
    ///
    /// This is what the resolver reads, so it is also the honest answer to
    /// "what may a design call this platform?". An alias repeating the name is
    /// listed once.
    #[must_use]
    pub fn spellings(&self) -> Vec<&'static str> {
        let mut out = Vec::with_capacity(self.aliases.len() + 1);
        out.push(self.name);
        for alias in self.aliases {
            if !out.contains(alias) {
                out.push(alias);
            }
        }
        out
    }

    /// Whether this dialect answers to `spelling`, ignoring case and
    /// surrounding whitespace.
    #[must_use]
    pub fn answers_to(&self, spelling: &str) -> bool {
        let wanted = spelling.trim();
        self.spellings().iter().any(|known| known.eq_ignore_ascii_case(wanted))
    }
}

/// String-keyed registry for platform dialects.
///
/// All dialects are indexed by their canonical string name
/// (e.g. `"postgres"`, `"snowflake"`, `"mysql"`).
pub struct PlatformRegistry {
    dialects: HashMap<String, Arc<dyn PlatformDialect>>,
}

impl PlatformRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self { dialects: HashMap::new() }
    }

    /// Register a dialect by its canonical string name.
    pub fn register(&mut self, name: String, dialect: Arc<dyn PlatformDialect>) {
        self.dialects.insert(name, dialect);
    }

    /// Resolve by string name (canonical path for all dialects).
    #[must_use]
    pub fn get_by_name(&self, name: &str) -> Option<&Arc<dyn PlatformDialect>> {
        self.dialects.get(name)
    }

    /// Resolve by string — same as [`get_by_name`](Self::get_by_name).
    #[must_use]
    pub fn resolve(&self, target: &str) -> Option<Arc<dyn PlatformDialect>> {
        self.dialects.get(target).cloned()
    }

    /// List all registered dialects.
    #[must_use]
    pub fn list(&self) -> Vec<DialectInfo> {
        self.dialects.values().map(|d| d.info()).collect()
    }

    /// Sorted machine-readable names of every registered dialect.
    ///
    /// The stable, ordered form of [`list`](Self::list); the
    /// [`resolve`](crate::resolve) module uses it for error messages and the
    /// typed-constants generator reads it for deterministic output.
    #[must_use]
    pub fn registered_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.dialects.keys().cloned().collect();
        names.sort();
        names
    }

    /// Build a registry pre-populated with all auto-discovered dialect crates.
    ///
    /// Uses `inventory` to find every [`crate::builder::DialectRegistration`]
    /// submitted at link time.
    #[must_use]
    pub fn with_auto_discovered() -> Self {
        use crate::builder::DialectRegistration;
        let mut registry = Self::new();
        for reg in inventory::iter::<DialectRegistration> {
            let dialect = (reg.factory)();
            let name = dialect.info().name.to_string();
            registry.register(name, dialect);
        }
        // Plugin crates linked into this binary with `export_plugin!`
        // register through a builder; the dialects are what is kept here.
        for reg in inventory::iter::<crate::builder::PluginRegistration> {
            let mut linked = crate::builder::PluginRegistryBuilder::new();
            (reg.register)(&mut linked);
            for (name, dialect) in linked.build().dialects.dialects {
                registry.register(name, dialect);
            }
        }
        registry
    }
}

impl Default for PlatformRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use razeri_plugin_contract::DataType;

    /// Test dialect for unit tests.
    struct TestDialect {
        info: DialectInfo,
    }

    impl TestDialect {
        fn postgres() -> Self {
            Self {
                info: DialectInfo {
                    name: "postgres",
                    display_name: "PostgreSQL",
                    aliases: &["postgresql", "pg"],
                    dialect_family: DialectFamily::PostgreSql,
                    family: "PostgreSQL",
                    is_cloud_native: false,
                    is_olap: false,
                    is_postgres_compatible: true,
                    versions: &[],
                    deploy_script: None,
                },
            }
        }

        fn redshift() -> Self {
            Self {
                info: DialectInfo {
                    name: "redshift",
                    display_name: "Amazon Redshift",
                    aliases: &["amazon_redshift", "rs"],
                    dialect_family: DialectFamily::PostgreSql,
                    family: "PostgreSQL",
                    is_cloud_native: true,
                    is_olap: true,
                    is_postgres_compatible: true,
                    versions: &[],
                    deploy_script: None,
                },
            }
        }

        fn snowflake() -> Self {
            Self {
                info: DialectInfo {
                    name: "snowflake",
                    display_name: "Snowflake",
                    aliases: &["sf"],
                    dialect_family: DialectFamily::Snowflake,
                    family: "Snowflake",
                    is_cloud_native: true,
                    is_olap: true,
                    is_postgres_compatible: false,
                    versions: &[],
                    deploy_script: None,
                },
            }
        }
    }

    impl SqlRenderer for TestDialect {
        fn render_data_type(&self, _dt: &DataType) -> String {
            "TEXT".to_string()
        }

        fn quote_identifier(&self, name: &str) -> String {
            format!("\"{name}\"")
        }

        fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
            match schema {
                Some(s) => format!("{}.{}", self.quote_identifier(s), self.quote_identifier(name)),
                None => self.quote_identifier(name),
            }
        }

        fn render_current_timestamp(&self) -> String {
            "CURRENT_TIMESTAMP".to_string()
        }
    }

    impl ExpressionRenderer for TestDialect {
        fn render_concat(&self, parts: &[String]) -> String {
            parts.join(" || ")
        }
    }

    impl DdlRenderer for TestDialect {}
    impl DmlRenderer for TestDialect {}
    impl ProcedureRenderer for TestDialect {}
    impl FormulaRenderer for TestDialect {}
    impl TaskRenderer for TestDialect {}
    impl ReplicationRenderer for TestDialect {}
    impl StorageRenderer for TestDialect {}

    impl DialectCapabilities for TestDialect {
        fn supports_identity(&self) -> bool {
            true
        }
        fn supports_sequences(&self) -> bool {
            true
        }
        fn supports_stored_procedures(&self) -> bool {
            true
        }
    }

    impl PlatformDialect for TestDialect {
        fn info(&self) -> DialectInfo {
            self.info.clone()
        }
    }

    const FLOOR_ONLY: &[EngineVersion] = &[EngineVersion::declared("15")];

    /// **A dialect with one answer is itself at its one version**, and the
    /// default refuses any other, naming the one it answers for.
    #[test]
    fn a_dialect_with_one_answer_is_itself_at_its_floor_and_refuses_another() {
        let dialect: Arc<dyn PlatformDialect> = Arc::new(TestDialect {
            info: DialectInfo { versions: FLOOR_ONLY, ..TestDialect::postgres().info() },
        });
        assert_eq!(dialect.engine_version(), Some(EngineVersion::declared("15")));
        let at_floor =
            Arc::clone(&dialect).at_version(&EngineVersion::declared("15")).expect("its floor");
        assert!(Arc::ptr_eq(&at_floor, &dialect), "a dialect with one answer returns itself");

        let Err(refused) = Arc::clone(&dialect).at_version(&EngineVersion::declared("17")) else {
            panic!("17 is not declared")
        };
        assert_eq!(refused.answers_for, vec![EngineVersion::declared("15")]);
        let said = refused.to_string();
        assert!(said.contains("PostgreSQL"), "{said}");
        assert!(said.contains("15"), "{said}");
        assert!(said.contains("`postgres`"), "names the spelling that works: {said}");
    }

    /// **A service that chooses its own version answers for none.**
    #[test]
    fn a_service_that_chooses_its_own_version_answers_for_none() {
        let dialect = TestDialect::snowflake();
        assert!(dialect.info().versions.is_empty());
        assert_eq!(dialect.engine_version(), None);
    }

    /// **The refusal lists every version, the floor first, and the names to
    /// write.**
    #[test]
    fn an_unsupported_version_names_every_version_and_how_to_write_each() {
        let refusal = UnsupportedVersion {
            engine: "postgres".to_owned(),
            display_name: "PostgreSQL".to_owned(),
            asked: "12".to_owned(),
            answers_for: ["15", "16", "17"].iter().map(|v| EngineVersion::declared(v)).collect(),
        };
        let said = refusal.to_string();
        assert!(said.contains("15, 16 and 17"), "{said}");
        assert!(said.contains("not at 12"), "{said}");
        assert!(said.contains("`postgres@17`"), "{said}");
        assert!(said.contains("`postgres` for 15"), "the name alone is the floor: {said}");
    }

    #[test]
    fn the_versions_ride_along_in_the_discovery_payload() {
        let info = DialectInfo { versions: FLOOR_ONLY, ..TestDialect::postgres().info() };
        let json = serde_json::to_value(&info).expect("DialectInfo serializes");
        assert_eq!(json["versions"], serde_json::json!(["15"]));
    }

    #[test]
    fn register_dialect_resolves_by_name() {
        let mut registry = PlatformRegistry::new();
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));
        assert!(registry.get_by_name("postgres").is_some());
    }

    #[test]
    fn register_extension_resolves_by_name() {
        let mut registry = PlatformRegistry::new();
        registry.register("redshift".to_string(), Arc::new(TestDialect::redshift()));
        assert!(registry.get_by_name("redshift").is_some());
    }

    #[test]
    fn resolve_tries_name_lookup() {
        let mut registry = PlatformRegistry::new();
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));
        registry.register("redshift".to_string(), Arc::new(TestDialect::redshift()));

        assert!(registry.resolve("postgres").is_some());
        assert!(registry.resolve("redshift").is_some());
        assert!(registry.resolve("nonexistent").is_none());
    }

    #[test]
    fn list_returns_all_registered_dialects() {
        let mut registry = PlatformRegistry::new();
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));
        registry.register("snowflake".to_string(), Arc::new(TestDialect::snowflake()));
        registry.register("redshift".to_string(), Arc::new(TestDialect::redshift()));

        let list = registry.list();
        assert_eq!(list.len(), 3);
    }

    #[test]
    fn duplicate_registration_overwrites() {
        let mut registry = PlatformRegistry::new();
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));

        assert!(registry.get_by_name("postgres").is_some());
        let list = registry.list();
        assert_eq!(list.len(), 1);
    }

    #[test]
    fn dialect_info_contains_expected_metadata() {
        let dialect = TestDialect::postgres();
        let info = dialect.info();
        assert_eq!(info.name, "postgres");
        assert_eq!(info.display_name, "PostgreSQL");
        assert_eq!(info.dialect_family, DialectFamily::PostgreSql);
    }

    #[test]
    fn classification_fields_reflect_dialect_characteristics() {
        let pg = TestDialect::postgres();
        let pg_info = pg.info();
        assert_eq!(pg_info.family, "PostgreSQL");
        assert!(pg_info.is_postgres_compatible);
        assert!(!pg_info.is_cloud_native);
        assert!(!pg_info.is_olap);

        let sf = TestDialect::snowflake();
        let sf_info = sf.info();
        assert_eq!(sf_info.family, "Snowflake");
        assert!(sf_info.is_cloud_native);
        assert!(sf_info.is_olap);
        assert!(!sf_info.is_postgres_compatible);

        let rd = TestDialect::redshift();
        let rd_info = rd.info();
        assert!(rd_info.is_cloud_native);
        assert!(rd_info.is_olap);
        assert!(rd_info.is_postgres_compatible);
    }

    #[test]
    fn empty_registry_returns_none() {
        let registry = PlatformRegistry::new();
        assert!(registry.get_by_name("postgres").is_none());
        assert!(registry.resolve("postgres").is_none());
        assert!(registry.list().is_empty());
    }

    // ── Discovery + canonical names ─────────────────────────────────────────

    #[test]
    fn registered_names_are_sorted() {
        let mut registry = PlatformRegistry::new();
        registry.register("snowflake".to_string(), Arc::new(TestDialect::snowflake()));
        registry.register("postgres".to_string(), Arc::new(TestDialect::postgres()));
        registry.register("redshift".to_string(), Arc::new(TestDialect::redshift()));
        assert_eq!(registry.registered_names(), vec!["postgres", "redshift", "snowflake"]);
    }

    #[test]
    fn dialect_info_serializes_for_discovery() {
        // The discovery payload (list_platforms) + the constants generator both
        // read serialized DialectInfo, so it must round-trip to JSON.
        let info = TestDialect::snowflake().info();
        let json = serde_json::to_value(&info).expect("DialectInfo serializes");
        assert_eq!(json["name"], "snowflake");
        assert_eq!(json["display_name"], "Snowflake");
        assert_eq!(json["dialect_family"], "snowflake");
        assert_eq!(json["is_cloud_native"], true);
        assert_eq!(json["is_postgres_compatible"], false);
        // The spellings ride along, so a host learns what a design may call
        // this platform from the same payload that lists it.
        assert_eq!(json["aliases"], serde_json::json!(["sf"]));
    }

    #[test]
    fn spellings_start_with_the_dialects_own_name() {
        let info = TestDialect::postgres().info();
        assert_eq!(info.spellings(), vec!["postgres", "postgresql", "pg"]);
    }

    #[test]
    fn a_dialect_answers_to_its_name_and_its_aliases_in_any_case() {
        let info = TestDialect::postgres().info();
        assert!(info.answers_to("postgres"));
        assert!(info.answers_to("pg"));
        assert!(info.answers_to("  PostgreSQL "));
        assert!(!info.answers_to("snowflake"));
    }

    #[test]
    fn an_alias_repeating_the_name_is_listed_once() {
        let info = DialectInfo { aliases: &["postgres", "pg"], ..TestDialect::postgres().info() };
        assert_eq!(info.spellings(), vec!["postgres", "pg"]);
    }
}