Skip to main content

razeri_plugin_contract/
replication.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//! Replication rendering traits with ANSI defaults.
6//!
7//! [`ReplicationRenderer`] extends [`SqlRenderer`] with methods for
8//! SID (surrogate ID) function generation, data extraction, data loading, and
9//! checksum validation. Each dialect crate overrides these methods to produce
10//! platform-native SQL.
11//!
12//! ## Format names
13//!
14//! Methods that accept a `format` parameter use well-known string identifiers:
15//!
16//! | Name | Description |
17//! |------|-------------|
18//! | `"csv"` | Comma-separated values |
19//! | `"parquet"` | Apache Parquet columnar format |
20//! | `"json_lines"` | JSON Lines (one object per line) |
21//! | `"native"` | Platform-native binary format |
22
23use crate::SqlRenderer;
24
25// ════════════════════════════════════════════════════════════════════════
26// SID Prerequisites — the statement boundary
27// ════════════════════════════════════════════════════════════════════════
28
29/// **The line a dialect writes between two independently-executable statements
30/// inside [`ReplicationRenderer::sid_prerequisites`].**
31///
32/// A prerequisite script is mostly prose — the `MariaDB` C source and the SQL
33/// Server C# are emitted as comment blocks for an operator to compile — but two
34/// arms emit real DDL a machine must run one statement at a time: Snowflake's
35/// JavaScript UDF plus its SQL wrapper, and Databricks' Python UDF. Neither can
36/// be recovered by splitting on `;`, because **both bodies contain
37/// semicolons**: a JavaScript function body is nothing but semicolons.
38///
39/// So the boundary is declared rather than inferred. The delimiter is a SQL line
40/// comment, so a script carrying it is still one paste-able file for a human
41/// operator, and [`ReplicationRenderer::sid_prerequisite_statements`] is the one
42/// splitter — a consumer that re-derived the boundary would be a second
43/// definition of it, and a second definition is how the two drift apart. Do not
44/// write your own splitter; split on this constant or call the trait method.
45pub const SID_PREREQUISITE_STATEMENT_DELIMITER: &str =
46    "-- ──── RAZERI SID PREREQUISITE STATEMENT ────";
47
48/// **The input every generated prerequisite probe asks about.**
49///
50/// One word, and it is the one [`ReplicationRenderer::sid_validation_query`]
51/// already puts in its `SELECT`. It lives here because three producers must
52/// agree on it and they live in different crates: the dialect writing the
53/// operator's instructions, the generator writing the deploy script's
54/// comparison, and the validation query itself. A probe that asked about one
55/// word while the instructions promised another would be a second, hand-spelled
56/// variant of the same fact — the kind of duplicate that drifts unnoticed.
57pub const SID_PROBE_INPUT: &str = "test";
58
59// ════════════════════════════════════════════════════════════════════════
60// SID Prerequisites — what KIND of step this platform's is
61// ════════════════════════════════════════════════════════════════════════
62
63/// **What a platform's SID prerequisite actually asks of whoever deploys.**
64///
65/// The bundle's prerequisites step has to emit a different *shape* for each of
66/// these, and the deploy script a different *behaviour*: one runs SQL, one
67/// verifies and refuses, one refuses outright, one says there is nothing to do.
68/// Sniffing that out of the prose at each call site would put the rule in the
69/// generator, the script writer and the runner — three readings of one fact,
70/// which is exactly how one derivation becomes two.
71///
72/// The default derives it from what the dialect already says, so a dialect that
73/// overrides nothing is still classified correctly and only the one platform
74/// the derivation cannot reach ([`SQLite`](Self::Refused)) has to override.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum SidPrerequisiteKind {
77    /// **Nothing to install: the engine's own hash already IS the canonical
78    /// number** (XXH64 seed 0), reachable from SQL razeri emits.
79    ///
80    /// **A positive claim, and therefore never a default.** Saying this means
81    /// razeri has *measured* that the platform's builtin returns XXH64 seed 0 —
82    /// not that nobody has said otherwise. A dialect that has declared nothing
83    /// gets [`Undeclared`](Self::Undeclared) instead, for the same reason
84    /// `DdlRenderer::representable_timestamp_ceiling`'s `None` means *no
85    /// measured ceiling* rather than *holds everything*.
86    ///
87    /// The derivation cannot reach this variant. A dialect claiming it
88    /// **overrides [`ReplicationRenderer::sid_prerequisite_kind`] and cites the
89    /// measurement**, as Razeri's own `ClickHouse` dialect does.
90    None,
91
92    /// Razeri emits statements that install it, and a deploy script can run
93    /// them unattended: `INSTALL`/`LOAD` (`DuckDB`), `CREATE FUNCTION`
94    /// (Snowflake's JavaScript UDF, Databricks' Python one).
95    ///
96    /// The test is *"can a script finish this with no human on the host"*. It is
97    /// **not** "is the statement SQL": `CREATE EXTENSION` is SQL and only
98    /// **registers** a shared object somebody compiled first, which is why
99    /// `PostgreSQL` and Citus are [`OperatorArtifact`](Self::OperatorArtifact)
100    /// and not this.
101    SqlInstallable,
102
103    /// An artifact the **operator** builds and places before any SQL can
104    /// reference it — SQL Server's CLR assembly, `MariaDB`'s and `MySQL`'s
105    /// `.so`, `PostgreSQL`'s and Citus's `pg_xxhash`. Razeri emits the source
106    /// or the build recipe as prose; it cannot compile anything, and it will not
107    /// pretend to.
108    ///
109    /// The deploy path's obligation here is the prerequisites verb: **verify,
110    /// then
111    /// refuse** — ask the engine for the function and stop in front of `schema`
112    /// when it is not there, rather than deploying a warehouse whose keys it
113    /// cannot compute.
114    OperatorArtifact,
115
116    /// The platform cannot be made to compute razeri's key from SQL **at all**,
117    /// and no artifact an operator drops in changes that.
118    ///
119    /// `SQLite` is the case and, so far, the only one: a standalone `sqlite3`
120    /// has no `CREATE FUNCTION` in its SQL surface, so there is no statement to
121    /// emit and no library to load. Razeri-*driven* `SQLite` can register a
122    /// function through `sqlite3_create_function()`, which is a C API, not SQL —
123    /// so the bundle's razeri-free operator genuinely cannot get there from
124    /// here.
125    ///
126    /// The answer is a **named refusal carried in the bundle**, checked before
127    /// any data moves. Never a silent fall-back expression — and the fall-back is
128    /// not hypothetical or historical: `SidSpelling`'s `sqlite` arm
129    /// **still** renders `ABS(UNICODE(x))`, the code point of the input's first
130    /// character. That is not a weak hash; it is not a hash.
131    /// The refusal is what stops it reaching a warehouse; the expression itself
132    /// is still what that arm would emit.
133    Refused,
134
135    /// **Nothing to install here, because razeri's own key function travels in
136    /// `schema.sql` instead** — one definition per domain, created in the
137    /// domain's own namespace.
138    ///
139    /// `BigQuery` is the case and the reason is name resolution, not taste: a
140    /// bare `generate_sid('test')` is *"Function not found: `generate_sid`; Did
141    /// you mean `generate_uuid`?"* there — no search path, no session schema, no
142    /// default dataset inside a procedure body — so every call site must name
143    /// the dataset the function was created in, and a prerequisites script has
144    /// no dataset to create it in. The definition therefore rides `schema.sql`,
145    /// where the domain's namespace is known.
146    ///
147    /// It is **not** [`None`](Self::None). That variant is the positive claim
148    /// *"the engine's own hash IS the canonical number"*, which is false here:
149    /// `BigQuery` has no XXH64 in any spelling and the key is a razeri-owned
150    /// JavaScript UDF. What the two share is only the deploy behaviour —
151    /// nothing to run before `schema.sql` — and sharing a behaviour is not
152    /// sharing a claim.
153    EmittedInSchema,
154
155    /// **Razeri has no measured answer for this platform** — the honest default,
156    /// and the one a dialect gets by saying nothing.
157    ///
158    /// # Why this variant exists
159    ///
160    /// A derivation that answered [`None`](Self::None) here would turn *"this
161    /// dialect declared nothing"* into the positive claim *"its own hash is
162    /// razeri's number"* — a claim that has been false on real engines. Silence
163    /// and safety must never read the same, so silence gets its own variant.
164    ///
165    /// # What it means to a deploy path
166    ///
167    /// The same as [`OperatorArtifact`](Self::OperatorArtifact): **verify, then
168    /// refuse.** Safe-by-default is the only defensible reading of "razeri does
169    /// not know" — the contract allows an emitted UDF or a named refusal and
170    /// explicitly not a local approximation, and proceeding on an unmeasured
171    /// platform is neither.
172    ///
173    /// A dialect that genuinely needs no prerequisite says so by overriding
174    /// [`ReplicationRenderer::sid_prerequisite_kind`] to
175    /// [`None`](Self::None), with its measurement cited.
176    Undeclared,
177}
178
179/// **The executable statements inside a prerequisite script**, split on
180/// [`SID_PREREQUISITE_STATEMENT_DELIMITER`].
181///
182/// The body of [`ReplicationRenderer::sid_prerequisite_statements`], lifted out
183/// so a caller holding a script that is not `self.sid_prerequisites()` — the
184/// bundle, when it swaps in
185/// [`ReplicationRenderer::sid_pure_sql_fallback`] — splits it the same way
186/// rather than growing a second reading of the boundary.
187///
188/// Leading comment and blank lines are dropped from each segment and one
189/// trailing terminator is stripped; see the trait method for why both.
190#[must_use]
191pub fn statements_in_prerequisite_script(script: &str) -> Vec<String> {
192    if !script.contains(SID_PREREQUISITE_STATEMENT_DELIMITER) {
193        return Vec::new();
194    }
195    script
196        .split(SID_PREREQUISITE_STATEMENT_DELIMITER)
197        .filter_map(|segment| {
198            let statement = segment
199                .lines()
200                .skip_while(|line| {
201                    let line = line.trim_start();
202                    line.is_empty() || line.starts_with("--")
203                })
204                .collect::<Vec<_>>()
205                .join("\n");
206            // One trailing terminator, not a run of them: `$$;` ends a body
207            // whose own last character may be a `;` the statement needs.
208            let statement = statement.trim_end().strip_suffix(';').map_or_else(
209                || statement.trim_end().to_owned(),
210                |trimmed| trimmed.trim_end().to_owned(),
211            );
212            (!statement.is_empty()).then_some(statement)
213        })
214        .collect()
215}
216
217/// **What shape a prerequisite script is**, read off the script itself.
218///
219/// The body of [`ReplicationRenderer::sid_prerequisite_kind`]'s default, lifted
220/// out for the same reason as [`statements_in_prerequisite_script`]: a caller
221/// classifying a script the dialect did not return from `sid_prerequisites()`
222/// must reach the same three answers by the same rule. A second reading of the
223/// table in the trait method's own doc comment is how a script comes to be
224/// classified two ways.
225///
226/// The two answers this cannot reach — [`SidPrerequisiteKind::None`] and
227/// [`SidPrerequisiteKind::Refused`] — are positive claims about an engine, and
228/// a dialect makes them by overriding, never by writing a script this reads.
229#[must_use]
230pub fn kind_of_prerequisite_script(script: &str) -> SidPrerequisiteKind {
231    if script.trim().is_empty() {
232        SidPrerequisiteKind::Undeclared
233    } else if statements_in_prerequisite_script(script).is_empty() {
234        SidPrerequisiteKind::OperatorArtifact
235    } else {
236        SidPrerequisiteKind::SqlInstallable
237    }
238}
239
240// ════════════════════════════════════════════════════════════════════════
241// The external artifact that IS `generate_sid`
242// ════════════════════════════════════════════════════════════════════════
243
244/// **The identity of the artifact the bundle's prerequisites step installs as
245/// `generate_sid`** — where one exists.
246///
247/// Returned by [`ReplicationRenderer::sid_external_artifact`], and the only
248/// thing a dialect still has to say about the key function's *body*: on every
249/// platform where razeri owns the name the body is
250/// Razeri's one surrogate-key derivation and reads out of one table, so
251/// there is nothing per-dialect left to declare.
252///
253/// This is an **identity, never a body**: a dialect names the artifact, and the
254/// derivation lives inside the artifact. A dialect carries no SQL spelling of
255/// the key function's body — a second spelling of the derivation is one that
256/// drifts. `generate_sid`'s parameter has **one** name, `input_value`.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct SidExternalArtifact {
259    /// Language name, e.g. `"tsql"`, `"C"`, `"javascript"`, `"python"`.
260    pub language: String,
261    /// Path or name of the external library, assembly, or emitted definition.
262    pub object_file: String,
263    /// Fully-qualified symbol within the library.
264    pub link_symbol: String,
265    /// Descriptive comment for the function — the **dialect's**, because *why
266    /// the platform's built-in was refused* is a platform fact.
267    pub comment: String,
268}
269
270// ════════════════════════════════════════════════════════════════════════
271// ReplicationRenderer Trait
272// ════════════════════════════════════════════════════════════════════════
273
274/// Rendering methods for replication operations: SID generation, data
275/// extraction, data loading, and checksum validation.
276///
277/// Defaults produce ANSI-safe SQL so extension dialects (e.g., `SQLite`) work
278/// without implementing every method.
279pub trait ReplicationRenderer: SqlRenderer {
280    // ── SID (Surrogate ID) Generation ────────────────────────────────
281
282    /// **Does an external artifact already carry the name `generate_sid` on
283    /// this platform, and what is it?**
284    ///
285    /// `None` — the default, and the honest answer for most engines — means
286    /// razeri itself defines the key function here: the body is Razeri's one
287    /// surrogate-key derivation with the platform's own hash inlined, composed
288    /// from the platform name alone, so there is nothing for a dialect to
289    /// spell.
290    ///
291    /// `Some(…)` names what the bundle's prerequisites step installs: SQL
292    /// Server's CLR assembly, MySQL/MariaDB's C UDF, Snowflake's emitted
293    /// JavaScript UDF, Databricks' emitted Python UDF. The derivation is inside
294    /// the artifact rather than in any SQL razeri emits, so what a dialect
295    /// states is the artifact's *identity*, matched against the very
296    /// prerequisites text that installs it. **This is an identity, not a
297    /// body** — see [`SidExternalArtifact`].
298    ///
299    /// A platform that can be given no function at all — `SQLite`, which has no
300    /// `CREATE FUNCTION` in its SQL surface — answers `None` here too and says
301    /// so through [`Self::sid_prerequisite_kind`]
302    /// ([`SidPrerequisiteKind::Refused`]). Razeri's conformance checks require
303    /// that refusal to be said out loud: where no artifact is declared and
304    /// razeri emits no helper either, a dialect that has simply declared
305    /// nothing is reported, which is the distinction
306    /// [`SidPrerequisiteKind::Undeclared`] exists to keep.
307    fn sid_external_artifact(&self) -> Option<SidExternalArtifact> {
308        None
309    }
310
311    /// Returns prerequisite SQL/instructions for SID deployment.
312    ///
313    /// For platforms that require extensions or external libraries (`PostgreSQL`
314    /// `pg_xxhash`, SQL Server CLR, `MariaDB` C UDF), this returns the deployment
315    /// script. Default: empty (no prerequisites needed).
316    fn sid_prerequisites(&self) -> String {
317        String::new()
318    }
319
320    /// **The executable statements inside [`Self::sid_prerequisites`], in
321    /// order** — razeri's own text, split on razeri's own declared boundary.
322    ///
323    /// This exists so a deploy path or a test harness can *install what razeri
324    /// emits* rather than a transcription of it — a hand-written copy is a
325    /// second implementation that drifts, and a second splitter would be a
326    /// second definition of the boundary.
327    ///
328    /// **A dialect that does not write
329    /// [`SID_PREREQUISITE_STATEMENT_DELIMITER`] declares no executable
330    /// statements**, and gets an empty vector. That is the honest answer for
331    /// every arm whose prerequisite is an operator's compile step (SQL Server's
332    /// CLR assembly, `MariaDB`'s and `MySQL`'s `.so`) and for the platforms with
333    /// no prerequisite at all — it is *not* a promise that a caller can run the
334    /// prose.
335    ///
336    /// Leading comment and blank lines are dropped from each segment, so the
337    /// prose that explains a statement travels with it in the script and does
338    /// not travel to the engine. Comments *inside* a statement survive: they are
339    /// part of the statement the operator would paste.
340    ///
341    /// **The trailing terminator is dropped here, once.** A `;` is how the
342    /// script reads to a human pasting the whole file, and is not part of a
343    /// single statement over a REST statement API — Snowflake's and Databricks'
344    /// both take exactly one. Stripping it in each consumer instead would put
345    /// the same rule in the cloud arms *and* in the bundle executor, which
346    /// is the shape this method exists to prevent. `sid_prerequisites()`' text
347    /// is unchanged and keeps its semicolons.
348    fn sid_prerequisite_statements(&self) -> Vec<String> {
349        statements_in_prerequisite_script(&self.sid_prerequisites())
350    }
351
352    /// **A prerequisite script that installs the same key function without
353    /// compiling anything** — where the platform has one, and `None` where it
354    /// does not.
355    ///
356    /// The default is `None`: most platforms have exactly one prerequisite and
357    /// [`Self::sid_prerequisites`] is it. A dialect answers `Some` only where
358    /// **two honest routes to the same number** exist and the choice belongs to
359    /// whoever deploys rather than to whoever designed — the case being a
360    /// managed `PostgreSQL` service (`RDS`, Aurora, Cloud SQL), where nobody has
361    /// a shell on the server host and so the compiled extension the ordinary
362    /// step names can never be built.
363    ///
364    /// # What answering `Some` promises
365    ///
366    /// **The same number, byte for byte.** Not a near-enough hash and not a
367    /// different algorithm: the surrogate-key rule is one hash and one
368    /// derivation everywhere, so a key minted through this route and a key
369    /// minted through the compiled one are the same `BIGINT` and a warehouse can
370    /// be moved between them without re-keying a row. A dialect that cannot
371    /// promise that answers `None` and lets the ordinary step refuse.
372    ///
373    /// It is a **deploy-time** choice and nothing about it reaches a design: the
374    /// text swaps into `prerequisites.sql` alone, `schema.sql` is unchanged, and
375    /// every call site still calls the one public name.
376    fn sid_pure_sql_fallback(&self) -> Option<String> {
377        None
378    }
379
380    /// **Which of [`SidPrerequisiteKind`]'s shapes this platform's prerequisite
381    /// is.**
382    ///
383    /// Derived from what the dialect already says, so the classification cannot
384    /// drift from the text it classifies:
385    ///
386    /// | [`sid_prerequisites`](Self::sid_prerequisites) | [`sid_prerequisite_statements`](Self::sid_prerequisite_statements) | kind |
387    /// |---|---|---|
388    /// | empty | — | [`Undeclared`](SidPrerequisiteKind::Undeclared) |
389    /// | prose **and** statements | non-empty | [`SqlInstallable`](SidPrerequisiteKind::SqlInstallable) |
390    /// | prose only | empty | [`OperatorArtifact`](SidPrerequisiteKind::OperatorArtifact) |
391    ///
392    /// # Silence is `Undeclared`, never `None`
393    ///
394    /// The two answers the derivation **cannot** reach are the two that are
395    /// *positive claims about an engine*:
396    ///
397    /// - [`None`](SidPrerequisiteKind::None) says the platform's own builtin
398    ///   returns the canonical number. That is a measurement, not an absence, and
399    ///   a dialect claiming it overrides this method and cites the arm that
400    ///   measured it;
401    /// - [`Refused`](SidPrerequisiteKind::Refused) says no SQL can ever install
402    ///   the function here, which a platform with a native hash and a lazy
403    ///   dialect author would also spell as silence.
404    ///
405    /// It is the same asymmetry `DdlRenderer::representable_timestamp_ceiling`
406    /// documents on its own `None`: *not measured* and *nothing to worry about*
407    /// are opposite facts that read identically when a default supplies them.
408    fn sid_prerequisite_kind(&self) -> SidPrerequisiteKind {
409        kind_of_prerequisite_script(&self.sid_prerequisites())
410    }
411
412    /// Returns a validation query to verify the SID function is operational.
413    ///
414    /// Default: schema-qualified `SELECT generate_sid('test')`.
415    fn sid_validation_query(&self, schema: Option<&str>, null_sid: i64) -> String {
416        let qualified = match schema {
417            Some(s) => format!("{s}.generate_sid"),
418            None => "generate_sid".to_string(),
419        };
420        format!("SELECT {qualified}('test') AS test_sid, {null_sid} AS null_sid;\n")
421    }
422
423    // ── Data Extraction ──────────────────────────────────────────────
424
425    /// Renders an extract/export SQL statement for the given table.
426    ///
427    /// The `format` parameter is one of: `"csv"`, `"parquet"`, `"json_lines"`, `"native"`.
428    ///
429    /// Default: ANSI `SELECT ... FROM ... WHERE ...` (no COPY).
430    fn render_data_extract(
431        &self,
432        qualified: &str,
433        columns: &str,
434        file_path: &str,
435        format: &str,
436        where_clause: &str,
437        _batch_size: Option<usize>,
438    ) -> String {
439        let _ = file_path;
440        let _ = format;
441        if where_clause.is_empty() {
442            format!("SELECT {columns} FROM {qualified};\n")
443        } else {
444            format!("SELECT {columns} FROM {qualified} {where_clause};\n")
445        }
446    }
447
448    // ── Data Loading ─────────────────────────────────────────────────
449
450    /// Renders a load/import SQL statement for the given table.
451    ///
452    /// The `format` parameter is one of: `"csv"`, `"parquet"`, `"json_lines"`, `"native"`.
453    ///
454    /// Default: ANSI comment placeholder.
455    fn render_data_load(&self, qualified: &str, file_path: &str, _format: &str) -> String {
456        format!("-- COPY INTO {qualified} FROM '{file_path}';\n")
457    }
458
459    // ── Checksum / Validation ────────────────────────────────────────
460
461    /// Renders a checksum validation query for data comparison.
462    ///
463    /// Default: `SELECT COUNT(*) AS cnt FROM <table>` (no checksum).
464    fn render_checksum_query(&self, qualified: &str) -> String {
465        format!("SELECT COUNT(*) AS cnt FROM {qualified};\n")
466    }
467
468    // ── Platform Warnings ────────────────────────────────────────────
469
470    /// Warning about Parquet export limitations on this platform.
471    ///
472    /// Default: `None` (no warning needed).
473    fn parquet_export_warning(&self) -> Option<&str> {
474        None
475    }
476
477    /// Warning about SID function deployment requirements on this platform.
478    ///
479    /// Default: `None` (no special deployment needed).
480    fn sid_deployment_warning(&self) -> Option<&str> {
481        None
482    }
483
484    /// General replication caveats for this platform as a target.
485    ///
486    /// Default: empty (no platform-specific caveats).
487    fn replication_target_warnings(&self) -> Vec<String> {
488        Vec::new()
489    }
490
491    /// Warning about TRUNCATE behavior on this platform.
492    ///
493    /// Default: `None` (TRUNCATE works normally).
494    fn truncate_caveat(&self) -> Option<&str> {
495        None
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::{ReplicationRenderer, SID_PREREQUISITE_STATEMENT_DELIMITER};
502    use crate::agnostic::AnsiDialect;
503
504    /// A dialect whose prerequisites are whatever a test hands it.
505    struct Emitting(String);
506
507    impl crate::SqlRenderer for Emitting {
508        fn dialect_name(&self) -> &'static str {
509            "emitting"
510        }
511        fn render_data_type(&self, dt: &crate::DataType) -> String {
512            AnsiDialect.render_data_type(dt)
513        }
514        fn quote_identifier(&self, name: &str) -> String {
515            AnsiDialect.quote_identifier(name)
516        }
517        fn qualify_name(&self, schema: Option<&str>, name: &str) -> String {
518            AnsiDialect.qualify_name(schema, name)
519        }
520        fn render_current_timestamp(&self) -> String {
521            AnsiDialect.render_current_timestamp()
522        }
523    }
524    impl crate::DdlRenderer for Emitting {}
525    impl crate::FormulaRenderer for Emitting {}
526    impl ReplicationRenderer for Emitting {
527        fn sid_prerequisites(&self) -> String {
528            self.0.clone()
529        }
530    }
531
532    /// **A JavaScript body is nothing but semicolons**, which is exactly why the
533    /// boundary is declared instead of inferred. Splitting the text below on
534    /// `;` yields five fragments, none of them a statement.
535    #[test]
536    fn the_delimiter_recovers_statements_a_semicolon_split_would_fracture() {
537        let script = format!(
538            "-- prose the operator reads\n\
539             {SID_PREREQUISITE_STATEMENT_DELIMITER}\n\
540             -- why this one exists\n\
541             CREATE FUNCTION f() AS $$\n  var a = 1; var b = 2; return a + b;\n$$;\n\
542             {SID_PREREQUISITE_STATEMENT_DELIMITER}\n\
543             CREATE FUNCTION g() AS $$ 1 $$;\n"
544        );
545        let statements = Emitting(script).sid_prerequisite_statements();
546        assert_eq!(statements.len(), 2, "{statements:#?}");
547        assert!(statements[0].starts_with("CREATE FUNCTION f()"), "{:?}", statements[0]);
548        assert!(statements[0].contains("var a = 1; var b = 2; return a + b;"));
549        assert_eq!(statements[1], "CREATE FUNCTION g() AS $$ 1 $$");
550    }
551
552    /// **The trailing terminator is dropped exactly once, and only at the end.**
553    ///
554    /// A REST statement API takes one statement and no terminator; a human
555    /// pasting the script wants the `;`. Both are served by leaving it in
556    /// `sid_prerequisites()`' text and removing it here — once, so a body whose
557    /// own last character is a `;` (every JavaScript function) keeps it.
558    #[test]
559    fn one_trailing_terminator_is_dropped_and_the_bodys_own_semicolons_survive() {
560        let script = format!(
561            "{SID_PREREQUISITE_STATEMENT_DELIMITER}\n\
562             CREATE FUNCTION f() AS $$\n  return 1;\n$$;\n\
563             {SID_PREREQUISITE_STATEMENT_DELIMITER}\n\
564             CREATE FUNCTION g() AS $$ 1 $$\n"
565        );
566        let statements = Emitting(script).sid_prerequisite_statements();
567        assert_eq!(statements[0], "CREATE FUNCTION f() AS $$\n  return 1;\n$$");
568        assert!(statements[0].contains("return 1;"), "the body's own `;` is not a terminator");
569        assert_eq!(
570            statements[1], "CREATE FUNCTION g() AS $$ 1 $$",
571            "a statement with no terminator is unchanged"
572        );
573    }
574
575    /// **No delimiter means no executable statements, and that is an answer.**
576    /// The prerequisite scripts for SQL Server, `MySQL` and `MariaDB` are an
577    /// operator's compile recipe wrapped in comments; handing a caller the prose
578    /// as if it were DDL is how a deferral turns into a failure nobody can read.
579    #[test]
580    fn an_undelimited_script_declares_no_executable_statements() {
581        let operator_recipe = "-- compile this yourself:\n/* int main() { } */\n".to_owned();
582        assert!(Emitting(operator_recipe).sid_prerequisite_statements().is_empty());
583        assert!(AnsiDialect.sid_prerequisite_statements().is_empty());
584    }
585}