Skip to content

NULL value cast as NUMERIC crashes under fetchone() #242

@zzzeek

Description

@zzzeek

Describe the bug

fetching a NULL value (directly or from a table column) while CASTing to NUMERIC causes the type coercion to fail under fetchone(). It does not fail under fetchall() or fetchmany() but I suspect this is also a bug due to #241.

Traceback (most recent call last):
  File "/home/classic/dev/sqlalchemy/test3.py", line 23, in <module>
    row = cursor.fetchone()
  File "/home/classic/.venv3/lib64/python3.13/site-packages/mssql_python/cursor.py", line 959, in fetchone
    raise e
  File "/home/classic/.venv3/lib64/python3.13/site-packages/mssql_python/cursor.py", line 939, in fetchone
    ret = ddbc_bindings.DDBCSQLFetchOne(self.hstmt, row_data)
ValueError: basic_string::_M_create
from mssql_python import connect
import uuid

conn_str = "UID=scott;PWD=tiger^5HHH;Server=mssql2022;Database=test;Encrypt=No"
conn = connect(conn_str)

cursor = conn.cursor()

cursor.execute("SELECT schema_name()")
schema_name = cursor.fetchone()[0]

cursor.execute(
    "SELECT CAST(57483735 AS NUMERIC(38,0))"
)
# works
row = cursor.fetchone()


cursor.execute(
    "SELECT CAST(NULL AS NUMERIC(38,0))"
)
# ValueError: basic_string::_M_create
row = cursor.fetchone()

Expected behavior

should return None

Further technical details

Python version: 3.13
SQL Server version: (e.g. SQL Server 2022) SQL Server 2022
Operating system: (e.g. Windows Server 2022, Ubuntu 24.04, macOS 14.7.1, Docker container)
Fedora 40

Additional context
We use this cast in SQLAlchemy in one of our table reflection queries that SELECTS from sys.identity_columns using a LEFT OUTER JOIN where most of the column values come back as NULL as it's an outer join.

Metadata

Metadata

Assignees

Labels

Triage DoneIssues that are triaged by dev team and are in investigation.

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions