Skip to content

Commit 9b4cd66

Browse files
jahnvi480Copilot
andauthored
FIX: Preserve executemany values with lossless batch inference (#907)
### Work Item / Issue Reference <!-- IMPORTANT: Please follow the PR template guidelines below. For mssql-python maintainers: Insert your ADO Work Item ID below For external contributors: Insert Github Issue number below Only one reference is required - either GitHub issue OR ADO Work Item. --> <!-- mssql-python maintainers: ADO Work Item --> > [AB#50465](https://sqlclientdrivers.visualstudio.com/c6d89619-62de-46a0-8b46-70b92a84d85e/_workitems/edit/50465) <!-- External contributors: GitHub Issue --> > N/A — maintainer ADO reference above. ------------------------------------------------------------------- ### Summary <!-- Insert your summary of changes below. Minimum 10 characters required. --> Fix lossless `executemany` inference across Unicode, Decimal, and mixed-type batches. Compute batch text metadata natively, preserve explicit overrides and rowcounts, and retain embedded/trailing NULs during binding and retrieval. Add boundary, ordering, NULL, subclass, and recovery regression coverage. Validation: **2,287 related runtime tests passed**, with 64 existing/platform/build-dependent skips; **4 strict typing checks passed**; pinned full-directory formatting and `git diff --check` passed. Validation used Windows x64, Python 3.13.17, and SQL Server 15.0.4382.1. Cross-platform CI is still required. Native metadata computation avoids Python character loops and encoded copies. Local long-Unicode benchmarks were 61–76% faster than the earlier correct fix. Comparisons with original HEAD had small variable differences; no zero-overhead guarantee. Incompatible mixed types use slower individual execution to preserve values. <!-- ### PR Title Guide > For feature requests FEAT: (short-description) > For non-feature requests like test case updates, config updates , dependency updates etc CHORE: (short-description) > For Fix requests FIX: (short-description) > For doc update requests DOC: (short-description) > For Formatting, indentation, or styling update STYLE: (short-description) > For Refactor, without any feature changes REFACTOR: (short-description) > For performance improvements PERF: (short-description) > For AI tooling, agents, skills, prompts, or AI-assisted development workflows AI: (short-description) > For release related changes RELEASE: #<RELEASE_VERSION> (short-description) ### Contribution Guidelines External contributors: - Create a GitHub issue first: https://github.com/microsoft/mssql-python/issues/new - Link the GitHub issue in the "GitHub Issue" section above - Follow the PR title format and provide a meaningful summary mssql-python maintainers: - Create an ADO Work Item following internal processes - Link the ADO Work Item in the "ADO Work Item" section above - Follow the PR title format and provide a meaningful summary --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent f3cc8c9 commit 9b4cd66

10 files changed

Lines changed: 1062 additions & 154 deletions

‎README.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,38 @@ example, requesting ASCII with `SQL_CHAR` does not cause non-ASCII parameters to
174174
raise encoding errors. Use `setencoding()` with no arguments to restore the
175175
supported defaults. `setdecoding()` independently controls how result data is read.
176176

177+
### Batch parameter inference
178+
179+
For automatically inferred `executemany()` text columns, any non-ASCII value
180+
makes the entire parameter column `NVARCHAR`; ASCII-only columns retain `VARCHAR`
181+
inference. Buffer sizes and the streaming threshold use the maximum UTF-16
182+
code-unit length across all rows, not just the longest Python string. Embedded
183+
NUL characters are preserved using explicit text lengths. Batch text metadata
184+
is computed natively without allocating encoded copies of each string; BMP-only
185+
strings do not require a character-by-character scan.
186+
Wide-character retrieval of `VARCHAR(MAX)` values uses a non-consuming binary
187+
length probe to size the conversion buffer, avoiding character loss at truncated
188+
UTF-16 conversion boundaries while preserving embedded and trailing NULs.
189+
Explicit `setinputsizes()` SQL types and sizes still take precedence. An explicit
190+
`VARCHAR` parameter can lose characters outside the database collation's code
191+
page even when inserting into an `NVARCHAR` destination; use `SQL_WVARCHAR` when
192+
Unicode preservation is required.
193+
194+
Automatically inferred Decimal columns use a `NUMERIC` precision and scale
195+
covering every row. Their formatted text buffer capacity is separate from SQL
196+
precision, so signs and decimal points do not change the declared numeric type.
197+
If individually valid Decimals cannot share a lossless precision/scale within SQL
198+
Server's 38-digit limit, the batch uses individual `execute()` calls. Columns
199+
mixing incompatible Python types (for example, integers and Decimals, or dates
200+
and datetimes) or naive and timezone-aware datetimes also use individual calls
201+
rather than coercing every value through one sample's type. Boolean/integer and
202+
bytes/bytearray mixtures, and mixtures of strings with `str` subclasses remain
203+
eligible for array binding. Explicit `setinputsizes()` overrides retain their
204+
specified SQL types, precision and scale, including numeric normalization during
205+
individual execution.
206+
Individual execution is slower than array binding; known affected-row counts are
207+
summed across the batch, or `rowcount` is `-1` if any execution's count is unknown.
208+
177209
## Getting Started Examples
178210
Connect to SQL Server and execute a simple query:
179211

‎mssql_python/_ddbc_types.pyi‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,8 @@ class EncodingSettings(TypedDict):
5959
encoding: str
6060
ctype: int
6161

62+
def _batch_text_metadata(column: list[Any]) -> tuple[bool, int]: ...
63+
6264
class ColumnMetadata(TypedDict):
6365
ColumnName: str
6466
DataType: int
@@ -105,6 +107,7 @@ class ParamInfo:
105107
paramCType: int
106108
paramSQLType: int
107109
columnSize: int
110+
arrayBufferSize: int
108111
decimalDigits: int
109112
strLenOrInd: int
110113
dataPtr: object

‎mssql_python/cursor.py‎

Lines changed: 123 additions & 71 deletions
Large diffs are not rendered by default.

‎mssql_python/ddbc_bindings.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
_abort_native_fetch_install as _abort_native_fetch_install,
2121
_activate_native_fetch_install as _activate_native_fetch_install,
2222
_begin_native_fetch_install as _begin_native_fetch_install,
23+
_batch_text_metadata as _batch_text_metadata,
2324
_disable_native_fetch_install as _disable_native_fetch_install,
2425
_fetch_conversion_ineligible as _fetch_conversion_ineligible,
2526
_fetch_observer as _fetch_observer,

‎mssql_python/pybind/ddbc_bindings.cpp‎

Lines changed: 74 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -2507,6 +2507,7 @@ SQLRETURN BindParameterArray(SqlHandle& handle, SQLHANDLE hStmt, const py::list&
25072507
for (int paramIndex = 0; paramIndex < columnwise_params.size(); ++paramIndex) {
25082508
const py::list& columnValues = columnwise_params[paramIndex].cast<py::list>();
25092509
ParamInfo& info = paramInfos[paramIndex];
2510+
const SQLULEN bufferSize = std::max(info.columnSize, info.arrayBufferSize);
25102511
LOG("BindParameterArray: Processing param_index=%d, C_type=%d, "
25112512
"SQL_type=%d, column_size=%zu, decimal_digits=%d",
25122513
paramIndex, info.paramCType, info.paramSQLType, info.columnSize,
@@ -2566,32 +2567,33 @@ SQLRETURN BindParameterArray(SqlHandle& handle, SQLHANDLE hStmt, const py::list&
25662567
"param_index=%d, count=%zu, column_size=%zu",
25672568
paramIndex, paramSetSize, info.columnSize);
25682569
SQLWCHAR* wcharArray = AllocateParamBufferArray<SQLWCHAR>(
2569-
tempBuffers, paramSetSize * (info.columnSize + 1));
2570+
tempBuffers, paramSetSize * (bufferSize + 1));
25702571
strLenOrIndArray = AllocateParamBufferArray<SQLLEN>(tempBuffers, paramSetSize);
25712572
for (size_t i = 0; i < paramSetSize; ++i) {
25722573
if (columnValues[i].is_none()) {
25732574
strLenOrIndArray[i] = SQL_NULL_DATA;
2574-
std::memset(wcharArray + i * (info.columnSize + 1), 0,
2575-
(info.columnSize + 1) * sizeof(SQLWCHAR));
2575+
std::memset(wcharArray + i * (bufferSize + 1), 0,
2576+
(bufferSize + 1) * sizeof(SQLWCHAR));
25762577
} else {
25772578
std::u16string wstr = columnValues[i].cast<std::u16string>();
25782579
// u16string is already UTF-16, so the
25792580
// original check is sufficient
2580-
if (wstr.length() > info.columnSize) {
2581+
if (wstr.length() > bufferSize) {
25812582
ThrowStdException("Input string exceeds allowed column size "
25822583
"at parameter index " +
25832584
std::to_string(paramIndex));
25842585
}
2585-
std::memcpy(wcharArray + i * (info.columnSize + 1), wstr.c_str(),
2586+
std::memcpy(wcharArray + i * (bufferSize + 1), wstr.c_str(),
25862587
(wstr.length() + 1) * sizeof(SQLWCHAR));
2587-
strLenOrIndArray[i] = SQL_NTS;
2588+
strLenOrIndArray[i] =
2589+
static_cast<SQLLEN>(wstr.length() * sizeof(SQLWCHAR));
25882590
}
25892591
}
25902592
LOG("BindParameterArray: SQL_C_WCHAR bound - "
25912593
"param_index=%d",
25922594
paramIndex);
25932595
dataPtr = wcharArray;
2594-
bufferLength = (info.columnSize + 1) * sizeof(SQLWCHAR);
2596+
bufferLength = (bufferSize + 1) * sizeof(SQLWCHAR);
25952597
break;
25962598
}
25972599
case SQL_C_TINYINT:
@@ -2663,13 +2665,13 @@ SQLRETURN BindParameterArray(SqlHandle& handle, SQLHANDLE hStmt, const py::list&
26632665
"param_index=%d, count=%zu, column_size=%zu, encoding='%s'",
26642666
paramIndex, paramSetSize, info.columnSize, charEncoding.c_str());
26652667
char* charArray = AllocateParamBufferArray<char>(
2666-
tempBuffers, paramSetSize * (info.columnSize + 1));
2668+
tempBuffers, paramSetSize * (bufferSize + 1));
26672669
strLenOrIndArray = AllocateParamBufferArray<SQLLEN>(tempBuffers, paramSetSize);
26682670
for (size_t i = 0; i < paramSetSize; ++i) {
26692671
if (columnValues[i].is_none()) {
26702672
strLenOrIndArray[i] = SQL_NULL_DATA;
2671-
std::memset(charArray + i * (info.columnSize + 1), 0,
2672-
info.columnSize + 1);
2673+
std::memset(charArray + i * (bufferSize + 1), 0,
2674+
bufferSize + 1);
26732675
} else {
26742676
std::string encodedStr;
26752677

@@ -2699,15 +2701,15 @@ SQLRETURN BindParameterArray(SqlHandle& handle, SQLHANDLE hStmt, const py::list&
26992701
encodedStr = columnValues[i].cast<std::string>();
27002702
}
27012703

2702-
if (encodedStr.size() > info.columnSize) {
2704+
if (encodedStr.size() > bufferSize) {
27032705
LOG("BindParameterArray: String/binary too "
27042706
"long - param_index=%d, row=%zu, size=%zu, "
27052707
"max=%zu",
27062708
paramIndex, i, encodedStr.size(), info.columnSize);
27072709
ThrowStdException("Input exceeds column size at index " +
27082710
std::to_string(i));
27092711
}
2710-
std::memcpy(charArray + i * (info.columnSize + 1), encodedStr.c_str(),
2712+
std::memcpy(charArray + i * (bufferSize + 1), encodedStr.c_str(),
27112713
encodedStr.size());
27122714
strLenOrIndArray[i] = static_cast<SQLLEN>(encodedStr.size());
27132715
}
@@ -2716,7 +2718,7 @@ SQLRETURN BindParameterArray(SqlHandle& handle, SQLHANDLE hStmt, const py::list&
27162718
"param_index=%d",
27172719
paramIndex);
27182720
dataPtr = charArray;
2719-
bufferLength = info.columnSize + 1;
2721+
bufferLength = bufferSize + 1;
27202722
break;
27212723
}
27222724
case SQL_C_BIT: {
@@ -3462,23 +3464,51 @@ SQLRETURN SQLFetch_wrap(SqlHandlePtr StatementHandle) {
34623464
// Non-static so it can be called from inline functions in header
34633465
py::object FetchLobColumnData(SQLHSTMT hStmt, SQLUSMALLINT colIndex, SQLSMALLINT cType,
34643466
bool isWideChar, bool isBinary, const std::string& charEncoding,
3465-
py::handle messages) {
3467+
py::handle messages, bool sizeWideConversion) {
34663468
PERF_TIMER("FetchLobColumnData");
34673469
std::vector<char> buffer;
34683470
SQLRETURN ret = SQL_SUCCESS_WITH_INFO;
34693471
int loopCount = 0;
3472+
size_t chunkSize = DAE_CHUNK_SIZE;
3473+
if (sizeWideConversion) {
3474+
// Unix drivers can consume characters that do not fit during a truncated
3475+
// VARCHAR-to-WCHAR conversion. A binary probe does not consume data and
3476+
// bounds UTF-16 output by two bytes per source byte, plus the terminator.
3477+
SQLLEN sourceLength = 0;
3478+
{
3479+
py::gil_scoped_release release;
3480+
ret = SQLGetData_ptr(hStmt, colIndex, SQL_C_BINARY, nullptr, 0, &sourceLength);
3481+
}
3482+
CaptureFetchDiagnostics(hStmt, ret, messages, true);
3483+
if (!SQL_SUCCEEDED(ret)) {
3484+
ThrowStdException("SQLGetData failed to probe the UTF-16 LOB length");
3485+
}
3486+
if (sourceLength == SQL_NULL_DATA) {
3487+
return py::none();
3488+
}
3489+
if (sourceLength < 0 ||
3490+
sourceLength > (std::numeric_limits<SQLLEN>::max() -
3491+
static_cast<SQLLEN>(sizeof(SQLWCHAR))) / 2) {
3492+
ThrowStdException("SQLGetData returned an invalid UTF-16 LOB source length");
3493+
}
3494+
chunkSize = std::max(chunkSize, static_cast<size_t>(sourceLength) * 2 + sizeof(SQLWCHAR));
3495+
}
34703496

34713497
while (true) {
34723498
++loopCount;
3473-
std::vector<char> chunk(DAE_CHUNK_SIZE, 0);
3499+
std::vector<char> chunk(chunkSize, 0);
34743500
SQLLEN actualRead = 0;
34753501
{
34763502
// Release the GIL during blocking SQLGetData LOB streaming
34773503
py::gil_scoped_release release;
3478-
ret = SQLGetData_ptr(hStmt, colIndex, cType, chunk.data(), DAE_CHUNK_SIZE, &actualRead);
3504+
ret = SQLGetData_ptr(hStmt, colIndex, cType, chunk.data(),
3505+
static_cast<SQLLEN>(chunkSize), &actualRead);
34793506
}
34803507
CaptureFetchDiagnostics(hStmt, ret, messages, true);
34813508

3509+
if (ret == SQL_NO_DATA) {
3510+
break;
3511+
}
34823512
if (ret == SQL_ERROR || !SQL_SUCCEEDED(ret) && ret != SQL_SUCCESS_WITH_INFO) {
34833513
std::ostringstream oss;
34843514
oss << "Error fetching LOB for column " << colIndex << ", cType=" << cType
@@ -3491,50 +3521,36 @@ py::object FetchLobColumnData(SQLHSTMT hStmt, SQLUSMALLINT colIndex, SQLSMALLINT
34913521
return py::none();
34923522
}
34933523

3524+
const size_t terminatorSize = isBinary ? 0 : (isWideChar ? sizeof(SQLWCHAR) : 1);
3525+
const size_t payloadCapacity = chunkSize - terminatorSize;
34943526
size_t bytesRead = 0;
34953527
if (actualRead >= 0) {
3496-
bytesRead = static_cast<size_t>(actualRead);
3497-
if (bytesRead > DAE_CHUNK_SIZE) {
3498-
bytesRead = DAE_CHUNK_SIZE;
3499-
}
3528+
// ODBC lengths exclude the terminator; payload NULs must not be trimmed.
3529+
bytesRead = std::min(static_cast<size_t>(actualRead), payloadCapacity);
3530+
} else if (actualRead == SQL_NO_TOTAL && ret == SQL_SUCCESS_WITH_INFO) {
3531+
bytesRead = payloadCapacity;
35003532
} else {
3501-
// fallback: use full buffer size if actualRead is unknown
3502-
bytesRead = DAE_CHUNK_SIZE;
3533+
ThrowStdException("SQLGetData returned an invalid LOB length indicator");
35033534
}
3504-
3505-
// For character data, trim trailing null terminators
3506-
if (!isBinary && bytesRead > 0) {
3507-
if (!isWideChar) {
3508-
// Narrow characters
3509-
while (bytesRead > 0 && chunk[bytesRead - 1] == '\0') {
3510-
--bytesRead;
3511-
}
3512-
if (bytesRead < DAE_CHUNK_SIZE) {
3513-
LOG("FetchLobColumnData: Trimmed null terminator from "
3514-
"narrow char data - loop=%d",
3515-
loopCount);
3516-
}
3535+
if (isWideChar && bytesRead % sizeof(SQLWCHAR) != 0) {
3536+
ThrowStdException("SQLGetData returned an unaligned UTF-16 LOB length");
3537+
}
3538+
if (sizeWideConversion && (actualRead == SQL_NO_TOTAL ||
3539+
static_cast<size_t>(actualRead) > payloadCapacity)) {
3540+
ThrowStdException("SQLGetData exceeded the probed UTF-16 LOB buffer size");
3541+
}
3542+
if (bytesRead > 0) {
3543+
if (buffer.empty()) {
3544+
buffer.swap(chunk);
3545+
buffer.resize(bytesRead);
35173546
} else {
3518-
// Wide characters
3519-
size_t wcharSize = sizeof(SQLWCHAR);
3520-
if (bytesRead >= wcharSize && (bytesRead % wcharSize == 0)) {
3521-
size_t wcharCount = bytesRead / wcharSize;
3522-
std::vector<SQLWCHAR> alignedBuf(wcharCount);
3523-
std::memcpy(alignedBuf.data(), chunk.data(), bytesRead);
3524-
while (wcharCount > 0 && alignedBuf[wcharCount - 1] == 0) {
3525-
--wcharCount;
3526-
bytesRead -= wcharSize;
3527-
}
3528-
if (bytesRead < DAE_CHUNK_SIZE) {
3529-
LOG("FetchLobColumnData: Trimmed null terminator from "
3530-
"wide char data - loop=%d",
3531-
loopCount);
3532-
}
3547+
if (bytesRead > buffer.max_size() - buffer.size()) {
3548+
ThrowStdException("SQLGetData LOB exceeds the maximum buffer size");
35333549
}
3550+
const size_t offset = buffer.size();
3551+
buffer.resize(offset + bytesRead);
3552+
std::copy_n(chunk.data(), bytesRead, buffer.data() + offset);
35343553
}
3535-
}
3536-
if (bytesRead > 0) {
3537-
buffer.insert(buffer.end(), chunk.begin(), chunk.begin() + bytesRead);
35383554
LOG("FetchLobColumnData: Appended %zu bytes at loop %d", bytesRead, loopCount);
35393555
}
35403556
if (ret == SQL_SUCCESS) {
@@ -3806,7 +3822,7 @@ static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT co
38063822
i, useWideChar ? "SQL_C_WCHAR" : "SQL_C_CHAR", (unsigned long)columnSize);
38073823
if (useWideChar) {
38083824
row.append(FetchLobColumnData(hStmt, i, SQL_C_WCHAR, true, false,
3809-
"utf-16le", messages));
3825+
"utf-16le", messages, true));
38103826
} else {
38113827
row.append(FetchLobColumnData(hStmt, i, SQL_C_CHAR, false, false,
38123828
effectiveCharEnc, messages));
@@ -3851,7 +3867,7 @@ static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT co
38513867
"truncated, using streaming LOB",
38523868
i);
38533869
row.append(FetchLobColumnData(hStmt, i, SQL_C_WCHAR, true, false,
3854-
"utf-16le", messages));
3870+
"utf-16le", messages, true));
38553871
}
38563872
} else if (dataLen == SQL_NULL_DATA) {
38573873
LOG("SQLGetData: Column %d is NULL (CHAR via WCHAR)", i);
@@ -3867,7 +3883,7 @@ static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT co
38673883
"streaming via FetchLobColumnData",
38683884
i);
38693885
row.append(FetchLobColumnData(hStmt, i, SQL_C_WCHAR, true, false,
3870-
"utf-16le", messages));
3886+
"utf-16le", messages, true));
38713887
} else if (dataLen < 0) {
38723888
LOG("SQLGetData: Unexpected negative data length "
38733889
"for column %d - dataType=%d, dataLen=%ld",
@@ -6823,6 +6839,7 @@ PYBIND11_MODULE(ddbc_bindings, m) {
68236839

68246840
// Expose the C++ functions to Python
68256841
m.def("ThrowStdException", &ThrowStdException);
6842+
m.def("_batch_text_metadata", &BatchTextMetadata);
68266843
m.def("GetDriverPathCpp", &GetDriverPathCpp, "Get the path to the ODBC driver");
68276844
m.def("_get_odbc_driver_path", &GetDriverPathForProviderCpp,
68286845
"Get the ODBC driver path for an explicit provider without selecting it");
@@ -6836,6 +6853,7 @@ PYBIND11_MODULE(ddbc_bindings, m) {
68366853
.def_readwrite("paramCType", &ParamInfo::paramCType)
68376854
.def_readwrite("paramSQLType", &ParamInfo::paramSQLType)
68386855
.def_readwrite("columnSize", &ParamInfo::columnSize)
6856+
.def_readwrite("arrayBufferSize", &ParamInfo::arrayBufferSize)
68396857
.def_readwrite("decimalDigits", &ParamInfo::decimalDigits)
68406858
.def_readwrite("strLenOrInd", &ParamInfo::strLenOrInd)
68416859
.def_property(

‎mssql_python/pybind/ddbc_bindings.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -540,7 +540,7 @@ struct ColumnInfoExt {
540540
// outside namespace
541541
py::object FetchLobColumnData(SQLHSTMT hStmt, SQLUSMALLINT col, SQLSMALLINT cType, bool isWideChar,
542542
bool isBinary, const std::string& charEncoding = "utf-8",
543-
py::handle messages = {});
543+
py::handle messages = {}, bool sizeWideConversion = false);
544544

545545
// Specialized column processors for each data type (eliminates switch in hot
546546
// loop)
@@ -722,7 +722,7 @@ inline void ProcessChar(PyObject* row, ColumnBuffers& buffers, const void* colIn
722722
// LOB / truncated: stream with SQL_C_WCHAR
723723
PyList_SET_ITEM(row, col - 1,
724724
FetchLobColumnData(hStmt, col, SQL_C_WCHAR, true, false, "utf-16le",
725-
py::handle(colInfo->messages))
725+
py::handle(colInfo->messages), true)
726726
.release()
727727
.ptr());
728728
}

0 commit comments

Comments
 (0)