-
Notifications
You must be signed in to change notification settings - Fork 378
Expand file tree
/
Copy pathtest_change_scenarios.py
More file actions
1517 lines (1264 loc) · 55.1 KB
/
test_change_scenarios.py
File metadata and controls
1517 lines (1264 loc) · 55.1 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 typing as t
import json
from datetime import timedelta
from unittest import mock
import pandas as pd # noqa: TID253
import pytest
from pathlib import Path
from sqlmesh.core.model.common import ParsableSql
import time_machine
from sqlglot.expressions import DataType
import re
from sqlmesh.cli.project_init import init_example_project
from sqlmesh.core import constants as c
from sqlmesh.core import dialect as d
from sqlmesh.core.config import (
AutoCategorizationMode,
Config,
GatewayConfig,
ModelDefaultsConfig,
DuckDBConnectionConfig,
)
from sqlmesh.core.context import Context
from sqlmesh.core.config.categorizer import CategorizerConfig
from sqlmesh.core.model import (
FullKind,
ModelKind,
ModelKindName,
SqlModel,
PythonModel,
ViewKind,
load_sql_based_model,
)
from sqlmesh.core.model.kind import model_kind_type_from_name
from sqlmesh.core.plan import Plan, SnapshotIntervals
from sqlmesh.core.snapshot import (
SnapshotChangeCategory,
)
from sqlmesh.utils.date import now, to_timestamp
from sqlmesh.utils.errors import (
SQLMeshError,
)
from tests.core.integration.utils import (
apply_to_environment,
add_projection_to_model,
initial_add,
change_data_type,
validate_apply_basics,
change_model_kind,
validate_model_kind_change,
validate_query_change,
validate_plan_changes,
)
pytestmark = pytest.mark.slow
def test_auto_categorization(sushi_context: Context):
environment = "dev"
for config in sushi_context.configs.values():
config.plan.auto_categorize_changes.sql = AutoCategorizationMode.FULL
initial_add(sushi_context, environment)
version = sushi_context.get_snapshot(
"sushi.waiter_as_customer_by_day", raise_if_missing=True
).version
fingerprint = sushi_context.get_snapshot(
"sushi.waiter_as_customer_by_day", raise_if_missing=True
).fingerprint
model = t.cast(SqlModel, sushi_context.get_model("sushi.customers", raise_if_missing=True))
sushi_context.upsert_model(
"sushi.customers",
query_=ParsableSql(sql=model.query.select("'foo' AS foo").sql(dialect=model.dialect)), # type: ignore
)
apply_to_environment(sushi_context, environment)
assert (
sushi_context.get_snapshot(
"sushi.waiter_as_customer_by_day", raise_if_missing=True
).change_category
== SnapshotChangeCategory.INDIRECT_NON_BREAKING
)
assert (
sushi_context.get_snapshot(
"sushi.waiter_as_customer_by_day", raise_if_missing=True
).fingerprint
!= fingerprint
)
assert (
sushi_context.get_snapshot("sushi.waiter_as_customer_by_day", raise_if_missing=True).version
== version
)
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_breaking_only_impacts_immediate_children(init_and_plan_context: t.Callable):
context, _ = init_and_plan_context("examples/sushi")
context.upsert_model(context.get_model("sushi.top_waiters").copy(update={"kind": FullKind()}))
context.plan("prod", skip_tests=True, auto_apply=True, no_prompts=True)
breaking_model = context.get_model("sushi.orders")
breaking_model = breaking_model.copy(update={"stamp": "force new version"})
context.upsert_model(breaking_model)
breaking_snapshot = context.get_snapshot(breaking_model, raise_if_missing=True)
non_breaking_model = context.get_model("sushi.waiter_revenue_by_day")
context.upsert_model(add_projection_to_model(t.cast(SqlModel, non_breaking_model)))
non_breaking_snapshot = context.get_snapshot(non_breaking_model, raise_if_missing=True)
top_waiter_snapshot = context.get_snapshot("sushi.top_waiters", raise_if_missing=True)
plan_builder = context.plan_builder("dev", skip_tests=True, enable_preview=False)
plan_builder.set_choice(breaking_snapshot, SnapshotChangeCategory.BREAKING)
plan = plan_builder.build()
assert (
plan.context_diff.snapshots[breaking_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.BREAKING
)
assert (
plan.context_diff.snapshots[non_breaking_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert (
plan.context_diff.snapshots[top_waiter_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.INDIRECT_NON_BREAKING
)
assert plan.start == to_timestamp("2023-01-01")
assert not any(i.snapshot_id == top_waiter_snapshot.snapshot_id for i in plan.missing_intervals)
context.apply(plan)
assert (
not context.plan_builder("dev", skip_tests=True, enable_preview=False)
.build()
.requires_backfill
)
# Deploy everything to prod.
plan = context.plan_builder("prod", skip_tests=True).build()
assert not plan.missing_intervals
context.apply(plan)
assert (
not context.plan_builder("prod", skip_tests=True, enable_preview=False)
.build()
.requires_backfill
)
@pytest.mark.parametrize(
"context_fixture",
["sushi_context", "sushi_dbt_context", "sushi_test_dbt_context", "sushi_no_default_catalog"],
)
def test_model_add(context_fixture: Context, request):
initial_add(request.getfixturevalue(context_fixture), "dev")
def test_model_removed(sushi_context: Context):
environment = "dev"
initial_add(sushi_context, environment)
top_waiters_snapshot_id = sushi_context.get_snapshot(
"sushi.top_waiters", raise_if_missing=True
).snapshot_id
sushi_context._models.pop('"memory"."sushi"."top_waiters"')
def _validate_plan(context, plan):
validate_plan_changes(plan, removed=[top_waiters_snapshot_id])
assert not plan.missing_intervals
def _validate_apply(context):
assert not sushi_context.get_snapshot("sushi.top_waiters", raise_if_missing=False)
assert sushi_context.state_reader.get_snapshots([top_waiters_snapshot_id])
env = sushi_context.state_reader.get_environment(environment)
assert env
assert all(snapshot.name != '"memory"."sushi"."top_waiters"' for snapshot in env.snapshots)
apply_to_environment(
sushi_context,
environment,
SnapshotChangeCategory.BREAKING,
plan_validators=[_validate_plan],
apply_validators=[_validate_apply],
)
def test_non_breaking_change(sushi_context: Context):
environment = "dev"
initial_add(sushi_context, environment)
validate_query_change(sushi_context, environment, SnapshotChangeCategory.NON_BREAKING, False)
def test_breaking_change(sushi_context: Context):
environment = "dev"
initial_add(sushi_context, environment)
validate_query_change(sushi_context, environment, SnapshotChangeCategory.BREAKING, False)
def test_logical_change(sushi_context: Context):
environment = "dev"
initial_add(sushi_context, environment)
previous_sushi_items_version = sushi_context.get_snapshot(
"sushi.items", raise_if_missing=True
).version
change_data_type(
sushi_context,
"sushi.items",
DataType.Type.DOUBLE,
DataType.Type.FLOAT,
)
apply_to_environment(sushi_context, environment, SnapshotChangeCategory.NON_BREAKING)
change_data_type(
sushi_context,
"sushi.items",
DataType.Type.FLOAT,
DataType.Type.DOUBLE,
)
apply_to_environment(sushi_context, environment, SnapshotChangeCategory.NON_BREAKING)
assert (
sushi_context.get_snapshot("sushi.items", raise_if_missing=True).version
== previous_sushi_items_version
)
@pytest.mark.parametrize(
"from_, to",
[
(ModelKindName.INCREMENTAL_BY_TIME_RANGE, ModelKindName.FULL),
(ModelKindName.FULL, ModelKindName.INCREMENTAL_BY_TIME_RANGE),
],
)
def test_model_kind_change(from_: ModelKindName, to: ModelKindName, sushi_context: Context):
environment = f"test_model_kind_change__{from_.value.lower()}__{to.value.lower()}"
incremental_snapshot = sushi_context.get_snapshot("sushi.items", raise_if_missing=True).copy()
if from_ != ModelKindName.INCREMENTAL_BY_TIME_RANGE:
change_model_kind(sushi_context, from_)
apply_to_environment(sushi_context, environment, SnapshotChangeCategory.NON_BREAKING)
if to == ModelKindName.INCREMENTAL_BY_TIME_RANGE:
sushi_context.upsert_model(incremental_snapshot.model)
else:
change_model_kind(sushi_context, to)
logical = to in (ModelKindName.INCREMENTAL_BY_TIME_RANGE, ModelKindName.EMBEDDED)
validate_model_kind_change(to, sushi_context, environment, logical=logical)
def test_environment_isolation(sushi_context: Context):
prod_snapshots = sushi_context.snapshots.values()
change_data_type(
sushi_context,
"sushi.items",
DataType.Type.DOUBLE,
DataType.Type.FLOAT,
)
directly_modified = ['"memory"."sushi"."items"']
indirectly_modified = [
'"memory"."sushi"."order_items"',
'"memory"."sushi"."waiter_revenue_by_day"',
'"memory"."sushi"."customer_revenue_by_day"',
'"memory"."sushi"."customer_revenue_lifetime"',
'"memory"."sushi"."top_waiters"',
"assert_item_price_above_zero",
]
apply_to_environment(sushi_context, "dev", SnapshotChangeCategory.BREAKING)
# Verify prod unchanged
validate_apply_basics(sushi_context, "prod", prod_snapshots)
def _validate_plan(context, plan):
validate_plan_changes(plan, modified=directly_modified + indirectly_modified)
assert not plan.missing_intervals
apply_to_environment(
sushi_context,
"prod",
SnapshotChangeCategory.BREAKING,
plan_validators=[_validate_plan],
)
def test_environment_promotion(sushi_context: Context):
initial_add(sushi_context, "dev")
# Simulate prod "ahead"
change_data_type(sushi_context, "sushi.items", DataType.Type.DOUBLE, DataType.Type.FLOAT)
apply_to_environment(sushi_context, "prod", SnapshotChangeCategory.BREAKING)
# Simulate rebase
apply_to_environment(sushi_context, "dev", SnapshotChangeCategory.BREAKING)
# Make changes in dev
change_data_type(sushi_context, "sushi.items", DataType.Type.FLOAT, DataType.Type.DECIMAL)
apply_to_environment(sushi_context, "dev", SnapshotChangeCategory.NON_BREAKING)
change_data_type(sushi_context, "sushi.top_waiters", DataType.Type.DOUBLE, DataType.Type.INT)
apply_to_environment(sushi_context, "dev", SnapshotChangeCategory.BREAKING)
change_data_type(
sushi_context,
"sushi.customer_revenue_by_day",
DataType.Type.DOUBLE,
DataType.Type.FLOAT,
)
apply_to_environment(
sushi_context,
"dev",
SnapshotChangeCategory.FORWARD_ONLY,
allow_destructive_models=['"memory"."sushi"."customer_revenue_by_day"'],
)
# Promote to prod
def _validate_plan(context, plan):
sushi_items_snapshot = context.get_snapshot("sushi.items", raise_if_missing=True)
sushi_top_waiters_snapshot = context.get_snapshot(
"sushi.top_waiters", raise_if_missing=True
)
sushi_customer_revenue_by_day_snapshot = context.get_snapshot(
"sushi.customer_revenue_by_day", raise_if_missing=True
)
assert (
plan.context_diff.modified_snapshots[sushi_items_snapshot.name][0].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert (
plan.context_diff.modified_snapshots[sushi_top_waiters_snapshot.name][0].change_category
== SnapshotChangeCategory.BREAKING
)
assert (
plan.context_diff.modified_snapshots[sushi_customer_revenue_by_day_snapshot.name][
0
].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert plan.context_diff.snapshots[
sushi_customer_revenue_by_day_snapshot.snapshot_id
].is_forward_only
apply_to_environment(
sushi_context,
"prod",
SnapshotChangeCategory.NON_BREAKING,
plan_validators=[_validate_plan],
allow_destructive_models=['"memory"."sushi"."customer_revenue_by_day"'],
)
def test_no_override(sushi_context: Context) -> None:
change_data_type(
sushi_context,
"sushi.items",
DataType.Type.INT,
DataType.Type.BIGINT,
)
change_data_type(
sushi_context,
"sushi.order_items",
DataType.Type.INT,
DataType.Type.BIGINT,
)
plan_builder = sushi_context.plan_builder("prod")
plan = plan_builder.build()
sushi_items_snapshot = sushi_context.get_snapshot("sushi.items", raise_if_missing=True)
sushi_order_items_snapshot = sushi_context.get_snapshot(
"sushi.order_items", raise_if_missing=True
)
sushi_water_revenue_by_day_snapshot = sushi_context.get_snapshot(
"sushi.waiter_revenue_by_day", raise_if_missing=True
)
items = plan.context_diff.snapshots[sushi_items_snapshot.snapshot_id]
order_items = plan.context_diff.snapshots[sushi_order_items_snapshot.snapshot_id]
waiter_revenue = plan.context_diff.snapshots[sushi_water_revenue_by_day_snapshot.snapshot_id]
plan_builder.set_choice(items, SnapshotChangeCategory.BREAKING).set_choice(
order_items, SnapshotChangeCategory.NON_BREAKING
)
plan_builder.build()
assert items.is_new_version
assert waiter_revenue.is_new_version
plan_builder.set_choice(items, SnapshotChangeCategory.NON_BREAKING)
plan_builder.build()
assert not waiter_revenue.is_new_version
@pytest.mark.parametrize(
"change_categories, expected",
[
([SnapshotChangeCategory.NON_BREAKING], SnapshotChangeCategory.BREAKING),
([SnapshotChangeCategory.BREAKING], SnapshotChangeCategory.BREAKING),
(
[SnapshotChangeCategory.NON_BREAKING, SnapshotChangeCategory.NON_BREAKING],
SnapshotChangeCategory.BREAKING,
),
(
[SnapshotChangeCategory.NON_BREAKING, SnapshotChangeCategory.BREAKING],
SnapshotChangeCategory.BREAKING,
),
(
[SnapshotChangeCategory.BREAKING, SnapshotChangeCategory.NON_BREAKING],
SnapshotChangeCategory.BREAKING,
),
(
[SnapshotChangeCategory.BREAKING, SnapshotChangeCategory.BREAKING],
SnapshotChangeCategory.BREAKING,
),
],
)
def test_revert(
sushi_context: Context,
change_categories: t.List[SnapshotChangeCategory],
expected: SnapshotChangeCategory,
):
environment = "prod"
original_snapshot_id = sushi_context.get_snapshot("sushi.items", raise_if_missing=True)
types = (DataType.Type.DOUBLE, DataType.Type.FLOAT, DataType.Type.DECIMAL)
assert len(change_categories) < len(types)
for i, category in enumerate(change_categories):
change_data_type(sushi_context, "sushi.items", *types[i : i + 2])
apply_to_environment(sushi_context, environment, category)
assert (
sushi_context.get_snapshot("sushi.items", raise_if_missing=True) != original_snapshot_id
)
change_data_type(sushi_context, "sushi.items", types[len(change_categories)], types[0])
def _validate_plan(_, plan):
snapshot = next(s for s in plan.snapshots.values() if s.name == '"memory"."sushi"."items"')
assert snapshot.change_category == expected
assert not plan.missing_intervals
apply_to_environment(
sushi_context,
environment,
change_categories[-1],
plan_validators=[_validate_plan],
)
assert sushi_context.get_snapshot("sushi.items", raise_if_missing=True) == original_snapshot_id
def test_revert_after_downstream_change(sushi_context: Context):
environment = "prod"
change_data_type(sushi_context, "sushi.items", DataType.Type.DOUBLE, DataType.Type.FLOAT)
apply_to_environment(sushi_context, environment, SnapshotChangeCategory.BREAKING)
change_data_type(
sushi_context,
"sushi.waiter_revenue_by_day",
DataType.Type.DOUBLE,
DataType.Type.FLOAT,
)
apply_to_environment(sushi_context, environment, SnapshotChangeCategory.NON_BREAKING)
change_data_type(sushi_context, "sushi.items", DataType.Type.FLOAT, DataType.Type.DOUBLE)
def _validate_plan(_, plan):
snapshot = next(s for s in plan.snapshots.values() if s.name == '"memory"."sushi"."items"')
assert snapshot.change_category == SnapshotChangeCategory.BREAKING
assert plan.missing_intervals
apply_to_environment(
sushi_context,
environment,
SnapshotChangeCategory.BREAKING,
plan_validators=[_validate_plan],
)
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_indirect_non_breaking_change_after_forward_only_in_dev(init_and_plan_context: t.Callable):
context, _ = init_and_plan_context("examples/sushi")
# Make sure that the most downstream model is a materialized model.
model = context.get_model("sushi.top_waiters")
model = model.copy(update={"kind": FullKind()})
context.upsert_model(model)
context.plan("prod", skip_tests=True, auto_apply=True, no_prompts=True)
# Make sushi.orders a forward-only model.
model = context.get_model("sushi.orders")
updated_model_kind = model.kind.copy(update={"forward_only": True})
model = model.copy(update={"stamp": "force new version", "kind": updated_model_kind})
context.upsert_model(model)
snapshot = context.get_snapshot(model, raise_if_missing=True)
plan = context.plan_builder(
"dev",
skip_tests=True,
enable_preview=False,
categorizer_config=CategorizerConfig.all_full(),
).build()
assert (
plan.context_diff.snapshots[snapshot.snapshot_id].change_category
== SnapshotChangeCategory.BREAKING
)
assert plan.context_diff.snapshots[snapshot.snapshot_id].is_forward_only
assert not plan.requires_backfill
context.apply(plan)
# Make a non-breaking change to a model.
model = context.get_model("sushi.top_waiters")
context.upsert_model(add_projection_to_model(t.cast(SqlModel, model)))
top_waiters_snapshot = context.get_snapshot("sushi.top_waiters", raise_if_missing=True)
plan = context.plan_builder("dev", skip_tests=True, enable_preview=False).build()
assert len(plan.new_snapshots) == 1
assert (
plan.context_diff.snapshots[top_waiters_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert plan.start == to_timestamp("2023-01-01")
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=top_waiters_snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
# Apply the non-breaking changes.
context.apply(plan)
# Make a non-breaking change upstream from the previously modified model.
model = context.get_model("sushi.waiter_revenue_by_day")
context.upsert_model(add_projection_to_model(t.cast(SqlModel, model)))
waiter_revenue_by_day_snapshot = context.get_snapshot(
"sushi.waiter_revenue_by_day", raise_if_missing=True
)
top_waiters_snapshot = context.get_snapshot("sushi.top_waiters", raise_if_missing=True)
plan = context.plan_builder("dev", skip_tests=True, enable_preview=False).build()
assert len(plan.new_snapshots) == 2
assert (
plan.context_diff.snapshots[waiter_revenue_by_day_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert (
plan.context_diff.snapshots[top_waiters_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.INDIRECT_NON_BREAKING
)
assert plan.start == to_timestamp("2023-01-01")
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=waiter_revenue_by_day_snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
# Apply the upstream non-breaking changes.
context.apply(plan)
assert not context.plan_builder("dev", skip_tests=True).build().requires_backfill
# Deploy everything to prod.
plan = context.plan_builder("prod", skip_tests=True, enable_preview=False).build()
assert plan.start == to_timestamp("2023-01-01")
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=top_waiters_snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
SnapshotIntervals(
snapshot_id=waiter_revenue_by_day_snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
context.apply(plan)
assert (
not context.plan_builder("prod", skip_tests=True, enable_preview=False)
.build()
.requires_backfill
)
@time_machine.travel("2023-01-08 15:00:00 UTC")
@pytest.mark.parametrize("forward_only", [False, True])
def test_plan_repairs_unrenderable_snapshot_state(
init_and_plan_context: t.Callable, forward_only: bool
):
context, plan = init_and_plan_context("examples/sushi")
context.apply(plan)
target_snapshot = context.get_snapshot("sushi.waiter_revenue_by_day")
assert target_snapshot
# Manually corrupt the snapshot's query
raw_snapshot = context.state_sync.state_sync.engine_adapter.fetchone(
f"SELECT snapshot FROM sqlmesh._snapshots WHERE name = '{target_snapshot.name}' AND identifier = '{target_snapshot.identifier}'"
)[0] # type: ignore
parsed_snapshot = json.loads(raw_snapshot)
parsed_snapshot["node"]["query"] = "SELECT @missing_macro()"
context.state_sync.state_sync.engine_adapter.update_table(
"sqlmesh._snapshots",
{"snapshot": json.dumps(parsed_snapshot)},
f"name = '{target_snapshot.name}' AND identifier = '{target_snapshot.identifier}'",
)
context.clear_caches()
target_snapshot_in_state = context.state_sync.get_snapshots([target_snapshot.snapshot_id])[
target_snapshot.snapshot_id
]
with pytest.raises(Exception):
target_snapshot_in_state.model.render_query_or_raise()
# Repair the snapshot by creating a new version of it
context.upsert_model(target_snapshot.model.name, stamp="repair")
target_snapshot = context.get_snapshot(target_snapshot.name)
plan_builder = context.plan_builder("prod", forward_only=forward_only)
plan = plan_builder.build()
if not forward_only:
assert target_snapshot.snapshot_id in {i.snapshot_id for i in plan.missing_intervals}
assert plan.directly_modified == {target_snapshot.snapshot_id}
plan_builder.set_choice(target_snapshot, SnapshotChangeCategory.NON_BREAKING)
plan = plan_builder.build()
context.apply(plan)
context.clear_caches()
assert context.get_snapshot(target_snapshot.name).model.render_query_or_raise()
target_snapshot_in_state = context.state_sync.get_snapshots([target_snapshot.snapshot_id])[
target_snapshot.snapshot_id
]
assert target_snapshot_in_state.model.render_query_or_raise()
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_no_backfill_for_model_downstream_of_metadata_change(init_and_plan_context: t.Callable):
context, _ = init_and_plan_context("examples/sushi")
# Make sushi.waiter_revenue_by_day a forward-only model.
forward_only_model = context.get_model("sushi.waiter_revenue_by_day")
updated_model_kind = forward_only_model.kind.copy(update={"forward_only": True})
forward_only_model = forward_only_model.copy(update={"kind": updated_model_kind})
context.upsert_model(forward_only_model)
context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True)
# Make a metadata change upstream of the forward-only model.
context.upsert_model("sushi.orders", owner="new_owner")
plan = context.plan_builder("test_dev").build()
assert plan.has_changes
assert not plan.directly_modified
assert not plan.indirectly_modified
assert not plan.missing_intervals
assert all(
snapshot.change_category == SnapshotChangeCategory.METADATA
for snapshot in plan.new_snapshots
)
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_plan_set_choice_is_reflected_in_missing_intervals(init_and_plan_context: t.Callable):
context, _ = init_and_plan_context("examples/sushi")
context.upsert_model(context.get_model("sushi.top_waiters").copy(update={"kind": FullKind()}))
context.plan("prod", skip_tests=True, no_prompts=True, auto_apply=True)
model_name = "sushi.waiter_revenue_by_day"
model = context.get_model(model_name)
context.upsert_model(add_projection_to_model(t.cast(SqlModel, model)))
snapshot = context.get_snapshot(model, raise_if_missing=True)
top_waiters_snapshot = context.get_snapshot("sushi.top_waiters", raise_if_missing=True)
plan_builder = context.plan_builder("dev", skip_tests=True)
plan = plan_builder.build()
assert len(plan.new_snapshots) == 2
assert (
plan.context_diff.snapshots[snapshot.snapshot_id].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert (
plan.context_diff.snapshots[top_waiters_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.INDIRECT_NON_BREAKING
)
assert plan.start == to_timestamp("2023-01-01")
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
# Change the category to BREAKING
plan = plan_builder.set_choice(
plan.context_diff.snapshots[snapshot.snapshot_id], SnapshotChangeCategory.BREAKING
).build()
assert (
plan.context_diff.snapshots[snapshot.snapshot_id].change_category
== SnapshotChangeCategory.BREAKING
)
assert (
plan.context_diff.snapshots[top_waiters_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.INDIRECT_BREAKING
)
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=top_waiters_snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
SnapshotIntervals(
snapshot_id=snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
# Change the category back to NON_BREAKING
plan = plan_builder.set_choice(
plan.context_diff.snapshots[snapshot.snapshot_id], SnapshotChangeCategory.NON_BREAKING
).build()
assert (
plan.context_diff.snapshots[snapshot.snapshot_id].change_category
== SnapshotChangeCategory.NON_BREAKING
)
assert (
plan.context_diff.snapshots[top_waiters_snapshot.snapshot_id].change_category
== SnapshotChangeCategory.INDIRECT_NON_BREAKING
)
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=snapshot.snapshot_id,
intervals=[
(to_timestamp("2023-01-01"), to_timestamp("2023-01-02")),
(to_timestamp("2023-01-02"), to_timestamp("2023-01-03")),
(to_timestamp("2023-01-03"), to_timestamp("2023-01-04")),
(to_timestamp("2023-01-04"), to_timestamp("2023-01-05")),
(to_timestamp("2023-01-05"), to_timestamp("2023-01-06")),
(to_timestamp("2023-01-06"), to_timestamp("2023-01-07")),
(to_timestamp("2023-01-07"), to_timestamp("2023-01-08")),
],
),
]
context.apply(plan)
dev_df = context.engine_adapter.fetchdf(
"SELECT DISTINCT event_date FROM sushi__dev.waiter_revenue_by_day ORDER BY event_date"
)
assert dev_df["event_date"].tolist() == [
pd.to_datetime(x)
for x in [
"2023-01-01",
"2023-01-02",
"2023-01-03",
"2023-01-04",
"2023-01-05",
"2023-01-06",
"2023-01-07",
]
]
# Promote changes to prod
prod_plan = context.plan_builder(skip_tests=True).build()
assert not prod_plan.missing_intervals
context.apply(prod_plan)
prod_df = context.engine_adapter.fetchdf(
"SELECT DISTINCT event_date FROM sushi.waiter_revenue_by_day WHERE one IS NOT NULL ORDER BY event_date"
)
assert prod_df["event_date"].tolist() == [
pd.to_datetime(x)
for x in [
"2023-01-01",
"2023-01-02",
"2023-01-03",
"2023-01-04",
"2023-01-05",
"2023-01-06",
"2023-01-07",
]
]
def test_plan_production_environment_statements(tmp_path: Path):
model_a = """
MODEL (
name test_schema.a,
kind FULL,
);
@IF(
@runtime_stage IN ('evaluating', 'creating'),
INSERT INTO schema_names_for_prod (physical_schema_name) VALUES (@resolve_template('@{schema_name}'))
);
SELECT 1 AS account_id
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
for path, defn in {"a.sql": model_a}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
before_all = [
"CREATE TABLE IF NOT EXISTS schema_names_for_@this_env (physical_schema_name VARCHAR)",
"@IF(@runtime_stage = 'before_all', CREATE TABLE IF NOT EXISTS should_create AS SELECT @runtime_stage)",
]
after_all = [
"@IF(@this_env = 'prod', CREATE TABLE IF NOT EXISTS after_t AS SELECT @var_5)",
"@IF(@runtime_stage = 'before_all', CREATE TABLE IF NOT EXISTS not_create AS SELECT @runtime_stage)",
]
config = Config(
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
before_all=before_all,
after_all=after_all,
variables={"var_5": 5},
)
ctx = Context(paths=[tmp_path], config=config)
ctx.plan(auto_apply=True, no_prompts=True)
before_t = ctx.fetchdf("select * from schema_names_for_prod").to_dict()
assert before_t["physical_schema_name"][0] == "sqlmesh__test_schema"
after_t = ctx.fetchdf("select * from after_t").to_dict()
assert after_t["5"][0] == 5
environment_statements = ctx.state_reader.get_environment_statements(c.PROD)
assert environment_statements[0].before_all == before_all
assert environment_statements[0].after_all == after_all
assert environment_statements[0].python_env.keys() == {"__sqlmesh__vars__"}
assert environment_statements[0].python_env["__sqlmesh__vars__"].payload == "{'var_5': 5}"
should_create = ctx.fetchdf("select * from should_create").to_dict()
assert should_create["before_all"][0] == "before_all"
with pytest.raises(
Exception, match=r"Catalog Error: Table with name not_create does not exist!"
):
ctx.fetchdf("select * from not_create")
def test_environment_statements_error_handling(tmp_path: Path):
model_a = """
MODEL (
name test_schema.a,
kind FULL,
);
SELECT 1 AS account_id
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
for path, defn in {"a.sql": model_a}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
before_all = [
"CREATE TABLE identical_table (physical_schema_name VARCHAR)",
"CREATE TABLE identical_table (physical_schema_name VARCHAR)",
]
config = Config(
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
before_all=before_all,
)
ctx = Context(paths=[tmp_path], config=config)
expected_error_message = re.escape(
"""An error occurred during execution of the following 'before_all' statement:
CREATE TABLE identical_table (physical_schema_name TEXT)
Catalog Error: Table with name "identical_table" already exists!"""
)
with pytest.raises(SQLMeshError, match=expected_error_message):
ctx.plan(auto_apply=True, no_prompts=True)
after_all = [
"@bad_macro()",
]
config = Config(
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
after_all=after_all,
)
ctx = Context(paths=[tmp_path], config=config)
expected_error_message = re.escape(
"""An error occurred during rendering of the 'after_all' statements:
Failed to resolve macros for
@bad_macro()
Macro 'bad_macro' does not exist."""
)
with pytest.raises(SQLMeshError, match=expected_error_message):
ctx.plan(auto_apply=True, no_prompts=True)
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_full_model_change_with_plan_start_not_matching_model_start(
init_and_plan_context: t.Callable,
):
context, plan = init_and_plan_context("examples/sushi")
context.apply(plan)
model = context.get_model("sushi.top_waiters")
context.upsert_model(model, kind=model_kind_type_from_name("FULL")()) # type: ignore
# Apply the change with --skip-backfill first and no plan start
context.plan("dev", skip_tests=True, skip_backfill=True, no_prompts=True, auto_apply=True)
# Apply the plan again but this time don't skip backfill and set start
# to be later than the model start
context.plan("dev", skip_tests=True, no_prompts=True, auto_apply=True, start="1 day ago")
# Check that the number of rows is not 0
row_num = context.engine_adapter.fetchone(f"SELECT COUNT(*) FROM sushi__dev.top_waiters")[0]
assert row_num > 0
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_hourly_model_with_lookback_no_backfill_in_dev(init_and_plan_context: t.Callable):
context, plan = init_and_plan_context("examples/sushi")
model_name = "sushi.waiter_revenue_by_day"
model = context.get_model(model_name)
model = SqlModel.parse_obj(
{
**model.dict(),
"kind": model.kind.copy(update={"lookback": 1}),
"cron": "@hourly",