-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathtest_config.py
More file actions
1540 lines (1283 loc) · 46.2 KB
/
test_config.py
File metadata and controls
1540 lines (1283 loc) · 46.2 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 os
import pathlib
import re
from pathlib import Path
from unittest import mock
import typing as t
import pytest
from pytest_mock import MockerFixture
from sqlglot import exp
from sqlmesh.core.config import (
Config,
DuckDBConnectionConfig,
GatewayConfig,
ModelDefaultsConfig,
BigQueryConnectionConfig,
MotherDuckConnectionConfig,
BuiltInSchedulerConfig,
EnvironmentSuffixTarget,
TableNamingConvention,
)
from sqlmesh.core.config.connection import DuckDBAttachOptions, RedshiftConnectionConfig
from sqlmesh.core.config.loader import (
load_config_from_env,
load_config_from_paths,
load_config_from_python_module,
load_configs,
)
from sqlmesh.core.context import Context
from sqlmesh.core.engine_adapter.athena import AthenaEngineAdapter
from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter
from sqlmesh.core.engine_adapter.redshift import RedshiftEngineAdapter
from sqlmesh.core.notification_target import ConsoleNotificationTarget
from sqlmesh.core.user import User
from sqlmesh.utils.errors import ConfigError
from sqlmesh.utils import yaml
from sqlmesh.dbt.loader import DbtLoader
from tests.utils.test_filesystem import create_temp_file
@pytest.fixture(scope="session")
def yaml_config_path(tmp_path_factory) -> Path:
config_path = tmp_path_factory.mktemp("yaml_config") / "config.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
another_gateway:
connection:
type: duckdb
database: test_db
model_defaults:
dialect: ''
"""
)
return config_path
@pytest.fixture(scope="session")
def python_config_path(tmp_path_factory) -> Path:
config_path = tmp_path_factory.mktemp("python_config") / "config.py"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig, ModelDefaultsConfig
config = Config(gateways=GatewayConfig(connection=DuckDBConnectionConfig()), model_defaults=ModelDefaultsConfig(dialect=''))
"""
)
return config_path
def test_update_with_gateways():
gateway0_config = GatewayConfig(connection=DuckDBConnectionConfig())
gateway1_config = GatewayConfig(connection=DuckDBConnectionConfig(database="test"))
assert Config(gateways=gateway0_config).update_with(
Config(gateways={"gateway1": gateway1_config})
) == Config(gateways={"": gateway0_config, "gateway1": gateway1_config})
assert Config(gateways={"gateway1": gateway1_config}).update_with(
Config(gateways=gateway0_config)
) == Config(gateways={"gateway1": gateway1_config, "": gateway0_config})
assert Config(gateways=gateway0_config).update_with(Config(gateways=gateway1_config)) == Config(
gateways=gateway1_config
)
assert Config(gateways={"gateway0": gateway0_config}).update_with(
Config(gateways={"gateway1": gateway1_config})
) == Config(gateways={"gateway0": gateway0_config, "gateway1": gateway1_config})
def test_update_with_users():
user_a = User(username="a")
user_b = User(username="b")
assert Config(users=[user_a]).update_with(Config(users=[user_b])) == Config(
users=[user_a, user_b]
)
def test_update_with_ignore_patterns():
pattern_a = "pattern_a"
pattern_b = "pattern_b"
assert Config(ignore_patterns=[pattern_a]).update_with(
Config(ignore_patterns=[pattern_b])
) == Config(ignore_patterns=[pattern_a, pattern_b])
def test_update_with_notification_targets():
target = ConsoleNotificationTarget()
assert Config(notification_targets=[target]).update_with(
Config(notification_targets=[target])
) == Config(notification_targets=[target] * 2)
def test_update_with_model_defaults():
config_a = Config(model_defaults=ModelDefaultsConfig(start="2022-01-01", dialect="duckdb"))
config_b = Config(model_defaults=ModelDefaultsConfig(dialect="spark"))
assert config_a.update_with(config_b) == Config(
model_defaults=ModelDefaultsConfig(start="2022-01-01", dialect="spark")
)
def test_default_gateway():
gateway_a = GatewayConfig(connection=DuckDBConnectionConfig(database="test_db_a"))
gateway_b = GatewayConfig(connection=DuckDBConnectionConfig(database="test_db_b"))
gateway_c = GatewayConfig(connection=DuckDBConnectionConfig(database="test_db_c"))
config = Config(
gateways={
"gateway1": gateway_b,
"gateway2": gateway_c,
"": gateway_a,
},
)
assert config.get_gateway() == gateway_a
assert config.copy(update={"default_gateway": "gateway2"}).get_gateway() == gateway_c
assert (
Config(
gateways={
"gateway1": gateway_b,
"gateway2": gateway_c,
},
).get_gateway()
== gateway_b
)
with pytest.raises(
ConfigError,
match="Missing gateway with name 'missing'",
):
config.copy(update={"default_gateway": "missing"}).get_gateway()
def test_load_config_from_paths(yaml_config_path: Path, python_config_path: Path):
config: Config = load_config_from_paths(
Config,
project_paths=[yaml_config_path, python_config_path],
)
assert config == Config(
gateways={ # type: ignore
"another_gateway": GatewayConfig(connection=DuckDBConnectionConfig(database="test_db")),
"": GatewayConfig(connection=DuckDBConnectionConfig()),
},
model_defaults=ModelDefaultsConfig(dialect=""),
)
def test_load_config_multiple_config_files_in_folder(tmp_path):
config_a_path = tmp_path / "config.yaml"
with open(config_a_path, "w", encoding="utf-8") as fd:
fd.write("project: project_a")
config_b_path = tmp_path / "config.yml"
with open(config_b_path, "w", encoding="utf-8") as fd:
fd.write("project: project_b")
with pytest.raises(ConfigError, match=r"^Multiple configuration files found in folder.*"):
load_config_from_paths(Config, project_paths=[config_a_path, config_b_path])
def test_load_config_no_config():
with pytest.raises(ConfigError, match=r"^SQLMesh project config could not be found.*"):
load_config_from_paths(Config, load_from_env=False)
def test_load_config_no_dialect(tmp_path):
create_temp_file(
tmp_path,
pathlib.Path("config.yaml"),
"""
gateways:
local:
connection:
type: duckdb
database: db.db
""",
)
create_temp_file(
tmp_path,
pathlib.Path("config.py"),
"""
from sqlmesh.core.config import Config, DuckDBConnectionConfig
config = Config(default_connection=DuckDBConnectionConfig())
""",
)
with pytest.raises(
ConfigError, match=r"^Default model SQL dialect is a required configuration parameter.*"
):
load_config_from_paths(Config, project_paths=[tmp_path / "config.yaml"])
with pytest.raises(
ConfigError, match=r"^Default model SQL dialect is a required configuration parameter.*"
):
load_config_from_paths(Config, project_paths=[tmp_path / "config.py"])
def test_load_config_bad_model_default_key(tmp_path):
create_temp_file(
tmp_path,
pathlib.Path("config.yaml"),
"""
gateways:
local:
connection:
type: duckdb
database: db.db
model_defaults:
dialect: ''
test: 1
""",
)
with pytest.raises(
ConfigError, match=r"^'test' is not a valid model default configuration key.*"
):
load_config_from_paths(Config, project_paths=[tmp_path / "config.yaml"])
def test_load_config_unsupported_extension(tmp_path):
config_path = tmp_path / "config.txt"
config_path.touch()
with pytest.raises(ConfigError, match=r"^Unsupported config file extension 'txt'.*"):
load_config_from_paths(Config, project_paths=[config_path])
def test_load_python_config_with_personal_config(tmp_path):
create_temp_file(
tmp_path / "personal",
pathlib.Path("config.yaml"),
"""
gateways:
local:
connection:
type: duckdb
database: db.db
""",
)
create_temp_file(
tmp_path,
pathlib.Path("config.py"),
"""
from sqlmesh.core.config import Config, DuckDBConnectionConfig, ModelDefaultsConfig
custom_config = Config(default_connection=DuckDBConnectionConfig(), model_defaults=ModelDefaultsConfig(dialect="duckdb"))
""",
)
config = load_config_from_paths(
Config,
project_paths=[tmp_path / "config.py"],
personal_paths=[tmp_path / "personal" / "config.yaml"],
config_name="custom_config",
)
assert config.gateways["local"].connection.database == "db.db"
assert config.default_connection.database is None
assert config.model_defaults.dialect == "duckdb"
def test_load_config_from_env():
with mock.patch.dict(
os.environ,
{
"SQLMESH__GATEWAY__CONNECTION__TYPE": "duckdb",
"SQLMESH__GATEWAY__CONNECTION__DATABASE": "test_db",
},
):
assert Config.parse_obj(load_config_from_env()) == Config(
gateways=GatewayConfig(connection=DuckDBConnectionConfig(database="test_db")),
)
def test_load_config_from_env_fails():
with mock.patch.dict(os.environ, {"SQLMESH__GATEWAYS__ABCDEF__CONNECTION__PASSWORD": "..."}):
with pytest.raises(
ConfigError,
match="Missing connection type.\n\nVerify your config.yaml and environment variables.",
):
Config.parse_obj(load_config_from_env())
def test_load_config_from_env_no_config_vars():
with mock.patch.dict(
os.environ,
{
"DUMMY_ENV_VAR": "dummy",
},
):
assert load_config_from_env() == {}
def test_load_config_from_env_invalid_variable_name():
with mock.patch.dict(
os.environ,
{
"SQLMESH__": "",
},
):
with pytest.raises(
ConfigError,
match="Invalid SQLMesh configuration variable 'sqlmesh__'.",
):
load_config_from_env()
def test_load_yaml_config_env_var_gateway_override(tmp_path_factory):
config_path = tmp_path_factory.mktemp("yaml_config") / "config.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
testing:
connection:
type: motherduck
database: blah
model_defaults:
dialect: bigquery
"""
)
with mock.patch.dict(
os.environ,
{
"SQLMESH__GATEWAYS__TESTING__STATE_CONNECTION__TYPE": "bigquery",
"SQLMESH__GATEWAYS__TESTING__STATE_CONNECTION__CHECK_IMPORT": "false",
"SQLMESH__DEFAULT_GATEWAY": "testing",
},
):
assert load_config_from_paths(
Config,
project_paths=[config_path],
) == Config(
gateways={
"testing": GatewayConfig(
connection=MotherDuckConnectionConfig(database="blah"),
state_connection=BigQueryConnectionConfig(check_import=False),
),
},
model_defaults=ModelDefaultsConfig(dialect="bigquery"),
default_gateway="testing",
)
def test_load_py_config_env_var_gateway_override(tmp_path_factory):
config_path = tmp_path_factory.mktemp("python_config") / "config.py"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig, ModelDefaultsConfig
config = Config(gateways={"duckdb_gateway": GatewayConfig(connection=DuckDBConnectionConfig())}, model_defaults=ModelDefaultsConfig(dialect=''))
"""
)
with mock.patch.dict(
os.environ,
{
"SQLMESH__GATEWAYS__DUCKDB_GATEWAY__STATE_CONNECTION__TYPE": "bigquery",
"SQLMESH__GATEWAYS__DUCKDB_GATEWAY__STATE_CONNECTION__CHECK_IMPORT": "false",
"SQLMESH__DEFAULT_GATEWAY": "duckdb_gateway",
},
):
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert config == Config(
gateways={ # type: ignore
"duckdb_gateway": GatewayConfig(
connection=DuckDBConnectionConfig(),
state_connection=BigQueryConnectionConfig(check_import=False),
),
},
model_defaults=ModelDefaultsConfig(dialect=""),
default_gateway="duckdb_gateway",
)
def test_load_config_from_python_module_missing_config(tmp_path):
config_path = tmp_path / "missing_config.py"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write("from sqlmesh.core.config import Config")
with pytest.raises(ConfigError, match="Config 'config' was not found."):
load_config_from_python_module(Config, config_path)
def test_load_config_from_python_module_invalid_config_object(tmp_path):
config_path = tmp_path / "invalid_config.py"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write("config = None")
with pytest.raises(
ConfigError,
match=r"^Config needs to be a valid object.*",
):
load_config_from_python_module(Config, config_path)
@pytest.mark.parametrize(
[
"mapping",
"expected",
"dialect",
"raise_error",
],
[
(
"'^dev$': dev_catalog\n '^other$': other_catalog",
{re.compile("^dev$"): "dev_catalog", re.compile("^other$"): "other_catalog"},
"duckdb",
"",
),
(
"'^(?!prod$)': dev",
{re.compile("^(?!prod$)"): "dev"},
"duckdb",
"",
),
(
"'^dev$': dev_catalog\n '[': other_catalog",
{},
"duckdb",
"`\\[` is not a valid regular expression.",
),
(
"'^prod$': prod_catalog",
{re.compile("^prod$"): "PROD_CATALOG"},
"snowflake",
"",
),
],
)
def test_environment_catalog_mapping(tmp_path_factory, mapping, expected, dialect, raise_error):
config_path = tmp_path_factory.mktemp("yaml_config") / "config.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
f"""
gateways:
local:
connection:
type: duckdb
model_defaults:
dialect: {dialect}
environment_catalog_mapping:
{mapping}
"""
)
if raise_error:
with pytest.raises(ConfigError, match=raise_error):
load_config_from_paths(
Config,
project_paths=[config_path],
)
else:
assert (
load_config_from_paths(Config, project_paths=[config_path]).environment_catalog_mapping
== expected
)
def test_physical_schema_mapping_mutually_exclusive_with_physical_schema_override() -> None:
Config(physical_schema_override={"foo": "bar"}) # type: ignore
Config(physical_schema_mapping={"^foo$": "bar"})
with pytest.raises(
ConfigError, match=r"Only one.*physical_schema_override.*physical_schema_mapping"
):
Config(physical_schema_override={"foo": "bar"}, physical_schema_mapping={"^foo$": "bar"}) # type: ignore
def test_load_alternative_config_type(yaml_config_path: Path, python_config_path: Path):
class DerivedConfig(Config):
pass
config = load_config_from_paths(
DerivedConfig,
project_paths=[yaml_config_path, python_config_path],
)
assert config == DerivedConfig(
gateways={ # type: ignore
"another_gateway": GatewayConfig(connection=DuckDBConnectionConfig(database="test_db")),
"": GatewayConfig(connection=DuckDBConnectionConfig()),
},
model_defaults=ModelDefaultsConfig(dialect=""),
)
def test_connection_config_serialization():
config = Config(
default_connection=DuckDBConnectionConfig(database="my_db"),
default_test_connection=DuckDBConnectionConfig(database="my_test_db"),
)
serialized = config.dict()
assert serialized["default_connection"] == {
"concurrent_tasks": 1,
"register_comments": True,
"type": "duckdb",
"extensions": [],
"pre_ping": False,
"pretty_sql": False,
"connector_config": {},
"secrets": [],
"filesystems": [],
"database": "my_db",
}
assert serialized["default_test_connection"] == {
"concurrent_tasks": 1,
"register_comments": True,
"type": "duckdb",
"extensions": [],
"pre_ping": False,
"pretty_sql": False,
"connector_config": {},
"secrets": [],
"filesystems": [],
"database": "my_test_db",
}
def test_variables():
variables = {
"int_var": 1,
"str_var": "test_value",
"bool_var": True,
"float_var": 1.0,
"list_var": [1, 2, 3],
"dict_var": {"a": "test_value", "b": 2},
}
gateway_variables = {
"UPPERCASE_VAR": 2,
}
config = Config(
variables=variables, gateways={"local": GatewayConfig(variables=gateway_variables)}
)
assert config.variables == variables
assert config.get_gateway("local").variables == {"uppercase_var": 2}
with pytest.raises(
ConfigError, match="Unsupported variable value type: <class 'sqlglot.expressions.Column'>"
):
Config(variables={"invalid_var": exp.column("sqlglot_expr")})
def test_load_duckdb_attach_config(tmp_path):
config_path = tmp_path / "config_duckdb_attach.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
another_gateway:
connection:
type: duckdb
catalogs:
memory: ':memory:'
sqlite:
type: 'sqlite'
path: 'test.db'
postgres:
type: 'postgres'
path: 'dbname=postgres user=postgres host=127.0.0.1'
read_only: true
model_defaults:
dialect: ''
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert config.gateways["another_gateway"].connection.catalogs.get("memory") == ":memory:"
attach_config_1 = config.gateways["another_gateway"].connection.catalogs.get("sqlite")
assert isinstance(attach_config_1, DuckDBAttachOptions)
assert attach_config_1.type == "sqlite"
assert attach_config_1.path == "test.db"
assert attach_config_1.read_only is False
attach_config_2 = config.gateways["another_gateway"].connection.catalogs.get("postgres")
assert isinstance(attach_config_2, DuckDBAttachOptions)
assert attach_config_2.type == "postgres"
assert attach_config_2.path == "dbname=postgres user=postgres host=127.0.0.1"
assert attach_config_2.read_only is True
def test_load_model_defaults_audits(tmp_path):
config_path = tmp_path / "config_model_defaults_audits.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
model_defaults:
dialect: ''
audits:
- assert_positive_order_ids
- does_not_exceed_threshold(column := id, threshold := 1000)
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert len(config.model_defaults.audits) == 2
assert config.model_defaults.audits[0] == ("assert_positive_order_ids", {})
assert config.model_defaults.audits[1][0] == "does_not_exceed_threshold"
assert type(config.model_defaults.audits[1][1]["column"]) == exp.Column
assert config.model_defaults.audits[1][1]["column"].this.this == "id"
assert type(config.model_defaults.audits[1][1]["threshold"]) == exp.Literal
assert config.model_defaults.audits[1][1]["threshold"].this == "1000"
def test_load_model_defaults_statements(tmp_path):
config_path = tmp_path / "config_model_defaults_statements.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
model_defaults:
dialect: duckdb
pre_statements:
- SET memory_limit = '10GB'
- CREATE TEMP TABLE temp_data AS SELECT 1 as id
post_statements:
- DROP TABLE IF EXISTS temp_data
- ANALYZE @this_model
- SET memory_limit = '5GB'
on_virtual_update:
- UPDATE stats_table SET last_update = CURRENT_TIMESTAMP
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert config.model_defaults.pre_statements is not None
assert len(config.model_defaults.pre_statements) == 2
assert isinstance(exp.maybe_parse(config.model_defaults.pre_statements[0]), exp.Set)
assert isinstance(exp.maybe_parse(config.model_defaults.pre_statements[1]), exp.Create)
assert config.model_defaults.post_statements is not None
assert len(config.model_defaults.post_statements) == 3
assert isinstance(exp.maybe_parse(config.model_defaults.post_statements[0]), exp.Drop)
assert isinstance(exp.maybe_parse(config.model_defaults.post_statements[1]), exp.Analyze)
assert isinstance(exp.maybe_parse(config.model_defaults.post_statements[2]), exp.Set)
assert config.model_defaults.on_virtual_update is not None
assert len(config.model_defaults.on_virtual_update) == 1
assert isinstance(exp.maybe_parse(config.model_defaults.on_virtual_update[0]), exp.Update)
def test_load_model_defaults_validation_statements(tmp_path):
config_path = tmp_path / "config_model_defaults_statements_wrong.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
model_defaults:
dialect: duckdb
pre_statements:
- 313
"""
)
with pytest.raises(TypeError, match=r"expected str instance, int found"):
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
def test_scheduler_config(tmp_path_factory):
config_path = tmp_path_factory.mktemp("yaml_config") / "config.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
builtin_gateway:
scheduler:
type: builtin
default_scheduler:
type: builtin
model_defaults:
dialect: bigquery
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert isinstance(config.default_scheduler, BuiltInSchedulerConfig)
assert isinstance(config.get_gateway("builtin_gateway").scheduler, BuiltInSchedulerConfig)
def test_multi_gateway_config(tmp_path, mocker: MockerFixture):
config_path = tmp_path / "config_athena_redshift.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
redshift:
connection:
type: redshift
user: user
password: '1234'
host: host
database: db
test_connection:
type: redshift
database: test_db
state_connection:
type: duckdb
database: state.db
athena:
connection:
type: athena
aws_access_key_id: '1234'
aws_secret_access_key: accesskey
work_group: group
s3_warehouse_location: s3://location
duckdb:
connection:
type: duckdb
database: db.db
default_gateway: redshift
model_defaults:
dialect: redshift
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
ctx = Context(paths=tmp_path, config=config)
assert isinstance(ctx.connection_config, RedshiftConnectionConfig)
assert len(ctx.engine_adapters) == 3
assert isinstance(ctx.engine_adapters["athena"], AthenaEngineAdapter)
assert isinstance(ctx.engine_adapters["redshift"], RedshiftEngineAdapter)
assert isinstance(ctx.engine_adapters["duckdb"], DuckDBEngineAdapter)
assert ctx.engine_adapter == ctx._get_engine_adapter("redshift")
# The duckdb engine adapter should be have been set as multithreaded as well
assert ctx.engine_adapters["duckdb"]._multithreaded
def test_multi_gateway_single_threaded_config(tmp_path):
config_path = tmp_path / "config_duck_athena.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
duckdb:
connection:
type: duckdb
database: db.db
athena:
connection:
type: athena
aws_access_key_id: '1234'
aws_secret_access_key: accesskey
work_group: group
s3_warehouse_location: s3://location
default_gateway: duckdb
model_defaults:
dialect: duckdb
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
ctx = Context(paths=tmp_path, config=config)
assert isinstance(ctx.connection_config, DuckDBConnectionConfig)
assert len(ctx.engine_adapters) == 2
assert ctx.engine_adapter == ctx._get_engine_adapter("duckdb")
assert isinstance(ctx.engine_adapters["athena"], AthenaEngineAdapter)
# In this case athena should use 1 concurrent task as the default gateway is duckdb
assert not ctx.engine_adapters["athena"]._multithreaded
def test_trino_schema_location_mapping_syntax(tmp_path):
config_path = tmp_path / "config_trino.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
trino:
connection:
type: trino
user: trino
host: trino
catalog: trino
schema_location_mapping:
'^utils$': 's3://utils-bucket/@{schema_name}'
'^landing\\..*$': 's3://raw-data/@{catalog_name}/@{schema_name}'
default_gateway: trino
model_defaults:
dialect: trino
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
from sqlmesh.core.config.connection import TrinoConnectionConfig
conn = config.gateways["trino"].connection
assert isinstance(conn, TrinoConnectionConfig)
assert len(conn.schema_location_mapping) == 2
def test_gcp_postgres_ip_and_scopes(tmp_path):
config_path = tmp_path / "config_gcp_postgres.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
gcp_postgres:
connection:
type: gcp_postgres
check_import: false
instance_connection_string: something
user: user
password: password
db: db
ip_type: private
scopes:
- https://www.googleapis.com/auth/cloud-platform
- https://www.googleapis.com/auth/sqlservice.admin
default_gateway: gcp_postgres
model_defaults:
dialect: postgres
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
from sqlmesh.core.config.connection import GCPPostgresConnectionConfig
conn = config.gateways["gcp_postgres"].connection
assert isinstance(conn, GCPPostgresConnectionConfig)
assert len(conn.scopes) == 2
assert conn.scopes[0] == "https://www.googleapis.com/auth/cloud-platform"
assert conn.scopes[1] == "https://www.googleapis.com/auth/sqlservice.admin"
assert conn.ip_type == "private"
def test_gateway_model_defaults(tmp_path):
global_defaults = ModelDefaultsConfig(
dialect="snowflake", owner="foo", optimize_query=True, enabled=True, cron="@daily"
)
gateway_defaults = ModelDefaultsConfig(dialect="duckdb", owner="baz", optimize_query=False)
config = Config(
gateways={
"duckdb": GatewayConfig(
connection=DuckDBConnectionConfig(database="db.db"),
model_defaults=gateway_defaults,
)
},
model_defaults=global_defaults,
default_gateway="duckdb",
)
ctx = Context(paths=tmp_path, config=config, gateway="duckdb")
expected = ModelDefaultsConfig(
dialect="duckdb", owner="baz", optimize_query=False, enabled=True, cron="@daily"
)
assert ctx.config.model_defaults == expected
def test_model_defaults_cron_tz(tmp_path):
"""Test that cron_tz can be set in model_defaults."""
import zoneinfo
config_path = tmp_path / "config_model_defaults_cron_tz.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
model_defaults:
dialect: duckdb
cron: '@daily'
cron_tz: 'America/Los_Angeles'
"""
)
config = load_config_from_paths(
Config,
project_paths=[config_path],
)
assert config.model_defaults.cron == "@daily"
assert config.model_defaults.cron_tz == zoneinfo.ZoneInfo("America/Los_Angeles")
assert config.model_defaults.cron_tz.key == "America/Los_Angeles"
def test_gateway_model_defaults_cron_tz(tmp_path):
"""Test that cron_tz can be set in gateway-specific model_defaults."""
import zoneinfo
global_defaults = ModelDefaultsConfig(
dialect="snowflake", owner="foo", cron="@daily", cron_tz="UTC"
)
gateway_defaults = ModelDefaultsConfig(dialect="duckdb", cron_tz="America/New_York")
config = Config(
gateways={
"duckdb": GatewayConfig(
connection=DuckDBConnectionConfig(database="db.db"),
model_defaults=gateway_defaults,
)
},
model_defaults=global_defaults,
default_gateway="duckdb",
)
ctx = Context(paths=tmp_path, config=config, gateway="duckdb")
expected = ModelDefaultsConfig(
dialect="duckdb", owner="foo", cron="@daily", cron_tz="America/New_York"
)
assert ctx.config.model_defaults == expected
# Also verify the cron_tz is a ZoneInfo object
assert isinstance(ctx.config.model_defaults.cron_tz, zoneinfo.ZoneInfo)
assert ctx.config.model_defaults.cron_tz.key == "America/New_York"
def test_redshift_merge_flag(tmp_path, mocker: MockerFixture):
config_path = tmp_path / "config_redshift_merge.yaml"
with open(config_path, "w", encoding="utf-8") as fd:
fd.write(
"""
gateways:
redshift:
connection:
type: redshift
user: user
password: '1234'