1use 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
28pub struct ModelMerger;
32
33impl ModelMerger {
34 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
96fn 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 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 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 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 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 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}