-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathevaluator.py
More file actions
2771 lines (2491 loc) · 109 KB
/
evaluator.py
File metadata and controls
2771 lines (2491 loc) · 109 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
"""
# SnapshotEvaluator
A snapshot evaluator is responsible for evaluating a snapshot given some runtime arguments, e.g. start
and end timestamps.
# Evaluation
Snapshot evaluation involves determining the queries necessary to evaluate a snapshot and using
`sqlmesh.core.engine_adapter` to execute the queries. Schemas, tables, and views are created if
they don't exist and data is inserted when applicable.
A snapshot evaluator also promotes and demotes snapshots to a given environment.
# Audits
A snapshot evaluator can also run the audits for a snapshot's node. This is often done after a snapshot
has been evaluated to check for data quality issues.
For more information about audits, see `sqlmesh.core.audit`.
"""
from __future__ import annotations
import abc
import logging
import typing as t
import sys
from collections import defaultdict
from contextlib import contextmanager
from functools import reduce
from sqlglot import exp, select
from sqlglot.executor import execute
from sqlmesh.core import constants as c
from sqlmesh.core import dialect as d
from sqlmesh.core.audit import Audit, StandaloneAudit
from sqlmesh.core.dialect import schema_
from sqlmesh.core.engine_adapter.shared import InsertOverwriteStrategy, DataObjectType, DataObject
from sqlmesh.core.macros import RuntimeStage
from sqlmesh.core.model import (
AuditResult,
IncrementalUnmanagedKind,
Model,
SeedModel,
SCDType2ByColumnKind,
SCDType2ByTimeKind,
ViewKind,
CustomKind,
)
from sqlmesh.core.model.kind import _Incremental
from sqlmesh.utils import CompletionStatus, columns_to_types_all_known
from sqlmesh.core.schema_diff import (
has_drop_alteration,
TableAlterOperation,
has_additive_alteration,
)
from sqlmesh.core.snapshot import (
DeployabilityIndex,
Intervals,
Snapshot,
SnapshotId,
SnapshotIdBatch,
SnapshotInfoLike,
SnapshotTableCleanupTask,
)
from sqlmesh.core.snapshot.execution_tracker import QueryExecutionTracker
from sqlmesh.utils import random_id, CorrelationId
from sqlmesh.utils.concurrency import (
concurrent_apply_to_snapshots,
concurrent_apply_to_values,
NodeExecutionFailedError,
)
from sqlmesh.utils.date import TimeLike, now, time_like_to_str
from sqlmesh.utils.errors import (
ConfigError,
DestructiveChangeError,
SQLMeshError,
format_destructive_change_msg,
format_additive_change_msg,
AdditiveChangeError,
)
if sys.version_info >= (3, 12):
from importlib import metadata
else:
import importlib_metadata as metadata # type: ignore
if t.TYPE_CHECKING:
from sqlmesh.core.engine_adapter._typing import DF, QueryOrDF
from sqlmesh.core.engine_adapter.base import EngineAdapter
from sqlmesh.core.environment import EnvironmentNamingInfo
logger = logging.getLogger(__name__)
class SnapshotCreationFailedError(SQLMeshError):
def __init__(
self, errors: t.List[NodeExecutionFailedError[SnapshotId]], skipped: t.List[SnapshotId]
):
messages = "\n\n".join(f"{error}\n {error.__cause__}" for error in errors)
super().__init__(f"Physical table creation failed:\n\n{messages}")
self.errors = errors
self.skipped = skipped
class SnapshotEvaluator:
"""Evaluates a snapshot given runtime arguments through an arbitrary EngineAdapter.
The SnapshotEvaluator contains the business logic to generically evaluate a snapshot.
It is responsible for delegating queries to the EngineAdapter. The SnapshotEvaluator
does not directly communicate with the underlying execution engine.
Args:
adapters: A single EngineAdapter or a dictionary of EngineAdapters where
the key is the gateway name. When a dictionary is provided, and not an
explicit default gateway its first item is treated as the default
adapter and used for the virtual layer.
ddl_concurrent_tasks: The number of concurrent tasks used for DDL
operations (table / view creation, deletion, etc). Default: 1.
"""
def __init__(
self,
adapters: EngineAdapter | t.Dict[str, EngineAdapter],
ddl_concurrent_tasks: int = 1,
selected_gateway: t.Optional[str] = None,
):
self.adapters = (
adapters if isinstance(adapters, t.Dict) else {selected_gateway or "": adapters}
)
self.execution_tracker = QueryExecutionTracker()
self.adapters = {
gateway: adapter.with_settings(query_execution_tracker=self.execution_tracker)
for gateway, adapter in self.adapters.items()
}
self.adapter = (
next(iter(self.adapters.values()))
if not selected_gateway
else self.adapters[selected_gateway]
)
self.selected_gateway = selected_gateway
self.ddl_concurrent_tasks = ddl_concurrent_tasks
def evaluate(
self,
snapshot: Snapshot,
*,
start: TimeLike,
end: TimeLike,
execution_time: TimeLike,
snapshots: t.Dict[str, Snapshot],
allow_destructive_snapshots: t.Optional[t.Set[str]] = None,
allow_additive_snapshots: t.Optional[t.Set[str]] = None,
deployability_index: t.Optional[DeployabilityIndex] = None,
batch_index: int = 0,
target_table_exists: t.Optional[bool] = None,
**kwargs: t.Any,
) -> t.Optional[str]:
"""Renders the snapshot's model, executes it and stores the result in the snapshot's physical table.
Args:
snapshot: Snapshot to evaluate.
start: The start datetime to render.
end: The end datetime to render.
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.
allow_destructive_snapshots: Snapshots for which destructive schema changes are allowed.
allow_additive_snapshots: Snapshots for which additive schema changes are allowed.
deployability_index: Determines snapshots that are deployable in the context of this evaluation.
batch_index: If the snapshot is part of a batch of related snapshots; which index in the batch is it
target_table_exists: Whether the target table exists. If None, the table will be checked for existence.
kwargs: Additional kwargs to pass to the renderer.
Returns:
The WAP ID of this evaluation if supported, None otherwise.
"""
with self.execution_tracker.track_execution(
SnapshotIdBatch(snapshot_id=snapshot.snapshot_id, batch_id=batch_index)
):
result = self._evaluate_snapshot(
start=start,
end=end,
execution_time=execution_time,
snapshot=snapshot,
snapshots=snapshots,
allow_destructive_snapshots=allow_destructive_snapshots or set(),
allow_additive_snapshots=allow_additive_snapshots or set(),
deployability_index=deployability_index,
batch_index=batch_index,
target_table_exists=target_table_exists,
**kwargs,
)
if result is None or isinstance(result, str):
return result
raise SQLMeshError(
f"Unexpected result {result} when evaluating snapshot {snapshot.snapshot_id}."
)
def evaluate_and_fetch(
self,
snapshot: Snapshot,
*,
start: TimeLike,
end: TimeLike,
execution_time: TimeLike,
snapshots: t.Dict[str, Snapshot],
limit: int,
deployability_index: t.Optional[DeployabilityIndex] = None,
**kwargs: t.Any,
) -> DF:
"""Renders the snapshot's model, executes it and returns a dataframe with the result.
Args:
snapshot: Snapshot to evaluate.
start: The start datetime to render.
end: The end datetime to render.
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.
limit: The maximum number of rows to fetch.
deployability_index: Determines snapshots that are deployable in the context of this evaluation.
kwargs: Additional kwargs to pass to the renderer.
Returns:
The result of the evaluation as a dataframe.
"""
import pandas as pd
adapter = self.get_adapter(snapshot.model.gateway)
render_kwargs = dict(
start=start,
end=end,
execution_time=execution_time,
snapshot=snapshot,
runtime_stage=RuntimeStage.EVALUATING,
**kwargs,
)
queries_or_dfs = self._render_snapshot_for_evaluation(
snapshot,
snapshots,
deployability_index or DeployabilityIndex.all_deployable(),
render_kwargs,
)
query_or_df = next(queries_or_dfs)
if isinstance(query_or_df, pd.DataFrame):
return query_or_df.head(limit)
if not isinstance(query_or_df, exp.Expression):
# We assume that if this branch is reached, `query_or_df` is a pyspark / snowpark / bigframe dataframe,
# so we use `limit` instead of `head` to get back a dataframe instead of List[Row]
# https://spark.apache.org/docs/3.1.1/api/python/reference/api/pyspark.sql.DataFrame.head.html#pyspark.sql.DataFrame.head
return query_or_df.limit(limit)
assert isinstance(query_or_df, exp.Query)
existing_limit = query_or_df.args.get("limit")
if existing_limit:
limit = min(limit, execute(exp.select(existing_limit.expression)).rows[0][0])
assert limit is not None
return adapter._fetch_native_df(query_or_df.limit(limit))
def promote(
self,
target_snapshots: t.Iterable[Snapshot],
environment_naming_info: EnvironmentNamingInfo,
deployability_index: t.Optional[DeployabilityIndex] = None,
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
snapshots: t.Optional[t.Dict[SnapshotId, Snapshot]] = None,
table_mapping: t.Optional[t.Dict[str, str]] = None,
on_complete: t.Optional[t.Callable[[SnapshotInfoLike], None]] = None,
) -> None:
"""Promotes the given collection of snapshots in the target environment by replacing a corresponding
view with a physical table associated with the given snapshot.
Args:
target_snapshots: Snapshots to promote.
environment_naming_info: Naming information for the target environment.
deployability_index: Determines snapshots that are deployable in the context of this promotion.
on_complete: A callback to call on each successfully promoted snapshot.
"""
tables_by_gateway: t.Dict[t.Union[str, None], t.List[exp.Table]] = defaultdict(list)
for snapshot in target_snapshots:
if snapshot.is_model and not snapshot.is_symbolic:
gateway = (
snapshot.model_gateway if environment_naming_info.gateway_managed else None
)
adapter = self.get_adapter(gateway)
table = snapshot.qualified_view_name.table_for_environment(
environment_naming_info, dialect=adapter.dialect
)
tables_by_gateway[gateway].append(table)
# A schema can be shared across multiple engines, so we need to group by gateway
for gateway, tables in tables_by_gateway.items():
if environment_naming_info.suffix_target.is_catalog:
self._create_catalogs(tables=tables, gateway=gateway)
gateway_table_pairs = [
(gateway, table) for gateway, tables in tables_by_gateway.items() for table in tables
]
self._create_schemas(gateway_table_pairs=gateway_table_pairs)
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
with self.concurrent_context():
concurrent_apply_to_snapshots(
target_snapshots,
lambda s: self._promote_snapshot(
s,
start=start,
end=end,
execution_time=execution_time,
snapshots=snapshots,
table_mapping=table_mapping,
environment_naming_info=environment_naming_info,
deployability_index=deployability_index, # type: ignore
on_complete=on_complete,
),
self.ddl_concurrent_tasks,
)
def demote(
self,
target_snapshots: t.Iterable[Snapshot],
environment_naming_info: EnvironmentNamingInfo,
table_mapping: t.Optional[t.Dict[str, str]] = None,
deployability_index: t.Optional[DeployabilityIndex] = None,
on_complete: t.Optional[t.Callable[[SnapshotInfoLike], None]] = None,
) -> None:
"""Demotes the given collection of snapshots in the target environment by removing its view.
Args:
target_snapshots: Snapshots to demote.
environment_naming_info: Naming info for the target environment.
on_complete: A callback to call on each successfully demoted snapshot.
"""
with self.concurrent_context():
concurrent_apply_to_snapshots(
target_snapshots,
lambda s: self._demote_snapshot(
s,
environment_naming_info,
deployability_index=deployability_index,
on_complete=on_complete,
table_mapping=table_mapping,
),
self.ddl_concurrent_tasks,
)
def create(
self,
target_snapshots: t.Iterable[Snapshot],
snapshots: t.Dict[SnapshotId, Snapshot],
deployability_index: t.Optional[DeployabilityIndex] = None,
on_start: t.Optional[t.Callable] = None,
on_complete: t.Optional[t.Callable[[SnapshotInfoLike], None]] = None,
allow_destructive_snapshots: t.Optional[t.Set[str]] = None,
allow_additive_snapshots: t.Optional[t.Set[str]] = None,
) -> CompletionStatus:
"""Creates a physical snapshot schema and table for the given collection of snapshots.
Args:
target_snapshots: Target snapshots.
snapshots: Mapping of snapshot ID to snapshot.
deployability_index: Determines snapshots that are deployable in the context of this creation.
on_start: A callback to initialize the snapshot creation progress bar.
on_complete: A callback to call on each successfully created snapshot.
allow_destructive_snapshots: Set of snapshots that are allowed to have destructive schema changes.
allow_additive_snapshots: Set of snapshots that are allowed to have additive schema changes.
Returns:
CompletionStatus: The status of the creation operation (success, failure, nothing to do).
"""
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
snapshots_to_create = self.get_snapshots_to_create(target_snapshots, deployability_index)
if not snapshots_to_create:
return CompletionStatus.NOTHING_TO_DO
if on_start:
on_start(snapshots_to_create)
self._create_snapshots(
snapshots_to_create=snapshots_to_create,
snapshots={s.name: s for s in snapshots.values()},
deployability_index=deployability_index,
on_complete=on_complete,
allow_destructive_snapshots=allow_destructive_snapshots or set(),
allow_additive_snapshots=allow_additive_snapshots or set(),
)
return CompletionStatus.SUCCESS
def create_physical_schemas(
self, snapshots: t.Iterable[Snapshot], deployability_index: DeployabilityIndex
) -> None:
"""Creates the physical schemas for the given snapshots.
Args:
snapshots: Snapshots to create physical schemas for.
deployability_index: Determines snapshots that are deployable in the context of this creation.
"""
tables_by_gateway: t.Dict[t.Optional[str], t.List[str]] = defaultdict(list)
for snapshot in snapshots:
if snapshot.is_model and not snapshot.is_symbolic:
tables_by_gateway[snapshot.model_gateway].append(
snapshot.table_name(is_deployable=deployability_index.is_deployable(snapshot))
)
gateway_table_pairs = [
(gateway, table) for gateway, tables in tables_by_gateway.items() for table in tables
]
self._create_schemas(gateway_table_pairs=gateway_table_pairs)
def get_snapshots_to_create(
self, target_snapshots: t.Iterable[Snapshot], deployability_index: DeployabilityIndex
) -> t.List[Snapshot]:
"""Returns a list of snapshots that need to have their physical tables created.
Args:
target_snapshots: Target snapshots.
deployability_index: Determines snapshots that are deployable / representative in the context of this creation.
"""
existing_data_objects = self._get_data_objects(target_snapshots, deployability_index)
snapshots_to_create = []
for snapshot in target_snapshots:
if not snapshot.is_model or snapshot.is_symbolic:
continue
if snapshot.snapshot_id not in existing_data_objects or (
snapshot.is_seed and not snapshot.intervals
):
snapshots_to_create.append(snapshot)
return snapshots_to_create
def _create_snapshots(
self,
snapshots_to_create: t.Iterable[Snapshot],
snapshots: t.Dict[str, Snapshot],
deployability_index: DeployabilityIndex,
on_complete: t.Optional[t.Callable[[SnapshotInfoLike], None]],
allow_destructive_snapshots: t.Set[str],
allow_additive_snapshots: t.Set[str],
) -> None:
"""Internal method to create tables in parallel."""
with self.concurrent_context():
errors, skipped = concurrent_apply_to_snapshots(
snapshots_to_create,
lambda s: self.create_snapshot(
s,
snapshots=snapshots,
deployability_index=deployability_index,
allow_destructive_snapshots=allow_destructive_snapshots,
allow_additive_snapshots=allow_additive_snapshots,
on_complete=on_complete,
),
self.ddl_concurrent_tasks,
raise_on_error=False,
)
if errors:
raise SnapshotCreationFailedError(errors, skipped)
def migrate(
self,
target_snapshots: t.Iterable[Snapshot],
snapshots: t.Dict[SnapshotId, Snapshot],
allow_destructive_snapshots: t.Optional[t.Set[str]] = None,
allow_additive_snapshots: t.Optional[t.Set[str]] = None,
deployability_index: t.Optional[DeployabilityIndex] = None,
) -> None:
"""Alters a physical snapshot table to match its snapshot's schema for the given collection of snapshots.
Args:
target_snapshots: Target snapshots.
snapshots: Mapping of snapshot ID to snapshot.
allow_destructive_snapshots: Set of snapshots that are allowed to have destructive schema changes.
allow_additive_snapshots: Set of snapshots that are allowed to have additive schema changes.
deployability_index: Determines snapshots that are deployable in the context of this evaluation.
"""
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
target_data_objects = self._get_data_objects(target_snapshots, deployability_index)
if not target_data_objects:
return
if not snapshots:
snapshots = {s.snapshot_id: s for s in target_snapshots}
allow_destructive_snapshots = allow_destructive_snapshots or set()
allow_additive_snapshots = allow_additive_snapshots or set()
snapshots_by_name = {s.name: s for s in snapshots.values()}
with self.concurrent_context():
# Only migrate snapshots for which there's an existing data object
concurrent_apply_to_snapshots(
snapshots_by_name.values(),
lambda s: self._migrate_snapshot(
s,
snapshots_by_name,
target_data_objects.get(s.snapshot_id),
allow_destructive_snapshots,
allow_additive_snapshots,
self.get_adapter(s.model_gateway),
deployability_index,
),
self.ddl_concurrent_tasks,
)
def cleanup(
self,
target_snapshots: t.Iterable[SnapshotTableCleanupTask],
on_complete: t.Optional[t.Callable[[str], None]] = None,
) -> None:
"""Cleans up the given snapshots by removing its table
Args:
target_snapshots: Snapshots to cleanup.
on_complete: A callback to call on each successfully deleted database object.
"""
snapshots_to_dev_table_only = {
t.snapshot.snapshot_id: t.dev_table_only for t in target_snapshots
}
with self.concurrent_context():
concurrent_apply_to_snapshots(
[t.snapshot for t in target_snapshots],
lambda s: self._cleanup_snapshot(
s,
snapshots_to_dev_table_only[s.snapshot_id],
self.get_adapter(s.model_gateway),
on_complete,
),
self.ddl_concurrent_tasks,
reverse_order=True,
)
def audit(
self,
snapshot: Snapshot,
*,
snapshots: t.Dict[str, Snapshot],
start: t.Optional[TimeLike] = None,
end: t.Optional[TimeLike] = None,
execution_time: t.Optional[TimeLike] = None,
deployability_index: t.Optional[DeployabilityIndex] = None,
wap_id: t.Optional[str] = None,
**kwargs: t.Any,
) -> t.List[AuditResult]:
"""Execute a snapshot's node's audit queries.
Args:
snapshot: Snapshot to evaluate.
snapshots: All upstream snapshots (by name) to use for expansion and mapping of physical locations.
start: The start datetime to audit. Defaults to epoch start.
end: The end datetime to audit. Defaults to epoch start.
execution_time: The date/time time reference to use for execution time.
deployability_index: Determines snapshots that are deployable in the context of this evaluation.
wap_id: The WAP ID if applicable, None otherwise.
kwargs: Additional kwargs to pass to the renderer.
"""
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
adapter = self.get_adapter(snapshot.model_gateway)
if not snapshot.version:
raise ConfigError(
f"Cannot audit '{snapshot.name}' because it has not been versioned yet. Apply a plan first."
)
if wap_id is not None:
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
original_table_name = snapshot.table_name(
is_deployable=deployability_index.is_deployable(snapshot)
)
wap_table_name = adapter.wap_table_name(original_table_name, wap_id)
logger.info(
"Auditing WAP table '%s', snapshot %s",
wap_table_name,
snapshot.snapshot_id,
)
table_mapping = kwargs.get("table_mapping") or {}
table_mapping[snapshot.name] = wap_table_name
kwargs["table_mapping"] = table_mapping
kwargs["this_model"] = exp.to_table(wap_table_name, dialect=adapter.dialect)
results = []
audits_with_args = snapshot.node.audits_with_args
force_non_blocking = False
if audits_with_args:
logger.info("Auditing snapshot %s", snapshot.snapshot_id)
if not deployability_index.is_deployable(snapshot) and not adapter.SUPPORTS_CLONING:
# For dev preview tables that aren't based on clones of the production table, only a subset of the data is typically available
# However, users still expect audits to run anwyay. Some audits (such as row count) are practically guaranteed to fail
# when run on only a subset of data, so we switch all audits to non blocking and the user can decide if they still want to proceed
force_non_blocking = True
for audit, audit_args in audits_with_args:
if force_non_blocking:
# remove any blocking indicator on the model itself
audit_args.pop("blocking", None)
# so that we can fall back to the audit's setting, which we override to blocking: False
audit = audit.model_copy(update={"blocking": False})
results.append(
self._audit(
audit=audit,
audit_args=audit_args,
snapshot=snapshot,
snapshots=snapshots,
start=start,
end=end,
execution_time=execution_time,
deployability_index=deployability_index,
**kwargs,
)
)
if wap_id is not None:
logger.info(
"Publishing evaluation results for snapshot %s, WAP ID '%s'",
snapshot.snapshot_id,
wap_id,
)
self.wap_publish_snapshot(snapshot, wap_id, deployability_index)
return results
@contextmanager
def concurrent_context(self) -> t.Iterator[None]:
try:
yield
finally:
self.recycle()
def recycle(self) -> None:
"""Closes all open connections and releases all allocated resources associated with any thread
except the calling one."""
try:
for adapter in self.adapters.values():
adapter.recycle()
except Exception:
logger.exception("Failed to recycle Snapshot Evaluator")
def close(self) -> None:
"""Closes all open connections and releases all allocated resources."""
try:
for adapter in self.adapters.values():
adapter.close()
except Exception:
logger.exception("Failed to close Snapshot Evaluator")
def set_correlation_id(self, correlation_id: CorrelationId) -> SnapshotEvaluator:
return SnapshotEvaluator(
{
gateway: adapter.with_settings(correlation_id=correlation_id)
for gateway, adapter in self.adapters.items()
},
self.ddl_concurrent_tasks,
self.selected_gateway,
)
def _evaluate_snapshot(
self,
start: TimeLike,
end: TimeLike,
execution_time: TimeLike,
snapshot: Snapshot,
snapshots: t.Dict[str, Snapshot],
allow_destructive_snapshots: t.Set[str],
allow_additive_snapshots: t.Set[str],
deployability_index: t.Optional[DeployabilityIndex],
batch_index: int,
target_table_exists: t.Optional[bool],
**kwargs: t.Any,
) -> t.Optional[str]:
"""Renders the snapshot's model and executes it. The return value depends on whether the limit was specified.
Args:
snapshot: Snapshot to evaluate.
start: The start datetime to render.
end: The end datetime to render.
execution_time: The date/time time reference to use for execution time.
snapshots: All upstream snapshots to use for expansion and mapping of physical locations.
allow_destructive_snapshots: Snapshots for which destructive schema changes are allowed.
allow_additive_snapshots: Snapshots for which additive schema changes are allowed.
deployability_index: Determines snapshots that are deployable in the context of this evaluation.
batch_index: If the snapshot is part of a batch of related snapshots; which index in the batch is it
target_table_exists: Whether the target table exists. If None, the table will be checked for existence.
kwargs: Additional kwargs to pass to the renderer.
"""
if not snapshot.is_model:
return None
model = snapshot.model
logger.info("Evaluating snapshot %s", snapshot.snapshot_id)
adapter = self.get_adapter(model.gateway)
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
is_snapshot_deployable = deployability_index.is_deployable(snapshot)
target_table_name = snapshot.table_name(is_deployable=is_snapshot_deployable)
# https://github.com/TobikoData/sqlmesh/issues/2609
# If there are no existing intervals yet; only consider this a first insert for the first snapshot in the batch
if target_table_exists is None:
target_table_exists = adapter.table_exists(target_table_name)
is_first_insert = (
not _intervals(snapshot, deployability_index) or not target_table_exists
) and batch_index == 0
# Use the 'creating' stage if the table doesn't exist yet to preserve backwards compatibility with existing projects
# that depend on a separate physical table creation stage.
runtime_stage = RuntimeStage.EVALUATING if target_table_exists else RuntimeStage.CREATING
common_render_kwargs = dict(
start=start,
end=end,
execution_time=execution_time,
snapshot=snapshot,
runtime_stage=runtime_stage,
**kwargs,
)
create_render_kwargs = dict(
engine_adapter=adapter,
snapshots=snapshots,
deployability_index=deployability_index,
**common_render_kwargs,
)
create_render_kwargs["runtime_stage"] = RuntimeStage.CREATING
render_statements_kwargs = dict(
engine_adapter=adapter,
snapshots=snapshots,
deployability_index=deployability_index,
**common_render_kwargs,
)
rendered_physical_properties = snapshot.model.render_physical_properties(
**render_statements_kwargs
)
with (
adapter.transaction(),
adapter.session(snapshot.model.render_session_properties(**render_statements_kwargs)),
):
adapter.execute(model.render_pre_statements(**render_statements_kwargs))
if not target_table_exists or (model.is_seed and not snapshot.intervals):
columns_to_types_provided = (
model.kind.is_materialized
and model.columns_to_types_
and columns_to_types_all_known(model.columns_to_types_)
) or (model.depends_on_self and model.annotated)
if self._can_clone(snapshot, deployability_index):
self._clone_snapshot_in_dev(
snapshot=snapshot,
snapshots=snapshots,
deployability_index=deployability_index,
render_kwargs=create_render_kwargs,
rendered_physical_properties=rendered_physical_properties,
allow_destructive_snapshots=allow_destructive_snapshots,
allow_additive_snapshots=allow_additive_snapshots,
)
runtime_stage = RuntimeStage.EVALUATING
target_table_exists = True
elif columns_to_types_provided or model.is_seed or model.kind.is_scd_type_2:
self._execute_create(
snapshot=snapshot,
table_name=target_table_name,
is_table_deployable=is_snapshot_deployable,
deployability_index=deployability_index,
create_render_kwargs=create_render_kwargs,
rendered_physical_properties=rendered_physical_properties,
dry_run=False,
run_pre_post_statements=False,
)
runtime_stage = RuntimeStage.EVALUATING
target_table_exists = True
evaluate_render_kwargs = {
**common_render_kwargs,
"runtime_stage": runtime_stage,
"snapshot_table_exists": target_table_exists,
}
wap_id: t.Optional[str] = None
if (
snapshot.is_materialized
and target_table_exists
and (model.wap_supported or adapter.wap_supported(target_table_name))
):
wap_id = random_id()[0:8]
logger.info("Using WAP ID '%s' for snapshot %s", wap_id, snapshot.snapshot_id)
target_table_name = adapter.wap_prepare(target_table_name, wap_id)
self._render_and_insert_snapshot(
start=start,
end=end,
execution_time=execution_time,
snapshot=snapshot,
snapshots=snapshots,
render_kwargs=evaluate_render_kwargs,
create_render_kwargs=create_render_kwargs,
rendered_physical_properties=rendered_physical_properties,
deployability_index=deployability_index,
target_table_name=target_table_name,
is_first_insert=is_first_insert,
batch_index=batch_index,
)
adapter.execute(model.render_post_statements(**render_statements_kwargs))
return wap_id
def create_snapshot(
self,
snapshot: Snapshot,
snapshots: t.Dict[str, Snapshot],
deployability_index: DeployabilityIndex,
allow_destructive_snapshots: t.Set[str],
allow_additive_snapshots: t.Set[str],
on_complete: t.Optional[t.Callable[[SnapshotInfoLike], None]] = None,
) -> None:
"""Creates a physical table for the given snapshot.
Args:
snapshot: Snapshot to create.
snapshots: All upstream snapshots to use for expansion and mapping of physical locations.
deployability_index: Determines snapshots that are deployable in the context of this creation.
on_complete: A callback to call on each successfully created database object.
allow_destructive_snapshots: Snapshots for which destructive schema changes are allowed.
allow_additive_snapshots: Snapshots for which additive schema changes are allowed.
"""
if not snapshot.is_model:
return
logger.info("Creating a physical table for snapshot %s", snapshot.snapshot_id)
adapter = self.get_adapter(snapshot.model.gateway)
create_render_kwargs: t.Dict[str, t.Any] = dict(
engine_adapter=adapter,
snapshots=snapshots,
runtime_stage=RuntimeStage.CREATING,
deployability_index=deployability_index,
)
with (
adapter.transaction(),
adapter.session(snapshot.model.render_session_properties(**create_render_kwargs)),
):
rendered_physical_properties = snapshot.model.render_physical_properties(
**create_render_kwargs
)
if self._can_clone(snapshot, deployability_index):
self._clone_snapshot_in_dev(
snapshot=snapshot,
snapshots=snapshots,
deployability_index=deployability_index,
render_kwargs=create_render_kwargs,
rendered_physical_properties=rendered_physical_properties,
allow_destructive_snapshots=allow_destructive_snapshots,
allow_additive_snapshots=allow_additive_snapshots,
)
else:
is_table_deployable = deployability_index.is_deployable(snapshot)
self._execute_create(
snapshot=snapshot,
table_name=snapshot.table_name(is_deployable=is_table_deployable),
is_table_deployable=is_table_deployable,
deployability_index=deployability_index,
create_render_kwargs=create_render_kwargs,
rendered_physical_properties=rendered_physical_properties,
dry_run=True,
)
if on_complete is not None:
on_complete(snapshot)
def wap_publish_snapshot(
self,
snapshot: Snapshot,
wap_id: str,
deployability_index: t.Optional[DeployabilityIndex],
) -> None:
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
table_name = snapshot.table_name(is_deployable=deployability_index.is_deployable(snapshot))
adapter = self.get_adapter(snapshot.model_gateway)
adapter.wap_publish(table_name, wap_id)
def _render_and_insert_snapshot(
self,
start: TimeLike,
end: TimeLike,
execution_time: TimeLike,
snapshot: Snapshot,
snapshots: t.Dict[str, Snapshot],
render_kwargs: t.Dict[str, t.Any],
create_render_kwargs: t.Dict[str, t.Any],
rendered_physical_properties: t.Dict[str, exp.Expression],
deployability_index: DeployabilityIndex,
target_table_name: str,
is_first_insert: bool,
batch_index: int,
) -> None:
if not snapshot.is_model or snapshot.is_seed:
return
logger.info("Inserting data for snapshot %s", snapshot.snapshot_id)
model = snapshot.model
adapter = self.get_adapter(model.gateway)
evaluation_strategy = _evaluation_strategy(snapshot, adapter)
queries_or_dfs = self._render_snapshot_for_evaluation(
snapshot,
snapshots,
deployability_index,
render_kwargs,
)
def apply(query_or_df: QueryOrDF, index: int = 0) -> None:
if index > 0:
evaluation_strategy.append(
table_name=target_table_name,
query_or_df=query_or_df,
model=snapshot.model,
snapshot=snapshot,
snapshots=snapshots,
deployability_index=deployability_index,
batch_index=batch_index,
start=start,
end=end,
execution_time=execution_time,
physical_properties=rendered_physical_properties,
render_kwargs=create_render_kwargs,
)
else:
logger.info(
"Inserting batch (%s, %s) into %s'",
time_like_to_str(start),
time_like_to_str(end),
target_table_name,
)
evaluation_strategy.insert(
table_name=target_table_name,
query_or_df=query_or_df,
is_first_insert=is_first_insert,
model=snapshot.model,
snapshot=snapshot,
snapshots=snapshots,
deployability_index=deployability_index,
batch_index=batch_index,
start=start,
end=end,
execution_time=execution_time,
physical_properties=rendered_physical_properties,
render_kwargs=create_render_kwargs,
)
# DataFrames, unlike SQL expressions, can provide partial results by yielding dataframes. As a result,
# if the engine supports INSERT OVERWRITE or REPLACE WHERE and the snapshot is incremental by time range, we risk
# having a partial result since each dataframe write can re-truncate partitions. To avoid this, we
# union all the dataframes together before writing. For pandas this could result in OOM and a potential
# workaround for that would be to serialize pandas to disk and then read it back with Spark.
# Note: We assume that if multiple things are yielded from `queries_or_dfs` that they are dataframes
# and not SQL expressions.
if (
adapter.INSERT_OVERWRITE_STRATEGY
in (
InsertOverwriteStrategy.INSERT_OVERWRITE,
InsertOverwriteStrategy.REPLACE_WHERE,
)
and snapshot.is_incremental_by_time_range
):
import pandas as pd
query_or_df = reduce(
lambda a, b: (
pd.concat([a, b], ignore_index=True) # type: ignore
if isinstance(a, pd.DataFrame)
else a.union_all(b) # type: ignore
), # type: ignore
queries_or_dfs,
)
apply(query_or_df, index=0)
else:
for index, query_or_df in enumerate(queries_or_dfs):
apply(query_or_df, index)
def _render_snapshot_for_evaluation(
self,
snapshot: Snapshot,
snapshots: t.Dict[str, Snapshot],
deployability_index: DeployabilityIndex,
render_kwargs: t.Dict[str, t.Any],
) -> t.Iterator[QueryOrDF]:
from sqlmesh.core.context import ExecutionContext
model = snapshot.model