Skip to content

FEAT: async POC - #677

Draft
Subrata (subrata-ms) wants to merge 8 commits into
mainfrom
subrata-ms/AsyncQueryImpl
Draft

Subrata (subrata-ms) wants to merge 8 commits into
mainfrom
subrata-ms/AsyncQueryImpl

Conversation

@subrata-ms

@subrata-ms Subrata (subrata-ms) commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Added an atomic cache (_asyncModeCache) in the Connection class to store the result of probing SQLGetInfo(SQL_ASYNC_MODE), minimizing redundant driver queries and improving performance for async operations.
  • Implemented the isAsyncCapable() method in both Connection and ConnectionHandle, 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]
  • Included necessary header for atomic operations.

Connection string handling improvements:

  • Updated the connection string allowlist in constants.py to explicitly document and support the ODBC-standard MARS_Connection parameter, while warning against using the SQL Server-native MultipleActiveResultSets alias unless driver support is confirmed, preventing user confusion and unpredictable behavior.

Work Item / Issue Reference

AB#<WORK_ITEM_ID>

GitHub Issue: #<ISSUE_NUMBER>


Summary

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.
@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

72%


🎯 Overall Coverage

80%


📈 Total Lines Covered: 6973 out of 8673
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/cursor.py (59.1%): Missing lines 3530,3541,3579,3581,3585-3586,3594-3597,3599,3606,3613,3622-3623,3661,3663-3664,3674,3676,3692-3697,3715-3717,3851,3887,3892-3893,3899,3901-3904,3916,3918,3920-3921,3925-3927,3929-3930,3932,3934,3937-3942,3955,3957-3958,3962-3964,3966-3967,3969,3971
  • mssql_python/pybind/connection/connection.cpp (61.8%): Missing lines 646-647,649-651,657,659-661,672-673,679-680
  • mssql_python/pybind/ddbc_bindings.cpp (82.5%): Missing lines 1849-1851,1859-1860,1885-1887,1893-1894,1903-1907,1914-1915,2021-2022,2038-2039,2041-2042,2048-2050,2052-2053,2201-2204,2214,4179-4182,4770-4771,6031-6032

Summary

  • Total: 427 lines
  • Missing: 119 lines
  • Coverage: 72%

mssql_python/cursor.py

Lines 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 =