FIX: Segmentation Fault when interleaving fetchmany and fetchone calls #427 by gargsaumya · Pull Request #441 · microsoft/mssql-python

Pull request overview

This pull request fixes a critical segmentation fault that occurred when interleaving fetchmany() and fetchone() calls on a database cursor (GitHub Issue #427). The root cause was that fetchmany() and fetchall() bind ODBC columns to memory buffers for performance, but fetchone() uses SQLGetData to retrieve data, which cannot be used on already-bound columns. The fix unbinds columns after bound fetch operations and at the start of fetchone() to prevent conflicts.

Changes:

  • Added comprehensive tests for interleaving fetchmany() and fetchone() calls to prevent regression
  • Fixed the segmentation fault by unbinding columns after fetchmany() and fetchall() operations
  • Enhanced error handling in FetchOne_wrap to properly detect and report SQLGetData failures

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
tests/test_017_fetchmany_fetchone_interleave.py New test file with three test cases covering basic interleaved fetch scenarios (fetchmany→fetchone, fetchone→fetchmany, and multiple alternating calls)
mssql_python/pybind/ddbc_bindings.cpp Added SQLFreeStmt(SQL_UNBIND) calls in FetchMany_wrap, FetchAll_wrap, and FetchOne_wrap; improved error handling in FetchOne_wrap to return early on SQLGetData failure

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.