Repository navigation
FEAT: async POC - #677
Draft
Subrata (subrata-ms) wants to merge 8 commits into
Draft
FEAT: async POC#677Subrata (subrata-ms) wants to merge 8 commits into
Subrata (subrata-ms) wants to merge 8 commits into
Conversation
Introduces the foundational C++ building blocks for the upcoming Cursor.execute_async / Cursor.fetch_async work. No user-facing API is exposed yet; sync execute/fetch paths are functionally unchanged. Helpers added in ddbc_bindings.cpp: - struct PollingConfig (initial_ms=0.5, max_ms=20, multiplier=1.5) - class AsyncEnableGuard: RAII sets/clears SQL_ATTR_ASYNC_ENABLE on an HSTMT so the async flag never leaks onto a handle reused by later sync calls. - template<Fn> ExecuteWithPolling(callOnce, asyncMode, cfg): sync passthrough when asyncMode=false; polling loop with exponential backoff when asyncMode=true. Caller owns GIL release. - PrepareAndBind(...): factored out of SQLExecute_wrap (SQLPrepare under released GIL, DescribeCache clear, isStmtPrepared flag update, BindParameters). Enables reuse from upcoming async execute wrap. SQLExecute_wrap refactored to route both branches through the helpers with asyncMode=false (semantic no-op vs. the previous inline calls). DAE loop unchanged. Capability probe: - Connection::isAsyncCapable() / ConnectionHandle::isAsyncCapable() probes SQLGetInfo(SQL_ASYNC_MODE), caches the value in an atomic int (SQL_AM_STATEMENT / SQL_AM_CONNECTION => true). Exposed to Python as Connection.is_async_capable(). Build: clean under -Werror -Wattributes -Wint-to-pointer-cast.
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/cursor.pyLines 3526-3534 3526 per connection.
3527 """
3528 conn = self._connection._conn
3529 if not conn.is_async_capable():
! 3530 raise NotSupportedError(
3531 driver_error=(
3532 "Async execution is not supported by this ODBC driver. "
3533 "SQLGetInfo(SQL_ASYNC_MODE) reports SQL_AM_NONE."
3534 ),Lines 3537-3545 3537
3538 def _acquire_async_slot(self) -> None:
3539 """Take the cursor-busy slot; raise ProgrammingError if already held."""
3540 if self._async_in_flight:
! 3541 raise ProgrammingError(
3542 driver_error=(
3543 "Cursor is busy: another async operation is already in flight "
3544 "on this cursor. One Cursor == one HSTMT, so async ops on the "
3545 "same cursor must be serialized. Create a second cursor for "Lines 3575-3590 3575 if reset_cursor:
3576 if self.hstmt:
3577 self._soft_reset_cursor()
3578 else:
! 3579 self._reset_cursor()
3580 else:
! 3581 if self.hstmt:
3582 logger.debug(
3583 "execute_async: Closing cursor for re-execution (reset_cursor=False)"
3584 )
! 3585 self.hstmt._close_cursor()
! 3586 self._clear_rownumber()
3587
3588 # Clear any previous messages
3589 self.messages = []Lines 3590-3603 3590
3591 # Parameter unwrap (same rules as sync execute).
3592 if parameters:
3593 if isinstance(parameters, tuple) and len(parameters) == 1:
! 3594 if isinstance(parameters[0], (tuple, list, dict)):
! 3595 actual_params = parameters[0]
! 3596 elif isinstance(parameters[0], Row):
! 3597 actual_params = tuple(parameters[0])
3598 else:
! 3599 actual_params = parameters
3600 else:
3601 actual_params = parameters
3602
3603 if operation == self.last_executed_stmt and isinstance(Lines 3602-3610 3602
3603 if operation == self.last_executed_stmt and isinstance(
3604 actual_params, (tuple, list)
3605 ):
! 3606 parameters = list(actual_params)
3607 else:
3608 operation, converted_params = detect_and_convert_parameters(
3609 operation, actual_params
3610 )Lines 3609-3617 3609 operation, actual_params
3610 )
3611 parameters = list(converted_params)
3612 else:
! 3613 parameters = []
3614
3615 encoding_settings = self._get_encoding_settings()
3616
3617 logger.debug("execute_async: Creating parameter type list")Lines 3618-3627 3618 param_info = ddbc_bindings.ParamInfo
3619 parameters_type: List[Any] = []
3620
3621 if parameters and self._inputsizes:
! 3622 if len(self._inputsizes) != len(parameters):
! 3623 warnings.warn(
3624 f"Number of input sizes ({len(self._inputsizes)}) does not match "
3625 f"number of parameters ({len(parameters)}). "
3626 f"This may lead to unexpected behavior.",
3627 Warning,Lines 3657-3668 3657 DELIBERATE DUPLICATE of the corresponding logic in ``execute()``.
3658 """
3659 try:
3660 check_error(ddbc_sql_const.SQL_HANDLE_STMT.value, self.hstmt, ret)
! 3661 except Exception as e: # pylint: disable=broad-exception-caught
3662 logger.warning("execute_async failed, resetting cursor: %s", e)
! 3663 self._reset_cursor()
! 3664 raise
3665
3666 self._capture_diagnostics(ret)
3667 self.last_executed_stmt = operation
3668 self.rowcount = ddbc_bindings.DDBCSQLRowCount(self.hstmt)Lines 3670-3680 3670 column_metadata: List[Any] = []
3671 try:
3672 ddbc_bindings.DDBCSQLDescribeCol(self.hstmt, column_metadata)
3673 self._initialize_description(column_metadata)
! 3674 except Exception: # pylint: disable=broad-exception-caught
3675 # If describe fails, it's likely there are no results (e.g. INSERT)
! 3676 self.description = None
3677
3678 if self.description:
3679 self.rowcount = -1
3680 self._reset_rownumber()Lines 3688-3701 3688 )
3689 self._cached_converter_map = self._build_converter_map()
3690 self._uuid_str_indices = self._compute_uuid_str_indices()
3691 else:
! 3692 self.rowcount = ddbc_bindings.DDBCSQLRowCount(self.hstmt)
! 3693 self._clear_rownumber()
! 3694 self._cached_column_map = None
! 3695 self._cached_column_map_lower = None
! 3696 self._cached_converter_map = None
! 3697 self._uuid_str_indices = None
3698
3699 self._reset_inputsizes()
3700
3701 def _wrap_row_async(self, row_data: List[Any]) -> Row:Lines 3711-3721 3711 )
3712
3713 def _wrap_rows_async(self, rows_data: List[List[Any]]) -> List[Row]:
3714 """Async-only mirror of fetchmany() / fetchall()'s Row-construction block."""
! 3715 column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
! 3716 uuid_idx = |
This pull request adds support for detecting and caching ODBC driver async capabilities, which is a foundational step for enabling asynchronous operations (such as
execute_async) on SQL Server connections. The changes ensure that the driver’s support for asynchronous execution is probed once per connection and cached for efficient future checks. Additionally, the connection string parsing is updated to clarify and safely handle the enabling of Multiple Active Result Sets (MARS).Async capability detection and caching:
_asyncModeCache) in theConnectionclass to store the result of probingSQLGetInfo(SQL_ASYNC_MODE), minimizing redundant driver queries and improving performance for async operations.isAsyncCapable()method in bothConnectionandConnectionHandle, which checks and caches whether the driver supports statement-level or connection-level async, and is used as a capability gate before enabling async features. [1] [2] [3]Connection string handling improvements:
constants.pyto explicitly document and support the ODBC-standardMARS_Connectionparameter, while warning against using the SQL Server-nativeMultipleActiveResultSetsalias unless driver support is confirmed, preventing user confusion and unpredictable behavior.Work Item / Issue Reference
Summary