-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathtest_connection_config.py
More file actions
1970 lines (1676 loc) · 67.8 KB
/
test_connection_config.py
File metadata and controls
1970 lines (1676 loc) · 67.8 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 base64
import re
import typing as t
import pytest
from _pytest.fixtures import FixtureRequest
from sqlglot import exp
from unittest.mock import patch, MagicMock
from sqlmesh.core.config.connection import (
BigQueryConnectionConfig,
ClickhouseConnectionConfig,
ConnectionConfig,
DatabricksConnectionConfig,
DuckDBAttachOptions,
FabricConnectionConfig,
DuckDBConnectionConfig,
GCPPostgresConnectionConfig,
MotherDuckConnectionConfig,
MySQLConnectionConfig,
PostgresConnectionConfig,
SnowflakeConnectionConfig,
TrinoAuthenticationMethod,
AthenaConnectionConfig,
MSSQLConnectionConfig,
_connection_config_validator,
_get_engine_import_validator,
INIT_DISPLAY_INFO_TO_TYPE,
)
from sqlmesh.utils.errors import ConfigError
from sqlmesh.utils.pydantic import PydanticModel
@pytest.fixture
def make_config() -> t.Callable:
def _make_function(**kwargs) -> ConnectionConfig:
return _connection_config_validator( # type: ignore
None, # type: ignore
kwargs,
)
return _make_function
@pytest.fixture
def snowflake_key_no_passphrase_path() -> str:
# openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8
return "tests/fixtures/snowflake/rsa_key_no_pass.p8"
@pytest.fixture
def snowflake_key_no_passphrase_pem(snowflake_key_no_passphrase_path) -> str:
with open(snowflake_key_no_passphrase_path, "r", encoding="utf-8") as key:
return key.read()
@pytest.fixture
def snowflake_key_no_passphrase_b64(snowflake_key_no_passphrase_pem) -> str:
return "\n".join(snowflake_key_no_passphrase_pem.split("\n")[1:-2])
@pytest.fixture
def snowflake_key_no_passphrase_bytes(snowflake_key_no_passphrase_b64) -> bytes:
return base64.b64decode(snowflake_key_no_passphrase_b64)
@pytest.fixture
def snowflake_key_passphrase_path() -> str:
return "tests/fixtures/snowflake/rsa_key_pass.p8"
@pytest.fixture
def snowflake_key_passphrase_pem(snowflake_key_passphrase_path) -> str:
with open(snowflake_key_passphrase_path, "r", encoding="utf-8") as key:
return key.read()
@pytest.fixture
def snowflake_key_passphrase_b64() -> str:
return "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCIxN7HxKFBa9e4CXdm6/2iDBgKt0QWFqKXnRH1oY3m3LgLHuhgZWb6itQGpEoRSoW3xizw9GeLdM8Jwq9OvZAPLxipC/MWrK3/ksnulBVyntPumeSKvumpUcbpVocyTGyvtiw+pwHNOySZDfgCHY0qcp3FiIk5iKN1qbOxEEeeKjwzCmv5Yd4A32TiNjmMkFso3EGxdR7CRhzNJFE+iJZ5R5drF0CHVB9hZEomf73gdWgAbhDr2KzJvsDvEUwcIZSHj+XKAtOtGSXiqwVp9reX5wBlrgQlvPrm8gPi9fkm+lJahTpprrYLvQlj+ccmgXE43ANY3WKagsJUNxi9EFuvAgMBAAECggEACEBoeIECgaHyB+Z6T7lZOheks7DO6M5AzQjq9njiyNT0PaeFuZsklWUe2a+70ENAwg+w0nDMdnt7qkkWrpd9Q41B3aEc73dHoC3JBR3mFV5Dxxd91GkkS9TlPVq9GWnG/OruzHDjCPDSinFvTyFdTPxRTIOqU9BMnGK6tqoWyBIJrG62EMXiBFxuFW8GPqsDHyTaVtO7bX47UoRbVhgh442PdV3GyKyKZDYoiPujnkVxE780zq8H2YL1xGfacDnTwoqpQfaA45fAaZc9guPI4C/8SWGfM+SBeA66ZqOUxgl62GYsybpYSTZAZeFRYZO+AlPgmhK2iNCvWFQgI6zRkQKBgQDBaAx5VlActbc6BrTLQuPhs4j3WvbayjCAdTyBeEJAboEr6Az2X/bcmI3krYin/XlIZkNMkktktS/M0Vxj6zwK7zQ7bULitIXQ3JrFDNt3pYdKY4eFSd7ALxc6DB7P1VetqlotOSUX4lZYEcsQ0eQsuj+ELtKPAS+LoNQVYnATxQKBgQC1CFhMiSzEYrHqQE5NrStjLRJzJcz6eCvUfkFMUFg06cp/hc8aePx2qTTgBlskRAh3k+7oObVCWQF3+h8ptRZ8O+AlVilKT/BvORrMVUDRGxtwg4QUD8/lvKIK4jyW5DNa4x7uou6/eBiBqRaLq7AR/UJP52ZWBmfKxUphPxzE4wKBgGrXe+ybze3ORMX9ZmrTLOhGMefTjIMZJuoP2bj8Ij1NznXe3ypLoSgD7n7hjpie4h0owQzP1G5x2VIgZhWcobK4qfYaSdTLPRFAjQ9GJwdVngNuMDNlt3Qbj401nN/bT3BUpzRMWT10f5ZvXeqQyKgcy3HOG+t8EDPmSML3ekqxAoGARyJ4T9q3FJQThRCvtCYPnnDfhw+bc/A0iNLzpaEMh/4169YQgz53NclXVZAp0B5LlXEzt1y1tNR0l0hZZnIZ28dLVGB+6QxwVcQCm7gEOCaGqbeD9r4f2w48PjqXxFL3Owdz6CFt3x65wnlGuqtEDE2P+QXcWIE715memIfMLjECgYB4SA/YOopbGeYPzU9jj0RpykyRjGMNdUyHypjDswwvZc7MMB3dYjynwoTSuGBTVm7R3NWS/Uj54MdZhGvfyb+xmEHaorPJv9YT5/b48mr3rhzPkFoJdy85epVzLvuZzSTPg92tDIcdF/Uabc7eLEbB3H5mVYqk6qRecL4h1fNIqg=="
@pytest.fixture
def snowflake_key_passphrase_bytes(snowflake_key_passphrase_b64) -> bytes:
return base64.b64decode(snowflake_key_passphrase_b64)
@pytest.fixture
def snowflake_oauth_access_token() -> str:
return "eyJhbGciOiJSUzI1NiIsImtpZCI6ImFmZmM2MjkwN2E0NDYxODJhZGMxZmE0ZTgxZmRiYTYzMTBkY2U2M2YifQ.eyJhenAiOiIyNzIxOTYwNjkxNzMtZm81ZWI0MXQzbmR1cTZ1ZXRkc2pkdWdzZXV0ZnBtc3QuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyNzIxOTYwNjkxNzMtZm81ZWI0MXQzbmR1cTZ1ZXRkc2pkdWdzZXV0ZnBtc3QuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMTc4NDc5MTI4NzU5MTM5MDU0OTMiLCJlbWFpbCI6ImFhcm9uLnBhcmVja2lAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF0X2hhc2giOiJpRVljNDBUR0luUkhoVEJidWRncEpRIiwiZXhwIjoxNTI0NTk5MDU2LCJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE1MjQ1OTU0NTZ9.ho2czp_1JWsglJ9jN8gCgWfxDi2gY4X5-QcT56RUGkgh5BJaaWdlrRhhN_eNuJyN3HRPhvVA_KJVy1tMltTVd2OQ6VkxgBNfBsThG_zLPZriw7a1lANblarwxLZID4fXDYG-O8U-gw4xb-NIsOzx6xsxRBdfKKniavuEg56Sd3eKYyqrMA0DWnIagqLiKE6kpZkaGImIpLcIxJPF0-yeJTMt_p1NoJF7uguHHLYr6752hqppnBpMjFL2YMDVeg3jl1y5DeSKNPh6cZ8H2p4Xb2UIrJguGbQHVIJvtm_AspRjrmaTUQKrzXDRCfDROSUU-h7XKIWRrEd2-W9UkV5oCg"
def test_snowflake(make_config, snowflake_key_passphrase_bytes, snowflake_oauth_access_token):
# Authenticator and user/password is fine
config = make_config(
type="snowflake",
account="test",
user="test",
password="test",
authenticator="externalbrowser",
)
assert isinstance(config, SnowflakeConnectionConfig)
# Auth with no user/password is fine
config = make_config(type="snowflake", account="test", authenticator="externalbrowser")
assert isinstance(config, SnowflakeConnectionConfig)
# No auth and no user raises
with pytest.raises(
ConfigError, match="User and password must be provided if using default authentication"
):
make_config(type="snowflake", account="test", password="test")
# No auth and no password raises
with pytest.raises(
ConfigError, match="User and password must be provided if using default authentication"
):
make_config(type="snowflake", account="test", user="test")
# No auth and no user/password raises
with pytest.raises(
ConfigError, match="User and password must be provided if using default authentication"
):
make_config(type="snowflake", account="test")
# Private key and username with no authenticator is fine
config = make_config(
type="snowflake", account="test", private_key=snowflake_key_passphrase_bytes, user="test"
)
assert isinstance(config, SnowflakeConnectionConfig)
# Private key with jwt auth is fine
config = make_config(
type="snowflake",
account="test",
private_key=snowflake_key_passphrase_bytes,
authenticator="snowflake_jwt",
user="test",
)
assert isinstance(config, SnowflakeConnectionConfig)
# Private key without username raises
with pytest.raises(
ConfigError, match=r"User must be provided when using SNOWFLAKE_JWT authentication"
):
make_config(
type="snowflake",
account="test",
private_key=snowflake_key_passphrase_bytes,
authenticator="snowflake_jwt",
)
# Private key with password raises
with pytest.raises(
ConfigError, match=r"Password cannot be provided when using SNOWFLAKE_JWT authentication"
):
make_config(
type="snowflake",
account="test",
private_key=snowflake_key_passphrase_bytes,
user="test",
password="test",
)
# Private key with different authenticator raise
with pytest.raises(
ConfigError,
match=r"Private key or private key path can only be provided when using SNOWFLAKE_JWT authentication",
):
make_config(
type="snowflake",
account="test",
private_key=snowflake_key_passphrase_bytes,
user="test",
authenticator="externalbrowser",
)
# Private key and private key both combined raises
with pytest.raises(
ConfigError, match=r"Cannot specify both `private_key` and `private_key_path`"
):
make_config(
type="snowflake",
account="test",
private_key=snowflake_key_passphrase_bytes,
private_key_path="test",
user="test",
authenticator="snowflake_jwt",
)
config = make_config(
type="snowflake",
account="test",
user="test",
password="test",
authenticator="externalbrowser",
database="test_catalog",
)
assert isinstance(config, SnowflakeConnectionConfig)
assert config.get_catalog() == "test_catalog"
with pytest.raises(ConfigError, match=r"Token must be provided if using oauth authentication"):
make_config(
type="snowflake",
account="test",
user="test",
authenticator="oauth",
)
# Can pass in session parameters
config = make_config(
type="snowflake",
account="test",
user="test",
password="test",
authenticator="externalbrowser",
session_parameters={"query_tag": "test", "timezone": "UTC"},
)
assert isinstance(config, SnowflakeConnectionConfig)
@pytest.mark.parametrize(
"key_path_fixture, key_pem_fixture, key_b64_fixture, key_bytes_fixture, key_passphrase",
[
(
"snowflake_key_no_passphrase_path",
"snowflake_key_no_passphrase_pem",
"snowflake_key_no_passphrase_b64",
"snowflake_key_no_passphrase_bytes",
None,
),
(
"snowflake_key_passphrase_path",
"snowflake_key_passphrase_pem",
"snowflake_key_passphrase_b64",
"snowflake_key_passphrase_bytes",
"insecure",
),
],
)
def test_snowflake_private_key_pass(
make_config,
key_path_fixture,
key_pem_fixture,
key_b64_fixture,
key_bytes_fixture,
key_passphrase,
request: FixtureRequest,
):
key_path = request.getfixturevalue(key_path_fixture)
key_pem = request.getfixturevalue(key_pem_fixture)
key_b64 = request.getfixturevalue(key_b64_fixture)
key_bytes = request.getfixturevalue(key_bytes_fixture)
common_kwargs = dict(
type="snowflake",
account="test",
user="test",
authenticator="snowflake_jwt",
database="test_catalog",
)
config = make_config(
private_key_path=key_path,
private_key_passphrase=key_passphrase,
**common_kwargs,
)
assert config.private_key == key_bytes
config = make_config(
private_key=key_pem,
private_key_passphrase=key_passphrase,
**common_kwargs,
)
assert config.private_key == key_bytes
config = make_config(
private_key=key_b64,
**common_kwargs,
)
assert config.private_key == key_bytes
config = make_config(
private_key=key_bytes,
**common_kwargs,
)
assert config.private_key == key_bytes
def test_validator():
assert _connection_config_validator(None, None) is None
snowflake_config = SnowflakeConnectionConfig(account="test", authenticator="externalbrowser")
assert _connection_config_validator(None, snowflake_config) == snowflake_config
assert (
_connection_config_validator(
None, dict(type="snowflake", account="test", authenticator="externalbrowser")
)
== snowflake_config
)
with pytest.raises(ConfigError, match="Missing connection type."):
_connection_config_validator(None, dict(account="test", authenticator="externalbrowser"))
with pytest.raises(ConfigError, match="Unknown connection type 'invalid'."):
_connection_config_validator(
None, dict(type="invalid", account="test", authenticator="externalbrowser")
)
def test_trino(make_config):
required_kwargs = dict(
type="trino",
user="user",
host="host",
catalog="catalog",
)
# Validate default behavior
config = make_config(**required_kwargs)
assert config.method == TrinoAuthenticationMethod.NO_AUTH
assert config.user == "user"
assert config.host == "host"
assert config.catalog == "catalog"
assert config.http_scheme == "https"
assert config.port == 443
assert config.get_catalog() == "catalog"
assert config.is_recommended_for_state_sync is False
# Validate Basic Auth
config = make_config(method="basic", password="password", **required_kwargs)
assert config.method == TrinoAuthenticationMethod.BASIC
assert config.user == "user"
assert config.password == "password"
assert config.host == "host"
assert config.catalog == "catalog"
with pytest.raises(
ConfigError, match="Username and Password must be provided if using basic authentication"
):
make_config(method="basic", **required_kwargs)
# Validate LDAP
config = make_config(method="ldap", password="password", **required_kwargs)
assert config.method == TrinoAuthenticationMethod.LDAP
with pytest.raises(
ConfigError, match="Username and Password must be provided if using ldap authentication"
):
make_config(method="ldap", **required_kwargs)
# Validate Kerberos
config = make_config(
method="kerberos",
keytab="path/to/keytab.keytab",
krb5_config="krb5.conf",
principal="user@company.com",
**required_kwargs,
)
assert config.method == TrinoAuthenticationMethod.KERBEROS
with pytest.raises(
ConfigError,
match="Kerberos requires the following fields: principal, keytab, and krb5_config",
):
make_config(method="kerberos", **required_kwargs)
# Validate JWT
config = make_config(method="jwt", jwt_token="blah", **required_kwargs)
assert config.method == TrinoAuthenticationMethod.JWT
with pytest.raises(ConfigError, match="JWT requires `jwt_token` to be set"):
make_config(method="jwt", **required_kwargs)
# Validate Certificate
config = make_config(
method="certificate",
cert="blah",
client_certificate="/tmp/client.crt",
client_private_key="/tmp/client.key",
**required_kwargs,
)
assert config.method == TrinoAuthenticationMethod.CERTIFICATE
with pytest.raises(
ConfigError,
match="Certificate requires the following fields: cert, client_certificate, and client_private_key",
):
make_config(method="certificate", **required_kwargs)
# Validate OAuth
config = make_config(method="oauth", **required_kwargs)
assert config.method == TrinoAuthenticationMethod.OAUTH
# Validate Port Behavior
config = make_config(http_scheme="http", **required_kwargs)
assert config.port == 80
config = make_config(http_scheme="https", **required_kwargs)
assert config.port == 443
# Validate http is only for basic and no auth
config = make_config(method="basic", password="password", http_scheme="http", **required_kwargs)
assert config.method == TrinoAuthenticationMethod.BASIC
assert config.http_scheme == "http"
with pytest.raises(
ConfigError, match="HTTP scheme can only be used with no-auth or basic method"
):
make_config(method="ldap", http_scheme="http", **required_kwargs)
def test_trino_schema_location_mapping(make_config):
required_kwargs = dict(
type="trino",
user="user",
host="host",
catalog="catalog",
)
with pytest.raises(
ConfigError, match=r".*needs to include the '@\{schema_name\}' placeholder.*"
):
make_config(**required_kwargs, schema_location_mapping={".*": "s3://foo"})
config = make_config(
**required_kwargs,
schema_location_mapping={
"^utils$": "s3://utils-bucket/@{schema_name}",
"^staging.*$": "s3://bucket/@{schema_name}_dev",
"^sqlmesh.*$": "s3://sqlmesh-internal/dev/@{schema_name}",
},
)
assert config.schema_location_mapping is not None
assert len(config.schema_location_mapping) == 3
assert all((isinstance(k, re.Pattern) for k in config.schema_location_mapping))
assert all((isinstance(v, str) for v in config.schema_location_mapping.values()))
def test_trino_catalog_type_override(make_config):
required_kwargs = dict(
type="trino",
user="user",
host="host",
catalog="catalog",
)
config = make_config(
**required_kwargs,
catalog_type_overrides={"my_catalog": "iceberg"},
)
assert config.catalog_type_overrides is not None
assert len(config.catalog_type_overrides) == 1
assert config.catalog_type_overrides == {"my_catalog": "iceberg"}
def test_trino_timestamp_mapping(make_config):
required_kwargs = dict(
type="trino",
user="user",
host="host",
catalog="catalog",
)
# Test config without timestamp_mapping
config = make_config(**required_kwargs)
assert config.timestamp_mapping is None
# Test config with timestamp_mapping
config = make_config(
**required_kwargs,
timestamp_mapping={
"TIMESTAMP": "TIMESTAMP(6)",
"TIMESTAMP(3)": "TIMESTAMP WITH TIME ZONE",
},
)
assert config.timestamp_mapping is not None
assert config.timestamp_mapping[exp.DataType.build("TIMESTAMP")] == exp.DataType.build(
"TIMESTAMP(6)"
)
# Test with invalid source type
with pytest.raises(ConfigError) as exc_info:
make_config(
**required_kwargs,
timestamp_mapping={
"INVALID_TYPE": "TIMESTAMP",
},
)
assert "Invalid SQL type string" in str(exc_info.value)
assert "INVALID_TYPE" in str(exc_info.value)
# Test with invalid target type (not a valid SQL type)
with pytest.raises(ConfigError) as exc_info:
make_config(
**required_kwargs,
timestamp_mapping={
"TIMESTAMP": "INVALID_TARGET_TYPE",
},
)
assert "Invalid SQL type string" in str(exc_info.value)
assert "INVALID_TARGET_TYPE" in str(exc_info.value)
# Test with empty mapping
config = make_config(
**required_kwargs,
timestamp_mapping={},
)
assert config.timestamp_mapping is not None
assert config.timestamp_mapping == {}
def test_duckdb(make_config):
config = make_config(
type="duckdb",
database="test",
connector_config={"foo": "bar"},
secrets=[
{
"type": "s3",
"region": "aws_region",
"key_id": "aws_access_key",
"secret": "aws_secret",
}
],
filesystems=[
{
"protocol": "abfs",
"storage_options": {
"account_name": "onelake",
"account_host": "onelake.blob.fabric.microsoft.com",
"anon": False,
},
}
],
)
assert config.connector_config
assert config.secrets
assert config.filesystems
assert isinstance(config, DuckDBConnectionConfig)
assert not config.is_recommended_for_state_sync
@patch("duckdb.connect")
def test_duckdb_multiple_secrets(mock_connect, make_config):
"""Test that multiple secrets are correctly converted to CREATE SECRET SQL statements."""
mock_cursor = MagicMock()
mock_connection = MagicMock()
mock_connection.cursor.return_value = mock_cursor
mock_connection.execute = mock_cursor.execute
mock_connect.return_value = mock_connection
# Create config with 2 secrets
config = make_config(
type="duckdb",
secrets=[
{
"type": "s3",
"region": "us-east-1",
"key_id": "my_aws_key",
"secret": "my_aws_secret",
},
{
"type": "azure",
"account_name": "myaccount",
"account_key": "myaccountkey",
},
],
)
assert isinstance(config, DuckDBConnectionConfig)
assert len(config.secrets) == 2
# Create cursor which triggers _cursor_init
cursor = config.create_engine_adapter().cursor
execute_calls = [call[0][0] for call in mock_cursor.execute.call_args_list]
create_secret_calls = [
call for call in execute_calls if call.startswith("CREATE OR REPLACE SECRET")
]
# Should have exactly 2 CREATE SECRET calls
assert len(create_secret_calls) == 2
# Verify the SQL for the first secret (S3)
assert (
create_secret_calls[0]
== "CREATE OR REPLACE SECRET (type 's3', region 'us-east-1', key_id 'my_aws_key', secret 'my_aws_secret');"
)
# Verify the SQL for the second secret (Azure)
assert (
create_secret_calls[1]
== "CREATE OR REPLACE SECRET (type 'azure', account_name 'myaccount', account_key 'myaccountkey');"
)
@patch("duckdb.connect")
def test_duckdb_named_secrets(mock_connect, make_config):
"""Test that named secrets are correctly converted to CREATE SECRET SQL statements."""
mock_cursor = MagicMock()
mock_connection = MagicMock()
mock_connection.cursor.return_value = mock_cursor
mock_connection.execute = mock_cursor.execute
mock_connect.return_value = mock_connection
# Create config with named secrets using dictionary format
config = make_config(
type="duckdb",
secrets={
"my_s3_secret": {
"type": "s3",
"region": "us-east-1",
"key_id": "my_aws_key",
"secret": "my_aws_secret",
},
"my_azure_secret": {
"type": "azure",
"account_name": "myaccount",
"account_key": "myaccountkey",
},
},
)
assert isinstance(config, DuckDBConnectionConfig)
assert len(config.secrets) == 2
# Create cursor which triggers _cursor_init
cursor = config.create_engine_adapter().cursor
execute_calls = [call[0][0] for call in mock_cursor.execute.call_args_list]
create_secret_calls = [
call for call in execute_calls if call.startswith("CREATE OR REPLACE SECRET")
]
# Should have exactly 2 CREATE SECRET calls
assert len(create_secret_calls) == 2
# Verify the SQL for the first secret (S3) includes the secret name
assert (
create_secret_calls[0]
== "CREATE OR REPLACE SECRET my_s3_secret (type 's3', region 'us-east-1', key_id 'my_aws_key', secret 'my_aws_secret');"
)
# Verify the SQL for the second secret (Azure) includes the secret name
assert (
create_secret_calls[1]
== "CREATE OR REPLACE SECRET my_azure_secret (type 'azure', account_name 'myaccount', account_key 'myaccountkey');"
)
@pytest.mark.parametrize(
"kwargs1, kwargs2, shared_adapter",
[
(
{
"database": "test.duckdb",
},
{
"database": "test.duckdb",
},
True,
),
(
{},
{},
False,
),
(
{
"database": "test1.duckdb",
},
{
"database": "test2.duckdb",
},
False,
),
(
{
"database": ":memory:",
},
{
"database": ":memory:",
},
False,
),
(
{
"database": ":memory:",
},
{
"database": "test.duckdb",
},
False,
),
(
{
"catalogs": {
"test": "test.duckdb",
}
},
{
"catalogs": {
"test": "test.duckdb",
}
},
True,
),
(
{
"catalogs": {
"test": ":memory:",
}
},
{
"catalogs": {
"test": ":memory:",
}
},
False,
),
(
{
"catalogs": {
"test1": ":memory:",
"test2": "test2.duckdb",
}
},
{
"catalogs": {
"test1": ":memory:",
"test2": "test2.duckdb",
}
},
True,
),
(
{
"catalogs": {
"test1": ":memory:",
"test2": "test2.duckdb",
}
},
{
"catalogs": {
"test1": "test2.duckdb",
"test2": ":memory:",
}
},
True,
),
(
{
"catalogs": {
"test1": "test1.duckdb",
"test2": "test2.duckdb",
"test3": "test3.duckdb",
}
},
{
"catalogs": {
"test1": "test1_miss.duckdb",
"test2": "test2_miss.duckdb",
"test3": "test3.duckdb",
}
},
True,
),
],
)
def test_duckdb_shared(make_config, caplog, kwargs1, kwargs2, shared_adapter):
config1 = make_config(
type="duckdb",
**kwargs1,
)
config2 = make_config(
type="duckdb",
**kwargs2,
)
assert isinstance(config1, DuckDBConnectionConfig)
assert isinstance(config2, DuckDBConnectionConfig)
adapter1 = config1.create_engine_adapter()
adapter2 = config2.create_engine_adapter()
if shared_adapter:
assert id(adapter1) == id(adapter2)
assert "Creating new DuckDB adapter" in caplog.messages[0]
assert "Using existing DuckDB adapter" in caplog.messages[1]
else:
assert id(adapter1) != id(adapter2)
assert "Creating new DuckDB adapter" in caplog.messages[0]
assert "Creating new DuckDB adapter" in caplog.messages[1]
def test_duckdb_attach_catalog(make_config):
config = make_config(
type="duckdb",
catalogs={
"test1": "test1.duckdb",
"test2": DuckDBAttachOptions(
type="duckdb",
path="test2.duckdb",
),
},
)
assert isinstance(config, DuckDBConnectionConfig)
assert config.get_catalog() == "test1"
assert config.catalogs.get("test2").read_only is False
assert config.catalogs.get("test2").path == "test2.duckdb"
assert not config.is_recommended_for_state_sync
def test_duckdb_attach_ducklake_catalog(make_config):
config = make_config(
type="duckdb",
catalogs={
"ducklake": DuckDBAttachOptions(
type="ducklake",
path="catalog.ducklake",
data_path="/tmp/ducklake_data",
encrypted=True,
data_inlining_row_limit=10,
),
},
)
assert isinstance(config, DuckDBConnectionConfig)
ducklake_catalog = config.catalogs.get("ducklake")
assert ducklake_catalog is not None
assert ducklake_catalog.type == "ducklake"
assert ducklake_catalog.path == "catalog.ducklake"
assert ducklake_catalog.data_path == "/tmp/ducklake_data"
assert ducklake_catalog.encrypted is True
assert ducklake_catalog.data_inlining_row_limit == 10
# Check that the generated SQL includes DATA_PATH
generated_sql = ducklake_catalog.to_sql("ducklake")
assert "DATA_PATH '/tmp/ducklake_data'" in generated_sql
assert "ENCRYPTED" in generated_sql
assert "DATA_INLINING_ROW_LIMIT 10" in generated_sql
# Check that the ducklake: prefix is automatically added
assert "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake'" in generated_sql
# Test that a path with existing ducklake: prefix is preserved
config_with_prefix = make_config(
type="duckdb",
catalogs={
"ducklake": DuckDBAttachOptions(
type="ducklake",
path="ducklake:catalog.ducklake",
data_path="/tmp/ducklake_data",
),
},
)
ducklake_catalog_with_prefix = config_with_prefix.catalogs.get("ducklake")
generated_sql_with_prefix = ducklake_catalog_with_prefix.to_sql("ducklake")
assert "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake'" in generated_sql_with_prefix
# Ensure we don't have double prefixes
assert "'ducklake:catalog.ducklake" in generated_sql_with_prefix
def test_duckdb_attach_options():
options = DuckDBAttachOptions(
type="postgres", path="dbname=postgres user=postgres host=127.0.0.1", read_only=True
)
assert (
options.to_sql(alias="db")
== "ATTACH IF NOT EXISTS 'dbname=postgres user=postgres host=127.0.0.1' AS db (TYPE POSTGRES, READ_ONLY)"
)
options = DuckDBAttachOptions(type="duckdb", path="test.db", read_only=False)
assert options.to_sql(alias="db") == "ATTACH IF NOT EXISTS 'test.db' AS db"
def test_ducklake_attach_add_ducklake_prefix():
# Test that ducklake: prefix is automatically added when missing
options = DuckDBAttachOptions(type="ducklake", path="catalog.ducklake")
assert (
options.to_sql(alias="my_ducklake")
== "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake' AS my_ducklake"
)
# Test that ducklake: prefix is preserved when already present
options = DuckDBAttachOptions(type="ducklake", path="ducklake:catalog.ducklake")
assert (
options.to_sql(alias="my_ducklake")
== "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake' AS my_ducklake"
)
def test_ducklake_metadata_schema():
# Test that metadata_schema parameter is included when specified
options = DuckDBAttachOptions(
type="ducklake", path="catalog.ducklake", metadata_schema="custom_schema"
)
assert (
options.to_sql(alias="my_ducklake")
== "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake' AS my_ducklake (METADATA_SCHEMA 'custom_schema')"
)
# Test that metadata_schema is not included when not specified (default behavior)
options = DuckDBAttachOptions(type="ducklake", path="catalog.ducklake")
assert (
options.to_sql(alias="my_ducklake")
== "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake' AS my_ducklake"
)
# Test metadata_schema with other ducklake options
options = DuckDBAttachOptions(
type="ducklake",
path="catalog.ducklake",
data_path="/path/to/data",
encrypted=True,
metadata_schema="workspace_schema",
)
assert (
options.to_sql(alias="my_ducklake")
== "ATTACH IF NOT EXISTS 'ducklake:catalog.ducklake' AS my_ducklake (DATA_PATH '/path/to/data', ENCRYPTED, METADATA_SCHEMA 'workspace_schema')"
)
def test_duckdb_config_json_strings(make_config):
config = make_config(
type="duckdb",
extensions='["foo","bar"]',
catalogs="""{
"test1": "test1.duckdb",
"test2": {
"type": "duckdb",
"path": "test2.duckdb"
}
}""",
)
assert isinstance(config, DuckDBConnectionConfig)
assert config.extensions == ["foo", "bar"]
assert config.get_catalog() == "test1"
assert config.catalogs.get("test1") == "test1.duckdb"
assert config.catalogs.get("test2").path == "test2.duckdb"
def test_motherduck_attach_catalog(make_config):
config = make_config(
type="motherduck",
catalogs={
"test1": "md:test1",
"test2": DuckDBAttachOptions(
type="motherduck",
path="md:test2",
),
},
)
assert isinstance(config, MotherDuckConnectionConfig)
assert config.get_catalog() == "test1"
assert config.catalogs.get("test2").read_only is False
assert config.catalogs.get("test2").path == "md:test2"
assert not config.is_recommended_for_state_sync
def test_motherduck_attach_options():
options = DuckDBAttachOptions(
type="postgres", path="dbname=postgres user=postgres host=127.0.0.1", read_only=True
)
assert (
options.to_sql(alias="db")
== "ATTACH IF NOT EXISTS 'dbname=postgres user=postgres host=127.0.0.1' AS db (TYPE POSTGRES, READ_ONLY)"
)
options = DuckDBAttachOptions(type="motherduck", path="md:test.db", read_only=False)
# Here the alias should be ignored compared to duckdb
assert options.to_sql(alias="db") == "ATTACH IF NOT EXISTS 'md:test.db'"
def test_duckdb_multithreaded_connection_factory(make_config):
from sqlmesh.core.engine_adapter import DuckDBEngineAdapter
from sqlmesh.utils.connection_pool import ThreadLocalSharedConnectionPool
from threading import Thread
config = make_config(type="duckdb")
# defaults to 1, no issue
assert config.concurrent_tasks == 1
# check that the connection factory always returns the same connection in multithreaded mode
# this sounds counter-intuitive but that's what DuckDB recommends here: https://duckdb.org/docs/guides/python/multiple_threads.html
config = make_config(type="duckdb", concurrent_tasks=8)
adapter = config.create_engine_adapter()
assert isinstance(adapter, DuckDBEngineAdapter)
assert isinstance(adapter._connection_pool, ThreadLocalSharedConnectionPool)
threads = []
connection_objects = []
def _thread_connection():
connection_objects.append(adapter.connection)
for _ in range(8):
threads.append(Thread(target=_thread_connection))
for thread in threads:
thread.start()
for thread in threads:
thread.join()