-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathtest_restatement.py
More file actions
1935 lines (1600 loc) · 62.1 KB
/
test_restatement.py
File metadata and controls
1935 lines (1600 loc) · 62.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 pandas as pd # noqa: TID253
import pytest
from pathlib import Path
from sqlmesh.core.console import (
MarkdownConsole,
set_console,
get_console,
CaptureTerminalConsole,
)
import time_machine
from sqlglot import exp
import re
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import time
import queue
from sqlmesh.core import constants as c
from sqlmesh.core.config import (
Config,
GatewayConfig,
ModelDefaultsConfig,
DuckDBConnectionConfig,
)
from sqlmesh.core.context import Context
from sqlmesh.core.model import (
IncrementalByTimeRangeKind,
IncrementalUnmanagedKind,
SqlModel,
)
from sqlmesh.core.plan import SnapshotIntervals
from sqlmesh.core.snapshot import (
Snapshot,
SnapshotId,
)
from sqlmesh.utils.date import to_timestamp
from sqlmesh.utils.errors import (
ConflictingPlanError,
)
from tests.core.integration.utils import add_projection_to_model
pytestmark = pytest.mark.slow
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_restatement_plan_ignores_changes(init_and_plan_context: t.Callable):
context, plan = init_and_plan_context("examples/sushi")
context.apply(plan)
restated_snapshot = context.get_snapshot("sushi.top_waiters")
# Simulate a change.
model = context.get_model("sushi.waiter_revenue_by_day")
context.upsert_model(add_projection_to_model(t.cast(SqlModel, model)))
plan = context.plan_builder(restate_models=["sushi.top_waiters"]).build()
assert plan.snapshots != context.snapshots
assert not plan.directly_modified
assert not plan.has_changes
assert not plan.new_snapshots
assert plan.requires_backfill
assert plan.restatements == {
restated_snapshot.snapshot_id: (to_timestamp("2023-01-01"), to_timestamp("2023-01-09"))
}
assert plan.missing_intervals == [
SnapshotIntervals(
snapshot_id=restated_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)
@time_machine.travel("2023-01-08 15:00:00 UTC")
def test_restatement_plan_across_environments_snapshot_with_shared_version(
init_and_plan_context: t.Callable,
):
context, _ = init_and_plan_context("examples/sushi")
# Change kind to incremental unmanaged
model = context.get_model("sushi.waiter_revenue_by_day")
previous_kind = model.kind.copy(update={"forward_only": True})
assert isinstance(previous_kind, IncrementalByTimeRangeKind)
model = model.copy(
update={
"kind": IncrementalUnmanagedKind(),
"physical_version": "pinned_version_12345",
"partitioned_by_": [exp.column("event_date")],
}
)
context.upsert_model(model)
context.plan("prod", auto_apply=True, no_prompts=True)
# Make some change and deploy it to both dev and prod environments
model = add_projection_to_model(t.cast(SqlModel, model))
context.upsert_model(model)
context.plan("dev_a", auto_apply=True, no_prompts=True)
context.plan("prod", auto_apply=True, no_prompts=True)
# Change the kind back to incremental by time range and deploy to prod
model = model.copy(update={"kind": previous_kind})
context.upsert_model(model)
context.plan("prod", auto_apply=True, no_prompts=True)
# Restate the model and verify that the interval hasn't been expanded because of the old snapshot
# with the same version
context.plan(
restate_models=["sushi.waiter_revenue_by_day"],
start="2023-01-06",
end="2023-01-08",
auto_apply=True,
no_prompts=True,
)
assert (
context.fetchdf(
"SELECT COUNT(*) AS cnt FROM sushi.waiter_revenue_by_day WHERE one IS NOT NULL AND event_date < '2023-01-06'"
)["cnt"][0]
== 0
)
plan = context.plan_builder("prod").build()
assert not plan.missing_intervals
def test_restatement_plan_hourly_with_downstream_daily_restates_correct_intervals(tmp_path: Path):
model_a = """
MODEL (
name test.a,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts"
),
start '2024-01-01 00:00:00',
cron '@hourly'
);
select account_id, ts from test.external_table;
"""
model_b = """
MODEL (
name test.b,
kind FULL,
cron '@daily'
);
select account_id, ts from test.a;
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
for path, defn in {"a.sql": model_a, "b.sql": model_b}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"ts": exp.DataType.build("timestamp"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# plan + apply
ctx.plan(auto_apply=True, no_prompts=True)
def _dates_in_table(table_name: str) -> t.List[str]:
return [
str(r[0]) for r in engine_adapter.fetchall(f"select ts from {table_name} order by ts")
]
# verify initial state
for tbl in ["test.a", "test.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# restate A
engine_adapter.execute("delete from test.external_table where ts = '2024-01-01 01:30:00'")
ctx.plan(
restate_models=["test.a"],
start="2024-01-01 01:00:00",
end="2024-01-01 02:00:00",
auto_apply=True,
no_prompts=True,
)
# verify result
for tbl in ["test.a", "test.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
], f"Table {tbl} wasnt cleared"
# Put some data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 01:30:00",
"2024-01-01 23:30:00",
"2024-01-02 03:30:00",
"2024-01-03 12:30:00",
],
}
)
engine_adapter.replace_query(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# Restate A across a day boundary with the expectation that two day intervals in B are affected
ctx.plan(
restate_models=["test.a"],
start="2024-01-01 02:00:00",
end="2024-01-02 04:00:00",
auto_apply=True,
no_prompts=True,
)
for tbl in ["test.a", "test.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00", # present already
# "2024-01-01 02:30:00", #removed in last restatement
"2024-01-01 23:30:00", # added in last restatement
"2024-01-02 03:30:00", # added in last restatement
], f"Table {tbl} wasnt cleared"
def test_restatement_plan_respects_disable_restatements(tmp_path: Path):
model_a = """
MODEL (
name test.a,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts"
),
start '2024-01-01',
cron '@daily'
);
select account_id, ts from test.external_table;
"""
model_b = """
MODEL (
name test.b,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts",
disable_restatement true,
),
start '2024-01-01',
cron '@daily'
);
select account_id, ts from test.a;
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
for path, defn in {"a.sql": model_a, "b.sql": model_b}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"ts": exp.DataType.build("timestamp"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# plan + apply
ctx.plan(auto_apply=True, no_prompts=True)
def _dates_in_table(table_name: str) -> t.List[str]:
return [
str(r[0]) for r in engine_adapter.fetchall(f"select ts from {table_name} order by ts")
]
def get_snapshot_intervals(snapshot_id):
return list(ctx.state_sync.get_snapshots([snapshot_id]).values())[0].intervals
# verify initial state
for tbl in ["test.a", "test.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# restate A and expect b to be ignored
starting_b_intervals = get_snapshot_intervals(ctx.snapshots['"memory"."test"."b"'].snapshot_id)
engine_adapter.execute("delete from test.external_table where ts = '2024-01-01 01:30:00'")
ctx.plan(
restate_models=["test.a"],
start="2024-01-01",
end="2024-01-02",
auto_apply=True,
no_prompts=True,
)
# verify A was changed and not b
assert _dates_in_table("test.a") == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
assert _dates_in_table("test.b") == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# Verify B intervals were not touched
b_intervals = get_snapshot_intervals(ctx.snapshots['"memory"."test"."b"'].snapshot_id)
assert starting_b_intervals == b_intervals
def test_restatement_plan_clears_correct_intervals_across_environments(tmp_path: Path):
model1 = """
MODEL (
name test.incremental_model,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "date"
),
start '2024-01-01',
cron '@daily'
);
select account_id, date from test.external_table;
"""
model2 = """
MODEL (
name test.downstream_of_incremental,
kind FULL
);
select account_id, date from test.incremental_model;
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
with open(models_dir / "model1.sql", "w") as f:
f.write(model1)
with open(models_dir / "model2.sql", "w") as f:
f.write(model2)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004, 1005],
"name": ["foo", "bar", "baz", "bing", "bong"],
"date": ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-04", "2024-01-05"],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"name": exp.DataType.build("varchar"),
"date": exp.DataType.build("date"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# first, create the prod models
ctx.plan(auto_apply=True, no_prompts=True)
assert engine_adapter.fetchone("select count(*) from test.incremental_model") == (5,)
assert engine_adapter.fetchone("select count(*) from test.downstream_of_incremental") == (5,)
assert not engine_adapter.table_exists("test__dev.incremental_model")
# then, make a dev version
model1 = """
MODEL (
name test.incremental_model,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "date"
),
start '2024-01-01',
cron '@daily'
);
select 1 as account_id, date from test.external_table;
"""
with open(models_dir / "model1.sql", "w") as f:
f.write(model1)
ctx.load()
ctx.plan(environment="dev", auto_apply=True, no_prompts=True)
assert engine_adapter.table_exists("test__dev.incremental_model")
assert engine_adapter.fetchone("select count(*) from test__dev.incremental_model") == (5,)
# drop some source data so when we restate the interval it essentially clears it which is easy to verify
engine_adapter.execute("delete from test.external_table where date = '2024-01-01'")
assert engine_adapter.fetchone("select count(*) from test.external_table") == (4,)
# now, restate intervals in dev and verify prod is NOT affected
ctx.plan(
environment="dev",
start="2024-01-01",
end="2024-01-02",
restate_models=["test.incremental_model"],
auto_apply=True,
no_prompts=True,
)
assert engine_adapter.fetchone("select count(*) from test.incremental_model") == (5,)
assert engine_adapter.fetchone(
"select count(*) from test.incremental_model where date = '2024-01-01'"
) == (1,)
assert engine_adapter.fetchone("select count(*) from test__dev.incremental_model") == (4,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-01'"
) == (0,)
# prod still should not be affected by a run because the restatement only happened in dev
ctx.run()
assert engine_adapter.fetchone("select count(*) from test.incremental_model") == (5,)
assert engine_adapter.fetchone(
"select count(*) from test.incremental_model where date = '2024-01-01'"
) == (1,)
# drop another interval from the source data
engine_adapter.execute("delete from test.external_table where date = '2024-01-02'")
# now, restate intervals in prod and verify that dev IS affected
ctx.plan(
start="2024-01-01",
end="2024-01-03",
restate_models=["test.incremental_model"],
auto_apply=True,
no_prompts=True,
)
assert engine_adapter.fetchone("select count(*) from test.incremental_model") == (3,)
assert engine_adapter.fetchone(
"select count(*) from test.incremental_model where date = '2024-01-01'"
) == (0,)
assert engine_adapter.fetchone(
"select count(*) from test.incremental_model where date = '2024-01-02'"
) == (0,)
assert engine_adapter.fetchone(
"select count(*) from test.incremental_model where date = '2024-01-03'"
) == (1,)
# dev not affected yet until `sqlmesh run` is run
assert engine_adapter.fetchone("select count(*) from test__dev.incremental_model") == (4,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-01'"
) == (0,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-02'"
) == (1,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-03'"
) == (1,)
# the restatement plan for prod should have cleared dev intervals too, which means this `sqlmesh run` re-runs 2024-01-01 and 2024-01-02
ctx.run(environment="dev")
assert engine_adapter.fetchone("select count(*) from test__dev.incremental_model") == (3,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-01'"
) == (0,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-02'"
) == (0,)
assert engine_adapter.fetchone(
"select count(*) from test__dev.incremental_model where date = '2024-01-03'"
) == (1,)
# the downstream full model should always reflect whatever the incremental model is showing
assert engine_adapter.fetchone("select count(*) from test.downstream_of_incremental") == (3,)
assert engine_adapter.fetchone("select count(*) from test__dev.downstream_of_incremental") == (
3,
)
def test_prod_restatement_plan_clears_correct_intervals_in_derived_dev_tables(tmp_path: Path):
"""
Scenario:
I have models A[hourly] <- B[daily] <- C in prod
I create dev and add 2 new models D and E so that my dev DAG looks like A <- B <- C <- D[daily] <- E
I prod, I restate *one hour* of A
Outcome:
D and E should be restated in dev despite not being a part of prod
since B and D are daily, the whole day should be restated even though only 1hr of the upstream model was restated
"""
model_a = """
MODEL (
name test.a,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts"
),
start '2024-01-01 00:00:00',
cron '@hourly'
);
select account_id, ts from test.external_table;
"""
def _derived_full_model_def(name: str, upstream: str) -> str:
return f"""
MODEL (
name test.{name},
kind FULL
);
select account_id, ts from test.{upstream};
"""
def _derived_incremental_model_def(name: str, upstream: str) -> str:
return f"""
MODEL (
name test.{name},
kind INCREMENTAL_BY_TIME_RANGE (
time_column ts
),
cron '@daily'
);
select account_id, ts from test.{upstream} where ts between @start_ts and @end_ts;
"""
model_b = _derived_incremental_model_def("b", upstream="a")
model_c = _derived_full_model_def("c", upstream="b")
models_dir = tmp_path / "models"
models_dir.mkdir()
for path, defn in {"a.sql": model_a, "b.sql": model_b, "c.sql": model_c}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"ts": exp.DataType.build("timestamp"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# plan + apply A, B, C in prod
ctx.plan(auto_apply=True, no_prompts=True)
# add D[daily], E in dev
model_d = _derived_incremental_model_def("d", upstream="c")
model_e = _derived_full_model_def("e", upstream="d")
for path, defn in {
"d.sql": model_d,
"e.sql": model_e,
}.items():
with open(models_dir / path, "w") as f:
f.write(defn)
# plan + apply dev
ctx.load()
ctx.plan(environment="dev", auto_apply=True, no_prompts=True)
def _dates_in_table(table_name: str) -> t.List[str]:
return [
str(r[0]) for r in engine_adapter.fetchall(f"select ts from {table_name} order by ts")
]
# verify initial state
for tbl in ["test.a", "test.b", "test.c", "test__dev.d", "test__dev.e"]:
assert engine_adapter.table_exists(tbl)
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
for tbl in ["test.d", "test.e"]:
assert not engine_adapter.table_exists(tbl)
# restate A in prod
engine_adapter.execute("delete from test.external_table where ts = '2024-01-01 01:30:00'")
ctx.plan(
restate_models=["test.a"],
start="2024-01-01 01:00:00",
end="2024-01-01 02:00:00",
auto_apply=True,
no_prompts=True,
)
# verify result
for tbl in ["test.a", "test.b", "test.c"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
], f"Table {tbl} wasnt cleared"
# dev shouldnt have been affected yet
for tbl in ["test__dev.d", "test__dev.e"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
], f"Table {tbl} was prematurely cleared"
# run dev to trigger the processing of the prod restatement
ctx.run(environment="dev")
# data should now be cleared from dev
# note that D is a daily model, so clearing an hour interval from A should have triggered the full day in D
for tbl in ["test__dev.d", "test__dev.e"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
], f"Table {tbl} wasnt cleared"
def test_prod_restatement_plan_clears_unaligned_intervals_in_derived_dev_tables(tmp_path: Path):
"""
Scenario:
I have a model A[hourly] in prod
I create dev and add a model B[daily]
I prod, I restate *one hour* of A
Outcome:
The whole day for B should be restated. The restatement plan for prod has no hints about B's cadence because
B only exists in dev and there are no other downstream models in prod that would cause the restatement intervals
to be widened.
Therefore, this test checks that SQLMesh does the right thing when an interval is partially cleared
"""
model_a = """
MODEL (
name test.a,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts"
),
start '2024-01-01 00:00:00',
cron '@hourly'
);
select account_id, ts from test.external_table;
"""
model_b = """
MODEL (
name test.b,
kind INCREMENTAL_BY_TIME_RANGE (
time_column ts
),
cron '@daily'
);
select account_id, ts from test.a where ts between @start_ts and @end_ts;
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
with open(models_dir / "a.sql", "w") as f:
f.write(model_a)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"ts": exp.DataType.build("timestamp"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# plan + apply A[hourly] in prod
ctx.plan(auto_apply=True, no_prompts=True)
# add B[daily] in dev
with open(models_dir / "b.sql", "w") as f:
f.write(model_b)
# plan + apply dev
ctx.load()
ctx.plan(environment="dev", auto_apply=True, no_prompts=True)
def _dates_in_table(table_name: str) -> t.List[str]:
return [
str(r[0]) for r in engine_adapter.fetchall(f"select ts from {table_name} order by ts")
]
# verify initial state
for tbl in ["test.a", "test__dev.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# restate A in prod
engine_adapter.execute("delete from test.external_table where ts = '2024-01-01 01:30:00'")
ctx.plan(
restate_models=["test.a"],
start="2024-01-01 01:00:00",
end="2024-01-01 02:00:00",
auto_apply=True,
no_prompts=True,
)
# verify result
assert _dates_in_table("test.a") == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# dev shouldnt have been affected yet
assert _dates_in_table("test__dev.b") == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# mess with A independently of SQLMesh to prove a whole day gets restated for B instead of just 1hr
snapshot_table_name = ctx.table_name("test.a", "dev")
engine_adapter.execute(
f"delete from {snapshot_table_name} where cast(ts as date) == '2024-01-01'"
)
engine_adapter.execute(
f"insert into {snapshot_table_name} (account_id, ts) values (1007, '2024-01-02 01:30:00')"
)
assert _dates_in_table("test.a") == ["2024-01-02 00:30:00", "2024-01-02 01:30:00"]
# run dev to trigger the processing of the prod restatement
ctx.run(environment="dev")
# B should now have no data for 2024-01-01
# To prove a single day was restated vs the whole model, it also shouldnt have the '2024-01-02 01:30:00' record
assert _dates_in_table("test__dev.b") == ["2024-01-02 00:30:00"]
def test_prod_restatement_plan_causes_dev_intervals_to_be_processed_in_next_dev_plan(
tmp_path: Path,
):
"""
Scenario:
I have a model A[hourly] in prod
I create dev and add a model B[daily]
I prod, I restate *one hour* of A
In dev, I run a normal plan instead of a cadence run
Outcome:
The whole day for B should be restated as part of a normal plan
"""
model_a = """
MODEL (
name test.a,
kind INCREMENTAL_BY_TIME_RANGE (
time_column "ts"
),
start '2024-01-01 00:00:00',
cron '@hourly'
);
select account_id, ts from test.external_table;
"""
model_b = """
MODEL (
name test.b,
kind INCREMENTAL_BY_TIME_RANGE (
time_column ts
),
cron '@daily'
);
select account_id, ts from test.a where ts between @start_ts and @end_ts;
"""
models_dir = tmp_path / "models"
models_dir.mkdir()
with open(models_dir / "a.sql", "w") as f:
f.write(model_a)
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
ctx = Context(paths=[tmp_path], config=config)
engine_adapter = ctx.engine_adapter
engine_adapter.create_schema("test")
# source data
df = pd.DataFrame(
{
"account_id": [1001, 1002, 1003, 1004],
"ts": [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
],
}
)
columns_to_types = {
"account_id": exp.DataType.build("int"),
"ts": exp.DataType.build("timestamp"),
}
external_table = exp.table_(table="external_table", db="test", quoted=True)
engine_adapter.create_table(table_name=external_table, target_columns_to_types=columns_to_types)
engine_adapter.insert_append(
table_name=external_table, query_or_df=df, target_columns_to_types=columns_to_types
)
# plan + apply A[hourly] in prod
ctx.plan(auto_apply=True, no_prompts=True)
# add B[daily] in dev
with open(models_dir / "b.sql", "w") as f:
f.write(model_b)
# plan + apply dev
ctx.load()
ctx.plan(environment="dev", auto_apply=True, no_prompts=True)
def _dates_in_table(table_name: str) -> t.List[str]:
return [
str(r[0]) for r in engine_adapter.fetchall(f"select ts from {table_name} order by ts")
]
# verify initial state
for tbl in ["test.a", "test__dev.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# restate A in prod
engine_adapter.execute("delete from test.external_table where ts = '2024-01-01 01:30:00'")
ctx.plan(
restate_models=["test.a"],
start="2024-01-01 01:00:00",
end="2024-01-01 02:00:00",
auto_apply=True,
no_prompts=True,
)
# verify result
assert _dates_in_table("test.a") == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# dev shouldnt have been affected yet
assert _dates_in_table("test__dev.b") == [
"2024-01-01 00:30:00",
"2024-01-01 01:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
# plan dev which should trigger the missing intervals to get repopulated
ctx.plan(environment="dev", auto_apply=True, no_prompts=True)
# dev should have the restated data
for tbl in ["test.a", "test__dev.b"]:
assert _dates_in_table(tbl) == [
"2024-01-01 00:30:00",
"2024-01-01 02:30:00",
"2024-01-02 00:30:00",
]
def test_prod_restatement_plan_causes_dev_intervals_to_be_widened_on_full_restatement_only_model(
tmp_path,
):
"""
Scenario:
I have am INCREMENTAL_BY_TIME_RANGE model A[daily] in prod
I create dev and add a INCREMENTAL_BY_UNIQUE_KEY model B (which supports full restatement only)
I prod, I restate one day of A which should cause intervals in dev to be cleared (but not processed)
In dev, I run a plan
Outcome:
In the dev plan, the entire model for B should be rebuilt because it does not support partial restatement
"""
model_a = """
MODEL (
name test.a,