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