Visitar URL original
[QUESTION/FEATURE] How to cancel a query? · Issue #424 · microsoft/mssql-python · GitHub
Skip to content

[QUESTION/FEATURE] How to cancel a query? #424

Description

@sdebruyn

Context: I'm creating an implementation of dbt-fabric that uses this driver.

How would I cancel a submitted query? Does the query cancel when the thread that is running cursor.execute gets killed?

Activity

  1. dlevy-msft-sql commented on Feb 8, 2026

    @dlevy-msft-sql
    Contributor

    There's no cursor.cancel() or connection.cancel() API today — this is a gap we need to close.

    Additionally, the GIL is currently held during SQLExecDirect/SQLExecute in the C++ layer, so cursor.execute() blocks the entire Python interpreter, not just the calling thread. That means killing the thread won't interrupt the underlying ODBC call.

    Calling cursor.close() or connection.close() from another thread during an in-flight query is not safe — it would free the statement handle while the ODBC driver is still using it.

    To support cancellation properly, we'd need to:

    1. Release the GIL during ODBC execute calls (so other threads can run)
    2. Expose SQLCancel(hstmt) as a cursor.cancel() method (thread-safe per the ODBC spec — SQLCancel is one of the few ODBC functions that can be called from a different thread)
    3. Handle the HY008 (Operation canceled) SQLSTATE that comes back (error mapping already exists)

    For now, the closest thing to a workaround is setting a query timeout via the connection string (Connection Timeout / Command Timeout) or SET LOCK_TIMEOUT in SQL.

    Tagging this as a feature request. The "Asynchronous Query Execution" item on our roadmap (Q1 2026) overlaps with this — cancel support would be a natural prerequisite.

  2. sdebruyn commented on Feb 8, 2026

    @sdebruyn
    Author

    Thanks! Would changing the timeout have any effect on running queries? So if I'd set the timeout to 1, would that immediately stop the running query (given it's been running for a second)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: api-compliancePython API behavior and typing: DB-API 2.0, exceptions, type stubs, new APIs.enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions