151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466 | class ModelConfig(BaseModel):
"""
Canonical, *flattened* model configuration for SQL and Python models.
This represents the keys that ultimately end up in Node.meta after:
- SQL: {{ config(...) }} in the model header
- Python: @model(..., meta={...})
- project.yml overlays (models.incremental / models.storage)
The schema is intentionally strict (extra="forbid") so that:
- only documented keys are allowed
- typos and unknown fields fail fast
"""
model_config = ConfigDict(extra="forbid")
# --- Core materialization & classification -----------------------------
materialized: Literal["table", "view", "incremental", "ephemeral", "snapshot"] | None = None
# Optional logical kind; useful for selectors (kind:python / kind:sql / etc.)
kind: str | None = None
# Tags for selection (tag:...); both SQL & Python models contribute here
tags: list[str] = Field(default_factory=list)
# Engine restriction, e.g. engines=["duckdb", "postgres"]
engines: list[str] = Field(default_factory=list)
# --- Per-model hooks (pre/post) ----------------------------------------
pre_hook: list[str] = Field(default_factory=list)
post_hook: list[str] = Field(default_factory=list)
# --- Storage override (per model) --------------------------------------
storage: StorageConfig | None = None
# --- Incremental flags & shortcuts -------------------------------------
# Shortcut:
# - True → incremental enabled
# - False / None → not incremental (unless executors override)
#
# Structured:
# - { ... IncrementalConfig fields ... }
incremental: IncrementalConfig | None = None
# --- Snapshot configuration (structured) ---------------------------------
snapshot: SnapshotConfig | None = None
# Top-level shortcuts (backwards-compatible)
# These are used by existing executor logic.
unique_key: list[str] | None = None
primary_key: list[str] | None = None # alias
# Updated-at / timestamp information
updated_at: str | None = None
updated_at_column: str | None = None
updated_at_columns: list[str] | None = None
timestamp_columns: list[str] | None = None
# Columns used to determine delta recency (used by Python incremental logic)
delta_columns: list[str] | None = None
# Delta definitions - shorthand, equivalent to fields on IncrementalConfig
delta: InlineDeltaConfig | None = None
delta_sql: str | None = None
delta_python: str | None = None
# Schema evolution behaviour; consumed by incremental._get_on_schema_change(...)
on_schema_change: Literal["ignore", "append_new_columns", "sync_all_columns"] | None = None
# --- HTTP/API extension points (optional) ------------------------------
# These are intentionally loose to allow API models to stash config blocks
# under known keys without having to allow arbitrary extras everywhere.
http: dict[str, Any] | None = None
api: dict[str, Any] | None = None
# ----------------------------------------------------------------------
# Normalisation helpers
# ----------------------------------------------------------------------
@field_validator("pre_hook", "post_hook", mode="before")
@classmethod
def _normalize_hooks(cls, v: Any) -> list[str]:
"""
Allow:
- string: "delete from {{ this }}" → ["delete from {{ this }}"]
- sequence: ["stmt1", "stmt2"]
- null: []
"""
if v is None:
return []
if isinstance(v, str):
text = v.strip()
return [text] if text else []
if isinstance(v, Sequence) and not isinstance(v, (str, bytes)):
return [str(x).strip() for x in v if str(x).strip()]
raise TypeError("pre_hook/post_hook must be a string or a sequence of strings")
@field_validator("tags", "engines", mode="before")
@classmethod
def _normalize_tags_engines(cls, v: Any) -> list[str]:
"""
Allow:
- string: "duckdb" → ["duckdb"]
- sequence: ["duckdb", "postgres"]
"""
if v is None:
return []
if isinstance(v, str):
return [v]
if isinstance(v, Sequence) and not isinstance(v, (str, bytes)):
return [str(x) for x in v]
raise TypeError("must be a string or a sequence of strings")
@field_validator(
"unique_key",
"primary_key",
"updated_at_columns",
"timestamp_columns",
"delta_columns",
mode="before",
)
@classmethod
def _normalize_key_lists(cls, v: Any) -> list[str] | None:
"""
Allow single string or list/tuple of strings.
"""
if v is None:
return None
if isinstance(v, str):
return [v]
if isinstance(v, Sequence) and not isinstance(v, (str, bytes)):
return [str(x) for x in v]
raise TypeError("must be a string or a sequence of strings")
@model_validator(mode="after")
def _merge_incremental_overlays(self) -> ModelConfig:
"""
Backwards- and executor-compatible merge:
- If `incremental` is an IncrementalConfig instance, mirror the
central fields onto the top-level shortcuts (unique_key, updated_at_column, delta_*).
- If `incremental == True` but no IncrementalConfig was provided,
we simply rely on top-level fields (unique_key, updated_at, …).
"""
inc = self.incremental
if isinstance(inc, IncrementalConfig):
# unique_key
if self.unique_key is None and inc.unique_key is not None:
self.unique_key = list(inc.unique_key)
# updated-at / updated_at_column
if self.updated_at_column is None and inc.updated_at_column is not None:
self.updated_at_column = inc.updated_at_column
if self.updated_at is None and inc.updated_at_column is not None:
# For older code that only checks `updated_at`
self.updated_at = inc.updated_at_column
# timestamp / updated_at columns
if self.updated_at_columns is None and inc.updated_at_columns is not None:
self.updated_at_columns = list(inc.updated_at_columns)
if self.timestamp_columns is None and inc.timestamp_columns is not None:
self.timestamp_columns = list(inc.timestamp_columns)
# delta hints
if self.delta_sql is None and inc.delta_sql is not None:
self.delta_sql = inc.delta_sql
if self.delta_python is None and inc.delta_python is not None:
self.delta_python = inc.delta_python
# schema evolution
if self.on_schema_change is None and inc.on_schema_change is not None:
self.on_schema_change = inc.on_schema_change
# If InlineDeltaConfig is used, prefer its SQL for delta_sql
if self.delta and not self.delta_sql:
self.delta_sql = self.delta.sql
# Mirror snapshot hints onto top-level shortcuts for backwards compatibility.
snap = self.snapshot
if snap:
if self.updated_at is None and snap.updated_at is not None:
self.updated_at = snap.updated_at
if self.updated_at_column is None and snap.updated_at_column is not None:
self.updated_at_column = snap.updated_at_column
return self
# ----------------------------------------------------------------------
# Convenience helpers for executor code
# ----------------------------------------------------------------------
def is_incremental_enabled(self) -> bool:
"""
Return True if incremental mode is effectively enabled for this model.
"""
if self.incremental is None:
return False
return bool(self.incremental.enabled)
# ----------------------------------------------------------------------
# Cross-field guardrails (fail fast with clear messages)
# ----------------------------------------------------------------------
@model_validator(mode="after")
def _validate_model_requirements(self) -> ModelConfig:
"""
Enforce combinations that must hold for incremental and snapshot models.
Incremental rules:
1) If materialized == 'incremental', incremental must be effectively enabled.
2) If incremental is enabled, at least one freshness/delta hint must exist:
- updated_at / updated_at_column / updated_at_columns / timestamp_columns
OR delta_sql OR delta_python.
3) If both updated_at and updated_at_column are provided, they must match.
4) Require unique_key when incremental is enabled.
Snapshot rules:
1) If materialized == 'snapshot', a snapshot config must be provided.
2) Snapshot models require unique_key (or primary_key).
3) strategy must be 'timestamp' or 'check'.
4) For 'timestamp', require updated_at / updated_at_column.
5) For 'check', require check_cols.
"""
# --- Incremental ---------------------------------------------------
is_mat_inc = self.materialized == "incremental"
is_inc_enabled = self.is_incremental_enabled()
# 1) Require incremental block when materialized='incremental'
if is_mat_inc and not is_inc_enabled:
raise ValueError(
"materialized='incremental' requires an enabled incremental configuration. "
"Either set `incremental: true` or provide a "
"structured `incremental: { enabled: true, ... }`."
)
# 2) If incremental is enabled, ensure at least one delta/freshness hint
if is_inc_enabled:
has_time_hints = any(
[
bool(self.updated_at),
bool(self.updated_at_column),
bool(self.updated_at_columns),
bool(self.timestamp_columns),
]
)
has_delta_hints = any([bool(self.delta_sql), bool(self.delta_python)])
if not (has_time_hints or has_delta_hints):
raise ValueError(
"incremental.enabled=True but no delta/freshness hints were provided. "
"Please set one of: updated_at / updated_at_column / updated_at_columns / "
"timestamp_columns, or provide delta_sql / delta_python."
)
# 3) If both notations are present, they must agree
if self.updated_at and self.updated_at_column and self.updated_at != self.updated_at_column:
raise ValueError(
f"updated_at ('{self.updated_at}') and "
f"updated_at_column ('{self.updated_at_column}') "
"refer to different columns. Use one or make them identical."
)
# 4) (Opinionated) Require unique_key when incremental is enabled
if is_inc_enabled and not (self.unique_key or self.primary_key):
raise ValueError(
"incremental.enabled=True requires a unique_key (or primary_key) to be set "
"for safe merges. Example: unique_key: ['id']"
)
# --- Snapshot-specific rules --------------------------------------
if self.materialized == "snapshot":
snap = self.snapshot
if snap is None:
raise ValueError(
"materialized='snapshot' requires a snapshot config block. "
"Example:\n"
" snapshot: { strategy: 'timestamp' }"
)
# business key
if not (self.unique_key or self.primary_key):
raise ValueError(
"materialized='snapshot' requires a unique_key (or primary_key). "
"Example: unique_key: ['id']"
)
# strategy is validated by SnapshotConfig (Literal), but we keep a guardrail here
if snap.strategy not in ("timestamp", "check"):
raise ValueError(
"Snapshot models require strategy='timestamp' or 'check'. "
"Example: snapshot: { strategy: 'timestamp' }"
)
# timestamp strategy: needs updated_at
snap_updated = snap.updated_at or snap.updated_at_column
if snap.strategy == "timestamp" and not snap_updated:
raise ValueError(
"strategy='timestamp' snapshots require snapshot.updated_at or "
"snapshot.updated_at_column."
)
# check strategy: needs check_cols
if snap.strategy == "check" and not snap.check_cols:
raise ValueError(
"strategy='check' snapshots require snapshot.check_cols "
"(string or list of column names)."
)
return self
|