mssql-python 1.16.0__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2357 @@
1
+ """
2
+ Copyright (c) Microsoft Corporation.
3
+ Licensed under the MIT license.
4
+ This module defines the Connection class, which is used to manage a connection to a database.
5
+ The class provides methods to establish a connection, create cursors, commit transactions,
6
+ roll back transactions, and close the connection.
7
+ Resource Management:
8
+ - All cursors created from this connection are tracked internally.
9
+ - When close() is called on the connection, all open cursors are automatically closed.
10
+ - Do not use any cursor after the connection is closed; doing so will raise an exception.
11
+ - Cursors are also cleaned up automatically when no longer referenced, to prevent memory leaks.
12
+ """
13
+
14
+ import weakref
15
+ import re
16
+ import codecs
17
+ import warnings
18
+ import struct
19
+ from types import MappingProxyType
20
+ from typing import Any, Dict, Optional, Union, List, Tuple, Callable, Protocol, TYPE_CHECKING
21
+ import threading
22
+
23
+ import mssql_python
24
+ from mssql_python.cursor import Cursor
25
+ from mssql_python.helpers import (
26
+ sanitize_user_input,
27
+ validate_attribute_value,
28
+ )
29
+ from mssql_python.connection_string_parser import sanitize_connection_string
30
+ from mssql_python.logging import logger
31
+ from mssql_python import ddbc_bindings
32
+ from mssql_python.pooling import PoolingManager
33
+ from mssql_python.odbc_provider import ProviderManager
34
+ from mssql_python.exceptions import (
35
+ Warning, # pylint: disable=redefined-builtin
36
+ Error,
37
+ InterfaceError,
38
+ DatabaseError,
39
+ DataError,
40
+ OperationalError,
41
+ IntegrityError,
42
+ InternalError,
43
+ ProgrammingError,
44
+ NotSupportedError,
45
+ sqlstate_to_exception,
46
+ )
47
+ from mssql_python.auth import (
48
+ extract_auth_type,
49
+ process_auth_parameters,
50
+ remove_sensitive_params,
51
+ get_auth_token_info,
52
+ compute_identity_key,
53
+ compute_token_identity,
54
+ )
55
+ from mssql_python.constants import ConstantsDDBC, GetInfoConstants
56
+ from mssql_python.connection_string_parser import _ConnectionStringParser
57
+ from mssql_python.connection_string_builder import _ConnectionStringBuilder
58
+ from mssql_python.constants import (
59
+ _RESERVED_PARAMETERS,
60
+ _KEY_AUTHENTICATION,
61
+ _KEY_UID,
62
+ _KEY_PWD,
63
+ _KEY_TRUSTED_CONNECTION,
64
+ _AuthInternal,
65
+ )
66
+
67
+ if TYPE_CHECKING:
68
+ from mssql_python.row import Row
69
+
70
+
71
+ class TokenProvider(Protocol):
72
+ """Structural type for the ``token_provider`` parameter.
73
+
74
+ Any object exposing a ``get_token(scope)`` method that returns an object
75
+ with a ``.token`` attribute (the raw JWT string) satisfies this protocol.
76
+ It is intentionally broader than ``azure.core.credentials.TokenCredential``
77
+ -- whose ``get_token`` requires the ``(*scopes, **kwargs)`` shape -- so that
78
+ a minimal ``get_token(scope)`` implementation (for example, a thin wrapper
79
+ around a token obtained from Microsoft Fabric's ``mssparkutils``) is
80
+ accepted by static type checkers, matching the documented contract. Every
81
+ ``azure-identity`` credential (``DefaultAzureCredential``,
82
+ ``AzureCliCredential``, ...) also conforms.
83
+ """
84
+
85
+ def get_token(self, scope: str) -> Any:
86
+ """Return an object with a ``.token`` attribute for ``scope``."""
87
+ ...
88
+
89
+
90
+ # Add SQL_WMETADATA constant for metadata decoding configuration
91
+ SQL_WMETADATA: int = -99 # Special flag for column name decoding
92
+ INFO_TYPE_STRING_THRESHOLD: int = 10000 # Legacy fallback for unlisted information types
93
+
94
+ # ODBC integers have fixed widths and native byte order; handles are pointer-sized.
95
+ _SQLUSMALLINT = struct.Struct("=H")
96
+ _SQLUINTEGER = struct.Struct("=I")
97
+ _SQLPOINTER = struct.Struct("P")
98
+
99
+ # SQLGetInfoW return types. Only type information is shared, never connection metadata.
100
+ _GETINFO_RETURN_TYPES = MappingProxyType(
101
+ {
102
+ GetInfoConstants.SQL_DATA_SOURCE_NAME.value: str,
103
+ GetInfoConstants.SQL_DATABASE_NAME.value: str,
104
+ GetInfoConstants.SQL_DRIVER_NAME.value: str,
105
+ GetInfoConstants.SQL_DRIVER_VER.value: str,
106
+ GetInfoConstants.SQL_SERVER_NAME.value: str,
107
+ GetInfoConstants.SQL_USER_NAME.value: str,
108
+ GetInfoConstants.SQL_DRIVER_ODBC_VER.value: str,
109
+ GetInfoConstants.SQL_IDENTIFIER_QUOTE_CHAR.value: str,
110
+ GetInfoConstants.SQL_CATALOG_NAME_SEPARATOR.value: str,
111
+ GetInfoConstants.SQL_CATALOG_TERM.value: str,
112
+ GetInfoConstants.SQL_SCHEMA_TERM.value: str,
113
+ GetInfoConstants.SQL_TABLE_TERM.value: str,
114
+ GetInfoConstants.SQL_KEYWORDS.value: str,
115
+ GetInfoConstants.SQL_PROCEDURE_TERM.value: str,
116
+ GetInfoConstants.SQL_SPECIAL_CHARACTERS.value: str,
117
+ GetInfoConstants.SQL_SEARCH_PATTERN_ESCAPE.value: str,
118
+ GetInfoConstants.SQL_ACCESSIBLE_PROCEDURES.value: str,
119
+ GetInfoConstants.SQL_ACCESSIBLE_TABLES.value: str,
120
+ GetInfoConstants.SQL_DATA_SOURCE_READ_ONLY.value: str,
121
+ GetInfoConstants.SQL_EXPRESSIONS_IN_ORDERBY.value: str,
122
+ GetInfoConstants.SQL_LIKE_ESCAPE_CLAUSE.value: str,
123
+ GetInfoConstants.SQL_MULTIPLE_ACTIVE_TXN.value: str,
124
+ GetInfoConstants.SQL_NEED_LONG_DATA_LEN.value: str,
125
+ GetInfoConstants.SQL_PROCEDURES.value: str,
126
+ GetInfoConstants.SQL_CATALOG_NAME.value: str,
127
+ GetInfoConstants.SQL_COLUMN_ALIAS.value: str,
128
+ GetInfoConstants.SQL_DESCRIBE_PARAMETER.value: str,
129
+ GetInfoConstants.SQL_ORDER_BY_COLUMNS_IN_SELECT.value: str,
130
+ GetInfoConstants.SQL_OUTER_JOINS.value: str,
131
+ GetInfoConstants.SQL_MULT_RESULT_SETS.value: str,
132
+ GetInfoConstants.SQL_DRIVER_HLIB.value: _SQLPOINTER,
133
+ GetInfoConstants.SQL_DRIVER_HENV.value: _SQLPOINTER,
134
+ GetInfoConstants.SQL_DRIVER_HDBC.value: _SQLPOINTER,
135
+ GetInfoConstants.SQL_SQL_CONFORMANCE.value: _SQLUINTEGER,
136
+ GetInfoConstants.SQL_IDENTIFIER_CASE.value: _SQLUSMALLINT,
137
+ GetInfoConstants.SQL_SUBQUERIES.value: _SQLUINTEGER,
138
+ GetInfoConstants.SQL_CORRELATION_NAME.value: _SQLUSMALLINT,
139
+ GetInfoConstants.SQL_CATALOG_USAGE.value: _SQLUINTEGER,
140
+ GetInfoConstants.SQL_SCHEMA_USAGE.value: _SQLUINTEGER,
141
+ GetInfoConstants.SQL_TXN_CAPABLE.value: _SQLUSMALLINT,
142
+ GetInfoConstants.SQL_TXN_ISOLATION_OPTION.value: _SQLUINTEGER,
143
+ GetInfoConstants.SQL_DEFAULT_TXN_ISOLATION.value: _SQLUINTEGER,
144
+ GetInfoConstants.SQL_NUMERIC_FUNCTIONS.value: _SQLUINTEGER,
145
+ GetInfoConstants.SQL_STRING_FUNCTIONS.value: _SQLUINTEGER,
146
+ GetInfoConstants.SQL_TIMEDATE_FUNCTIONS.value: _SQLUINTEGER,
147
+ GetInfoConstants.SQL_SYSTEM_FUNCTIONS.value: _SQLUINTEGER,
148
+ GetInfoConstants.SQL_CONVERT_FUNCTIONS.value: _SQLUINTEGER,
149
+ GetInfoConstants.SQL_MAX_COLUMN_NAME_LEN.value: _SQLUSMALLINT,
150
+ GetInfoConstants.SQL_MAX_TABLE_NAME_LEN.value: _SQLUSMALLINT,
151
+ GetInfoConstants.SQL_MAX_SCHEMA_NAME_LEN.value: _SQLUSMALLINT,
152
+ GetInfoConstants.SQL_MAX_CATALOG_NAME_LEN.value: _SQLUSMALLINT,
153
+ GetInfoConstants.SQL_MAX_IDENTIFIER_LEN.value: _SQLUSMALLINT,
154
+ GetInfoConstants.SQL_MAX_STATEMENT_LEN.value: _SQLUINTEGER,
155
+ GetInfoConstants.SQL_MAX_CHAR_LITERAL_LEN.value: _SQLUINTEGER,
156
+ GetInfoConstants.SQL_MAX_BINARY_LITERAL_LEN.value: _SQLUINTEGER,
157
+ GetInfoConstants.SQL_MAX_COLUMNS_IN_TABLE.value: _SQLUSMALLINT,
158
+ GetInfoConstants.SQL_MAX_COLUMNS_IN_SELECT.value: _SQLUSMALLINT,
159
+ GetInfoConstants.SQL_MAX_COLUMNS_IN_GROUP_BY.value: _SQLUSMALLINT,
160
+ GetInfoConstants.SQL_MAX_COLUMNS_IN_ORDER_BY.value: _SQLUSMALLINT,
161
+ GetInfoConstants.SQL_MAX_COLUMNS_IN_INDEX.value: _SQLUSMALLINT,
162
+ GetInfoConstants.SQL_MAX_TABLES_IN_SELECT.value: _SQLUSMALLINT,
163
+ GetInfoConstants.SQL_MAX_CONCURRENT_ACTIVITIES.value: _SQLUSMALLINT,
164
+ GetInfoConstants.SQL_MAX_DRIVER_CONNECTIONS.value: _SQLUSMALLINT,
165
+ GetInfoConstants.SQL_MAX_ROW_SIZE.value: _SQLUINTEGER,
166
+ GetInfoConstants.SQL_MAX_USER_NAME_LEN.value: _SQLUSMALLINT,
167
+ GetInfoConstants.SQL_GETDATA_EXTENSIONS.value: _SQLUINTEGER,
168
+ GetInfoConstants.SQL_CURSOR_COMMIT_BEHAVIOR.value: _SQLUSMALLINT,
169
+ GetInfoConstants.SQL_CURSOR_ROLLBACK_BEHAVIOR.value: _SQLUSMALLINT,
170
+ GetInfoConstants.SQL_CURSOR_SENSITIVITY.value: _SQLUINTEGER,
171
+ GetInfoConstants.SQL_BOOKMARK_PERSISTENCE.value: _SQLUINTEGER,
172
+ GetInfoConstants.SQL_DYNAMIC_CURSOR_ATTRIBUTES1.value: _SQLUINTEGER,
173
+ GetInfoConstants.SQL_DYNAMIC_CURSOR_ATTRIBUTES2.value: _SQLUINTEGER,
174
+ GetInfoConstants.SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1.value: _SQLUINTEGER,
175
+ GetInfoConstants.SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2.value: _SQLUINTEGER,
176
+ GetInfoConstants.SQL_STATIC_CURSOR_ATTRIBUTES1.value: _SQLUINTEGER,
177
+ GetInfoConstants.SQL_STATIC_CURSOR_ATTRIBUTES2.value: _SQLUINTEGER,
178
+ GetInfoConstants.SQL_KEYSET_CURSOR_ATTRIBUTES1.value: _SQLUINTEGER,
179
+ GetInfoConstants.SQL_KEYSET_CURSOR_ATTRIBUTES2.value: _SQLUINTEGER,
180
+ GetInfoConstants.SQL_SCROLL_OPTIONS.value: _SQLUINTEGER,
181
+ GetInfoConstants.SQL_SCROLL_CONCURRENCY.value: _SQLUINTEGER,
182
+ GetInfoConstants.SQL_FETCH_DIRECTION.value: _SQLUINTEGER,
183
+ GetInfoConstants.SQL_STATIC_SENSITIVITY.value: _SQLUINTEGER,
184
+ GetInfoConstants.SQL_BATCH_SUPPORT.value: _SQLUINTEGER,
185
+ GetInfoConstants.SQL_BATCH_ROW_COUNT.value: _SQLUINTEGER,
186
+ GetInfoConstants.SQL_PARAM_ARRAY_ROW_COUNTS.value: _SQLUINTEGER,
187
+ GetInfoConstants.SQL_PARAM_ARRAY_SELECTS.value: _SQLUINTEGER,
188
+ GetInfoConstants.SQL_POSITIONED_STATEMENTS.value: _SQLUINTEGER,
189
+ GetInfoConstants.SQL_GROUP_BY.value: _SQLUSMALLINT,
190
+ GetInfoConstants.SQL_OJ_CAPABILITIES.value: _SQLUINTEGER,
191
+ GetInfoConstants.SQL_QUOTED_IDENTIFIER_CASE.value: _SQLUSMALLINT,
192
+ GetInfoConstants.SQL_CONCAT_NULL_BEHAVIOR.value: _SQLUSMALLINT,
193
+ GetInfoConstants.SQL_NULL_COLLATION.value: _SQLUSMALLINT,
194
+ GetInfoConstants.SQL_ALTER_TABLE.value: _SQLUINTEGER,
195
+ GetInfoConstants.SQL_UNION.value: _SQLUINTEGER,
196
+ GetInfoConstants.SQL_DDL_INDEX.value: _SQLUINTEGER,
197
+ GetInfoConstants.SQL_TIMEDATE_ADD_INTERVALS.value: _SQLUINTEGER,
198
+ GetInfoConstants.SQL_TIMEDATE_DIFF_INTERVALS.value: _SQLUINTEGER,
199
+ # Standard information types not currently exposed by GetInfoConstants.
200
+ 17: str, # SQL_DBMS_NAME
201
+ 18: str, # SQL_DBMS_VER
202
+ 10000: str, # SQL_XOPEN_CLI_YEAR
203
+ 10021: _SQLUINTEGER, # SQL_ASYNC_MODE
204
+ 127: _SQLUINTEGER, # SQL_CREATE_ASSERTION
205
+ }
206
+ )
207
+
208
+ # UTF-16 encoding variants that should use SQL_WCHAR by default
209
+ # Note: "utf-16" with BOM is NOT included as it's problematic for SQL_WCHAR
210
+ UTF16_ENCODINGS: frozenset[str] = frozenset(["utf-16le", "utf-16be"])
211
+
212
+ _SQLSTATE_RE = re.compile(r"^SQLSTATE:([A-Z0-9]{0,5}):(.*)", re.DOTALL)
213
+
214
+
215
+ def _raise_connection_error(e: RuntimeError) -> None:
216
+ """Map a RuntimeError from the C++ pybind layer to the correct DB-API 2.0 exception.
217
+
218
+ Connection::checkError() throws "SQLSTATE:XXXXX:<odbc_message>" so the SQLSTATE
219
+ can be mapped via sqlstate_to_exception(), consistent with cursor-level error handling.
220
+ """
221
+ error_msg = str(e)
222
+ match = _SQLSTATE_RE.match(error_msg)
223
+ if match:
224
+ sqlstate, ddbc_error = match.group(1), match.group(2)
225
+ # Handle malformed SQLSTATE prefix (empty or invalid code)
226
+ if not sqlstate or len(sqlstate) != 5:
227
+ logger.error("Connection error (malformed SQLSTATE): %s", ddbc_error)
228
+ raise OperationalError(
229
+ driver_error="Connection operation failed",
230
+ ddbc_error=ddbc_error,
231
+ ) from None
232
+ exc = sqlstate_to_exception(sqlstate, ddbc_error)
233
+ if exc is None:
234
+ logger.error("Unknown SQLSTATE %s, raising DatabaseError", sqlstate)
235
+ raise DatabaseError(
236
+ driver_error=f"An error occurred with SQLSTATE code: {sqlstate}",
237
+ ddbc_error=ddbc_error,
238
+ ) from None
239
+ logger.error("Connection error (SQLSTATE %s): %s", sqlstate, ddbc_error)
240
+ raise exc from None
241
+ # Fallback: no SQLSTATE prefix — e.g. "Connection handle not allocated"
242
+ logger.error("Connection error: %s", error_msg)
243
+ raise OperationalError(
244
+ driver_error="Connection operation failed",
245
+ ddbc_error=error_msg,
246
+ ) from None
247
+
248
+
249
+ def _validate_utf16_wchar_compatibility(
250
+ encoding: str, wchar_type: int, context: str = "SQL_WCHAR"
251
+ ) -> None:
252
+ """
253
+ Validates UTF-16 encoding compatibility with SQL_WCHAR.
254
+
255
+ Centralizes the validation logic to eliminate duplication across setencoding/setdecoding.
256
+
257
+ Args:
258
+ encoding: The encoding string (already normalized to lowercase)
259
+ wchar_type: The SQL_WCHAR constant value to check against
260
+ context: Context string for error messages ('SQL_WCHAR', 'SQL_WCHAR ctype', etc.)
261
+
262
+ Raises:
263
+ ProgrammingError: If encoding is incompatible with SQL_WCHAR
264
+ """
265
+ if encoding == "utf-16":
266
+ # UTF-16 with BOM is rejected due to byte order ambiguity
267
+ logger.warning("utf-16 with BOM rejected for %s", context)
268
+ raise ProgrammingError(
269
+ driver_error="UTF-16 with Byte Order Mark not supported for SQL_WCHAR",
270
+ ddbc_error=(
271
+ "Cannot use 'utf-16' encoding with SQL_WCHAR due to Byte Order Mark ambiguity. "
272
+ "Use 'utf-16le' or 'utf-16be' instead for explicit byte order."
273
+ ),
274
+ )
275
+ elif encoding not in UTF16_ENCODINGS:
276
+ # Non-UTF-16 encodings are not supported with SQL_WCHAR
277
+ logger.warning(
278
+ "Non-UTF-16 encoding %s attempted with %s", sanitize_user_input(encoding), context
279
+ )
280
+
281
+ # Generate context-appropriate error messages
282
+ if "ctype" in context:
283
+ driver_error = "SQL_WCHAR ctype only supports UTF-16 encodings"
284
+ ddbc_context = "SQL_WCHAR ctype"
285
+ else:
286
+ driver_error = "SQL_WCHAR only supports UTF-16 encodings"
287
+ ddbc_context = "SQL_WCHAR"
288
+
289
+ raise ProgrammingError(
290
+ driver_error=driver_error,
291
+ ddbc_error=(
292
+ f"Cannot use encoding '{encoding}' with {ddbc_context}. "
293
+ f"SQL_WCHAR requires UTF-16 encodings (utf-16le, utf-16be)"
294
+ ),
295
+ )
296
+
297
+
298
+ def _validate_encoding(encoding: str) -> bool:
299
+ """
300
+ Cached encoding validation using codecs.lookup().
301
+
302
+ Args:
303
+ encoding (str): The encoding name to validate.
304
+
305
+ Returns:
306
+ bool: True if encoding is valid, False otherwise.
307
+
308
+ Note:
309
+ Uses LRU cache to avoid repeated expensive codecs.lookup() calls.
310
+ Cache size is limited to 128 entries which should cover most use cases.
311
+ Also validates that encoding name only contains safe characters.
312
+ """
313
+ # Basic security checks - prevent obvious attacks
314
+ if not encoding or not isinstance(encoding, str):
315
+ return False
316
+
317
+ # Check length limit (prevent DOS)
318
+ if len(encoding) > 100:
319
+ return False
320
+
321
+ # Prevent null bytes and control characters that could cause issues
322
+ if "\x00" in encoding or any(ord(c) < 32 and c not in "\t\n\r" for c in encoding):
323
+ return False
324
+
325
+ # Then check if it's a valid Python codec
326
+ try:
327
+ codecs.lookup(encoding)
328
+ return True
329
+ except LookupError:
330
+ return False
331
+
332
+
333
+ class Connection:
334
+ """
335
+ A class to manage a connection to a database, compliant with DB-API 2.0 specifications.
336
+
337
+ This class provides methods to establish a connection to a database, create cursors,
338
+ commit transactions, roll back transactions, and close the connection. It is designed
339
+ to be used in a context where database operations are required, such as executing queries
340
+ and fetching results.
341
+
342
+ The Connection class supports the Python context manager protocol (with statement).
343
+ When used as a context manager, it will automatically close the connection when
344
+ exiting the context, ensuring proper resource cleanup.
345
+
346
+ Example usage:
347
+ with connect(connection_string) as conn:
348
+ cursor = conn.cursor()
349
+ cursor.execute("INSERT INTO table VALUES (?)", [value])
350
+ # Connection is automatically closed when exiting the with block
351
+
352
+ For long-lived connections, use without context manager:
353
+ conn = connect(connection_string)
354
+ try:
355
+ # Multiple operations...
356
+ finally:
357
+ conn.close()
358
+
359
+ Methods:
360
+ __init__(database: str) -> None:
361
+ connect_to_db() -> None:
362
+ cursor() -> Cursor:
363
+ commit() -> None:
364
+ rollback() -> None:
365
+ close() -> None:
366
+ __enter__() -> Connection:
367
+ __exit__() -> None:
368
+ setencoding(encoding=None, ctype=None) -> None:
369
+ setdecoding(sqltype, encoding=None, ctype=None) -> None:
370
+ getdecoding(sqltype) -> dict:
371
+ set_attr(attribute, value) -> None:
372
+ """
373
+
374
+ # DB-API 2.0 Exception attributes
375
+ # These allow users to catch exceptions using connection.Error,
376
+ # connection.ProgrammingError, etc.
377
+ Warning = Warning
378
+ Error = Error
379
+ InterfaceError = InterfaceError
380
+ DatabaseError = DatabaseError
381
+ DataError = DataError
382
+ OperationalError = OperationalError
383
+ IntegrityError = IntegrityError
384
+ InternalError = InternalError
385
+ ProgrammingError = ProgrammingError
386
+ NotSupportedError = NotSupportedError
387
+
388
+ def __init__(
389
+ self,
390
+ connection_str: str = "",
391
+ autocommit: bool = False,
392
+ attrs_before: Optional[Dict[int, Union[int, str, bytes]]] = None,
393
+ timeout: int = 0,
394
+ native_uuid: Optional[bool] = None,
395
+ token_provider: Optional["TokenProvider"] = None,
396
+ **kwargs: Any,
397
+ ) -> None:
398
+ """
399
+ Initialize the connection object with the specified connection string and parameters.
400
+
401
+ Args:
402
+ connection_str (str): The connection string to connect to.
403
+ autocommit (bool): If True, causes a commit to be performed after
404
+ each SQL statement.
405
+ attrs_before (dict, optional): Dictionary of connection attributes to set before
406
+ connection establishment. Keys are SQL_ATTR_* constants,
407
+ and values are their corresponding settings.
408
+ Use this for attributes that must be set before
409
+ connecting, such as SQL_ATTR_LOGIN_TIMEOUT,
410
+ SQL_ATTR_ODBC_CURSORS, and SQL_ATTR_PACKET_SIZE.
411
+ timeout (int): Login (connection-attempt) timeout in seconds. 0 (default)
412
+ means the driver default is used. This sets SQL_ATTR_LOGIN_TIMEOUT
413
+ before connecting and bounds the login/network connection attempt.
414
+ (Microsoft Entra ID token acquisition happens before the ODBC
415
+ connect and is not covered by this attribute.) It is distinct from
416
+ the ``Connection.timeout`` property, which is the per-statement
417
+ query timeout. An explicit ``attrs_before[SQL_ATTR_LOGIN_TIMEOUT]``
418
+ takes precedence over this value. (pyodbc migration note: pyodbc
419
+ lets a positive ``timeout=`` override ``attrs_before``; here the
420
+ explicit ``attrs_before`` entry wins.)
421
+ native_uuid (bool, optional): Controls whether UNIQUEIDENTIFIER columns return
422
+ uuid.UUID objects (True) or str (False) for cursors created from this connection.
423
+ None (default) defers to the module-level ``mssql_python.native_uuid`` setting (True).
424
+ token_provider (object, optional): Advanced token provider for Microsoft Entra ID
425
+ authentication. Must expose a callable ``.get_token(scope)`` method that returns
426
+ an object with a ``.token`` attribute.
427
+
428
+ This parameter is mutually exclusive with ``Authentication=`` in the connection
429
+ string and with ``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]``; supplying more than
430
+ one token source raises ``InterfaceError`` at connect time.
431
+
432
+ If ``UID``/``PWD``/``Trusted_Connection`` are also present in the connection
433
+ string they are ignored (access-token auth wins) and a warning is emitted.
434
+
435
+ .. note::
436
+ The token scope is fixed to the Azure **commercial** cloud
437
+ (``https://database.windows.net/.default``). Sovereign clouds (Azure US
438
+ Government, Azure China, Azure Germany) are **out of scope** for this
439
+ parameter — a token acquired for a different audience is rejected by SQL
440
+ Server at login. For sovereign clouds, acquire the token yourself and pass
441
+ it via ``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]`` instead.
442
+
443
+ .. note::
444
+ Connection pooling is enabled for access-token connections
445
+ (``token_provider=``, built-in ``Authentication=ActiveDirectory*``, or a raw
446
+ ``attrs_before[SQL_COPT_SS_ACCESS_TOKEN]``). The native pool key is
447
+ identity-aware — the sanitized connection string plus a per-identity suffix
448
+ (``msi:``/``acct:``/``tok:``) — so different principals sharing the same
449
+ server/database land in distinct pool buckets and are never handed each
450
+ other's authenticated connection, while same-identity reuse still benefits
451
+ from pooling.
452
+
453
+ .. note::
454
+ Token lifecycle limitations: the access token is a *pre-connect* ODBC
455
+ attribute, so it cannot be refreshed on a live connection. Long-lived
456
+ connections must be recycled by the application once the token nears expiry,
457
+ and Continuous Access Evaluation (CAE) claims challenges are not handled.
458
+ These require native driver support and are tracked as follow-up work.
459
+ Interactive credentials (e.g. ``InteractiveBrowserCredential``) block
460
+ ``connect()`` until the user completes sign-in; prefer non-interactive
461
+ credentials in server contexts.
462
+ **kwargs: Additional key/value pairs for the connection string.
463
+
464
+ Returns:
465
+ None
466
+
467
+ Raises:
468
+ InterfaceError: If ``token_provider`` is misused (combined with another token
469
+ source, or lacking a valid ``.get_token`` method), or the credential returns
470
+ no valid token.
471
+ OperationalError: If acquiring a token from ``token_provider`` fails.
472
+ ValueError: If the connection string is invalid or connection fails.
473
+
474
+ This method sets up the initial state for the connection object,
475
+ preparing it for further operations such as connecting to the
476
+ database, executing queries, etc.
477
+
478
+ Example:
479
+ >>> # Setting login timeout using attrs_before
480
+ >>> import mssql_python as ms
481
+ >>> conn = ms.connect("Server=myserver;Database=mydb",
482
+ ... attrs_before={ms.SQL_ATTR_LOGIN_TIMEOUT: 30})
483
+
484
+ >>> # Return native uuid.UUID objects instead of strings
485
+ >>> conn = ms.connect("Server=myserver;Database=mydb", native_uuid=True)
486
+ """
487
+ # Store per-connection native_uuid override.
488
+ # None means "use module-level mssql_python.native_uuid".
489
+ if native_uuid is not None and not isinstance(native_uuid, bool):
490
+ raise ValueError("native_uuid must be a boolean value or None")
491
+ self._native_uuid = native_uuid
492
+
493
+ self.connection_str, parsed_params = self._construct_connection_string(
494
+ connection_str, **kwargs
495
+ )
496
+ # Shallow-copy so we never mutate the caller's dict (e.g. when the
497
+ # token_provider path injects SQL_COPT_SS_ACCESS_TOKEN). Mutating the
498
+ # caller's object would leak the access token into user state and break
499
+ # re-using the same attrs_before dict across multiple connections.
500
+ self._attrs_before = dict(attrs_before) if attrs_before else {}
501
+
502
+ # Validate and apply the LOGIN/connection-attempt timeout up front —
503
+ # before any Entra/token acquisition below — so invalid input (negative,
504
+ # non-int, bool) fails fast without triggering a network or interactive
505
+ # token fetch. ``timeout`` matches pyodbc's login timeout: it sets
506
+ # SQL_ATTR_LOGIN_TIMEOUT and bounds the login/network connection attempt.
507
+ # It is distinct from Connection.timeout (the per-statement QUERY timeout,
508
+ # tracked by self._timeout and applied to cursors), which defaults to
509
+ # 0 = disabled. Only inject the login timeout when the caller asked for
510
+ # one (> 0) and did not already set it explicitly via attrs_before (an
511
+ # explicit attrs_before value wins).
512
+ self._timeout = 0
513
+ login_timeout = self._validate_timeout(timeout, kind="Login timeout")
514
+ if login_timeout > 0:
515
+ self._attrs_before.setdefault(ConstantsDDBC.SQL_ATTR_LOGIN_TIMEOUT.value, login_timeout)
516
+
517
+ # Initialize encoding settings with defaults for Python 3
518
+ # Python 3 only has str (which is Unicode), so we use utf-16le by default
519
+ self._encoding_settings = {
520
+ "encoding": "utf-16le",
521
+ "ctype": ConstantsDDBC.SQL_WCHAR.value,
522
+ }
523
+
524
+ # Initialize decoding settings with Python 3 defaults
525
+ # SQL_CHAR default uses SQL_WCHAR ctype so the ODBC driver returns
526
+ # UTF-16 data for VARCHAR columns. This avoids encoding mismatches on
527
+ # Windows where the driver returns raw bytes in the server's native
528
+ # code page (e.g. CP-1252) that may fail to decode as UTF-8.
529
+ self._decoding_settings = {
530
+ ConstantsDDBC.SQL_CHAR.value: {
531
+ "encoding": "utf-16le",
532
+ "ctype": ConstantsDDBC.SQL_WCHAR.value,
533
+ },
534
+ ConstantsDDBC.SQL_WCHAR.value: {
535
+ "encoding": "utf-16le",
536
+ "ctype": ConstantsDDBC.SQL_WCHAR.value,
537
+ },
538
+ SQL_WMETADATA: {
539
+ "encoding": "utf-16le",
540
+ "ctype": ConstantsDDBC.SQL_WCHAR.value,
541
+ },
542
+ }
543
+ self._decoding_generation = 0
544
+
545
+ # Auth type for acquiring fresh tokens at bulk copy time.
546
+ # We intentionally do NOT cache the token — a fresh one is acquired
547
+ # each time bulkcopy() is called to avoid expired-token errors.
548
+ self._auth_type = None
549
+ # Credential constructor kwargs (e.g. user-assigned MSI client_id)
550
+ # captured at __init__ time before remove_sensitive_params strips UID
551
+ # from self.connection_str. bulkcopy() re-uses these when acquiring a
552
+ # fresh token; re-parsing self.connection_str at that point would miss
553
+ # them because UID is already gone.
554
+ self._credential_kwargs: Optional[Dict[str, str]] = None
555
+ # User-supplied token provider for custom Entra ID authentication.
556
+ # Stored so bulk copy can call .get_token() for a fresh JWT later.
557
+ self._token_provider: Optional["TokenProvider"] = None
558
+ # POSIX timestamp (seconds) at which the current access token expires,
559
+ # captured from the credential's AccessToken result. None when unknown.
560
+ # The token is a pre-connect ODBC attribute and cannot be refreshed on
561
+ # a live connection — this is exposed for diagnostics/logging only.
562
+ # A custom token_provider may report a float POSIX timestamp, so the
563
+ # hint is Optional[float] (int is accepted under the numeric tower).
564
+ self._token_expires_on: Optional[float] = None
565
+
566
+ # Composite, identity-aware pool key. Empty means "key the native pool
567
+ # on the connection string" (legacy behavior, used for non-token auth).
568
+ # For Entra access-token auth it is set to connStr + identity so that
569
+ # distinct identities never share a pooled connection.
570
+ self._pool_key: str = ""
571
+
572
+ # Optional deferred-attrs callback handed to the native layer. When set,
573
+ # native invokes it *only* when it actually opens a physical connection
574
+ # (a pool miss or a non-pooled connect), so a same-identity pool hit
575
+ # skips token acquisition entirely. None means "no deferred
576
+ # token" — the token (if any) is already in self._attrs_before.
577
+ #
578
+ # NOTE: This is an internal, private callback and is intentionally NOT
579
+ # the public ``token_provider=`` credential parameter. It returns the
580
+ # full connect-attrs dict lazily; hence the distinct name
581
+ # ``_token_factory``.
582
+ self._token_factory = None
583
+
584
+ # Custom token_provider= parameter — takes priority, mutually exclusive
585
+ # with Authentication= in the connection string.
586
+ if token_provider is not None:
587
+ self._configure_token_provider(token_provider, parsed_params)
588
+
589
+ # Handle Entra ID authentication if specified.
590
+ # The parsed dict is used directly — no re-parsing of the connection string.
591
+ elif _KEY_AUTHENTICATION in parsed_params:
592
+ auth_type = process_auth_parameters(parsed_params)
593
+
594
+ if auth_type:
595
+ # Capture credential kwargs (e.g. user-assigned MSI client_id)
596
+ # from the parsed dict *before* remove_sensitive_params strips UID.
597
+ credential_kwargs: Optional[Dict[str, str]] = None
598
+ if auth_type == _AuthInternal.MSI:
599
+ uid = (parsed_params.get(_KEY_UID) or "").strip()
600
+ if uid:
601
+ credential_kwargs = {"client_id": uid}
602
+
603
+ # Strip sensitive params and rebuild the connection string.
604
+ sanitized = remove_sensitive_params(parsed_params)
605
+ self.connection_str = _ConnectionStringBuilder(sanitized).build()
606
+ self._credential_kwargs = credential_kwargs
607
+
608
+ # Make the pool key identity-aware so two callers using the
609
+ # same server but different Entra identities never reuse each
610
+ # other's authenticated connection. auth_type here
611
+ # is the process_auth_parameters result, which is truthy only
612
+ # for the token-bearing types (default/devicecode/msi/
613
+ # interactive-non-Windows); ServicePrincipal and Windows
614
+ # Interactive return None and keep their identity in the
615
+ # connection string, so they stay on the legacy connStr key.
616
+ #
617
+ # First try to derive the identity *without* a token. For MSI
618
+ # the client/object id comes straight from the params, so the
619
+ # pool key is known before any token exists — which lets us
620
+ # defer token acquisition to a provider callback that native
621
+ # invokes only on a pool miss.
622
+ #
623
+ # The factory returns ``(attrs, expires_on)``: the connect-attrs
624
+ # dict plus the token's POSIX-epoch expiry (or None). Native
625
+ # stores the expiry so it can refresh/discard a pooled
626
+ # connection whose token is near expiry on checkout.
627
+ token_attr = ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value
628
+ base_attrs = self._attrs_before
629
+
630
+ def _acquire_token_info():
631
+ # DB-API boundary: get_auth_token_info fails closed by
632
+ # letting the underlying Azure error propagate as a
633
+ # ValueError (unsupported auth type) or RuntimeError
634
+ # (credential/network/auth failure). Re-wrap those as a
635
+ # DB-API 2.0 InterfaceError so every auth failure surfaced
636
+ # from connect() / the token factory is a consistent,
637
+ # catchable driver exception rather than a bare RuntimeError.
638
+ try:
639
+ return get_auth_token_info(auth_type, credential_kwargs)
640
+ except (RuntimeError, ValueError) as e:
641
+ raise InterfaceError(
642
+ driver_error=(
643
+ "Failed to acquire an Entra ID access token for "
644
+ f"authentication type '{auth_type}': {e}"
645
+ ),
646
+ ddbc_error=str(e),
647
+ ) from e
648
+
649
+ def _make_token_factory(expected_account: Optional[str] = None):
650
+ # Build the deferred connect-attrs provider handed to native.
651
+ # Native invokes the returned callable only when it actually
652
+ # opens a physical connection (a pool miss, non-pooled
653
+ # connect, or near-expiry refresh on checkout), so a
654
+ # same-identity pool hit never pays for a token.
655
+ #
656
+ # ``expected_account`` binds an account-keyed (``acct:``)
657
+ # pool to the exact account it was keyed on: the shared
658
+ # interactive/device-code credential can silently switch
659
+ # signed-in accounts between pooling and a later refresh, and
660
+ # opening a *different* principal's connection inside this
661
+ # pool would hand a caller a connection authenticated as the
662
+ # wrong account. MSI pools pass ``None`` (their identity is
663
+ # fixed by params, not by a mutable signed-in account).
664
+ def _token_factory():
665
+ attrs = dict(base_attrs)
666
+ info = _acquire_token_info()
667
+ if info and info.token_struct:
668
+ if (
669
+ expected_account is not None
670
+ and info.home_account_id != expected_account
671
+ ):
672
+ # Fail closed: the signed-in account changed out
673
+ # from under this account-keyed pool. Refuse
674
+ # rather than authenticate as the new principal.
675
+ raise InterfaceError(
676
+ driver_error=(
677
+ "The signed-in account changed between "
678
+ "pooling and connect for authentication "
679
+ f"type '{auth_type}'; refusing to open a "
680
+ "connection for a different account in "
681
+ "this pool."
682
+ ),
683
+ ddbc_error="Account mismatch in token factory.",
684
+ )
685
+ attrs[token_attr] = info.token_struct
686
+ return attrs, info.expires_on
687
+ # Fail closed: a token-backed pool must never open a
688
+ # physical connection without the token it is meant to
689
+ # carry. get_auth_token_info already raises when
690
+ # acquisition fails; this guards the empty-token edge so
691
+ # native never connects with Authentication= stripped.
692
+ raise InterfaceError(
693
+ driver_error=(
694
+ "Unable to acquire an Entra ID access token for "
695
+ f"authentication type '{auth_type}'."
696
+ ),
697
+ ddbc_error="Token factory produced no usable token.",
698
+ )
699
+
700
+ return _token_factory
701
+
702
+ identity = compute_identity_key(auth_type, credential_kwargs)
703
+ if identity:
704
+ # A real connection string can
705
+ # never contain \0, so the composite key can never collide
706
+ # with a bare connStr pool key. std::u16string map keys hold
707
+ # embedded NULs fine and the key is never used as a C string.
708
+ self._pool_key = self.connection_str + "\x00" + identity
709
+
710
+ # Lazy token acquisition: native invokes this only
711
+ # when it opens a physical connection, so same-identity pool
712
+ # hits never pay for a token. MSI identity is param-derived,
713
+ # so there is no signed-in account to bind.
714
+ self._token_factory = _make_token_factory()
715
+ else:
716
+ # Token/account-dependent identity: acquire once to derive
717
+ # the key. Interactive / Device-code yield a stable
718
+ # home_account_id (key ``acct:``) so subsequent acquisitions
719
+ # can be deferred to the factory (silent refresh reuses the
720
+ # pool). DefaultAzureCredential / raw token key on the token
721
+ # hash (``tok:``); the pooled connection is bound to that
722
+ # exact token, so it is kept in attrs_before with no factory.
723
+ info = _acquire_token_info()
724
+ token = info.token_struct if info else None
725
+ home_account_id = info.home_account_id if info else None
726
+ identity = compute_identity_key(
727
+ auth_type,
728
+ credential_kwargs,
729
+ token_struct=token,
730
+ home_account_id=home_account_id,
731
+ )
732
+ if identity:
733
+ self._pool_key = self.connection_str + "\x00" + identity
734
+ if identity and identity.startswith("acct:"):
735
+ # Account-stable key: safe to defer to the factory so a
736
+ # same-account pool hit skips token acquisition and a
737
+ # near-expiry checkout can refresh silently. Bind the
738
+ # factory to this exact account so a concurrent sign-in
739
+ # that flips the shared credential's account can never
740
+ # open a different principal's connection in this pool.
741
+ self._token_factory = _make_token_factory(expected_account=home_account_id)
742
+ elif token:
743
+ # Token-hash key: bind the pooled connection to this
744
+ # exact token so its hash always matches the pool key.
745
+ # No token factory is attached, so this pool is NOT
746
+ # expiry-aware — the near-expiry refresh in the native
747
+ # layer only runs for factory-backed (msi:/acct:) pools.
748
+ # A driver-acquired DAC/raw token is reused until the
749
+ # connection dies; see the pooling notes in the README.
750
+ self._attrs_before[token_attr] = token
751
+ else:
752
+ # Fail closed: a token-backed auth type reached here but
753
+ # we could derive neither a deferred factory nor an
754
+ # eager token, so connecting now would strip
755
+ # Authentication= and open with no token (potentially
756
+ # authenticating as an unintended identity). Surface a
757
+ # clear error instead of silently falling through.
758
+ raise InterfaceError(
759
+ driver_error=(
760
+ "Unable to acquire an Entra ID access token for "
761
+ f"authentication type '{auth_type}'."
762
+ ),
763
+ ddbc_error="Token acquisition returned no usable token.",
764
+ )
765
+
766
+ # Store auth type so bulkcopy() can acquire a fresh token later.
767
+ # On Windows Interactive, process_auth_parameters returns None
768
+ # (DDBC handles auth natively), so fall back to extract_auth_type.
769
+ self._auth_type = auth_type or extract_auth_type(parsed_params)
770
+
771
+ self._closed = False
772
+
773
+ # Using WeakSet which automatically removes cursors when they are no
774
+ # longer in use
775
+ # It is a set that holds weak references to its elements.
776
+ # When an object is only weakly referenced, it can be garbage
777
+ # collected even if it's still in the set.
778
+ # It prevents memory leaks by ensuring that cursors are cleaned up
779
+ # when no longer in use without requiring explicit deletion.
780
+ # TODO: Think and implement scenarios for multi-threaded access
781
+ # to cursors
782
+ self._cursors = weakref.WeakSet()
783
+
784
+ # Initialize output converters dictionary and its lock for thread safety
785
+ self._output_converters = {}
786
+ self._converters_generation = 0
787
+ self._converters_lock = threading.Lock()
788
+
789
+ # Initialize encoding/decoding settings lock for thread safety
790
+ # This lock protects both _encoding_settings and _decoding_settings dictionaries
791
+ # from concurrent modification. We use a simple Lock (not RLock) because:
792
+ # - Write operations (setencoding/setdecoding) replace the entire dict atomically
793
+ # - Read operations (getencoding/getdecoding) return a copy, so they're safe
794
+ # - No recursive locking is needed in our usage pattern
795
+ # This is more performant than RLock for the multiple-readers-single-writer pattern
796
+ self._encoding_lock = threading.Lock()
797
+
798
+ # Initialize search escape character
799
+ self._searchescape = None
800
+
801
+ # Safety net for the raw access-token pattern: a caller may pass
802
+ # SQL_COPT_SS_ACCESS_TOKEN directly in attrs_before with no
803
+ # Authentication= keyword (the documented msodbcsql raw-token pattern),
804
+ # or via the public token_provider= API. That path never runs the
805
+ # identity-key logic above, so without this guard the pool key would
806
+ # stay empty and two callers with different raw tokens against the same
807
+ # server would share a pool — handing user B user A's authenticated
808
+ # connection on a pool hit. Bind the pool key to the token hash so
809
+ # distinct tokens never collide (upholds the "a token is present =>
810
+ # key is never the bare connStr" invariant).
811
+ if not self._pool_key:
812
+ _raw_token = self._attrs_before.get(ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value)
813
+ if _raw_token is not None and not isinstance(_raw_token, (bytes, bytearray)):
814
+ # Fail closed: an access token supplied as anything other than
815
+ # raw bytes (e.g. a str) cannot be hashed into an identity-aware
816
+ # pool key, so it would fall through with the bare connStr key
817
+ # and two callers passing different str tokens against the same
818
+ # server could share a pooled, authenticated connection. Reject
819
+ # it up front with a clear DB-API error instead of relying on
820
+ # ODBC to mangle/reject the byte-struct downstream. The native
821
+ # setAttribute() enforces the same rule, so the invariant holds
822
+ # at both boundaries.
823
+ raise InterfaceError(
824
+ driver_error=(
825
+ "SQL_COPT_SS_ACCESS_TOKEN must be supplied as bytes (the "
826
+ "raw [length][UTF-16LE token] struct), not "
827
+ f"{type(_raw_token).__name__}."
828
+ ),
829
+ ddbc_error="Non-binary access token attribute rejected.",
830
+ )
831
+ if isinstance(_raw_token, (bytes, bytearray)):
832
+ # Freeze a mutable bytearray token to immutable bytes ONCE and
833
+ # store it back, so the pool-key hash below and the later native
834
+ # connect both read the exact same value. Hashing the bytearray
835
+ # and letting native read it separately would be a TOCTOU: a
836
+ # caller mutating the bytearray in between would bind the pooled
837
+ # connection to a key that no longer matches its token.
838
+ _frozen_token = bytes(_raw_token)
839
+ self._attrs_before[ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value] = _frozen_token
840
+ # This raw token has no param-derivable identity, so key it on
841
+ # the token hash directly.
842
+ _token_identity = compute_token_identity(_frozen_token)
843
+ if _token_identity:
844
+ self._pool_key = self.connection_str + "\x00" + _token_identity
845
+
846
+ # Auto-enable pooling if user never called
847
+ if not PoolingManager.is_initialized():
848
+ PoolingManager.enable()
849
+ self._pooling = PoolingManager.is_enabled()
850
+
851
+ # Resolve and freeze the ODBC provider, then hand the selection to the
852
+ # native loader so it imports the matching provider package. Done here —
853
+ # after every Python-side validation and token acquisition has succeeded
854
+ # and immediately before the native driver loads — so a call that fails
855
+ # earlier never freezes the selection as a side effect; a later, corrected
856
+ # connection can then still choose a different provider without a process
857
+ # restart.
858
+ _provider = ProviderManager.ensure_available()
859
+ ddbc_bindings._set_odbc_provider(_provider)
860
+
861
+ try:
862
+ self._conn = ddbc_bindings.Connection(
863
+ self.connection_str,
864
+ self._pooling,
865
+ self._attrs_before,
866
+ self._pool_key,
867
+ self._token_factory,
868
+ )
869
+ except RuntimeError as e:
870
+ _raise_connection_error(e)
871
+ self.setautocommit(autocommit)
872
+
873
+ # Register this connection for cleanup before Python shutdown
874
+ # This ensures ODBC handles are freed in correct order, preventing leaks
875
+ try:
876
+ if hasattr(mssql_python, "_register_connection"):
877
+ mssql_python._register_connection(self)
878
+ except AttributeError as e:
879
+ # If registration fails, continue - cleanup will still happen via __del__
880
+ logger.warning(
881
+ f"Failed to register connection for shutdown cleanup: {type(e).__name__}: {e}"
882
+ )
883
+ except Exception as e:
884
+ # Catch any other unexpected errors during registration
885
+ logger.error(
886
+ f"Unexpected error during connection registration: {type(e).__name__}: {e}"
887
+ )
888
+
889
+ def _configure_token_provider(
890
+ self, token_provider: "TokenProvider", parsed_params: Dict[str, str]
891
+ ) -> None:
892
+ """Validate a custom ``token_provider`` and wire it for pooled auth.
893
+
894
+ Validates that ``token_provider`` is not combined with another token
895
+ source and exposes a ``get_token()`` method, strips sensitive params
896
+ from the connection string, and acquires a token once up front so an
897
+ invalid credential fails fast at connect() and the expiry is captured.
898
+ The acquired token is placed in ``attrs_before``; the pool is keyed on
899
+ the token hash (``tok:``) by the safety net in ``__init__`` so distinct
900
+ tokens never share a pooled connection. Mutually exclusive with
901
+ ``Authentication=`` and a manual ``attrs_before`` access token.
902
+
903
+ Raises:
904
+ InterfaceError: If ``token_provider`` is combined with another token
905
+ source, or lacks a ``get_token(scope)`` method.
906
+ OperationalError: If acquiring a token from ``token_provider`` fails.
907
+ """
908
+ if _KEY_AUTHENTICATION in parsed_params:
909
+ raise InterfaceError(
910
+ driver_error=(
911
+ "Cannot specify both 'token_provider' parameter and "
912
+ "'Authentication' in the connection string. "
913
+ "Use one or the other."
914
+ ),
915
+ ddbc_error="",
916
+ )
917
+ if ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value in self._attrs_before:
918
+ raise InterfaceError(
919
+ driver_error=(
920
+ "Cannot specify both 'token_provider' parameter and "
921
+ "attrs_before[SQL_COPT_SS_ACCESS_TOKEN]. "
922
+ "Use one token source."
923
+ ),
924
+ ddbc_error="",
925
+ )
926
+ get_token = getattr(token_provider, "get_token", None)
927
+ if not callable(get_token):
928
+ raise InterfaceError(
929
+ driver_error=(
930
+ f"token_provider must have a .get_token() method. "
931
+ f"Got {type(token_provider).__name__}."
932
+ ),
933
+ ddbc_error="",
934
+ )
935
+ # The get_token() signature is NOT inspected here: inspect.signature()
936
+ # is unreliable for partial/decorated/C-extension callables and would
937
+ # produce false warnings on valid credentials. The actual call is the
938
+ # source of truth — _get_token_from_credential turns a bad signature
939
+ # (TypeError) into a clear InterfaceError.
940
+ from mssql_python.auth import acquire_token_from_credential, _user_facing_stacklevel
941
+
942
+ # access-token auth ignores UID/PWD/Trusted_Connection — warn so the
943
+ # user is not surprised that those credentials are silently dropped.
944
+ dropped = [
945
+ key for key in (_KEY_UID, _KEY_PWD, _KEY_TRUSTED_CONNECTION) if key in parsed_params
946
+ ]
947
+ if dropped:
948
+ warnings.warn(
949
+ "token_provider is set, so the following connection-string "
950
+ f"credential(s) are ignored: {', '.join(sorted(dropped))}. "
951
+ "Remove them to silence this warning.",
952
+ UserWarning,
953
+ # Point the warning at the caller's own code rather than this
954
+ # internal helper, regardless of call depth (connect() vs a
955
+ # direct Connection()).
956
+ stacklevel=_user_facing_stacklevel(),
957
+ )
958
+ self._token_provider = token_provider
959
+
960
+ # Strip sensitive params (UID/PWD/Trusted_Connection) since access-token
961
+ # auth is used — same as the Authentication= path. Do this BEFORE
962
+ # building the pool key so the key is derived from the exact connection
963
+ # string native will connect with.
964
+ sanitized = remove_sensitive_params(parsed_params)
965
+ self.connection_str = _ConnectionStringBuilder(sanitized).build()
966
+
967
+ # Acquire the token once, up front. This validates the credential so an
968
+ # invalid one fails fast at connect() (raising InterfaceError/
969
+ # OperationalError here), captures the expiry for diagnostics, and fires
970
+ # the already-expired-token warning. The token is placed directly in
971
+ # attrs_before; the identity-aware safety net in __init__ then keys the
972
+ # pool on the token hash (``tok:``).
973
+ #
974
+ # NOTE: a custom token_provider is keyed on the token it mints, NOT on
975
+ # the provider object. Object-identity keying would be unsafe: a mutable
976
+ # credential (e.g. AzureCliCredential, which follows whoever is logged
977
+ # into the az CLI) can represent different principals over its lifetime,
978
+ # yet a same-object pool hit skips re-acquisition — so a caller could be
979
+ # handed a connection authenticated as a stale principal. Token-hash
980
+ # keying re-derives identity from the actual token on every physical
981
+ # connect, so a principal change always lands in a distinct pool. The
982
+ # trade-off is weaker reuse (a rotated token opens a new bucket, which
983
+ # the native idle sweep later evicts) and no expiry-aware refresh — the
984
+ # pooled connection is reused until it dies. See the pooling notes in
985
+ # the README.
986
+ token, token_expires_on = acquire_token_from_credential(token_provider)
987
+ self._token_expires_on = token_expires_on
988
+ self._attrs_before[ConstantsDDBC.SQL_COPT_SS_ACCESS_TOKEN.value] = token
989
+
990
+ def _construct_connection_string(
991
+ self, connection_str: str = "", **kwargs: Any
992
+ ) -> Tuple[str, Dict[str, str]]:
993
+ """
994
+ Construct the connection string by parsing, validating, and merging parameters.
995
+
996
+ 1. Parse and validate the base connection_str (validates against allowlist)
997
+ 2. Normalize parameter names (e.g., addr/address -> Server, uid -> UID)
998
+ 3. Merge kwargs (which override connection_str params after normalization)
999
+ 4. Add Driver and APP (always controlled by the driver)
1000
+ 5. Build and return the final connection string + parameter dictionary
1001
+
1002
+ Args:
1003
+ connection_str (str): The base connection string.
1004
+ **kwargs: Additional key/value pairs for the connection string.
1005
+
1006
+ Returns:
1007
+ Tuple[str, Dict[str, str]]: The constructed connection string and
1008
+ the normalized parameter dictionary.
1009
+ """
1010
+
1011
+ # Reject embedded NUL (\x00) up front, for both the base string and every
1012
+ # kwargs value. The ODBC layer terminates the connection string at the
1013
+ # first NUL (SQL_NTS), so anything after it is silently dropped; worse,
1014
+ # the identity-aware pool key joins the connection string and the
1015
+ # per-identity discriminator with a NUL separator, so a NUL smuggled into
1016
+ # a value could forge or collide pool keys. Fail closed at this Python
1017
+ # boundary rather than relying on downstream truncation.
1018
+ if isinstance(connection_str, str) and "\x00" in connection_str:
1019
+ raise InterfaceError(
1020
+ driver_error="Connection string must not contain a NUL (\\x00) character.",
1021
+ ddbc_error="Embedded NUL in connection string.",
1022
+ )
1023
+ for _key, _value in kwargs.items():
1024
+ if isinstance(_value, str) and "\x00" in _value:
1025
+ raise InterfaceError(
1026
+ driver_error=(
1027
+ f"Connection parameter '{_key}' must not contain a NUL "
1028
+ "(\\x00) character."
1029
+ ),
1030
+ ddbc_error="Embedded NUL in connection parameter.",
1031
+ )
1032
+
1033
+ # Step 1: Parse base connection string with allowlist validation
1034
+ # The parser validates everything: unknown params, reserved params, duplicates, syntax
1035
+ parser = _ConnectionStringParser(validate_keywords=True)
1036
+ parsed_params = parser._parse(connection_str)
1037
+
1038
+ # Step 2: Normalize parameter names (e.g., addr/address -> Server, uid -> UID)
1039
+ # This handles synonym mapping and deduplication via normalized keys
1040
+ normalized_params = _ConnectionStringParser._normalize_params(
1041
+ parsed_params, warn_rejected=False
1042
+ )
1043
+
1044
+ # Step 3: Process kwargs and merge with normalized_params
1045
+ # kwargs override connection string values (processed after, so they take precedence)
1046
+ for key, value in kwargs.items():
1047
+ normalized_key = _ConnectionStringParser.normalize_key(key)
1048
+ if normalized_key:
1049
+ # Driver and APP are reserved - raise error if user tries to set them
1050
+ if normalized_key in _RESERVED_PARAMETERS:
1051
+ raise ValueError(
1052
+ f"Connection parameter '{key}' is reserved and controlled by the driver. "
1053
+ f"It cannot be set by the user."
1054
+ )
1055
+ # kwargs override any existing values from connection string
1056
+ normalized_params[normalized_key] = str(value)
1057
+ else:
1058
+ logger.warning(f"Ignoring unknown connection parameter from kwargs: {key}")
1059
+
1060
+ # Step 4: Add Driver and APP (always controlled by the driver).
1061
+ normalized_params["Driver"] = "ODBC Driver 18 for SQL Server"
1062
+ normalized_params["APP"] = "MSSQL-Python"
1063
+
1064
+ # Step 5: Build final connection string
1065
+ conn_str = _ConnectionStringBuilder(normalized_params).build()
1066
+
1067
+ logger.info("Final connection string: %s", sanitize_connection_string(conn_str))
1068
+
1069
+ return conn_str, normalized_params
1070
+
1071
+ @staticmethod
1072
+ def _validate_timeout(value: int, kind: str = "Timeout") -> int:
1073
+ """
1074
+ Validate a timeout value (login or query) and normalize it to ``int``.
1075
+
1076
+ Shared by ``__init__`` (login timeout) and the ``timeout`` setter (query
1077
+ timeout) so both entry points reject invalid input identically and can
1078
+ never drift apart. ``kind`` only customizes the error-message wording
1079
+ ("Login timeout" vs "Query timeout"); the validation rules are identical.
1080
+
1081
+ Args:
1082
+ value (int): Timeout in seconds. Must be a non-negative integer.
1083
+ kind (str): Human-readable label used in error messages.
1084
+
1085
+ Returns:
1086
+ int: The validated timeout value.
1087
+
1088
+ Raises:
1089
+ TypeError: If ``value`` is not an integer (``bool`` is rejected too).
1090
+ ValueError: If ``value`` is negative.
1091
+ """
1092
+ # ``bool`` is a subclass of ``int``; reject it explicitly so a stray
1093
+ # ``timeout=True`` cannot slip through as ``1`` (a classic int/bool footgun).
1094
+ if isinstance(value, bool) or not isinstance(value, int):
1095
+ raise TypeError(f"{kind} must be an integer")
1096
+ if value < 0:
1097
+ raise ValueError(f"{kind} cannot be negative")
1098
+ return value
1099
+
1100
+ @property
1101
+ def timeout(self) -> int:
1102
+ """
1103
+ Get the current query timeout setting in seconds.
1104
+
1105
+ Returns:
1106
+ int: The timeout value in seconds. Zero means no timeout (wait indefinitely).
1107
+ """
1108
+ return self._timeout
1109
+
1110
+ @timeout.setter
1111
+ def timeout(self, value: int) -> None:
1112
+ """
1113
+ Set the query timeout for all operations performed by this connection.
1114
+
1115
+ Args:
1116
+ value (int): The timeout value in seconds. Zero means no timeout.
1117
+
1118
+ Returns:
1119
+ None
1120
+
1121
+ Note:
1122
+ This timeout applies to all cursors created from this connection.
1123
+ It cannot be changed for individual cursors or SQL statements.
1124
+ If a query timeout occurs, an OperationalError exception will be raised.
1125
+ """
1126
+ self._timeout = self._validate_timeout(value, kind="Query timeout")
1127
+ logger.info(f"Query timeout set to {value} seconds")
1128
+
1129
+ @property
1130
+ def autocommit(self) -> bool:
1131
+ """
1132
+ Return the current autocommit mode of the connection.
1133
+ Returns:
1134
+ bool: True if autocommit is enabled, False otherwise.
1135
+ """
1136
+ try:
1137
+ return self._conn.get_autocommit()
1138
+ except RuntimeError as e:
1139
+ _raise_connection_error(e)
1140
+
1141
+ @autocommit.setter
1142
+ def autocommit(self, value: bool) -> None:
1143
+ """
1144
+ Set the autocommit mode of the connection.
1145
+ Args:
1146
+ value (bool): True to enable autocommit, False to disable it.
1147
+ Returns:
1148
+ None
1149
+ """
1150
+ self.setautocommit(value)
1151
+ logger.info("Autocommit mode set to %s.", value)
1152
+
1153
+ @property
1154
+ def closed(self) -> bool:
1155
+ """
1156
+ Returns True if the connection is closed, False otherwise.
1157
+
1158
+ This property indicates whether close() was explicitly called on
1159
+ the connection. Note that this does not indicate whether the
1160
+ connection is healthy/alive - if a timeout or network issue breaks
1161
+ the connection, closed would still be False until close() is
1162
+ explicitly called.
1163
+
1164
+ Returns:
1165
+ bool: True if the connection is closed, False otherwise.
1166
+ """
1167
+ return self._closed
1168
+
1169
+ def setautocommit(self, value: bool = False) -> None:
1170
+ """
1171
+ Set the autocommit mode of the connection.
1172
+ Args:
1173
+ value (bool): True to enable autocommit, False to disable it.
1174
+ Returns:
1175
+ None
1176
+ Raises:
1177
+ DatabaseError: If there is an error while setting the autocommit mode.
1178
+ """
1179
+ try:
1180
+ self._conn.set_autocommit(value)
1181
+ except RuntimeError as e:
1182
+ _raise_connection_error(e)
1183
+
1184
+ def setencoding(self, encoding: Optional[str] = None, ctype: Optional[int] = None) -> None:
1185
+ """
1186
+ Records the requested text encoding settings for compatibility.
1187
+
1188
+ SQL statements and str parameters are always sent as UTF-16LE; text
1189
+ parameters are bound as SQL_C_WCHAR on every platform. This applies to
1190
+ execute() and executemany(), with or without setinputsizes(). This method
1191
+ does not change that behavior or enforce the requested codec.
1192
+
1193
+ Requests that pass validation but differ from UTF-16LE with SQL_WCHAR emit
1194
+ UserWarning. Invalid codec names, invalid ctypes, and incompatible
1195
+ combinations (such as UTF-8 with SQL_WCHAR) raise ProgrammingError before
1196
+ any warning is emitted or settings are stored. Accepted settings are still
1197
+ returned by getencoding(), not the effective binding. Use setdecoding()
1198
+ separately to configure how results are read.
1199
+
1200
+ Args:
1201
+ encoding (str, optional): The requested encoding. This must be a valid Python
1202
+ encoding that converts text to bytes. If None, defaults to 'utf-16le'.
1203
+ ctype (int, optional): The requested C data type:
1204
+ SQL_CHAR or SQL_WCHAR. If not provided, SQL_WCHAR is used for
1205
+ UTF-16 variants (see UTF16_ENCODINGS constant). SQL_CHAR is used
1206
+ for all other encodings.
1207
+
1208
+ Returns:
1209
+ None
1210
+
1211
+ Raises:
1212
+ ProgrammingError: If the encoding or ctype is invalid, or their
1213
+ combination is incompatible.
1214
+ InterfaceError: If the connection is closed.
1215
+
1216
+ Warns:
1217
+ UserWarning: If the request passes validation but its encoding or
1218
+ ctype cannot be honored.
1219
+
1220
+ Example:
1221
+ # Restore the supported default.
1222
+ cnxn.setencoding()
1223
+
1224
+ # Warns: parameters still use UTF-16LE / SQL_C_WCHAR.
1225
+ cnxn.setencoding(encoding='cp1252', ctype=mssql_python.SQL_CHAR)
1226
+ """
1227
+ logger.debug(
1228
+ "setencoding: Configuring encoding=%s, ctype=%s",
1229
+ str(encoding) if encoding else "default",
1230
+ str(ctype) if ctype else "auto",
1231
+ )
1232
+ if self._closed:
1233
+ logger.debug("setencoding: Connection is closed")
1234
+ raise InterfaceError(
1235
+ driver_error="Connection is closed",
1236
+ ddbc_error="Connection is closed",
1237
+ )
1238
+
1239
+ # Set default encoding if not provided
1240
+ if encoding is None:
1241
+ encoding = "utf-16le"
1242
+ logger.debug("setencoding: Using default encoding=utf-16le")
1243
+
1244
+ # Validate encoding using cached validation for better performance
1245
+ if not _validate_encoding(encoding):
1246
+ # Log the sanitized encoding for security
1247
+ logger.warning(
1248
+ "Invalid encoding attempted: %s",
1249
+ sanitize_user_input(str(encoding)),
1250
+ )
1251
+ raise ProgrammingError(
1252
+ driver_error=f"Unsupported encoding: {encoding}",
1253
+ ddbc_error=f"The encoding '{encoding}' is not supported by Python",
1254
+ )
1255
+
1256
+ # Normalize encoding to casefold for more robust Unicode handling
1257
+ encoding = encoding.casefold()
1258
+ logger.debug("setencoding: Encoding normalized to %s", encoding)
1259
+
1260
+ # Early validation if ctype is already specified as SQL_WCHAR
1261
+ if ctype == ConstantsDDBC.SQL_WCHAR.value:
1262
+ _validate_utf16_wchar_compatibility(encoding, ctype, "SQL_WCHAR")
1263
+
1264
+ # Set default ctype based on encoding if not provided
1265
+ if ctype is None:
1266
+ if encoding in UTF16_ENCODINGS:
1267
+ ctype = ConstantsDDBC.SQL_WCHAR.value
1268
+ logger.debug("setencoding: Auto-selected SQL_WCHAR for UTF-16")
1269
+ else:
1270
+ ctype = ConstantsDDBC.SQL_CHAR.value
1271
+ logger.debug("setencoding: Auto-selected SQL_CHAR for non-UTF-16")
1272
+
1273
+ # Validate ctype
1274
+ valid_ctypes = [ConstantsDDBC.SQL_CHAR.value, ConstantsDDBC.SQL_WCHAR.value]
1275
+ if ctype not in valid_ctypes:
1276
+ # Log the sanitized ctype for security
1277
+ logger.warning(
1278
+ "Invalid ctype attempted: %s",
1279
+ sanitize_user_input(str(ctype)),
1280
+ )
1281
+ raise ProgrammingError(
1282
+ driver_error=f"Invalid ctype: {ctype}",
1283
+ ddbc_error=(
1284
+ f"ctype must be SQL_CHAR ({ConstantsDDBC.SQL_CHAR.value}) or "
1285
+ f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value})"
1286
+ ),
1287
+ )
1288
+
1289
+ # Final validation: SQL_WCHAR ctype only supports UTF-16 encodings (without BOM)
1290
+ if ctype == ConstantsDDBC.SQL_WCHAR.value:
1291
+ _validate_utf16_wchar_compatibility(encoding, ctype, "SQL_WCHAR")
1292
+
1293
+ if encoding != "utf-16le" or ctype != ConstantsDDBC.SQL_WCHAR.value:
1294
+ warnings.warn(
1295
+ "setencoding() does not change SQL statement encoding or text parameter binding: "
1296
+ "statements and str parameters always use UTF-16LE, and text parameters are "
1297
+ "bound as SQL_C_WCHAR. The requested settings are retained by getencoding() "
1298
+ "for compatibility but are not applied. Use setencoding() with no arguments "
1299
+ "to restore the supported defaults.",
1300
+ UserWarning,
1301
+ stacklevel=2,
1302
+ )
1303
+
1304
+ # Store the encoding settings (thread-safe with lock)
1305
+ with self._encoding_lock:
1306
+ self._encoding_settings = {"encoding": encoding, "ctype": ctype}
1307
+
1308
+ # Log with sanitized values for security
1309
+ logger.info(
1310
+ "Requested text encoding stored as %s with ctype %s",
1311
+ sanitize_user_input(encoding),
1312
+ sanitize_user_input(str(ctype)),
1313
+ )
1314
+
1315
+ def getencoding(self) -> Dict[str, Union[str, int]]:
1316
+ """
1317
+ Gets the requested text encoding settings (thread-safe).
1318
+
1319
+ These settings are retained for compatibility. They do not describe the
1320
+ effective binding: SQL statements and str parameters always use UTF-16LE,
1321
+ and text parameters are bound as SQL_C_WCHAR.
1322
+
1323
+ Returns:
1324
+ dict: A dictionary containing 'encoding' and 'ctype' keys.
1325
+
1326
+ Raises:
1327
+ InterfaceError: If the connection is closed.
1328
+
1329
+ Example:
1330
+ settings = cnxn.getencoding()
1331
+ print(f"Current encoding: {settings['encoding']}")
1332
+ print(f"Current ctype: {settings['ctype']}")
1333
+
1334
+ Note:
1335
+ This method is thread-safe and can be called from multiple threads concurrently.
1336
+ Returns a copy of the settings to prevent external modification.
1337
+ """
1338
+ if self._closed:
1339
+ raise InterfaceError(
1340
+ driver_error="Connection is closed",
1341
+ ddbc_error="Connection is closed",
1342
+ )
1343
+
1344
+ # Thread-safe read with lock to prevent race conditions
1345
+ with self._encoding_lock:
1346
+ return self._encoding_settings.copy()
1347
+
1348
+ def setdecoding(
1349
+ self, sqltype: int, encoding: Optional[str] = None, ctype: Optional[int] = None
1350
+ ) -> None:
1351
+ """
1352
+ Sets the text decoding used when reading SQL_CHAR and SQL_WCHAR from the database.
1353
+
1354
+ Existing cursors refresh their cached SQL_CHAR/SQL_WCHAR decoding settings
1355
+ before their next fetch.
1356
+
1357
+ This method configures how text data is decoded when reading from the database.
1358
+ In Python 3, all text is Unicode (str), so this primarily affects the encoding
1359
+ used to decode bytes from the database.
1360
+
1361
+ Args:
1362
+ sqltype (int): The SQL type being configured: SQL_CHAR, SQL_WCHAR, or SQL_WMETADATA.
1363
+ SQL_WMETADATA is a special flag for configuring column name decoding.
1364
+ encoding (str, optional): The Python encoding to use when decoding the data.
1365
+ If None, defaults to ``'utf-16le'`` for all sqltypes (SQL_CHAR,
1366
+ SQL_WCHAR, and SQL_WMETADATA), matching the connection-level
1367
+ defaults set in ``Connection.__init__``. Passing ``encoding=None``
1368
+ therefore resets the sqltype to its initial default.
1369
+ ctype (int, optional): The C data type to request from SQLGetData:
1370
+ SQL_CHAR or SQL_WCHAR. If None, uses default based on encoding
1371
+ (SQL_WCHAR for UTF-16 variants, SQL_CHAR otherwise).
1372
+
1373
+ Returns:
1374
+ None
1375
+
1376
+ Raises:
1377
+ ProgrammingError: If the sqltype, encoding, or ctype is invalid.
1378
+ InterfaceError: If the connection is closed.
1379
+
1380
+ Example:
1381
+ # Reset SQL_CHAR to the connection default (utf-16le + SQL_WCHAR ctype)
1382
+ cnxn.setdecoding(mssql_python.SQL_CHAR)
1383
+
1384
+ # Configure SQL_CHAR to use UTF-8 decoding (opt-in, non-default)
1385
+ cnxn.setdecoding(mssql_python.SQL_CHAR, encoding='utf-8')
1386
+
1387
+ # Configure column metadata decoding
1388
+ cnxn.setdecoding(mssql_python.SQL_WMETADATA, encoding='utf-16le')
1389
+
1390
+ # Use explicit ctype
1391
+ cnxn.setdecoding(mssql_python.SQL_WCHAR, encoding='utf-16le',
1392
+ ctype=mssql_python.SQL_WCHAR)
1393
+ """
1394
+ if self._closed:
1395
+ raise InterfaceError(
1396
+ driver_error="Connection is closed",
1397
+ ddbc_error="Connection is closed",
1398
+ )
1399
+
1400
+ # Validate sqltype
1401
+ valid_sqltypes = [
1402
+ ConstantsDDBC.SQL_CHAR.value,
1403
+ ConstantsDDBC.SQL_WCHAR.value,
1404
+ SQL_WMETADATA,
1405
+ ]
1406
+ if sqltype not in valid_sqltypes:
1407
+ logger.warning(
1408
+ "Invalid sqltype attempted: %s",
1409
+ sanitize_user_input(str(sqltype)),
1410
+ )
1411
+ raise ProgrammingError(
1412
+ driver_error=f"Invalid sqltype: {sqltype}",
1413
+ ddbc_error=(
1414
+ f"sqltype must be SQL_CHAR ({ConstantsDDBC.SQL_CHAR.value}), "
1415
+ f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value}), or "
1416
+ f"SQL_WMETADATA ({SQL_WMETADATA})"
1417
+ ),
1418
+ )
1419
+
1420
+ # Set default encoding based on sqltype if not provided.
1421
+ # All sqltypes default to UTF-16LE to match Connection.__init__ defaults.
1422
+ # SQL_CHAR uses utf-16le + SQL_WCHAR ctype so the ODBC driver returns
1423
+ # UTF-16 data for VARCHAR columns, avoiding encoding mismatches on
1424
+ # Windows where the driver may otherwise return raw bytes in the
1425
+ # server's native code page (e.g. CP-1252). This makes
1426
+ # ``setdecoding(SQL_CHAR)`` with no arguments a true reset-to-defaults.
1427
+ if encoding is None:
1428
+ encoding = "utf-16le"
1429
+
1430
+ # Validate encoding using cached validation for better performance
1431
+ if not _validate_encoding(encoding):
1432
+ logger.warning(
1433
+ "Invalid encoding attempted: %s",
1434
+ sanitize_user_input(str(encoding)),
1435
+ )
1436
+ raise ProgrammingError(
1437
+ driver_error=f"Unsupported encoding: {encoding}",
1438
+ ddbc_error=f"The encoding '{encoding}' is not supported by Python",
1439
+ )
1440
+
1441
+ # Normalize encoding to lowercase for consistency
1442
+ encoding = encoding.lower()
1443
+
1444
+ # Validate SQL_WCHAR encoding compatibility
1445
+ if sqltype == ConstantsDDBC.SQL_WCHAR.value:
1446
+ _validate_utf16_wchar_compatibility(encoding, sqltype, "SQL_WCHAR sqltype")
1447
+
1448
+ # SQL_WMETADATA can use any valid encoding (UTF-8, UTF-16, etc.)
1449
+ # No restriction needed here - let users configure as needed
1450
+
1451
+ # Set default ctype based on encoding if not provided
1452
+ if ctype is None:
1453
+ if encoding in UTF16_ENCODINGS:
1454
+ ctype = ConstantsDDBC.SQL_WCHAR.value
1455
+ else:
1456
+ ctype = ConstantsDDBC.SQL_CHAR.value
1457
+
1458
+ # Validate ctype
1459
+ valid_ctypes = [ConstantsDDBC.SQL_CHAR.value, ConstantsDDBC.SQL_WCHAR.value]
1460
+ if ctype not in valid_ctypes:
1461
+ logger.warning(
1462
+ "Invalid ctype attempted: %s",
1463
+ sanitize_user_input(str(ctype)),
1464
+ )
1465
+ raise ProgrammingError(
1466
+ driver_error=f"Invalid ctype: {ctype}",
1467
+ ddbc_error=(
1468
+ f"ctype must be SQL_CHAR ({ConstantsDDBC.SQL_CHAR.value}) or "
1469
+ f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value})"
1470
+ ),
1471
+ )
1472
+
1473
+ # Validate SQL_WCHAR ctype encoding compatibility
1474
+ if ctype == ConstantsDDBC.SQL_WCHAR.value:
1475
+ _validate_utf16_wchar_compatibility(encoding, ctype, "SQL_WCHAR ctype")
1476
+
1477
+ # Store the decoding settings for the specified sqltype (thread-safe with lock)
1478
+ with self._encoding_lock:
1479
+ self._decoding_settings[sqltype] = {"encoding": encoding, "ctype": ctype}
1480
+ self._decoding_generation += 1
1481
+
1482
+ # Log with sanitized values for security
1483
+ sqltype_name = {
1484
+ ConstantsDDBC.SQL_CHAR.value: "SQL_CHAR",
1485
+ ConstantsDDBC.SQL_WCHAR.value: "SQL_WCHAR",
1486
+ SQL_WMETADATA: "SQL_WMETADATA",
1487
+ }.get(sqltype, str(sqltype))
1488
+
1489
+ logger.info(
1490
+ "Text decoding set for %s to %s with ctype %s",
1491
+ sqltype_name,
1492
+ sanitize_user_input(encoding),
1493
+ sanitize_user_input(str(ctype)),
1494
+ )
1495
+
1496
+ def getdecoding(self, sqltype: int) -> Dict[str, Union[str, int]]:
1497
+ """
1498
+ Gets the current text decoding settings for the specified SQL type (thread-safe).
1499
+
1500
+ Args:
1501
+ sqltype (int): The SQL type to get settings for: SQL_CHAR, SQL_WCHAR, or SQL_WMETADATA.
1502
+
1503
+ Returns:
1504
+ dict: A dictionary containing 'encoding' and 'ctype' keys for the specified sqltype.
1505
+
1506
+ Raises:
1507
+ ProgrammingError: If the sqltype is invalid.
1508
+ InterfaceError: If the connection is closed.
1509
+
1510
+ Example:
1511
+ settings = cnxn.getdecoding(mssql_python.SQL_CHAR)
1512
+ print(f"SQL_CHAR encoding: {settings['encoding']}")
1513
+ print(f"SQL_CHAR ctype: {settings['ctype']}")
1514
+
1515
+ Note:
1516
+ This method is thread-safe and can be called from multiple threads concurrently.
1517
+ Returns a copy of the settings to prevent external modification.
1518
+ """
1519
+ if self._closed:
1520
+ raise InterfaceError(
1521
+ driver_error="Connection is closed",
1522
+ ddbc_error="Connection is closed",
1523
+ )
1524
+
1525
+ # Validate sqltype
1526
+ valid_sqltypes = [
1527
+ ConstantsDDBC.SQL_CHAR.value,
1528
+ ConstantsDDBC.SQL_WCHAR.value,
1529
+ SQL_WMETADATA,
1530
+ ]
1531
+ if sqltype not in valid_sqltypes:
1532
+ raise ProgrammingError(
1533
+ driver_error=f"Invalid sqltype: {sqltype}",
1534
+ ddbc_error=(
1535
+ f"sqltype must be SQL_CHAR ({ConstantsDDBC.SQL_CHAR.value}), "
1536
+ f"SQL_WCHAR ({ConstantsDDBC.SQL_WCHAR.value}), or "
1537
+ f"SQL_WMETADATA ({SQL_WMETADATA})"
1538
+ ),
1539
+ )
1540
+
1541
+ # Thread-safe read with lock to prevent race conditions
1542
+ with self._encoding_lock:
1543
+ return self._decoding_settings[sqltype].copy()
1544
+
1545
+ def set_attr(self, attribute: int, value: Union[int, str, bytes, bytearray]) -> None:
1546
+ """
1547
+ Set a connection attribute.
1548
+
1549
+ This method sets a connection attribute using SQLSetConnectAttr.
1550
+ It provides pyodbc-compatible functionality for configuring connection
1551
+ behavior such as autocommit mode, transaction isolation level, and
1552
+ connection timeouts.
1553
+
1554
+ Args:
1555
+ attribute (int): The connection attribute to set. Should be one of the
1556
+ SQL_ATTR_* constants (e.g., SQL_ATTR_AUTOCOMMIT,
1557
+ SQL_ATTR_TXN_ISOLATION).
1558
+ value: The value to set for the attribute. Can be an integer, string,
1559
+ bytes, or bytearray depending on the attribute type.
1560
+
1561
+ Raises:
1562
+ InterfaceError: If the connection is closed or attribute is invalid.
1563
+ ProgrammingError: If the value type or range is invalid.
1564
+ ProgrammingError: If the attribute cannot be set after connection.
1565
+
1566
+ Example:
1567
+ >>> conn.set_attr(SQL_ATTR_TXN_ISOLATION, SQL_TXN_READ_COMMITTED)
1568
+
1569
+ Note:
1570
+ Some attributes (like SQL_ATTR_LOGIN_TIMEOUT, SQL_ATTR_ODBC_CURSORS, and
1571
+ SQL_ATTR_PACKET_SIZE) can only be set before connection establishment and
1572
+ must be provided in the attrs_before parameter when creating the connection.
1573
+ Attempting to set these attributes after connection will raise a ProgrammingError.
1574
+ """
1575
+ if self._closed:
1576
+ raise InterfaceError(
1577
+ "Cannot set attribute on closed connection", "Connection is closed"
1578
+ )
1579
+
1580
+ # Use the integrated validation helper function with connection state
1581
+ is_valid, error_message, sanitized_attr, sanitized_val = validate_attribute_value(
1582
+ attribute, value, is_connected=True
1583
+ )
1584
+
1585
+ if not is_valid:
1586
+ # Use the already sanitized values for logging
1587
+ logger.debug(
1588
+ "warning",
1589
+ f"Invalid attribute or value: {sanitized_attr}={sanitized_val}, {error_message}",
1590
+ )
1591
+ raise ProgrammingError(
1592
+ driver_error=f"Invalid attribute or value: {error_message}",
1593
+ ddbc_error=error_message,
1594
+ )
1595
+
1596
+ # Log with sanitized values
1597
+ logger.debug(f"Setting connection attribute: {sanitized_attr}={sanitized_val}")
1598
+
1599
+ try:
1600
+ # Call the underlying C++ method
1601
+ self._conn.set_attr(attribute, value)
1602
+ logger.info(f"Connection attribute {sanitized_attr} set successfully")
1603
+
1604
+ except Exception as e:
1605
+ error_msg = f"Failed to set connection attribute {sanitized_attr}: {str(e)}"
1606
+
1607
+ # Determine appropriate exception type based on error content
1608
+ error_str = str(e).lower()
1609
+ if "invalid" in error_str or "unsupported" in error_str or "cast" in error_str:
1610
+ logger.error(error_msg)
1611
+ raise InterfaceError(error_msg, str(e)) from e
1612
+ logger.error(error_msg)
1613
+ raise ProgrammingError(error_msg, str(e)) from e
1614
+
1615
+ @property
1616
+ def searchescape(self) -> str:
1617
+ """
1618
+ The ODBC search pattern escape character, as returned by
1619
+ SQLGetInfo(SQL_SEARCH_PATTERN_ESCAPE), used to escape special characters
1620
+ such as '%' and '_' in LIKE clauses. These are driver specific.
1621
+
1622
+ Returns:
1623
+ str: The search pattern escape character (usually '\' or another character)
1624
+ """
1625
+ if not hasattr(self, "_searchescape") or self._searchescape is None:
1626
+ try:
1627
+ escape_char = self.getinfo(GetInfoConstants.SQL_SEARCH_PATTERN_ESCAPE.value)
1628
+ # Some drivers might return this as an integer memory address
1629
+ # or other non-string format, so ensure we have a string
1630
+ if not isinstance(escape_char, str):
1631
+ # Default to backslash if not a string
1632
+ escape_char = "\\"
1633
+ self._searchescape = escape_char
1634
+ except Exception as e:
1635
+ # Log the exception for debugging, but do not expose sensitive info
1636
+ logger.debug(
1637
+ "warning",
1638
+ "Failed to retrieve search escape character, using default '\\'. "
1639
+ "Exception: %s",
1640
+ type(e).__name__,
1641
+ )
1642
+ self._searchescape = "\\"
1643
+ return self._searchescape
1644
+
1645
+ def cursor(self) -> Cursor:
1646
+ """
1647
+ Return a new Cursor object using the connection.
1648
+
1649
+ This method creates and returns a new cursor object that can be used to
1650
+ execute SQL queries and fetch results. The cursor is associated with the
1651
+ current connection and allows interaction with the database.
1652
+
1653
+ Returns:
1654
+ Cursor: A new cursor object for executing SQL queries.
1655
+
1656
+ Raises:
1657
+ DatabaseError: If there is an error while creating the cursor.
1658
+ InterfaceError: If there is an error related to the database interface.
1659
+ """
1660
+ logger.debug(
1661
+ "cursor: Creating new cursor - timeout=%d, total_cursors=%d",
1662
+ self._timeout,
1663
+ len(self._cursors),
1664
+ )
1665
+ if self._closed:
1666
+ logger.error("cursor: Cannot create cursor on closed connection")
1667
+ # raise InterfaceError
1668
+ raise InterfaceError(
1669
+ driver_error="Cannot create cursor on closed connection",
1670
+ ddbc_error="Cannot create cursor on closed connection",
1671
+ )
1672
+
1673
+ cursor = Cursor(self, timeout=self._timeout)
1674
+ self._cursors.add(cursor) # Track the cursor
1675
+ logger.debug("cursor: Cursor created successfully - total_cursors=%d", len(self._cursors))
1676
+ return cursor
1677
+
1678
+ def add_output_converter(self, sqltype: Union[int, type], func: Callable[[Any], Any]) -> None:
1679
+ """
1680
+ Register an output converter function that will be called whenever a value
1681
+ with the given SQL type is read from the database.
1682
+
1683
+ Thread-safe implementation that protects the converters dictionary with a lock.
1684
+
1685
+ Changes apply on the next fetch, including for an already executed result set.
1686
+
1687
+ ⚠️ WARNING: Registering an output converter will cause the supplied Python function
1688
+ to be executed on every matching database value. Do not register converters from
1689
+ untrusted sources, as this can result in arbitrary code execution and security
1690
+ vulnerabilities. This API should never be exposed to untrusted or external input.
1691
+
1692
+ Args:
1693
+ sqltype (int or type): The type to convert. Either:
1694
+ - an integer ODBC SQL type code (pyodbc-compatible), which can be one of
1695
+ the standard constants (e.g. SQL_VARCHAR, SQL_DECIMAL) or a
1696
+ database-specific value (e.g. -151 for the SQL Server geometry type). The
1697
+ converter fires for columns whose ODBC SQL type matches exactly, so
1698
+ distinct types such as DECIMAL and NUMERIC can have separate converters; or
1699
+ - a Python type (e.g. ``decimal.Decimal``, ``str``, ``bytes``), which fires
1700
+ for every column whose value materializes to that Python type (so, for
1701
+ example, a single ``decimal.Decimal`` converter matches DECIMAL, NUMERIC,
1702
+ MONEY and SMALLMONEY columns alike). The supported Python types are
1703
+ ``str``, ``bytes``, ``bool``, ``int``, ``float``, ``decimal.Decimal``,
1704
+ ``datetime.date``, ``datetime.time``, ``datetime.datetime`` and
1705
+ ``uuid.UUID``.
1706
+ When both an integer-keyed and a Python-type-keyed converter could apply to
1707
+ the same column, the integer SQL-type converter takes precedence.
1708
+
1709
+ For pyodbc compatibility the ``sqltype`` argument is not validated: any key
1710
+ is accepted and stored. A key that matches neither an exact integer ODBC SQL
1711
+ type code nor an exact materialized Python type (for example a ``set``, a
1712
+ ``dict``, ``object``, or a ``decimal.Decimal`` subclass) is stored but never
1713
+ dispatched — registering it is a harmless no-op rather than an error.
1714
+ func (callable): The converter function, called with a single parameter (the
1715
+ value) that returns the converted value. The converter is not
1716
+ invoked for SQL NULL values (they are returned as ``None``
1717
+ unchanged). For non-NULL values the parameter is the value
1718
+ already materialized as its Python type (e.g. a
1719
+ ``decimal.Decimal`` or ``datetime.datetime``); string values are
1720
+ passed as their UTF-16LE-encoded ``bytes``.
1721
+
1722
+ Returns:
1723
+ None
1724
+ """
1725
+ with self._converters_lock:
1726
+ self._output_converters[sqltype] = func
1727
+ self._converters_generation += 1
1728
+ # Pass to the underlying connection if native implementation supports it
1729
+ if hasattr(self._conn, "add_output_converter"):
1730
+ self._conn.add_output_converter(sqltype, func)
1731
+ logger.info(f"Added output converter for SQL type {sqltype}")
1732
+
1733
+ def get_output_converter(self, sqltype: Union[int, type]) -> Optional[Callable[[Any], Any]]:
1734
+ """
1735
+ Get the output converter function for the specified SQL type.
1736
+
1737
+ Thread-safe implementation that protects the converters dictionary with a lock.
1738
+
1739
+ Args:
1740
+ sqltype (int or type): The SQL type value or Python type to get the converter for
1741
+
1742
+ Returns:
1743
+ callable or None: The converter function or None if no converter is registered
1744
+
1745
+ Note:
1746
+ ⚠️ The returned converter function will be executed on database values. Only use
1747
+ converters from trusted sources.
1748
+ """
1749
+ with self._converters_lock:
1750
+ return self._output_converters.get(sqltype)
1751
+
1752
+ def remove_output_converter(self, sqltype: Union[int, type]) -> None:
1753
+ """
1754
+ Remove the output converter function for the specified SQL type.
1755
+
1756
+ Thread-safe implementation that protects the converters dictionary with a lock.
1757
+
1758
+ Existing cursors use the updated converters on their next fetch.
1759
+
1760
+ Args:
1761
+ sqltype (int or type): The SQL type value to remove the converter for
1762
+
1763
+ Returns:
1764
+ None
1765
+ """
1766
+ with self._converters_lock:
1767
+ if sqltype in self._output_converters:
1768
+ del self._output_converters[sqltype]
1769
+ self._converters_generation += 1
1770
+ # Pass to the underlying connection if native implementation supports it
1771
+ if hasattr(self._conn, "remove_output_converter"):
1772
+ self._conn.remove_output_converter(sqltype)
1773
+ logger.info(f"Removed output converter for SQL type {sqltype}")
1774
+
1775
+ def clear_output_converters(self) -> None:
1776
+ """
1777
+ Remove all output converter functions.
1778
+
1779
+ Thread-safe implementation that protects the converters dictionary with a lock.
1780
+
1781
+ Existing cursors stop applying converters on their next fetch.
1782
+
1783
+ Returns:
1784
+ None
1785
+ """
1786
+ with self._converters_lock:
1787
+ self._output_converters.clear()
1788
+ self._converters_generation += 1
1789
+ # Pass to the underlying connection if native implementation supports it
1790
+ if hasattr(self._conn, "clear_output_converters"):
1791
+ self._conn.clear_output_converters()
1792
+ logger.info("Cleared all output converters")
1793
+
1794
+ def execute(self, sql: str, *args: Any) -> Cursor:
1795
+ """
1796
+ Creates a new Cursor object, calls its execute method, and returns the new cursor.
1797
+
1798
+ This is a convenience method that is not part of the DB API. Since a new Cursor
1799
+ is allocated by each call, this should not be used if more than one SQL statement
1800
+ needs to be executed on the connection.
1801
+
1802
+ Note on cursor lifecycle management:
1803
+ - Each call creates a new cursor that is tracked by the connection's internal WeakSet
1804
+ - Cursors are automatically dereferenced/closed when they go out of scope
1805
+ - For long-running applications or loops, explicitly call cursor.close() when done
1806
+ to release resources immediately rather than waiting for garbage collection
1807
+
1808
+ Args:
1809
+ sql (str): The SQL query to execute.
1810
+ *args: Parameters to be passed to the query.
1811
+
1812
+ Returns:
1813
+ Cursor: A new cursor with the executed query.
1814
+
1815
+ Raises:
1816
+ DatabaseError: If there is an error executing the query.
1817
+ InterfaceError: If the connection is closed.
1818
+
1819
+ Example:
1820
+ # Automatic cleanup (cursor goes out of scope after the operation)
1821
+ row = connection.execute("SELECT name FROM users WHERE id = ?", 123).fetchone()
1822
+
1823
+ # Manual cleanup for more explicit resource management
1824
+ cursor = connection.execute("SELECT * FROM large_table")
1825
+ try:
1826
+ # Use cursor...
1827
+ rows = cursor.fetchall()
1828
+ finally:
1829
+ cursor.close() # Explicitly release resources
1830
+ """
1831
+ cursor = self.cursor()
1832
+ try:
1833
+ # Add the cursor to our tracking set BEFORE execution
1834
+ # This ensures it's tracked even if execution fails
1835
+ self._cursors.add(cursor)
1836
+
1837
+ # Now execute the query
1838
+ cursor.execute(sql, *args)
1839
+ return cursor
1840
+ except Exception:
1841
+ # If execution fails, close the cursor to avoid leaking resources
1842
+ cursor.close()
1843
+ raise
1844
+
1845
+ def batch_execute(
1846
+ self,
1847
+ statements: List[str],
1848
+ params: Optional[List[Union[None, Any, Tuple[Any, ...], List[Any]]]] = None,
1849
+ reuse_cursor: Optional[Cursor] = None,
1850
+ auto_close: bool = False,
1851
+ ) -> Tuple[List[Union[List["Row"], int]], Cursor]:
1852
+ """
1853
+ Execute multiple SQL statements efficiently using a single cursor.
1854
+
1855
+ This method allows executing multiple SQL statements in sequence using a single
1856
+ cursor, which is more efficient than creating a new cursor for each statement.
1857
+
1858
+ Args:
1859
+ statements (list): List of SQL statements to execute
1860
+ params (list, optional): List of parameter sets corresponding to statements.
1861
+ Each item can be None, a single parameter, or a sequence of parameters.
1862
+ If None, no parameters will be used for any statement.
1863
+ reuse_cursor (Cursor, optional): Existing cursor to reuse instead of creating a new one.
1864
+ If None, a new cursor will be created.
1865
+ auto_close (bool): Whether to close the cursor after execution if a new one was created.
1866
+ Defaults to False. Has no effect if reuse_cursor is provided.
1867
+
1868
+ Returns:
1869
+ tuple: (results, cursor) where:
1870
+ - results is a list of execution results, one for each statement
1871
+ - cursor is the cursor used for execution (useful if you want to keep using it)
1872
+
1873
+ Raises:
1874
+ TypeError: If statements is not a list or if params is provided but not a list
1875
+ ValueError: If params is provided but has different length than statements
1876
+ DatabaseError: If there is an error executing any of the statements
1877
+ InterfaceError: If the connection is closed
1878
+
1879
+ Example:
1880
+ # Execute multiple statements with a single cursor
1881
+ results, _ = conn.batch_execute([
1882
+ "INSERT INTO users VALUES (?, ?)",
1883
+ "UPDATE stats SET count = count + 1",
1884
+ "SELECT * FROM users"
1885
+ ], [
1886
+ (1, "user1"),
1887
+ None,
1888
+ None
1889
+ ])
1890
+
1891
+ # Last result contains the SELECT results
1892
+ for row in results[-1]:
1893
+ print(row)
1894
+
1895
+ # Reuse an existing cursor
1896
+ my_cursor = conn.cursor()
1897
+ results, _ = conn.batch_execute([
1898
+ "SELECT * FROM table1",
1899
+ "SELECT * FROM table2"
1900
+ ], reuse_cursor=my_cursor)
1901
+
1902
+ # Cursor remains open for further use
1903
+ my_cursor.execute("SELECT * FROM table3")
1904
+ """
1905
+ # Validate inputs
1906
+ if not isinstance(statements, list):
1907
+ raise TypeError("statements must be a list of SQL statements")
1908
+
1909
+ if params is not None:
1910
+ if not isinstance(params, list):
1911
+ raise TypeError("params must be a list of parameter sets")
1912
+ if len(params) != len(statements):
1913
+ raise ValueError("params list must have the same length as statements list")
1914
+ else:
1915
+ # Create a list of None values with the same length as statements
1916
+ params = [None] * len(statements)
1917
+
1918
+ # Determine which cursor to use
1919
+ is_new_cursor = reuse_cursor is None
1920
+ cursor = self.cursor() if is_new_cursor else reuse_cursor
1921
+
1922
+ # Execute statements and collect results
1923
+ results = []
1924
+ try:
1925
+ for i, (stmt, param) in enumerate(zip(statements, params)):
1926
+ try:
1927
+ # Execute the statement with parameters if provided
1928
+ if param is not None:
1929
+ cursor.execute(stmt, param)
1930
+ else:
1931
+ cursor.execute(stmt)
1932
+
1933
+ # For SELECT statements, fetch all rows
1934
+ # For other statements, get the row count
1935
+ if cursor.description is not None:
1936
+ # This is a SELECT statement or similar that returns rows
1937
+ results.append(cursor.fetchall())
1938
+ else:
1939
+ # This is an INSERT, UPDATE, DELETE or similar that doesn't return rows
1940
+ results.append(cursor.rowcount)
1941
+
1942
+ logger.debug(f"Executed batch statement {i+1}/{len(statements)}")
1943
+
1944
+ except Exception as e:
1945
+ # If a statement fails, include statement context in the error
1946
+ logger.debug(
1947
+ "error",
1948
+ f"Error executing statement {i+1}/{len(statements)}: {e}",
1949
+ )
1950
+ raise
1951
+
1952
+ except Exception:
1953
+ # If an error occurs and auto_close is True, close the cursor
1954
+ if auto_close:
1955
+ try:
1956
+ # Close the cursor regardless of whether it's reused or new
1957
+ cursor.close()
1958
+ logger.debug(
1959
+ "debug",
1960
+ "Automatically closed cursor after batch execution error",
1961
+ )
1962
+ except Exception as close_err:
1963
+ logger.debug(
1964
+ "warning",
1965
+ f"Error closing cursor after execution failure: {close_err}",
1966
+ )
1967
+ # Re-raise the original exception
1968
+ raise
1969
+
1970
+ # Close the cursor if requested and we created a new one
1971
+ if is_new_cursor and auto_close:
1972
+ cursor.close()
1973
+ logger.debug("Automatically closed cursor after batch execution")
1974
+
1975
+ return results, cursor
1976
+
1977
+ def getinfo(self, info_type: int) -> Union[str, int, bool, None]:
1978
+ """
1979
+ Return general information about the driver and data source.
1980
+
1981
+ Args:
1982
+ info_type (int): The type of information to return. See the ODBC
1983
+ SQLGetInfo documentation for the supported values.
1984
+
1985
+ Returns:
1986
+ The requested information. The type of the returned value depends
1987
+ on the information requested. For registered ODBC types, character values (including
1988
+ "Y"/"N") return strings; numeric values and bitmasks return unsigned
1989
+ integers. Native retrieval failures, including unsupported types,
1990
+ timeouts, and connection loss, are logged and return None.
1991
+
1992
+ Note:
1993
+ SQL_DRIVER_HDBC, SQL_DRIVER_HENV and SQL_DRIVER_HLIB are implemented
1994
+ by the ODBC Driver Manager, which this driver bypasses. Correct IDs
1995
+ do not imply that the selected native provider supports these queries.
1996
+ A native provider may return cached metadata even after connection loss;
1997
+ getinfo() is not a connection-health check.
1998
+ Deprecated GetInfoConstants names are retained for API compatibility,
1999
+ not as valid requests. Their integer values may request unrelated information.
2000
+
2001
+ Raises:
2002
+ DatabaseError: If a numeric byte result does not match its ODBC type's width.
2003
+ InterfaceError: If the connection is closed.
2004
+ """
2005
+ if self._closed:
2006
+ raise InterfaceError(
2007
+ driver_error="Cannot get info on closed connection",
2008
+ ddbc_error="Cannot get info on closed connection",
2009
+ )
2010
+
2011
+ # Check that info_type is an integer
2012
+ if not isinstance(info_type, int):
2013
+ raise ValueError(f"info_type must be an integer, got {type(info_type).__name__}")
2014
+
2015
+ # Check for invalid info_type values
2016
+ if info_type < 0:
2017
+ logger.debug("Invalid info_type: %d. Must be non-negative.", info_type)
2018
+ return None
2019
+
2020
+ # Get the raw result from the C++ layer
2021
+ try:
2022
+ raw_result = self._conn.get_info(info_type)
2023
+ except Exception as e: # pylint: disable=broad-exception-caught
2024
+ # Preserve the legacy logged-None contract for native retrieval failures.
2025
+ logger.warning(f"getinfo({info_type}) failed: {e}")
2026
+ return None
2027
+
2028
+ if raw_result is None:
2029
+ return None
2030
+
2031
+ # Check if the result is already a simple type
2032
+ if isinstance(raw_result, (str, int, bool)):
2033
+ return raw_result
2034
+
2035
+ # If it's a dictionary with data and metadata
2036
+ if isinstance(raw_result, dict) and "data" in raw_result:
2037
+ # Extract data and metadata from the raw result
2038
+ data = raw_result["data"]
2039
+ length = raw_result["length"]
2040
+
2041
+ logger.debug(
2042
+ "getinfo: info_type=%d, length=%r, data_type=%s",
2043
+ info_type,
2044
+ length,
2045
+ type(data),
2046
+ )
2047
+
2048
+ # Explicit numeric types take precedence over the legacy high-ID
2049
+ # string fallback (e.g. SQL_MAX_IDENTIFIER_LEN is numeric at 10005).
2050
+ return_type = _GETINFO_RETURN_TYPES.get(info_type)
2051
+ is_string_type = return_type is str or (
2052
+ return_type is None and info_type > INFO_TYPE_STRING_THRESHOLD
2053
+ )
2054
+ if is_string_type:
2055
+ # For string data, ensure we properly handle the byte array
2056
+ if isinstance(data, bytes):
2057
+ # Make sure we use the correct amount of data based on length
2058
+ actual_data = data[:length]
2059
+
2060
+ # SQLGetInfoW returns UTF-16LE encoded strings (wide-character ODBC API)
2061
+ # Try UTF-16LE first (expected), then UTF-8 as fallback
2062
+ for encoding in ("utf-16-le", "utf-8"):
2063
+ try:
2064
+ return actual_data.decode(encoding).rstrip("\0")
2065
+ except UnicodeDecodeError:
2066
+ continue
2067
+
2068
+ # All decodings failed
2069
+ logger.debug(
2070
+ "Failed to decode string in getinfo (info_type=%d) with supported encodings. "
2071
+ "Returning None to avoid silent corruption.",
2072
+ info_type,
2073
+ )
2074
+ return None
2075
+ else:
2076
+ # If it's not bytes, return as is
2077
+ return data
2078
+ elif isinstance(return_type, struct.Struct):
2079
+ if isinstance(data, bytes):
2080
+ if (
2081
+ type(length) is not int
2082
+ or length != return_type.size
2083
+ or len(data) < return_type.size
2084
+ ):
2085
+ raise DatabaseError(
2086
+ driver_error=f"Invalid numeric result length for getinfo({info_type})",
2087
+ ddbc_error=(
2088
+ f"Expected {return_type.size} bytes; "
2089
+ f"got length={length} with {len(data)} bytes of data"
2090
+ ),
2091
+ )
2092
+ return return_type.unpack_from(data)[0]
2093
+ # Legacy non-byte payloads must not lose precision or change bool to int.
2094
+ if isinstance(data, str) and data.isdecimal():
2095
+ try:
2096
+ return int(data)
2097
+ except ValueError:
2098
+ logger.debug(
2099
+ "Numeric getinfo compatibility value exceeds the integer conversion "
2100
+ "limit; returning it unchanged"
2101
+ )
2102
+ return data
2103
+
2104
+ # Preserve legacy handling for unregistered, driver-specific info types.
2105
+ if isinstance(data, bytes):
2106
+ # Try to convert to string first
2107
+ try:
2108
+ return data[:length].decode("utf-8").rstrip("\0")
2109
+ except UnicodeDecodeError:
2110
+ pass
2111
+
2112
+ # Try to convert to int for short binary data
2113
+ try:
2114
+ if length <= 8:
2115
+ return int.from_bytes(data[:length], "little", signed=True)
2116
+ except Exception: # pylint: disable=broad-exception-caught
2117
+ pass
2118
+
2119
+ # Return as is if we can't determine
2120
+ return data
2121
+
2122
+ return data
2123
+
2124
+ return raw_result # Return as-is
2125
+
2126
+ def commit(self) -> None:
2127
+ """
2128
+ Commit the current transaction.
2129
+
2130
+ This method commits the current transaction to the database, making all
2131
+ changes made during the transaction permanent. It should be called after
2132
+ executing a series of SQL statements that modify the database to ensure
2133
+ that the changes are saved.
2134
+
2135
+ Raises:
2136
+ InterfaceError: If the connection is closed.
2137
+ DatabaseError: If there is an error while committing the transaction.
2138
+ """
2139
+ # Check if connection is closed
2140
+ if self._closed or self._conn is None:
2141
+ raise InterfaceError(
2142
+ driver_error="Cannot commit on a closed connection",
2143
+ ddbc_error="Cannot commit on a closed connection",
2144
+ )
2145
+
2146
+ # Commit the current transaction
2147
+ try:
2148
+ self._conn.commit()
2149
+ except RuntimeError as e:
2150
+ _raise_connection_error(e)
2151
+ logger.info("Transaction committed successfully.")
2152
+
2153
+ def rollback(self) -> None:
2154
+ """
2155
+ Roll back the current transaction.
2156
+
2157
+ This method rolls back the current transaction, undoing all changes made
2158
+ during the transaction. It should be called if an error occurs during the
2159
+ transaction or if the changes should not be saved.
2160
+
2161
+ Raises:
2162
+ InterfaceError: If the connection is closed.
2163
+ DatabaseError: If there is an error while rolling back the transaction.
2164
+ """
2165
+ # Check if connection is closed
2166
+ if self._closed or self._conn is None:
2167
+ raise InterfaceError(
2168
+ driver_error="Cannot rollback on a closed connection",
2169
+ ddbc_error="Cannot rollback on a closed connection",
2170
+ )
2171
+
2172
+ # Roll back the current transaction
2173
+ try:
2174
+ self._conn.rollback()
2175
+ except RuntimeError as e:
2176
+ _raise_connection_error(e)
2177
+ logger.info("Transaction rolled back successfully.")
2178
+
2179
+ def close(self) -> None:
2180
+ """
2181
+ Close the connection now (rather than whenever .__del__() is called).
2182
+
2183
+ This method closes the connection to the database, releasing any resources
2184
+ associated with it. After calling this method, the connection object should
2185
+ not be used for any further operations. The same applies to all cursor objects
2186
+ trying to use the connection. Note that closing a connection without committing
2187
+ the changes first will cause an implicit rollback to be performed.
2188
+
2189
+ Raises:
2190
+ DatabaseError: If there is an error while closing the connection.
2191
+ """
2192
+ # Close the connection
2193
+ if self._closed:
2194
+ return
2195
+
2196
+ # Close all cursors first, but don't let one failure stop the others
2197
+ if hasattr(self, "_cursors"):
2198
+ # Convert to list to avoid modification during iteration
2199
+ cursors_to_close = list(self._cursors)
2200
+ close_errors = []
2201
+
2202
+ for cursor in cursors_to_close:
2203
+ try:
2204
+ if not cursor.closed:
2205
+ cursor.close()
2206
+ except Exception as e: # pylint: disable=broad-exception-caught
2207
+ # Collect errors but continue closing other cursors
2208
+ close_errors.append(f"Error closing cursor: {e}")
2209
+ logger.warning(f"Error closing cursor: {e}")
2210
+
2211
+ # If there were errors closing cursors, log them but continue
2212
+ if close_errors:
2213
+ logger.debug(
2214
+ "warning",
2215
+ "Encountered %d errors while closing cursors",
2216
+ len(close_errors),
2217
+ )
2218
+
2219
+ # Clear the cursor set explicitly to release any internal
2220
+ # references
2221
+ self._cursors.clear()
2222
+
2223
+ # Close the connection even if cursor cleanup had issues
2224
+ try:
2225
+ if self._conn:
2226
+ autocommit_error = None
2227
+ rollback_error = None
2228
+ manual_commit = False
2229
+ try:
2230
+ manual_commit = not self._conn.get_autocommit()
2231
+ except RuntimeError as e:
2232
+ autocommit_error = e
2233
+ if manual_commit:
2234
+ # End caller work before native close. Pooled connections are
2235
+ # additionally restored to autocommit by native check-in,
2236
+ # which atomically discards them if sanitation fails.
2237
+ logger.debug("Rolling back uncommitted changes before closing connection.")
2238
+ try:
2239
+ self._conn.rollback()
2240
+ except RuntimeError as e:
2241
+ rollback_error = e
2242
+ # TODO: Check potential race conditions in case of multithreaded scenarios
2243
+ # Close the connection
2244
+ try:
2245
+ self._conn.close(manual_commit and rollback_error is None)
2246
+ except RuntimeError as e:
2247
+ _raise_connection_error(e)
2248
+ finally:
2249
+ self._conn = None
2250
+ if rollback_error is not None:
2251
+ # Preserve prior DB-API error mapping after deterministic cleanup.
2252
+ _raise_connection_error(rollback_error)
2253
+ if autocommit_error is not None:
2254
+ _raise_connection_error(autocommit_error)
2255
+ except Exception as e:
2256
+ logger.error(f"Error closing database connection: {e}")
2257
+ # Re-raise the connection close error as it's more critical
2258
+ raise
2259
+ finally:
2260
+ # Always mark as closed, even if there were errors
2261
+ self._closed = True
2262
+
2263
+ logger.info("Connection closed successfully.")
2264
+
2265
+ def _remove_cursor(self, cursor: Cursor) -> None:
2266
+ """
2267
+ Remove a cursor from the connection's tracking.
2268
+
2269
+ This method is called when a cursor is closed to ensure proper cleanup.
2270
+
2271
+ Args:
2272
+ cursor: The cursor to remove from tracking.
2273
+ """
2274
+ if hasattr(self, "_cursors"):
2275
+ try:
2276
+ self._cursors.discard(cursor)
2277
+ except Exception:
2278
+ pass # Ignore errors during cleanup
2279
+
2280
+ def __enter__(self) -> "Connection":
2281
+ """
2282
+ Enter the context manager.
2283
+
2284
+ This method enables the Connection to be used with the 'with' statement.
2285
+ When entering the context, it simply returns the connection object itself.
2286
+
2287
+ Returns:
2288
+ Connection: The connection object itself.
2289
+
2290
+ Example:
2291
+ with connect(connection_string) as conn:
2292
+ cursor = conn.cursor()
2293
+ cursor.execute("INSERT INTO table VALUES (?)", [value])
2294
+ # Transaction will be committed automatically when exiting
2295
+ """
2296
+ logger.info("Entering connection context manager.")
2297
+ return self
2298
+
2299
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
2300
+ """
2301
+ Exit the context manager.
2302
+
2303
+ Implements commit-on-success / rollback-on-exception semantics:
2304
+ - If the block exits cleanly and autocommit is off, the transaction
2305
+ is committed.
2306
+ - If an exception is raised and autocommit is off, the transaction
2307
+ is rolled back.
2308
+ - The connection is always closed when leaving the block.
2309
+
2310
+ If commit() fails on clean exit, the connection is closed and the
2311
+ commit exception is raised. On exception exit, cleanup failures
2312
+ (rollback or close) are suppressed so the original user exception
2313
+ propagates unchanged.
2314
+ """
2315
+ if self._closed:
2316
+ return
2317
+ try:
2318
+ if not self.autocommit:
2319
+ if exc_type is None:
2320
+ self.commit()
2321
+ else:
2322
+ self.rollback()
2323
+ except Exception:
2324
+ try:
2325
+ self.close()
2326
+ except Exception:
2327
+ logger.warning(
2328
+ "Failed to close connection after failed "
2329
+ "commit/rollback in context manager.",
2330
+ exc_info=True,
2331
+ )
2332
+ if exc_type is None:
2333
+ raise
2334
+ return
2335
+ try:
2336
+ self.close()
2337
+ except Exception:
2338
+ if exc_type is None:
2339
+ raise
2340
+ logger.warning(
2341
+ "Failed to close connection in context manager.",
2342
+ exc_info=True,
2343
+ )
2344
+
2345
+ def __del__(self) -> None:
2346
+ """
2347
+ Destructor to ensure the connection is closed when the connection object
2348
+ is no longer needed.
2349
+ This is a safety net to ensure resources are cleaned up
2350
+ even if close() was not called explicitly.
2351
+ """
2352
+ if "_closed" not in self.__dict__ or not self._closed:
2353
+ try:
2354
+ self.close()
2355
+ except Exception as e:
2356
+ # Dont raise exceptions from __del__ to avoid issues during garbage collection
2357
+ logger.warning(f"Error during connection cleanup: {e}")