-
Notifications
You must be signed in to change notification settings - Fork 468
/
connection.py
1943 lines (1731 loc) · 74.9 KB
/
connection.py
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
#
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
#
from __future__ import annotations
import atexit
import logging
import os
import pathlib
import re
import sys
import traceback
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 partial
from io import StringIO
from logging import getLogger
from threading import Lock
from time import strptime
from types import TracebackType
from typing import Any, Callable, Generator, Iterable, Iterator, NamedTuple, Sequence
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, proxy
from ._query_context_cache import QueryContextCache
from .auth import (
FIRST_PARTY_AUTHENTICATORS,
Auth,
AuthByDefault,
AuthByKeyPair,
AuthByOAuth,
AuthByOkta,
AuthByPlugin,
AuthByUsrPwdMfa,
AuthByWebBrowser,
)
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 (
ENV_VAR_PARTNER,
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_TELEMETRY_OOB_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 .cursor import LOG_MAX_QUERY_LENGTH, SnowflakeCursor
from .description import (
CLIENT_NAME,
CLIENT_VERSION,
PLATFORM,
PYTHON_VERSION,
SNOWFLAKE_CONNECTOR_VERSION,
)
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_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,
OAUTH_AUTHENTICATOR,
REQUEST_ID,
USR_PWD_MFA_AUTHENTICATOR,
ReauthenticationRequest,
SnowflakeRestful,
)
from .sqlstate import SQLSTATE_CONNECTION_NOT_EXISTS, SQLSTATE_FEATURE_NOT_SUPPORTED
from .telemetry import TelemetryClient, TelemetryData, TelemetryField
from .telemetry_oob import TelemetryService
from .time_util import HeartBeatTimer, get_time_millis
from .util_text import construct_hostname, parse_account, split_statements
DEFAULT_CLIENT_PREFETCH_THREADS = 4
MAX_CLIENT_PREFETCH_THREADS = 10
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": (8080, (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
"protocol": ("http", 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)),
"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), str, RSAPrivateKey)),
"private_key_file": (None, (type(None), str)),
"private_key_file_pwd": (None, (type(None), str, bytes)),
"token": (None, (type(None), str)), # OAuth or JWT Token
"authenticator": (DEFAULT_AUTHENTICATOR, (type(None), 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": (CLIENT_NAME, (type(None), str)),
"internal_application_version": (CLIENT_VERSION, (type(None), str)),
"insecure_mode": (False, bool), # Error security fix requirement
"ocsp_fail_open": (True, bool), # fail open on ocsp issues, default true
"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
"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 file for Linux, default false. Mac/Win will overlook this
"client_store_temporary_credential": (False, bool),
"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
}
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))
# Workaround for https://bugs.python.org/issue7980
strptime("20150102030405", "%Y%m%d%H%M%S")
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: Whether or not the connection is in insecure mode. Insecure mode means that the connection
validates the TLS certificate but doesn't check revocation status.
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.
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.
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.
"""
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.
"""
# initiate easy logging during every connection
easy_logging = EasyLoggingConfigPython()
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.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,
)
self._rest = 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:
if ENV_VAR_PARTNER in os.environ.keys():
kwargs["application"] = os.environ[ENV_VAR_PARTNER]
elif "streamlit" in sys.modules:
kwargs["application"] = "streamlit"
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()
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)
@property
def insecure_mode(self) -> bool:
return self._insecure_mode
@property
def ocsp_fail_open(self) -> bool:
return self._ocsp_fail_open
def _ocsp_mode(self) -> OCSPMode:
"""OCSP mode. INSEC
URE, FAIL_OPEN or FAIL_CLOSED."""
if self.insecure_mode:
return OCSPMode.INSECURE
elif self.ocsp_fail_open:
return OCSPMode.FAIL_OPEN
else:
return OCSPMode.FAIL_CLOSED
@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 | str: # TODO: shouldn't be a string
return 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 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 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 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 self._telemetry_enabled
@telemetry_enabled.setter
def telemetry_enabled(self, value) -> None:
self._telemetry_enabled = True if value else False
@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:
return self._enable_stage_s3_privatelink_for_us_east_1
@enable_stage_s3_privatelink_for_us_east_1.setter
def enable_stage_s3_privatelink_for_us_east_1(self, value) -> None:
self._enable_stage_s3_privatelink_for_us_east_1 = True if value else False
@property
def enable_connection_diag(self) -> bool:
return self._enable_connection_diag
@property
def connection_diag_log_path(self):
return self._connection_diag_log_path
@property
def connection_diag_whitelist_path(self):
"""
Old version of ``connection_diag_allowlist_path``.
This used to be the original name, but snowflake backend
deprecated whitelist for allowlist. This name will be
deprecated in the future.
"""
warnings.warn(
"connection_diag_whitelist_path has been deprecated, use connection_diag_allowlist_path instead",
DeprecationWarning,
stacklevel=2,
)
return self._connection_diag_whitelist_path
@property
def connection_diag_allowlist_path(self):
return self._connection_diag_allowlist_path
@arrow_number_to_decimal.setter
def arrow_number_to_decimal_setter(self, value: bool) -> None:
self._arrow_number_to_decimal = value
@property
def auth_class(self) -> AuthByPlugin | None:
return self._auth_class
@auth_class.setter
def auth_class(self, value: AuthByPlugin) -> None:
if isinstance(value, AuthByPlugin):
self._auth_class = value
else:
raise TypeError("auth_class must subclass AuthByPlugin")
@property
def is_query_context_cache_disabled(self) -> bool:
return self._disable_query_context_cache
def connect(self, **kwargs) -> None:
"""Establishes connection to Snowflake."""
logger.debug("connect")
if len(kwargs) > 0:
self.__config(**kwargs)
TelemetryService.get_instance().update_context(kwargs)
if self.enable_connection_diag:
exceptions_dict = {}
connection_diag = ConnectionDiagnostic(
account=self.account,
host=self.host,
connection_diag_log_path=self.connection_diag_log_path,
connection_diag_allowlist_path=(
self.connection_diag_allowlist_path
if self.connection_diag_allowlist_path is not None
else self.connection_diag_whitelist_path
),
proxy_host=self.proxy_host,
proxy_port=self.proxy_port,
proxy_user=self.proxy_user,
proxy_password=self.proxy_password,
)
try:
connection_diag.run_test()
self.__open_connection()
connection_diag.cursor = self.cursor()
except Exception:
exceptions_dict["connection_test"] = traceback.format_exc()
logger.warning(
f"""Exception during connection test:\n{exceptions_dict["connection_test"]} """
)
try:
connection_diag.run_post_test()
except Exception:
exceptions_dict["post_test"] = traceback.format_exc()
logger.warning(
f"""Exception during post connection test:\n{exceptions_dict["post_test"]} """
)
finally:
connection_diag.generate_report()
if exceptions_dict:
raise Exception(str(exceptions_dict))
else:
self.__open_connection()
def close(self, retry: bool = True) -> None:
"""Closes the connection."""
# unregister to dereference connection object as it's already closed after the execution
atexit.unregister(self._close_at_exit)
try:
if not self.rest:
logger.debug("Rest object has been destroyed, cannot close session")
return
# will hang if the application doesn't close the connection and
# CLIENT_SESSION_KEEP_ALIVE is set, because the heartbeat runs on
# a separate thread.
self._cancel_heartbeat()
# close telemetry first, since it needs rest to send remaining data
logger.info("closed")
self._telemetry.close(send_on_close=retry)
if (
self._all_async_queries_finished()
and not self._server_session_keep_alive
):
logger.info("No async queries seem to be running, deleting session")
self.rest.delete_session(retry=retry)
else:
logger.info(
"There are {} async queries still running, not deleting session".format(
len(self._async_sfqids)
)
)
self.rest.close()
self._rest = None
if self.query_context_cache:
self.query_context_cache.clear_cache()
del self.messages[:]
logger.debug("Session is closed")
except Exception as e:
logger.debug(
"Exception encountered in closing connection. ignoring...: %s", e
)
def is_closed(self) -> bool:
"""Checks whether the connection has been closed."""
return self.rest is None
def autocommit(self, mode) -> None:
"""Sets autocommit mode to True, or False. Defaults to True."""
if not self.rest:
Error.errorhandler_wrapper(
self,
None,
DatabaseError,
{
"msg": "Connection is closed",
"errno": ER_CONNECTION_IS_CLOSED,
"sqlstate": SQLSTATE_CONNECTION_NOT_EXISTS,
},
)
if not isinstance(mode, bool):
Error.errorhandler_wrapper(
self,
None,
ProgrammingError,
{
"msg": f"Invalid parameter: {mode}",
"errno": ER_INVALID_VALUE,
},
)
try:
self.cursor().execute(f"ALTER SESSION SET autocommit={mode}")
except Error as e:
if e.sqlstate == SQLSTATE_FEATURE_NOT_SUPPORTED:
logger.debug(
"Autocommit feature is not enabled for this " "connection. Ignored"
)
def commit(self) -> None:
"""Commits the current transaction."""
self.cursor().execute("COMMIT")
def rollback(self) -> None:
"""Rolls back the current transaction."""
self.cursor().execute("ROLLBACK")
def cursor(
self, cursor_class: type[SnowflakeCursor] = SnowflakeCursor
) -> SnowflakeCursor:
"""Creates a cursor object. Each statement will be executed in a new cursor object."""
logger.debug("cursor")
if not self.rest:
Error.errorhandler_wrapper(
self,
None,
DatabaseError,
{
"msg": "Connection is closed",
"errno": ER_CONNECTION_IS_CLOSED,
"sqlstate": SQLSTATE_CONNECTION_NOT_EXISTS,
},
)
return cursor_class(self)
def execute_string(
self,
sql_text: str,
remove_comments: bool = False,
return_cursors: bool = True,
cursor_class: SnowflakeCursor = SnowflakeCursor,
**kwargs,
) -> Iterable[SnowflakeCursor]:
"""Executes a SQL text including multiple statements. This is a non-standard convenience method."""
stream = StringIO(sql_text)
stream_generator = self.execute_stream(
stream, remove_comments=remove_comments, cursor_class=cursor_class, **kwargs
)
ret = list(stream_generator)
return ret if return_cursors else list()
def execute_stream(
self,
stream: StringIO,
remove_comments: bool = False,
cursor_class: SnowflakeCursor = SnowflakeCursor,
**kwargs,
) -> Generator[SnowflakeCursor, None, None]:
"""Executes a stream of SQL statements. This is a non-standard convenient method."""
split_statements_list = split_statements(
stream, remove_comments=remove_comments
)
# Note: split_statements_list is a list of tuples of sql statements and whether they are put/get
non_empty_statements = [e for e in split_statements_list if e[0]]
for sql, is_put_or_get in non_empty_statements:
cur = self.cursor(cursor_class=cursor_class)
cur.execute(sql, _is_put_get=is_put_or_get, **kwargs)
yield cur
def __set_error_attributes(self) -> None:
for m in [
method for method in dir(errors) if callable(getattr(errors, method))
]:
# If name starts with _ then ignore that
name = m if not m.startswith("_") else m[1:]
setattr(self, name, getattr(errors, m))
@staticmethod
def setup_ocsp_privatelink(app, hostname) -> None:
SnowflakeConnection.OCSP_ENV_LOCK.acquire()
ocsp_cache_server = f"http://ocsp.{hostname}/ocsp_response_cache.json"
os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_URL"] = ocsp_cache_server
logger.debug("OCSP Cache Server is updated: %s", ocsp_cache_server)
SnowflakeConnection.OCSP_ENV_LOCK.release()
def __open_connection(self):
"""Opens a new network connection."""
self.converter = self._converter_class(
use_numpy=self._numpy, support_negative_year=self._support_negative_year
)
proxy.set_proxies(
self.proxy_host, self.proxy_port, self.proxy_user, self.proxy_password
)
self._rest = SnowflakeRestful(
host=self.host,
port=self.port,
protocol=self._protocol,
inject_client_pause=self._inject_client_pause,
connection=self,
)
logger.debug("REST API object was created: %s:%s", self.host, self.port)
if "SF_OCSP_RESPONSE_CACHE_SERVER_URL" in os.environ:
logger.debug(
"Custom OCSP Cache Server URL found in environment - %s",
os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_URL"],
)
if self.host.endswith(".privatelink.snowflakecomputing.com"):
SnowflakeConnection.setup_ocsp_privatelink(self.application, self.host)
else:
if "SF_OCSP_RESPONSE_CACHE_SERVER_URL" in os.environ:
del os.environ["SF_OCSP_RESPONSE_CACHE_SERVER_URL"]
if self._session_parameters is None:
self._session_parameters = {}
if self._autocommit is not None:
self._session_parameters[PARAMETER_AUTOCOMMIT] = self._autocommit
if self._timezone is not None:
self._session_parameters[PARAMETER_TIMEZONE] = self._timezone
if self._validate_default_parameters:
# Snowflake will validate the requested database, schema, and warehouse
self._session_parameters[PARAMETER_CLIENT_VALIDATE_DEFAULT_PARAMETERS] = (
True
)
if self.client_session_keep_alive is not None:
self._session_parameters[PARAMETER_CLIENT_SESSION_KEEP_ALIVE] = (
self._client_session_keep_alive
)
if self.client_session_keep_alive_heartbeat_frequency is not None:
self._session_parameters[
PARAMETER_CLIENT_SESSION_KEEP_ALIVE_HEARTBEAT_FREQUENCY
] = self._validate_client_session_keep_alive_heartbeat_frequency()
if self.client_prefetch_threads:
self._session_parameters[PARAMETER_CLIENT_PREFETCH_THREADS] = (
self._validate_client_prefetch_threads()
)
# Setup authenticator
auth = Auth(self.rest)
if self._session_token and self._master_token:
auth._rest.update_tokens(
self._session_token,
self._master_token,
self._master_validity_in_seconds,
)
heartbeat_ret = auth._rest._heartbeat()
logger.debug(heartbeat_ret)
if not heartbeat_ret or not heartbeat_ret.get("success"):
Error.errorhandler_wrapper(
self,
None,
ProgrammingError,
{
"msg": "Session and master tokens invalid",
"errno": ER_INVALID_VALUE,
},
)
else:
logger.debug("Session and master token validation successful.")
else:
if self.auth_class is not None:
if type(
self.auth_class
) not in FIRST_PARTY_AUTHENTICATORS and not issubclass(
type(self.auth_class), AuthByKeyPair
):
raise TypeError("auth_class must be a child class of AuthByKeyPair")