-
Notifications
You must be signed in to change notification settings - Fork 537
Expand file tree
/
Copy pathconnection.py
More file actions
2523 lines (2274 loc) · 98.6 KB
/
connection.py
File metadata and controls
2523 lines (2274 loc) · 98.6 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
#!/usr/bin/env python
from __future__ import annotations
import atexit
import logging
import os
import pathlib
import re
import sys
import traceback
import typing
import uuid
import warnings
import weakref
from concurrent.futures import as_completed
from concurrent.futures.thread import ThreadPoolExecutor
from contextlib import suppress
from difflib import get_close_matches
from functools import cached_property, partial
from io import StringIO
from logging import getLogger
from threading import Lock
from types import TracebackType
from typing import (
Any,
Callable,
Generator,
Iterable,
Iterator,
NamedTuple,
Sequence,
TypeVar,
)
from uuid import UUID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from . import errors
from ._query_context_cache import QueryContextCache
from ._utils import (
_DEFAULT_VALUE_SERVER_DOP_CAP_FOR_FILE_TRANSFER,
_VARIABLE_NAME_SERVER_DOP_CAP_FOR_FILE_TRANSFER,
)
from .auth import (
FIRST_PARTY_AUTHENTICATORS,
Auth,
AuthByDefault,
AuthByKeyPair,
AuthByOAuth,
AuthByOauthCode,
AuthByOauthCredentials,
AuthByOkta,
AuthByPAT,
AuthByPlugin,
AuthByUsrPwdMfa,
AuthByWebBrowser,
AuthByWorkloadIdentity,
AuthNoAuth,
)
from .auth.idtoken import AuthByIdToken
from .backoff_policies import exponential_backoff
from .bind_upload_agent import BindUploadError
from .compat import IS_LINUX, IS_WINDOWS, quote, urlencode
from .config_manager import CONFIG_MANAGER, _get_default_connection_params
from .connection_diagnostic import ConnectionDiagnostic
from .constants import (
_CONNECTIVITY_ERR_MSG,
_DOMAIN_NAME_MAP,
_OAUTH_DEFAULT_SCOPE,
ENV_VAR_PARTNER,
OCSP_ROOT_CERTS_DICT_LOCK_TIMEOUT_DEFAULT_NO_TIMEOUT,
PARAMETER_AUTOCOMMIT,
PARAMETER_CLIENT_PREFETCH_THREADS,
PARAMETER_CLIENT_REQUEST_MFA_TOKEN,
PARAMETER_CLIENT_SESSION_KEEP_ALIVE,
PARAMETER_CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY,
PARAMETER_CLIENT_STORE_TEMPORARY_CREDENTIAL,
PARAMETER_CLIENT_TELEMETRY_ENABLED,
PARAMETER_CLIENT_VALIDATE_DEFAULT_PARAMETERS,
PARAMETER_ENABLE_STAGE_S3_PRIVATELINK_FOR_US_EAST_1,
PARAMETER_QUERY_CONTEXT_CACHE_SIZE,
PARAMETER_SERVICE_NAME,
PARAMETER_TIMEZONE,
OCSPMode,
QueryStatus,
)
from .converter import SnowflakeConverter
from .crl import CRLConfig
from .cursor import LOG_MAX_QUERY_LENGTH, SnowflakeCursor, SnowflakeCursorBase
from .description import (
CLIENT_NAME,
CLIENT_VERSION,
PLATFORM,
PYTHON_VERSION,
SNOWFLAKE_CONNECTOR_VERSION,
)
from .direct_file_operation_utils import FileOperationParser, StreamDownloader
from .errorcode import (
ER_CONNECTION_IS_CLOSED,
ER_FAILED_PROCESSING_PYFORMAT,
ER_FAILED_PROCESSING_QMARK,
ER_FAILED_TO_CONNECT_TO_DB,
ER_INVALID_BACKOFF_POLICY,
ER_INVALID_VALUE,
ER_INVALID_WIF_SETTINGS,
ER_NO_ACCOUNT_NAME,
ER_NO_NUMPY,
ER_NO_PASSWORD,
ER_NO_USER,
ER_NOT_IMPLICITY_SNOWFLAKE_DATATYPE,
)
from .errors import DatabaseError, Error, OperationalError, ProgrammingError
from .log_configuration import EasyLoggingConfigPython
from .network import (
DEFAULT_AUTHENTICATOR,
EXTERNAL_BROWSER_AUTHENTICATOR,
KEY_PAIR_AUTHENTICATOR,
NO_AUTH_AUTHENTICATOR,
OAUTH_AUTHENTICATOR,
OAUTH_AUTHORIZATION_CODE,
OAUTH_CLIENT_CREDENTIALS,
PAT_WITH_EXTERNAL_SESSION,
PROGRAMMATIC_ACCESS_TOKEN,
REQUEST_ID,
USR_PWD_MFA_AUTHENTICATOR,
WORKLOAD_IDENTITY_AUTHENTICATOR,
ReauthenticationRequest,
SnowflakeRestful,
)
from .session_manager import (
HttpConfig,
ProxySupportAdapterFactory,
SessionManager,
SessionManagerFactory,
)
from .sqlstate import SQLSTATE_CONNECTION_NOT_EXISTS, SQLSTATE_FEATURE_NOT_SUPPORTED
from .telemetry import TelemetryClient, TelemetryData, TelemetryField
from .time_util import HeartBeatTimer, get_time_millis
from .url_util import extract_top_level_domain_from_hostname
from .util_text import construct_hostname, parse_account, split_statements
from .wif_util import AttestationProvider
if sys.version_info >= (3, 13) or typing.TYPE_CHECKING:
CursorCls = TypeVar("CursorCls", bound=SnowflakeCursorBase, default=SnowflakeCursor)
else:
CursorCls = TypeVar("CursorCls", bound=SnowflakeCursorBase)
DEFAULT_CLIENT_PREFETCH_THREADS = 4
MAX_CLIENT_PREFETCH_THREADS = 10
MAX_CLIENT_FETCH_THREADS = 1024
DEFAULT_BACKOFF_POLICY = exponential_backoff()
def DefaultConverterClass() -> type:
if IS_WINDOWS:
from .converter_issue23517 import SnowflakeConverterIssue23517
return SnowflakeConverterIssue23517
else:
from .converter import SnowflakeConverter
return SnowflakeConverter
def _get_private_bytes_from_file(
private_key_file: str | bytes | os.PathLike[str] | os.PathLike[bytes],
private_key_file_pwd: bytes | str | None = None,
) -> bytes:
if private_key_file_pwd is not None and isinstance(private_key_file_pwd, str):
private_key_file_pwd = private_key_file_pwd.encode("utf-8")
with open(private_key_file, "rb") as key:
private_key = serialization.load_pem_private_key(
key.read(),
password=private_key_file_pwd,
backend=default_backend(),
)
pkb = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
return pkb
SUPPORTED_PARAMSTYLES = {
"qmark",
"numeric",
"format",
"pyformat",
}
# Default configs, tuple of default variable and accepted types
DEFAULT_CONFIGURATION: dict[str, tuple[Any, type | tuple[type, ...]]] = {
"dsn": (None, (type(None), str)), # standard
"user": ("", str), # standard
"password": ("", str), # standard
"host": ("127.0.0.1", str), # standard
"port": (443, (int, str)), # standard
"database": (None, (type(None), str)), # standard
"proxy_host": (None, (type(None), str)), # snowflake
"proxy_port": (None, (type(None), str)), # snowflake
"proxy_user": (None, (type(None), str)), # snowflake
"proxy_password": (None, (type(None), str)), # snowflake
"no_proxy": (
None,
(type(None), str, Iterable),
), # hosts/ips to bypass proxy (str or iterable)
"protocol": ("https", str), # snowflake
"warehouse": (None, (type(None), str)), # snowflake
"region": (None, (type(None), str)), # snowflake
"account": (None, (type(None), str)), # snowflake
"schema": (None, (type(None), str)), # snowflake
"role": (None, (type(None), str)), # snowflake
"session_id": (None, (type(None), str)), # snowflake
"login_timeout": (None, (type(None), int)), # login timeout
"network_timeout": (
None,
(type(None), int),
), # network timeout (infinite by default)
"socket_timeout": (None, (type(None), int)),
"external_browser_timeout": (120, int),
"platform_detection_timeout_seconds": (
None,
(type(None), float),
), # Platform detection timeout for CSP metadata endpoints
"backoff_policy": (DEFAULT_BACKOFF_POLICY, Callable),
"passcode_in_password": (False, bool), # Snowflake MFA
"passcode": (None, (type(None), str)), # Snowflake MFA
"private_key": (None, (type(None), bytes, str, RSAPrivateKey)),
"private_key_file": (None, (type(None), str)),
"private_key_file_pwd": (None, (type(None), str, bytes)),
"token": (None, (type(None), str)), # OAuth/JWT/PAT/OIDC Token
"token_file_path": (
None,
(type(None), str, bytes),
), # OAuth/JWT/PAT/OIDC Token file path
"authenticator": (DEFAULT_AUTHENTICATOR, (type(None), str)),
"workload_identity_provider": (None, (type(None), AttestationProvider)),
"workload_identity_entra_resource": (None, (type(None), str)),
"workload_identity_impersonation_path": (None, (type(None), list[str])),
"mfa_callback": (None, (type(None), Callable)),
"password_callback": (None, (type(None), Callable)),
"auth_class": (None, (type(None), AuthByPlugin)),
"application": (CLIENT_NAME, (type(None), str)),
# internal_application_name/version is used to tell the server the type of client connecting to
# Snowflake. There are some functionalities (e.g., MFA, Arrow result format) that
# Snowflake server doesn't support for new client types, which requires developers to
# add the new client type to the server to support these features.
"internal_application_name": (CLIENT_NAME, (type(None), str)),
"internal_application_version": (CLIENT_VERSION, (type(None), str)),
"disable_ocsp_checks": (False, bool),
"ocsp_fail_open": (True, bool), # fail open on ocsp issues, default true
"ocsp_root_certs_dict_lock_timeout": (
OCSP_ROOT_CERTS_DICT_LOCK_TIMEOUT_DEFAULT_NO_TIMEOUT, # no timeout
int,
),
"inject_client_pause": (0, int), # snowflake internal
"session_parameters": (None, (type(None), dict)), # snowflake session parameters
"autocommit": (None, (type(None), bool)), # snowflake
"client_session_keep_alive": (None, (type(None), bool)), # snowflake
"client_session_keep_alive_heartbeat_frequency": (
None,
(type(None), int),
), # snowflake
"client_prefetch_threads": (4, int), # snowflake
"client_fetch_threads": (None, (type(None), int)),
"client_fetch_use_mp": (False, bool),
"numpy": (False, bool), # snowflake
"ocsp_response_cache_filename": (None, (type(None), str)), # snowflake internal
"converter_class": (DefaultConverterClass(), SnowflakeConverter),
"validate_default_parameters": (False, bool), # snowflake
"probe_connection": (False, bool), # snowflake
"paramstyle": (None, (type(None), str)), # standard/snowflake
"timezone": (None, (type(None), str)), # snowflake
"consent_cache_id_token": (True, bool), # snowflake
"service_name": (None, (type(None), str)), # snowflake
"support_negative_year": (True, bool), # snowflake
"log_max_query_length": (LOG_MAX_QUERY_LENGTH, int), # snowflake
"disable_request_pooling": (False, bool), # snowflake
# enable temporary credential storing - in file for Linux, in keyring for Mac/Win;
# sets session PARAMETER_CLIENT_STORE_TEMPORARY_CREDENTIAL as well;
# default false
"client_store_temporary_credential": (False, bool),
# Whether to allow clients to cache MFA credentials. Caching must be enabled on the server.
# In driver, we extract this from session using PARAMETER_CLIENT_REQUEST_MFA_TOKEN. Default is ``False``.
"client_request_mfa_token": (False, bool),
"use_openssl_only": (
True,
bool,
), # ignored - python only crypto modules are no longer used
# whether to convert Arrow number values to decimal instead of doubles
"arrow_number_to_decimal": (False, bool),
"enable_stage_s3_privatelink_for_us_east_1": (
False,
bool,
), # only use regional url when the param is set
# Allows cursors to be re-iterable
"reuse_results": (False, bool),
# parameter protecting behavior change of SNOW-501058
"interpolate_empty_sequences": (False, bool),
"enable_connection_diag": (False, bool), # Generate SnowCD like report
"connection_diag_log_path": (
None,
(type(None), str),
), # Path to connection diag report
"connection_diag_whitelist_path": (
None,
(type(None), str),
), # Path to connection diag whitelist json - Deprecated remove in future
"connection_diag_allowlist_path": (
None,
(type(None), str),
), # Path to connection diag allowlist json
"log_imported_packages_in_telemetry": (
True,
bool,
), # Whether to log imported packages in telemetry
"disable_query_context_cache": (
False,
bool,
), # Disable query context cache
"json_result_force_utf8_decoding": (
False,
bool,
), # Whether to force the JSON content to be decoded in utf-8, it is only effective when result format is JSON
"server_session_keep_alive": (
False,
bool,
), # Whether to keep session alive after connector shuts down
"enable_retry_reason_in_query_response": (
True,
bool,
), # Enable sending retryReason in response header for query-requests
"session_token": (
None,
(type(None), str),
), # session token from another connection, to be provided together with master token
"master_token": (
None,
(type(None), str),
), # master token from another connection, to be provided together with session token
"master_validity_in_seconds": (
None,
(type(None), int),
), # master token validity in seconds
"disable_console_login": (
True,
bool,
), # Disable console login and fall back to getting SSO URL from GS
"debug_arrow_chunk": (
False,
bool,
), # log raw arrow chunk for debugging purpuse in case there is malformed arrow data
"disable_saml_url_check": (
False,
bool,
), # disable saml url check in okta authentication
"iobound_tpe_limit": (
None,
(type(None), int),
), # SNOW-1817982: limit iobound TPE sizes when executing PUT/GET
"oauth_client_id": (
None,
(type(None), str),
# SNOW-1825621: OAUTH implementation
),
"oauth_client_secret": (
None,
(type(None), str),
# SNOW-1825621: OAUTH implementation
),
"oauth_credentials_in_body": (
False,
bool,
# SNOW-2300649: Option to send client credentials in body
),
"oauth_authorization_url": (
"https://{host}:{port}/oauth/authorize",
str,
# SNOW-1825621: OAUTH implementation
),
"oauth_token_request_url": (
"https://{host}:{port}/oauth/token-request",
str,
# SNOW-1825621: OAUTH implementation
),
"oauth_redirect_uri": ("http://127.0.0.1", str),
"oauth_scope": (
"",
str,
# SNOW-1825621: OAUTH implementation
),
"oauth_disable_pkce": (
False,
bool,
# SNOW-1825621: OAUTH PKCE
),
"oauth_enable_refresh_tokens": (
False,
bool,
),
"oauth_enable_single_use_refresh_tokens": (
False,
bool,
# Client-side opt-in to single-use refresh tokens.
),
"check_arrow_conversion_error_on_every_column": (
True,
bool,
), # SNOW-XXXXX: remove the check_arrow_conversion_error_on_every_column flag
"external_session_id": (
None,
str,
# SNOW-2096721: External (Spark) session ID
),
"unsafe_file_write": (
False,
bool,
), # SNOW-1944208: add unsafe write flag
"unsafe_skip_file_permissions_check": (
False,
bool,
), # SNOW-2127911: add flag to opt-out file permissions check
_VARIABLE_NAME_SERVER_DOP_CAP_FOR_FILE_TRANSFER: (
_DEFAULT_VALUE_SERVER_DOP_CAP_FOR_FILE_TRANSFER, # default value
int, # type
), # snowflake internal
"reraise_error_in_file_transfer_work_function": (
False,
bool,
),
# CRL (Certificate Revocation List) configuration parameters
# The default setup is specified in CRLConfig class
"cert_revocation_check_mode": (
None,
(type(None), str),
), # CRL revocation check mode: DISABLED, ENABLED, ADVISORY
"allow_certificates_without_crl_url": (
None,
(type(None), bool),
), # Allow certificates without CRL distribution points
"crl_connection_timeout_ms": (
None,
(type(None), int),
), # Connection timeout for CRL downloads in milliseconds
"crl_read_timeout_ms": (
None,
(type(None), int),
), # Read timeout for CRL downloads in milliseconds
"crl_cache_validity_hours": (
None,
(type(None), float),
), # CRL cache validity time in hours
"enable_crl_cache": (None, (type(None), bool)), # Enable CRL caching
"enable_crl_file_cache": (None, (type(None), bool)), # Enable file-based CRL cache
"crl_cache_dir": (None, (type(None), str)), # Directory for CRL file cache
"crl_cache_removal_delay_days": (
None,
(type(None), int),
), # Days to keep expired CRL files before removal
"crl_cache_cleanup_interval_hours": (
None,
(type(None), int),
), # CRL cache cleanup interval in hours
"crl_cache_start_cleanup": (
None,
(type(None), bool),
), # Run CRL cache cleanup in the background
}
APPLICATION_RE = re.compile(r"[\w\d_]+")
# adding the exception class to Connection class
for m in [method for method in dir(errors) if callable(getattr(errors, method))]:
setattr(sys.modules[__name__], m, getattr(errors, m))
logger = getLogger(__name__)
class TypeAndBinding(NamedTuple):
"""Stores the type name and the Snowflake binding."""
type: str
binding: str | None
class SnowflakeConnection:
"""Implementation of the connection object for the Snowflake Database.
Use connect(..) to get the object.
Attributes:
insecure_mode (deprecated): Whether or not the connection is in OCSP disabled mode. It means that the connection
validates the TLS certificate but doesn't check revocation status with OCSP provider.
disable_ocsp_checks: Whether or not the connection is in OCSP disabled mode. It means that the connection
validates the TLS certificate but doesn't check revocation status with OCSP provider.
ocsp_fail_open: Whether or not the connection is in fail open mode. Fail open mode decides if TLS certificates
continue to be validated. Revoked certificates are blocked. Any other exceptions are disregarded.
ocsp_root_certs_dict_lock_timeout: Timeout for the OCSP root certs dict lock in seconds. Default value is -1, which means no timeout.
session_id: The session ID of the connection.
user: The user name used in the connection.
host: The host name the connection attempts to connect to.
port: The port to communicate with on the host.
region: Region name if not the default Snowflake Database deployment.
proxy_host: The hostname used proxy server.
proxy_port: Port on proxy server to communicate with.
proxy_user: User name to login with on the proxy sever.
proxy_password: Password to be used to authenticate with proxy server.
account: Account name to be used to authenticate with Snowflake.
database: Database to use on Snowflake.
schema: Schema in use on Snowflake.
warehouse: Warehouse to be used on Snowflake.
role: Role in use on Snowflake.
login_timeout: Login timeout in seconds. Login requests will not be retried after this timeout expires.
Note that the login attempt may still take more than login_timeout seconds as an ongoing login request
cannot be canceled even upon login timeout expiry. The login timeout only prevents further retries.
If not specified, login_timeout is set to `snowflake.connector.auth.by_plugin.DEFAULT_AUTH_CLASS_TIMEOUT`.
Note that the number of retries on login requests is still limited by
`snowflake.connector.auth.by_plugin.DEFAULT_MAX_CON_RETRY_ATTEMPTS`.
network_timeout: Network timeout in seconds. Network requests besides login requests will not be retried
after this timeout expires. Overriden in cursor query execution if timeout is passed to cursor.execute.
Note that an operation may still take more than network_timeout seconds for the same reason as above.
If not specified, network_timeout is infinite.
socket_timeout: Socket timeout in seconds. Sets both socket connect and read timeout.
backoff_policy: Backoff policy to use for login and network requests. Must be a callable generator function.
Standard linear and exponential backoff implementations are included in `snowflake.connector.backoff_policies`
See the backoff_policies module for details and implementation examples.
client_session_keep_alive_heartbeat_frequency: Heartbeat frequency to keep connection alive in seconds.
client_prefetch_threads: Number of threads to download the result set.
client_fetch_threads: Number of threads (or processes) to fetch staged query results.
If not specified, reuses client_prefetch_threads value.
client_fetch_use_mp: Enables multiprocessing for fetching query results in parallel.
rest: Snowflake REST API object. Internal use only. Maybe removed in a later release.
application: Application name to communicate with Snowflake as. By default, this is "PythonConnector".
errorhandler: Handler used with errors. By default, an exception will be raised on error.
converter_class: Handler used to convert data to Python native objects.
validate_default_parameters: Validate database, schema, role and warehouse used on Snowflake.
is_pyformat: Whether the current argument binding is pyformat or format.
consent_cache_id_token: Consented cache ID token.
enable_stage_s3_privatelink_for_us_east_1: when true, clients use regional s3 url to upload files.
enable_connection_diag: when true, clients will generate a connectivity diagnostic report.
connection_diag_log_path: path to location to create diag report with enable_connection_diag.
connection_diag_whitelist_path: path to a whitelist.json file to test with enable_connection_diag - deprecated remove in future
connection_diag_allowlist_path: path to a allowlist.json file to test with enable_connection_diag.
json_result_force_utf8_decoding: When true, json result will be decoded in utf-8,
when false, the encoding of the content is auto-detected. Default value is false.
This parameter is only effective when the result format is JSON.
server_session_keep_alive: When true, the connector does not destroy the session on the Snowflake server side
before the connector shuts down. Default value is false.
token_file_path: The file path of the token file. If both token and token_file_path are provided, the token in token_file_path will be used.
unsafe_file_write: When true, files downloaded by GET will be saved with 644 permissions. Otherwise, files will be saved with safe - owner-only permissions: 600.
check_arrow_conversion_error_on_every_column: When true, the error check after the conversion from arrow to python types will happen for every column in the row. This is a new behaviour which fixes the bug that caused the type errors to trigger silently when occurring at any place other than last column in a row. To revert the previous (faulty) behaviour, please set this flag to false.
"""
OCSP_ENV_LOCK = Lock()
def __init__(
self,
connection_name: str | None = None,
connections_file_path: pathlib.Path | None = None,
**kwargs,
) -> None:
"""Create a new SnowflakeConnection.
Connections can be loaded from the TOML file located at
snowflake.connector.constants.CONNECTIONS_FILE.
When connection_name is supplied we will first load that connection
and then override any other values supplied.
When no arguments are given (other than connection_file_path) the
default connection will be loaded first. Note that no overwriting is
supported in this case.
If overwriting values from the default connection is desirable, supply
the name explicitly.
"""
self._unsafe_skip_file_permissions_check = kwargs.get(
"unsafe_skip_file_permissions_check", False
)
# initiate easy logging during every connection
easy_logging = EasyLoggingConfigPython(
skip_config_file_permissions_check=self._unsafe_skip_file_permissions_check
)
easy_logging.create_log()
self._lock_sequence_counter = Lock()
self.sequence_counter = 0
self._errorhandler = Error.default_errorhandler
self._lock_converter = Lock()
self.messages = []
self._async_sfqids: dict[str, None] = {}
self._done_async_sfqids: dict[str, None] = {}
self._client_param_telemetry_enabled = True
self._server_param_telemetry_enabled = False
self._session_parameters: dict[str, str | int | bool] = {}
logger.info(
"Snowflake Connector for Python Version: %s, "
"Python Version: %s, Platform: %s",
SNOWFLAKE_CONNECTOR_VERSION,
PYTHON_VERSION,
PLATFORM,
)
# Placeholder attributes; will be initialized in connect()
self._http_config: HttpConfig | None = None
self._crl_config: CRLConfig | None = None
self._session_manager: SessionManager | None = None
self._rest: SnowflakeRestful | None = None
for name, (value, _) in DEFAULT_CONFIGURATION.items():
setattr(self, f"_{name}", value)
self.heartbeat_thread = None
is_kwargs_empty = not kwargs
if "application" not in kwargs:
app = self._detect_application()
if app:
kwargs["application"] = app
if "insecure_mode" in kwargs:
warn_message = "The 'insecure_mode' connection property is deprecated. Please use 'disable_ocsp_checks' instead"
warnings.warn(
warn_message,
DeprecationWarning,
stacklevel=2,
)
if (
"disable_ocsp_checks" in kwargs
and kwargs["disable_ocsp_checks"] != kwargs["insecure_mode"]
):
logger.warning(
"The values for 'disable_ocsp_checks' and 'insecure_mode' differ. "
"Using the value of 'disable_ocsp_checks."
)
else:
self._disable_ocsp_checks = kwargs["insecure_mode"]
self.converter = None
self.query_context_cache: QueryContextCache | None = None
self.query_context_cache_size = 5
if connections_file_path is not None:
# Change config file path and force update cache
for i, s in enumerate(CONFIG_MANAGER._slices):
if s.section == "connections":
CONFIG_MANAGER._slices[i] = s._replace(path=connections_file_path)
CONFIG_MANAGER.read_config(
skip_file_permissions_check=self._unsafe_skip_file_permissions_check
)
break
if connection_name is not None:
connections = CONFIG_MANAGER["connections"]
if connection_name not in connections:
raise Error(
f"Invalid connection_name '{connection_name}',"
f" known ones are {list(connections.keys())}"
)
kwargs = {**connections[connection_name], **kwargs}
elif is_kwargs_empty:
# connection_name is None and kwargs was empty when called
kwargs = _get_default_connection_params()
self.__set_error_attributes()
self.connect(**kwargs)
self._telemetry = TelemetryClient(self._rest)
self.expired = False
# get the imported modules from sys.modules
self._log_telemetry_imported_packages()
# check SNOW-1218851 for long term improvement plan to refactor ocsp code
atexit.register(self._close_at_exit)
# Set up the file operation parser and stream downloader.
self._file_operation_parser = FileOperationParser(self)
self._stream_downloader = StreamDownloader(self)
# Deprecated
@property
def insecure_mode(self) -> bool:
return self._disable_ocsp_checks
@property
def disable_ocsp_checks(self) -> bool:
return self._disable_ocsp_checks
@property
def ocsp_fail_open(self) -> bool:
return self._ocsp_fail_open
def _ocsp_mode(self) -> OCSPMode:
"""OCSP mode. DISABLE_OCSP_CHECKS, FAIL_OPEN or FAIL_CLOSED."""
if self.disable_ocsp_checks:
return OCSPMode.DISABLE_OCSP_CHECKS
elif self.ocsp_fail_open:
return OCSPMode.FAIL_OPEN
else:
return OCSPMode.FAIL_CLOSED
# CRL (Certificate Revocation List) configuration properties
@property
def cert_revocation_check_mode(self) -> str | None:
"""Certificate revocation check mode: DISABLED, ENABLED, or ADVISORY."""
if not self._crl_config:
return self._cert_revocation_check_mode
return self._crl_config.cert_revocation_check_mode.value
@property
def allow_certificates_without_crl_url(self) -> bool | None:
"""Whether to allow certificates without CRL distribution points."""
if not self._crl_config:
return self._allow_certificates_without_crl_url
return self._crl_config.allow_certificates_without_crl_url
@property
def crl_connection_timeout_ms(self) -> int | None:
"""Connection timeout for CRL downloads in milliseconds."""
if not self._crl_config:
return self._crl_connection_timeout_ms
return self._crl_config.connection_timeout_ms
@property
def crl_read_timeout_ms(self) -> int | None:
"""Read timeout for CRL downloads in milliseconds."""
if not self._crl_config:
return self._crl_read_timeout_ms
return self._crl_config.read_timeout_ms
@property
def crl_cache_validity_hours(self) -> float | None:
"""CRL cache validity time in hours."""
if not self._crl_config:
return self._crl_cache_validity_hours
return self._crl_config.cache_validity_time.total_seconds() / 3600
@property
def enable_crl_cache(self) -> bool | None:
"""Whether CRL caching is enabled."""
if not self._crl_config:
return self._enable_crl_cache
return self._crl_config.enable_crl_cache
@property
def enable_crl_file_cache(self) -> bool | None:
"""Whether file-based CRL cache is enabled."""
if not self._crl_config:
return self._enable_crl_file_cache
return self._crl_config.enable_crl_file_cache
@property
def crl_cache_dir(self) -> str | None:
"""Directory for CRL file cache."""
if not self._crl_config:
return self._crl_cache_dir
if not self._crl_config.crl_cache_dir:
return None
return str(self._crl_config.crl_cache_dir)
@property
def crl_cache_removal_delay_days(self) -> int | None:
"""Days to keep expired CRL files before removal."""
if not self._crl_config:
return self._crl_cache_removal_delay_days
return self._crl_config.crl_cache_removal_delay_days
@property
def crl_cache_cleanup_interval_hours(self) -> int | None:
"""CRL cache cleanup interval in hours."""
if not self._crl_config:
return self._crl_cache_cleanup_interval_hours
return self._crl_config.crl_cache_cleanup_interval_hours
@property
def crl_cache_start_cleanup(self) -> bool | None:
"""Whether to start CRL cache cleanup immediately."""
if not self._crl_config:
return self._crl_cache_start_cleanup
return self._crl_config.crl_cache_start_cleanup
@property
def session_id(self) -> int:
return self._session_id
@property
def user(self) -> str:
return self._user
@property
def host(self) -> str:
return self._host
@property
def port(self) -> int:
return int(self._port)
@property
def region(self) -> str | None:
warnings.warn(
"Region has been deprecated and will be removed in the near future",
PendingDeprecationWarning,
# Raise warning from where this property was called from
stacklevel=2,
)
return self._region
@property
def proxy_host(self) -> str | None:
return self._proxy_host
@property
def proxy_port(self) -> str | None:
return self._proxy_port
@property
def proxy_user(self) -> str | None:
return self._proxy_user
@property
def proxy_password(self) -> str | None:
return self._proxy_password
@property
def no_proxy(self) -> str | Iterable | None:
return self._no_proxy
@property
def account(self) -> str:
return self._account
@property
def database(self) -> str | None:
return self._database
@property
def schema(self) -> str | None:
return self._schema
@property
def warehouse(self) -> str | None:
return self._warehouse
@property
def role(self) -> str | None:
return self._role
@property
def login_timeout(self) -> int | None:
return int(self._login_timeout) if self._login_timeout is not None else None
@property
def network_timeout(self) -> int | None:
return int(self._network_timeout) if self._network_timeout is not None else None
@property
def socket_timeout(self) -> int | None:
return int(self._socket_timeout) if self._socket_timeout is not None else None
@property
def _backoff_generator(self) -> Iterator:
return self._backoff_policy()
@property
def client_session_keep_alive(self) -> bool | None:
return self._client_session_keep_alive
@client_session_keep_alive.setter
def client_session_keep_alive(self, value) -> None:
self._client_session_keep_alive = value
@property
def client_session_keep_alive_heartbeat_frequency(self) -> int | None:
return self._client_session_keep_alive_heartbeat_frequency
@client_session_keep_alive_heartbeat_frequency.setter
def client_session_keep_alive_heartbeat_frequency(self, value) -> None:
self._client_session_keep_alive_heartbeat_frequency = value
self._validate_client_session_keep_alive_heartbeat_frequency()
@property
def platform_detection_timeout_seconds(self) -> float | None:
return self._platform_detection_timeout_seconds
@platform_detection_timeout_seconds.setter
def platform_detection_timeout_seconds(self, value) -> None:
self._platform_detection_timeout_seconds = value
@property
def client_prefetch_threads(self) -> int:
return (
self._client_prefetch_threads
if self._client_prefetch_threads
else DEFAULT_CLIENT_PREFETCH_THREADS
)
@client_prefetch_threads.setter
def client_prefetch_threads(self, value) -> None:
self._client_prefetch_threads = value
self._validate_client_prefetch_threads()
@property
def client_fetch_threads(self) -> int | None:
return self._client_fetch_threads
@client_fetch_threads.setter
def client_fetch_threads(self, value: None | int) -> None:
if value is not None:
value = min(max(1, value), MAX_CLIENT_FETCH_THREADS)
self._client_fetch_threads = value
@property
def client_fetch_use_mp(self) -> bool:
return self._client_fetch_use_mp
@property
def rest(self) -> SnowflakeRestful | None:
return self._rest
@property
def application(self) -> str:
return self._application
@property
def errorhandler(self) -> Callable: # TODO: callable args
return self._errorhandler
@errorhandler.setter
# Note: Callable doesn't implement operator|
def errorhandler(self, value: Callable | None) -> None:
if value is None:
raise ProgrammingError("None errorhandler is specified")
self._errorhandler = value
@property
def converter_class(self) -> type[SnowflakeConverter]:
return self._converter_class
@property
def validate_default_parameters(self) -> bool:
return self._validate_default_parameters
@property
def is_pyformat(self) -> bool:
return self._paramstyle in ("pyformat", "format")
@property
def consent_cache_id_token(self):
return self._consent_cache_id_token
@property
def telemetry_enabled(self) -> bool:
return bool(
self._client_param_telemetry_enabled
and self._server_param_telemetry_enabled
)
@telemetry_enabled.setter
def telemetry_enabled(self, value) -> None:
self._client_param_telemetry_enabled = True if value else False
if (
self._client_param_telemetry_enabled
and not self._server_param_telemetry_enabled
):
logger.info(
"Telemetry has been disabled by the session parameter CLIENT_TELEMETRY_ENABLED."
" Set session parameter CLIENT_TELEMETRY_ENABLED to true to enable telemetry."
)
@property
def service_name(self) -> str | None:
return self._service_name
@service_name.setter
def service_name(self, value) -> None:
self._service_name = value
@property
def log_max_query_length(self) -> int:
return self._log_max_query_length
@property
def disable_request_pooling(self) -> bool:
return self._disable_request_pooling
@disable_request_pooling.setter
def disable_request_pooling(self, value) -> None:
self._disable_request_pooling = True if value else False
@property
def use_openssl_only(self) -> bool:
# Deprecated, kept for backwards compatibility
return True
@property
def arrow_number_to_decimal(self):
return self._arrow_number_to_decimal
@property
def enable_stage_s3_privatelink_for_us_east_1(self) -> bool: