-
Notifications
You must be signed in to change notification settings - Fork 422
Expand file tree
/
Copy pathdefinition.py
More file actions
3290 lines (2800 loc) · 123 KB
/
Copy pathdefinition.py
File metadata and controls
3290 lines (2800 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import logging
import types
import re
import typing as t
from functools import cached_property, partial
from pathlib import Path
from pydantic import Field
from sqlglot import diff, exp
from sqlglot.diff import Insert
from sqlglot.helper import seq_get
from sqlglot.optimizer.qualify_columns import quote_identifiers
from sqlglot.optimizer.simplify import gen
from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
from sqlglot.schema import MappingSchema, nested_set
from sqlglot.time import format_time
from sqlmesh.core import constants as c
from sqlmesh.core import dialect as d
from sqlmesh.core.audit import Audit, ModelAudit
from sqlmesh.core.node import IntervalUnit
from sqlmesh.core.macros import MacroRegistry, macro
from sqlmesh.core.model.common import (
ParsableSql,
make_python_env,
parse_dependencies,
parse_strings_with_macro_refs,
single_value_or_tuple,
sorted_python_env_payloads,
validate_extra_and_required_fields,
)
from sqlmesh.core.model.meta import ModelMeta
from sqlmesh.core.model.kind import (
ExternalKind,
ModelKindName,
SeedKind,
ModelKind,
FullKind,
create_model_kind,
CustomKind,
)
from sqlmesh.core.model.seed import CsvSeedReader, Seed, create_seed
from sqlmesh.core.renderer import ExpressionRenderer, QueryRenderer
from sqlmesh.core.signal import SignalRegistry
from sqlmesh.utils import columns_to_types_all_known, str_to_bool, UniqueKeyDict
from sqlmesh.utils.cron import CroniterCache
from sqlmesh.utils.date import TimeLike, make_inclusive, to_datetime, to_time_column
from sqlmesh.utils.errors import ConfigError, SQLMeshError, raise_config_error, PythonModelEvalError
from sqlmesh.utils.hashing import hash_data
from sqlmesh.utils.jinja import JinjaMacroRegistry, extract_macro_references_and_variables
from sqlmesh.utils.pydantic import PydanticModel, PRIVATE_FIELDS
from sqlmesh.utils.metaprogramming import (
Executable,
SqlValue,
build_env,
prepare_env,
serialize_env,
format_evaluated_code_exception,
)
if t.TYPE_CHECKING:
from sqlglot.dialects.dialect import DialectType
from sqlmesh.core.node import _Node
from sqlmesh.core._typing import Self, TableName, SessionProperties
from sqlmesh.core.context import ExecutionContext
from sqlmesh.core.engine_adapter import EngineAdapter
from sqlmesh.core.engine_adapter._typing import QueryOrDF
from sqlmesh.core.engine_adapter.shared import DataObjectType
from sqlmesh.core.linter.rule import Rule
from sqlmesh.core.snapshot import DeployabilityIndex, Node, Snapshot
from sqlmesh.utils.jinja import MacroReference
logger = logging.getLogger(__name__)
PROPERTIES = {"physical_properties", "session_properties", "virtual_properties"}
RUNTIME_RENDERED_MODEL_FIELDS = {
"audits",
"signals",
"merge_filter",
} | PROPERTIES
CRON_SHORTCUTS = {
"@midnight",
"@hourly",
"@daily",
"@weekly",
"@monthly",
"@yearly",
"@annually",
}
class _Model(ModelMeta, frozen=True):
"""Model is the core abstraction for user defined datasets.
A model consists of logic that fetches the data (a SQL query, a Python script or a seed) and metadata
associated with it. Models can be run on arbitrary cadences and support incremental or full refreshes.
Models can also be materialized into physical tables or shared across other models as temporary views.
Example:
MODEL (
name sushi.order_items,
owner jen,
cron '@daily',
start '2020-01-01',
partitioned_by ds
);
@DEF(var, 'my_var');
SELECT
1 AS column_a # my first column,
@var AS my_column # my second column,
;
Args:
name: The name of the model, which is of the form [catalog].[db].table.
The catalog and db are optional.
dialect: The SQL dialect that the model's query is written in. By default,
this is assumed to be the dialect of the context.
owner: The owner of the model.
cron: A cron string specifying how often the model should be refreshed, leveraging the
[croniter](https://github.com/kiorky/croniter) library.
description: The optional model description.
stamp: An optional arbitrary string sequence used to create new model versions without making
changes to any of the functional components of the definition.
start: The earliest date that the model will be backfilled for. If this is None,
then the date is inferred by taking the most recent start date of its ancestors.
The start date can be a static datetime or a relative datetime like "1 year ago"
end: The date that the model will be backfilled up until. Follows the same syntax as 'start',
should be omitted if there is no end date.
lookback: The number of previous incremental intervals in the lookback window.
table_format: The table format used to manage the physical table files defined by `storage_format`, only applicable in certain engines.
(eg, 'iceberg', 'delta', 'hudi')
storage_format: The storage format used to store the physical table, only applicable in certain engines.
(eg. 'parquet', 'orc')
partitioned_by: The partition columns or engine specific expressions, only applicable in certain engines. (eg. (ds, hour))
clustered_by: The cluster columns or engine specific expressions, only applicable in certain engines. (eg. (ds, hour))
python_env: Dictionary containing all global variables needed to render the model's macros.
mapping_schema: The schema of table names to column and types.
extract_dependencies_from_query: Whether to extract additional dependencies from the rendered model's query.
physical_schema_override: The desired physical schema name override.
"""
python_env: t.Dict[str, Executable] = {}
jinja_macros: JinjaMacroRegistry = JinjaMacroRegistry()
audit_definitions: t.Dict[str, ModelAudit] = {}
mapping_schema: t.Dict[str, t.Any] = {}
extract_dependencies_from_query: bool = True
pre_statements_: t.Optional[t.List[ParsableSql]] = Field(default=None, alias="pre_statements")
post_statements_: t.Optional[t.List[ParsableSql]] = Field(default=None, alias="post_statements")
on_virtual_update_: t.Optional[t.List[ParsableSql]] = Field(
default=None, alias="on_virtual_update"
)
_full_depends_on: t.Optional[t.Set[str]] = None
_statement_renderer_cache: t.Dict[int, ExpressionRenderer] = {}
_is_metadata_only_change_cache: t.Dict[int, bool] = {}
_expressions_validator = ParsableSql.validator()
def __getstate__(self) -> t.Dict[t.Any, t.Any]:
state = super().__getstate__()
private = state[PRIVATE_FIELDS]
private["_statement_renderer_cache"] = {}
return state
def copy(self, **kwargs: t.Any) -> Self:
model = super().copy(**kwargs)
model._statement_renderer_cache = {}
return model
def render(
self,
*,
context: ExecutionContext,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
**kwargs: t.Any,
) -> t.Iterator[QueryOrDF]:
"""Renders the content of this model in a form of either a SELECT query, executing which the data for this model can
be fetched, or a dataframe object which contains the data itself.
The type of the returned object (query or dataframe) depends on whether the model was sourced from a SQL query,
a Python script or a pre-built dataset (seed).
Args:
context: The execution context used for fetching data.
start: The start date/time of the run.
end: The end date/time of the run.
execution_time: The date/time time reference to use for execution time.
Returns:
A generator which yields either a query object or one of the supported dataframe objects.
"""
yield self.render_query_or_raise(
start=start,
end=end,
execution_time=execution_time,
snapshots=context.snapshots,
deployability_index=context.deployability_index,
engine_adapter=context.engine_adapter,
**kwargs,
)
def render_definition(
self,
include_python: bool = True,
include_defaults: bool = False,
render_query: bool = False,
) -> t.List[exp.Expr]:
"""Returns the original list of sql expressions comprising the model definition.
Args:
include_python: Whether or not to include Python code in the rendered definition.
"""
expressions = []
comment = None
for field_name, field_info in ModelMeta.all_field_infos().items():
field_value = getattr(self, field_name)
if (include_defaults and field_value) or field_value != field_info.default:
if field_name == "description":
comment = field_value
elif field_name == "kind":
expressions.append(
exp.Property(
this="kind",
value=field_value.to_expression(dialect=self.dialect),
)
)
elif field_name == "name":
expressions.append(
exp.Property(
this=field_name,
value=exp.to_table(field_value, dialect=self.dialect),
)
)
elif field_name not in ("default_catalog", "enabled", "ignored_rules_"):
expressions.append(
exp.Property(
this=field_info.alias or field_name,
value=META_FIELD_CONVERTER.get(field_name, exp.to_identifier)(
field_value
),
)
)
model = d.Model(expressions=expressions)
model.comments = [comment] if comment else None
jinja_expressions = []
python_expressions = []
if include_python:
python_env = d.PythonCode(expressions=sorted_python_env_payloads(self.python_env))
if python_env.expressions:
python_expressions.append(python_env)
jinja_expressions = self.jinja_macros.to_expressions()
return [
model,
*python_expressions,
*jinja_expressions,
]
def render_query(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[str, Snapshot]] = None,
table_mapping: t.Optional[t.Dict[str, str]] = None,
expand: t.Iterable[str] = tuple(),
deployability_index: t.Optional[DeployabilityIndex] = None,
engine_adapter: t.Optional[EngineAdapter] = None,
**kwargs: t.Any,
) -> t.Optional[exp.Query]:
"""Renders a model's query, expanding macros with provided kwargs, and optionally expanding referenced models.
Args:
start: The start datetime to render. Defaults to epoch start.
end: The end datetime to render. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
snapshots: All upstream snapshots (by name) to use for expansion and mapping of physical locations.
table_mapping: Table mapping of physical locations. Takes precedence over snapshot mappings.
expand: Expand referenced models as subqueries. This is used to bypass backfills when running queries
that depend on materialized tables. Model definitions are inlined and can thus be run end to
end on the fly.
deployability_index: Determines snapshots that are deployable in the context of this render.
kwargs: Additional kwargs to pass to the renderer.
Returns:
The rendered expression.
"""
return exp.select(
*(
exp.cast(exp.Null(), column_type, copy=False).as_(name, copy=False, quoted=True)
for name, column_type in (self.columns_to_types or {}).items()
),
copy=False,
).from_(exp.values([tuple([1])], alias="t", columns=["dummy"]), copy=False)
def render_query_or_raise(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[str, Snapshot]] = None,
table_mapping: t.Optional[t.Dict[str, str]] = None,
expand: t.Iterable[str] = tuple(),
deployability_index: t.Optional[DeployabilityIndex] = None,
engine_adapter: t.Optional[EngineAdapter] = None,
**kwargs: t.Any,
) -> exp.Query:
"""Same as `render_query()` but raises an exception if the query can't be rendered.
Args:
start: The start datetime to render. Defaults to epoch start.
end: The end datetime to render. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
snapshots: All upstream snapshots (by model name) to use for expansion and mapping of physical locations.
table_mapping: Table mapping of physical locations. Takes precedence over snapshot mappings.
expand: Expand referenced models as subqueries. This is used to bypass backfills when running queries
that depend on materialized tables. Model definitions are inlined and can thus be run end to
end on the fly.
deployability_index: Determines snapshots that are deployable in the context of this render.
kwargs: Additional kwargs to pass to the renderer.
Returns:
The rendered expression.
"""
query = self.render_query(
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
table_mapping=table_mapping,
expand=expand,
deployability_index=deployability_index,
engine_adapter=engine_adapter,
**kwargs,
)
if query is None:
raise SQLMeshError(f"Failed to render query for model '{self.name}'.")
return query
def render_pre_statements(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Collection[Snapshot]] = None,
expand: t.Iterable[str] = tuple(),
deployability_index: t.Optional[DeployabilityIndex] = None,
engine_adapter: t.Optional[EngineAdapter] = None,
inside_transaction: t.Optional[bool] = True,
**kwargs: t.Any,
) -> t.List[exp.Expr]:
"""Renders pre-statements for a model.
Pre-statements are statements that preceded the model's SELECT query.
Args:
start: The start datetime to render. Defaults to epoch start.
end: The end datetime to render. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
snapshots: All upstream snapshots (by model name) to use for expansion and mapping of physical locations.
expand: Expand referenced models as subqueries. This is used to bypass backfills when running queries
that depend on materialized tables. Model definitions are inlined and can thus be run end to
end on the fly.
deployability_index: Determines snapshots that are deployable in the context of this render.
kwargs: Additional kwargs to pass to the renderer.
Returns:
The list of rendered expressions.
"""
return self._render_statements(
[
stmt
for stmt in self.pre_statements
if stmt.args.get("transaction", True) == inside_transaction
],
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
expand=expand,
deployability_index=deployability_index,
engine_adapter=engine_adapter,
**kwargs,
)
def render_post_statements(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[str, Snapshot]] = None,
expand: t.Iterable[str] = tuple(),
deployability_index: t.Optional[DeployabilityIndex] = None,
engine_adapter: t.Optional[EngineAdapter] = None,
inside_transaction: t.Optional[bool] = True,
**kwargs: t.Any,
) -> t.List[exp.Expr]:
"""Renders post-statements for a model.
Post-statements are statements that follow after the model's SELECT query.
Args:
start: The start datetime to render. Defaults to epoch start.
end: The end datetime to render. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
snapshots: All upstream snapshots (by model name) to use for expansion and mapping of physical locations.
expand: Expand referenced models as subqueries. This is used to bypass backfills when running queries
that depend on materialized tables. Model definitions are inlined and can thus be run end to
end on the fly.
deployability_index: Determines snapshots that are deployable in the context of this render.
inside_transaction: Whether to render hooks with transaction=True (inside) or transaction=False (outside).
kwargs: Additional kwargs to pass to the renderer.
Returns:
The list of rendered expressions.
"""
return self._render_statements(
[
stmt
for stmt in self.post_statements
if stmt.args.get("transaction", True) == inside_transaction
],
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
expand=expand,
deployability_index=deployability_index,
engine_adapter=engine_adapter,
**kwargs,
)
def render_on_virtual_update(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[str, Snapshot]] = None,
expand: t.Iterable[str] = tuple(),
deployability_index: t.Optional[DeployabilityIndex] = None,
engine_adapter: t.Optional[EngineAdapter] = None,
**kwargs: t.Any,
) -> t.List[exp.Expr]:
return self._render_statements(
self.on_virtual_update,
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
expand=expand,
deployability_index=deployability_index,
engine_adapter=engine_adapter,
**kwargs,
)
def render_audit_query(
self,
audit: Audit,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[str, Snapshot]] = None,
deployability_index: t.Optional[DeployabilityIndex] = None,
**kwargs: t.Any,
) -> exp.Query:
from sqlmesh.core.snapshot import DeployabilityIndex
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
snapshot = (snapshots or {}).get(self.fqn)
this_model = kwargs.pop("this_model", None) or (
snapshot.table_name(deployability_index.is_deployable(snapshot))
if snapshot
else self.fqn
)
columns_to_types: t.Optional[t.Dict[str, t.Any]] = None
if "engine_adapter" in kwargs:
try:
columns_to_types = kwargs["engine_adapter"].columns(this_model)
except Exception:
pass
if self.time_column:
low, high = [
self.convert_to_time_column(dt, columns_to_types)
for dt in make_inclusive(start or c.EPOCH, end or c.EPOCH, self.dialect)
]
where = self.time_column.column.between(low, high)
else:
where = None
# The model's name is already normalized, but in case of snapshots we also prepend a
# case-sensitive physical schema name, so we quote here to ensure that we won't have
# a broken schema reference after the resulting query is normalized in `render`.
quoted_model_name = quote_identifiers(
exp.to_table(this_model, dialect=self.dialect), dialect=self.dialect
)
query_renderer = QueryRenderer(
audit.query,
audit.dialect or self.dialect,
audit.macro_definitions,
path=audit._path or Path(),
jinja_macro_registry=audit.jinja_macros,
python_env=self.python_env,
only_execution_time=self.kind.only_execution_time,
default_catalog=self.default_catalog,
)
rendered_query = query_renderer.render(
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
deployability_index=deployability_index,
**{
**audit.defaults,
"this_model": exp.select("*").from_(quoted_model_name).where(where).subquery()
if where is not None
else quoted_model_name,
**kwargs,
}, # type: ignore
)
if rendered_query is None:
raise SQLMeshError(
f"Failed to render query for audit '{audit.name}', model '{self.name}'."
)
return rendered_query
@property
def pre_statements(self) -> t.List[exp.Expr]:
return self._get_parsed_statements("pre_statements_")
@property
def post_statements(self) -> t.List[exp.Expr]:
return self._get_parsed_statements("post_statements_")
@property
def on_virtual_update(self) -> t.List[exp.Expr]:
return self._get_parsed_statements("on_virtual_update_")
@property
def macro_definitions(self) -> t.List[d.MacroDef]:
"""All macro definitions from the list of expressions."""
return [
s
for s in self.pre_statements + self.post_statements + self.on_virtual_update
if isinstance(s, d.MacroDef)
]
def _get_parsed_statements(self, attr_name: str) -> t.List[exp.Expr]:
value = getattr(self, attr_name)
if not value:
return []
result = []
for v in value:
parsed = v.parse(self.dialect)
if getattr(v, "transaction", None) is not None:
parsed.set("transaction", v.transaction)
if not isinstance(parsed, exp.Semicolon):
result.append(parsed)
return result
def _render_statements(
self,
statements: t.Iterable[exp.Expr],
**kwargs: t.Any,
) -> t.List[exp.Expr]:
rendered = (
self._statement_renderer(statement).render(**kwargs)
for statement in statements
if not isinstance(statement, d.MacroDef)
)
return [r for expressions in rendered if expressions for r in expressions]
def _statement_renderer(self, expression: exp.Expr) -> ExpressionRenderer:
expression_key = id(expression)
if expression_key not in self._statement_renderer_cache:
self._statement_renderer_cache[expression_key] = ExpressionRenderer(
expression,
self.dialect,
self.macro_definitions,
path=self._path,
jinja_macro_registry=self.jinja_macros,
python_env=self.python_env,
only_execution_time=False,
default_catalog=self.default_catalog,
model=self,
)
return self._statement_renderer_cache[expression_key]
def render_signals(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
) -> t.List[t.Dict[str, str | int | float | bool]]:
"""Renders external; signals defined for this model.
Args:
start: The start datetime to render. Defaults to epoch start.
end: The end datetime to render. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
Returns:
The list of rendered expressions.
"""
def _render(e: exp.Expr) -> str | int | float | bool:
rendered_exprs = (
self._create_renderer(e).render(start=start, end=end, execution_time=execution_time)
or []
)
if len(rendered_exprs) != 1:
raise SQLMeshError(f"Expected one expression but got {len(rendered_exprs)}")
rendered = rendered_exprs[0]
if rendered.is_int:
return int(rendered.this)
if rendered.is_number:
return float(rendered.this)
if isinstance(rendered, (exp.Literal, exp.Boolean)):
return rendered.this
return rendered.sql(dialect=self.dialect)
# airflow only
return [
{k: _render(v) for k, v in signal.items()} for name, signal in self.signals if not name
]
def render_signal_calls(self) -> EvaluatableSignals:
python_env = self.python_env
env = prepare_env(python_env)
signals_to_kwargs = {
name: {
k: seq_get(self._create_renderer(v).render() or [], 0) for k, v in kwargs.items()
}
for name, kwargs in self.signals
if name
}
return EvaluatableSignals(
signals_to_kwargs=signals_to_kwargs,
python_env=python_env,
prepared_python_env=env,
)
def render_merge_filter(
self,
*,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
) -> t.Optional[exp.Expr]:
if self.merge_filter is None:
return None
rendered_exprs = (
self._create_renderer(self.merge_filter).render(
start=start, end=end, execution_time=execution_time
)
or []
)
if len(rendered_exprs) != 1:
raise SQLMeshError(f"Expected one expression but got {len(rendered_exprs)}")
return rendered_exprs[0].transform(d.replace_merge_table_aliases, dialect=self.dialect)
def _render_properties(
self, properties: t.Dict[str, exp.Expr] | SessionProperties, **render_kwargs: t.Any
) -> t.Dict[str, t.Any]:
def _render(expression: exp.Expr) -> exp.Expr | None:
# note: we use the _statement_renderer instead of _create_renderer because it sets model_fqn which
# in turn makes @this_model available in the evaluation context
rendered_exprs = self._statement_renderer(expression).render(**render_kwargs)
# Inform instead of raising for cases where a property is conditionally assigned
if not rendered_exprs or rendered_exprs[0].sql().lower() in {"none", "null"}:
logger.info(
f"Rendering '{expression.sql(dialect=self.dialect)}' did not return an expression"
)
return None
if len(rendered_exprs) != 1:
raise SQLMeshError(
f"Expected one result when rendering '{expression.sql(dialect=self.dialect)}' but got {len(rendered_exprs)}"
)
return rendered_exprs[0]
return {
k: rendered
for k, v in properties.items()
if (rendered := (_render(v) if isinstance(v, exp.Expr) else v))
}
def render_physical_properties(self, **render_kwargs: t.Any) -> t.Dict[str, t.Any]:
rendered = self._render_properties(properties=self.physical_properties, **render_kwargs)
# Some engines (e.g. StarRocks) accept properties whose values reference other models and
# need the physical table name rather than the logical view SQLMesh exposes. Resolve those.
engine_adapter = render_kwargs.get("engine_adapter")
resolve_keys: t.FrozenSet[str] = getattr(
engine_adapter, "RESOLVE_TABLE_REFS_IN_PHYSICAL_PROPERTIES", frozenset()
)
keys_to_resolve = [key for key in resolve_keys if key in rendered]
if keys_to_resolve:
# Local import: sqlmesh.core.snapshot.definition imports _Model, so importing
# to_table_mapping at module scope would be circular.
from sqlmesh.core.snapshot.definition import to_table_mapping
table_mapping = to_table_mapping(
(render_kwargs.get("snapshots") or {}).values(),
render_kwargs.get("deployability_index"),
)
for key in keys_to_resolve:
rendered[key] = _resolve_model_refs_to_physical_tables(
rendered[key], table_mapping, self.dialect
)
return rendered
def render_virtual_properties(self, **render_kwargs: t.Any) -> t.Dict[str, t.Any]:
return self._render_properties(properties=self.virtual_properties, **render_kwargs)
def render_session_properties(self, **render_kwargs: t.Any) -> t.Dict[str, t.Any]:
return self._render_properties(properties=self.session_properties, **render_kwargs)
def _create_renderer(self, expression: exp.Expr) -> ExpressionRenderer:
return ExpressionRenderer(
expression,
self.dialect,
[],
path=self._path,
jinja_macro_registry=self.jinja_macros,
python_env=self.python_env,
only_execution_time=False,
quote_identifiers=False,
)
def ctas_query(self, **render_kwarg: t.Any) -> exp.Query:
"""Return a dummy query to do a CTAS.
If a model's column types are unknown, the only way to create the table is to
run the fully expanded query. This can be expensive so we add a WHERE FALSE to all
SELECTS and hopefully the optimizer is smart enough to not do anything.
Args:
render_kwarg: Additional kwargs to pass to the renderer.
Return:
The mocked out ctas query.
"""
query = self.render_query_or_raise(**render_kwarg).limit(0)
for select_or_set_op in query.find_all(exp.Select, exp.SetOperation):
if isinstance(select_or_set_op, exp.Select) and select_or_set_op.args.get("from_"):
select_or_set_op.where(exp.false(), copy=False)
if self.managed_columns:
query.select(
*[
exp.alias_(exp.cast(exp.Null(), to=col_type), col)
for col, col_type in self.managed_columns.items()
if col not in query.named_selects
],
append=True,
copy=False,
)
return query
def text_diff(self, other: Node, rendered: bool = False) -> str:
"""Produce a text diff against another node.
Args:
other: The node to diff against.
rendered: Whether the diff should compare raw vs rendered models
Returns:
A unified text diff showing additions and deletions.
"""
if not isinstance(other, _Model):
raise SQLMeshError(
f"Cannot diff model '{self.name} against a non-model node '{other.name}'"
)
text_diff = d.text_diff(
self.render_definition(render_query=rendered),
other.render_definition(render_query=rendered),
self.dialect,
other.dialect,
).strip()
if not text_diff and not rendered:
text_diff = d.text_diff(
self.render_definition(render_query=True),
other.render_definition(render_query=True),
self.dialect,
other.dialect,
).strip()
return text_diff
def set_time_format(self, default_time_format: str = c.DEFAULT_TIME_COLUMN_FORMAT) -> None:
"""Sets the default time format for a model.
Args:
default_time_format: A python time format used as the default format when none is provided.
"""
if not self.time_column:
return
if self.time_column.format:
# Transpile the time column format into the generic dialect
formatted_time = format_time(
self.time_column.format,
d.Dialect.get_or_raise(self.dialect).TIME_MAPPING,
)
assert formatted_time is not None
self.time_column.format = formatted_time
else:
self.time_column.format = default_time_format
def convert_to_time_column(
self, time: TimeLike, columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None
) -> exp.Expr:
"""Convert a TimeLike object to the same time format and type as the model's time column."""
if self.time_column:
if columns_to_types is None:
columns_to_types = self.columns_to_types_or_raise
if self.time_column.column.name not in columns_to_types:
raise ConfigError(
f"Time column '{self.time_column.column.sql(dialect=self.dialect)}' not found in model '{self.name}'."
)
time_column_type = columns_to_types[self.time_column.column.name]
return to_time_column(
time,
time_column_type,
self.dialect,
self.time_column.format,
)
return exp.convert(time)
def set_mapping_schema(self, schema: t.Dict) -> None:
self.mapping_schema.clear()
self.mapping_schema.update(schema)
def update_schema(self, schema: MappingSchema) -> None:
"""Updates the schema for this model's dependencies based on the given mapping schema."""
for dep in self.depends_on:
table = exp.to_table(dep)
mapping_schema = schema.find(table)
if mapping_schema:
nested_set(
self.mapping_schema,
tuple(part.sql(copy=False) for part in table.parts),
{col: dtype.sql(dialect=self.dialect) for col, dtype in mapping_schema.items()},
)
@property
def depends_on(self) -> t.Set[str]:
"""All of the upstream dependencies referenced in the model's query, excluding self references.
Returns:
A list of all the upstream table names.
"""
return self.full_depends_on - {self.fqn}
@property
def columns_to_types(self) -> t.Optional[t.Dict[str, exp.DataType]]:
"""Returns the mapping of column names to types of this model."""
if self.columns_to_types_ is None:
return None
return {**self.columns_to_types_, **self.managed_columns}
@property
def columns_to_types_or_raise(self) -> t.Dict[str, exp.DataType]:
"""Returns the mapping of column names to types of this model or raise if not available."""
columns_to_types = self.columns_to_types
if columns_to_types is None:
raise SQLMeshError(f"Column information is not available for model '{self.name}'")
return columns_to_types
@property
def annotated(self) -> bool:
"""Checks if all column projection types of this model are known."""
if self.columns_to_types is None:
return False
columns_to_types = {
k: v for k, v in self.columns_to_types.items() if k not in self.managed_columns
}
if not columns_to_types:
return False
return columns_to_types_all_known(columns_to_types)
@property
def sorted_python_env(self) -> t.List[t.Tuple[str, Executable]]:
"""Returns the python env sorted by executable kind and then var name."""
return sorted(self.python_env.items(), key=lambda x: (x[1].kind, x[0]))
@property
def view_name(self) -> str:
return self.fully_qualified_table.name
@property
def schema_name(self) -> str:
return self.fully_qualified_table.db or c.DEFAULT_SCHEMA
@property
def physical_schema(self) -> str:
return self.physical_schema_override or f"{c.SQLMESH}__{self.schema_name}"
@property
def is_sql(self) -> bool:
return False
@property
def is_python(self) -> bool:
return False
@property
def is_seed(self) -> bool:
return False
@property
def depends_on_self(self) -> bool:
return self.fqn in self.full_depends_on
@property
def forward_only(self) -> bool:
return getattr(self.kind, "forward_only", False)
@property
def disable_restatement(self) -> bool:
return getattr(self.kind, "disable_restatement", False)
@property
def auto_restatement_intervals(self) -> t.Optional[int]:
return getattr(self.kind, "auto_restatement_intervals", None)
@property
def auto_restatement_cron(self) -> t.Optional[str]:
return getattr(self.kind, "auto_restatement_cron", None)
def auto_restatement_croniter(self, value: TimeLike) -> CroniterCache:
cron = self.auto_restatement_cron
if cron is None:
raise SQLMeshError("Auto restatement cron is not set.")
return CroniterCache(cron, value)
@property
def wap_supported(self) -> bool:
return self.kind.is_materialized and (self.storage_format or "").lower() == "iceberg"
def validate_definition(self) -> None:
"""Validates the model's definition.
Raises:
ConfigError
"""
for field in ("partitioned_by", "clustered_by"):
values = getattr(self, field)
if values:
values = [
col.name
for expr in values
if not (
field == "clustered_by"
and (self.dialect or "").lower() == "databricks"
and isinstance(expr, exp.Var)
and expr.name.upper() in c.LIQUID_CLUSTERING_KEYWORDS
)