-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathconnection.py
More file actions
2410 lines (2011 loc) · 90.3 KB
/
connection.py
File metadata and controls
2410 lines (2011 loc) · 90.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import abc
import base64
import logging
import os
import importlib
import pathlib
import re
import typing as t
from enum import Enum
from functools import partial
import pydantic
from pydantic import Field
from pydantic_core import from_json
from packaging import version
from sqlglot import exp
from sqlglot.helper import subclasses
from sqlglot.errors import ParseError
from sqlmesh.core import engine_adapter
from sqlmesh.core.config.base import BaseConfig
from sqlmesh.core.config.common import (
concurrent_tasks_validator,
http_headers_validator,
compile_regex_mapping,
)
from sqlmesh.core.engine_adapter.shared import CatalogSupport
from sqlmesh.core.engine_adapter import EngineAdapter
from sqlmesh.utils import debug_mode_enabled, str_to_bool
from sqlmesh.utils.errors import ConfigError
from sqlmesh.utils.pydantic import (
ValidationInfo,
field_validator,
model_validator,
validation_error_message,
get_concrete_types_from_typehint,
)
from sqlmesh.utils.aws import validate_s3_uri
if t.TYPE_CHECKING:
from sqlmesh.core._typing import Self
logger = logging.getLogger(__name__)
RECOMMENDED_STATE_SYNC_ENGINES = {
"postgres",
"gcp_postgres",
"mysql",
"mssql",
"azuresql",
}
FORBIDDEN_STATE_SYNC_ENGINES = {
# Do not support row-level operations
"spark",
"trino",
# Nullable types are problematic
"clickhouse",
}
MOTHERDUCK_TOKEN_REGEX = re.compile(r"(\?|\&)(motherduck_token=)(\S*)")
PASSWORD_REGEX = re.compile(r"(password=)(\S+)")
def _get_engine_import_validator(
import_name: str, engine_type: str, extra_name: t.Optional[str] = None, decorate: bool = True
) -> t.Callable:
extra_name = extra_name or engine_type
def validate(cls: t.Any, data: t.Any) -> t.Any:
check_import = (
str_to_bool(str(data.pop("check_import", True))) if isinstance(data, dict) else True
)
if not check_import:
return data
try:
importlib.import_module(import_name)
except ImportError:
if debug_mode_enabled():
raise
logger.exception("Failed to import the engine library")
raise ConfigError(
f"Failed to import the '{engine_type}' engine library. This may be due to a missing "
"or incompatible installation. Please ensure the required dependency is installed by "
f'running: `pip install "sqlmesh[{extra_name}]"`. For more details, check the logs '
"in the 'logs/' folder, or rerun the command with the '--debug' flag."
)
return data
return model_validator(mode="before")(validate) if decorate else validate
class ConnectionConfig(abc.ABC, BaseConfig):
type_: str
DIALECT: t.ClassVar[str]
DISPLAY_NAME: t.ClassVar[str]
DISPLAY_ORDER: t.ClassVar[int]
concurrent_tasks: int
register_comments: bool
pre_ping: bool
pretty_sql: bool = False
schema_differ_overrides: t.Optional[t.Dict[str, t.Any]] = None
catalog_type_overrides: t.Optional[t.Dict[str, str]] = None
# Whether to share a single connection across threads or create a new connection per thread.
shared_connection: t.ClassVar[bool] = False
@property
@abc.abstractmethod
def _connection_kwargs_keys(self) -> t.Set[str]:
"""keywords that should be passed into the connection"""
@property
@abc.abstractmethod
def _engine_adapter(self) -> t.Type[EngineAdapter]:
"""The engine adapter for this connection"""
@property
@abc.abstractmethod
def _connection_factory(self) -> t.Callable:
"""A function that is called to return a connection object for the given Engine Adapter"""
@property
def _static_connection_kwargs(self) -> t.Dict[str, t.Any]:
"""The static connection kwargs for this connection"""
return {}
@property
def _extra_engine_config(self) -> t.Dict[str, t.Any]:
"""kwargs that are for execution config only"""
return {}
@property
def _cursor_init(self) -> t.Optional[t.Callable[[t.Any], None]]:
"""A function that is called to initialize the cursor"""
return None
@property
def is_recommended_for_state_sync(self) -> bool:
"""Whether this engine is recommended for being used as a state sync for production state syncs"""
return self.type_ in RECOMMENDED_STATE_SYNC_ENGINES
@property
def is_forbidden_for_state_sync(self) -> bool:
"""Whether this engine is forbidden from being used as a state sync"""
return self.type_ in FORBIDDEN_STATE_SYNC_ENGINES
@property
def _connection_factory_with_kwargs(self) -> t.Callable[[], t.Any]:
"""A function that is called to return a connection object for the given Engine Adapter"""
return partial(
self._connection_factory,
**{
**self._static_connection_kwargs,
**{k: v for k, v in self.dict().items() if k in self._connection_kwargs_keys},
},
)
def connection_validator(self) -> t.Callable[[], None]:
"""A function that validates the connection configuration"""
return self.create_engine_adapter().ping
def create_engine_adapter(
self, register_comments_override: bool = False, concurrent_tasks: t.Optional[int] = None
) -> EngineAdapter:
"""Returns a new instance of the Engine Adapter."""
concurrent_tasks = concurrent_tasks or self.concurrent_tasks
return self._engine_adapter(
self._connection_factory_with_kwargs,
multithreaded=concurrent_tasks > 1,
default_catalog=self.get_catalog(),
cursor_init=self._cursor_init,
register_comments=register_comments_override or self.register_comments,
pre_ping=self.pre_ping,
pretty_sql=self.pretty_sql,
shared_connection=self.shared_connection,
schema_differ_overrides=self.schema_differ_overrides,
catalog_type_overrides=self.catalog_type_overrides,
**self._extra_engine_config,
)
def get_catalog(self) -> t.Optional[str]:
"""The catalog for this connection"""
if hasattr(self, "catalog"):
return self.catalog
if hasattr(self, "database"):
return self.database
if hasattr(self, "db"):
return self.db
return None
@model_validator(mode="before")
@classmethod
def _expand_json_strings_to_concrete_types(cls, data: t.Any) -> t.Any:
"""
There are situations where a connection config class has a field that is some kind of complex type
(eg a list of strings or a dict) but the value is being supplied from a source such as an environment variable
When this happens, the value is supplied as a string rather than a Python object. We need some way
of turning this string into the corresponding Python list or dict.
Rather than doing this piecemeal on every config subclass, this provides a generic implementatation
to identify fields that may be be supplied as JSON strings and handle them transparently
"""
if data and isinstance(data, dict):
for maybe_json_field_name in cls._get_list_and_dict_field_names():
if (value := data.get(maybe_json_field_name)) and isinstance(value, str):
# crude JSON check as we dont want to try and parse every string we get
value = value.strip()
if value.startswith("{") or value.startswith("["):
data[maybe_json_field_name] = from_json(value)
return data
@classmethod
def _get_list_and_dict_field_names(cls) -> t.Set[str]:
field_names = set()
for name, field in cls.model_fields.items():
if field.annotation:
field_types = get_concrete_types_from_typehint(field.annotation)
# check if the field type is something that could concievably be supplied as a json string
if any(ft is t for t in (list, tuple, set, dict) for ft in field_types):
field_names.add(name)
return field_names
class DuckDBAttachOptions(BaseConfig):
type: str
path: str
read_only: bool = False
# DuckLake specific options
data_path: t.Optional[str] = None
encrypted: bool = False
data_inlining_row_limit: t.Optional[int] = None
metadata_schema: t.Optional[str] = None
def to_sql(self, alias: str) -> str:
options = []
# 'duckdb' is actually not a supported type, but we'd like to allow it for
# fully qualified attach options or integration testing, similar to duckdb-dbt
if self.type not in ("duckdb", "ducklake", "motherduck"):
options.append(f"TYPE {self.type.upper()}")
if self.read_only:
options.append("READ_ONLY")
# DuckLake specific options
path = self.path
if self.type == "ducklake":
if not path.startswith("ducklake:"):
path = f"ducklake:{path}"
if self.data_path is not None:
options.append(f"DATA_PATH '{self.data_path}'")
if self.encrypted:
options.append("ENCRYPTED")
if self.data_inlining_row_limit is not None:
options.append(f"DATA_INLINING_ROW_LIMIT {self.data_inlining_row_limit}")
if self.metadata_schema is not None:
options.append(f"METADATA_SCHEMA '{self.metadata_schema}'")
options_sql = f" ({', '.join(options)})" if options else ""
alias_sql = ""
# TODO: Add support for Postgres schema. Currently adding it blocks access to the information_schema
# MotherDuck does not support aliasing
alias_sql = (
f" AS {alias}" if not (self.type == "motherduck" or self.path.startswith("md:")) else ""
)
return f"ATTACH IF NOT EXISTS '{path}'{alias_sql}{options_sql}"
class BaseDuckDBConnectionConfig(ConnectionConfig):
"""Common configuration for the DuckDB-based connections.
Args:
database: The optional database name. If not specified, the in-memory database will be used.
catalogs: Key is the name of the catalog and value is the path.
extensions: A list of autoloadable extensions to load.
connector_config: A dictionary of configuration to pass into the duckdb connector.
secrets: A list of dictionaries used to generate DuckDB secrets for authenticating with external services (e.g. S3).
filesystems: A list of dictionaries used to register `fsspec` filesystems to the DuckDB cursor.
concurrent_tasks: The maximum number of tasks that can use this connection concurrently.
register_comments: Whether or not to register model comments with the SQL engine.
pre_ping: Whether or not to pre-ping the connection before starting a new transaction to ensure it is still alive.
token: The optional MotherDuck token. If not specified and a MotherDuck path is in the catalog, the user will be prompted to login with their web browser.
"""
database: t.Optional[str] = None
catalogs: t.Optional[t.Dict[str, t.Union[str, DuckDBAttachOptions]]] = None
extensions: t.List[t.Union[str, t.Dict[str, t.Any]]] = []
connector_config: t.Dict[str, t.Any] = {}
secrets: t.Union[t.List[t.Dict[str, t.Any]], t.Dict[str, t.Dict[str, t.Any]]] = []
filesystems: t.List[t.Dict[str, t.Any]] = []
concurrent_tasks: int = 1
register_comments: bool = True
pre_ping: t.Literal[False] = False
token: t.Optional[str] = None
shared_connection: t.ClassVar[bool] = True
_data_file_to_adapter: t.ClassVar[t.Dict[str, EngineAdapter]] = {}
@model_validator(mode="before")
def _validate_database_catalogs(cls, data: t.Any) -> t.Any:
if not isinstance(data, dict):
return data
db_path = data.get("database")
if db_path and data.get("catalogs"):
raise ConfigError(
"Cannot specify both `database` and `catalogs`. Define all your catalogs in `catalogs` and have the first entry be the default catalog"
)
if isinstance(db_path, str) and db_path.startswith("md:"):
raise ConfigError(
"Please use connection type 'motherduck' without the `md:` prefix if you want to use a MotherDuck database as the single `database`."
)
return data
@property
def _engine_adapter(self) -> t.Type[EngineAdapter]:
return engine_adapter.DuckDBEngineAdapter
@property
def _connection_kwargs_keys(self) -> t.Set[str]:
return {"database"}
@property
def _connection_factory(self) -> t.Callable:
import duckdb
return duckdb.connect
@property
def _cursor_init(self) -> t.Optional[t.Callable[[t.Any], None]]:
"""A function that is called to initialize the cursor"""
import duckdb
from duckdb import BinderException
def init(cursor: duckdb.DuckDBPyConnection) -> None:
for extension in self.extensions:
extension = extension if isinstance(extension, dict) else {"name": extension}
install_command = f"INSTALL {extension['name']}"
if extension.get("repository"):
install_command = f"{install_command} FROM {extension['repository']}"
if extension.get("force_install"):
install_command = f"FORCE {install_command}"
try:
cursor.execute(install_command)
cursor.execute(f"LOAD {extension['name']}")
except Exception as e:
raise ConfigError(f"Failed to load extension {extension['name']}: {e}")
if self.connector_config:
option_names = list(self.connector_config)
in_part = ",".join("?" for _ in range(len(option_names)))
cursor.execute(
f"SELECT name, value FROM duckdb_settings() WHERE name IN ({in_part})",
option_names,
)
existing_values = {field: setting for field, setting in cursor.fetchall()}
# only set connector_config items if the values differ from what is already set
# trying to set options like 'temp_directory' even to the same value can throw errors like:
# Not implemented Error: Cannot switch temporary directory after the current one has been used
for field, setting in self.connector_config.items():
if existing_values.get(field) != setting:
try:
cursor.execute(f"SET {field} = '{setting}'")
except Exception as e:
raise ConfigError(
f"Failed to set connector config {field} to {setting}: {e}"
)
if self.secrets:
duckdb_version = duckdb.__version__
if version.parse(duckdb_version) < version.parse("0.10.0"):
from sqlmesh.core.console import get_console
get_console().log_warning(
f"DuckDB version {duckdb_version} does not support secrets-based authentication (requires 0.10.0 or later).\n"
"To use secrets, please upgrade DuckDB. For older versions, configure legacy authentication via `connector_config`.\n"
"More info: https://duckdb.org/docs/stable/extensions/httpfs/s3api_legacy_authentication.html"
)
else:
if isinstance(self.secrets, list):
secrets_items = [(secret_dict, "") for secret_dict in self.secrets]
else:
secrets_items = [
(secret_dict, secret_name)
for secret_name, secret_dict in self.secrets.items()
]
for secret_dict, secret_name in secrets_items:
secret_settings: t.List[str] = []
for field, setting in secret_dict.items():
secret_settings.append(f"{field} '{setting}'")
if secret_settings:
secret_clause = ", ".join(secret_settings)
try:
cursor.execute(
f"CREATE OR REPLACE SECRET {secret_name} ({secret_clause});"
)
except Exception as e:
raise ConfigError(f"Failed to create secret: {e}")
if self.filesystems:
from fsspec import filesystem # type: ignore
for file_system in self.filesystems:
options = file_system.copy()
fs = options.pop("fs")
fs = filesystem(fs, **options)
cursor.register_filesystem(fs)
for i, (alias, path_options) in enumerate(
(getattr(self, "catalogs", None) or {}).items()
):
# we parse_identifier and generate to ensure that `alias` has exactly one set of quotes
# regardless of whether it comes in quoted or not
alias = exp.parse_identifier(alias, dialect="duckdb").sql(
identify=True, dialect="duckdb"
)
try:
if isinstance(path_options, DuckDBAttachOptions):
query = path_options.to_sql(alias)
else:
query = f"ATTACH IF NOT EXISTS '{path_options}'"
if not path_options.startswith("md:"):
query += f" AS {alias}"
cursor.execute(query)
except BinderException as e:
# If a user tries to create a catalog pointing at `:memory:` and with the name `memory`
# then we don't want to raise since this happens by default. They are just doing this to
# set it as the default catalog.
# If a user tried to attach a MotherDuck database/share which has already by attached via
# `ATTACH 'md:'`, then we don't want to raise since this is expected.
if (
not (
'database with name "memory" already exists' in str(e)
and path_options == ":memory:"
)
and f"""database with name "{path_options.path.replace("md:", "")}" already exists"""
not in str(e)
):
raise e
if i == 0 and not getattr(self, "database", None):
cursor.execute(f"USE {alias}")
return init
def create_engine_adapter(
self, register_comments_override: bool = False, concurrent_tasks: t.Optional[int] = None
) -> EngineAdapter:
"""Checks if another engine adapter has already been created that shares a catalog that points to the same data
file. If so, it uses that same adapter instead of creating a new one. As a result, any additional configuration
associated with the new adapter will be ignored."""
data_files = set((self.catalogs or {}).values())
if self.database:
if isinstance(self, MotherDuckConnectionConfig):
data_files.add(
f"md:{self.database}"
+ (f"?motherduck_token={self.token}" if self.token else "")
)
else:
data_files.add(self.database)
data_files.discard(":memory:")
for data_file in data_files:
key = data_file if isinstance(data_file, str) else data_file.path
adapter = BaseDuckDBConnectionConfig._data_file_to_adapter.get(key)
if adapter is not None:
logger.info(
f"Using existing DuckDB adapter due to overlapping data file: {self._mask_sensitive_data(key)}"
)
return adapter
if data_files:
masked_files = {
self._mask_sensitive_data(file if isinstance(file, str) else file.path)
for file in data_files
}
logger.info(f"Creating new DuckDB adapter for data files: {masked_files}")
else:
logger.info("Creating new DuckDB adapter for in-memory database")
adapter = super().create_engine_adapter(
register_comments_override, concurrent_tasks=concurrent_tasks
)
for data_file in data_files:
key = data_file if isinstance(data_file, str) else data_file.path
BaseDuckDBConnectionConfig._data_file_to_adapter[key] = adapter
return adapter
def get_catalog(self) -> t.Optional[str]:
if self.database:
# Remove `:` from the database name in order to handle if `:memory:` is passed in
return pathlib.Path(self.database.replace(":memory:", "memory")).stem
if self.catalogs:
return list(self.catalogs)[0]
return None
def _mask_sensitive_data(self, string: str) -> str:
# Mask MotherDuck tokens with fixed number of asterisks
result = MOTHERDUCK_TOKEN_REGEX.sub(
lambda m: f"{m.group(1)}{m.group(2)}{'*' * 8 if m.group(3) else ''}", string
)
# Mask PostgreSQL/MySQL passwords with fixed number of asterisks
result = PASSWORD_REGEX.sub(lambda m: f"{m.group(1)}{'*' * 8}", result)
return result
class MotherDuckConnectionConfig(BaseDuckDBConnectionConfig):
"""Configuration for the MotherDuck connection."""
type_: t.Literal["motherduck"] = Field(alias="type", default="motherduck")
DIALECT: t.ClassVar[t.Literal["duckdb"]] = "duckdb"
DISPLAY_NAME: t.ClassVar[t.Literal["MotherDuck"]] = "MotherDuck"
DISPLAY_ORDER: t.ClassVar[t.Literal[5]] = 5
@property
def _connection_kwargs_keys(self) -> t.Set[str]:
return set()
@property
def _static_connection_kwargs(self) -> t.Dict[str, t.Any]:
"""kwargs that are for execution config only"""
from sqlmesh import __version__
custom_user_agent_config = {"custom_user_agent": f"SQLMesh/{__version__}"}
connection_str = "md:"
if self.database:
# Attach single MD database instead of all databases on the account
connection_str += f"{self.database}?attach_mode=single"
if self.token:
connection_str += f"{'&' if self.database else '?'}motherduck_token={self.token}"
return {"database": connection_str, "config": custom_user_agent_config}
@property
def _extra_engine_config(self) -> t.Dict[str, t.Any]:
return {"is_motherduck": True}
class DuckDBConnectionConfig(BaseDuckDBConnectionConfig):
"""Configuration for the DuckDB connection."""
type_: t.Literal["duckdb"] = Field(alias="type", default="duckdb")
DIALECT: t.ClassVar[t.Literal["duckdb"]] = "duckdb"
DISPLAY_NAME: t.ClassVar[t.Literal["DuckDB"]] = "DuckDB"
DISPLAY_ORDER: t.ClassVar[t.Literal[1]] = 1
class SnowflakeConnectionConfig(ConnectionConfig):
"""Configuration for the Snowflake connection.
Args:
account: The Snowflake account name.
user: The Snowflake username.
password: The Snowflake password.
warehouse: The optional warehouse name.
database: The optional database name.
role: The optional role name.
concurrent_tasks: The maximum number of tasks that can use this connection concurrently.
authenticator: The optional authenticator name. Defaults to username/password authentication ("snowflake").
Options: https://github.com/snowflakedb/snowflake-connector-python/blob/e937591356c067a77f34a0a42328907fda792c23/src/snowflake/connector/network.py#L178-L183
token: The optional oauth access token to use for authentication when authenticator is set to "oauth".
private_key: The optional private key to use for authentication. Key can be Base64-encoded DER format (representing the key bytes), a plain-text PEM format, or bytes (Python config only). https://docs.snowflake.com/en/developer-guide/python-connector/python-connector-connect#using-key-pair-authentication-key-pair-rotation
private_key_path: The optional path to the private key to use for authentication. This would be used instead of `private_key`.
private_key_passphrase: The optional passphrase to use to decrypt `private_key` or `private_key_path`. Keys can be created without encryption so only provide this if needed.
register_comments: Whether or not to register model comments with the SQL engine.
pre_ping: Whether or not to pre-ping the connection before starting a new transaction to ensure it is still alive.
session_parameters: The optional session parameters to set for the connection.
host: Host address for the connection.
port: Port for the connection.
"""
account: str
user: t.Optional[str] = None
password: t.Optional[str] = None
warehouse: t.Optional[str] = None
database: t.Optional[str] = None
role: t.Optional[str] = None
authenticator: t.Optional[str] = None
token: t.Optional[str] = None
host: t.Optional[str] = None
port: t.Optional[int] = None
application: t.Literal["Tobiko_SQLMesh"] = "Tobiko_SQLMesh"
# Private Key Auth
private_key: t.Optional[t.Union[str, bytes]] = None
private_key_path: t.Optional[str] = None
private_key_passphrase: t.Optional[str] = None
concurrent_tasks: int = 4
register_comments: bool = True
pre_ping: bool = False
session_parameters: t.Optional[dict] = None
type_: t.Literal["snowflake"] = Field(alias="type", default="snowflake")
DIALECT: t.ClassVar[t.Literal["snowflake"]] = "snowflake"
DISPLAY_NAME: t.ClassVar[t.Literal["Snowflake"]] = "Snowflake"
DISPLAY_ORDER: t.ClassVar[t.Literal[2]] = 2
_concurrent_tasks_validator = concurrent_tasks_validator
@model_validator(mode="before")
def _validate_authenticator(cls, data: t.Any) -> t.Any:
if not isinstance(data, dict):
return data
from snowflake.connector.network import DEFAULT_AUTHENTICATOR, OAUTH_AUTHENTICATOR
auth = data.get("authenticator")
auth = auth.upper() if auth else DEFAULT_AUTHENTICATOR
user = data.get("user")
password = data.get("password")
data["private_key"] = cls._get_private_key(data, auth) # type: ignore
if (
auth == DEFAULT_AUTHENTICATOR
and not data.get("private_key")
and (not user or not password)
):
raise ConfigError("User and password must be provided if using default authentication")
if auth == OAUTH_AUTHENTICATOR and not data.get("token"):
raise ConfigError("Token must be provided if using oauth authentication")
return data
_engine_import_validator = _get_engine_import_validator(
"snowflake.connector.network", "snowflake"
)
@classmethod
def _get_private_key(cls, values: t.Dict[str, t.Optional[str]], auth: str) -> t.Optional[bytes]:
"""
source: https://github.com/dbt-labs/dbt-snowflake/blob/0374b4ec948982f2ac8ec0c95d53d672ad19e09c/dbt/adapters/snowflake/connections.py#L247C5-L285C1
Overall code change: Use local variables instead of class attributes + Validation
"""
# Start custom code
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from snowflake.connector.network import (
DEFAULT_AUTHENTICATOR,
KEY_PAIR_AUTHENTICATOR,
)
private_key = values.get("private_key")
private_key_path = values.get("private_key_path")
private_key_passphrase = values.get("private_key_passphrase")
user = values.get("user")
password = values.get("password")
auth = auth if auth and auth != DEFAULT_AUTHENTICATOR else KEY_PAIR_AUTHENTICATOR
if not private_key and not private_key_path:
return None
if private_key and private_key_path:
raise ConfigError("Cannot specify both `private_key` and `private_key_path`")
if auth != KEY_PAIR_AUTHENTICATOR:
raise ConfigError(
f"Private key or private key path can only be provided when using {KEY_PAIR_AUTHENTICATOR} authentication"
)
if not user:
raise ConfigError(
f"User must be provided when using {KEY_PAIR_AUTHENTICATOR} authentication"
)
if password:
raise ConfigError(
f"Password cannot be provided when using {KEY_PAIR_AUTHENTICATOR} authentication"
)
if isinstance(private_key, bytes):
return private_key
# End Custom Code
if private_key_passphrase:
encoded_passphrase = private_key_passphrase.encode()
else:
encoded_passphrase = None
if private_key:
if private_key.startswith("-"):
p_key = serialization.load_pem_private_key(
data=bytes(private_key, "utf-8"),
password=encoded_passphrase,
backend=default_backend(),
)
else:
p_key = serialization.load_der_private_key(
data=base64.b64decode(private_key),
password=encoded_passphrase,
backend=default_backend(),
)
elif private_key_path:
with open(private_key_path, "rb") as key:
p_key = serialization.load_pem_private_key(
key.read(), password=encoded_passphrase, backend=default_backend()
)
else:
return None
return p_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
@property
def _connection_kwargs_keys(self) -> t.Set[str]:
return {
"user",
"password",
"account",
"warehouse",
"database",
"role",
"authenticator",
"token",
"private_key",
"session_parameters",
"application",
"host",
"port",
}
@property
def _engine_adapter(self) -> t.Type[EngineAdapter]:
return engine_adapter.SnowflakeEngineAdapter
@property
def _static_connection_kwargs(self) -> t.Dict[str, t.Any]:
return {"autocommit": False}
@property
def _connection_factory(self) -> t.Callable:
from snowflake import connector
return connector.connect
class DatabricksConnectionConfig(ConnectionConfig):
"""
Databricks connection that uses the SQL connector for SQL models and then Databricks Connect for Dataframe operations
Arg Source: https://github.com/databricks/databricks-sql-python/blob/main/src/databricks/sql/client.py#L39
OAuth ref: https://docs.databricks.com/en/dev-tools/python-sql-connector.html#oauth-machine-to-machine-m2m-authentication
Args:
server_hostname: Databricks instance host name.
http_path: Http path either to a DBSQL endpoint (e.g. /sql/1.0/endpoints/1234567890abcdef)
or to a DBR interactive cluster (e.g. /sql/protocolv1/o/1234567890123456/1234-123456-slid123)
access_token: Http Bearer access token, e.g. Databricks Personal Access Token.
auth_type: Set to 'databricks-oauth' or 'azure-oauth' to trigger OAuth (or dont set at all to use `access_token`)
oauth_client_id: Client ID to use when auth_type is set to one of the 'oauth' types
oauth_client_secret: Client Secret to use when auth_type is set to one of the 'oauth' types
catalog: Default catalog to use for SQL models. Defaults to None which means it will use the default set in
the Databricks cluster (most likely `hive_metastore`).
http_headers: An optional list of (k, v) pairs that will be set as Http headers on every request
session_configuration: An optional dictionary of Spark session parameters.
Execute the SQL command `SET -v` to get a full list of available commands.
databricks_connect_server_hostname: The hostname to use when establishing a connecting using Databricks Connect.
Defaults to the `server_hostname` value.
databricks_connect_access_token: The access token to use when establishing a connecting using Databricks Connect.
Defaults to the `access_token` value.
databricks_connect_cluster_id: The cluster id to use when establishing a connecting using Databricks Connect.
Defaults to deriving the cluster id from the `http_path` value.
force_databricks_connect: Force all queries to run using Databricks Connect instead of the SQL connector.
disable_databricks_connect: Even if databricks connect is installed, do not use it.
disable_spark_session: Do not use SparkSession if it is available (like when running in a notebook).
pre_ping: Whether or not to pre-ping the connection before starting a new transaction to ensure it is still alive.
"""
server_hostname: t.Optional[str] = None
http_path: t.Optional[str] = None
access_token: t.Optional[str] = None
auth_type: t.Optional[str] = None
oauth_client_id: t.Optional[str] = None
oauth_client_secret: t.Optional[str] = None
catalog: t.Optional[str] = None
http_headers: t.Optional[t.List[t.Tuple[str, str]]] = None
session_configuration: t.Optional[t.Dict[str, t.Any]] = None
databricks_connect_server_hostname: t.Optional[str] = None
databricks_connect_access_token: t.Optional[str] = None
databricks_connect_cluster_id: t.Optional[str] = None
databricks_connect_use_serverless: bool = False
force_databricks_connect: bool = False
disable_databricks_connect: bool = False
disable_spark_session: bool = False
concurrent_tasks: int = 1
register_comments: bool = True
pre_ping: t.Literal[False] = False
type_: t.Literal["databricks"] = Field(alias="type", default="databricks")
DIALECT: t.ClassVar[t.Literal["databricks"]] = "databricks"
DISPLAY_NAME: t.ClassVar[t.Literal["Databricks"]] = "Databricks"
DISPLAY_ORDER: t.ClassVar[t.Literal[3]] = 3
_concurrent_tasks_validator = concurrent_tasks_validator
_http_headers_validator = http_headers_validator
@model_validator(mode="before")
def _databricks_connect_validator(cls, data: t.Any) -> t.Any:
# SQLQueryContextLogger will output any error SQL queries even if they are in a try/except block.
# Disabling this allows SQLMesh to determine what should be shown to the user.
# Ex: We describe a table to see if it exists and therefore that execution can fail but we don't need to show
# the user since it is expected if the table doesn't exist. Without this change the user would see the error.
logging.getLogger("SQLQueryContextLogger").setLevel(logging.CRITICAL)
if not isinstance(data, dict):
return data
from sqlmesh.core.engine_adapter.databricks import DatabricksEngineAdapter
if DatabricksEngineAdapter.can_access_spark_session(
bool(data.get("disable_spark_session"))
):
return data
databricks_connect_use_serverless = data.get("databricks_connect_use_serverless")
server_hostname, http_path, access_token, auth_type = (
data.get("server_hostname"),
data.get("http_path"),
data.get("access_token"),
data.get("auth_type"),
)
if (not server_hostname or not http_path or not access_token) and (
not databricks_connect_use_serverless and not auth_type
):
raise ValueError(
"`server_hostname`, `http_path`, and `access_token` are required for Databricks connections when not running in a notebook"
)
if (
databricks_connect_use_serverless
and not server_hostname
and not data.get("databricks_connect_server_hostname")
):
raise ValueError(
"`server_hostname` or `databricks_connect_server_hostname` is required when `databricks_connect_use_serverless` is set"
)
if DatabricksEngineAdapter.can_access_databricks_connect(
bool(data.get("disable_databricks_connect"))
):
if not data.get("databricks_connect_access_token"):
data["databricks_connect_access_token"] = access_token
if not data.get("databricks_connect_server_hostname"):
data["databricks_connect_server_hostname"] = f"https://{server_hostname}"
if not databricks_connect_use_serverless and not data.get(
"databricks_connect_cluster_id"
):
if t.TYPE_CHECKING:
assert http_path is not None
data["databricks_connect_cluster_id"] = http_path.split("/")[-1]
if auth_type:
from databricks.sql.auth.auth import AuthType
all_data = [m.value for m in AuthType]
if auth_type not in all_data:
raise ValueError(
f"`auth_type` {auth_type} does not match a valid option: {all_data}"
)
client_id = data.get("oauth_client_id")
client_secret = data.get("oauth_client_secret")
if client_secret and not client_id:
raise ValueError(
"`oauth_client_id` is required when `oauth_client_secret` is specified"
)
if not http_path:
raise ValueError("`http_path` is still required when using `auth_type`")
return data
_engine_import_validator = _get_engine_import_validator("databricks", "databricks")
@property
def _connection_kwargs_keys(self) -> t.Set[str]:
if self.use_spark_session_only:
return set()
return {
"server_hostname",
"http_path",
"access_token",
"http_headers",
"session_configuration",
"catalog",
}
@property
def _engine_adapter(self) -> t.Type[engine_adapter.DatabricksEngineAdapter]:
return engine_adapter.DatabricksEngineAdapter
@property
def _extra_engine_config(self) -> t.Dict[str, t.Any]:
return {
k: v
for k, v in self.dict().items()
if k.startswith("databricks_connect_")
or k in ("catalog", "disable_databricks_connect", "disable_spark_session")
}
@property
def use_spark_session_only(self) -> bool:
from sqlmesh.core.engine_adapter.databricks import DatabricksEngineAdapter
return (
DatabricksEngineAdapter.can_access_spark_session(self.disable_spark_session)
or self.force_databricks_connect
)
@property
def _connection_factory(self) -> t.Callable:
if self.use_spark_session_only:
from sqlmesh.engines.spark.db_api.spark_session import connection
return connection
from databricks import sql # type: ignore
return sql.connect
@property
def _static_connection_kwargs(self) -> t.Dict[str, t.Any]:
from sqlmesh.core.engine_adapter.databricks import DatabricksEngineAdapter
if not self.use_spark_session_only:
conn_kwargs: t.Dict[str, t.Any] = {
"_user_agent_entry": "sqlmesh",
}
if self.auth_type and "oauth" in self.auth_type:
# there are two types of oauth: User-to-Machine (U2M) and Machine-to-Machine (M2M)
if self.oauth_client_secret:
# if a client_secret exists, then a client_id also exists and we are using M2M
# ref: https://docs.databricks.com/en/dev-tools/python-sql-connector.html#oauth-machine-to-machine-m2m-authentication
# ref: https://github.com/databricks/databricks-sql-python/blob/main/examples/m2m_oauth.py
from databricks.sdk.core import oauth_service_principal, Config
config = Config(
host=f"https://{self.server_hostname}",
client_id=self.oauth_client_id,
client_secret=self.oauth_client_secret,
)
conn_kwargs["credentials_provider"] = lambda: oauth_service_principal(config)
else:
# if auth_type is set to an 'oauth' type but no client_id/secret are set, then we are using U2M
# ref: https://docs.databricks.com/en/dev-tools/python-sql-connector.html#oauth-user-to-machine-u2m-authentication
conn_kwargs["auth_type"] = self.auth_type
return conn_kwargs
if DatabricksEngineAdapter.can_access_spark_session(self.disable_spark_session):
from pyspark.sql import SparkSession
return dict(
spark=SparkSession.getActiveSession(),
catalog=self.catalog,
)
from databricks.connect import DatabricksSession
if t.TYPE_CHECKING:
assert self.databricks_connect_server_hostname is not None
assert self.databricks_connect_access_token is not None
if self.databricks_connect_use_serverless:
builder = DatabricksSession.builder.remote(
host=self.databricks_connect_server_hostname,
token=self.databricks_connect_access_token,
serverless=True,
)
else:
if t.TYPE_CHECKING:
assert self.databricks_connect_cluster_id is not None
builder = DatabricksSession.builder.remote(
host=self.databricks_connect_server_hostname,
token=self.databricks_connect_access_token,
cluster_id=self.databricks_connect_cluster_id,
)