Skip to main content

razeri_plugin_api/
conformance.rs

1// Copyright (C) 2026 Gabriel Shea
2// Licensed under either of the Apache License, Version 2.0 or the MIT
3// license, at your option.
4
5//! **Every obligation a dialect owes, reported at once.**
6//!
7//! A dialect owes Razeri more than the methods its traits require: decisions
8//! whose default is another engine's answer, facts it declares twice that must
9//! agree, the wording of its refusals, the names it answers to. Met one at a
10//! time, each is a separate failing test, found only once it fires. This
11//! module is the report that answers all of them in one pass.
12//!
13//! # Running it
14//!
15//! From your own crate's tests, where your dialect is linked and Razeri's
16//! registry can see it:
17//!
18//! ```rust
19//! # use razeri_plugin_api::conformance;
20//! # fn example(my_dialect: &dyn razeri_plugin_api::PlatformDialect) {
21//! let report = conformance::check(my_dialect);
22//! assert!(report.is_clean(), "{report}");
23//! # }
24//! ```
25//!
26//! # What it can and cannot see
27//!
28//! Everything here is read off the dialect object, so it works wherever your
29//! plugin compiles: it grades what your dialect declares and what its
30//! renderers return. It runs no SQL, so anything only an engine can settle —
31//! whether the SQL your dialect emits is the SQL that engine accepts — stays
32//! yours to test against a real instance.
33//!
34//! # Your dialect's name
35//!
36//! Your platform's names are yours. `DialectInfo::name` is the one Razeri
37//! reports, `aliases` is every other spelling a design may use for it, and the
38//! resolver reads both off the dialects that are loaded — so the report asks
39//! only that your own spellings reach you, and there is no table inside Razeri
40//! for your platform to be missing from. The one thing it will tell you is that
41//! a spelling you declared is one another loaded platform also answers to,
42//! because then the spelling names neither of you.
43
44use crate::PlatformDialect;
45use razeri_plugin_contract::{
46    BitwiseOperator, CatalogueReach, ColumnEvolution, Concat, ConstraintEnforcement, DataType,
47    DdlRenderer, DialectCapabilities, DialectFamily, EntityRef, ExpressionRenderer,
48    FormulaRenderer, HeldAs, MergeRestrictions, MergeShape, ProcedureForm, RoutineKind,
49    RoutineSpec, ScalarFunctionForm, SliceRef, SliceReplacement, SqlRenderer, StorageRenderer,
50    TableFunctionForm, TableRole, UNKNOWN_PLATFORM, WrittenObject,
51    data_type::{ArrayDataType, MapDataType, StructDataType, StructField},
52    storage_strategy::{
53        CompressionStrategy, IndexStrategy, PartitionGranularity, PartitionStrategy, StoragePlan,
54    },
55};
56use std::fmt;
57use std::fmt::Write as _;
58
59/// How much a finding matters.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
61pub enum Severity {
62    /// **This dialect will produce SQL its engine rejects.** Fix it before
63    /// anything else.
64    Blocking,
65    /// **A question this dialect has not answered.** Razeri has a default and
66    /// will use it; the default was written for a different engine.
67    Unanswered,
68    /// Worth a look. Nothing is broken.
69    Note,
70}
71
72impl fmt::Display for Severity {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(match self {
75            Self::Blocking => "must fix",
76            Self::Unanswered => "unanswered",
77            Self::Note => "worth a look",
78        })
79    }
80}
81
82/// One thing to fix, in the order a reader wants it: what is wrong, then what
83/// to do about it.
84#[derive(Debug, Clone)]
85pub struct Finding {
86    /// How much it matters.
87    pub severity: Severity,
88    /// One line naming what is wrong.
89    pub what: String,
90    /// One line naming what to do.
91    pub fix: String,
92}
93
94/// The whole report for one dialect.
95#[derive(Debug, Clone)]
96pub struct Report {
97    /// The dialect's registry name.
98    pub dialect: String,
99    /// Everything found, worst first.
100    pub findings: Vec<Finding>,
101    /// **The answers that shape a statement this dialect left to the
102    /// contract**, in the order the bundle's files run — see
103    /// [`taken_as_default`].
104    pub taken_as_default: Vec<TakenAsDefault>,
105}
106
107/// **One answer a dialect left to the contract**: it answers as the
108/// contract's own method body does, so Razeri writes the default's SQL there.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct TakenAsDefault {
111    /// The trait and the method.
112    pub name: &'static str,
113    /// The file it shows up in.
114    pub shows_in: &'static str,
115    /// The contract's answer, which Razeri writes for this dialect.
116    pub answer: String,
117}
118
119impl Report {
120    /// Whether nothing blocking or unanswered was found.
121    ///
122    /// Notes do not fail a report: they are observations, not obligations.
123    #[must_use]
124    pub fn is_clean(&self) -> bool {
125        !self.findings.iter().any(|f| f.severity != Severity::Note)
126    }
127
128    /// How many findings of one severity.
129    #[must_use]
130    pub fn count(&self, severity: Severity) -> usize {
131        self.findings.iter().filter(|f| f.severity == severity).count()
132    }
133}
134
135impl Report {
136    /// **The report's opening and its findings**: what it read and what it
137    /// ran, then each finding, worst first.
138    ///
139    /// The `Display` of the report is this and then the answers left to the
140    /// contract; `razeri plugin conform` prints this and then the same answers
141    /// with how many of the engines Razeri ships write their own.
142    #[must_use]
143    pub fn head(&self) -> String {
144        let mut out = String::new();
145        let name = &self.dialect;
146        let blocking = self.count(Severity::Blocking);
147        let summary = if self.findings.is_empty() {
148            "nothing to fix".to_owned()
149        } else {
150            format!(
151                "{blocking} to fix, {} unanswered, {} worth a look",
152                self.count(Severity::Unanswered),
153                self.count(Severity::Note)
154            )
155        };
156        let _ = writeln!(out, "{name}: {summary}, in the answers this dialect states.");
157        let zero = if blocking == 0 {
158            let phrase = if self.findings.is_empty() { "nothing to fix" } else { "0 to fix" };
159            format!(" \"{phrase}\" means no question is open, not that the SQL runs.")
160        } else {
161            String::new()
162        };
163        let _ = writeln!(
164            out,
165            "This report read the dialect's answers and ran nothing on an engine.{zero} Only the \
166             SQL Razeri renders for it, run on your engine, shows that it runs."
167        );
168        for finding in &self.findings {
169            let _ = writeln!(out);
170            let _ = writeln!(out, "  [{}] {}", finding.severity, finding.what);
171            let _ = writeln!(out, "      → {}", finding.fix);
172        }
173        out
174    }
175}
176
177impl fmt::Display for Report {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        f.write_str(&self.head())?;
180        writeln!(f)?;
181        if self.taken_as_default.is_empty() {
182            return writeln!(
183                f,
184                "This dialect answers every question Razeri asks here about the shape of a \
185                 statement differently from the contract's default."
186            );
187        }
188        let count = self.taken_as_default.len();
189        writeln!(
190            f,
191            "Taken as the contract's default: this dialect answers {count} {} as the contract's \
192             default does, so Razeri writes the default's SQL, shown beside each. Confirm each \
193             on your engine.",
194            if count == 1 { "question" } else { "questions" }
195        )?;
196        for taken in &self.taken_as_default {
197            writeln!(f)?;
198            writeln!(f, "  {} → {}", taken.name, taken.answer)?;
199            writeln!(f, "      in {}", taken.shows_in)?;
200        }
201        Ok(())
202    }
203}
204
205/// **The four traits a statement's shape is asked of**, so one answer can be
206/// read off a dialect and off the contract's own defaults alike.
207#[derive(Clone, Copy)]
208enum Asked {
209    Sql(fn(&dyn SqlRenderer) -> String),
210    Expression(fn(&dyn ExpressionRenderer) -> String),
211    Ddl(fn(&dyn DdlRenderer) -> String),
212    Capabilities(fn(&dyn DialectCapabilities) -> String),
213}
214
215/// One answer a dialect gives that decides the shape of a statement Razeri
216/// writes, and the file of a bundle it shows up in.
217#[derive(Clone, Copy)]
218struct Seam {
219    name: &'static str,
220    shows_in: &'static str,
221    asked: Asked,
222}
223
224impl Seam {
225    /// The dialect's answer, as text two answers are compared by.
226    fn answer_of(&self, dialect: &dyn PlatformDialect) -> String {
227        match self.asked {
228            Asked::Sql(answer) => answer(dialect),
229            Asked::Expression(answer) => answer(dialect),
230            Asked::Ddl(answer) => answer(dialect),
231            Asked::Capabilities(answer) => answer(dialect),
232        }
233    }
234
235    /// The contract's own answer, spelled with the dialect's quoting.
236    fn default_of(&self, defaults: &ContractDefaults<'_>) -> String {
237        match self.asked {
238            Asked::Sql(answer) => answer(defaults),
239            Asked::Expression(answer) => answer(defaults),
240            Asked::Ddl(answer) => answer(defaults),
241            Asked::Capabilities(answer) => answer(defaults),
242        }
243    }
244}
245
246/// **Every answer that shapes a statement Razeri writes into a bundle**, in
247/// the order the bundle's files run.
248///
249/// Each is read by the render, so an answer written here changes what the
250/// engine is given; and each is a statement an engine has refused when a
251/// dialect left it to the contract. Answers this report grades elsewhere
252/// (the routine forms, the key, the merge) are not repeated.
253fn statement_seams() -> &'static [Seam] {
254    SEAMS
255}
256
257const SCHEMA: &str = "schema.sql";
258const LOADS: &str = "loads.sql";
259const RECONCILE: &str = "reconcile.sql";
260const EVERY: &str = "every file";
261const fn seam(name: &'static str, shows_in: &'static str, asked: Asked) -> Seam {
262    Seam { name, shows_in, asked }
263}
264const SEAMS: &[Seam] = &[
265    seam(
266        "DdlRenderer::supports_if_not_exists",
267        SCHEMA,
268        Asked::Ddl(|d| said(d.supports_if_not_exists())),
269    ),
270    seam(
271        "DdlRenderer::supports_primary_key_constraint",
272        SCHEMA,
273        Asked::Ddl(|d| said(d.supports_primary_key_constraint())),
274    ),
275    seam(
276        "DdlRenderer::supports_foreign_key_constraint",
277        SCHEMA,
278        Asked::Ddl(|d| said(d.supports_foreign_key_constraint())),
279    ),
280    seam(
281        "DdlRenderer::render_create_view_prefix",
282        SCHEMA,
283        Asked::Ddl(|d| quoted(d.render_create_view_prefix())),
284    ),
285    seam(
286        "DdlRenderer::replaces_a_view_that_is_read",
287        SCHEMA,
288        Asked::Ddl(|d| said(d.replaces_a_view_that_is_read())),
289    ),
290    seam(
291        "DdlRenderer::render_drop_view_prefix",
292        SCHEMA,
293        Asked::Ddl(|d| quoted(&d.render_drop_view_prefix(true))),
294    ),
295    seam(
296        "DdlRenderer::render_drop_table_prefix",
297        SCHEMA,
298        Asked::Ddl(|d| quoted(&d.render_drop_table_prefix(true))),
299    ),
300    seam(
301        "DdlRenderer::render_drop_function",
302        SCHEMA,
303        Asked::Ddl(|d| quoted(&d.render_drop_function("f", &["BIGINT"], true))),
304    ),
305    seam(
306        "DdlRenderer::supports_drop_function_arg_types",
307        SCHEMA,
308        Asked::Ddl(|d| said(d.supports_drop_function_arg_types())),
309    ),
310    seam(
311        "DdlRenderer::render_create_schema_statement",
312        SCHEMA,
313        Asked::Ddl(|d| quoted(&d.render_create_schema_statement("s", true))),
314    ),
315    seam(
316        "DialectCapabilities::supports_schemas",
317        SCHEMA,
318        Asked::Capabilities(|d| said(d.supports_schemas())),
319    ),
320    seam(
321        "SqlRenderer::uses_schema_in_qualified_names",
322        SCHEMA,
323        Asked::Sql(|d| said(d.uses_schema_in_qualified_names())),
324    ),
325    seam(
326        "DdlRenderer::supports_ddl_transactions",
327        SCHEMA,
328        Asked::Ddl(|d| said(d.supports_ddl_transactions())),
329    ),
330    seam(
331        "DdlRenderer::render_begin_transaction",
332        SCHEMA,
333        Asked::Ddl(|d| quoted(d.render_begin_transaction())),
334    ),
335    seam("DdlRenderer::render_commit", SCHEMA, Asked::Ddl(|d| quoted(d.render_commit()))),
336    seam(
337        "SqlRenderer::scalar_function_body_is_expression",
338        SCHEMA,
339        Asked::Sql(|d| said(d.scalar_function_body_is_expression())),
340    ),
341    seam(
342        "DialectCapabilities::max_identifier_length",
343        EVERY,
344        Asked::Capabilities(|d| said(d.max_identifier_length())),
345    ),
346    seam(
347        "DialectCapabilities::begin_transaction_keyword",
348        LOADS,
349        Asked::Capabilities(|d| quoted(d.begin_transaction_keyword())),
350    ),
351    seam(
352        "SqlRenderer::merge_source_requires_inlined_ctes",
353        LOADS,
354        Asked::Sql(|d| said(d.merge_source_requires_inlined_ctes())),
355    ),
356    seam(
357        "SqlRenderer::insert_accepts_leading_ctes",
358        LOADS,
359        Asked::Sql(|d| said(d.insert_accepts_leading_ctes())),
360    ),
361    seam(
362        "SqlRenderer::is_reserved_word",
363        LOADS,
364        Asked::Sql(|d| {
365            if d.is_reserved_word("matched") {
366                "`matched` is reserved: a load writes it quoted".to_owned()
367            } else {
368                "`matched` is free: a load writes `1 AS matched`".to_owned()
369            }
370        }),
371    ),
372    seam(
373        "SqlRenderer::render_empty_table",
374        LOADS,
375        Asked::Sql(|d| quoted(&d.render_empty_table("t"))),
376    ),
377    seam(
378        "SqlRenderer::render_procedure_variable_reference",
379        LOADS,
380        Asked::Sql(|d| quoted(&d.render_procedure_variable_reference("v"))),
381    ),
382    seam(
383        "ExpressionRenderer::render_concat",
384        LOADS,
385        Asked::Expression(|d| quoted(&d.render_concat(&["a".into(), "b".into()]))),
386    ),
387    seam(
388        "SqlRenderer::statement_separator",
389        LOADS,
390        Asked::Sql(|d| quoted(d.statement_separator())),
391    ),
392    seam(
393        "SqlRenderer::render_one_row_source",
394        RECONCILE,
395        Asked::Sql(|d| match d.render_one_row_source() {
396            Some(source) => quoted(&source),
397            None => "none: a `SELECT` with no `FROM`".to_owned(),
398        }),
399    ),
400];
401
402/// A yes, a no or a number, as the report prints it.
403fn said(answer: impl fmt::Display) -> String {
404    format!("`{answer}`")
405}
406
407/// A piece of SQL, as the report prints it, its line breaks shown.
408fn quoted(sql: &str) -> String {
409    format!("`{}`", sql.replace('\n', "\\n"))
410}
411
412/// **The answers `dialect` left to the contract**, in the order the bundle's
413/// files run.
414///
415/// A dialect "takes the default" when its answer is the one the contract's
416/// own method body gives. That is read by asking both: the dialect, and a
417/// stand-in that writes only what the contract requires — the column types,
418/// the quoting, the qualified name and the current timestamp, borrowed from
419/// the dialect — and answers every other question with the contract's
420/// default. A dialect that wrote the default's answer out by hand reads the
421/// same, and is listed to confirm, not as wrong.
422#[must_use]
423pub fn taken_as_default(dialect: &dyn PlatformDialect) -> Vec<TakenAsDefault> {
424    let defaults = ContractDefaults { graded: dialect };
425    statement_seams()
426        .iter()
427        .filter_map(|seam| {
428            let default = seam.default_of(&defaults);
429            (seam.answer_of(dialect) == default).then_some(TakenAsDefault {
430                name: seam.name,
431                shows_in: seam.shows_in,
432                answer: default,
433            })
434        })
435        .collect()
436}
437
438/// A dialect that writes only what the contract requires, and borrows those
439/// four answers from the dialect being graded: every other answer is the
440/// contract's own default, spelled with the graded dialect's quoting.
441struct ContractDefaults<'a> {
442    graded: &'a dyn PlatformDialect,
443}
444
445impl SqlRenderer for ContractDefaults<'_> {
446    fn render_data_type(&self, dt: &DataType) -> String {
447        self.graded.render_data_type(dt)
448    }
449
450    fn quote_identifier(&self, name: &str) -> String {
451        self.graded.quote_identifier(name)
452    }
453
454    fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
455        self.graded.qualify_name(schema, name)
456    }
457
458    fn render_current_timestamp(&self) -> String {
459        self.graded.render_current_timestamp()
460    }
461}
462impl ExpressionRenderer for ContractDefaults<'_> {}
463impl DdlRenderer for ContractDefaults<'_> {}
464impl DialectCapabilities for ContractDefaults<'_> {}
465
466/// **The report.** Everything about this dialect that Razeri can check by
467/// asking it.
468///
469/// Registration is checked against the dialects linked into this program. A
470/// dialect the host loaded at run time is not among them, so report it with
471/// [`check_with_registry`] and the registry it was loaded into.
472#[must_use]
473pub fn check(dialect: &dyn PlatformDialect) -> Report {
474    check_with_registry(dialect, &crate::dialect::PlatformRegistry::with_auto_discovered())
475}
476
477/// The same report, against a registry the host built — the path for a dialect
478/// loaded at run time rather than linked in.
479#[must_use]
480pub fn check_with_registry(
481    dialect: &dyn PlatformDialect,
482    registry: &crate::dialect::PlatformRegistry,
483) -> Report {
484    let info = dialect.info();
485    let mut findings = Vec::new();
486
487    check_registration(&info, registry, &mut findings);
488    check_family(info.dialect_family, &mut findings);
489    check_required_rendering(dialect, &mut findings);
490    check_decisions(dialect, &mut findings);
491    check_formula_renderer(dialect, &mut findings);
492    check_evolution(dialect, &mut findings);
493    check_run_again(dialect, &mut findings);
494    check_transactions(dialect, &mut findings);
495    check_paired_facts(dialect, &mut findings);
496    check_schema_fold(dialect, &mut findings);
497    check_deploy_client(&info, &mut findings);
498
499    findings.sort_by_key(|f| f.severity);
500    Report { dialect: info.name.to_owned(), findings, taken_as_default: taken_as_default(dialect) }
501}
502
503/// Every spelling this dialect answers to has to reach this dialect: its own
504/// name, and each alias it declares.
505///
506/// That is the whole obligation, and it is one the author can meet from their
507/// own crate — the spellings are the dialect's own, so there is no list inside
508/// Razeri to be missing from and nothing here can ask for a change only Razeri
509/// could make. What is worth saying is a spelling that reaches somewhere else:
510/// one another loaded platform also claims (so it names neither, and Razeri
511/// refuses it), or one that reaches a different platform because the registry
512/// holds this dialect under another key.
513fn check_registration(
514    info: &crate::dialect::DialectInfo,
515    registry: &crate::dialect::PlatformRegistry,
516    findings: &mut Vec<Finding>,
517) {
518    let name = info.name;
519    if matches!(
520        crate::resolve::resolve_dialect_by_name_with_registry(name, registry),
521        Err(crate::ResolveError::UnknownDialect { .. })
522    ) {
523        findings.push(Finding {
524            severity: Severity::Blocking,
525            what: format!(
526                "the name `{name}` does not resolve — nothing in this program registered it"
527            ),
528            fix: "add `razeri_plugin_api::export_plugin!(register);` at the top of your \
529                  crate's `lib.rs`, where `register` calls \
530                  `builder.register_dialect(Arc::new(MyDialect))`. The one line makes the \
531                  dialect one the registry finds, whether razeri loads your library from a \
532                  plugin directory or links your crate in."
533                .to_owned(),
534        });
535        return;
536    }
537    for spelling in info.spellings() {
538        match crate::resolve::resolve_dialect_by_name_with_registry(spelling, registry) {
539            Ok(found) if found.info().name == name => {}
540            Ok(found) => findings.push(Finding {
541                severity: Severity::Blocking,
542                what: format!("`{spelling}` reaches `{}` rather than `{name}`", found.info().name),
543                fix: format!(
544                    "the registry holds `{name}` under another key. Register it under its own \
545                     name, or drop `{spelling}` from its aliases."
546                ),
547            }),
548            Err(crate::ResolveError::AmbiguousName { claimed_by, .. }) => findings.push(Finding {
549                severity: Severity::Blocking,
550                what: format!(
551                    "`{spelling}` is claimed by more than one loaded platform ({}), so it names \
552                     none of them — Razeri refuses that spelling rather than guessing which one \
553                     a design meant",
554                    claimed_by.join(" and ")
555                ),
556                fix: format!(
557                    "give this dialect a name no other platform answers to. A platform name is \
558                     read off the loaded dialects' own declared spellings, so a spelling another \
559                     platform already claims is never `{name}`'s."
560                ),
561            }),
562            Err(_) => findings.push(Finding {
563                severity: Severity::Blocking,
564                what: format!(
565                    "`{spelling}` is declared as a spelling of `{name}` but reaches no platform"
566                ),
567                fix: format!(
568                    "the `{name}` in the registry is a different build of this dialect and does \
569                     not declare `{spelling}`. Register the one you are grading."
570                ),
571            }),
572        }
573    }
574}
575
576/// A family is a claim about spelling, so an unmeasured engine claiming a
577/// measured family's name licenses SQL it may reject.
578fn check_family(family: DialectFamily, findings: &mut Vec<Finding>) {
579    if matches!(family, DialectFamily::Custom(name) if name.trim().is_empty()) {
580        findings.push(Finding {
581            severity: Severity::Blocking,
582            what: "this dialect's family is a custom one with no name".to_owned(),
583            fix: "give `DialectFamily::Custom` your engine's own name — it is what a report \
584                  prints and what a reader looks up."
585                .to_owned(),
586        });
587    }
588}
589
590/// The four required methods must answer for every type a design can declare.
591fn check_required_rendering(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
592    let declarable = declarable_types();
593    let empty_column: Vec<String> = declarable
594        .iter()
595        .filter(|dt| SqlRenderer::render_data_type(dialect, dt).trim().is_empty())
596        .map(|dt| format!("{dt:?}"))
597        .collect();
598    if !empty_column.is_empty() {
599        findings.push(Finding {
600            severity: Severity::Blocking,
601            what: format!(
602                "`render_data_type` answers nothing for {} of the types a design can declare",
603                empty_column.len()
604            ),
605            fix: "every declarable type needs a column spelling on this engine, even if the \
606                  spelling is a wider type that stores it. A blank answer becomes a column \
607                  declaration with no type in it."
608                .to_owned(),
609        });
610    }
611    let empty_cast: Vec<String> = declarable
612        .iter()
613        .filter(|dt| SqlRenderer::render_cast_type(dialect, dt).trim().is_empty())
614        .map(|dt| format!("{dt:?}"))
615        .collect();
616    if !empty_cast.is_empty() {
617        findings.push(Finding {
618            severity: Severity::Blocking,
619            what: format!(
620                "`render_cast_type` answers nothing for {} declarable types",
621                empty_cast.len()
622            ),
623            fix: "the generated load opens by casting every source column to its declared type, \
624                  so a blank answer fails the load on its first statement."
625                .to_owned(),
626        });
627    }
628    let quoted = SqlRenderer::quote_identifier(dialect, "order");
629    if quoted == "order" {
630        findings.push(Finding {
631            severity: Severity::Blocking,
632            what: "`quote_identifier` returns the identifier unchanged, so a reserved word \
633                   reaches this engine bare"
634                .to_owned(),
635            fix: "wrap the identifier in whatever this engine quotes with — double quotes, \
636                  backticks, or brackets."
637                .to_owned(),
638        });
639    }
640    if SqlRenderer::render_current_timestamp(dialect).trim().is_empty() {
641        findings.push(Finding {
642            severity: Severity::Blocking,
643            what: "`render_current_timestamp` answers nothing, and every generated load stamps \
644                   a row with it"
645                .to_owned(),
646            fix: "return this engine's own expression for the current moment.".to_owned(),
647        });
648    }
649}
650
651/// **Reading a file in a named encoding**, where the dialect states a way to.
652///
653/// The same path question [`check_decisions`] asks of the plain relation, for
654/// the same reason, plus one only this method can get wrong: an engine that
655/// reads no file at all cannot read one in a named encoding, and a dialect that
656/// answers here and not there states a relation nothing will ever ask it for.
657///
658/// Parameters:
659/// - `dialect`: the plugin under test.
660/// - `probe`: the same quoted path literal the plain relation was asked about.
661/// - `findings`: where anything wrong is recorded.
662fn check_encoded_file_relation(
663    dialect: &dyn PlatformDialect,
664    probe: &str,
665    findings: &mut Vec<Finding>,
666) {
667    let Some(relation) =
668        SqlRenderer::delimited_file_relation_in_encoding(dialect, probe, "windows-1252")
669    else {
670        return;
671    };
672    if !relation.contains(probe) {
673        findings.push(Finding {
674            severity: Severity::Blocking,
675            what: "`delimited_file_relation_in_encoding` returns a relation that does not carry \
676                   the path it was given"
677                .to_owned(),
678            fix: "put the literal you were handed where your engine's file relation takes a \
679                  path. It arrives already quoted and escaped."
680                .to_owned(),
681        });
682    }
683    if SqlRenderer::delimited_file_relation(dialect, probe).is_none() {
684        findings.push(Finding {
685            severity: Severity::Blocking,
686            what: "this dialect states how to read a file in a named encoding and states no way \
687                   to read a file at all"
688                .to_owned(),
689            fix: "answer `delimited_file_relation` as well, or answer neither. Razeri asks the \
690                  first question before the second — a source whose bytes are UTF-8 never \
691                  reaches the encoding arm — so an engine that answers only the second has \
692                  written a relation nothing will ask it for."
693                .to_owned(),
694        });
695    }
696}
697
698/// The decisions a dialect states rather than inherits.
699fn check_decisions(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
700    let spelling = SqlRenderer::sid_spelling(dialect);
701    if spelling.platform == UNKNOWN_PLATFORM {
702        findings.push(Finding {
703            severity: Severity::Blocking,
704            what: "this dialect states no surrogate-key spelling, so every key it renders calls \
705                   an `xxhash64` its engine very likely does not have"
706                .to_owned(),
707            fix: "override `SqlRenderer::sid_spelling`. Say how this engine writes a \
708                  replacement and a Unicode literal, how it joins strings, how it casts to text, \
709                  and how it spells a 64-bit hash. If it has no portable hash, name an artifact your prerequisites install \
710                  — never the nearest-looking built-in, which keys a warehouse to a number \
711                  nothing else can reproduce."
712                .to_owned(),
713        });
714    }
715
716    // A join with no name in it writes `(a, '|', b)` or `a  '|'  b`: a
717    // composite key the engine cannot parse, met at the first load that
718    // joins two parts.
719    let join = match spelling.concat {
720        Concat::Function(name) | Concat::FunctionBinary(name) | Concat::Operator(name) => name,
721        Concat::Plus => "+",
722    };
723    if join.trim().is_empty() {
724        findings.push(Finding {
725            severity: Severity::Blocking,
726            what: "this dialect's surrogate-key spelling joins the parts of a composite key \
727                   with a function or operator that has no name"
728                .to_owned(),
729            fix: "name what your engine joins strings with in `SidSpelling::concat`: \
730                  `Concat::Function(\"CONCAT\")`, `Concat::FunctionBinary(\"CONCAT\")` where it \
731                  takes exactly two arguments, or `Concat::Operator(\"||\")` where it has an \
732                  operator and no function."
733                .to_owned(),
734        });
735    }
736
737    // **A stated body that says nothing is worse than no body at all.** Razeri
738    // writes the `CREATE FUNCTION` envelope around whatever comes back, so an
739    // empty one deploys cleanly and returns nothing — every key in the
740    // warehouse is then the sentinel or garbage, under a green deploy.
741    if let Some(supplied) = SqlRenderer::sid_helper_body(dialect)
742        && supplied.body.trim().is_empty()
743    {
744        findings.push(Finding {
745            severity: Severity::Blocking,
746            what: "this dialect says its surrogate-key helper has a body Razeri cannot compose, \
747                   and then supplies an empty one"
748                .to_owned(),
749            fix: "return the body that computes XXH64 with seed 0 over the UTF-8 bytes of the \
750                  one argument, or answer `None` and let Razeri compose the derivation from \
751                  your `sid_spelling`. An empty body deploys without error and keys every row \
752                  to nothing."
753                .to_owned(),
754        });
755    }
756
757    // A file relation that drops its path reads the same file for every entity
758    // — one table filled, the rest filled wrong, and nothing about it fails.
759    let probe = "'/razeri/probe.csv'";
760    if let Some(relation) = SqlRenderer::delimited_file_relation(dialect, probe)
761        && !relation.contains(probe)
762    {
763        findings.push(Finding {
764            severity: Severity::Blocking,
765            what: "`delimited_file_relation` returns a relation that does not carry the path it \
766                   was given"
767                .to_owned(),
768            fix: "put the literal you were handed where your engine's file relation takes a \
769                  path. It arrives already quoted and escaped. A relation that drops it reads \
770                  one file for every entity the design binds, and the generated fill loads the \
771                  wrong rows without failing."
772                .to_owned(),
773        });
774    }
775
776    check_encoded_file_relation(dialect, probe, findings);
777    check_routine_forms(dialect, findings);
778    check_slice_replacement(dialect, findings);
779
780    // The note is what a reader of the DDL learns from, and on an engine with
781    // no keyword of its own it is the ONLY place they can learn it.
782    if let ConstraintEnforcement::DeclaredOnly(declared) =
783        DdlRenderer::constraint_enforcement(dialect)
784        && declared.note.split_whitespace().count() < 5
785    {
786        findings.push(Finding {
787            severity: Severity::Blocking,
788            what: "this dialect says its engine accepts constraints it does not enforce, and \
789                   the note explaining that says almost nothing"
790                .to_owned(),
791            fix: "a reader of your rendered DDL sees a PRIMARY KEY that looks like a \
792                  guarantee. Say what this engine really does with the declaration, and where \
793                  the guarantee has to come from instead."
794                .to_owned(),
795        });
796    }
797
798    // **The two refusals are different findings, and that is the point of the
799    // second variant.** `None` is silence, and silence is unanswered. A stated
800    // `Unsupported` is a measured claim; what is left to grade there is whether
801    // the sentence is worth reading, because it is the only thing an operator
802    // gets where the load would have been.
803    match DialectCapabilities::merge_shape(dialect) {
804        MergeShape::None => findings.push(Finding {
805            severity: Severity::Unanswered,
806            what: "this dialect has not stated its upsert shape, so Razeri writes no generated \
807                   load for it"
808                .to_owned(),
809            fix: "if this engine has a MERGE or an upsert statement, say which in \
810                  `DialectCapabilities::merge_shape`. If it genuinely has neither, answer \
811                  `MergeShape::Unsupported` with your engine's own sentence — a refusal an \
812                  operator can act on, rather than a silence."
813                .to_owned(),
814        }),
815        MergeShape::Unsupported(orientation) => {
816            check_refusal_copy("the upsert refusal", orientation, findings);
817        }
818        MergeShape::Merge(restrictions) => check_merge_restrictions(restrictions, findings),
819        _ => {}
820    }
821}
822
823/// **A dialect that names a verb for replacing one slice has to put the slice
824/// in it.**
825///
826/// Most dialects answer nothing here, and nothing is a complete answer: Razeri
827/// then writes a delete filtered to the slice, which is correct on every
828/// engine. What is worth grading is the dialect that *does* answer, because its
829/// statement runs in front of a load's write and clears rows. A statement that
830/// forgot the value it was handed does not clear the day this call was given —
831/// it clears some other day, or every day, and the load then reports success
832/// over a table it emptied.
833///
834/// The probe is a daily partition of a date column, which is the case every
835/// partition-level verb is allowed to answer for. A dialect that answers
836/// nothing to it has said the portable form is what it wants.
837fn check_slice_replacement(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
838    const VALUE: &str = "$razeri_slice_probe";
839    let plan = StoragePlan {
840        partition: PartitionStrategy::RangeByTimeDimension {
841            field: "razeri_probe_day".to_owned(),
842            granularity: PartitionGranularity::Day,
843            retention: None,
844            look_ahead: None,
845            window: razeri_plugin_contract::storage_strategy::PartitionWindow::default(),
846        },
847        compression: CompressionStrategy::None,
848        index: IndexStrategy::None,
849    };
850    let day = DataType::date();
851    let columns = ["razeri_probe_day"];
852    let entity = EntityRef {
853        schema: Some("razeri_probe"),
854        name: "razeri_probe_table",
855        role: TableRole::Written,
856        columns: &columns,
857        partition_column_type: Some(&day),
858    };
859    let slice = SliceRef { column: "razeri_probe_day", value: VALUE };
860    let Some(answer) = StorageRenderer::render_slice_replacement(dialect, entity, &plan, slice)
861    else {
862        return;
863    };
864
865    let carries = match &answer {
866        SliceReplacement::Emptied(statements) => {
867            !statements.is_empty() && statements.iter().all(|sql| sql.contains(VALUE))
868        }
869        SliceReplacement::WrittenByInsert(clause) => clause.contains(VALUE),
870    };
871    // **A verb that carries the slice is graded nowhere**, deliberately. The
872    // kit cannot tell a measured answer from a lucky one, and a note on every
873    // dialect that got it right would fire on exactly the dialects that need no
874    // help. What is left to say is said where it is useful — in the trait's own
875    // documentation, which an author reads before writing the override.
876    if carries {
877        return;
878    }
879    findings.push(Finding {
880        severity: Severity::Blocking,
881        what: "`render_slice_replacement` returns a statement that does not carry the slice it \
882               was handed"
883            .to_owned(),
884        fix: "put the value you were given where your statement names the slice, and build any \
885              partition NAME from it the same way your extend procedure built it. A replacement \
886              that drops the value clears a slice this call was not given — or every slice — \
887              and the load reports success over what it emptied."
888            .to_owned(),
889    });
890}
891
892/// **The two halves of an evolution, held together**: what this engine says it
893/// keeps when a loaded table changes shape, and the statement it writes for the
894/// change.
895///
896/// An answer left at its default is graded nowhere, for the reason
897/// [`check_merge_restrictions`] states: from outside, a measured *"my engine
898/// does not do that"* and a question nobody asked read the same, and a finding
899/// made out of that silence would fire on every dialect.
900///
901/// What is worth saying is a **pair that disagrees**. A dialect that says its
902/// engine widens a string in place and then writes no statement for a widening
903/// has told Razeri to call the change safe and left the operator to work out
904/// the `ALTER` alone — a gap that reads to them as Razeri not having finished.
905/// And a dialect that answers `None` to a new column has declined the one
906/// evolution every warehouse has, which is nearly always an override that meant
907/// to narrow something and narrowed everything.
908fn check_evolution(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
909    let answers = DialectCapabilities::evolution_answers(dialect);
910    let boolean = DataType::boolean();
911    let long = DataType::varchar(40);
912
913    if DdlRenderer::render_column_evolution(
914        dialect,
915        &ColumnEvolution::AddColumn {
916            schema: Some("s"),
917            table: "t",
918            column: "c",
919            data_type: &boolean,
920        },
921    )
922    .is_none()
923    {
924        findings.push(Finding {
925            severity: Severity::Blocking,
926            what: "this dialect writes no statement for a column that is new, which is the \
927                  commonest change a deployed warehouse ever sees"
928                .to_owned(),
929            fix: "answer `ColumnEvolution::AddColumn` in `render_column_evolution`, or drop the \
930                 override and take the contract's `ALTER TABLE … ADD COLUMN …`, which most \
931                 engines take; some write `ADD` without `COLUMN`, so run it on yours first. An \
932                 engine that genuinely has no way to add a column is worth saying out loud in \
933                 the crate's own documentation."
934                .to_owned(),
935        });
936    }
937
938    if answers.parameterized_string_widening_is_lossless
939        && DdlRenderer::render_column_evolution(
940            dialect,
941            &ColumnEvolution::WidenColumn {
942                schema: Some("s"),
943                table: "t",
944                column: "c",
945                data_type: &long,
946            },
947        )
948        .is_none()
949    {
950        findings.push(Finding {
951            severity: Severity::Note,
952            what: "this dialect says its engine widens a string's declared length in place, and \
953                  writes no statement for the change"
954                .to_owned(),
955            fix: "answer `ColumnEvolution::WidenColumn` in `render_column_evolution` with this \
956                 engine's spelling of it. Without it Razeri tells an operator the widening \
957                 costs nothing and then hands them nothing to run, which reads as Razeri not \
958                 having finished rather than as a statement they own."
959                .to_owned(),
960        });
961    }
962
963    if answers.nested_field_addition_is_lossless
964        && DdlRenderer::render_column_evolution(
965            dialect,
966            &ColumnEvolution::AddNestedField {
967                schema: Some("s"),
968                table: "t",
969                column: "c",
970                field: "f",
971                data_type: &long,
972            },
973        )
974        .is_none()
975    {
976        findings.push(Finding {
977            severity: Severity::Note,
978            what: "this dialect says its engine keeps every value when a record gains a field, \
979                  and writes no statement for the change"
980                .to_owned(),
981            fix: "answer `ColumnEvolution::AddNestedField` in `render_column_evolution`. Some \
982                 engines name the new field; some restate the whole column's type, which is \
983                 why the change carries both the field's path and the column's type with the \
984                 field in it."
985                .to_owned(),
986        });
987    }
988}
989
990/// **The statements a redeploy and a file of drops run again**, each carrying
991/// the object it was handed.
992///
993/// A drop that forgot the column it was asked about drops another one, or
994/// none, under a green run; a guard around a `CREATE TABLE` that left the
995/// statement out makes nothing, and the next file meets a table that is not
996/// there. Each answer is asked about a table of the dialect's own spelling and
997/// read for the names it was given.
998fn check_run_again(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
999    let schema = SqlRenderer::quote_identifier(dialect, "razeri_probe_schema");
1000    let name = SqlRenderer::quote_identifier(dialect, "razeri_probe_table");
1001    let relation = format!("{schema}.{name}");
1002    let table = WrittenObject::new(Some(&schema), &name, &relation);
1003    let column = SqlRenderer::quote_identifier(dialect, "razeri_probe_column");
1004    let mut lost: Vec<&str> = Vec::new();
1005
1006    match DdlRenderer::render_drop_column(dialect, table, &column, false) {
1007        Some(drop) if drop.text().contains(&column) => {}
1008        _ => lost.push("render_drop_column"),
1009    }
1010    if let Some(guarded) = DdlRenderer::render_drop_column(dialect, table, &column, true)
1011        && !guarded.text().contains(&column)
1012    {
1013        lost.push("render_drop_column (only where it stands)");
1014    }
1015    for only_where_it_stands in [false, true] {
1016        if let Some(drop) = DdlRenderer::render_drop_view(dialect, table, only_where_it_stands)
1017            && !drop.text().contains(&name)
1018        {
1019            lost.push("render_drop_view");
1020        }
1021    }
1022    let create = format!("CREATE TABLE {relation} (a INTEGER)");
1023    if let Some(guarded) = DdlRenderer::render_create_table_if_absent(dialect, table, &create)
1024        && !guarded.text().contains(&create)
1025    {
1026        lost.push("render_create_table_if_absent");
1027    }
1028    lost.dedup();
1029    if !lost.is_empty() {
1030        findings.push(Finding {
1031            severity: Severity::Blocking,
1032            what: format!(
1033                "{} returns a statement that does not carry the object it was handed",
1034                lost.join(", ")
1035            ),
1036            fix: "put the names you were given where your statement names the object, and keep \
1037                  a create you guard whole inside the guard. A drop that loses its column drops \
1038                  another one or none, and a guard that loses its statement makes nothing — \
1039                  both under a run that reports success."
1040                .to_owned(),
1041        });
1042    }
1043
1044    // A comparison that loses the value it stands for compares something
1045    // else, and the load's search for a row that arrives twice finds none.
1046    let value = "razeri_probe_value";
1047    let loses_its_value = declarable_types().iter().any(|data_type| {
1048        [HeldAs::Declared, HeldAs::Converted].into_iter().any(|held| {
1049            ExpressionRenderer::render_comparable(dialect, value, data_type, held)
1050                .is_some_and(|compared| !compared.contains(value))
1051        })
1052    });
1053    if loses_its_value {
1054        findings.push(Finding {
1055            severity: Severity::Blocking,
1056            what: "`render_comparable` answers an expression that does not carry the value it \
1057                   stands for"
1058                .to_owned(),
1059            fix: "answer the value itself where your engine compares the type directly, an \
1060                  expression over it where it compares one only that way, and `None` where it \
1061                  cannot compare one at all — then Razeri refuses such a column by name."
1062                .to_owned(),
1063        });
1064    }
1065
1066    // A text ceiling of nothing refuses every varchar, and a blank word for
1067    // what a text cannot be says nothing beside the type.
1068    if let Some(limits) = DialectCapabilities::text_limits(dialect)
1069        && (limits.longest_varchar == Some(0)
1070            || limits.text_is_not.is_some_and(|what| what.trim().is_empty()))
1071    {
1072        findings.push(Finding {
1073            severity: Severity::Blocking,
1074            what: "`text_limits` states a longest varchar of 0, or a blank word for what an \
1075                   unbounded text cannot be"
1076                .to_owned(),
1077            fix: "state the longest varchar(n) your engine creates — one more is refused at \
1078                  CREATE TABLE — and name what it refuses a text column as, or leave it None."
1079                .to_owned(),
1080        });
1081    }
1082
1083    match DialectCapabilities::catalogue_reach(dialect) {
1084        CatalogueReach::HeldColumnsOnly(reason) | CatalogueReach::Nothing(reason) => {
1085            check_refusal_copy("the reason the schema check is not asked", reason, findings);
1086        }
1087        _ => {}
1088    }
1089}
1090
1091/// **A begin statement that leaves the commit to the client**, said by an
1092/// engine that has no transaction spanning statements, is two answers that
1093/// cannot both be true.
1094fn check_transactions(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1095    // A log line answered with no text writes a blank statement into every
1096    // routine that logs; `None` is how an engine with no log statement says so.
1097    if SqlRenderer::render_procedure_log(
1098        dialect,
1099        razeri_plugin_contract::ProcedureLogLevel::Info,
1100        "'razeri'",
1101    )
1102    .is_some_and(|line| line.trim().is_empty())
1103    {
1104        findings.push(Finding {
1105            severity: Severity::Blocking,
1106            what: "`render_procedure_log` answers a log line with no text in it".to_owned(),
1107            fix: "answer `None` where your engine has no statement that writes a message: the \
1108                  line is then left out of the routine."
1109                .to_owned(),
1110        });
1111    }
1112    if DialectCapabilities::begin_leaves_the_commit_to_the_client(dialect)
1113        && !DialectCapabilities::supports_multi_statement_transactions(dialect)
1114    {
1115        findings.push(Finding {
1116            severity: Severity::Blocking,
1117            what: "this dialect says its begin statement leaves the commit to the client, and \
1118                   that its engine has no transaction spanning statements"
1119                .to_owned(),
1120            fix: "answer `begin_leaves_the_commit_to_the_client` only for an engine whose loads \
1121                  run in one transaction. Where there is none, the bundle already tells the \
1122                  operator the boundary is theirs."
1123                .to_owned(),
1124        });
1125    }
1126}
1127
1128/// **What a stated `MERGE` restriction changes about the SQL Razeri writes for
1129/// this engine**, said back to the author while the claim is still cheap to
1130/// withdraw.
1131///
1132/// A restriction left at its default costs nothing and is graded nowhere: the
1133/// kit cannot tell a measured *"my engine is fine with this"* from a question
1134/// nobody asked, and inventing a finding out of that silence would fire on
1135/// every dialect. What it can do is report the restriction a dialect does
1136/// state, because each one makes Razeri emit something other than the
1137/// statement it emits everywhere else.
1138fn check_merge_restrictions(restrictions: MergeRestrictions, findings: &mut Vec<Finding>) {
1139    if restrictions.slice_pruning_needs_literal {
1140        findings.push(Finding {
1141            severity: Severity::Note,
1142            what: "this dialect says its planner reads one slice of a partitioned table only \
1143                   from a literal, so a load scoped to one day cannot simply bind the day"
1144                .to_owned(),
1145            fix: "Razeri will put the day into the statement text through this engine's \
1146                  dynamic-execution form rather than binding it to the load procedure's \
1147                  parameter. Confirm that is what your engine wants: the statement is composed \
1148                  once per call and its text differs per day, which some planners cache and \
1149                  some do not. If a bound parameter does prune here, drop the restriction and \
1150                  Razeri binds it like everywhere else."
1151                .to_owned(),
1152        });
1153    }
1154}
1155
1156/// The one override nothing tells an author about, and every formula in every
1157/// design goes through it — and the operators a formula is written with.
1158fn check_formula_renderer(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1159    // An operator answered with no text writes `a  b`, which reads as two
1160    // values side by side. `None` is the answer for an operator the engine
1161    // lacks, and it is refused by name where a formula needs it.
1162    let bitwise = BitwiseOperator::ALL.map(|operator| {
1163        (
1164            format!("render_bitwise_operator({operator:?})"),
1165            FormulaRenderer::render_bitwise_operator(dialect, operator),
1166        )
1167    });
1168    let blank: Vec<String> = [
1169        ("render_power_operator".to_owned(), FormulaRenderer::render_power_operator(dialect)),
1170        ("render_ilike_operator".to_owned(), FormulaRenderer::render_ilike_operator(dialect)),
1171        (
1172            "render_not_ilike_operator".to_owned(),
1173            FormulaRenderer::render_not_ilike_operator(dialect),
1174        ),
1175        ("render_concat_operator".to_owned(), FormulaRenderer::render_concat_operator(dialect)),
1176    ]
1177    .into_iter()
1178    .chain(bitwise)
1179    .filter(|(_, answer)| answer.as_deref().is_some_and(|op| op.trim().is_empty()))
1180    .map(|(method, _)| method)
1181    .collect();
1182    if !blank.is_empty() {
1183        findings.push(Finding {
1184            severity: Severity::Blocking,
1185            what: format!("{} answers an operator with no text in it", blank.join(", ")),
1186            fix: "answer `None` where your engine has no such operator: a formula that needs it \
1187                  is then refused by name, and the reader is told to write the function your \
1188                  engine has. An empty answer writes the two operands side by side."
1189                .to_owned(),
1190        });
1191    }
1192
1193    let formula = SqlRenderer::to_formula_renderer(dialect);
1194    let dialect_name = SqlRenderer::dialect_name(dialect);
1195    if formula.dialect_name() != dialect_name && dialect_name != "ansi" {
1196        findings.push(Finding {
1197            severity: Severity::Blocking,
1198            what: "`to_formula_renderer` was not overridden, so every formula in every design \
1199                   renders through Razeri's ANSI defaults instead of this dialect"
1200                .to_owned(),
1201            fix: "return `Box::new(Self)`. It is one line, nothing fails without it, and every \
1202                  formula this engine sees is silently somebody else's."
1203                .to_owned(),
1204        });
1205    }
1206}
1207
1208/// **The three routine grammars a dialect states**, and what each answer owes.
1209///
1210/// A grammar Razeri carries needs nothing further. A refusal owes words a
1211/// reader can act on. `Custom` owes the render method it promised — see
1212/// [`check_custom_grammar`].
1213fn check_routine_forms(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1214    match SqlRenderer::procedure_form(dialect) {
1215        // Razeri's own agnostic renderer answers `Agnostic` on purpose: the
1216        // annotated form IS its output. Every other dialect that answers it has
1217        // simply not said.
1218        ProcedureForm::Agnostic if SqlRenderer::is_agnostic_dialect(dialect) => {}
1219        ProcedureForm::Agnostic => findings.push(Finding {
1220            severity: Severity::Unanswered,
1221            what: "this dialect states no stored-procedure grammar, so Razeri emits its own \
1222                   annotated form — which no engine parses"
1223                .to_owned(),
1224            fix: "override `SqlRenderer::procedure_form` with the grammar this engine speaks, \
1225                  or with `ProcedureForm::Unsupported(\"…\")` and a sentence saying what it \
1226                  offers instead."
1227                .to_owned(),
1228        }),
1229        ProcedureForm::Unsupported(orientation) => {
1230            check_refusal_copy("the stored-procedure refusal", orientation, findings);
1231            if DialectCapabilities::supports_stored_procedures(dialect) {
1232                findings.push(Finding {
1233                    severity: Severity::Blocking,
1234                    what: "this dialect says its engine has stored procedures, and its \
1235                           procedure form refuses to write one"
1236                        .to_owned(),
1237                    fix: "decide which is true. If the engine has none, leave \
1238                          `DialectCapabilities::supports_stored_procedures` at `false`; if it \
1239                          has them, answer `procedure_form` with the grammar it speaks."
1240                        .to_owned(),
1241                });
1242            }
1243        }
1244        ProcedureForm::Custom(grammar) => check_custom_grammar(
1245            CustomGrammar {
1246                kind: RoutineKind::Procedure,
1247                grammar,
1248                form_method: "procedure_form",
1249                render_method: "render_procedure",
1250                noun: "procedures",
1251            },
1252            |spec| SqlRenderer::render_procedure(dialect, spec),
1253            findings,
1254        ),
1255        _ => {}
1256    }
1257    check_procedures_are_used(dialect, findings);
1258
1259    match SqlRenderer::scalar_function_form(dialect) {
1260        ScalarFunctionForm::Unsupported(orientation) => {
1261            check_refusal_copy("the scalar-function refusal", orientation, findings);
1262        }
1263        ScalarFunctionForm::Custom(grammar) => check_custom_grammar(
1264            CustomGrammar {
1265                kind: RoutineKind::ScalarFunction,
1266                grammar,
1267                form_method: "scalar_function_form",
1268                render_method: "render_scalar_function",
1269                noun: "scalar functions",
1270            },
1271            |spec| SqlRenderer::render_scalar_function(dialect, spec),
1272            findings,
1273        ),
1274        _ => {}
1275    }
1276
1277    match SqlRenderer::table_function_form(dialect) {
1278        TableFunctionForm::Unsupported(orientation) => {
1279            check_refusal_copy("the table-function refusal", orientation, findings);
1280        }
1281        TableFunctionForm::Custom(grammar) => check_custom_grammar(
1282            CustomGrammar {
1283                kind: RoutineKind::TableFunction,
1284                grammar,
1285                form_method: "table_function_form",
1286                render_method: "render_table_function",
1287                noun: "table functions",
1288            },
1289            |spec| SqlRenderer::render_table_function(dialect, spec),
1290            findings,
1291        ),
1292        _ => {}
1293    }
1294
1295    check_parameter_type_spelling(dialect, findings);
1296}
1297
1298/// **A dialect that spells its own procedures has to say its engine has
1299/// them**, or Razeri never writes one.
1300///
1301/// Two answers carry the fact. `procedure_form` says how a procedure is
1302/// written; `DialectCapabilities::supports_stored_procedures` says whether a
1303/// load is one, and its default is `false`. A dialect that answers `Custom`
1304/// and leaves the capability alone renders a procedure nothing asks for:
1305/// every load is written as plain statements, and the bundle says the engine
1306/// has no stored procedures. A grammar Razeri carries is left out on purpose,
1307/// because Razeri keeps that pair for its own engines: `ClickHouse`'s form
1308/// writes executable functions, which no load runs as a procedure.
1309fn check_procedures_are_used(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1310    let Some(grammar) = SqlRenderer::procedure_form(dialect).custom_grammar() else {
1311        return;
1312    };
1313    if DialectCapabilities::supports_stored_procedures(dialect) {
1314        return;
1315    }
1316    findings.push(Finding {
1317        severity: Severity::Blocking,
1318        what: format!(
1319            "this dialect writes procedures in {grammar:?} and says its engine has none, so no \
1320             load is ever written as one"
1321        ),
1322        fix: "answer `DialectCapabilities::supports_stored_procedures` with `true`. Razeri asks \
1323              it before it writes a load as a procedure, and its default is `false`."
1324            .to_owned(),
1325    });
1326}
1327
1328/// **A parameter's type is not always spelled the way a column's is**, and this
1329/// asks whether the dialect has looked.
1330///
1331/// Oracle is the measured case: a column there takes `NUMBER(19, 0)` and
1332/// `VARCHAR2(100)`, and the same types in a parameter list are a compile error
1333/// — the bare `NUMBER` and `VARCHAR2` are what a parameter clause takes, with
1334/// the precision belonging on the local declaration instead. A dialect that has
1335/// not said otherwise gets the column spelling in its parameter lists, which is
1336/// right for most engines and a routine that will not compile on one like that.
1337///
1338/// It is a note and not a failure, because for most engines the two spellings
1339/// genuinely are the same and there is nothing to say. And it is asked only of a
1340/// dialect spelling a grammar of its own, because that is the population where
1341/// nobody has measured the answer yet.
1342fn check_parameter_type_spelling(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1343    let spells_its_own = SqlRenderer::procedure_form(dialect).custom_grammar().is_some()
1344        || SqlRenderer::scalar_function_form(dialect).custom_grammar().is_some()
1345        || SqlRenderer::table_function_form(dialect).custom_grammar().is_some();
1346    if !spells_its_own {
1347        return;
1348    }
1349    // A type that carries a length is the only kind the two spellings can
1350    // disagree about, so it is the only kind worth asking with.
1351    let qualified = DataType::varchar(100);
1352    let column = SqlRenderer::render_data_type(dialect, &qualified);
1353    let parameter = SqlRenderer::render_parameter_data_type(dialect, &qualified);
1354    if column == parameter && column.contains('(') {
1355        findings.push(Finding {
1356            severity: Severity::Note,
1357            what: format!(
1358                "a parameter of this routine's would be declared `{parameter}`, the same as a \
1359                column of that type"
1360            ),
1361            fix: "that is right for most engines, so this is only worth a look. If yours refuses \
1362                 a length or a precision in a parameter list — Oracle does, and answers \
1363                 PLS-00103 at the opening parenthesis — override \
1364                 `SqlRenderer::render_parameter_data_type` with the bare spelling. Local \
1365                 declarations keep the length either way."
1366                .to_owned(),
1367        });
1368    }
1369}
1370
1371/// One routine kind whose grammar a dialect said it spells itself.
1372#[derive(Clone, Copy)]
1373struct CustomGrammar {
1374    /// Which routine kind the claim is about.
1375    kind: RoutineKind,
1376    /// The grammar's own name, as the dialect wrote it.
1377    grammar: &'static str,
1378    /// The method that carried the claim.
1379    form_method: &'static str,
1380    /// The method that owes the rendering.
1381    render_method: &'static str,
1382    /// What to call the routines in a sentence.
1383    noun: &'static str,
1384}
1385
1386/// **A dialect that says it spells its own grammar has to spell it.**
1387///
1388/// `Custom` moves the whole rendering to the dialect: Razeri substitutes no
1389/// near-neighbour grammar and refuses nothing, because both of those say
1390/// something false — one about the engine's syntax, the other about whether the
1391/// engine has the routine at all. So the claim is only worth anything with the
1392/// method behind it, and a dialect that made the claim and left the method
1393/// alone ships a build that stops on the routine.
1394///
1395/// The check is the question itself: hand the render method the shape it will
1396/// receive and see whether anything comes back.
1397///
1398/// Parameters:
1399/// - `claim`: which kind, which grammar, and the two method names to name;
1400/// - `render`: the dialect's render method for that kind;
1401/// - `findings`: where the report is collected.
1402fn check_custom_grammar(
1403    claim: CustomGrammar,
1404    render: impl Fn(&RoutineSpec) -> Option<String>,
1405    findings: &mut Vec<Finding>,
1406) {
1407    let CustomGrammar { kind, grammar, form_method, render_method, noun } = claim;
1408    // The grammar's name is a name, not a refusal: it is read in a report and
1409    // in a comment, so it has to say something and does not have to say much.
1410    if grammar.trim().is_empty() {
1411        findings.push(Finding {
1412            severity: Severity::Blocking,
1413            what: format!("`{form_method}` says Custom, and names no grammar"),
1414            fix: "carry your grammar's own name — `Custom(\"PL/SQL\")`. It is what a reader \
1415                  of a report, and of the comment Razeri writes where a routine could not be \
1416                  rendered, is told this engine speaks."
1417                .to_owned(),
1418        });
1419    }
1420
1421    let mut probe = RoutineSpec::new(kind, "razeri_conformance_probe");
1422    probe.or_replace = true;
1423    if render(&probe).is_none_or(|rendered| rendered.trim().is_empty()) {
1424        findings.push(Finding {
1425            severity: Severity::Blocking,
1426            what: format!(
1427                "`{form_method}` says Custom({grammar:?}), so this dialect must render {noun} \
1428                 itself — and `{render_method}` returns nothing"
1429            ),
1430            fix: format!(
1431                "override `SqlRenderer::{render_method}`. It receives the routine Razeri \
1432                 composed — name, parameters with their types already in your spelling, body, \
1433                 comment — and returns the whole CREATE statement your engine parses. Razeri \
1434                 emits what you return and writes nothing of its own: a near-neighbour grammar \
1435                 fails on deploy, and a refusal would say this engine has no {noun} when it \
1436                 has them in a grammar of its own."
1437            ),
1438        });
1439    }
1440}
1441
1442/// A refusal that does not say what to do instead is a wall.
1443fn check_refusal_copy(subject: &str, copy: &str, findings: &mut Vec<Finding>) {
1444    if copy.trim().is_empty() {
1445        findings.push(Finding {
1446            severity: Severity::Blocking,
1447            what: format!("{subject} has no words in it"),
1448            fix: "say what this engine offers instead. A reader who hits a refusal needs the \
1449                  next thing to try, and it has to be about their engine."
1450                .to_owned(),
1451        });
1452        return;
1453    }
1454    if copy.split_whitespace().count() < 5 {
1455        findings.push(Finding {
1456            severity: Severity::Note,
1457            what: format!("{subject} is very short"),
1458            fix: "a refusal earns its place by naming the alternative — what this engine has \
1459                  instead of the thing it cannot do."
1460                .to_owned(),
1461        });
1462    }
1463}
1464
1465/// Fifteen facts are declared twice and must agree.
1466fn check_paired_facts(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1467    let caps: &dyn DialectCapabilities = dialect;
1468    let ren: &dyn SqlRenderer = dialect;
1469    let ddl: &dyn DdlRenderer = dialect;
1470    let mut disagreements: Vec<&'static str> = Vec::new();
1471
1472    macro_rules! pair {
1473        ($m:ident, $renderer_value:expr) => {
1474            if caps.$m() != $renderer_value {
1475                disagreements.push(stringify!($m));
1476            }
1477        };
1478    }
1479    pair!(supports_on_conflict, ren.supports_on_conflict());
1480    pair!(supports_insert_overwrite, ren.supports_insert_overwrite());
1481    pair!(supports_update_from, ren.supports_update_from());
1482    pair!(supports_named_windows, ren.supports_named_windows());
1483    pair!(supports_compound_assignment, ren.supports_compound_assignment());
1484    pair!(supports_window_frame_exclude, ren.supports_window_frame_exclude());
1485    pair!(supports_merge_not_matched_by_source, ren.supports_merge_not_matched_by_source());
1486    pair!(merge_not_matched_keyword, ren.merge_not_matched_keyword());
1487    pair!(uses_alter_table_update, ren.uses_alter_table_update());
1488    pair!(supports_multi_table_insert, ren.supports_multi_table_insert());
1489    pair!(supports_cascade_drop, ddl.supports_cascade_drop());
1490    pair!(supports_sync_drop, ddl.supports_sync_drop());
1491    pair!(supports_force_drop, ddl.supports_force_drop());
1492
1493    // **The fourteenth, whose two sides are different types.** The capability
1494    // is a boolean; the renderer answer is a form that either renders or
1495    // carries a refusal. Both are read — the build door reads the form, and
1496    // registry-walking rosters read the capability — so a dialect claiming a
1497    // table function on one side and refusing on the other has an engine that
1498    // both does and does not have one. `SQLite` was exactly that on the day
1499    // this check was written: `false` since the capability existed, and a
1500    // renderer still inheriting PostgreSQL's `RETURNS TABLE`.
1501    if caps.supports_table_functions() != ren.table_function_form().refusal().is_none() {
1502        disagreements.push("supports_table_functions");
1503    }
1504    // **The fifteenth, the same shape for a scalar function.** The build door
1505    // reads the capability; the renderer reads the form.
1506    if caps.supports_stored_functions() != ren.scalar_function_form().refusal().is_none() {
1507        disagreements.push("supports_stored_functions");
1508    }
1509
1510    if !disagreements.is_empty() {
1511        findings.push(Finding {
1512            severity: Severity::Blocking,
1513            what: format!(
1514                "this dialect declares {} {} two ways and the two disagree: {}",
1515                disagreements.len(),
1516                if disagreements.len() == 1 { "fact" } else { "facts" },
1517                disagreements.join(", ")
1518            ),
1519            fix: "each of these is declared once on the capability trait and once in the \
1520                  renderer hierarchy, and Razeri reads both. Decide which is true of your engine \
1521                  and move the other one to match."
1522                .to_owned(),
1523        });
1524    }
1525}
1526
1527/// **A dialect that folds each schema into an object's name has to fold it
1528/// everywhere.**
1529///
1530/// Razeri writes most names itself, asking `fold_schema_into_name`, and some
1531/// through the dialect's own `qualify_name`. The two have to name the same
1532/// object, or a table is created under one name and read under another. And a
1533/// fold is asked for only where the engine has no schemas: on one that has
1534/// them, the schema is written apart from the name, and a fold says otherwise.
1535fn check_schema_fold(dialect: &dyn PlatformDialect, findings: &mut Vec<Finding>) {
1536    let (schema, name) = ("razeri_probe_raw", "razeri_probe_table");
1537    let Some(folded) = SqlRenderer::fold_schema_into_name(dialect, schema, name) else {
1538        return;
1539    };
1540    if DialectCapabilities::supports_schemas(dialect) {
1541        findings.push(Finding {
1542            severity: Severity::Blocking,
1543            what: "this dialect folds a schema into an object's name on an engine it says has \
1544                   schemas"
1545                .to_owned(),
1546            fix: "answer `fold_schema_into_name` with `None`. A fold is for an engine with no \
1547                  schemas, and only there is it asked; or answer \
1548                  `DialectCapabilities::supports_schemas` with `false` if your engine has none."
1549                .to_owned(),
1550        });
1551        return;
1552    }
1553    let expected = SqlRenderer::quote_identifier(dialect, &folded);
1554    let qualified = SqlRenderer::qualify_name(dialect, Some(schema), name);
1555    if qualified != expected {
1556        findings.push(Finding {
1557            severity: Severity::Blocking,
1558            what: format!(
1559                "`fold_schema_into_name` names an object `{expected}` and `qualify_name` names \
1560                 the same object `{qualified}`"
1561            ),
1562            fix: "make `qualify_name` answer the folded name, quoted, when it is given a \
1563                  schema. Razeri names some objects through it and the rest through the fold, \
1564                  so a difference creates a table under one name and reads it under another."
1565                .to_owned(),
1566        });
1567    }
1568}
1569
1570/// **A described deploy client has to be told which file to run.**
1571///
1572/// The generated script substitutes the file for `{file}` in the arguments
1573/// the dialect names, and reads nothing else, so an argument list without it
1574/// runs the client with no SQL at all — and a client given no file usually
1575/// waits for one on its input.
1576fn check_deploy_client(info: &crate::dialect::DialectInfo, findings: &mut Vec<Finding>) {
1577    let Some(crate::dialect::DeployScript::Client(client)) = info.deploy_script else {
1578        return;
1579    };
1580    if client.command.trim().is_empty() {
1581        findings.push(Finding {
1582            severity: Severity::Blocking,
1583            what: "this dialect describes a deploy client with no command".to_owned(),
1584            fix: "name the client's command as an operator has it on `PATH`.".to_owned(),
1585        });
1586    }
1587    let unnamed: Vec<&str> = [("run_file", Some(client.run_file)), ("read_rows", client.read_rows)]
1588        .into_iter()
1589        .filter_map(|(field, args)| {
1590            args.filter(|args| !args.iter().any(|arg| arg.contains("{file}"))).map(|_| field)
1591        })
1592        .collect();
1593    if !unnamed.is_empty() {
1594        findings.push(Finding {
1595            severity: Severity::Blocking,
1596            what: format!(
1597                "the deploy client's {} never names the file to run",
1598                unnamed.join(" and ")
1599            ),
1600            fix: "put `{file}` where your client takes the file of SQL to run — on its own, or \
1601                  inside an argument such as `--file={file}`. The script writes the file there \
1602                  and nowhere else."
1603                .to_owned(),
1604        });
1605    }
1606    if let Some(terminator) = client.block_terminator
1607        && [terminator.open, terminator.end, terminator.close]
1608            .iter()
1609            .any(|part| part.trim().is_empty())
1610    {
1611        findings.push(Finding {
1612            severity: Severity::Blocking,
1613            what: "the deploy client's block terminator leaves a part blank".to_owned(),
1614            fix: "name the line before a routine, what ends it, and the line after it — \
1615                  `SET TERM ^ ;`, `^` and `SET TERM ; ^` for Firebird's isql. A blank end leaves \
1616                  the routine open, and the next statement is read into it."
1617                .to_owned(),
1618        });
1619    }
1620}
1621
1622/// Every type a design can declare, which is the set the required methods owe
1623/// an answer for.
1624///
1625/// The last four are the ones whose spelling actually varies between engines:
1626/// an array, a map, a struct, and an array of structs. A dialect that answers
1627/// only for scalars is a dialect that has not been graded on the types a
1628/// nested source table is made of.
1629fn declarable_types() -> Vec<DataType> {
1630    vec![
1631        DataType::tinyint(),
1632        DataType::smallint(),
1633        DataType::int(),
1634        DataType::bigint(),
1635        DataType::double(),
1636        DataType::boolean(),
1637        DataType::text(),
1638        DataType::varchar(200),
1639        DataType::uuid(),
1640        DataType::json(),
1641        DataType::date(),
1642        DataType::timestamp(),
1643        DataType::timestamp_tz(),
1644        DataType::decimal(18, 2),
1645        DataType::Array(ArrayDataType::new(DataType::varchar(100))),
1646        DataType::Map(MapDataType::new(DataType::varchar(50), DataType::bigint())),
1647        DataType::Struct(StructDataType::new(vec![
1648            StructField::new("street", DataType::varchar(200)),
1649            StructField::new("zip", DataType::varchar(10)),
1650        ])),
1651        DataType::Array(ArrayDataType::new(DataType::Struct(StructDataType::new(vec![
1652            StructField::new("key", DataType::varchar(100)),
1653            StructField::new("value", DataType::varchar(1000)),
1654        ])))),
1655    ]
1656}
1657
1658#[cfg(test)]
1659mod tests {
1660    use super::*;
1661    use crate::dialect::DialectInfo;
1662    use razeri_plugin_contract::{
1663        Concat, DmlRenderer, ExpressionRenderer, FormulaRenderer, MergeRestrictions,
1664        ProcedureRenderer, ReplicationRenderer, ScalarFunctionForm, SidSpelling, StorageRenderer,
1665        TaskRenderer, TextCast,
1666    };
1667    use std::marker::PhantomData;
1668
1669    // ── The broken fixture ────────────────────────────────────────────
1670    //
1671    // A plugin that compiles, registers nothing it should, and answers every
1672    // question with somebody else's default. This is what the kit exists to
1673    // catch, and it is deliberately the plugin an author gets by implementing
1674    // only the four required methods and stopping.
1675
1676    struct BrokenPlugin;
1677
1678    impl SqlRenderer for BrokenPlugin {
1679        fn render_data_type(&self, _dt: &DataType) -> String {
1680            String::new()
1681        }
1682        fn quote_identifier(&self, name: &str) -> String {
1683            name.to_owned()
1684        }
1685        fn render_cast_type(&self, _dt: &DataType) -> String {
1686            String::new()
1687        }
1688        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
1689            name.to_owned()
1690        }
1691        fn render_current_timestamp(&self) -> String {
1692            String::new()
1693        }
1694        fn dialect_name(&self) -> &'static str {
1695            "brokendb"
1696        }
1697        // No `sid_spelling`, no `procedure_form`, no `to_formula_renderer` —
1698        // and one fact declared twice, two ways.
1699        fn supports_on_conflict(&self) -> bool {
1700            true
1701        }
1702    }
1703    impl ExpressionRenderer for BrokenPlugin {}
1704    impl DdlRenderer for BrokenPlugin {}
1705    impl DmlRenderer for BrokenPlugin {}
1706    impl ProcedureRenderer for BrokenPlugin {}
1707    impl FormulaRenderer for BrokenPlugin {}
1708    impl TaskRenderer for BrokenPlugin {}
1709    impl ReplicationRenderer for BrokenPlugin {}
1710    impl StorageRenderer for BrokenPlugin {}
1711    impl DialectCapabilities for BrokenPlugin {
1712        fn supports_on_conflict(&self) -> bool {
1713            false
1714        }
1715    }
1716    impl PlatformDialect for BrokenPlugin {
1717        fn info(&self) -> DialectInfo {
1718            DialectInfo {
1719                name: "brokendb",
1720                display_name: "Broken DB",
1721                aliases: &[],
1722                dialect_family: DialectFamily::Custom(""),
1723                family: "Broken",
1724                is_cloud_native: false,
1725                is_olap: false,
1726                is_postgres_compatible: false,
1727                versions: &[],
1728                deploy_script: None,
1729            }
1730        }
1731    }
1732
1733    // ── The answered fixture, under two names ─────────────────────────
1734    //
1735    // The same plugin with every question answered, carrying the name it
1736    // registers under as a type parameter. Neither name is one Razeri knows a
1737    // spelling for; the difference is that one of them is in the registry and
1738    // the other is in nothing at all. Those are two different facts about a
1739    // dialect, and they read as two different reports.
1740
1741    trait FixtureName: Send + Sync + 'static {
1742        /// The registry name this fixture answers to.
1743        const NAME: &'static str;
1744        /// How this fixture's engine joins the parts of a composite key. Most
1745        /// of them take the inherited variadic `CONCAT`; the one that does not
1746        /// is the point of it being a knob.
1747        const CONCAT: Concat = Concat::Function("CONCAT");
1748        /// This fixture's engine's exponentiation operator; `None` where it
1749        /// has none.
1750        const POWER: Option<&'static str> = Some("^");
1751        /// This fixture's engine's left shift; `None` where it has none.
1752        const SHIFT_LEFT: Option<&'static str> = Some("<<");
1753        /// Whether this fixture's column drop forgets the column it was handed.
1754        const DROP_LOSES_ITS_COLUMN: bool = false;
1755        /// Whether this fixture compares something other than the value.
1756        const COMPARES_SOMETHING_ELSE: bool = false;
1757        /// Whether this fixture says its begin leaves the commit to the client
1758        /// while it has no transaction spanning statements.
1759        const BEGIN_WITHOUT_TRANSACTIONS: bool = false;
1760        /// The client this fixture's deploy script drives, if it names one.
1761        const DEPLOY: Option<crate::dialect::DeployScript> = None;
1762    }
1763
1764    /// Answered, and nothing linked it — what an author sees running the report
1765    /// from a crate whose registration nobody calls.
1766    struct Unlinked;
1767    impl FixtureName for Unlinked {
1768        const NAME: &'static str = "healthydb";
1769    }
1770
1771    /// Answered and registered, under a name Razeri ships no spelling for —
1772    /// the shape of every dialect written outside Razeri's own tree.
1773    struct Outside;
1774    impl FixtureName for Outside {
1775        const NAME: &'static str = "outsidedb";
1776    }
1777
1778    /// Answered, and joining composite keys with a `CONCAT` that takes exactly
1779    /// two arguments — the shape of Db2 and of older Oracle releases. Nothing
1780    /// about the join is an obligation, so the report on it must read exactly
1781    /// like the report on a variadic engine.
1782    struct BinaryConcat;
1783    impl FixtureName for BinaryConcat {
1784        const NAME: &'static str = "binaryconcatdb";
1785        const CONCAT: Concat = Concat::FunctionBinary("CONCAT");
1786    }
1787
1788    /// Answered, and joining composite keys with the `||` operator — the
1789    /// shape of an engine with no `CONCAT` function at all. Like the
1790    /// two-argument join, it is a decision and owes nothing.
1791    struct OperatorConcat;
1792    impl FixtureName for OperatorConcat {
1793        const NAME: &'static str = "operatorconcatdb";
1794        const CONCAT: Concat = Concat::Operator("||");
1795    }
1796
1797    /// Answered, with a join that names nothing.
1798    struct NamelessConcat;
1799    impl FixtureName for NamelessConcat {
1800        const NAME: &'static str = "namelessconcatdb";
1801        const CONCAT: Concat = Concat::Operator(" ");
1802    }
1803
1804    /// Answered, with an engine that raises to a power only through a
1805    /// function: no operator, said out loud.
1806    struct NoPowerOperator;
1807    impl FixtureName for NoPowerOperator {
1808        const NAME: &'static str = "nopowerdb";
1809        const POWER: Option<&'static str> = None;
1810    }
1811
1812    /// Answered, with an operator spelled as nothing at all.
1813    struct BlankPowerOperator;
1814    impl FixtureName for BlankPowerOperator {
1815        const NAME: &'static str = "blankpowerdb";
1816        const POWER: Option<&'static str> = Some(" ");
1817    }
1818
1819    /// Answered, with a comparison that forgets the value it stands for.
1820    struct ComparesSomethingElse;
1821    impl FixtureName for ComparesSomethingElse {
1822        const NAME: &'static str = "comparesotherdb";
1823        const COMPARES_SOMETHING_ELSE: bool = true;
1824    }
1825
1826    /// Answered, with a column drop that forgets its column.
1827    struct DropLosesItsColumn;
1828    impl FixtureName for DropLosesItsColumn {
1829        const NAME: &'static str = "droplosesdb";
1830        const DROP_LOSES_ITS_COLUMN: bool = true;
1831    }
1832
1833    /// Answered, with a begin that leaves the commit to a client on an engine
1834    /// with no transaction spanning statements.
1835    struct BeginWithoutTransactions;
1836    impl FixtureName for BeginWithoutTransactions {
1837        const NAME: &'static str = "beginwithouttxdb";
1838        const BEGIN_WITHOUT_TRANSACTIONS: bool = true;
1839    }
1840
1841    /// Answered, with an engine that has no left shift — an answer.
1842    struct NoShiftOperator;
1843    impl FixtureName for NoShiftOperator {
1844        const NAME: &'static str = "noshiftdb";
1845        const SHIFT_LEFT: Option<&'static str> = None;
1846    }
1847
1848    /// Answered, with a left shift that has no text in it.
1849    struct BlankShiftOperator;
1850    impl FixtureName for BlankShiftOperator {
1851        const NAME: &'static str = "blankshiftdb";
1852        const SHIFT_LEFT: Option<&'static str> = Some("");
1853    }
1854
1855    /// Answered, with a deploy client described well.
1856    struct DescribedClient;
1857    impl FixtureName for DescribedClient {
1858        const NAME: &'static str = "describedclientdb";
1859        const DEPLOY: Option<crate::dialect::DeployScript> =
1860            Some(crate::dialect::DeployScript::Client(crate::dialect::DeployClient {
1861                command: "sqlite3",
1862                run_file: &["-bail", "{target}", ".read {file}"],
1863                read_rows: Some(&["-csv", "-noheader", "{target}", ".read {file}"]),
1864                block_terminator: None,
1865            }));
1866    }
1867
1868    /// Answered, with a deploy client that is never told which file to run.
1869    struct FilelessClient;
1870    impl FixtureName for FilelessClient {
1871        const NAME: &'static str = "filelessclientdb";
1872        const DEPLOY: Option<crate::dialect::DeployScript> =
1873            Some(crate::dialect::DeployScript::Client(crate::dialect::DeployClient {
1874                command: "sqlite3",
1875                run_file: &["-bail", "{target}"],
1876                read_rows: None,
1877                block_terminator: None,
1878            }));
1879    }
1880
1881    /// Answered, with a deploy client whose routine end is blank.
1882    struct BlankBlockEnd;
1883    impl FixtureName for BlankBlockEnd {
1884        const NAME: &'static str = "blankblockenddb";
1885        const DEPLOY: Option<crate::dialect::DeployScript> =
1886            Some(crate::dialect::DeployScript::Client(crate::dialect::DeployClient {
1887                command: "isql",
1888                run_file: &["-bail", "-input", "{file}", "{target}"],
1889                read_rows: None,
1890                block_terminator: Some(crate::dialect::BlockTerminator {
1891                    open: "SET TERM ^ ;",
1892                    end: " ",
1893                    close: "SET TERM ; ^",
1894                }),
1895            }));
1896    }
1897
1898    struct Answered<N: FixtureName>(PhantomData<N>);
1899
1900    impl<N: FixtureName> Answered<N> {
1901        const fn new() -> Self {
1902            Self(PhantomData)
1903        }
1904    }
1905
1906    type HealthyPlugin = Answered<Unlinked>;
1907    type OutsidePlugin = Answered<Outside>;
1908
1909    inventory::submit! {
1910        crate::builder::DialectRegistration::new(
1911            Outside::NAME,
1912            || std::sync::Arc::new(OutsidePlugin::new()),
1913        )
1914    }
1915
1916    impl<N: FixtureName> SqlRenderer for Answered<N> {
1917        fn render_data_type(&self, dt: &DataType) -> String {
1918            razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
1919        }
1920        fn quote_identifier(&self, name: &str) -> String {
1921            format!("\"{name}\"")
1922        }
1923        fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
1924            schema.map_or_else(
1925                || self.quote_identifier(name),
1926                |s| format!("{}.{}", self.quote_identifier(s), self.quote_identifier(name)),
1927            )
1928        }
1929        fn render_current_timestamp(&self) -> String {
1930            "NOW()".to_owned()
1931        }
1932        fn dialect_name(&self) -> &'static str {
1933            N::NAME
1934        }
1935        fn sid_spelling(&self) -> SidSpelling {
1936            SidSpelling {
1937                platform: N::NAME,
1938                hash: ("answered_xxhash64(", ")"),
1939                cast_type: TextCast::Direct("STRING"),
1940                concat: N::CONCAT,
1941                through_helper: false,
1942                ..razeri_plugin_contract::ANSI_SID_SPELLING
1943            }
1944        }
1945        fn procedure_form(&self) -> ProcedureForm {
1946            ProcedureForm::Unsupported(
1947                "This engine has no stored procedures; write the load as a scheduled query \
1948                 instead.",
1949            )
1950        }
1951        fn scalar_function_form(&self) -> ScalarFunctionForm {
1952            ScalarFunctionForm::PostgreSql
1953        }
1954        fn to_formula_renderer(&self) -> Box<dyn FormulaRenderer> {
1955            Box::new(Self::new())
1956        }
1957    }
1958    impl<N: FixtureName> ExpressionRenderer for Answered<N> {
1959        fn render_comparable(
1960            &self,
1961            value: &str,
1962            _data_type: &DataType,
1963            _held: HeldAs,
1964        ) -> Option<String> {
1965            Some(if N::COMPARES_SOMETHING_ELSE { "1".to_owned() } else { value.to_owned() })
1966        }
1967    }
1968    impl<N: FixtureName> DdlRenderer for Answered<N> {
1969        fn render_drop_column(
1970            &self,
1971            table: WrittenObject<'_>,
1972            column: &str,
1973            only_where_it_stands: bool,
1974        ) -> Option<razeri_plugin_contract::Written> {
1975            if N::DROP_LOSES_ITS_COLUMN {
1976                return Some(razeri_plugin_contract::Written::Statement(format!(
1977                    "ALTER TABLE {} DROP COLUMN c",
1978                    table.relation
1979                )));
1980            }
1981            let guard = if only_where_it_stands { " IF EXISTS" } else { "" };
1982            Some(razeri_plugin_contract::Written::Statement(format!(
1983                "ALTER TABLE {} DROP COLUMN{guard} {column}",
1984                table.relation
1985            )))
1986        }
1987    }
1988    impl<N: FixtureName> DmlRenderer for Answered<N> {}
1989    impl<N: FixtureName> ProcedureRenderer for Answered<N> {}
1990    impl<N: FixtureName> FormulaRenderer for Answered<N> {
1991        fn render_power_operator(&self) -> Option<String> {
1992            N::POWER.map(str::to_owned)
1993        }
1994        fn render_bitwise_operator(&self, operator: BitwiseOperator) -> Option<String> {
1995            match operator {
1996                BitwiseOperator::ShiftLeft => N::SHIFT_LEFT.map(str::to_owned),
1997                other => Some(other.standard_spelling().to_owned()),
1998            }
1999        }
2000    }
2001    impl<N: FixtureName> TaskRenderer for Answered<N> {}
2002    impl<N: FixtureName> ReplicationRenderer for Answered<N> {}
2003    impl<N: FixtureName> StorageRenderer for Answered<N> {}
2004    impl<N: FixtureName> DialectCapabilities for Answered<N> {
2005        fn begin_leaves_the_commit_to_the_client(&self) -> bool {
2006            N::BEGIN_WITHOUT_TRANSACTIONS
2007        }
2008        fn supports_multi_statement_transactions(&self) -> bool {
2009            !N::BEGIN_WITHOUT_TRANSACTIONS
2010        }
2011        fn merge_shape(&self) -> MergeShape {
2012            MergeShape::Merge(MergeRestrictions::none())
2013        }
2014    }
2015    impl<N: FixtureName> PlatformDialect for Answered<N> {
2016        fn info(&self) -> DialectInfo {
2017            DialectInfo {
2018                name: N::NAME,
2019                display_name: "An Answered Engine",
2020                // It answers to its own name and nothing else, which is the
2021                // shape of a plugin that declares no extra spellings.
2022                aliases: &[],
2023                dialect_family: DialectFamily::Custom(N::NAME),
2024                family: "Answered",
2025                is_cloud_native: false,
2026                is_olap: false,
2027                is_postgres_compatible: false,
2028                versions: &[],
2029                deploy_script: N::DEPLOY,
2030            }
2031        }
2032    }
2033
2034    // ── The twin: a dialect that claims a name another platform answers to ──
2035    //
2036    // Answered in every other respect, so the only thing its report can be
2037    // about is the spelling it took.
2038
2039    struct Twin;
2040
2041    impl SqlRenderer for Twin {
2042        fn render_data_type(&self, dt: &DataType) -> String {
2043            razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
2044        }
2045        fn quote_identifier(&self, name: &str) -> String {
2046            format!("\"{name}\"")
2047        }
2048        fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
2049            self.quote_identifier(name)
2050        }
2051        fn render_current_timestamp(&self) -> String {
2052            "NOW()".to_owned()
2053        }
2054    }
2055    impl ExpressionRenderer for Twin {}
2056    impl DdlRenderer for Twin {}
2057    impl DmlRenderer for Twin {}
2058    impl ProcedureRenderer for Twin {}
2059    impl FormulaRenderer for Twin {}
2060    impl TaskRenderer for Twin {}
2061    impl ReplicationRenderer for Twin {}
2062    impl StorageRenderer for Twin {}
2063    impl DialectCapabilities for Twin {}
2064    impl PlatformDialect for Twin {
2065        fn info(&self) -> DialectInfo {
2066            DialectInfo {
2067                name: "twindb",
2068                display_name: "Twin DB",
2069                // The name the answered fixture already answers to.
2070                aliases: &["healthydb"],
2071                dialect_family: DialectFamily::Custom("twindb"),
2072                family: "Twin",
2073                is_cloud_native: false,
2074                is_olap: false,
2075                is_postgres_compatible: false,
2076                versions: &[],
2077                deploy_script: None,
2078            }
2079        }
2080    }
2081
2082    /// Every finding whose `what` line mentions one of these subjects.
2083    fn mentions(report: &Report, needle: &str) -> bool {
2084        report.findings.iter().any(|f| f.what.contains(needle) || f.fix.contains(needle))
2085    }
2086
2087    /// **The author's own test prints what the command prints**
2088    /// (`fr-1021-48`): what the report read, that it ran nothing on an
2089    /// engine, and the answers the dialect left to the contract.
2090    #[test]
2091    fn the_report_says_what_it_read_and_what_it_took_as_the_default() {
2092        let report = check(&BrokenPlugin);
2093        let printed = report.to_string();
2094        let first = printed.lines().next().unwrap_or_default();
2095        assert!(first.ends_with("in the answers this dialect states."), "{printed}");
2096        assert!(printed.contains("ran nothing on an engine"), "{printed}");
2097        assert!(printed.contains("Taken as the contract's default"), "{printed}");
2098        let names: Vec<&str> = report.taken_as_default.iter().map(|taken| taken.name).collect();
2099        assert!(names.contains(&"DdlRenderer::supports_if_not_exists"), "{names:?}");
2100        let view = report
2101            .taken_as_default
2102            .iter()
2103            .find(|taken| taken.name == "DdlRenderer::render_create_view_prefix")
2104            .expect("listed");
2105        assert!(view.answer.contains("CREATE OR REPLACE VIEW"), "{view:?}");
2106        assert_eq!(view.shows_in, "schema.sql");
2107        assert!(printed.contains(&view.answer), "{printed}");
2108    }
2109
2110    /// **An answer the dialect wrote is not listed**, even where it reads the
2111    /// same as the contract's: the healthy fixture writes its own transaction
2112    /// keyword.
2113    #[test]
2114    fn a_report_with_nothing_to_fix_still_says_it_ran_nothing() {
2115        let report = check(&Answered::<Outside>::new());
2116        let printed = report.to_string();
2117        assert!(printed.contains("ran nothing on an engine"), "{printed}");
2118        assert!(!printed.lines().next().unwrap_or_default().ends_with("0 to fix."), "{printed}");
2119    }
2120
2121    /// **The key's fix names what the key runs** (`fr-1021-53`): a
2122    /// replacement, a Unicode literal, a join, a cast and a 64-bit hash —
2123    /// never LOWER and TRIM, which the key no longer calls.
2124    #[test]
2125    fn a_dialect_with_no_key_spelling_is_asked_for_what_the_key_runs() {
2126        let report = check(&BrokenPlugin);
2127        let key = report
2128            .findings
2129            .iter()
2130            .find(|finding| finding.what.contains("surrogate-key spelling"))
2131            .expect("the key's finding");
2132        for words in ["a replacement and a Unicode literal", "joins strings", "casts to text"] {
2133            assert!(key.fix.contains(words), "no {words}: {}", key.fix);
2134        }
2135        assert!(!key.fix.contains("LOWER") && !key.fix.contains("TRIM"), "{}", key.fix);
2136    }
2137
2138    /// **The kit's own red.** A plugin that implements the four required
2139    /// methods and stops compiles and registers, and every one of these
2140    /// findings is a defect a shipped dialect actually had.
2141    #[test]
2142    fn the_kit_catches_a_deliberately_broken_plugin() {
2143        let report = check(&BrokenPlugin);
2144        assert!(!report.is_clean(), "the broken plugin reported clean:\n{report}");
2145
2146        assert!(mentions(&report, "does not resolve"), "unregistered:\n{report}");
2147        assert!(mentions(&report, "custom one with no name"), "unnamed family:\n{report}");
2148        assert!(mentions(&report, "render_data_type"), "empty column types:\n{report}");
2149        assert!(mentions(&report, "render_cast_type"), "empty cast types:\n{report}");
2150        assert!(mentions(&report, "identifier unchanged"), "no quoting:\n{report}");
2151        assert!(mentions(&report, "render_current_timestamp"), "no now():\n{report}");
2152        assert!(mentions(&report, "surrogate-key spelling"), "unspelled key:\n{report}");
2153        assert!(mentions(&report, "stored-procedure grammar"), "no procedure form:\n{report}");
2154        assert!(mentions(&report, "upsert shape"), "no merge shape:\n{report}");
2155        assert!(mentions(&report, "to_formula_renderer"), "formula renderer:\n{report}");
2156        assert!(mentions(&report, "supports_on_conflict"), "paired fact:\n{report}");
2157
2158        assert!(
2159            report.count(Severity::Blocking) >= 8,
2160            "the broken plugin owes more than {} blocking fixes:\n{report}",
2161            report.count(Severity::Blocking)
2162        );
2163    }
2164
2165    /// **The kit does not cry wolf.** The same plugin with its questions
2166    /// answered reports only what is actually true of it: it is not
2167    /// registered in this test binary, and nothing else.
2168    #[test]
2169    fn the_kit_reports_only_registration_on_a_plugin_that_answered_everything() {
2170        let report = check(&HealthyPlugin::new());
2171        let unregistered: Vec<&Finding> =
2172            report.findings.iter().filter(|f| f.what.contains("does not resolve")).collect();
2173        assert_eq!(unregistered.len(), 1, "the registration finding is the honest one here");
2174        assert_eq!(
2175            report.findings.len(),
2176            1,
2177            "a plugin that answered every question owes nothing else:\n{report}"
2178        );
2179    }
2180
2181    /// **A join written for a two-argument `CONCAT` is an answer, not a
2182    /// shortfall.** The report on a dialect that states it reads exactly like
2183    /// the report on a variadic one, and the key it renders nests pairwise
2184    /// instead of widening a call the engine does not have.
2185    #[test]
2186    fn the_kit_takes_a_two_argument_concat_as_an_answer_like_any_other() {
2187        let binary = Answered::<BinaryConcat>::new();
2188        let report = check(&binary);
2189        assert_eq!(
2190            report.findings.len(),
2191            check(&HealthyPlugin::new()).findings.len(),
2192            "the join form is a decision, so stating this one owes nothing extra:\n{report}"
2193        );
2194        assert!(
2195            !report.to_string().contains("joins"),
2196            "nothing about the join is outstanding:\n{report}"
2197        );
2198
2199        let key = razeri_plugin_contract::sid::sid_expression(
2200            SqlRenderer::sid_spelling(&binary),
2201            razeri_plugin_contract::sid::Backslash::of(&binary),
2202            None,
2203            &["a".to_owned(), "b".to_owned(), "c".to_owned()],
2204        );
2205        assert!(
2206            key.contains("CONCAT(CONCAT("),
2207            "a two-argument engine gets one call per pair:\n{key}"
2208        );
2209    }
2210
2211    /// **A join written with an operator is an answer too**, and the key it
2212    /// renders is one expression with the operator between each part and the
2213    /// separator.
2214    #[test]
2215    fn the_kit_takes_an_operator_join_as_an_answer_like_any_other() {
2216        let operator = Answered::<OperatorConcat>::new();
2217        let report = check(&operator);
2218        assert_eq!(
2219            report.findings.len(),
2220            check(&HealthyPlugin::new()).findings.len(),
2221            "the join form is a decision, so stating this one owes nothing extra:\n{report}"
2222        );
2223        let key = razeri_plugin_contract::sid::sid_expression(
2224            SqlRenderer::sid_spelling(&operator),
2225            razeri_plugin_contract::sid::Backslash::of(&operator),
2226            None,
2227            &["a".to_owned(), "b".to_owned()],
2228        );
2229        assert!(key.contains(" || '|' || "), "the operator joins each part:\n{key}");
2230        assert!(!key.contains("CONCAT"), "an operator engine calls no function:\n{key}");
2231    }
2232
2233    /// **A join that names nothing is refused**, because the key it writes is
2234    /// one the engine cannot parse.
2235    #[test]
2236    fn a_join_that_names_nothing_must_be_fixed() {
2237        let report = check(&Answered::<NamelessConcat>::new());
2238        assert!(
2239            report.findings.iter().any(|finding| finding.severity == Severity::Blocking
2240                && finding.what.contains("joins the parts of a composite key")),
2241            "{report}"
2242        );
2243        assert!(
2244            !check(&Answered::<OperatorConcat>::new())
2245                .findings
2246                .iter()
2247                .any(|finding| finding.what.contains("joins the parts of a composite key")),
2248            "a named operator is not the finding"
2249        );
2250    }
2251
2252    /// **An operator the engine lacks is answered `None`, and that is an
2253    /// answer**; an operator answered with no text is the finding, because it
2254    /// writes two operands side by side.
2255    #[test]
2256    fn an_operator_is_answered_none_where_the_engine_lacks_it_and_never_blank() {
2257        let none = check(&Answered::<NoPowerOperator>::new());
2258        assert_eq!(
2259            none.findings.len(),
2260            check(&HealthyPlugin::new()).findings.len(),
2261            "saying the engine has no such operator owes nothing:\n{none}"
2262        );
2263        let blank = check(&Answered::<BlankPowerOperator>::new());
2264        assert!(
2265            blank.findings.iter().any(|finding| finding.severity == Severity::Blocking
2266                && finding.what.contains("render_power_operator")),
2267            "{blank}"
2268        );
2269    }
2270
2271    /// **A bitwise operator the engine lacks is answered `None`, and that is
2272    /// an answer** (`fr-1018-121`); one answered with no text is the finding.
2273    #[test]
2274    fn a_bitwise_operator_is_answered_none_where_the_engine_lacks_it_and_never_blank() {
2275        let none = check(&Answered::<NoShiftOperator>::new());
2276        assert_eq!(
2277            none.findings.len(),
2278            check(&HealthyPlugin::new()).findings.len(),
2279            "saying the engine has no left shift owes nothing:\n{none}"
2280        );
2281        let blank = check(&Answered::<BlankShiftOperator>::new());
2282        assert!(
2283            blank.findings.iter().any(|finding| finding.severity == Severity::Blocking
2284                && finding.what.contains("render_bitwise_operator(ShiftLeft)")),
2285            "{blank}"
2286        );
2287    }
2288
2289    /// **A column drop that loses the column it was handed is the finding**
2290    /// (`fr-1018-84`); the healthy fixture's drop carries it.
2291    #[test]
2292    fn a_drop_that_loses_its_column_must_be_fixed() {
2293        let healthy = check(&HealthyPlugin::new());
2294        assert!(!healthy.to_string().contains("render_drop_column"), "{healthy}");
2295        let lost = check(&Answered::<DropLosesItsColumn>::new());
2296        assert!(
2297            lost.findings.iter().any(|finding| finding.severity == Severity::Blocking
2298                && finding.what.contains("render_drop_column")),
2299            "{lost}"
2300        );
2301    }
2302
2303    /// **A comparison that loses the value it stands for is the finding**
2304    /// (`fr-1019-71`).
2305    #[test]
2306    fn a_comparison_that_loses_its_value_must_be_fixed() {
2307        assert!(!check(&HealthyPlugin::new()).to_string().contains("render_comparable"));
2308        let report = check(&Answered::<ComparesSomethingElse>::new());
2309        assert!(
2310            report.findings.iter().any(|finding| finding.severity == Severity::Blocking
2311                && finding.what.contains("render_comparable")),
2312            "{report}"
2313        );
2314    }
2315
2316    /// **A begin that leaves the commit to a client, on an engine with no
2317    /// transaction spanning statements, is two answers that disagree**
2318    /// (`fr-1019-62`).
2319    #[test]
2320    fn a_begin_that_leaves_the_commit_needs_a_transaction() {
2321        let report = check(&Answered::<BeginWithoutTransactions>::new());
2322        assert!(
2323            report.findings.iter().any(|finding| finding.severity == Severity::Blocking
2324                && finding.what.contains("leaves the commit to the client")),
2325            "{report}"
2326        );
2327    }
2328
2329    /// **A block terminator with a blank part is the finding** (`fr-1016-28`).
2330    #[test]
2331    fn a_block_terminator_with_a_blank_part_must_be_fixed() {
2332        let report = check(&Answered::<BlankBlockEnd>::new());
2333        assert!(
2334            report.findings.iter().any(|finding| finding.severity == Severity::Blocking
2335                && finding.what.contains("block terminator")),
2336            "{report}"
2337        );
2338    }
2339
2340    /// **A described deploy client is an answer; one that is never told which
2341    /// file to run is the finding.**
2342    #[test]
2343    fn a_deploy_client_has_to_be_told_which_file_to_run() {
2344        let described = check(&Answered::<DescribedClient>::new());
2345        assert_eq!(
2346            described.findings.len(),
2347            check(&HealthyPlugin::new()).findings.len(),
2348            "a client described in full owes nothing:\n{described}"
2349        );
2350        let fileless = check(&Answered::<FilelessClient>::new());
2351        assert!(
2352            fileless.findings.iter().any(|finding| finding.severity == Severity::Blocking
2353                && finding.what.contains("run_file never names the file")),
2354            "{fileless}"
2355        );
2356    }
2357
2358    /// **A fold has to agree with `qualify_name`, and is for an engine with no
2359    /// schemas.** `SCHEMAS`: what the engine says about schemas. `AGREES`:
2360    /// whether `qualify_name` answers the folded name.
2361    #[test]
2362    fn a_schema_fold_agrees_with_qualify_name_on_an_engine_with_no_schemas() {
2363        struct Folder<const SCHEMAS: bool, const AGREES: bool>;
2364        impl<const SCHEMAS: bool, const AGREES: bool> SqlRenderer for Folder<SCHEMAS, AGREES> {
2365            fn render_data_type(&self, dt: &DataType) -> String {
2366                razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
2367            }
2368            fn quote_identifier(&self, name: &str) -> String {
2369                format!("\"{name}\"")
2370            }
2371            fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
2372                match schema {
2373                    Some(schema) if AGREES => self.quote_identifier(&format!("{schema}_{name}")),
2374                    Some(schema) => format!("{schema}.{}", self.quote_identifier(name)),
2375                    None => self.quote_identifier(name),
2376                }
2377            }
2378            fn render_current_timestamp(&self) -> String {
2379                "CURRENT_TIMESTAMP".to_owned()
2380            }
2381            fn fold_schema_into_name(&self, schema: &str, name: &str) -> Option<String> {
2382                Some(format!("{schema}_{name}"))
2383            }
2384        }
2385        impl<const S: bool, const A: bool> ExpressionRenderer for Folder<S, A> {}
2386        impl<const S: bool, const A: bool> DdlRenderer for Folder<S, A> {}
2387        impl<const S: bool, const A: bool> DmlRenderer for Folder<S, A> {}
2388        impl<const S: bool, const A: bool> ProcedureRenderer for Folder<S, A> {}
2389        impl<const S: bool, const A: bool> FormulaRenderer for Folder<S, A> {}
2390        impl<const S: bool, const A: bool> TaskRenderer for Folder<S, A> {}
2391        impl<const S: bool, const A: bool> ReplicationRenderer for Folder<S, A> {}
2392        impl<const S: bool, const A: bool> StorageRenderer for Folder<S, A> {}
2393        impl<const S: bool, const A: bool> DialectCapabilities for Folder<S, A> {
2394            fn supports_schemas(&self) -> bool {
2395                S
2396            }
2397        }
2398        impl<const S: bool, const A: bool> PlatformDialect for Folder<S, A> {
2399            fn info(&self) -> DialectInfo {
2400                DialectInfo {
2401                    name: "folderdb",
2402                    display_name: "Folder DB",
2403                    aliases: &[],
2404                    dialect_family: DialectFamily::Custom("folderdb"),
2405                    family: "Folder",
2406                    is_cloud_native: false,
2407                    is_olap: false,
2408                    is_postgres_compatible: false,
2409                    versions: &[],
2410                    deploy_script: None,
2411                }
2412            }
2413        }
2414
2415        let fold_findings = |dialect: &dyn PlatformDialect| {
2416            let mut findings = Vec::new();
2417            check_schema_fold(dialect, &mut findings);
2418            findings
2419        };
2420        assert!(fold_findings(&Folder::<false, true>).is_empty(), "a fold kept everywhere");
2421        let disagrees = fold_findings(&Folder::<false, false>);
2422        assert_eq!(disagrees.len(), 1, "{disagrees:?}");
2423        assert!(disagrees[0].what.contains("`qualify_name` names"), "{disagrees:?}");
2424        let has_schemas = fold_findings(&Folder::<true, true>);
2425        assert_eq!(has_schemas.len(), 1, "{has_schemas:?}");
2426        assert!(has_schemas[0].what.contains("says has schemas"), "{has_schemas:?}");
2427    }
2428
2429    /// **A stated `MERGE` restriction is reported; a default one is not.**
2430    ///
2431    /// The asymmetry is the point. A dialect that says its planner needs a
2432    /// literal slice gets Razeri's plan for that answer back, while the engine
2433    /// it is describing is still in front of the author. A dialect that has
2434    /// said nothing gets nothing, because the kit cannot tell a measured
2435    /// *"a parameter is fine here"* from a question never asked, and a finding
2436    /// made out of that silence would fire on every dialect alike.
2437    #[test]
2438    fn a_stated_merge_restriction_is_reported_and_a_default_one_is_not() {
2439        let mut quiet = Vec::new();
2440        check_merge_restrictions(MergeRestrictions::none(), &mut quiet);
2441        assert!(quiet.is_empty(), "a dialect with no stated restriction is asked nothing");
2442
2443        let mut stated = Vec::new();
2444        check_merge_restrictions(MergeRestrictions::requiring_a_literal_slice(), &mut stated);
2445        assert_eq!(stated.len(), 1, "the stated restriction is reported once");
2446        assert_eq!(stated[0].severity, Severity::Note, "nothing is broken; it is worth a look");
2447        assert!(
2448            stated[0].what.contains("literal"),
2449            "the finding names the restriction:\n{}",
2450            stated[0].what
2451        );
2452        assert!(
2453            stated[0].fix.contains("dynamic-execution"),
2454            "and says what Razeri does with the answer:\n{}",
2455            stated[0].fix
2456        );
2457
2458        // The other restriction travels on the same struct and must not drag
2459        // the new finding along with it.
2460        let mut two_clauses = Vec::new();
2461        check_merge_restrictions(MergeRestrictions::requiring_two_when_clauses(), &mut two_clauses);
2462        assert!(two_clauses.is_empty(), "one restriction is not the other");
2463    }
2464
2465    /// **A dialect written outside Razeri reaches a clean report.** It is
2466    /// reached the way every out-of-tree dialect is reached — it registered, and
2467    /// the resolver reads the loaded dialects' own declared spellings — so there
2468    /// is nothing for Razeri to be missing it from and nothing for the report to
2469    /// ask of its author.
2470    #[test]
2471    fn a_dialect_registered_under_its_own_name_reaches_a_clean_report() {
2472        assert!(
2473            crate::resolve_dialect_by_name(Outside::NAME).is_ok(),
2474            "the fixture registers through the registry, which is the whole path being graded"
2475        );
2476        // The precondition that used to read "no row in Razeri's table": no
2477        // other loaded platform declares this name, so the fixture is reached
2478        // only because it registered and said so itself.
2479        let registry = crate::dialect::PlatformRegistry::with_auto_discovered();
2480        assert!(
2481            registry
2482                .list()
2483                .iter()
2484                .filter(|info| info.name != Outside::NAME)
2485                .all(|info| !info.answers_to(Outside::NAME)),
2486            "the fixture's name must be one no other platform claims"
2487        );
2488
2489        let report = check(&OutsidePlugin::new());
2490        assert!(report.findings.is_empty(), "nothing is owed here:\n{report}");
2491        assert!(report.is_clean(), "and the report says so:\n{report}");
2492        assert_eq!(report.count(Severity::Blocking), 0, "{report}");
2493        assert!(
2494            report.to_string().contains("nothing to fix"),
2495            "a clean dialect is told it is clean:\n{report}"
2496        );
2497    }
2498
2499    /// **A platform cannot be reachable under an alias but not under its own
2500    /// name.** A dialect declares its own spellings and its own name leads
2501    /// them, so a platform reachable as `mynew_db` and never as `mynewdb`
2502    /// cannot be written down — and this is the assertion that keeps it that
2503    /// way.
2504    #[test]
2505    fn a_platform_is_never_reachable_by_an_alias_but_not_by_its_own_name() {
2506        let registry = crate::dialect::PlatformRegistry::with_auto_discovered();
2507        for info in registry.list() {
2508            assert_eq!(
2509                info.spellings().first().copied(),
2510                Some(info.name),
2511                "a platform's own name leads its spellings"
2512            );
2513            assert!(info.answers_to(info.name), "{} answers to its own name", info.name);
2514        }
2515    }
2516
2517    /// **A name another platform already answers to is a collision, not a
2518    /// registration.** A dialect claiming a spelling Healthy DB answers to is
2519    /// named as the collision it is — with both platforms named, and a fix its
2520    /// author can actually perform — rather than being reported as an
2521    /// unregistered platform, which is a different problem with a different fix.
2522    #[test]
2523    fn a_name_razeri_reads_as_another_platform_is_blocking_and_says_which() {
2524        let mut registry = crate::dialect::PlatformRegistry::new();
2525        registry.register("healthydb".to_owned(), std::sync::Arc::new(HealthyPlugin::new()));
2526        registry.register("twindb".to_owned(), std::sync::Arc::new(Twin));
2527
2528        let report = check_with_registry(&Twin, &registry);
2529        let collision = report
2530            .findings
2531            .iter()
2532            .find(|f| f.what.contains("claimed by more than one loaded platform"))
2533            .unwrap_or_else(|| panic!("the collision is reported:\n{report}"));
2534        assert_eq!(collision.severity, Severity::Blocking, "{collision:?}");
2535        assert!(collision.what.contains("healthydb"), "the other platform is named: {collision:?}");
2536        assert!(collision.what.contains("twindb"), "{collision:?}");
2537        assert!(collision.fix.contains("name no other platform answers to"), "{collision:?}");
2538        assert!(
2539            !mentions(&report, "does not resolve"),
2540            "a collision is not an unregistered platform:\n{report}"
2541        );
2542    }
2543
2544    /// A platform reached under its own name owes nothing, whatever the case or
2545    /// the surrounding whitespace, and a name nothing has ever heard of is
2546    /// simply unknown rather than a finding against this dialect.
2547    #[test]
2548    fn registration_is_silent_on_a_platform_reached_under_its_own_name() {
2549        let mut registry = crate::dialect::PlatformRegistry::new();
2550        registry.register("healthydb".to_owned(), std::sync::Arc::new(HealthyPlugin::new()));
2551
2552        let mut findings = Vec::new();
2553        check_registration(&HealthyPlugin::new().info(), &registry, &mut findings);
2554        assert!(findings.is_empty(), "{findings:?}");
2555
2556        for spelling in ["healthydb", "HealthyDB", "  healthydb  "] {
2557            assert!(
2558                crate::resolve::resolve_dialect_by_name_with_registry(spelling, &registry).is_ok(),
2559                "'{spelling}' is the same platform"
2560            );
2561        }
2562        assert!(
2563            crate::resolve::resolve_dialect_by_name_with_registry("nosuchdb", &registry).is_err()
2564        );
2565    }
2566
2567    /// **A dialect the host loaded at run time can be graded at all.** [`check`]
2568    /// asks the dialects linked into this program, which one loaded from a
2569    /// shared library is not among; [`check_with_registry`] asks the registry it
2570    /// was loaded into, and the registration judgement is answered from there.
2571    #[test]
2572    fn a_dialect_the_host_loaded_reports_clean_against_its_own_registry() {
2573        let mut registry = crate::dialect::PlatformRegistry::new();
2574        registry.register("healthydb".to_owned(), std::sync::Arc::new(HealthyPlugin::new()));
2575
2576        let report = check_with_registry(&HealthyPlugin::new(), &registry);
2577        assert!(
2578            report.is_clean(),
2579            "a loaded dialect that answered everything owes nothing:\n{report}"
2580        );
2581    }
2582
2583    /// **Every fix an outside author can read is a fix in their own crate.** A
2584    /// report that names a file inside Razeri is telling an author to edit a
2585    /// tree they do not have, and the fix cannot be performed at all.
2586    #[test]
2587    fn no_fix_line_sends_an_author_into_razeris_own_tree() {
2588        let mut collided = crate::dialect::PlatformRegistry::new();
2589        collided.register("healthydb".to_owned(), std::sync::Arc::new(HealthyPlugin::new()));
2590        collided.register("twindb".to_owned(), std::sync::Arc::new(Twin));
2591
2592        let mut fixes: Vec<String> = Vec::new();
2593        for report in [
2594            check(&BrokenPlugin),
2595            check(&HealthyPlugin::new()),
2596            check(&OutsidePlugin::new()),
2597            // The collision and the unregistered-name judgements, which are the
2598            // two registration findings an author can actually reach.
2599            check_with_registry(&Twin, &collided),
2600            check_with_registry(&Twin, &crate::dialect::PlatformRegistry::new()),
2601        ] {
2602            fixes.extend(report.findings.iter().map(|f| f.fix.clone()));
2603        }
2604        assert!(fixes.len() >= 10, "the sweep reached the findings: {}", fixes.len());
2605        for fix in &fixes {
2606            for path in ["schemas/", "crates/", ".json", "scripts/", "razeri-design"] {
2607                assert!(
2608                    !fix.contains(path),
2609                    "a fix line names `{path}`, which is not in the author's crate:\n  {fix}"
2610                );
2611            }
2612        }
2613    }
2614
2615    /// **No finding prints a run of spaces in the middle of a sentence.** A
2616    /// string literal broken across source lines without a `\` keeps the next
2617    /// line's indentation, and the report then reads "the same as a", a run of
2618    /// eighteen spaces, then "column". This reaches every finding the fixtures
2619    /// can reach, plus the four that only a dialect declining every column
2620    /// change and spelling its own routine grammar can.
2621    #[test]
2622    fn no_finding_holds_a_run_of_spaces() {
2623        struct Declining;
2624        impl SqlRenderer for Declining {
2625            fn render_data_type(&self, dt: &DataType) -> String {
2626                razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
2627            }
2628            fn quote_identifier(&self, name: &str) -> String {
2629                format!("\"{name}\"")
2630            }
2631            fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
2632                name.to_owned()
2633            }
2634            fn render_current_timestamp(&self) -> String {
2635                "CURRENT_TIMESTAMP".to_owned()
2636            }
2637            fn procedure_form(&self) -> ProcedureForm {
2638                ProcedureForm::Custom("Declining PSQL")
2639            }
2640        }
2641        impl ExpressionRenderer for Declining {}
2642        impl DdlRenderer for Declining {
2643            fn render_column_evolution(&self, _change: &ColumnEvolution<'_>) -> Option<String> {
2644                None
2645            }
2646        }
2647        impl DialectCapabilities for Declining {
2648            fn evolution_answers(&self) -> razeri_plugin_contract::EvolutionAnswers {
2649                razeri_plugin_contract::EvolutionAnswers::widening_a_string_in_place()
2650                    .and_a_nested_field()
2651            }
2652        }
2653        impl DmlRenderer for Declining {}
2654        impl ProcedureRenderer for Declining {}
2655        impl FormulaRenderer for Declining {}
2656        impl TaskRenderer for Declining {}
2657        impl ReplicationRenderer for Declining {}
2658        impl StorageRenderer for Declining {}
2659        impl PlatformDialect for Declining {
2660            fn info(&self) -> DialectInfo {
2661                DialectInfo {
2662                    name: "decliningdb",
2663                    display_name: "Declining DB",
2664                    aliases: &[],
2665                    dialect_family: DialectFamily::Custom("decliningdb"),
2666                    family: "Declining",
2667                    is_cloud_native: false,
2668                    is_olap: false,
2669                    is_postgres_compatible: false,
2670                    versions: &[],
2671                    deploy_script: None,
2672                }
2673            }
2674        }
2675
2676        let mut findings = Vec::new();
2677        check_evolution(&Declining, &mut findings);
2678        check_parameter_type_spelling(&Declining, &mut findings);
2679        assert_eq!(findings.len(), 4, "every column change and the parameter note: {findings:?}");
2680
2681        for report in [
2682            check(&BrokenPlugin),
2683            check(&HealthyPlugin::new()),
2684            check(&OutsidePlugin::new()),
2685            check(&Declining),
2686            check_with_registry(&Twin, &crate::dialect::PlatformRegistry::new()),
2687        ] {
2688            findings.extend(report.findings);
2689        }
2690        for finding in &findings {
2691            for text in [&finding.what, &finding.fix] {
2692                assert!(!text.contains("  "), "a finding holds a run of spaces:\n  {text:?}");
2693            }
2694        }
2695    }
2696
2697    /// **A dialect that claims its own grammar and does not spell it is
2698    /// blocking**, and the finding names the method it owes.
2699    ///
2700    /// `Custom` is a promise that the dialect renders the routine itself, and
2701    /// Razeri keeps its side by writing nothing: no near-neighbour grammar,
2702    /// which fails on deploy, and no refusal, which would tell an author their
2703    /// engine has no routines when it has a whole language. A promise with
2704    /// nothing behind it is therefore a build that stops, and it has to be
2705    /// findable before the deploy rather than during it.
2706    #[test]
2707    fn a_custom_grammar_without_a_render_method_is_blocking_on_all_three_kinds() {
2708        for (kind, form_method, render_method) in [
2709            (RoutineKind::Procedure, "procedure_form", "render_procedure"),
2710            (RoutineKind::ScalarFunction, "scalar_function_form", "render_scalar_function"),
2711            (RoutineKind::TableFunction, "table_function_form", "render_table_function"),
2712        ] {
2713            let mut promised = Vec::new();
2714            check_custom_grammar(
2715                CustomGrammar {
2716                    kind,
2717                    grammar: "PL/SQL",
2718                    form_method,
2719                    render_method,
2720                    noun: "routines",
2721                },
2722                |_| None,
2723                &mut promised,
2724            );
2725            assert_eq!(promised.len(), 1, "{form_method}: {promised:?}");
2726            assert_eq!(promised[0].severity, Severity::Blocking, "{promised:?}");
2727            assert!(promised[0].what.contains(form_method), "{promised:?}");
2728            assert!(promised[0].what.contains("PL/SQL"), "{promised:?}");
2729            assert!(promised[0].fix.contains(render_method), "{promised:?}");
2730
2731            // The same claim, kept: nothing to report.
2732            let mut kept = Vec::new();
2733            check_custom_grammar(
2734                CustomGrammar {
2735                    kind,
2736                    grammar: "PL/SQL",
2737                    form_method,
2738                    render_method,
2739                    noun: "routines",
2740                },
2741                |spec| Some(format!("CREATE {} …", spec.name)),
2742                &mut kept,
2743            );
2744            assert!(kept.is_empty(), "{form_method}: a kept promise is not a finding: {kept:?}");
2745        }
2746    }
2747
2748    /// **The two answers about stored procedures have to agree.** A dialect
2749    /// that writes its own procedures and leaves the capability at its default
2750    /// `false` gets no load written as one; a dialect that says its engine has
2751    /// them and refuses to write one says both things at once.
2752    #[test]
2753    fn a_procedure_form_and_the_procedure_capability_must_agree() {
2754        fn check_forms(dialect: &dyn PlatformDialect) -> Report {
2755            let mut findings = Vec::new();
2756            check_routine_forms(dialect, &mut findings);
2757            Report { dialect: "claimsdb".to_owned(), findings, taken_as_default: Vec::new() }
2758        }
2759
2760        /// `CUSTOM`: the form spells its own grammar, or refuses. `HAS`: the
2761        /// capability's answer.
2762        struct Claims<const CUSTOM: bool, const HAS: bool>;
2763        impl<const CUSTOM: bool, const HAS: bool> SqlRenderer for Claims<CUSTOM, HAS> {
2764            fn render_data_type(&self, dt: &DataType) -> String {
2765                razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
2766            }
2767            fn quote_identifier(&self, name: &str) -> String {
2768                format!("\"{name}\"")
2769            }
2770            fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
2771                self.quote_identifier(name)
2772            }
2773            fn render_current_timestamp(&self) -> String {
2774                "CURRENT_TIMESTAMP".to_owned()
2775            }
2776            fn procedure_form(&self) -> ProcedureForm {
2777                if CUSTOM {
2778                    ProcedureForm::Custom("Firebird PSQL")
2779                } else {
2780                    ProcedureForm::Unsupported(
2781                        "This engine has no stored procedures; schedule the load as a query.",
2782                    )
2783                }
2784            }
2785            fn render_procedure(&self, spec: &RoutineSpec) -> Option<String> {
2786                Some(format!("CREATE PROCEDURE {} AS BEGIN END", spec.name))
2787            }
2788        }
2789        impl<const CUSTOM: bool, const HAS: bool> ExpressionRenderer for Claims<CUSTOM, HAS> {}
2790        impl<const CUSTOM: bool, const HAS: bool> DdlRenderer for Claims<CUSTOM, HAS> {}
2791        impl<const CUSTOM: bool, const HAS: bool> DmlRenderer for Claims<CUSTOM, HAS> {}
2792        impl<const CUSTOM: bool, const HAS: bool> ProcedureRenderer for Claims<CUSTOM, HAS> {}
2793        impl<const CUSTOM: bool, const HAS: bool> FormulaRenderer for Claims<CUSTOM, HAS> {}
2794        impl<const CUSTOM: bool, const HAS: bool> TaskRenderer for Claims<CUSTOM, HAS> {}
2795        impl<const CUSTOM: bool, const HAS: bool> ReplicationRenderer for Claims<CUSTOM, HAS> {}
2796        impl<const CUSTOM: bool, const HAS: bool> StorageRenderer for Claims<CUSTOM, HAS> {}
2797        impl<const CUSTOM: bool, const HAS: bool> DialectCapabilities for Claims<CUSTOM, HAS> {
2798            fn supports_stored_procedures(&self) -> bool {
2799                HAS
2800            }
2801        }
2802        impl<const CUSTOM: bool, const HAS: bool> PlatformDialect for Claims<CUSTOM, HAS> {
2803            fn info(&self) -> DialectInfo {
2804                DialectInfo {
2805                    name: "claimsdb",
2806                    display_name: "Claims DB",
2807                    aliases: &[],
2808                    dialect_family: DialectFamily::Custom("claimsdb"),
2809                    family: "Claims",
2810                    is_cloud_native: false,
2811                    is_olap: false,
2812                    is_postgres_compatible: false,
2813                    versions: &[],
2814                    deploy_script: None,
2815                }
2816            }
2817        }
2818
2819        let disagreement = |report: &Report| {
2820            report
2821                .findings
2822                .iter()
2823                .filter(|finding| {
2824                    finding.severity == Severity::Blocking
2825                        && (finding.what.contains("says its engine has none")
2826                            || finding.what.contains("refuses to write one"))
2827                })
2828                .count()
2829        };
2830        let mut findings = Vec::new();
2831        check_routine_forms(&Claims::<true, false>, &mut findings);
2832        let report =
2833            Report { dialect: "claimsdb".to_owned(), findings, taken_as_default: Vec::new() };
2834        assert_eq!(disagreement(&report), 1, "{report}");
2835        assert!(report.to_string().contains("supports_stored_procedures"), "{report}");
2836
2837        for (agrees, label) in [
2838            (check_forms(&Claims::<true, true>), "spelled and used"),
2839            (check_forms(&Claims::<false, false>), "refused and absent"),
2840        ] {
2841            assert_eq!(disagreement(&agrees), 0, "{label}: {agrees}");
2842        }
2843        assert_eq!(disagreement(&check_forms(&Claims::<false, true>)), 1, "refused and claimed");
2844    }
2845
2846    /// **A render method that answers with nothing at all is the same defect.**
2847    ///
2848    /// An override that returns an empty string is a routine razeri would emit
2849    /// as blank space in the middle of a schema, which is worse than an error:
2850    /// nothing in the deploy says anything is missing.
2851    #[test]
2852    fn a_custom_render_method_that_returns_nothing_is_blocking() {
2853        let mut findings = Vec::new();
2854        check_custom_grammar(
2855            CustomGrammar {
2856                kind: RoutineKind::Procedure,
2857                grammar: "PL/SQL",
2858                form_method: "procedure_form",
2859                render_method: "render_procedure",
2860                noun: "procedures",
2861            },
2862            |_| Some("   \n".to_owned()),
2863            &mut findings,
2864        );
2865        assert_eq!(findings.len(), 1, "{findings:?}");
2866        assert_eq!(findings[0].severity, Severity::Blocking, "{findings:?}");
2867    }
2868
2869    /// **A `Custom` grammar with no name gives a reader nothing to read.**
2870    #[test]
2871    fn a_custom_grammar_with_no_name_is_blocking() {
2872        let mut findings = Vec::new();
2873        check_custom_grammar(
2874            CustomGrammar {
2875                kind: RoutineKind::ScalarFunction,
2876                grammar: "  ",
2877                form_method: "scalar_function_form",
2878                render_method: "render_scalar_function",
2879                noun: "scalar functions",
2880            },
2881            |spec| Some(format!("CREATE FUNCTION {}", spec.name)),
2882            &mut findings,
2883        );
2884        assert_eq!(findings.len(), 1, "{findings:?}");
2885        assert!(findings[0].what.contains("names no grammar"), "{findings:?}");
2886    }
2887
2888    /// **A stated fact that is empty, and a stated fact that ignores its
2889    /// argument.**
2890    ///
2891    /// Both answers deploy without an error and are wrong in the data: an empty
2892    /// helper body keys every row to nothing, and a file relation that drops
2893    /// its path reads one file for every entity a design binds. Neither is
2894    /// visible anywhere else, which is why the kit grades them.
2895    #[test]
2896    fn a_stated_key_body_that_is_blank_and_a_file_relation_that_drops_its_path_are_blocking() {
2897        struct Overstated;
2898        impl SqlRenderer for Overstated {
2899            fn render_data_type(&self, dt: &DataType) -> String {
2900                razeri_plugin_contract::agnostic::render_data_type_ansi(dt)
2901            }
2902            fn quote_identifier(&self, name: &str) -> String {
2903                format!("\"{name}\"")
2904            }
2905            fn qualify_name(&self, _schema: Option<&str>, name: &str) -> String {
2906                name.to_owned()
2907            }
2908            fn render_current_timestamp(&self) -> String {
2909                "CURRENT_TIMESTAMP".to_owned()
2910            }
2911            fn dialect_name(&self) -> &'static str {
2912                "overstateddb"
2913            }
2914            fn sid_helper_body(&self) -> Option<razeri_plugin_contract::SidHelperBody> {
2915                Some(razeri_plugin_contract::SidHelperBody {
2916                    language: razeri_plugin_contract::SidHelperLanguage::JavaScript,
2917                    body: "   \n  ",
2918                })
2919            }
2920            fn delimited_file_relation(&self, _path_literal: &str) -> Option<String> {
2921                Some("read_csv_auto('/tmp/whatever.csv')".to_owned())
2922            }
2923        }
2924        impl ExpressionRenderer for Overstated {}
2925        impl DdlRenderer for Overstated {}
2926        impl DmlRenderer for Overstated {}
2927        impl ProcedureRenderer for Overstated {}
2928        impl FormulaRenderer for Overstated {}
2929        impl TaskRenderer for Overstated {}
2930        impl ReplicationRenderer for Overstated {}
2931        impl StorageRenderer for Overstated {}
2932        impl DialectCapabilities for Overstated {}
2933        impl PlatformDialect for Overstated {
2934            fn info(&self) -> DialectInfo {
2935                DialectInfo {
2936                    name: "overstateddb",
2937                    display_name: "Overstated DB",
2938                    aliases: &[],
2939                    dialect_family: DialectFamily::Custom(""),
2940                    family: "Overstated",
2941                    is_cloud_native: false,
2942                    is_olap: false,
2943                    is_postgres_compatible: false,
2944                    versions: &[],
2945                    deploy_script: None,
2946                }
2947            }
2948        }
2949
2950        let report = check(&Overstated);
2951        for (fragment, why) in [
2952            ("supplies an empty one", "a blank helper body"),
2953            ("does not carry the path", "a file relation that drops its path"),
2954        ] {
2955            let found = report
2956                .findings
2957                .iter()
2958                .find(|f| f.what.contains(fragment))
2959                .unwrap_or_else(|| panic!("{why} is not graded:\n{report}"));
2960            assert_eq!(found.severity, Severity::Blocking, "{why}: {found:?}");
2961        }
2962
2963        // And silence is not a finding. The fully-answered fixture states
2964        // neither fact — the majority answer — and owes nothing for it.
2965        let quiet = check(&HealthyPlugin::new());
2966        for fragment in ["supplies an empty one", "does not carry the path"] {
2967            assert!(
2968                !quiet.findings.iter().any(|f| f.what.contains(fragment)),
2969                "silence is the default and owes nothing:\n{quiet}"
2970            );
2971        }
2972    }
2973
2974    /// **A stated refusal is a claim, and a claim owes the reader words** — the
2975    /// same grading every other refusal gets, because these words are the only
2976    /// thing an operator finds where the load would have been.
2977    #[test]
2978    fn a_stated_upsert_refusal_is_graded_as_copy_and_a_silent_one_as_unanswered() {
2979        let mut mute = Vec::new();
2980        check_refusal_copy("the upsert refusal", "no merge", &mut mute);
2981        assert_eq!(mute.len(), 1, "a three-word refusal is a wall: {mute:?}");
2982        assert!(mute[0].what.contains("the upsert refusal"), "{mute:?}");
2983
2984        let silence = check(&BrokenPlugin);
2985        assert!(
2986            silence
2987                .findings
2988                .iter()
2989                .any(|f| f.severity == Severity::Unanswered && f.what.contains("upsert shape")),
2990            "a dialect that never answered is unanswered, not wrong:\n{silence}"
2991        );
2992        assert!(
2993            silence.findings.iter().any(|f| f.fix.contains("MergeShape::Unsupported")),
2994            "the fix line names the way to state a measured refusal:\n{silence}"
2995        );
2996    }
2997
2998    /// The report leads with what to fix and says it in words a reader can
2999    /// act on — no identifiers from Razeri's own record-keeping, and a
3000    /// one-line count before the detail.
3001    #[test]
3002    fn the_report_reads_as_a_summary_then_a_fix_list() {
3003        let text = check(&BrokenPlugin).to_string();
3004        let first = text.lines().next().expect("a summary line");
3005        assert!(first.starts_with("brokendb:"), "{first}");
3006        assert!(first.contains("to fix"), "{first}");
3007        assert!(text.contains("      → "), "every finding names the fix:\n{text}");
3008    }
3009}