Skip to main content

sql_splitter/synthetic/
merge.rs

1//! Merges a base `model` with a typed `overrides` patch into a complete
2//! candidate [`SyntheticModel`].
3//!
4//! This is a typed, field-wise patch — not a generic YAML merge. Generic
5//! YAML merging happens once, at import time, in
6//! [`super::config::ConfigLoader`]; by the time a [`SyntheticOverrides`]
7//! reaches [`ModelMerger`], both documents are already fully typed and this
8//! module only has to decide, per field, whether the patch may replace the
9//! base value outright (generation rules, rows, relationships, planners) or
10//! may only assert that it still matches an immutable structural fact (the
11//! source schema, the source fingerprint). Every table and column override
12//! is checked independently, via [`crate::diagnostic::DiagnosticBag`], so a
13//! patch with several unrelated mistakes reports all of them at once rather
14//! than stopping at the first.
15
16use crate::diagnostic::DiagnosticBag;
17
18use super::model::{
19    ColumnRule, FingerprintPolicy, OutputModel, RowsModel, SourceModel, SyntheticModel, TableModel,
20    TableSeed,
21};
22use super::overrides::{
23    ColumnRuleOverride, OutputOverride, PortableTableOverride, RootSeedOverride, RowsKind,
24    RowsOverride, SyntheticOverrides, TableOverride, TableSeedOverride,
25};
26use super::schema::PortableTable;
27
28/// Merges a base [`SyntheticModel`] with a typed [`SyntheticOverrides`]
29/// patch, producing a complete candidate model or the diagnostics that
30/// block it.
31pub struct ModelMerger;
32
33impl ModelMerger {
34    /// Applies `patch` on top of `base`, field by field.
35    ///
36    /// Diagnostics are gathered rather than short-circuited: a missing
37    /// table, a missing column, and a structural schema mismatch on three
38    /// unrelated tables all get reported together.
39    ///
40    /// On success, the returned `DiagnosticBag` carries any warnings
41    /// produced along the way (e.g. a `GEN-SOURCE-FINGERPRINT` warning
42    /// under `warn` policy) — it may be empty, but it is never discarded.
43    /// This is why the success type is `(SyntheticModel, DiagnosticBag)`
44    /// rather than plain `SyntheticModel`: a bag with no error-severity
45    /// diagnostic still deserves to be seen by the caller. On failure (any
46    /// error-severity diagnostic), `Err(bag)` carries every diagnostic,
47    /// warnings included, same as before.
48    pub fn merge(
49        mut base: SyntheticModel,
50        patch: SyntheticOverrides,
51    ) -> Result<(SyntheticModel, DiagnosticBag), DiagnosticBag> {
52        let mut bag = DiagnosticBag::default();
53
54        match patch.seed {
55            RootSeedOverride::Inherit => {}
56            RootSeedOverride::Random => base.seed = None,
57            RootSeedOverride::Fixed(seed) => base.seed = Some(seed),
58        }
59
60        if let Some(output) = patch.output {
61            output.apply_to(&mut base.output);
62        }
63
64        if let Some(defaults) = patch.defaults {
65            base.defaults = defaults;
66        }
67
68        if let Some(source) = patch.source {
69            apply_source(source, &mut base.source, &mut bag);
70        }
71
72        for (name, table_patch) in patch.tables {
73            match base.tables.get_mut(&name) {
74                Some(table) => {
75                    let table_path = format!("tables.{name}");
76                    table_patch.apply_to(&table_path, table, &mut bag);
77                }
78                None => {
79                    bag.error(
80                        crate::diagnostic::codes::MISSING_TABLE.code,
81                        format!("tables.{name}"),
82                        "override table does not exist in the source/base model",
83                    );
84                }
85            }
86        }
87
88        if bag.has_errors() {
89            Err(bag)
90        } else {
91            Ok((base, bag))
92        }
93    }
94}
95
96/// Applies a `source:` override, which reuses [`SourceModel`] wholesale
97/// rather than a partial-override shape (every override field is a
98/// meaningful full value, `dialect` included, since `SourceModel::dialect`
99/// is not optional).
100///
101/// The one field this does not treat as a plain replacement is
102/// `fingerprint`: a mismatch against the base's recorded fingerprint is
103/// diagnosed according to the effective [`FingerprintPolicy`] (the
104/// override's own policy if given, else the base's, else
105/// [`FingerprintPolicy::Ignore`]) rather than silently dropped. The
106/// replacement still happens — fingerprint differences are expected to
107/// occur (a dump was re-profiled, say) — but never *without* the caller
108/// being told, at least at `warn` severity.
109fn apply_source(
110    patch: SourceModel,
111    base_source: &mut Option<SourceModel>,
112    bag: &mut DiagnosticBag,
113) {
114    let existing_fingerprint = base_source.as_ref().and_then(|s| s.fingerprint.clone());
115    let existing_policy = base_source.as_ref().and_then(|s| s.fingerprint_policy);
116
117    if let (Some(existing), Some(patched)) = (&existing_fingerprint, &patch.fingerprint) {
118        if existing != patched {
119            let policy = patch
120                .fingerprint_policy
121                .or(existing_policy)
122                .unwrap_or(FingerprintPolicy::Ignore);
123            let message = format!(
124                "override source fingerprint `{patched}` does not match the base model's recorded fingerprint `{existing}`"
125            );
126            match policy {
127                FingerprintPolicy::Ignore => {}
128                FingerprintPolicy::Warn => {
129                    bag.warning(
130                        crate::diagnostic::codes::SOURCE_FINGERPRINT.code,
131                        "source.fingerprint",
132                        message,
133                    );
134                }
135                FingerprintPolicy::Require => {
136                    bag.error(
137                        crate::diagnostic::codes::SOURCE_FINGERPRINT.code,
138                        "source.fingerprint",
139                        message,
140                    );
141                }
142            }
143        }
144    }
145
146    *base_source = Some(patch);
147}
148
149impl OutputOverride {
150    /// Replaces each present field on `output`; absent fields leave the
151    /// base value untouched.
152    fn apply_to(self, output: &mut OutputModel) {
153        if let Some(dialect) = self.dialect {
154            output.dialect = Some(dialect);
155        }
156        if let Some(mode) = self.mode {
157            output.mode = Some(mode);
158        }
159        if let Some(inserts) = self.inserts {
160            output.inserts = Some(inserts);
161        }
162        if let Some(batch_size) = self.batch_size {
163            output.batch_size = Some(batch_size);
164        }
165    }
166}
167
168impl TableOverride {
169    /// Applies a per-table patch: seed, schema assertion, rows, per-column
170    /// rules, and whole-list relationship/planner replacement.
171    fn apply_to(self, table_path: &str, table: &mut TableModel, bag: &mut DiagnosticBag) {
172        match self.seed {
173            TableSeedOverride::Inherit => {}
174            TableSeedOverride::Random => table.seed = TableSeed::Random,
175            TableSeedOverride::Fixed(seed) => table.seed = TableSeed::Fixed(seed),
176        }
177
178        if let Some(schema_patch) = self.schema {
179            schema_patch.check_matches(table_path, &table.schema, bag);
180        }
181
182        if let Some(rows_patch) = self.rows {
183            rows_patch.apply_to(table_path, &mut table.rows, bag);
184        }
185
186        for (column_name, column_patch) in self.columns {
187            let column_path = format!("{table_path}.columns.{column_name}");
188            if !table.schema.columns.iter().any(|c| c.name == column_name) {
189                bag.error(
190                    crate::diagnostic::codes::MISSING_COLUMN.code,
191                    column_path,
192                    format!(
193                        "override column `{column_name}` does not exist in table `{}`'s schema",
194                        table.schema.name
195                    ),
196                );
197                continue;
198            }
199            let rule = table
200                .columns
201                .entry(column_name)
202                .or_insert_with(|| ColumnRule {
203                    semantic: None,
204                    generator: None,
205                    modifiers: Vec::new(),
206                });
207            column_patch.apply_to(rule);
208        }
209
210        if let Some(relationships) = self.relationships {
211            table.relationships = relationships;
212        }
213        if let Some(planners) = self.planners {
214            table.planners = planners;
215        }
216    }
217}
218
219impl PortableTableOverride {
220    /// Asserts that any structural fact the override names still matches
221    /// the base/source schema; never mutates `schema`. Overrides cannot
222    /// rename a table or redefine its DDL — see the design's "source,
223    /// model, and overrides merge predictably" section — so a mismatch
224    /// here is always `GEN-SCHEMA-MISMATCH`, not a silent structural
225    /// change.
226    ///
227    /// Column-level structural facts (type, nullability, key, existence)
228    /// are not represented in [`PortableTableOverride`] at all — it carries
229    /// only `name` and `create_statement` — so the type system already
230    /// forecloses column-level structural overrides; this only needs to
231    /// guard the two table-level facts that do exist.
232    fn check_matches(&self, table_path: &str, schema: &PortableTable, bag: &mut DiagnosticBag) {
233        if let Some(name) = &self.name {
234            if name != &schema.name {
235                bag.error(
236                    crate::diagnostic::codes::SCHEMA_MISMATCH.code,
237                    format!("{table_path}.schema.name"),
238                    format!(
239                        "override asserts table name `{name}`, but the source/base schema names it `{}`; overrides cannot rename or otherwise restructure DDL",
240                        schema.name
241                    ),
242                );
243            }
244        }
245        if let Some(create_statement) = &self.create_statement {
246            if Some(create_statement) != schema.create_statement.as_ref() {
247                bag.error(
248                    crate::diagnostic::codes::SCHEMA_MISMATCH.code,
249                    format!("{table_path}.schema.create_statement"),
250                    "override's create_statement does not match the source/base schema; overrides cannot redefine DDL structure",
251                );
252            }
253        }
254    }
255}
256
257impl ColumnRuleOverride {
258    /// Replaces each present field on `rule`; absent fields leave the base
259    /// rule untouched. Generator/modifier changes are ordinary generation
260    /// rules, not structural facts, so they are always legal.
261    fn apply_to(self, rule: &mut ColumnRule) {
262        if let Some(semantic) = self.semantic {
263            rule.semantic = Some(semantic);
264        }
265        if let Some(generator) = self.generator {
266            rule.generator = Some(generator);
267        }
268        if let Some(modifiers) = self.modifiers {
269            rule.modifiers = modifiers;
270        }
271    }
272}
273
274impl RowsOverride {
275    /// Applies a `rows:` patch. When the override's `kind` matches the
276    /// base's current variant, only the fields the override actually
277    /// supplies change — the rest are read back off the base variant. When
278    /// the override switches to a different `kind`, there is no base value
279    /// to fall back on for the fields it omits, so it must supply every
280    /// field that variant needs; if it doesn't, this reports
281    /// `GEN-INCOMPLETE-ROWS` rather than guessing.
282    fn apply_to(self, table_path: &str, rows: &mut RowsModel, bag: &mut DiagnosticBag) {
283        let path = format!("{table_path}.rows");
284        match self.kind {
285            RowsKind::Fixed => {
286                let base_count = match rows {
287                    RowsModel::Fixed { count } => Some(*count),
288                    _ => None,
289                };
290                match self.count.or(base_count) {
291                    Some(count) => *rows = RowsModel::Fixed { count },
292                    None => {
293                        bag.error(
294                            crate::diagnostic::codes::INCOMPLETE_ROWS.code,
295                            path,
296                            "rows override switches to `fixed` but supplies no `count`, and the base table's rows are not already `fixed`",
297                        );
298                    }
299                }
300            }
301            RowsKind::Observed => {
302                let base_count = match rows {
303                    RowsModel::Observed { count } => Some(*count),
304                    _ => None,
305                };
306                let count = self.count.or_else(|| {
307                    self.scale
308                        .zip(base_count)
309                        .map(|(scale, base)| ((base as f64) * scale).round() as u64)
310                });
311                match count {
312                    Some(count) => *rows = RowsModel::Observed { count },
313                    None => {
314                        bag.error(
315                            crate::diagnostic::codes::INCOMPLETE_ROWS.code,
316                            path,
317                            "rows override switches to `observed` but supplies neither `count` nor a `scale` against an already-`observed` base count",
318                        );
319                    }
320                }
321            }
322            RowsKind::Scale => {
323                let (base_base, base_factor) = match rows {
324                    RowsModel::Scale { base, factor, .. } => (Some(*base), Some(*factor)),
325                    _ => (None, None),
326                };
327                match (self.base.or(base_base), self.factor.or(base_factor)) {
328                    (Some(base), Some(factor)) => {
329                        let count = ((base as f64) * factor).round() as u64;
330                        *rows = RowsModel::Scale {
331                            base,
332                            factor,
333                            count,
334                        };
335                    }
336                    _ => {
337                        bag.error(
338                            crate::diagnostic::codes::INCOMPLETE_ROWS.code,
339                            path,
340                            "rows override switches to `scale` but is missing `base` and/or `factor`",
341                        );
342                    }
343                }
344            }
345            RowsKind::RelationChildren => {
346                let (base_parent, base_count, base_distribution) = match rows {
347                    RowsModel::RelationChildren {
348                        parent,
349                        count,
350                        distribution,
351                    } => (
352                        Some(parent.clone()),
353                        Some(*count),
354                        Some(distribution.clone()),
355                    ),
356                    _ => (None, None, None),
357                };
358                match (
359                    self.parent.or(base_parent),
360                    self.count.or(base_count),
361                    self.distribution.or(base_distribution),
362                ) {
363                    (Some(parent), Some(count), Some(distribution)) => {
364                        *rows = RowsModel::RelationChildren {
365                            parent,
366                            count,
367                            distribution,
368                        };
369                    }
370                    _ => {
371                        bag.error(
372                            crate::diagnostic::codes::INCOMPLETE_ROWS.code,
373                            path,
374                            "rows override switches to `relation.children` but is missing `parent`, `count`, and/or `distribution`",
375                        );
376                    }
377                }
378            }
379        }
380    }
381}