-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathconnection.py
More file actions
2218 lines (1936 loc) · 99.1 KB
/
Copy pathconnection.py
File metadata and controls
2218 lines (1936 loc) · 99.1 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
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
This module defines the Connection class, which is used to manage a connection to a database.
The class provides methods to establish a connection, create cursors, commit transactions,
roll back transactions, and close the connection.
Resource Management:
- All cursors created from this connection are tracked internally.
- When close() is called on the connection, all open cursors are automatically closed.
- Do not use any cursor after the connection is closed; doing so will raise an exception.
- Cursors are also cleaned up automatically when no longer referenced, to prevent memory leaks.
"""
import weakref
import re
import codecs
import warnings
from typing import Any, Dict, Optional, Union, List, Tuple, Callable, Protocol, TYPE_CHECKING
import threading
import mssql_python
from mssql_python.cursor import Cursor
from mssql_python.helpers import (
sanitize_user_input,
validate_attribute_value,
)
from mssql_python.connection_string_parser import sanitize_connection_string
from mssql_python.logging import logger
from mssql_python import ddbc_bindings
from mssql_python.pooling import PoolingManager
from mssql_python.exceptions import (
Warning, # pylint: disable=redefined-builtin
Error,
InterfaceError,
DatabaseError,
DataError,
OperationalError,
IntegrityError,
InternalError,
ProgrammingError,
NotSupportedError,
sqlstate_to_exception,
)
from mssql_python.auth import (
extract_auth_type,
process_auth_parameters,
remove_sensitive_params,
get_auth_token_info,
compute_identity_key,
compute_token_identity,
)
from mssql_python.constants import ConstantsDDBC, GetInfoConstants
from mssql_python.connection_string_parser import _ConnectionStringParser
from mssql_python.connection_string_builder import _ConnectionStringBuilder
from mssql_python.constants import (
_RESERVED_PARAMETERS,
_KEY_AUTHENTICATION,
_KEY_UID,
_KEY_PWD,
_KEY_TRUSTED_CONNECTION,
_AuthInternal,
)
if TYPE_CHECKING:
from mssql_python.row import Row
class TokenProvider(Protocol):
"""Structural type for the ``token_provider`` parameter.
Any object exposing a ``get_token(scope)`` method that returns an object
with a ``.token`` attribute (the raw JWT string) satisfies this protocol.
It is intentionally broader than ``azure.core.credentials.TokenCredential``
-- whose ``get_token`` requires the ``(*scopes, **kwargs)`` shape -- so that
a minimal ``get_token(scope)`` implementation (for example, a thin wrapper
around a token obtained from Microsoft Fabric's ``mssparkutils``) is
accepted by static type checkers, matching the documented contract. Every
``azure-identity`` credential (``DefaultAzureCredential``,
``AzureCliCredential``, ...) also conforms.
"""
def get_token(self, scope: str) -> Any:
"""Return an object with a ``.token`` attribute for ``scope``."""
...
# Add SQL_WMETADATA constant for metadata decoding configuration
SQL_WMETADATA: int = -99 # Special flag for column name decoding
# Threshold to determine if an info type is string-based
INFO_TYPE_STRING_THRESHOLD: int = 10000
# UTF-16 encoding variants that should use SQL_WCHAR by default
# Note: "utf-16" with BOM is NOT included as it's problematic for SQL_WCHAR
UTF16_ENCODINGS: frozenset[str] = frozenset(["utf-16le", "utf-16be"])
_SQLSTATE_RE = re.compile(r"^SQLSTATE:([A-Z0-9]{0,5}):(.*)", re.DOTALL)
def _raise_connection_error(e: RuntimeError) -> None:
"""Map a RuntimeError from the C++ pybind layer to the correct DB-API 2.0 exception.
Connection::checkError() throws "SQLSTATE:XXXXX:<odbc_message>" so the SQLSTATE
can be mapped via sqlstate_to_exception(), consistent with cursor-level error handling.
"""
error_msg = str(e)
match = _SQLSTATE_RE.match(error_msg)
if match:
sqlstate, ddbc_error = match.group(1), match.group(2)
# Handle malformed SQLSTATE prefix (empty or invalid code)
if not sqlstate or len(sqlstate) != 5:
logger.error("Connection error (malformed SQLSTATE): %s", ddbc_error)
raise OperationalError(
driver_error="Connection operation failed",
ddbc_error=ddbc_error,
) from None
exc = sqlstate_to_exception(sqlstate, ddbc_error)
if exc is None:
logger.error("Unknown SQLSTATE %s, raising DatabaseError", sqlstate)
raise DatabaseError(
driver_error=f"An error occurred with SQLSTATE code: {sqlstate}",
ddbc_error=ddbc_error,
) from None
logger.error("Connection error (SQLSTATE %s): %s", sqlstate, ddbc_error)
raise exc from None
# Fallback: no SQLSTATE prefix — e.g. "Connection handle not allocated"
logger.error("Connection error: %s", error_msg)
raise OperationalError(
driver_error="Connection operation failed",
ddbc_error=error_msg,
) from None
def _validate_utf16_wchar_compatibility(
encoding: str, wchar_type: int, context: str = "SQL_WCHAR"
) -> None:
"""
Validates UTF-16 encoding compatibility with SQL_WCHAR.
Centralizes the validation logic to eliminate duplication across setencoding/setdecoding.
Args:
encoding: The encoding string (already normalized to lowercase)
wchar_type: The SQL_WCHAR constant value to check against
context: Context string for error messages ('SQL_WCHAR', 'SQL_WCHAR ctype', etc.)
Raises:
ProgrammingError: If encoding is incompatible with SQL_WCHAR
"""
if encoding == "utf-16":
# UTF-16 with BOM is rejected due to byte order ambiguity
logger.warning("utf-16 with BOM rejected for %s", context)
raise ProgrammingError(
driver_error="UTF-16 with Byte Order Mark not supported for SQL_WCHAR",
ddbc_error=(
"Cannot use 'utf-16' encoding with SQL_WCHAR due to Byte Order Mark ambiguity. "
"Use 'utf-16le' or 'utf-16be' instead for explicit byte order."
),
)
elif encoding not in UTF16_ENCODINGS:
# Non-UTF-16 encodings are not supported with SQL_WCHAR
logger.warning(
"Non-UTF-16 encoding %s attempted with %s", sanitize_user_input(encoding), context
)
# Generate context-appropriate error messages
if "ctype" in context:
driver_error = "SQL_WCHAR ctype only supports UTF-16 encodings"
ddbc_context = "SQL_WCHAR ctype"
else:
driver_error = "SQL_WCHAR only supports UTF-16 encodings"
ddbc_context = "SQL_WCHAR"
raise ProgrammingError(
driver_error=driver_error,
ddbc_error=(
f"Cannot use encoding '{encoding}' with {ddbc_context}. "
f"SQL_WCHAR requires UTF-16 encodings (utf-16le, utf-16be)"
),
)
def _validate_encoding(encoding: str) -> bool:
"""
Cached encoding validation using codecs.lookup().
Args:
encoding (str): The encoding name to validate.
Returns:
bool: True if encoding is valid, False otherwise.
Note:
Uses LRU cache to avoid repeated expensive codecs.lookup() calls.
Cache size is limited to 128 entries which should cover most use cases.
Also validates that encoding name only contains safe characters.
"""
# Basic security checks - prevent obvious attacks
if not encoding or not isinstance(encoding, str):
return False
# Check length limit (prevent DOS)
if len(encoding) > 100:
return False
# Prevent null bytes and control characters that could cause issues
if "\x00" in encoding or any(ord(c) < 32 and c not in "\t\n\r" for c in encoding):
return False
# Then check if it's a valid Python codec
try:
codecs.lookup(encoding)
return True
except LookupError:
return False
class Connection:
"""
A class to manage a connection to a database, compliant with DB-API 2.0 specifications.
This class provides methods to establish a connection to a database, create cursors,
commit transactions, roll back transactions, and close the connection. It is designed
to be used in a context where database operations are required, such as executing queries
and fetching results.
The Connection class supports the Python context manager protocol (with statement).
When used as a context manager, it will automatically close the connection when
exiting the context, ensuring proper resource cleanup.
Example usage:
with connect(connection_string) as conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO table VALUES (?)", [value])
# Connection is automatically closed when exiting the with block
For long-lived connections, use without context manager:
conn = connect(connection_string)
try:
# Multiple operations...
finally:
conn.close()
Methods:
__init__(database: str) -> None:
connect_to_db() -> None:
cursor() -> Cursor:
commit() -> None:
rollback() -> None:
close() -> None:
__enter__() -> Connection:
__exit__() -> None:
setencoding(encoding=None, ctype=None) -> None:
setdecoding(sqltype, encoding=None, ctype=None) -> None:
getdecoding(sqltype) -> dict:
set_attr(attribute, value) -> None:
"""
# DB-API 2.0 Exception attributes
# These allow users to catch exceptions using connection.Error,
# connection.ProgrammingError, etc.
Warning = Warning
Error = Error
InterfaceError = InterfaceError
DatabaseError = DatabaseError
DataError = DataError
OperationalError = OperationalError
IntegrityError = IntegrityError
InternalError = InternalError
ProgrammingError = ProgrammingError
NotSupportedError = NotSupportedError
def __init__(
self,
connection_str: str = "",
autocommit: bool = False,
attrs_before: Optional[Dict[int, Union[int, str, bytes]]] = None,
timeout: int = 0,
native_uuid: Optional[bool] = None,
token_provider: Optional["TokenProvider"] = None,
**kwargs: Any,
) -> None:
"""
Initialize the connection object with the specified connection string and parameters.
Args:
connection_str (str): The connection string to connect to.
autocommit (bool): If True, causes a commit to be performed after
each SQL statement.
attrs_before (dict, optional): Dictionary of connection attributes to set before
connection establishment. Keys are SQL_ATTR_* constants,
and values are their corresponding settings.
Use this for attributes that must be set before
connecting, such as SQL_ATTR_LOGIN_TIMEOUT,
SQL_ATTR_ODBC_CURSORS, and SQL_ATTR_PACKET_SIZE.
timeout (int): Login timeout in seconds. 0 means no timeout.
native_uuid (bool, optional): Controls whether UNIQUEIDENTIFIER columns return
uuid.UUID objects (True) or str (False) for cursors created from this connection.
None (default) defers to the module-level ``mssql_python.native_uuid`` setting (True).
token_provider (object, optional): Advanced token provider for Microsoft Entra ID
authentication. Must expose a callable ``.get_token(scope)`` method that returns
an object with a ``.token`` attribute.
This parameter is mutually exclusive with ``Authentication=`` in the connection
string and with ``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]``; supplying more than
one token source raises ``InterfaceError`` at connect time.
If ``UID``/``PWD``/``Trusted_Connection`` are also present in the connection
string they are ignored (access-token auth wins) and a warning is emitted.
.. note::
The token scope is fixed to the Azure **commercial** cloud
(``https://database.windows.net/.default``). Sovereign clouds (Azure US
Government, Azure China, Azure Germany) are **out of scope** for this
parameter — a token acquired for a different audience is rejected by SQL
Server at login. For sovereign clouds, acquire the token yourself and pass
it via ``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]`` instead.
.. note::
Connection pooling is enabled for access-token connections
(``token_provider=``, built-in ``Authentication=ActiveDirectory*``, or a raw
``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]``). The native pool key is
identity-aware — the sanitized connection string plus a per-identity suffix
(``msi:``/``acct:``/``tok:``) — so different principals sharing the same
server/database land in distinct pool buckets and are never handed each
other's authenticated connection, while same-identity reuse still benefits
from pooling.
.. note::
Token lifecycle limitations: the access token is a *pre-connect* ODBC
attribute, so it cannot be refreshed on a live connection. Long-lived
connections must be recycled by the application once the token nears expiry,
and Continuous Access Evaluation (CAE) claims challenges are not handled.
These require native driver support and are tracked as follow-up work.
Interactive credentials (e.g. ``InteractiveBrowserCredential``) block
``connect()`` until the user completes sign-in; prefer non-interactive
credentials in server contexts.
**kwargs: Additional key/value pairs for the connection string.
Returns:
None
Raises:
InterfaceError: If ``token_provider`` is misused (combined with another token
source, or lacking a valid ``.get_token`` method), or the credential returns
no valid token.
OperationalError: If acquiring a token from ``token_provider`` fails.
ValueError: If the connection string is invalid or connection fails.
This method sets up the initial state for the connection object,
preparing it for further operations such as connecting to the
database, executing queries, etc.
Example:
>>> # Setting login timeout using attrs_before
>>> import mssql_python as ms
>>> conn = ms.connect("Server=myserver;Database=mydb",
... attrs_before={ms.SQL_ATTR_LOGIN_TIMEOUT: 30})
>>> # Return native uuid.UUID objects instead of strings
>>> conn = ms.connect("Server=myserver;Database=mydb", native_uuid=True)
"""
# Store per-connection native_uuid override.
# None means "use module-level mssql_python.native_uuid".
if native_uuid is not None and not isinstance(native_uuid, bool):
raise ValueError("native_uuid must be a boolean value or None")
self._native_uuid = native_uuid
self.connection_str, parsed_params = self._construct_connection_string(
connection_str, **kwargs
)
# Shallow-copy so we never mutate the caller's dict (e.g. when the
# token_provider path injects SQL_COPT_SS_ACCESS_TOKEN). Mutating the
# caller's object would leak the access token into user state and break
# re-using the same attrs_before dict across multiple connections.
self._attrs_before = dict(attrs_before) if attrs_before else {}
# Initialize encoding settings with defaults for Python 3
# Python 3 only has str (which is Unicode), so we use utf-16le by default
self._encoding_settings = {
"encoding": "utf-16le",
"ctype": ConstantsDDBC.SQL_WCHAR.value,
}
# Initialize decoding settings with Python 3 defaults
# SQL_CHAR default uses SQL_WCHAR ctype so the ODBC driver returns
# UTF-16 data for VARCHAR columns. This avoids encoding mismatches on
# Windows where the driver returns raw bytes in the server's native
# code page (e.g. CP-1252) that may fail to decode as UTF-8.
self._decoding_settings = {
ConstantsDDBC.SQL_CHAR.value: {
"encoding": "utf-16le",
"ctype": ConstantsDDBC.SQL_WCHAR.value,
},
ConstantsDDBC.SQL_WCHAR.value: {
"encoding": "utf-16le",
"ctype": ConstantsDDBC.SQL_WCHAR.value,
},
SQL_WMETADATA: {
"encoding": "utf-16le",
"ctype": ConstantsDDBC.SQL_WCHAR.value,
},
}
# Auth type for acquiring fresh tokens at bulk copy time.
# We intentionally do NOT cache the token — a fresh one is acquired
# each time bulkcopy() is called to avoid expired-token errors.
self._auth_type = None
# Credential constructor kwargs (e.g. user-assigned MSI client_id)
# captured at __init__ time before remove_sensitive_params strips UID
# from self.connection_str. bulkcopy() re-uses these when acquiring a
# fresh token; re-parsing self.connection_str at that point would miss
# them because UID is already gone.
self._credential_kwargs: Optional[Dict[str, str]] = None
# User-supplied token provider for custom Entra ID authentication.
# Stored so bulk copy can call .get_token() for a fresh JWT later.
self._token_provider: Optional["TokenProvider"] = None
# POSIX timestamp (seconds) at which the current access token expires,
# captured from the credential's AccessToken result. None when unknown.
# The token is a pre-connect ODBC attribute and cannot be refreshed on
# a live connection — this is exposed for diagnostics/logging only.
# A custom token_provider may report a float POSIX timestamp, so the
# hint is Optional[float] (int is accepted under the numeric tower).
self._token_expires_on: Optional[float] = None
# Composite, identity-aware pool key. Empty means "key the native pool
# on the connection string" (legacy behavior, used for non-token auth).
# For Entra access-token auth it is set to connStr + identity so that
# distinct identities never share a pooled connection.
self._pool_key: str = ""
# Optional deferred-attrs callback handed to the native layer. When set,
# native invokes it *only* when it actually opens a physical connection
# (a pool miss or a non-pooled connect), so a same-identity pool hit
# skips token acquisition entirely. None means "no deferred
# token" — the token (if any) is already in self._attrs_before.
#
# NOTE: This is an internal, private callback and is intentionally NOT
# the public ``token_provider=`` credential parameter. It returns the
# full connect-attrs dict lazily; hence the distinct name
# ``_token_factory``.
self._token_factory = None
# Custom token_provider= parameter — takes priority, mutually exclusive
# with Authentication= in the connection string.
if token_provider is not None:
self._configure_token_provider(token_provider, parsed_params)
# Handle Entra ID authentication if specified.
# The parsed dict is used directly — no re-parsing of the connection string.
elif _KEY_AUTHENTICATION in parsed_params:
auth_type = process_auth_parameters(parsed_params)
if auth_type:
# Capture credential kwargs (e.g. user-assigned MSI client_id)
# from the parsed dict *before* remove_sensitive_params strips UID.
credential_kwargs: Optional[Dict[str, str]] = None
if auth_type == _AuthInternal.MSI:
uid = (parsed_params.get(_KEY_UID) or "").strip()
if uid:
credential_kwargs = {"client_id": uid}
# Strip sensitive params and rebuild the connection string.
sanitized = remove_sensitive_params(parsed_params)
self.connection_str = _ConnectionStringBuilder(sanitized).build()
self._credential_kwargs = credential_kwargs
# Make the pool key identity-aware so two callers using the
# same server but different Entra identities never reuse each
# other's authenticated connection. auth_type here
# is the process_auth_parameters result, which is truthy only
# for the token-bearing types (default/devicecode/msi/
# interactive-non-Windows); ServicePrincipal and Windows
# Interactive return None and keep their identity in the
# connection string, so they stay on the legacy connStr key.
#
# First try to derive the identity *without* a token. For MSI
# the client/object id comes straight from the params, so the
# pool key is known before any token exists — which lets us
# defer token acquisition to a provider callback that native
# invokes only on a pool miss.
#
# The factory returns ``(attrs, expires_on)``: the connect-attrs
# dict plus the token's POSIX-epoch expiry (or None). Native
# stores the expiry so it can refresh/discard a pooled
# connection whose token is near expiry on checkout.
token_attr = ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value
base_attrs = self._attrs_before
def _acquire_token_info():
# DB-API boundary: get_auth_token_info fails closed by
# letting the underlying Azure error propagate as a
# ValueError (unsupported auth type) or RuntimeError
# (credential/network/auth failure). Re-wrap those as a
# DB-API 2.0 InterfaceError so every auth failure surfaced
# from connect() / the token factory is a consistent,
# catchable driver exception rather than a bare RuntimeError.
try:
return get_auth_token_info(auth_type, credential_kwargs)
except (RuntimeError, ValueError) as e:
raise InterfaceError(
driver_error=(
"Failed to acquire an Entra ID access token for "
f"authentication type '{auth_type}': {e}"
),
ddbc_error=str(e),
) from e
def _make_token_factory(expected_account: Optional[str] = None):
# Build the deferred connect-attrs provider handed to native.
# Native invokes the returned callable only when it actually
# opens a physical connection (a pool miss, non-pooled
# connect, or near-expiry refresh on checkout), so a
# same-identity pool hit never pays for a token.
#
# ``expected_account`` binds an account-keyed (``acct:``)
# pool to the exact account it was keyed on: the shared
# interactive/device-code credential can silently switch
# signed-in accounts between pooling and a later refresh, and
# opening a *different* principal's connection inside this
# pool would hand a caller a connection authenticated as the
# wrong account. MSI pools pass ``None`` (their identity is
# fixed by params, not by a mutable signed-in account).
def _token_factory():
attrs = dict(base_attrs)
info = _acquire_token_info()
if info and info.token_struct:
if (
expected_account is not None
and info.home_account_id != expected_account
):
# Fail closed: the signed-in account changed out
# from under this account-keyed pool. Refuse
# rather than authenticate as the new principal.
raise InterfaceError(
driver_error=(
"The signed-in account changed between "
"pooling and connect for authentication "
f"type '{auth_type}'; refusing to open a "
"connection for a different account in "
"this pool."
),
ddbc_error="Account mismatch in token factory.",
)
attrs[token_attr] = info.token_struct
return attrs, info.expires_on
# Fail closed: a token-backed pool must never open a
# physical connection without the token it is meant to
# carry. get_auth_token_info already raises when
# acquisition fails; this guards the empty-token edge so
# native never connects with Authentication= stripped.
raise InterfaceError(
driver_error=(
"Unable to acquire an Entra ID access token for "
f"authentication type '{auth_type}'."
),
ddbc_error="Token factory produced no usable token.",
)
return _token_factory
identity = compute_identity_key(auth_type, credential_kwargs)
if identity:
# A real connection string can
# never contain \0, so the composite key can never collide
# with a bare connStr pool key. std::u16string map keys hold
# embedded NULs fine and the key is never used as a C string.
self._pool_key = self.connection_str + "\x00" + identity
# Lazy token acquisition: native invokes this only
# when it opens a physical connection, so same-identity pool
# hits never pay for a token. MSI identity is param-derived,
# so there is no signed-in account to bind.
self._token_factory = _make_token_factory()
else:
# Token/account-dependent identity: acquire once to derive
# the key. Interactive / Device-code yield a stable
# home_account_id (key ``acct:``) so subsequent acquisitions
# can be deferred to the factory (silent refresh reuses the
# pool). DefaultAzureCredential / raw token key on the token
# hash (``tok:``); the pooled connection is bound to that
# exact token, so it is kept in attrs_before with no factory.
info = _acquire_token_info()
token = info.token_struct if info else None
home_account_id = info.home_account_id if info else None
identity = compute_identity_key(
auth_type,
credential_kwargs,
token_struct=token,
home_account_id=home_account_id,
)
if identity:
self._pool_key = self.connection_str + "\x00" + identity
if identity and identity.startswith("acct:"):
# Account-stable key: safe to defer to the factory so a
# same-account pool hit skips token acquisition and a
# near-expiry checkout can refresh silently. Bind the
# factory to this exact account so a concurrent sign-in
# that flips the shared credential's account can never
# open a different principal's connection in this pool.
self._token_factory = _make_token_factory(expected_account=home_account_id)
elif token:
# Token-hash key: bind the pooled connection to this
# exact token so its hash always matches the pool key.
# No token factory is attached, so this pool is NOT
# expiry-aware — the near-expiry refresh in the native
# layer only runs for factory-backed (msi:/acct:) pools.
# A driver-acquired DAC/raw token is reused until the
# connection dies; see the pooling notes in the README.
self._attrs_before[token_attr] = token
else:
# Fail closed: a token-backed auth type reached here but
# we could derive neither a deferred factory nor an
# eager token, so connecting now would strip
# Authentication= and open with no token (potentially
# authenticating as an unintended identity). Surface a
# clear error instead of silently falling through.
raise InterfaceError(
driver_error=(
"Unable to acquire an Entra ID access token for "
f"authentication type '{auth_type}'."
),
ddbc_error="Token acquisition returned no usable token.",
)
# Store auth type so bulkcopy() can acquire a fresh token later.
# On Windows Interactive, process_auth_parameters returns None
# (DDBC handles auth natively), so fall back to extract_auth_type.
self._auth_type = auth_type or extract_auth_type(parsed_params)
self._closed = False
self._timeout = timeout
# Using WeakSet which automatically removes cursors when they are no
# longer in use
# It is a set that holds weak references to its elements.
# When an object is only weakly referenced, it can be garbage
# collected even if it's still in the set.
# It prevents memory leaks by ensuring that cursors are cleaned up
# when no longer in use without requiring explicit deletion.
# TODO: Think and implement scenarios for multi-threaded access
# to cursors
self._cursors = weakref.WeakSet()
# Initialize output converters dictionary and its lock for thread safety
self._output_converters = {}
self._converters_lock = threading.Lock()
# Initialize encoding/decoding settings lock for thread safety
# This lock protects both _encoding_settings and _decoding_settings dictionaries
# from concurrent modification. We use a simple Lock (not RLock) because:
# - Write operations (setencoding/setdecoding) replace the entire dict atomically
# - Read operations (getencoding/getdecoding) return a copy, so they're safe
# - No recursive locking is needed in our usage pattern
# This is more performant than RLock for the multiple-readers-single-writer pattern
self._encoding_lock = threading.Lock()
# Initialize search escape character
self._searchescape = None
# Safety net for the raw access-token pattern: a caller may pass
# SQL_COPT_SS_ACCESS_TOKEN directly in attrs_before with no
# Authentication= keyword (the documented msodbcsql raw-token pattern),
# or via the public token_provider= API. That path never runs the
# identity-key logic above, so without this guard the pool key would
# stay empty and two callers with different raw tokens against the same
# server would share a pool — handing user B user A's authenticated
# connection on a pool hit. Bind the pool key to the token hash so
# distinct tokens never collide (upholds the "a token is present =>
# key is never the bare connStr" invariant).
if not self._pool_key:
_raw_token = self._attrs_before.get(ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value)
if _raw_token is not None and not isinstance(_raw_token, (bytes, bytearray)):
# Fail closed: an access token supplied as anything other than
# raw bytes (e.g. a str) cannot be hashed into an identity-aware
# pool key, so it would fall through with the bare connStr key
# and two callers passing different str tokens against the same
# server could share a pooled, authenticated connection. Reject
# it up front with a clear DB-API error instead of relying on
# ODBC to mangle/reject the byte-struct downstream. The native
# setAttribute() enforces the same rule, so the invariant holds
# at both boundaries.
raise InterfaceError(
driver_error=(
"SQL_COPT_SS_ACCESS_TOKEN must be supplied as bytes (the "
"raw [length][UTF-16LE token] struct), not "
f"{type(_raw_token).__name__}."
),
ddbc_error="Non-binary access token attribute rejected.",
)
if isinstance(_raw_token, (bytes, bytearray)):
# Freeze a mutable bytearray token to immutable bytes ONCE and
# store it back, so the pool-key hash below and the later native
# connect both read the exact same value. Hashing the bytearray
# and letting native read it separately would be a TOCTOU: a
# caller mutating the bytearray in between would bind the pooled
# connection to a key that no longer matches its token.
_frozen_token = bytes(_raw_token)
self._attrs_before[ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value] = _frozen_token
# This raw token has no param-derivable identity, so key it on
# the token hash directly.
_token_identity = compute_token_identity(_frozen_token)
if _token_identity:
self._pool_key = self.connection_str + "\x00" + _token_identity
# Auto-enable pooling if user never called
if not PoolingManager.is_initialized():
PoolingManager.enable()
self._pooling = PoolingManager.is_enabled()
try:
self._conn = ddbc_bindings.Connection(
self.connection_str,
self._pooling,
self._attrs_before,
self._pool_key,
self._token_factory,
)
except RuntimeError as e:
_raise_connection_error(e)
self.setautocommit(autocommit)
# Register this connection for cleanup before Python shutdown
# This ensures ODBC handles are freed in correct order, preventing leaks
try:
if hasattr(mssql_python, "_register_connection"):
mssql_python._register_connection(self)
except AttributeError as e:
# If registration fails, continue - cleanup will still happen via __del__
logger.warning(
f"Failed to register connection for shutdown cleanup: {type(e).__name__}: {e}"
)
except Exception as e:
# Catch any other unexpected errors during registration
logger.error(
f"Unexpected error during connection registration: {type(e).__name__}: {e}"
)
def _configure_token_provider(
self, token_provider: "TokenProvider", parsed_params: Dict[str, str]
) -> None:
"""Validate a custom ``token_provider`` and wire it for pooled auth.
Validates that ``token_provider`` is not combined with another token
source and exposes a ``get_token()`` method, strips sensitive params
from the connection string, and acquires a token once up front so an
invalid credential fails fast at connect() and the expiry is captured.
The acquired token is placed in ``attrs_before``; the pool is keyed on
the token hash (``tok:``) by the safety net in ``__init__`` so distinct
tokens never share a pooled connection. Mutually exclusive with
``Authentication=`` and a manual ``attrs_before`` access token.
Raises:
InterfaceError: If ``token_provider`` is combined with another token
source, or lacks a ``get_token(scope)`` method.
OperationalError: If acquiring a token from ``token_provider`` fails.
"""
if _KEY_AUTHENTICATION in parsed_params:
raise InterfaceError(
driver_error=(
"Cannot specify both 'token_provider' parameter and "
"'Authentication' in the connection string. "
"Use one or the other."
),
ddbc_error="",
)
if ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value in self._attrs_before:
raise InterfaceError(
driver_error=(
"Cannot specify both 'token_provider' parameter and "
"attrs_before[SQL_COPT_SS_ACCESS_TOKEN]. "
"Use one token source."
),
ddbc_error="",
)
get_token = getattr(token_provider, "get_token", None)
if not callable(get_token):
raise InterfaceError(
driver_error=(
f"token_provider must have a .get_token() method. "
f"Got {type(token_provider).__name__}."
),
ddbc_error="",
)
# The get_token() signature is NOT inspected here: inspect.signature()
# is unreliable for partial/decorated/C-extension callables and would
# produce false warnings on valid credentials. The actual call is the
# source of truth — _get_token_from_credential turns a bad signature
# (TypeError) into a clear InterfaceError.
from mssql_python.auth import acquire_token_from_credential, _user_facing_stacklevel
# access-token auth ignores UID/PWD/Trusted_Connection — warn so the
# user is not surprised that those credentials are silently dropped.
dropped = [
key for key in (_KEY_UID, _KEY_PWD, _KEY_TRUSTED_CONNECTION) if key in parsed_params
]
if dropped:
warnings.warn(
"token_provider is set, so the following connection-string "
f"credential(s) are ignored: {', '.join(sorted(dropped))}. "
"Remove them to silence this warning.",
UserWarning,
# Point the warning at the caller's own code rather than this
# internal helper, regardless of call depth (connect() vs a
# direct Connection()).
stacklevel=_user_facing_stacklevel(),
)
self._token_provider = token_provider
# Strip sensitive params (UID/PWD/Trusted_Connection) since access-token
# auth is used — same as the Authentication= path. Do this BEFORE
# building the pool key so the key is derived from the exact connection
# string native will connect with.
sanitized = remove_sensitive_params(parsed_params)
self.connection_str = _ConnectionStringBuilder(sanitized).build()
# Acquire the token once, up front. This validates the credential so an
# invalid one fails fast at connect() (raising InterfaceError/
# OperationalError here), captures the expiry for diagnostics, and fires
# the already-expired-token warning. The token is placed directly in
# attrs_before; the identity-aware safety net in __init__ then keys the
# pool on the token hash (``tok:``).
#
# NOTE: a custom token_provider is keyed on the token it mints, NOT on
# the provider object. Object-identity keying would be unsafe: a mutable
# credential (e.g. AzureCliCredential, which follows whoever is logged
# into the az CLI) can represent different principals over its lifetime,
# yet a same-object pool hit skips re-acquisition — so a caller could be
# handed a connection authenticated as a stale principal. Token-hash
# keying re-derives identity from the actual token on every physical
# connect, so a principal change always lands in a distinct pool. The
# trade-off is weaker reuse (a rotated token opens a new bucket, which
# the native idle sweep later evicts) and no expiry-aware refresh — the
# pooled connection is reused until it dies. See the pooling notes in
# the README.
token, token_expires_on = acquire_token_from_credential(token_provider)
self._token_expires_on = token_expires_on
self._attrs_before[ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value] = token
def _construct_connection_string(
self, connection_str: str = "", **kwargs: Any
) -> Tuple[str, Dict[str, str]]:
"""
Construct the connection string by parsing, validating, and merging parameters.
1. Parse and validate the base connection_str (validates against allowlist)
2. Normalize parameter names (e.g., addr/address -> Server, uid -> UID)
3. Merge kwargs (which override connection_str params after normalization)
4. Add Driver and APP (always controlled by the driver)
5. Build and return the final connection string + parameter dictionary
Args:
connection_str (str): The base connection string.
**kwargs: Additional key/value pairs for the connection string.
Returns:
Tuple[str, Dict[str, str]]: The constructed connection string and
the normalized parameter dictionary.
"""
# Reject embedded NUL (\x00) up front, for both the base string and every
# kwargs value. The ODBC layer terminates the connection string at the
# first NUL (SQL_NTS), so anything after it is silently dropped; worse,
# the identity-aware pool key joins the connection string and the
# per-identity discriminator with a NUL separator, so a NUL smuggled into
# a value could forge or collide pool keys. Fail closed at this Python
# boundary rather than relying on downstream truncation.
if isinstance(connection_str, str) and "\x00" in connection_str:
raise InterfaceError(
driver_error="Connection string must not contain a NUL (\\x00) character.",
ddbc_error="Embedded NUL in connection string.",
)
for _key, _value in kwargs.items():
if isinstance(_value, str) and "\x00" in _value:
raise InterfaceError(
driver_error=(
f"Connection parameter '{_key}' must not contain a NUL "
"(\\x00) character."
),
ddbc_error="Embedded NUL in connection parameter.",
)
# Step 1: Parse base connection string with allowlist validation
# The parser validates everything: unknown params, reserved params, duplicates, syntax
parser = _ConnectionStringParser(validate_keywords=True)
parsed_params = parser._parse(connection_str)
# Step 2: Normalize parameter names (e.g., addr/address -> Server, uid -> UID)
# This handles synonym mapping and deduplication via normalized keys
normalized_params = _ConnectionStringParser._normalize_params(
parsed_params, warn_rejected=False
)
# Step 3: Process kwargs and merge with normalized_params
# kwargs override connection string values (processed after, so they take precedence)
for key, value in kwargs.items():
normalized_key = _ConnectionStringParser.normalize_key(key)
if normalized_key:
# Driver and APP are reserved - raise error if user tries to set them
if normalized_key in _RESERVED_PARAMETERS:
raise ValueError(
f"Connection parameter '{key}' is reserved and controlled by the driver. "
f"It cannot be set by the user."
)
# kwargs override any existing values from connection string
normalized_params[normalized_key] = str(value)
else:
logger.warning(f"Ignoring unknown connection parameter from kwargs: {key}")
# Step 4: Add Driver and APP (always controlled by the driver).
normalized_params["Driver"] = "ODBC Driver 18 for SQL Server"
normalized_params["APP"] = "MSSQL-Python"
# Step 5: Build final connection string
conn_str = _ConnectionStringBuilder(normalized_params).build()
logger.info("Final connection string: %s", sanitize_connection_string(conn_str))
return conn_str, normalized_params
@property
def timeout(self) -> int:
"""
Get the current query timeout setting in seconds.
Returns:
int: The timeout value in seconds. Zero means no timeout (wait indefinitely).
"""
return self._timeout
@timeout.setter
def timeout(self, value: int) -> None:
"""
Set the query timeout for all operations performed by this connection.
Args:
value (int): The timeout value in seconds. Zero means no timeout.
Returns:
None
Note:
This timeout applies to all cursors created from this connection.
It cannot be changed for individual cursors or SQL statements.
If a query timeout occurs, an OperationalError exception will be raised.
"""
if not isinstance(value, int):
raise TypeError("Timeout must be an integer")
if value < 0:
raise ValueError("Timeout cannot be negative")
self._timeout = value
logger.info(f"Query timeout set to {value} seconds")
@property
def autocommit(self) -> bool:
"""
Return the current autocommit mode of the connection.
Returns:
bool: True if autocommit is enabled, False otherwise.
"""
try:
return self._conn.get_autocommit()
except RuntimeError as e:
_raise_connection_error(e)
@autocommit.setter
def autocommit(self, value: bool) -> None:
"""
Set the autocommit mode of the connection.
Args:
value (bool): True to enable autocommit, False to disable it.
Returns:
None
"""
self.setautocommit(value)
logger.info("Autocommit mode set to %s.", value)
@property
def closed(self) -> bool:
"""
Returns True if the connection is closed, False otherwise.
This property indicates whether close() was explicitly called on
the connection. Note that this does not indicate whether the
connection is healthy/alive - if a timeout or network issue breaks
the connection, closed would still be False until close() is
explicitly called.
Returns:
bool: True if the connection is closed, False otherwise.
"""
return self._closed
def setautocommit(self, value: bool = False) -> None:
"""
Set the autocommit mode of the connection.
Args:
value (bool): True to enable autocommit, False to disable it.
Returns:
None
Raises: