-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathtest_context.py
More file actions
3381 lines (2782 loc) · 116 KB
/
test_context.py
File metadata and controls
3381 lines (2782 loc) · 116 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
import logging
import pathlib
import typing as t
import re
from datetime import date, timedelta, datetime
from tempfile import TemporaryDirectory
from unittest.mock import PropertyMock, call, patch
import time_machine
import pytest
import pandas as pd # noqa: TID253
from pathlib import Path
from pytest_mock.plugin import MockerFixture
from sqlglot import ParseError, exp, parse_one, Dialect
from sqlglot.errors import SchemaError
import sqlmesh.core.constants
from sqlmesh.cli.project_init import init_example_project
from sqlmesh.core.console import TerminalConsole
from sqlmesh.core import dialect as d, constants as c
from sqlmesh.core.config import (
load_configs,
AutoCategorizationMode,
CategorizerConfig,
Config,
DuckDBConnectionConfig,
EnvironmentSuffixTarget,
GatewayConfig,
LinterConfig,
ModelDefaultsConfig,
PlanConfig,
SnowflakeConnectionConfig,
)
from sqlmesh.core.context import Context
from sqlmesh.core.console import create_console, get_console
from sqlmesh.core.dialect import parse, schema_
from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter
from sqlmesh.core.environment import Environment, EnvironmentNamingInfo, EnvironmentStatements
from sqlmesh.core.plan.definition import Plan
from sqlmesh.core.macros import MacroEvaluator, RuntimeStage
from sqlmesh.core.model import load_sql_based_model, model, SqlModel, Model
from sqlmesh.core.model.common import ParsableSql
from sqlmesh.core.model.cache import OptimizedQueryCache
from sqlmesh.core.renderer import render_statements
from sqlmesh.core.model.kind import ModelKindName
from sqlmesh.core.state_sync.cache import CachingStateSync
from sqlmesh.core.state_sync.db import EngineAdapterStateSync
from sqlmesh.utils.connection_pool import SingletonConnectionPool, ThreadLocalSharedConnectionPool
from sqlmesh.utils.date import (
make_inclusive_end,
now,
to_date,
to_datetime,
to_timestamp,
yesterday_ds,
)
from sqlmesh.utils.errors import (
ConfigError,
SQLMeshError,
LinterError,
PlanError,
NoChangesPlanError,
)
from sqlmesh.utils.metaprogramming import Executable
from sqlmesh.utils.windows import IS_WINDOWS, fix_windows_path
from tests.utils.test_helpers import use_terminal_console
from tests.utils.test_filesystem import create_temp_file
def test_global_config(copy_to_temp_path: t.Callable):
context = Context(paths=copy_to_temp_path("examples/sushi"))
assert context.config.dialect == "duckdb"
assert context.config.time_column_format == "%Y-%m-%d"
def test_named_config(copy_to_temp_path: t.Callable):
context = Context(paths=copy_to_temp_path("examples/sushi"), config="test_config")
assert len(context.config.gateways) == 1
def test_invalid_named_config(copy_to_temp_path: t.Callable):
with pytest.raises(
ConfigError,
match="Config 'blah' was not found.",
):
Context(paths=copy_to_temp_path("examples/sushi"), config="blah")
def test_missing_named_config(copy_to_temp_path: t.Callable):
with pytest.raises(ConfigError, match=r"Config 'imaginary_config' was not found."):
Context(paths=copy_to_temp_path("examples/sushi"), config="imaginary_config")
def test_config_parameter(copy_to_temp_path: t.Callable):
config = Config(model_defaults=ModelDefaultsConfig(dialect="presto"), project="test_project")
context = Context(paths=copy_to_temp_path("examples/sushi"), config=config)
assert context.config.dialect == "presto"
assert context.config.project == "test_project"
def test_generate_table_name_in_dialect(mocker: MockerFixture):
context = Context(config=Config(model_defaults=ModelDefaultsConfig(dialect="bigquery")))
mocker.patch(
"sqlmesh.core.context.GenericContext._model_tables",
PropertyMock(return_value={'"project-id"."dataset"."table"': '"project-id".dataset.table'}),
)
assert (
context.resolve_table('"project-id"."dataset"."table"') == "`project-id`.`dataset`.`table`"
)
def test_config_not_found(copy_to_temp_path: t.Callable):
with pytest.raises(
ConfigError,
match=r".*config could not be found.*",
):
Context(paths="nonexistent/directory", config="config")
def test_custom_macros(sushi_context):
assert "add_one" in sushi_context._macros
def test_dag(sushi_context):
assert set(sushi_context.dag.upstream('"memory"."sushi"."customer_revenue_by_day"')) == {
'"memory"."sushi"."items"',
'"memory"."sushi"."orders"',
'"memory"."sushi"."order_items"',
}
@pytest.mark.slow
def test_render_sql_model(sushi_context, assert_exp_eq, copy_to_temp_path: t.Callable):
assert_exp_eq(
sushi_context.render(
"sushi.waiter_revenue_by_day",
start=date(2021, 1, 1),
end=date(2021, 1, 1),
expand=True,
),
"""
SELECT
CAST("o"."waiter_id" AS INT) AS "waiter_id", /* Waiter id */
CAST(SUM("oi"."quantity" * "i"."price") AS DOUBLE) AS "revenue", /* Revenue from orders taken by this waiter */
CAST("o"."event_date" AS DATE) AS "event_date" /* Date */
FROM (
SELECT
CAST(NULL AS INT) AS "id",
CAST(NULL AS INT) AS "customer_id",
CAST(NULL AS INT) AS "waiter_id",
CAST(NULL AS INT) AS "start_ts",
CAST(NULL AS INT) AS "end_ts",
CAST(NULL AS DATE) AS "event_date"
FROM (VALUES
(1)) AS "t"("dummy")
) AS "o"
LEFT JOIN (
SELECT
CAST(NULL AS INT) AS "id",
CAST(NULL AS INT) AS "order_id",
CAST(NULL AS INT) AS "item_id",
CAST(NULL AS INT) AS "quantity",
CAST(NULL AS DATE) AS "event_date"
FROM (VALUES
(1)) AS "t"("dummy")
) AS "oi"
ON "o"."event_date" = "oi"."event_date" AND "o"."id" = "oi"."order_id"
LEFT JOIN (
SELECT
CAST(NULL AS INT) AS "id",
CAST(NULL AS TEXT) AS "name",
CAST(NULL AS DOUBLE) AS "price",
CAST(NULL AS DATE) AS "event_date"
FROM (VALUES
(1)) AS "t"("dummy")
) AS "i"
ON "i"."event_date" = "oi"."event_date" AND "i"."id" = "oi"."item_id"
WHERE
"o"."event_date" <= CAST('2021-01-01' AS DATE)
AND "o"."event_date" >= CAST('2021-01-01' AS DATE)
GROUP BY
"o"."waiter_id",
"o"."event_date"
""",
)
# unpushed render should not expand
unpushed = Context(paths=copy_to_temp_path("examples/sushi"))
assert_exp_eq(
unpushed.render("sushi.waiter_revenue_by_day"),
"""
SELECT
CAST("o"."waiter_id" AS INT) AS "waiter_id", /* Waiter id */
CAST(SUM("oi"."quantity" * "i"."price") AS DOUBLE) AS "revenue", /* Revenue from orders taken by this waiter */
CAST("o"."event_date" AS DATE) AS "event_date" /* Date */
FROM "memory"."sushi"."orders" AS "o"
LEFT JOIN "memory"."sushi"."order_items" AS "oi"
ON "o"."event_date" = "oi"."event_date" AND "o"."id" = "oi"."order_id"
LEFT JOIN "memory"."sushi"."items" AS "i"
ON "i"."event_date" = "oi"."event_date" AND "i"."id" = "oi"."item_id"
WHERE
"o"."event_date" <= CAST('1970-01-01' AS DATE) AND "o"."event_date" >= CAST('1970-01-01' AS DATE)
GROUP BY
"o"."waiter_id",
"o"."event_date"
""",
)
@pytest.mark.slow
def test_render_non_deployable_parent(sushi_context, assert_exp_eq, copy_to_temp_path: t.Callable):
model = sushi_context.get_model("sushi.waiter_revenue_by_day")
forward_only_kind = model.kind.copy(update={"forward_only": True})
model = model.copy(update={"kind": forward_only_kind, "stamp": "trigger forward-only change"})
sushi_context.upsert_model(model)
sushi_context.plan("dev", no_prompts=True, auto_apply=True)
expected_table_name = parse_one(
sushi_context.get_snapshot("sushi.waiter_revenue_by_day").table_name(is_deployable=False),
into=exp.Table,
).this.this
assert_exp_eq(
sushi_context.render(
"sushi.top_waiters",
start=date(2021, 1, 1),
end=date(2021, 1, 1),
),
f"""
WITH "test_macros" AS (
SELECT
2 AS "lit_two",
"waiter_revenue_by_day"."revenue" * 2.0 AS "sql_exp",
CAST("waiter_revenue_by_day"."revenue" AS TEXT) AS "sql_lit"
FROM "memory"."sqlmesh__sushi"."{expected_table_name}" AS "waiter_revenue_by_day" /* memory.sushi.waiter_revenue_by_day */
)
SELECT
CAST("waiter_revenue_by_day"."waiter_id" AS INT) AS "waiter_id",
CAST("waiter_revenue_by_day"."revenue" AS DOUBLE) AS "revenue"
FROM "memory"."sqlmesh__sushi"."{expected_table_name}" AS "waiter_revenue_by_day" /* memory.sushi.waiter_revenue_by_day */
WHERE
"waiter_revenue_by_day"."event_date" = (
SELECT
MAX("waiter_revenue_by_day"."event_date") AS "_col_0"
FROM "memory"."sqlmesh__sushi"."{expected_table_name}" AS "waiter_revenue_by_day" /* memory.sushi.waiter_revenue_by_day */
)
ORDER BY
"revenue" DESC
LIMIT 10
""",
)
@pytest.mark.slow
def test_render_seed_model(sushi_context, assert_exp_eq):
assert_exp_eq(
sushi_context.render(
"sushi.waiter_names",
start=date(2021, 1, 1),
end=date(2021, 1, 1),
),
"""
SELECT
CAST(id AS BIGINT) AS id,
CAST(name AS TEXT) AS name
FROM (VALUES
(0, 'Toby'),
(1, 'Tyson'),
(2, 'Ryan'),
(3, 'George'),
(4, 'Chris')) AS t(id, name)
""",
)
@pytest.mark.slow
def test_diff(sushi_context: Context, mocker: MockerFixture):
mock_console = mocker.Mock()
sushi_context.console = mock_console
yesterday = yesterday_ds()
success = sushi_context.run(start=yesterday, end=yesterday)
sushi_context.upsert_model("sushi.customers", query=parse_one("select 1 as customer_id"))
sushi_context.diff("test")
assert mock_console.show_environment_difference_summary.called
assert mock_console.show_model_difference_summary.called
assert success
@pytest.mark.slow
def test_evaluate_limit():
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(name with_limit, kind FULL);
SELECT t.v as v FROM (VALUES (1), (2), (3), (4), (5)) AS t(v) LIMIT 1 + 2"""
)
)
)
assert context.evaluate("with_limit", "2020-01-01", "2020-01-02", "2020-01-02").size == 3
assert context.evaluate("with_limit", "2020-01-01", "2020-01-02", "2020-01-02", 4).size == 3
assert context.evaluate("with_limit", "2020-01-01", "2020-01-02", "2020-01-02", 2).size == 2
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(name without_limit, kind FULL);
SELECT t.v as v FROM (VALUES (1), (2), (3), (4), (5)) AS t(v)"""
)
)
)
assert context.evaluate("without_limit", "2020-01-01", "2020-01-02", "2020-01-02").size == 5
assert context.evaluate("without_limit", "2020-01-01", "2020-01-02", "2020-01-02", 4).size == 4
assert context.evaluate("without_limit", "2020-01-01", "2020-01-02", "2020-01-02", 2).size == 2
def test_gateway_specific_adapters(copy_to_temp_path, mocker):
path = copy_to_temp_path("examples/sushi")
ctx = Context(paths=path, config="isolated_systems_config", gateway="prod")
assert len(ctx.engine_adapters) == 3
assert ctx.engine_adapter == ctx.engine_adapters["prod"]
assert ctx._get_engine_adapter("dev") == ctx.engine_adapters["dev"]
ctx = Context(paths=path, config="isolated_systems_config")
assert len(ctx.engine_adapters) == 3
assert ctx.engine_adapter == ctx.engine_adapters["dev"]
ctx = Context(paths=path, config="isolated_systems_config")
assert len(ctx.engine_adapters) == 3
assert ctx.engine_adapter == ctx._get_engine_adapter()
assert ctx._get_engine_adapter("test") == ctx.engine_adapters["test"]
def test_multiple_gateways(tmp_path: Path):
db_path = str(tmp_path / "db.db")
gateways = {
"staging": GatewayConfig(connection=DuckDBConnectionConfig(database=db_path)),
"final": GatewayConfig(connection=DuckDBConnectionConfig(database=db_path)),
}
config = Config(gateways=gateways, default_gateway="final")
context = Context(config=config)
gateway_model = load_sql_based_model(
parse(
"""
MODEL(name staging.stg_model, start '2024-01-01',kind FULL, gateway staging);
SELECT t.v as v FROM (VALUES (1), (2), (3), (4), (5)) AS t(v)"""
),
default_catalog="db",
)
assert gateway_model.gateway == "staging"
context.upsert_model(gateway_model)
assert context.evaluate("staging.stg_model", "2020-01-01", "2020-01-02", "2020-01-02").size == 5
default_model = load_sql_based_model(
parse(
"""
MODEL(name main.final_model, start '2024-01-01',kind FULL);
SELECT v FROM staging.stg_model"""
),
default_catalog="db",
)
assert not default_model.gateway
context.upsert_model(default_model)
context.plan(
execution_time="2024-01-02",
auto_apply=True,
no_prompts=True,
)
sorted_snapshots = sorted(context.snapshots.values())
physical_schemas = [snapshot.physical_schema for snapshot in sorted_snapshots]
assert physical_schemas == ["sqlmesh__main", "sqlmesh__staging"]
view_schemas = [snapshot.qualified_view_name.schema_name for snapshot in sorted_snapshots]
assert view_schemas == ["main", "staging"]
assert (
str(context.fetchdf("select * from staging.stg_model"))
== " v\n0 1\n1 2\n2 3\n3 4\n4 5"
)
assert str(context.fetchdf("select * from final_model")) == " v\n0 1\n1 2\n2 3\n3 4\n4 5"
assert (
context.snapshots['"db"."main"."final_model"'].parents[0].name
== '"db"."staging"."stg_model"'
)
assert context.dag._sorted == ['"db"."staging"."stg_model"', '"db"."main"."final_model"']
def test_plan_execution_time():
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name db.x,
start '2024-01-01',
kind FULL
);
SELECT @execution_date AS execution_date
"""
)
)
)
context.plan(
"dev",
execution_time="2024-01-02",
auto_apply=True,
no_prompts=True,
)
assert (
str(list(context.fetchdf("select * from db__dev.x")["execution_date"])[0])
== "2024-01-02 00:00:00"
)
def test_plan_execution_time_start_end():
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name db.x,
start '2020-01-01',
kind INCREMENTAL_BY_TIME_RANGE (
time_column ds
),
cron '@daily'
);
SELECT id, ds FROM (VALUES
('1', '2020-01-01'),
('2', '2021-01-01'),
('3', '2022-01-01'),
('4', '2023-01-01'),
('5', '2024-01-01')
) data(id, ds)
WHERE ds BETWEEN @start_ds AND @end_ds
"""
)
)
)
# prod plan - no fixed execution time so it defaults to now() and reads all the data
prod_plan = context.plan(auto_apply=True)
assert len(prod_plan.new_snapshots) == 1
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name db.x,
start '2020-01-01',
kind INCREMENTAL_BY_TIME_RANGE (
time_column ds
),
cron '@daily'
);
SELECT id, ds, 'changed' as a FROM (VALUES
('1', '2020-01-01'),
('2', '2021-01-01'),
('3', '2022-01-01'),
('4', '2023-01-01'),
('5', '2024-01-01')
) data(id, ds)
WHERE ds BETWEEN @start_ds AND @end_ds
"""
)
)
)
# dev plan with an execution time in the past and no explicit start/end specified
# the plan end should be bounded to it and not exceed it even though in prod the last interval (used as a default end)
# is newer than the execution time
dev_plan = context.plan("dev", execution_time="2020-01-05")
assert to_datetime(dev_plan.start) == to_datetime(
"2020-01-01"
) # default start is the earliest prod interval
assert to_datetime(dev_plan.execution_time) == to_datetime("2020-01-05")
assert to_datetime(dev_plan.end) == to_datetime(
"2020-01-05"
) # end should not be greater than execution_time
# same as above but with a relative start
dev_plan = context.plan("dev", start="1 day ago", execution_time="2020-01-05")
assert to_datetime(dev_plan.start) == to_datetime(
"2020-01-04"
) # start relative to execution_time
assert to_datetime(dev_plan.execution_time) == to_datetime("2020-01-05")
assert to_datetime(dev_plan.end) == to_datetime(
"2020-01-05"
) # end should not be greater than execution_time
# same as above but with a relative start and a relative end
dev_plan = context.plan("dev", start="2 days ago", execution_time="2020-01-05", end="1 day ago")
assert to_datetime(dev_plan.start) == to_datetime(
"2020-01-03"
) # start relative to execution_time
assert to_datetime(dev_plan.execution_time) == to_datetime("2020-01-05")
assert to_datetime(dev_plan.end) == to_datetime("2020-01-04") # end relative to execution_time
def test_override_builtin_audit_blocking_mode():
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name db.x,
kind FULL,
audits (
not_null(columns := [c], blocking := false),
unique_values(columns := [c]),
)
);
SELECT NULL AS c
"""
)
)
)
with patch.object(context.console, "log_warning") as mock_logger:
plan = context.plan(auto_apply=True, no_prompts=True)
new_snapshot = next(iter(plan.context_diff.new_snapshots.values()))
assert (
mock_logger.call_args_list[0][0][0] == "\ndb.x: 'not_null' audit error: 1 row failed."
)
# Even though there are two builtin audits referenced in the above definition, we only
# store the one that overrides `blocking` in the snapshot; the other one isn't needed
audits_with_args = new_snapshot.model.audits_with_args
assert len(audits_with_args) == 2
audit, args = audits_with_args[0]
assert audit.name == "not_null"
assert list(args) == ["columns", "blocking"]
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name db.x,
kind FULL,
audits (
not_null_non_blocking(columns := [c], blocking := true)
)
);
SELECT NULL AS c
"""
)
)
)
with pytest.raises(SQLMeshError):
context.plan(auto_apply=True, no_prompts=True)
def test_python_model_empty_df_raises(sushi_context, capsys):
sushi_context.console = create_console()
@model(
"memory.sushi.test_model",
columns={"col": "int"},
kind=dict(name=ModelKindName.FULL),
)
def entrypoint(context, **kwargs):
yield pd.DataFrame({"col": []})
test_model = model.get_registry()["memory.sushi.test_model"].model(
module_path=Path("."), path=Path(".")
)
sushi_context.upsert_model(test_model)
capsys.readouterr()
with pytest.raises(SQLMeshError):
sushi_context.plan(no_prompts=True, auto_apply=True)
assert (
"Cannot construct source query from an empty DataFrame. This error is commonly related to Python models that produce no data. For such models, consider yielding from an empty generator if the resulting set is empty, i.e. use"
) in capsys.readouterr().out.replace("\n", "")
def test_env_and_default_schema_normalization(mocker: MockerFixture):
from sqlglot.dialects import DuckDB
from sqlglot.dialects.dialect import NormalizationStrategy
mocker.patch.object(DuckDB, "NORMALIZATION_STRATEGY", NormalizationStrategy.UPPERCASE)
context = Context(config=Config())
context.upsert_model(
load_sql_based_model(
parse(
"""
MODEL(
name x,
kind FULL
);
SELECT 1 AS c
"""
)
)
)
context.plan("dev", auto_apply=True, no_prompts=True)
assert list(context.fetchdf('select c from "DEFAULT__DEV"."X"')["c"])[0] == 1
def test_jinja_macro_undefined_variable_error(tmp_path: pathlib.Path):
models_dir = tmp_path / "models"
models_dir.mkdir(parents=True)
macros_dir = tmp_path / "macros"
macros_dir.mkdir(parents=True)
macro_file = macros_dir / "my_macros.sql"
macro_file.write_text("""
{%- macro generate_select(table_name) -%}
{%- if target.name == 'production' -%}
{%- set results = run_query('SELECT 1') -%}
{%- endif -%}
SELECT {{ results.columns[0].values()[0] }} FROM {{ table_name }}
{%- endmacro -%}
""")
model_file = models_dir / "my_model.sql"
model_file.write_text("""
MODEL (
name my_schema.my_model,
kind FULL
);
JINJA_QUERY_BEGIN;
{{ generate_select('users') }}
JINJA_END;
""")
config_file = tmp_path / "config.yaml"
config_file.write_text("""
model_defaults:
dialect: duckdb
""")
with pytest.raises(ConfigError) as exc_info:
Context(paths=str(tmp_path))
error_message = str(exc_info.value)
assert "Failed to load model" in error_message
assert "Could not render jinja for" in error_message
assert "Undefined macro/variable: 'target' in macro: 'generate_select'" in error_message
def test_clear_caches(tmp_path: pathlib.Path):
models_dir = tmp_path / "models"
cache_dir = models_dir / sqlmesh.core.constants.CACHE
cache_dir.mkdir(parents=True)
model_cache_file = cache_dir / "test.txt"
model_cache_file.write_text("test")
assert model_cache_file.exists()
assert len(list(cache_dir.iterdir())) == 1
context = Context(config=Config(), paths=str(models_dir))
context.clear_caches()
assert not cache_dir.exists()
assert models_dir.exists()
# Ensure that we don't initialize a CachingStateSync only to clear its (empty) caches
assert context._state_sync is None
# Test clearing caches when cache directory doesn't exist
# This should not raise an exception
context.clear_caches()
assert not cache_dir.exists()
def test_clear_caches_with_long_base_path(tmp_path: pathlib.Path):
base_path = tmp_path / ("abcde" * 50)
assert (
len(str(base_path.absolute())) > 260
) # Paths longer than 260 chars trigger problems on Windows
default_cache_dir = base_path / c.CACHE
custom_cache_dir = base_path / ".test_cache"
# note: we create the Context here so it doesnt get passed any "fixed" paths
ctx = Context(config=Config(cache_dir=str(custom_cache_dir)), paths=base_path)
if IS_WINDOWS:
# fix these so we can use them in this test
default_cache_dir = fix_windows_path(default_cache_dir)
custom_cache_dir = fix_windows_path(custom_cache_dir)
default_cache_dir.mkdir(parents=True)
custom_cache_dir.mkdir(parents=True)
default_cache_file = default_cache_dir / "cache.txt"
custom_cache_file = custom_cache_dir / "cache.txt"
default_cache_file.write_text("test")
custom_cache_file.write_text("test")
assert default_cache_file.exists()
assert custom_cache_file.exists()
assert default_cache_dir.exists()
assert custom_cache_dir.exists()
ctx.clear_caches()
assert not default_cache_file.exists()
assert not custom_cache_file.exists()
assert not default_cache_dir.exists()
assert not custom_cache_dir.exists()
def test_cache_path_configurations(tmp_path: pathlib.Path):
project_dir = tmp_path / "project"
project_dir.mkdir(parents=True)
config_file = project_dir / "config.yaml"
# Test relative path
config_file.write_text("model_defaults:\n dialect: duckdb\ncache_dir: .my_cache")
context = Context(paths=str(project_dir))
assert context.cache_dir == project_dir / ".my_cache"
# Test absolute path
abs_cache = tmp_path / "abs_cache"
config_file.write_text(f"model_defaults:\n dialect: duckdb\ncache_dir: {abs_cache}")
context = Context(paths=str(project_dir))
assert context.cache_dir == abs_cache
# Test default
config_file.write_text("model_defaults:\n dialect: duckdb")
context = Context(paths=str(project_dir))
assert context.cache_dir == project_dir / ".cache"
def test_plan_apply_populates_cache(copy_to_temp_path, mocker):
sushi_paths = copy_to_temp_path("examples/sushi")
sushi_path = sushi_paths[0]
custom_cache_dir = sushi_path.parent / "custom_cache"
# Modify the existing config.py to add cache_dir to test_config
config_py_path = sushi_path / "config.py"
with open(config_py_path, "r") as f:
config_content = f.read()
# Add cache_dir to the test_config definition
config_content += f"""test_config_cache_dir = Config(
gateways={{"in_memory": GatewayConfig(connection=DuckDBConnectionConfig())}},
default_gateway="in_memory",
plan=PlanConfig(
auto_categorize_changes=CategorizerConfig(
sql=AutoCategorizationMode.SEMI, python=AutoCategorizationMode.OFF
)
),
model_defaults=model_defaults,
cache_dir="{custom_cache_dir.as_posix()}",
before_all=before_all,
)"""
with open(config_py_path, "w") as f:
f.write(config_content)
# Create context with the test config
context = Context(paths=sushi_path, config="test_config_cache_dir")
custom_cache_dir = context.cache_dir
assert "custom_cache" in str(custom_cache_dir)
assert (custom_cache_dir / "optimized_query").exists()
assert (custom_cache_dir / "model_definition").exists()
assert not (custom_cache_dir / "snapshot").exists()
# Clear the cache
context.clear_caches()
assert not custom_cache_dir.exists()
plan = context.plan("dev", create_from="prod", skip_tests=True)
context.apply(plan)
# Cache directory should now exist again
assert custom_cache_dir.exists()
assert any(custom_cache_dir.iterdir())
# Since the cache has been deleted post loading here only snapshot should exist
assert (custom_cache_dir / "snapshot").exists()
assert not (custom_cache_dir / "optimized_query").exists()
assert not (custom_cache_dir / "model_definition").exists()
# New context should load same models and create the cache for optimized_query and model_definition
initial_model_count = len(context.models)
context2 = Context(paths=context.path, config="test_config_cache_dir")
cached_model_count = len(context2.models)
assert initial_model_count == cached_model_count > 0
assert (custom_cache_dir / "optimized_query").exists()
assert (custom_cache_dir / "model_definition").exists()
assert (custom_cache_dir / "snapshot").exists()
# Clear caches should remove the custom cache directory
context.clear_caches()
assert not custom_cache_dir.exists()
def test_ignore_files(mocker: MockerFixture, tmp_path: pathlib.Path):
mocker.patch.object(
sqlmesh.core.constants,
"IGNORE_PATTERNS",
[".ipynb_checkpoints/*.sql"],
)
models_dir = pathlib.Path("models")
macros_dir = pathlib.Path("macros")
create_temp_file(
tmp_path,
pathlib.Path(models_dir, "ignore", "ignore_model.sql"),
"MODEL(name ignore.ignore_model); SELECT 1 AS cola",
)
create_temp_file(
tmp_path,
pathlib.Path(models_dir, "ignore", "inner_ignore", "inner_ignore_model.sql"),
"MODEL(name ignore.inner_ignore_model); SELECT 1 AS cola",
)
create_temp_file(
tmp_path,
pathlib.Path(macros_dir, "macro_ignore.py"),
"""
from sqlmesh.core.macros import macro
@macro()
def test():
return "test"
""",
)
create_temp_file(
tmp_path,
pathlib.Path(models_dir, ".ipynb_checkpoints", "ignore_model2.sql"),
"MODEL(name ignore_model2); SELECT cola::bigint AS cola FROM db.other_table",
)
create_temp_file(
tmp_path,
pathlib.Path(models_dir, "db", "actual_test.sql"),
"MODEL(name db.actual_test, kind full); SELECT 1 AS cola",
)
create_temp_file(
tmp_path,
pathlib.Path(macros_dir, "macro_file.py"),
"""
from sqlmesh.core.macros import macro
@macro()
def test():
return "test"
""",
)
config = Config(
ignore_patterns=["models/ignore/**/*.sql", "macro_ignore.py", ".ipynb_checkpoints/*"]
)
context = Context(paths=tmp_path, config=config)
assert ['"memory"."db"."actual_test"'] == list(context.models)
assert "test" in context._macros
@pytest.mark.slow
def test_plan_apply(sushi_context_pre_scheduling) -> None:
logger = logging.getLogger("sqlmesh.core.renderer")
with patch.object(logger, "warning") as mock_logger:
sushi_context_pre_scheduling.plan(
"dev",
auto_apply=True,
no_prompts=True,
include_unmodified=True,
)
mock_logger.assert_not_called()
assert sushi_context_pre_scheduling.state_reader.get_environment("dev")
def test_project_config_person_config_overrides(tmp_path: pathlib.Path):
with TemporaryDirectory() as td:
home_path = pathlib.Path(td)
create_temp_file(
home_path,
pathlib.Path("config.yaml"),
"""
gateways:
snowflake:
connection:
type: snowflake
password: XYZ
user: ABC
""",
)
project_config = create_temp_file(
tmp_path,
pathlib.Path("config.yaml"),
"""
gateways:
snowflake:
connection:
type: snowflake
account: abc123
user: CDE
model_defaults:
dialect: snowflake
""",
)
with pytest.raises(
ConfigError,
match="User and password must be provided if using default authentication",
):
load_configs("config", Config, paths=project_config.parent)
loaded_configs: t.Dict[pathlib.Path, Config] = load_configs(
"config", Config, paths=project_config.parent, sqlmesh_path=home_path
)
assert len(loaded_configs) == 1
snowflake_connection = list(loaded_configs.values())[0].gateways["snowflake"].connection # type: ignore
assert isinstance(snowflake_connection, SnowflakeConnectionConfig)
assert snowflake_connection.account == "abc123"
assert snowflake_connection.user == "ABC"
assert snowflake_connection.password == "XYZ"
assert snowflake_connection.application == "Tobiko_SQLMesh"
@pytest.mark.slow
def test_physical_schema_override(copy_to_temp_path: t.Callable) -> None:
def get_schemas(context: Context):
return {
snapshot.physical_schema for snapshot in context.snapshots.values() if snapshot.is_model
}
def get_view_schemas(context: Context):
return {
snapshot.qualified_view_name.schema_name
for snapshot in context.snapshots.values()
if snapshot.is_model
}
def get_sushi_fingerprints(context: Context):
return {
snapshot.fingerprint.to_identifier()
for snapshot in context.snapshots.values()
if snapshot.is_model and snapshot.model.schema_name == "sushi"
}
project_path = copy_to_temp_path("examples/sushi")
no_mapping_context = Context(paths=project_path)
assert no_mapping_context.config.physical_schema_mapping == {}
assert get_schemas(no_mapping_context) == {"sqlmesh__sushi", "sqlmesh__raw"}
assert get_view_schemas(no_mapping_context) == {"sushi", "raw"}
no_mapping_fingerprints = get_sushi_fingerprints(no_mapping_context)
context = Context(paths=project_path, config="map_config")
assert context.config.physical_schema_mapping == {re.compile("^sushi$"): "company_internal"}
assert get_schemas(context) == {"company_internal", "sqlmesh__raw"}
assert get_view_schemas(context) == {"sushi", "raw"}
sushi_fingerprints = get_sushi_fingerprints(context)
assert (
len(sushi_fingerprints)
== len(no_mapping_fingerprints)
== len(no_mapping_fingerprints - sushi_fingerprints)
)
@pytest.mark.slow
def test_physical_schema_mapping(tmp_path: pathlib.Path) -> None:
create_temp_file(
tmp_path,
pathlib.Path(pathlib.Path("models"), "a.sql"),
"MODEL(name foo_staging.model_a); SELECT 1;",
)
create_temp_file(