From a4e986c164bb22ceee7848d009693094cec9ea1b Mon Sep 17 00:00:00 2001 From: ziyziy89 Date: Fri, 6 Nov 2026 22:41:14 +0530 Subject: [PATCH 01/22] reject negative scale in fast_executemany PyToCType (#1515) --- src/params.cpp | 4 ++-- tests/sqlite_test.py | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/params.cpp b/src/params.cpp index cf240388..7a12aeb0 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -225,7 +225,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI static PyObject *tenObject; // Need to scale by 10**pi->DecimalDigits - if (pi->DecimalDigits > 38) + if (pi->DecimalDigits < 0 || pi->DecimalDigits > 38) { NumericOverflow: RaiseErrorV(0, ProgrammingError, "Numeric overflow"); @@ -347,7 +347,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI pts->second = PyDateTime_DATE_GET_SECOND(cell); // Truncate the fraction according to precision - size_t digits = min(9, pi->DecimalDigits); + size_t digits = (pi->DecimalDigits > 0) ? min(9, pi->DecimalDigits) : 0; long fast_pow10[] = {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000}; SQLUINTEGER milliseconds = PyDateTime_DATE_GET_MICROSECOND(cell) * 1000; pts->fraction = milliseconds - (milliseconds % fast_pow10[9 - digits]); diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index f3bd94fc..9800c3ad 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -104,6 +104,15 @@ def test_different_bindings(cursor: pyodbc.Cursor): cursor.execute("insert into t2 values (?)", datetime.now()) # noqa: DTZ005 +def test_fast_executemany_negative_scale(cursor: pyodbc.Cursor): + "A negative decimal scale must not be used to index the scaling table" + cursor.execute("create table t1(n numeric(18, 0))") + cursor.fast_executemany = True + cursor.setinputsizes([(pyodbc.SQL_DECIMAL, 18, -1)]) + with pytest.raises(pyodbc.ProgrammingError, match="Numeric overflow"): + cursor.executemany("insert into t1 values (?)", [(123,)]) + + def test_drivers(): p = pyodbc.drivers() assert isinstance(p, list) From 916e4866c14e8c003e690e75c2503a1ff93fa4e9 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 11:38:35 -0600 Subject: [PATCH 02/22] params: fix crashes in fast_executemany, TVP binding, and Decimal parameters - fast_executemany: an error while sending data-at-execution parameters returned without resetting SQL_ATTR_PARAMSET_SIZE and SQL_ATTR_PARAM_BIND_OFFSET_PTR (left pointing at a local), so the next execute on the cursor failed or crashed. Route those errors through the normal cleanup, cancelling first if SQLPutData failed. - fast_executemany: reject Decimals that cannot fit in SQL_NUMERIC_STRUCT before building the scaled digit tuple, and check the results of the Python calls that follow. - Decimal NaN and Infinity raise a ProgrammingError instead of crashing. as_tuple() and UUID.bytes_le results are checked before use. - CreateDecimalString uses Py_ssize_t lengths and counters. - TVP type and schema names must be str; encoding failures are raised instead of passing NULL to PyBytes_AsString. Row and value references are held while in use, NULL results are checked, and an empty first row is now caught by the "same size" check. - fast_executemany checks the row buffer size for overflow. --- src/params.cpp | 280 +++++++++++++++++++++++++++++----------- tests/sqlserver_test.py | 72 +++++++++++ 2 files changed, 275 insertions(+), 77 deletions(-) diff --git a/src/params.cpp b/src/params.cpp index 7a12aeb0..a6f8bce2 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -191,6 +191,51 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) return true; } +static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp) +{ + // Calls value.as_tuple() and checks that the result is the (sign, digits, exponent) tuple + // a Decimal returns, since a subclass can override as_tuple. NaN and Infinity have a str + // exponent and cannot be bound. + + if (!parts.Attach(PyObject_CallMethod(value, "as_tuple", 0))) + return false; + + PyObject* t = parts.Get(); + if (!PyTuple_Check(t) || PyTuple_GET_SIZE(t) != 3 || !PyTuple_Check(PyTuple_GET_ITEM(t, 1))) + { + PyErr_SetString(PyExc_TypeError, "Decimal.as_tuple() did not return (sign, digits, exponent)"); + return false; + } + + if (!PyLong_Check(PyTuple_GET_ITEM(t, 2))) + { + RaiseErrorV(0, ProgrammingError, "Cannot bind a Decimal NaN or Infinity"); + return false; + } + + sign = PyLong_AsLong(PyTuple_GET_ITEM(t, 0)); + exp = PyLong_AsSsize_t(PyTuple_GET_ITEM(t, 2)); + if (PyErr_Occurred()) + return false; + + digits = PyTuple_GET_ITEM(t, 1); + return true; +} + +static bool GetUUIDBytes(PyObject* value, Object& bytes) +{ + // Returns value.bytes_le, checking that it is 16 bytes since a subclass can override it. + // (Do we need to use "bytes" on a big endian machine?) + if (!bytes.Attach(PyObject_GetAttrString(value, "bytes_le"))) + return false; + if (!PyBytes_Check(bytes.Get()) || PyBytes_GET_SIZE(bytes.Get()) != sizeof(SQLGUID)) + { + PyErr_SetString(PyExc_TypeError, "UUID.bytes_le must be 16 bytes"); + return false; + } + return true; +} + #define WRITEOUT(type, ptr, val, indv) { *(type*)(*ptr) = (val); *ptr += sizeof(type); indv = sizeof(type); } // Convert Python object into C data for binding. // Output pointer is written to with data, indicator, and updated. @@ -424,9 +469,8 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI if (pi->ValueType != SQL_C_GUID) return false; pi->BufferLength = 16; - // Do we need to use "bytes" on a big endian machine? - Object b(PyObject_GetAttrString(cell, "bytes_le")); - if (!b) + Object b; + if (!GetUUIDBytes(cell, b)) return false; memcpy(*outbuf, PyBytes_AS_STRING(b.Get()), sizeof(SQLGUID)); *outbuf += pi->BufferLength; @@ -440,14 +484,15 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI // by hand rather than by calling Decimal.normalize(): normalize() rounds the value to // the calling thread's decimal context precision (28 digits by default), which // silently corrupts values with more significant digits (up to 38 are valid). - PyObject *cellParts = PyObject_CallMethod(cell, "as_tuple", 0); - if (!cellParts) + Object cellParts; + long sign; + PyObject* digits; + Py_ssize_t exp; + if (!GetDecimalParts(cell, cellParts, sign, digits, exp)) return false; SQL_NUMERIC_STRUCT *pNum = (SQL_NUMERIC_STRUCT*)*outbuf; - pNum->sign = !PyLong_AsLong(PyTuple_GET_ITEM(cellParts, 0)); - PyObject* digits = PyTuple_GET_ITEM(cellParts, 1); - long exp = PyLong_AsLong(PyTuple_GET_ITEM(cellParts, 2)); + pNum->sign = !sign; Py_ssize_t numDigits = PyTuple_GET_SIZE(digits); // Strip trailing zeros (e.g. 1.50 -> 1.5, 100 -> 1E+2) so the "loses precision" check @@ -470,35 +515,51 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI return false; } + // The 16-byte val holds at most 39 digits, so anything longer cannot fit. Checking + // here also keeps a huge exponent from sizing the tuple below. + if (numDigits + scaleDiff > 39) + { + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; + } + // Append '0's to the end of the digits to effect the scaling. - PyObject *newDigits = PyTuple_New(numDigits + scaleDiff); + Object newDigits(PyTuple_New(numDigits + scaleDiff)); + if (!newDigits) + return false; for (Py_ssize_t i = 0; i < numDigits; i++) { - PyTuple_SET_ITEM(newDigits, i, PyLong_FromLong(PyNumber_AsSsize_t(PyTuple_GET_ITEM(digits, i), 0))); + PyObject* digit = PyLong_FromSsize_t(PyNumber_AsSsize_t(PyTuple_GET_ITEM(digits, i), 0)); + if (!digit) + return false; + PyTuple_SET_ITEM(newDigits.Get(), i, digit); } for (Py_ssize_t i = numDigits; i < scaleDiff + numDigits; i++) { - PyTuple_SET_ITEM(newDigits, i, PyLong_FromLong(0)); + PyObject* zero = PyLong_FromLong(0); + if (!zero) + return false; + PyTuple_SET_ITEM(newDigits.Get(), i, zero); } - PyObject *args = Py_BuildValue("((iOi))", 0, newDigits, 0); - PyObject *scaledDecimal = PyObject_CallObject((PyObject*)cell->ob_type, args); - PyObject *digitLong = PyNumber_Long(scaledDecimal); - - Py_XDECREF(args); - Py_XDECREF(scaledDecimal); - Py_XDECREF(newDigits); - Py_XDECREF(cellParts); + Object args(Py_BuildValue("((iOi))", 0, newDigits.Get(), 0)); + if (!args) + return false; + Object scaledDecimal(PyObject_CallObject((PyObject*)cell->ob_type, args)); + if (!scaledDecimal) + return false; + Object digitLong(PyNumber_Long(scaledDecimal)); + if (!digitLong) + return false; pNum->precision = (SQLCHAR)pi->ColumnSize; pNum->scale = (SQLCHAR)pi->DecimalDigits; #if PY_VERSION_HEX < 0x030D0000 - int ret = _PyLong_AsByteArray((PyLongObject*)digitLong, pNum->val, sizeof(pNum->val), 1, 0); + int ret = _PyLong_AsByteArray((PyLongObject*)digitLong.Get(), pNum->val, sizeof(pNum->val), 1, 0); #else - int ret = _PyLong_AsByteArray((PyLongObject*)digitLong, pNum->val, sizeof(pNum->val), 1, 0, 1); + int ret = _PyLong_AsByteArray((PyLongObject*)digitLong.Get(), pNum->val, sizeof(pNum->val), 1, 0, 1); #endif - Py_XDECREF(digitLong); if (ret) { PyErr_Clear(); @@ -790,14 +851,21 @@ static bool GetFloatInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamIn return true; } -static char* CreateDecimalString(long sign, PyObject* digits, long exp) +static char* CreateDecimalString(long sign, PyObject* digits, Py_ssize_t exp) { - // Allocate an ASCII string containing the given decimal. + // Allocate an ASCII string containing the given decimal. Lengths and counters are + // Py_ssize_t because a Decimal's exponent can be far larger than an int (or a 32-bit long). - long count = (long)PyTuple_GET_SIZE(digits); + Py_ssize_t count = PyTuple_GET_SIZE(digits); + Py_ssize_t ndigits = (exp >= 0) ? count + exp : max(count, -exp); + if (ndigits > PY_SSIZE_T_MAX - 4) + { + PyErr_NoMemory(); + return 0; + } char* pch; - long len; + Py_ssize_t len; if (exp >= 0) { @@ -810,9 +878,9 @@ static char* CreateDecimalString(long sign, PyObject* digits, long exp) char* p = pch; if (sign) *p++ = '-'; - for (long i = 0; i < count; i++) + for (Py_ssize_t i = 0; i < count; i++) *p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i))); - for (long i = 0; i < exp; i++) + for (Py_ssize_t i = 0; i < exp; i++) *p++ = '0'; *p = 0; } @@ -828,7 +896,7 @@ static char* CreateDecimalString(long sign, PyObject* digits, long exp) char* p = pch; if (sign) *p++ = '-'; - int i = 0; + Py_ssize_t i = 0; for (; i < (count + exp); i++) *p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i))); *p++ = '.'; @@ -852,16 +920,19 @@ static char* CreateDecimalString(long sign, PyObject* digits, long exp) *p++ = '0'; *p++ = '.'; - for (int i = 0; i < -(exp + count); i++) + for (Py_ssize_t i = 0; i < -(exp + count); i++) *p++ = '0'; - for (int i = 0; i < count; i++) + for (Py_ssize_t i = 0; i < count; i++) *p++ = (char)('0' + PyLong_AS_LONG(PyTuple_GET_ITEM(digits, i))); *p++ = 0; } } - assert(pch == 0 || (int)(strlen(pch) + 1) == len); + if (!pch) + PyErr_NoMemory(); + + assert(pch == 0 || (Py_ssize_t)(strlen(pch) + 1) == len); return pch; } @@ -883,9 +954,8 @@ static bool GetUUIDInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInf return false; } - // Do we need to use "bytes" on a big endian machine? - Object b(PyObject_GetAttrString(param, "bytes_le")); - if (!b) + Object b; + if (!GetUUIDBytes(param, b)) return false; memcpy(info.ParameterValuePtr, PyBytes_AS_STRING(b.Get()), sizeof(SQLGUID)); info.StrLen_or_Ind = sizeof(SQLGUID); @@ -902,14 +972,13 @@ static bool GetDecimalInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param // string. Unfortunately, the Decimal class doesn't seem to have a way to force it to return a string without // exponents, so we'll have to build it ourselves. - Object t(PyObject_CallMethod(param, "as_tuple", 0)); - if (!t) + Object t; + long sign; + PyObject* digits; + Py_ssize_t exp; + if (!GetDecimalParts(param, t, sign, digits, exp)) return false; - long sign = PyLong_AsLong(PyTuple_GET_ITEM(t.Get(), 0)); - PyObject* digits = PyTuple_GET_ITEM(t.Get(), 1); - long exp = PyLong_AsLong(PyTuple_GET_ITEM(t.Get(), 2)); - Py_ssize_t count = PyTuple_GET_SIZE(digits); info.ValueType = SQL_C_CHAR; @@ -940,10 +1009,7 @@ static bool GetDecimalInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param info.ParameterValuePtr = CreateDecimalString(sign, digits, exp); if (!info.ParameterValuePtr) - { - PyErr_NoMemory(); return false; - } info.allocated = true; info.StrLen_or_Ind = (SQLINTEGER)strlen((char*)info.ParameterValuePtr); @@ -1176,11 +1242,12 @@ static bool UpdateParamInfo(Cursor* pCursor, Py_ssize_t nIndex, ParamInfo *pInfo // Peek at a Decimal value to get binding needed information without serializing it to a string. static bool GetDecimalPrecisionAndScale(PyObject* value, SQLULEN& precision, SQLSMALLINT& scale) { - Object t(PyObject_CallMethod(value, "as_tuple", 0)); - if (!t) + Object t; + long sign; + PyObject* digits; + Py_ssize_t exp; + if (!GetDecimalParts(value, t, sign, digits, exp)) return false; - PyObject* digits = PyTuple_GET_ITEM(t.Get(), 1); - long exp = PyLong_AsLong(PyTuple_GET_ITEM(t.Get(), 2)); Py_ssize_t count = PyTuple_GET_SIZE(digits); if (exp >= 0) { precision = (SQLULEN)((SQLUINTEGER)count + exp); @@ -1197,34 +1264,59 @@ static bool GetDecimalPrecisionAndScale(PyObject* value, SQLULEN& precision, SQL return true; } +static bool SetTVPName(Cursor* cur, SQLHDESC desc, Py_ssize_t index, SQLSMALLINT field, PyObject* name) +{ + // Sets the TVP's type or schema name (`field`) on the IPD. + if (!PyUnicode_Check(name)) + { + PyErr_Format(PyExc_TypeError, "A TVP's type and schema names must be str, not %s", + Py_TYPE(name)->tp_name); + return false; + } + + Object encoded(PyCodec_Encode(name, "UTF-16LE", "strict")); + if (!encoded) + return false; + + SQLRETURN ret = SQLSetDescFieldW(desc, (SQLSMALLINT)(index + 1), field, + (SQLPOINTER)PyBytes_AS_STRING(encoded.Get()), + (SQLINTEGER)PyBytes_GET_SIZE(encoded.Get())); + if (!SQL_SUCCEEDED(ret)) + { + RaiseErrorFromHandle(cur->cnxn, "SQLSetDescFieldW", GetConnection(cur)->hdbc, cur->hstmt); + return false; + } + return true; +} + // Helper for BindParameter, which was getting unwieldy enough already. static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) { // Register the type name and schema for the TVP if provided (they'll be strings // instead of sequences). Py_ssize_t sequenceSize = PySequence_Size(info.pObject); + if (sequenceSize < 0) + return false; Py_ssize_t dataStart = 0; if (sequenceSize > 0) { - PyObject *cell0 = PySequence_GetItem(info.pObject, 0); - Py_XDECREF(cell0); + Object cell0(PySequence_GetItem(info.pObject, 0)); + if (!cell0) + return false; if (PyBytes_Check(cell0) || PyUnicode_Check(cell0)) { ++dataStart; SQLHDESC desc; - PyObject *tvpname = PyCodec_Encode(cell0, "UTF-16LE", 0); SQLGetStmtAttr(cur->hstmt, SQL_ATTR_IMP_PARAM_DESC, &desc, 0, 0); - SQLSetDescFieldW(desc, index + 1, SQL_CA_SS_TYPE_NAME, - (SQLPOINTER)PyBytes_AsString(tvpname), PyBytes_Size(tvpname)); - Py_XDECREF(tvpname); + if (!SetTVPName(cur, desc, index, SQL_CA_SS_TYPE_NAME, cell0)) + return false; if (sequenceSize > 1) { - PyObject *cell1 = PySequence_GetItem(info.pObject, 1); - Py_XDECREF(cell1); + Object cell1(PySequence_GetItem(info.pObject, 1)); + if (!cell1) + return false; if (PyBytes_Check(cell1) || PyUnicode_Check(cell1)) { ++dataStart; - PyObject *tvpschema = PyCodec_Encode(cell1, "UTF-16LE", 0); - SQLSetDescFieldW(desc, index + 1, SQL_CA_SS_SCHEMA_NAME, - (SQLPOINTER)PyBytes_AsString(tvpschema), PyBytes_Size(tvpschema)); - Py_XDECREF(tvpschema); + if (!SetTVPName(cur, desc, index, SQL_CA_SS_SCHEMA_NAME, cell1)) + return false; } } } @@ -1238,17 +1330,21 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) Py_ssize_t ncols = 0; Py_ssize_t nrows = sequenceSize - dataStart; for (Py_ssize_t r = 0; r < nrows; ++r) { - PyObject* row = PySequence_GetItem(info.pObject, r + dataStart); - Py_XDECREF(row); + Object row(PySequence_GetItem(info.pObject, r + dataStart)); + if (!row) + return false; if (!PySequence_Check(row)) { PyErr_SetString(ProgrammingError, "A TVP's rows must be Sequence objects."); return false; } - if (ncols && ncols != PySequence_Size(row)) { + Py_ssize_t size = PySequence_Size(row); + if (size < 0) + return false; + if (r > 0 && size != ncols) { RaiseErrorV(0, ProgrammingError, "A TVP's rows must all be the same size."); return false; } - ncols = PySequence_Size(row); + ncols = size; } // If the TVP is empty we're done. @@ -1309,20 +1405,22 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) // Check the row's value for each parameter for which we still need information. bool keep_scanning = false; - PyObject* row = PySequence_GetItem(info.pObject, dataStart + r); - Py_XDECREF(row); + Object row(PySequence_GetItem(info.pObject, dataStart + r)); + if (!row) + return false; for (Py_ssize_t i = 0; i < ncols; i++) { if (bindinfo[i].confirmed) continue; keep_scanning = true; - PyObject* value = PySequence_GetItem(row, i); - Py_XDECREF(value); + Object value(PySequence_GetItem(row, i)); + if (!value) + return false; // Populate the nested array from the first row in the nested vector. if (r == 0) { // Populate nested[i] directly for the first row, even for NULLs. - if (!GetParameterInfo(cur, i, value, info.nested[i], true)) + if (!GetParameterInfo(cur, i, value.Get(), info.nested[i], true)) return false; bindinfo[i].vtype = info.nested[i].ValueType; bindinfo[i].ptype = info.nested[i].ParameterType; @@ -1341,7 +1439,7 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) // is Decimal (so we need to make sure we bind the column with a precision and // scale which can handle all the values in the TVP for the column). else { - if (value == Py_None) + if (value.Get() == Py_None) continue; if (info.nested[i].ParameterType == SQL_NUMERIC) { @@ -1349,7 +1447,9 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) // Bump up digit counts if appropriate. SQLULEN precision; SQLSMALLINT scale; - if (!GetDecimalPrecisionAndScale(value, precision, scale)) { + if (!GetDecimalPrecisionAndScale(value.Get(), precision, scale)) { + if (!PyErr_ExceptionMatches(PyExc_AttributeError)) + return false; RaiseErrorV(0, PyExc_TypeError, "Expected Decimal but got %s (TVP column %d)", Py_TYPE(value)->tp_name, i); return false; @@ -1363,7 +1463,7 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) // All we have so far are NULL values, so we're trying to discover the true type. ParamInfo tempinfo; memset(&tempinfo, 0, sizeof(tempinfo)); - if (!GetParameterInfo(cur, i, value, tempinfo, true)) + if (!GetParameterInfo(cur, i, value.Get(), tempinfo, true)) return false; // We're not going to use the actual value yet, so make sure memory gets cleaned up. @@ -1712,6 +1812,7 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) // Start at a non-zero offset to prevent null pointer detection. char *bindptr = (char*)16; + Py_ssize_t rowlen = 0; Py_ssize_t i = 0; for (; i < cur->paramcount; i++) @@ -1739,13 +1840,26 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) SQLSetDescField(desc, i + 1, SQL_DESC_SCALE, (SQLPOINTER)(uintptr_t)cur->paramInfos[i].DecimalDigits, 0); SQLSetDescField(desc, i + 1, SQL_DESC_DATA_PTR, bindptr, 0); } - bindptr += cur->paramInfos[i].BufferLength + sizeof(SQLLEN); + // BufferLength comes from the driver's (or setinputsizes') column size, so make sure + // the row length cannot overflow. + SQLLEN cbParam = cur->paramInfos[i].BufferLength; + if (cbParam < 0 || rowlen > PY_SSIZE_T_MAX - (Py_ssize_t)sizeof(SQLLEN) - cbParam) + { + RaiseErrorV(0, ProgrammingError, "Parameter %zd is too large for fast_executemany", i + 1); + goto ErrorRet4; + } + rowlen += cbParam + sizeof(SQLLEN); + bindptr += cbParam + sizeof(SQLLEN); } - Py_ssize_t rowlen = bindptr - (char*)16; // Assume parameters are homogeneous between rows in the common case, to avoid // another rescan for determining the array height. // Subtract number of rows processed as an upper bound. + if (rowlen > 0 && (rowcount - r) > PY_SSIZE_T_MAX / rowlen) + { + PyErr_NoMemory(); + goto ErrorRet4; + } if (!(cur->paramArray = (unsigned char*)PyMem_Malloc(rowlen * (rowcount - r)))) { PyErr_NoMemory(); @@ -1873,7 +1987,10 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) Py_END_ALLOW_THREADS if (rc != SQL_NEED_DATA && rc != SQL_NO_DATA && !SQL_SUCCEEDED(rc)) - return RaiseErrorFromHandle(cur->cnxn, "SQLParamData", cur->cnxn->hdbc, cur->hstmt) != NULL; + { + RaiseErrorFromHandle(cur->cnxn, "SQLParamData", cur->cnxn->hdbc, cur->hstmt); + goto ErrorRet8; + } TRACE("SQLParamData() --> %d\n", rc); @@ -1938,7 +2055,13 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) rc = SQLPutData(cur->hstmt, (SQLPOINTER)&p[offset], remaining); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(rc)) - return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt) != NULL; + { + RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt); + // The statement is still waiting for data. Cancel it so the + // attribute resets below are not rejected as a sequence error. + SQLCancel(cur->hstmt); + goto ErrorRet8; + } offset += remaining; } while (offset < cb); @@ -1954,7 +2077,10 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) } if (!SQL_SUCCEEDED(rc) && rc != SQL_NO_DATA) - return RaiseErrorFromHandle(cur->cnxn, szLastFunction, cur->cnxn->hdbc, cur->hstmt) != NULL; + { + RaiseErrorFromHandle(cur->cnxn, szLastFunction, cur->cnxn->hdbc, cur->hstmt); + goto ErrorRet8; + } SQLSetStmtAttr(cur->hstmt, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)1, SQL_IS_UINTEGER); SQLSetStmtAttr(cur->hstmt, SQL_ATTR_PARAM_BIND_OFFSET_PTR, 0, SQL_IS_POINTER); diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index 4e5ea63c..f449649a 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -438,6 +438,40 @@ def test_decimal_e(cursor: pyodbc.Cursor): assert result == value +def test_decimal_fast_executemany_huge_exponent(cursor: pyodbc.Cursor): + """An exponent far too large for SQL_NUMERIC_STRUCT is an overflow, not a crash.""" + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = True + # The largest exponent decimal allows, which is smaller on 32-bit platforms. + value = Decimal(f"1E+{decimal.MAX_EMAX}") + with pytest.raises(pyodbc.ProgrammingError, match="Numeric overflow"): + cursor.executemany("insert into t1 values (?)", [(value,)]) + + +@pytest.mark.parametrize("fast", [False, True]) +@pytest.mark.parametrize("value", ["NaN", "sNaN", "Infinity", "-Infinity"]) +def test_decimal_special_values_rejected(cursor: pyodbc.Cursor, fast, value): + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = fast + with pytest.raises(pyodbc.ProgrammingError, match="NaN or Infinity"): + cursor.executemany("insert into t1 values (?)", [(Decimal(value),)]) + + +def test_fast_executemany_cursor_usable_after_dae_error(cursor: pyodbc.Cursor): + """ + An error while sending data-at-execution (max-type) parameters must restore the + cursor's parameter-array settings, or the next execute on the cursor fails or crashes. + """ + cursor.execute("create table t1(id int primary key, v varchar(max))") + cursor.execute("insert into t1 values (1, 'x')") + cursor.fast_executemany = True + with pytest.raises(pyodbc.IntegrityError): + cursor.executemany("insert into t1 values (?, ?)", [(i, "a") for i in range(1, 6)]) + + cursor.execute("insert into t1(id, v) values (?, ?)", 100, "z") + assert cursor.execute("select v from t1 where id = 100").fetchval() == "z" + + @pytest.mark.parametrize("prec", [10, 28, 38]) def test_decimal_fast_executemany_ignores_context_precision(cursor: pyodbc.Cursor, prec): """ @@ -1863,6 +1897,44 @@ def test_tvp_with_nulls(cursor: pyodbc.Cursor): cursor.commit() +@pytest.fixture +def tvp_count_proc(cursor: pyodbc.Cursor) -> Iterator[str]: + """A procedure taking a one-int-column TVP and returning its row count.""" + cursor.execute("drop procedure if exists tvp_count_p") + cursor.execute("drop type if exists tvp_count_t") + cursor.execute("create type tvp_count_t as table (n int)") + cursor.execute("create procedure tvp_count_p @t tvp_count_t readonly" + " as select count(*) from @t") + cursor.commit() + yield "{call tvp_count_p(?)}" + cursor.execute("drop procedure if exists tvp_count_p") + cursor.execute("drop type if exists tvp_count_t") + cursor.commit() + + +@pytest.mark.skipif(SQLSERVER_YEAR < 2008, reason="TVP not supported until 2008") +@pytest.mark.skipif(IS_FREETDS, reason="FreeTDS does not support TVP") +def test_tvp_name_errors(cursor: pyodbc.Cursor, tvp_count_proc: str): + """Type and schema names that can't be used raise instead of crashing.""" + rows = ["tvp_count_t", "dbo", (1,), (2,)] + assert cursor.execute(tvp_count_proc, (rows,)).fetchval() == 2 + + with pytest.raises(TypeError, match="must be str"): + cursor.execute(tvp_count_proc, ([b"tvp_count_t", "dbo", (1,)],)) + with pytest.raises(TypeError, match="must be str"): + cursor.execute(tvp_count_proc, (["tvp_count_t", b"dbo", (1,)],)) + with pytest.raises(UnicodeEncodeError): + cursor.execute(tvp_count_proc, (["tvp_count_t\ud800", "dbo", (1,)],)) + + +@pytest.mark.skipif(SQLSERVER_YEAR < 2008, reason="TVP not supported until 2008") +@pytest.mark.skipif(IS_FREETDS, reason="FreeTDS does not support TVP") +def test_tvp_empty_first_row(cursor: pyodbc.Cursor, tvp_count_proc: str): + """An empty first row followed by a non-empty one is a shape error, not a crash.""" + with pytest.raises(pyodbc.ProgrammingError, match="same size"): + cursor.execute(tvp_count_proc, (["tvp_count_t", "dbo", (), (1,)],)) + + @pytest.mark.skipif(SQLSERVER_YEAR < 2000, reason='sql_variant not supported until 2000') def test_sql_variant(cursor: pyodbc.Cursor): """ From eebd0ee700ada21d446be98ad980ee560952e882 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 11:32:42 -0600 Subject: [PATCH 03/22] setinputsizes: default the scale to the existing scale, not the size A (sqltype, size) tuple with no scale set DecimalDigits to the column size, so (SQL_DECIMAL, 18) bound as decimal(18, 18) and values like 123 were out of range. Keep the described/derived scale instead. --- src/params.cpp | 2 +- tests/sqlserver_test.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/params.cpp b/src/params.cpp index a6f8bce2..070948c1 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -1223,7 +1223,7 @@ static bool UpdateParamInfo(Cursor* pCursor, Py_ssize_t nIndex, ParamInfo *pInfo { pInfo->ParameterType = (SQLSMALLINT)getSequenceValue(desc, 0, (long)pInfo->ParameterType, rc); pInfo->ColumnSize = (SQLUINTEGER)getSequenceValue(desc, 1, (long)pInfo->ColumnSize, rc); - pInfo->DecimalDigits = (SQLSMALLINT)getSequenceValue(desc, 2, (long)pInfo->ColumnSize, rc); + pInfo->DecimalDigits = (SQLSMALLINT)getSequenceValue(desc, 2, (long)pInfo->DecimalDigits, rc); } Py_CLEAR(desc); diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index f449649a..fd7b7798 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -511,6 +511,21 @@ def test_decimal_fast_executemany_trailing_zeros(cursor: pyodbc.Cursor): assert [r.v for r in rows] == values +@pytest.mark.parametrize("fast", [False, True]) +def test_setinputsizes_without_scale(cursor: pyodbc.Cursor, fast): + """ + A (sqltype, size) input size with no scale must keep the existing scale, not use the + size as the scale. Scale 18 with precision 18 made both values out of range. + """ + cursor.execute("create table t1(id int, v decimal(18, 2))") + cursor.fast_executemany = fast + cursor.setinputsizes([None, (pyodbc.SQL_DECIMAL, 18)]) + cursor.executemany("insert into t1(id, v) values (?, ?)", [(0, 123), (1, Decimal("4.5"))]) + + rows = cursor.execute("select v from t1 order by id").fetchall() + assert [r.v for r in rows] == [Decimal("123.00"), Decimal("4.50")] + + def test_subquery_params(cursor: pyodbc.Cursor): """Ensure parameter markers work in a subquery""" cursor.execute("create table t1(id integer, s varchar(20))") From 04fe0da377eafeb03a0bd7a500641127a3f271a7 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 11:40:24 -0600 Subject: [PATCH 04/22] row: fix crashes deleting columns and reading a bad column map - `del row[i]` and `del row.name` passed a NULL value to Row_ass_item, which INCREF'd it. Raise TypeError instead. - Row_getattro used the column map's value as an index without a bounds check. The map comes from the unpickle constructor, so check it. - Row_richcompare treated an error from PyObject_RichCompareBool as "not equal" and continued with the exception set. Propagate it. --- src/row.cpp | 23 +++++++++++++++++++++-- tests/sqlite_test.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/row.cpp b/src/row.cpp index 4298a721..d04bc5f1 100644 --- a/src/row.cpp +++ b/src/row.cpp @@ -176,7 +176,15 @@ static PyObject* Row_getattro(PyObject* o, PyObject* name) if (index) { + // The map can come from an unpickled Row, so don't trust its values. Py_ssize_t i = PyNumber_AsSsize_t(index, 0); + if (i == -1 && PyErr_Occurred()) + return 0; + if (i < 0 || i >= self->cValues) + { + PyErr_SetString(PyExc_IndexError, "Row column index out of range"); + return 0; + } Py_INCREF(self->apValues[i]); return self->apValues[i]; } @@ -225,10 +233,16 @@ PyObject* Row_item(PyObject* o, Py_ssize_t i) static int Row_ass_item(PyObject* o, Py_ssize_t i, PyObject* v) { - // Implements row[i] = value. + // Implements row[i] = value. Python passes a NULL value for `del row[i]`. Row* self = (Row*)o; + if (!v) + { + PyErr_SetString(PyExc_TypeError, "Row columns cannot be deleted"); + return -1; + } + if (i < 0 || i >= self->cValues) { PyErr_SetString(PyExc_IndexError, "Row assignment index out of range"); @@ -309,8 +323,13 @@ static PyObject* Row_richcompare(PyObject* olhs, PyObject* orhs, int op) } for (Py_ssize_t i = 0, c = lhs->cValues; i < c; i++) - if (!PyObject_RichCompareBool(lhs->apValues[i], rhs->apValues[i], Py_EQ)) + { + int eq = PyObject_RichCompareBool(lhs->apValues[i], rhs->apValues[i], Py_EQ); + if (eq < 0) + return 0; + if (!eq) return PyObject_RichCompare(lhs->apValues[i], rhs->apValues[i], op); + } // All items are equal. switch (op) diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 9800c3ad..c28b52d5 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -663,6 +663,36 @@ def test_row_gtlt(cursor: pyodbc.Cursor): rows.sort() # uses < +def test_row_delete_column(cursor: pyodbc.Cursor): + "Deleting a Row column raises instead of crashing" + row = cursor.execute("select 1 as a").fetchone() + with pytest.raises(TypeError): + del row[0] + with pytest.raises(TypeError): + del row.a + assert row.a == 1 + + +def test_row_bad_name_map(): + "A Row whose column map points outside the row raises instead of reading past it" + for index in (100000, -5): + row = pyodbc.Row(("x",), {"a": index}, 1) + with pytest.raises(IndexError): + row.a + + +def test_row_compare_error(): + "An exception from comparing two values propagates out of the Row comparison" + class Uncomparable: + def __eq__(self, other): + raise ValueError("no comparing") + + row1 = pyodbc.Row(("a",), {"a": 0}, Uncomparable()) + row2 = pyodbc.Row(("a",), {"a": 0}, Uncomparable()) + with pytest.raises(ValueError, match="no comparing"): + row1 == row2 # noqa: B015 + + def _test_context_manager(connection_string): # TODO: This is failing, but it may be due to the design of sqlite. I've disabled it # for now until I can research it some more. From 5cd1a619fe607103ac733069df43be2feef62ae1 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 11:44:19 -0600 Subject: [PATCH 05/22] cursor: fix crashes in catalog functions, fetchval, and TVP execution - Catalog functions (tables, columns, primaryKeys, ...) on a closed cursor passed NULL to free_results. Raise "Attempt to use a closed cursor." - fetchval with rows_as_dicts passed the dict to Row_item. Always fetch a Row for fetchval. - If create_name_map failed (e.g. a column name that can't be decoded), colinfos stayed allocated with no description or map, and the next fetch read through them. Free colinfos on failure. - TVP data-at-execution: the column loop used the row's current length rather than the number of bound columns, released the row and cell before using them, and didn't check for NULL. Bound the loop by the nested bindings, hold the references (including the cell whose buffer the driver reads), and check errors. - Errors while sending data-at-execution parameters now cancel the statement, so the cursor is usable afterwards instead of failing with HY010. --- src/cursor.cpp | 126 ++++++++++++++++++++++++++++++++-------- tests/sqlite_test.py | 29 +++++++++ tests/sqlserver_test.py | 63 ++++++++++++++++++++ 3 files changed, 194 insertions(+), 24 deletions(-) diff --git a/src/cursor.cpp b/src/cursor.cpp index b525e190..fbbedbcf 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -151,7 +151,7 @@ static bool create_name_map(Cursor* cur, SQLSMALLINT field_count, bool lower) if (cur->cnxn->hdbc == SQL_NULL_HANDLE) { RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); - return false; + goto done; } desc = PyTuple_New((Py_ssize_t)field_count); @@ -308,6 +308,14 @@ static bool create_name_map(Cursor* cur, SQLSMALLINT field_count, bool lower) Py_XDECREF(colinfo); PyMem_Free(szName); + if (!success) + { + // Without a description and map the results can't be read, so drop the column info + // too. Otherwise fetch would see colinfos and assume both are set. + PyMem_Free(cur->colinfos); + cur->colinfos = 0; + } + return success; } @@ -741,6 +749,17 @@ int GetDiagRecs(Cursor* cur) } +static PyObject* CancelDataAtExec(Cursor* cur, PyObject* result) +{ + // Called when an error interrupts sending data-at-execution parameters. The statement is + // still waiting for data, so cancel it or every later call on the cursor (including + // freeing the parameters) fails with a function sequence error. Returns `result`. + Py_BEGIN_ALLOW_THREADS + SQLCancel(cur->hstmt); + Py_END_ALLOW_THREADS + return result; +} + static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool skip_first) { // Internal function to execute SQL, called by .execute and .executemany. @@ -893,7 +912,7 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski ret = SQLPutData(cur->hstmt, (SQLPOINTER)&p[offset], remaining); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) - return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt); + return CancelDataAtExec(cur, RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt)); offset += remaining; } while (offset < cb); @@ -903,20 +922,50 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski // TVP // Need to convert its columns into the bound row buffers int hasTvpRows = 0; - if (pInfo->curTvpRow < PySequence_Length(pInfo->pObject)) + Py_ssize_t tvpRowCount = PySequence_Length(pInfo->pObject); + if (tvpRowCount < 0) { - PyObject *tvpRow = PySequence_GetItem(pInfo->pObject, pInfo->curTvpRow); - Py_XDECREF(tvpRow); - for (Py_ssize_t i = 0; i < PySequence_Size(tvpRow); i++) + CancelDataAtExec(cur, 0); + FreeParameterData(cur); + return NULL; + } + if (pInfo->curTvpRow < tvpRowCount) + { + Object tvpRow(PySequence_GetItem(pInfo->pObject, pInfo->curTvpRow)); + if (!tvpRow) + { + CancelDataAtExec(cur, 0); + FreeParameterData(cur); + return NULL; + } + + // `nested` was sized from the rows when the TVP was bound, so the sequence + // must not have changed shape since. + if (PySequence_Size(tvpRow) != pInfo->maxlength) + { + CancelDataAtExec(cur, 0); + FreeParameterData(cur); + if (PyErr_Occurred()) + return NULL; + return RaiseErrorV(0, ProgrammingError, "A TVP's rows must all be the same size."); + } + + for (Py_ssize_t i = 0; i < pInfo->maxlength; i++) { struct ParamInfo newParam; struct ParamInfo *prevParam = pInfo->nested + i; - PyObject *cell = PySequence_GetItem(tvpRow, i); - Py_XDECREF(cell); + Object cell(PySequence_GetItem(tvpRow, i)); + if (!cell) + { + CancelDataAtExec(cur, 0); + FreeParameterData(cur); + return NULL; + } memset(&newParam, 0, sizeof(newParam)); if (!GetParameterInfo(cur, i, cell, newParam, true)) { // Error converting object + CancelDataAtExec(cur, 0); FreeParameterData(cur); return NULL; } @@ -925,10 +974,20 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski (newParam.ValueType != prevParam->ValueType || newParam.ParameterType != prevParam->ParameterType)) { + Py_XDECREF(newParam.pObject); + if (newParam.allocated) + PyMem_Free(newParam.ParameterValuePtr); + CancelDataAtExec(cur, 0); FreeParameterData(cur); return RaiseErrorV(0, ProgrammingError, "Type mismatch between TVP row values"); } + // ParameterValuePtr can point into the cell's own buffer (bytes), which the + // driver reads when it asks for this column, so keep the cell alive until + // the next row replaces it. + if (!newParam.pObject) + newParam.pObject = cell.Detach(); + if (prevParam->allocated) PyMem_Free(prevParam->ParameterValuePtr); Py_XDECREF(prevParam->pObject); @@ -947,7 +1006,7 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski ret = SQLPutData(cur->hstmt, hasTvpRows ? (SQLPOINTER)1 : 0, hasTvpRows); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) - return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt); + return CancelDataAtExec(cur, RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt)); } else { @@ -956,7 +1015,7 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski ret = SQLPutData(cur->hstmt, pInfo->ParameterValuePtr, pInfo->BufferLength); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) - return RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt); + return CancelDataAtExec(cur, RaiseErrorFromHandle(cur->cnxn, "SQLPutData", cur->cnxn->hdbc, cur->hstmt)); } ret = SQL_NEED_DATA; } @@ -1221,12 +1280,12 @@ static PyObject* Cursor_setinputsizes(PyObject* self, PyObject* sizes) Py_RETURN_NONE; } -static PyObject* Cursor_fetch(Cursor* cur) +static PyObject* Cursor_fetch(Cursor* cur, bool allow_dict = true) { // Internal function to fetch a single row and construct a Row object from it. Used by all of the fetching // functions. // - // Returns a Row object if successful. If there are no more rows, zero is returned. If an error occurs, an + // Returns a Row object if successful, or a dict if rows_as_dicts is set and `allow_dict` is true. If there are no more rows, zero is returned. If an error occurs, an // exception is set and zero is returned. (To differentiate between the last two, use PyErr_Occurred.) SQLRETURN ret = 0; @@ -1271,7 +1330,7 @@ static PyObject* Cursor_fetch(Cursor* cur) // Return a dict instead of a Row if so requested. // See https://github.com/mkleehammer/pyodbc/issues/171, - if (cur->rows_as_dicts) + if (cur->rows_as_dicts && allow_dict) { PyObject* dict = PyDict_New(); if (!dict) @@ -1372,7 +1431,8 @@ static PyObject* Cursor_fetchval(PyObject* self, PyObject* args) if (!cursor) return 0; - Object row(Cursor_fetch(cursor)); + // Always fetch a Row, even when rows_as_dicts is set, so we can index the first column. + Object row(Cursor_fetch(cursor, false)); if (!row) { @@ -1469,7 +1529,9 @@ static PyObject* Cursor_tables(PyObject* self, PyObject* args, PyObject* kwargs) if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|zzzz", Cursor_tables_kwnames, &szTableName, &szCatalog, &szSchema, &szTableType)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -1553,7 +1615,9 @@ static PyObject* Cursor_tablePrivileges(PyObject* self, PyObject* args, PyObject if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOO", kwnames, &pTable, &pCatalog, &pSchema)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -1683,7 +1747,9 @@ static PyObject* Cursor_columns(PyObject* self, PyObject* args, PyObject* kwargs if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOOO", Cursor_column_kwnames, &pTable, &pCatalog, &pSchema, &pColumn)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -1768,7 +1834,7 @@ static PyObject* Cursor_statistics(PyObject* self, PyObject* args, PyObject* kwa &pUnique, &pQuick)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); if (!cur) return 0; @@ -1910,7 +1976,9 @@ static PyObject* _specialColumns(PyObject* self, PyObject* args, PyObject* kwarg if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|zzO", Cursor_specialColumn_kwnames, &szTable, &szCatalog, &szSchema, &pNullable)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -1981,7 +2049,9 @@ static PyObject* Cursor_primaryKeys(PyObject* self, PyObject* args, PyObject* kw if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|zz", Cursor_primaryKeys_kwnames, &szTable, &szCatalog, &szSchema)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -2052,7 +2122,9 @@ static PyObject* Cursor_foreignKeys(PyObject* self, PyObject* args, PyObject* kw &szForeignTable, &szForeignCatalog, &szForeignSchema)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -2120,7 +2192,9 @@ static PyObject* Cursor_getTypeInfo(PyObject* self, PyObject* args, PyObject* kw if (!PyArg_ParseTuple(args, "|i", &nDataType)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -2291,7 +2365,9 @@ static PyObject* Cursor_procedureColumns(PyObject* self, PyObject* args, PyObjec if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|zzz", Cursor_procedureColumns_kwnames, &szProcedure, &szCatalog, &szSchema)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; @@ -2350,7 +2426,9 @@ static PyObject* Cursor_procedures(PyObject* self, PyObject* args, PyObject* kwa if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|zzz", Cursor_procedures_kwnames, &szProcedure, &szCatalog, &szSchema)) return 0; - Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); + if (!cur) + return 0; if (!free_results(cur, FREE_STATEMENT | FREE_PREPARED)) return 0; diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index c28b52d5..8ee5003f 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -838,3 +838,32 @@ def test_rows_as_dicts(cursor: pyodbc.Cursor): row = cursor.execute("select name, name from t1").fetchone() assert len(row) == 1 assert row == {"name": "Kathleen"} + + +def test_rows_as_dicts_fetchval(cursor: pyodbc.Cursor): + "fetchval returns the first column even when rows are dicts" + cursor.rows_as_dicts = True + assert cursor.execute("select 42 as a, 1 as b").fetchval() == 42 + + +@pytest.mark.parametrize("method, args", [ + ("tables", ()), ("tablePrivileges", ()), ("columns", ()), ("statistics", ("t1",)), + ("rowIdColumns", ("t1",)), ("rowVerColumns", ("t1",)), ("primaryKeys", ("t1",)), + ("foreignKeys", ()), ("getTypeInfo", ()), ("procedures", ()), ("procedureColumns", ()), +]) +def test_catalog_on_closed_cursor(cursor: pyodbc.Cursor, method, args): + "Catalog functions on a closed cursor raise instead of crashing" + cursor.close() + with pytest.raises(pyodbc.ProgrammingError, match="closed cursor"): + getattr(cursor, method)(*args) + + +def test_fetch_after_column_name_decode_error(cnxn: pyodbc.Connection): + "If column names can't be decoded, a later fetch raises instead of reading bad state" + cnxn.setdecoding(pyodbc.SQL_WMETADATA, encoding="ascii") + cursor = cnxn.cursor() + with pytest.raises(UnicodeDecodeError): + cursor.execute('select 1 as "é"') + assert cursor.description is None + with pytest.raises(pyodbc.ProgrammingError): + cursor.fetchone() diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index fd7b7798..0f8d53f4 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -2112,3 +2112,66 @@ def test_set_string_attr(cursor: pyodbc.Cursor): cursor.connection.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, "master") new_db = cursor.execute("SELECT db_name()").fetchval() assert new_db == "master" + + +@pytest.fixture +def tvp_binary_proc(cursor: pyodbc.Cursor) -> Iterator[str]: + """A procedure taking a one-varbinary-column TVP and returning its rows.""" + cursor.execute("drop procedure if exists tvp_binary_p") + cursor.execute("drop type if exists tvp_binary_t") + cursor.execute("create type tvp_binary_t as table (id int, b varbinary(100))") + cursor.execute("create procedure tvp_binary_p @t tvp_binary_t readonly" + " as select id, b from @t order by id") + cursor.commit() + yield "{call tvp_binary_p(?)}" + cursor.execute("drop procedure if exists tvp_binary_p") + cursor.execute("drop type if exists tvp_binary_t") + cursor.commit() + + +class _FreshValuesRow: + "A TVP row that builds new value objects every time one is read" + def __init__(self, n): + self.n = n + + def __len__(self): + return 2 + + def __getitem__(self, i): + if i == 0: + return self.n + 1000000 + if i == 1: + return b"value-%d-" % self.n + b"x" * 50 + raise IndexError(i) + + +@pytest.mark.skipif(SQLSERVER_YEAR < 2008, reason="TVP not supported until 2008") +@pytest.mark.skipif(IS_FREETDS, reason="FreeTDS does not support TVP") +def test_tvp_rows_with_fresh_values(cursor: pyodbc.Cursor, tvp_binary_proc: str): + "Values are kept alive until the driver has read them" + rows = [_FreshValuesRow(n) for n in range(5)] + result = cursor.execute(tvp_binary_proc, (rows,)).fetchall() + assert [tuple(r) for r in result] == [(row[0], row[1]) for row in rows] + + +class _ShapeShiftingRow: + "A TVP row that reports two columns when bound and four when executed" + def __init__(self): + self.len_calls = 0 + + def __len__(self): + self.len_calls += 1 + return 2 if self.len_calls == 1 else 4 + + def __getitem__(self, i): + if i >= 4: + raise IndexError(i) + return 1 if i == 0 else b"x" + + +@pytest.mark.skipif(SQLSERVER_YEAR < 2008, reason="TVP not supported until 2008") +@pytest.mark.skipif(IS_FREETDS, reason="FreeTDS does not support TVP") +def test_tvp_row_changes_size(cursor: pyodbc.Cursor, tvp_binary_proc: str): + "A row whose length changes after binding raises instead of overrunning the bindings" + with pytest.raises(pyodbc.ProgrammingError, match="same size"): + cursor.execute(tvp_binary_proc, ([_ShapeShiftingRow()],)) From 82adba8242dbbf81bfb4c8cae5637ede47d49dbf Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 11:47:49 -0600 Subject: [PATCH 06/22] connection: fix crashes in connect(), set_attr, and TimeFromTicks - connect(encoding=...) with a name that can't be encoded as UTF-8 passed NULL to PyBytes_AsString. Raise the encoding error. - attrs_before: check PySequence_GetItem results (and re-check the item type, since the sequence is read again after validation), check the key for overflow, and give str values a NUL as wide as a character; they are passed with SQL_NTS but a bytes object only ends in one NUL byte. - set_attr: validate the connection, raise encoding errors instead of passing a NULL buffer, and raise integer overflow. - getinfo, searchescape and Windows dataSources clamp the returned length to the buffer when the driver truncates. searchescape validates the connection and checks the decode. - TimeFromTicks converted the original object instead of the int (so floats returned with a TypeError pending) and dereferenced a NULL localtime() result. Raise OverflowError for values localtime() can't represent. --- src/connection.cpp | 87 +++++++++++++++++++++++++++++++++++++++----- src/pyodbcmodule.cpp | 21 ++++++++--- tests/sqlite_test.py | 57 ++++++++++++++++++++++++++++- 3 files changed, 149 insertions(+), 16 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index b5f845ef..e9cc12eb 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -165,10 +165,18 @@ static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char } else if (PyUnicode_Check(value)) { - Object po(PyUnicode_AsEncodedString(value, strencoding ? strencoding : "utf-16le", "strict")); + Object encoded(PyUnicode_AsEncodedString(value, strencoding ? strencoding : "utf-16le", "strict")); + if (!encoded) + return false; + // The value is passed with SQL_NTS, so it needs a NUL as wide as a character. A bytes + // object only has one NUL byte, so copy it with 4 (enough for UTF-16 or UTF-32). + Py_ssize_t cb = PyBytes_GET_SIZE(encoded.Get()); + Object po(PyBytes_FromStringAndSize(0, cb + 4)); if (!po) return false; // OOM - ivalue = (SQLPOINTER)PyBytes_AsString(po); + memcpy(PyBytes_AS_STRING(po.Get()), PyBytes_AS_STRING(encoded.Get()), (size_t)cb); + memset(PyBytes_AS_STRING(po.Get()) + cb, 0, 4); + ivalue = (SQLPOINTER)PyBytes_AS_STRING(po.Get()); vallen = SQL_NTS; // PyList_Append increments the refcount, so the list owns the encoded buffer for as long // as the driver needs it; po releases our own reference when it goes out of scope. @@ -179,9 +187,21 @@ static bool ApplyPreconnAttrs(HDBC hdbc, SQLINTEGER ikey, PyObject *value, char { // To allow for possibility of setting multiple attributes more than once. Py_ssize_t len = PySequence_Size(value); + if (len < 0) + return false; for (Py_ssize_t i = 0; i < len; i++) { Object v(PySequence_GetItem(value, i)); + if (!v) + return false; + // Only one level of nesting is allowed (CheckAttrsVal), but the sequence could + // return something else now than when it was checked. + if (!PyLong_Check(v) && !PyByteArray_Check(v) && !PyBytes_Check(v) && !PyUnicode_Check(v)) + { + RaiseErrorV(0, PyExc_TypeError, "Unsupported attrs_before type: %s", + Py_TYPE(v.Get())->tp_name); + return false; + } if (!ApplyPreconnAttrs(hdbc, ikey, v.Get(), strencoding, keepalives)) return false; } @@ -246,16 +266,48 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou PyObject* value = 0; Object encodingholder; - char *strencoding = (encoding != 0) ? - (PyUnicode_Check(encoding) ? PyBytes_AsString(encodingholder = PyCodec_Encode(encoding, "utf-8", "strict")) : - PyBytes_Check(encoding) ? PyBytes_AsString(encoding) : 0) : 0; + char *strencoding = 0; + if (encoding && PyUnicode_Check(encoding)) + { + encodingholder = PyCodec_Encode(encoding, "utf-8", "strict"); + if (!encodingholder) + { + Py_DECREF(preconn_keepalives); + Py_BEGIN_ALLOW_THREADS + SQLFreeHandle(SQL_HANDLE_DBC, hdbc); + Py_END_ALLOW_THREADS + return 0; + } + strencoding = PyBytes_AS_STRING(encodingholder.Get()); + } + else if (encoding && PyBytes_Check(encoding)) + { + strencoding = PyBytes_AS_STRING(encoding); + } while (PyDict_Next(attrs_before, &pos, &key, &value)) { SQLINTEGER ikey = 0; if (PyLong_Check(key)) - ikey = (int)PyLong_AsLong(key); + { + // Attribute IDs are SQLINTEGERs. long is 64 bits on most Unix platforms, so + // check the range rather than truncate to another attribute. + long lkey = PyLong_AsLong(key); + if (!PyErr_Occurred() && (lkey < INT_MIN || lkey > INT_MAX)) + PyErr_Format(PyExc_OverflowError, + "attrs_before key %ld is outside the range of an ODBC attribute ID", + lkey); + ikey = (SQLINTEGER)lkey; + if (PyErr_Occurred()) + { + Py_DECREF(preconn_keepalives); + Py_BEGIN_ALLOW_THREADS + SQLFreeHandle(SQL_HANDLE_DBC, hdbc); + Py_END_ALLOW_THREADS + return 0; + } + } if (!ApplyPreconnAttrs(hdbc, ikey, value, strencoding, preconn_keepalives)) { Py_DECREF(preconn_keepalives); @@ -419,7 +471,9 @@ static PyObject* Connection_set_attr(PyObject* self, PyObject* args) if (!PyArg_ParseTuple(args, "iO", &id, &value)) return 0; - Connection* cnxn = (Connection*)self; + Connection* cnxn = Connection_Validate(self); + if (!cnxn) + return 0; SQLRETURN ret; SQLWChar sqlchar; // declared here so buffer stays alive across the call @@ -427,13 +481,21 @@ static PyObject* Connection_set_attr(PyObject* self, PyObject* args) if (PyLong_Check(value)) { long ival = PyLong_AsLong(value); + if (ival == -1 && PyErr_Occurred()) + return 0; Py_BEGIN_ALLOW_THREADS ret = SQLSetConnectAttrW(cnxn->hdbc, id, (SQLPOINTER)(intptr_t)ival, SQL_IS_INTEGER); Py_END_ALLOW_THREADS } else if (PyUnicode_Check(value)) { + // SQLWChar clears encoding errors and leaves a NULL buffer, so check first to raise them. + Object check(PyUnicode_AsEncodedString(value, "utf-16le", "strict")); + if (!check) + return 0; sqlchar.set(value, "utf-16le"); + if (!sqlchar.isValid()) + return PyErr_NoMemory(); Py_BEGIN_ALLOW_THREADS ret = SQLSetConnectAttrW(cnxn->hdbc, id, sqlchar.get(), SQL_NTS); Py_END_ALLOW_THREADS @@ -798,7 +860,8 @@ static PyObject* Connection_getinfo(PyObject* self, PyObject* args) break; case GI_STRING: - result = PyUnicode_FromStringAndSize(szBuffer, (Py_ssize_t)cch); + // On truncation cch is the full length, not what fit in the buffer. + result = PyUnicode_FromStringAndSize(szBuffer, min((Py_ssize_t)cch, (Py_ssize_t)sizeof(szBuffer) - 1)); break; case GI_UINTEGER: @@ -973,7 +1036,9 @@ static PyObject* Connection_getsearchescape(PyObject* self, void* closure) { UNUSED(closure); - Connection* cnxn = (Connection*)self; + Connection* cnxn = Connection_Validate(self); + if (!cnxn) + return 0; if (!cnxn->searchescape) { @@ -987,7 +1052,9 @@ static PyObject* Connection_getsearchescape(PyObject* self, void* closure) if (!SQL_SUCCEEDED(ret)) return RaiseErrorFromHandle(cnxn, "SQLGetInfo", cnxn->hdbc, SQL_NULL_HANDLE); - cnxn->searchescape = PyUnicode_FromStringAndSize(sz, (Py_ssize_t)cch); + cnxn->searchescape = PyUnicode_FromStringAndSize(sz, min((Py_ssize_t)cch, (Py_ssize_t)sizeof(sz) - 1)); + if (!cnxn->searchescape) + return 0; } Py_INCREF(cnxn->searchescape); diff --git a/src/pyodbcmodule.cpp b/src/pyodbcmodule.cpp index d0d110d0..85f1fa84 100644 --- a/src/pyodbcmodule.cpp +++ b/src/pyodbcmodule.cpp @@ -354,10 +354,12 @@ static bool CheckAttrsVal(PyObject *val, bool allowSeq) if (allowSeq && PySequence_Check(val)) { Py_ssize_t len = PySequence_Size(val); + if (len < 0) + return false; for (Py_ssize_t i = 0; i < len; i++) { Object v(PySequence_GetItem(val, i)); - if (!CheckAttrsVal(v, false)) + if (!v || !CheckAttrsVal(v, false)) return false; } return true; @@ -681,9 +683,12 @@ static PyObject* mod_datasources(PyObject* self, PyObject* args, PyObject* kwarg if (!SQL_SUCCEEDED(ret)) break; + // On truncation the lengths are the full lengths, not what fit in the buffers. + SQLSMALLINT cchDSN = min(cbDSN, (SQLSMALLINT)(_countof(szDSN) - 1)); + SQLSMALLINT cchDesc = min(cbDesc, (SQLSMALLINT)(_countof(szDesc) - 1)); int byteorder = BYTEORDER_NATIVE; - PyObject* key = PyUnicode_DecodeUTF16((char*)szDSN, cbDSN * sizeof(wchar_t), "strict", &byteorder); - PyObject* val = PyUnicode_DecodeUTF16((char*)szDesc, cbDesc * sizeof(wchar_t), "strict", &byteorder); + PyObject* key = PyUnicode_DecodeUTF16((char*)szDSN, cchDSN * sizeof(wchar_t), "strict", &byteorder); + PyObject* val = PyUnicode_DecodeUTF16((char*)szDesc, cchDesc * sizeof(wchar_t), "strict", &byteorder); #else // UTF-8 ret = SQLDataSources(henv, nDirection, szDSN, _countof(szDSN), &cbDSN, szDesc, _countof(szDesc), &cbDesc); @@ -731,8 +736,14 @@ static PyObject* mod_timefromticks(PyObject* self, PyObject* args) if (!l) return 0; - time_t t = PyLong_AsLong(num); - struct tm* fields = localtime(&t); + long long ticks = PyLong_AsLongLong(l); + if (ticks == -1 && PyErr_Occurred()) + return 0; + + time_t t = (time_t)ticks; + struct tm* fields = ((long long)t == ticks) ? localtime(&t) : 0; + if (!fields) + return PyErr_Format(PyExc_OverflowError, "timestamp %lld out of range for localtime()", ticks); return PyTime_FromTime(fields->tm_hour, fields->tm_min, fields->tm_sec, 0); } diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 8ee5003f..9801dcc3 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -23,7 +23,7 @@ import platform import re from collections.abc import Iterator -from datetime import datetime +from datetime import datetime, time import pyodbc import pytest @@ -123,6 +123,61 @@ def test_datasources(): assert isinstance(p, dict) +def test_connect_bad_encoding(connection_string: str): + "An encoding name that can't be encoded raises instead of crashing" + with pytest.raises(UnicodeEncodeError): + pyodbc.connect(connection_string, encoding="\udcff", + attrs_before={pyodbc.SQL_ATTR_CURRENT_CATALOG: "x"}) + + +def test_attrs_before_sequence_error(connection_string: str): + "An error reading an attrs_before sequence value propagates" + class BadSequence: + def __len__(self): + return 1 + + def __getitem__(self, i): + raise ValueError("no items") + + with pytest.raises(ValueError, match="no items"): + pyodbc.connect(connection_string, + attrs_before={pyodbc.SQL_ATTR_CURRENT_CATALOG: BadSequence()}) + + +@pytest.mark.parametrize('key', [2**31, -2**31 - 1, 2**40 + 102, 2**64]) +def test_attrs_before_key_out_of_range(connection_string: str, key): + "attrs_before keys that don't fit a SQLINTEGER raise instead of being truncated" + # 2**40 + 102 was truncated to 102, SQL_ATTR_AUTOCOMMIT. + with pytest.raises(OverflowError): + pyodbc.connect(connection_string, attrs_before={key: 1}) + + +def test_set_attr_errors(cnxn: pyodbc.Connection): + "set_attr raises for values it can't pass and for a closed connection" + with pytest.raises(UnicodeEncodeError): + cnxn.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, "\ud800") + with pytest.raises(OverflowError): + cnxn.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, 2**100) + cnxn.close() + with pytest.raises(pyodbc.ProgrammingError, match="closed connection"): + cnxn.set_attr(pyodbc.SQL_ATTR_CURRENT_CATALOG, "x") + + +def test_searchescape_closed(cnxn: pyodbc.Connection): + cnxn.close() + with pytest.raises(pyodbc.ProgrammingError, match="closed connection"): + cnxn.searchescape + + +def test_timefromticks(): + "TimeFromTicks accepts floats and rejects timestamps localtime() can't represent" + assert isinstance(pyodbc.TimeFromTicks(1.5), time) + with pytest.raises(OverflowError): + pyodbc.TimeFromTicks(2**62) + with pytest.raises(OverflowError): + pyodbc.TimeFromTicks(2**100) + + def test_getinfo_string(cnxn: pyodbc.Connection): value = cnxn.getinfo(pyodbc.SQL_CATALOG_NAME_SEPARATOR) assert isinstance(value, str) From 2a9cfdc52ff816eafed9acdda1a94372a2f8a83d Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 14:39:57 -0600 Subject: [PATCH 07/22] decimal: build Decimals from SQL_NUMERIC_STRUCT with one constructor call DecimalFromNumericStruct converted the 16-byte magnitude to a Python int, the int to a str, the str to a tuple of one int per digit, and then called Decimal((sign, digits, exponent)). That made several Python objects per digit for every value read. Format the value as "E<-scale>" in C instead and call Decimal() once. The result is identical, exponent included. Reading 200,000 numeric(18,2) values takes about 20-25% less time on PostgreSQL and SQL Server. --- src/decimal.cpp | 73 +++++++++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 33 deletions(-) diff --git a/src/decimal.cpp b/src/decimal.cpp index 0f983ed3..ff17e3d5 100644 --- a/src/decimal.cpp +++ b/src/decimal.cpp @@ -162,40 +162,47 @@ PyObject* DecimalFromNumericStruct(const SQL_NUMERIC_STRUCT& num) { // Avoid the problems introduced by locale-specific delimiters in numeric strings // by having the driver provide the value using a well-defined binary structure. - - // Convert the little-endian (1) unsigned (0) magnitude to a Python int. - PyObject* magnitude = _PyLong_FromByteArray(num.val, SQL_MAX_NUMERIC_LEN, 1, 0); - if (!magnitude) - return NULL; - - // Convert magnitude to a tuple of decimal digits via str(). - Object magStr(PyObject_Str(magnitude)); - Py_DECREF(magnitude); - if (!magStr) - return NULL; - - Py_ssize_t nDigits = PyUnicode_GET_LENGTH(magStr.Get()); - Object digitTuple(PyTuple_New(nDigits)); - if (!digitTuple) - return NULL; - - for (Py_ssize_t i = 0; i < nDigits; i++) + // + // The value is formatted as "E<-scale>" and passed to the Decimal constructor once, + // which is much cheaper than building a Python int, its str, and a tuple of digit objects. + // The result is identical, including the exponent: Decimal("365688E-2") is + // Decimal("3656.88"). + + // The magnitude is a 128-bit little-endian unsigned integer. Divide it by 10 repeatedly, + // collecting the remainders, which are the decimal digits from least significant up. + unsigned char val[SQL_MAX_NUMERIC_LEN]; + memcpy(val, num.val, sizeof(val)); + int top = SQL_MAX_NUMERIC_LEN; + while (top > 0 && val[top - 1] == 0) + top--; + + char digits[40]; // 2**128 has 39 digits + int cDigits = 0; + do { - Py_UCS4 ch = PyUnicode_READ_CHAR(magStr.Get(), i); - PyObject* digit = PyLong_FromLong((long)(ch - '0')); - if (!digit) - return NULL; - PyTuple_SET_ITEM(digitTuple.Get(), i, digit); - } - - // Decimal sign: 0 = positive, 1 = negative (opposite of ODBC convention). - int decimalSign = (num.sign == 1) ? 0 : 1; - long exponent = -(long)num.scale; - - // Decimal((sign, (d, d, ...), exponent)) - Object args(Py_BuildValue("((iOl))", decimalSign, digitTuple.Get(), exponent)); - if (!args) + unsigned int rem = 0; + for (int i = top - 1; i >= 0; i--) + { + unsigned int cur = (rem << 8) | val[i]; + val[i] = (unsigned char)(cur / 10); + rem = cur % 10; + } + digits[cDigits++] = (char)('0' + rem); + while (top > 0 && val[top - 1] == 0) + top--; + } while (top > 0); + + char text[64]; + int cch = 0; + if (num.sign != 1) // ODBC: 1 is positive, 0 is negative + text[cch++] = '-'; + while (cDigits > 0) + text[cch++] = digits[--cDigits]; + cch += snprintf(text + cch, sizeof(text) - cch, "E%d", -(int)num.scale); + + Object str(PyUnicode_FromStringAndSize(text, cch)); + if (!str) return NULL; - return PyObject_CallObject(decimal, args.Get()); + return PyObject_CallFunctionObjArgs(decimal, str.Get(), NULL); } From a8374fa12a262f76caa5d9004afc562de764a6f5 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 14:43:20 -0600 Subject: [PATCH 08/22] fast_executemany: take Decimal scale from the values when the driver can't describe it ExecuteMulti used SQLDescribeParam's precision and scale for Decimal parameters even when the driver reports SQL_DESCRIBE_PARAMETER "N". psqlODBC is such a driver: it describes every numeric parameter as numeric(28,6), or with the precision and scale last bound to the statement. So on PostgreSQL, fast_executemany raised "Converting decimal loses precision" for any value with more than 6 decimal places, and for any fractional value after the same cursor had run the statement with an integral Decimal. When the driver can't describe the parameter and setinputsizes doesn't give a scale, bind Decimals as numeric(38, s), or with the setinputsizes size as the precision, and take s from the values. DetectCType picks the smallest scale the batch's first row needs, counting only significant digits, or the previous batch's scale if the row fits it too. A later row that does not fit the scale chosen, but fits another, ends the current batch, and the parameters are rebound from that row. Digits are checked against the precision in the SQL_NUMERIC_STRUCT, for Decimals and ints, rather than the 39 digits the 16-byte val can hold: psqlODBC silently drops the leading digits of a value with more digits than the struct's precision. The described type and size are restored before each batch, so guessing for a Decimal does not change how a str in the same column is bound. --- src/cursor.h | 15 +++ src/params.cpp | 257 +++++++++++++++++++++++++++++++-------- tests/postgresql_test.py | 109 +++++++++++++++++ 3 files changed, 333 insertions(+), 48 deletions(-) diff --git a/src/cursor.h b/src/cursor.h index 36b781f9..958baad8 100644 --- a/src/cursor.h +++ b/src/cursor.h @@ -71,6 +71,21 @@ struct ParamInfo // written to each SQLPutData call. (It is not clear if they are limited // like SQLBindParameter or not.) + // fast_executemany only: true if the driver cannot describe this parameter (and + // setinputsizes did not give a scale), so a Decimal's precision and scale are taken from + // the values. The batch is executed and rebound when a row does not fit the scale chosen + // so far. + bool guessScale; + // When guessScale is set: the type, size, and scale from SQLDescribeParam and + // setinputsizes, restored before each batch is bound so that guessing for a Decimal does + // not change how other types in the column are bound; the most digits to bind (38, or the + // setinputsizes size); and the scale guessed for the last batch, or -1. + SQLSMALLINT describedType; + SQLULEN describedSize; + SQLSMALLINT describedDigits; + SQLSMALLINT guessPrecision; + SQLSMALLINT guessedScale; + // For TVPs, the nested descriptors and current row. struct ParamInfo *nested; SQLLEN curTvpRow; diff --git a/src/params.cpp b/src/params.cpp index 070948c1..b7974ec5 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -38,6 +38,41 @@ struct DAEParam }; +// The largest precision a SQL_NUMERIC_STRUCT is used for (SQL Server's maximum). +static const int MAX_NUMERIC_PRECISION = 38; + +static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp); + +static void StripDecimalZeros(PyObject* digits, Py_ssize_t& numDigits, Py_ssize_t& exp) +{ + // Removes trailing zeros (1.50 -> 1.5, 100 -> 1E+2) by reducing numDigits and increasing + // exp, so only significant digits are counted. Any zero becomes 0E0. The digits have been + // checked by GetDecimalParts. + numDigits = PyTuple_GET_SIZE(digits); + while (numDigits > 1 && PyLong_AsLong(PyTuple_GET_ITEM(digits, numDigits - 1)) == 0) + { + numDigits--; + exp++; + } + if (numDigits == 1 && PyLong_AsLong(PyTuple_GET_ITEM(digits, 0)) == 0) + exp = 0; +} + +static bool FitsGuessedNumeric(Py_ssize_t numDigits, Py_ssize_t exp, Py_ssize_t scale, Py_ssize_t precision) +{ + // Returns true if a Decimal with numDigits significant digits and exponent exp (from + // StripDecimalZeros) can be bound exactly as numeric(precision, scale). + if (scale < 0 || scale > precision || scale + exp < 0) + return false; + long long digits = (long long)numDigits + exp + scale; // digits in the scaled integer + return digits <= precision; +} + +static Py_ssize_t MinimumScale(Py_ssize_t exp) +{ + return exp < 0 ? -exp : 0; +} + static int DetectCType(PyObject *cell, ParamInfo *pi) { // Detects and sets the appropriate C type to use for binding the specified Python object. @@ -48,6 +83,17 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) // could be from a previous row or could have been initialized from SQLDescribeParam. PyObject* cls = 0; + + if (pi->guessScale && cell != Py_None && cell != null_binary) + { + // Start from the described type so that a scale guessed for a Decimal in an earlier + // batch does not change how a str, for example, is bound. None keeps the type of the + // previous batch. + pi->ParameterType = pi->describedType; + pi->ColumnSize = pi->describedSize; + pi->DecimalDigits = pi->describedDigits; + } + if (PyBool_Check(cell)) { Type_Bool: @@ -62,6 +108,13 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) { pi->ValueType = SQL_C_NUMERIC; pi->BufferLength = sizeof(SQL_NUMERIC_STRUCT); + if (pi->guessScale) + { + // An integer needs no scale. A Decimal in a later row that needs one causes a + // rebind. + pi->ColumnSize = (SQLULEN)pi->guessPrecision; + pi->DecimalDigits = 0; + } } else { @@ -182,6 +235,34 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) Type_Decimal: pi->ValueType = SQL_C_NUMERIC; pi->BufferLength = sizeof(SQL_NUMERIC_STRUCT); + + if (pi->guessScale && cell != Py_None && cell != null_binary) + { + // Bind with the full precision and the smallest scale this value needs, or the + // scale from the last batch if this value fits it too, so rows that alternate + // between scales do not each cause a rebind. If no scale fits, PyToCType raises. + Object parts; + long sign; + PyObject* digits; + Py_ssize_t exp; + if (!GetDecimalParts(cell, parts, sign, digits, exp)) + return false; + Py_ssize_t numDigits; + StripDecimalZeros(digits, numDigits, exp); + + Py_ssize_t precision = pi->guessPrecision; + Py_ssize_t scale = MinimumScale(exp); + if (scale > precision) + scale = precision; + if (pi->guessedScale > scale && FitsGuessedNumeric(numDigits, exp, pi->guessedScale, precision)) + scale = pi->guessedScale; + + pi->guessedScale = (SQLSMALLINT)scale; + pi->DecimalDigits = (SQLSMALLINT)scale; + if (pi->ParameterType != SQL_DECIMAL) + pi->ParameterType = SQL_NUMERIC; + pi->ColumnSize = (SQLULEN)precision; + } } else { @@ -236,6 +317,27 @@ static bool GetUUIDBytes(PyObject* value, Object& bytes) return true; } +static PyObject* PowerOfTen(Py_ssize_t n) +{ + // Returns a borrowed reference to 10**n, for 0 <= n <= MAX_NUMERIC_PRECISION, or null with + // an exception set. + static PyObject* table[MAX_NUMERIC_PRECISION + 1]; + if (n < 0 || n > MAX_NUMERIC_PRECISION) + { + PyErr_SetString(PyExc_ValueError, "power of ten out of range"); + return 0; + } + if (!table[n]) + { + Object ten(PyLong_FromLong(10)); + Object exponent(PyLong_FromSsize_t(n)); + if (!ten || !exponent) + return 0; + table[n] = PyNumber_Power(ten, exponent, Py_None); + } + return table[n]; +} + #define WRITEOUT(type, ptr, val, indv) { *(type*)(*ptr) = (val); *ptr += sizeof(type); indv = sizeof(type); } // Convert Python object into C data for binding. // Output pointer is written to with data, indicator, and updated. @@ -263,44 +365,63 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI // Convert a PyLong into a SQL_NUMERIC_STRUCT, without losing precision // or taking an unnecessary trip through character strings. SQL_NUMERIC_STRUCT *pNum = (SQL_NUMERIC_STRUCT*)*outbuf; - PyObject *absVal = PyNumber_Absolute(cell); - if (pi->DecimalDigits) + + if (pi->DecimalDigits < 0 || pi->DecimalDigits > MAX_NUMERIC_PRECISION) { - static PyObject *scaler_table[38]; - static PyObject *tenObject; + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; + } - // Need to scale by 10**pi->DecimalDigits - if (pi->DecimalDigits < 0 || pi->DecimalDigits > 38) - { - NumericOverflow: - RaiseErrorV(0, ProgrammingError, "Numeric overflow"); - Py_XDECREF(absVal); - return false; - } + // The struct's precision tells the driver how many digits to send, and some + // drivers drop the leading digits of a value with more, so check the digits + // against it, not just against the 16-byte val. + Py_ssize_t precision = MAX_NUMERIC_PRECISION; + if (pi->guessScale && pi->ColumnSize >= 1 && pi->ColumnSize < MAX_NUMERIC_PRECISION) + precision = (Py_ssize_t)pi->ColumnSize; - if (!scaler_table[pi->DecimalDigits - 1]) + Object absVal(PyNumber_Absolute(cell)); + if (!absVal) + return false; + PyObject* scaler = PowerOfTen(pi->DecimalDigits); + PyObject* limit = PowerOfTen(precision); + if (!scaler || !limit) + return false; + Object scaledVal(PyNumber_Multiply(absVal, scaler)); + if (!scaledVal) + return false; + int tooBig = PyObject_RichCompareBool(scaledVal, limit, Py_GE); + if (tooBig < 0) + return false; + if (tooBig) + { + if (pi->guessScale && (pi->DecimalDigits > 0 || precision < pi->guessPrecision)) { - if (!tenObject) - tenObject = PyLong_FromLong(10); - PyObject *scaleObj = PyLong_FromLong(pi->DecimalDigits); - scaler_table[pi->DecimalDigits - 1] = PyNumber_Power(tenObject, scaleObj, Py_None); - Py_XDECREF(scaleObj); + // It fits with no scale. Returning false without an exception executes + // the rows so far and rebinds starting at this row. + PyObject* guessLimit = PowerOfTen(pi->guessPrecision); + if (!guessLimit) + return false; + int fits = PyObject_RichCompareBool(absVal, guessLimit, Py_LT); + if (fits) + return false; // a rebind, or an error if fits < 0 + } - PyObject *scaledVal = PyNumber_Multiply(absVal, scaler_table[pi->DecimalDigits - 1]); - Py_XDECREF(absVal); - absVal = scaledVal; + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; } - pNum->precision = (SQLCHAR)pi->ColumnSize; + + pNum->precision = (SQLCHAR)(pi->guessScale ? precision : pi->ColumnSize); pNum->scale = (SQLCHAR)pi->DecimalDigits; pNum->sign = _PyLong_Sign(cell) >= 0; #if PY_VERSION_HEX < 0x030D0000 - if (_PyLong_AsByteArray((PyLongObject*)absVal, pNum->val, sizeof(pNum->val), 1, 0)) { + if (_PyLong_AsByteArray((PyLongObject*)scaledVal.Get(), pNum->val, sizeof(pNum->val), 1, 0)) { #else - if (_PyLong_AsByteArray((PyLongObject*)absVal, pNum->val, sizeof(pNum->val), 1, 0, 1)) { + if (_PyLong_AsByteArray((PyLongObject*)scaledVal.Get(), pNum->val, sizeof(pNum->val), 1, 0, 1)) { #endif - goto NumericOverflow; + PyErr_Clear(); + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; } - Py_XDECREF(absVal); *outbuf += pi->BufferLength; ind = sizeof(SQL_NUMERIC_STRUCT); } @@ -493,31 +614,45 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI SQL_NUMERIC_STRUCT *pNum = (SQL_NUMERIC_STRUCT*)*outbuf; pNum->sign = !sign; - Py_ssize_t numDigits = PyTuple_GET_SIZE(digits); - // Strip trailing zeros (e.g. 1.50 -> 1.5, 100 -> 1E+2) so the "loses precision" check - // below only fires for digits that are really significant. - while (numDigits > 1 && PyNumber_AsSsize_t(PyTuple_GET_ITEM(digits, numDigits - 1), 0) == 0) + // Strip trailing zeros so the checks below count only significant digits. + Py_ssize_t numDigits; + StripDecimalZeros(digits, numDigits, exp); + + // The struct's precision tells the driver how many digits to send, and some drivers + // (psqlODBC) silently drop the leading digits of a value with more, so the digits are + // checked against it. When the parameter was described, the driver knows the real + // column, so allow up to 38 and let the database reject values too large for it. + Py_ssize_t precision = MAX_NUMERIC_PRECISION; + if (pi->guessScale && pi->ColumnSize >= 1 && pi->ColumnSize < MAX_NUMERIC_PRECISION) + precision = (Py_ssize_t)pi->ColumnSize; + + if (pi->DecimalDigits < 0 || pi->DecimalDigits > MAX_NUMERIC_PRECISION) { - numDigits--; - exp++; + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; } - // Any zero, whatever its exponent, is just 0. - if (numDigits == 1 && PyNumber_AsSsize_t(PyTuple_GET_ITEM(digits, 0), 0) == 0) - exp = 0; // PyDecimal is digits * 10**exp = digits / 10**-exp // SQL_NUMERIC_STRUCT is val / 10**scale Py_ssize_t scaleDiff = pi->DecimalDigits + exp; + + if (pi->guessScale && !FitsGuessedNumeric(numDigits, exp, pi->DecimalDigits, precision) && + FitsGuessedNumeric(numDigits, exp, MinimumScale(exp), pi->guessPrecision)) + { + // The scale was guessed from earlier rows and this value does not fit it, but it + // fits another. Returning false without an exception executes the rows so far and + // rebinds starting at this row, where DetectCType picks a scale that fits. + return false; + } if (scaleDiff < 0) { RaiseErrorV(0, ProgrammingError, "Converting decimal loses precision"); return false; } - // The 16-byte val holds at most 39 digits, so anything longer cannot fit. Checking - // here also keeps a huge exponent from sizing the tuple below. - if (numDigits + scaleDiff > 39) + // Checking here also keeps a huge exponent from sizing the tuple below. + if ((long long)numDigits + scaleDiff > precision) { RaiseErrorV(0, ProgrammingError, "Numeric overflow"); return false; @@ -551,7 +686,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI if (!digitLong) return false; - pNum->precision = (SQLCHAR)pi->ColumnSize; + pNum->precision = (SQLCHAR)(pi->guessScale ? precision : pi->ColumnSize); pNum->scale = (SQLCHAR)pi->DecimalDigits; @@ -1194,8 +1329,13 @@ static long getSequenceValue(PyObject *pSequence, Py_ssize_t nIndex, long nDefau * * sparhawk@gmx.at (Gerhard Gruber) */ -static bool UpdateParamInfo(Cursor* pCursor, Py_ssize_t nIndex, ParamInfo *pInfo) +static bool UpdateParamInfo(Cursor* pCursor, Py_ssize_t nIndex, ParamInfo *pInfo, bool* pScaleSet = 0) { + // Returns true if anything was set. If pScaleSet is not null, it is set to true if the + // scale was. + if (pScaleSet) + *pScaleSet = false; + if (pCursor->inputsizes == NULL || nIndex >= PySequence_Length(pCursor->inputsizes)) return false; @@ -1223,7 +1363,12 @@ static bool UpdateParamInfo(Cursor* pCursor, Py_ssize_t nIndex, ParamInfo *pInfo { pInfo->ParameterType = (SQLSMALLINT)getSequenceValue(desc, 0, (long)pInfo->ParameterType, rc); pInfo->ColumnSize = (SQLUINTEGER)getSequenceValue(desc, 1, (long)pInfo->ColumnSize, rc); - pInfo->DecimalDigits = (SQLSMALLINT)getSequenceValue(desc, 2, (long)pInfo->DecimalDigits, rc); + bool scaleSet = false; + pInfo->DecimalDigits = (SQLSMALLINT)getSequenceValue(desc, 2, (long)pInfo->DecimalDigits, scaleSet); + if (scaleSet) + rc = true; + if (pScaleSet) + *pScaleSet = scaleSet; } Py_CLEAR(desc); @@ -1752,9 +1897,10 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) for (Py_ssize_t i = 0; i < cur->paramcount; i++) { SQLSMALLINT nullable; - if (!SQL_SUCCEEDED(SQLDescribeParam(cur->hstmt, i + 1, &(cur->paramInfos[i].ParameterType), + bool described = SQL_SUCCEEDED(SQLDescribeParam(cur->hstmt, i + 1, &(cur->paramInfos[i].ParameterType), &cur->paramInfos[i].ColumnSize, &cur->paramInfos[i].DecimalDigits, - &nullable))) + &nullable)); + if (!described) { // Default to a medium-length varchar if describing the parameter didn't work cur->paramInfos[i].ParameterType = SQL_VARCHAR; @@ -1762,11 +1908,26 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) cur->paramInfos[i].DecimalDigits = 0; } - // This supports overriding of input sizes via setinputsizes - // See issue 380 - // The logic is duplicated from BindParameter - UpdateParamInfo(cur, i, &cur->paramInfos[i]); - } + // This supports overriding of input sizes via setinputsizes + // See issue 380 + // The logic is duplicated from BindParameter + bool scaleSet = false; + bool overridden = UpdateParamInfo(cur, i, &cur->paramInfos[i], &scaleSet); + + // A driver that reports SQL_DESCRIBE_PARAMETER "N" may still answer SQLDescribeParam, but + // not reliably: psqlODBC returns a generic numeric(28,6), or the precision and scale of + // whatever was last bound to the statement. A size from setinputsizes limits the + // precision guessed; a scale stops the guessing. + ParamInfo& info = cur->paramInfos[i]; + info.guessScale = !scaleSet && !(described && cur->cnxn->supports_describeparam); + info.describedType = info.ParameterType; + info.describedSize = info.ColumnSize; + info.describedDigits = info.DecimalDigits; + info.guessPrecision = MAX_NUMERIC_PRECISION; + if (overridden && info.ColumnSize >= 1 && info.ColumnSize < MAX_NUMERIC_PRECISION) + info.guessPrecision = (SQLSMALLINT)info.ColumnSize; + info.guessedScale = -1; + } PyObject *rowseq = PySequence_Fast(paramArrayObj, "Parameter array must be a sequence."); if (!rowseq) diff --git a/tests/postgresql_test.py b/tests/postgresql_test.py index d269b7aa..f06c7039 100644 --- a/tests/postgresql_test.py +++ b/tests/postgresql_test.py @@ -704,3 +704,112 @@ def test_handles(cursor: pyodbc.Cursor): conn.close() assert not isinstance(conn.hdbc, ctypes.c_void_p) assert conn.hdbc is None + + +@pytest.mark.parametrize('first', ['execute', 'fast_executemany']) +def test_fast_executemany_decimal_scale_after_reuse(cursor: pyodbc.Cursor, first): + # psqlODBC does not support SQLDescribeParam. 5.4.0 reuses the scale guessed from an + # earlier statement on the same cursor and raises "Converting decimal loses precision". + cursor.execute("create table t1(col numeric(10,2))") + sql = "insert into t1 values (?)" + if first == 'execute': + cursor.execute(sql, Decimal('3656')) + else: + cursor.fast_executemany = True + cursor.executemany(sql, [(Decimal('3656'),)]) + cursor.fast_executemany = True + cursor.executemany(sql, [(Decimal('3656.88'),), (Decimal('-0.5'),)]) + results = [row[0] for row in cursor.execute("select col::text from t1 order by col")] + assert results == ['-0.50', '3656.00', '3656.88'] + + +def test_fast_executemany_decimal_scale_from_values(cursor: pyodbc.Cursor): + # psqlODBC describes every numeric parameter as numeric(28,6), so 5.4.0 rejected any value + # with more than 6 decimal places. The scale now comes from the values, growing as rows + # need it. + cursor.execute("create table t1(n int, col numeric(30,12))") + values = [None, '1', '0.1234567', '-2.5', '123456789012345678.123456789012', None, '7.1'] + cursor.fast_executemany = True + cursor.executemany("insert into t1 values (?, ?)", + [(i, None if v is None else Decimal(v)) for i, v in enumerate(values)]) + results = [row[0] for row in cursor.execute("select col from t1 order by n")] + assert results == [None if v is None else Decimal(v) for v in values] + + +def _fast_executemany_numeric(cursor: pyodbc.Cursor, values, column="numeric"): + "Inserts values with fast_executemany and returns them read back in order" + cursor.execute(f"create table t1(n int, v {column})") + cursor.fast_executemany = True + cursor.executemany("insert into t1 values (?, ?)", list(enumerate(values))) + return [row[0] for row in cursor.execute("select v from t1 order by n")] + + +@pytest.mark.parametrize("values", [ + pytest.param(['1E-30', '123456789'], id="int-digits-after-scale"), + pytest.param(['1E-38', '3'], id="whole-after-scale-38"), + pytest.param(['0.333333333333333333333333333333', '123456789012.5'], id="mixed"), + pytest.param(['0E-50', '12'], id="zero-with-exponent"), + pytest.param(['1.' + '0' * 40, '5.5'], id="trailing-zeros"), + pytest.param(['0.123456789012345678901234567890', '12345678901'], id="shrink"), + pytest.param([str(Decimal(1).scaleb(-(i % 39))) for i in range(80)], id="many-scales"), +]) +def test_fast_executemany_guessed_scale_values(cursor: pyodbc.Cursor, values): + """ + psqlODBC cannot describe parameters, so the scale comes from the values. A row that does + not fit the scale chosen for earlier rows rebinds instead of losing digits (5.5.0 betas + stored 123456789 as 23456789) or failing. + """ + values = [Decimal(v) for v in values] + assert _fast_executemany_numeric(cursor, values) == values + + +def test_fast_executemany_guessed_scale_int_after_scale(cursor: pyodbc.Cursor): + "A Python int after a guessed scale rebinds instead of losing its leading digit" + values = [Decimal('1E-30'), 123456789, Decimal('2.5'), 10**37] + assert _fast_executemany_numeric(cursor, values) == [Decimal(v) for v in values] + + +@pytest.mark.parametrize("before", [[], [Decimal('1E-30')]], ids=["alone", "after-scale"]) +@pytest.mark.parametrize("value", [ + pytest.param(Decimal('12.1111111111111111111111111111111111111'), id="39-digits"), + pytest.param(Decimal('1' * 39), id="39-digit-decimal"), +]) +def test_fast_executemany_too_many_digits(cursor: pyodbc.Cursor, before, value): + "A value with more than 38 digits raises instead of being stored with a digit missing" + cursor.execute("create table t1(v numeric)") + cursor.fast_executemany = True + with pytest.raises(pyodbc.ProgrammingError, match="Numeric overflow|loses precision"): + cursor.executemany("insert into t1 values (?)", [(v,) for v in before + [value]]) + + +def test_fast_executemany_too_many_digits_int(cursor: pyodbc.Cursor): + "A 39-digit int bound as a numeric raises instead of being stored with a digit missing" + cursor.execute("create table t1(v numeric)") + cursor.fast_executemany = True + with pytest.raises(pyodbc.ProgrammingError, match="Numeric overflow"): + cursor.executemany("insert into t1 values (?)", [(Decimal('1.5'),), (int('1' * 39),)]) + + +def test_fast_executemany_guessed_scale_too_small(cursor: pyodbc.Cursor): + "More than 38 decimal places cannot be bound" + with pytest.raises(pyodbc.ProgrammingError, match="loses precision"): + _fast_executemany_numeric(cursor, [Decimal('1E-40')]) + + +@pytest.mark.parametrize("sizes", [[(pyodbc.SQL_DECIMAL, 18)], [18]]) +def test_fast_executemany_setinputsizes_without_scale(cursor: pyodbc.Cursor, sizes): + "setinputsizes without a scale still takes the scale from the values" + cursor.execute("create table t1(v numeric(18, 9))") + cursor.fast_executemany = True + cursor.setinputsizes(sizes) + values = [Decimal('1.1234567'), Decimal('12345.123456789')] + cursor.executemany("insert into t1 values (?)", [(v,) for v in values]) + assert [row[0] for row in cursor.execute("select v from t1 order by v")] == values + + +def test_fast_executemany_decimal_and_str(cursor: pyodbc.Cursor): + "A guessed Decimal scale does not change how a str in the same column is bound" + values = ['x' * 60, Decimal('15'), 'y' * 60] + results = _fast_executemany_numeric(cursor, values, column="text") + assert results == ['x' * 60, '15', 'y' * 60] + From aa85f4de410d808fc83fef91da61588b2769da15 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 14:50:40 -0600 Subject: [PATCH 09/22] Add Connection.decimal_mode, read PostgreSQL numerics as text, and support NaN and Infinity 5.4.0 reads DECIMAL and NUMERIC columns into a SQL_NUMERIC_STRUCT. psqlODBC cannot put NaN, Infinity, or more than 38 digits into the struct, and silently returns 0 for the first two and a wrong number for the third. The text path the struct replaced has its own problem: it strips everything but the decimal separator pyodbc read from the locale at import, so a driver that sends '.' while that separator is ',' (#753), or psqlODBC under a comma locale set after import, reads 3656.88 as 365688. Connection.decimal_mode selects how these columns are read: - 'binary': the SQL_NUMERIC_STRUCT, as in 5.4.0. It stays the default except for PostgreSQL. A value the driver reports did not fit (01004) raises DataError instead of returning the wrong number left in the struct. The column is not read again as text: a conforming driver returns SQL_NO_DATA for a column already read, and what others return cannot be relied on. - 'text': text from drivers that never add grouping separators. The one separator can only be the decimal point, so '.' and ',' are both accepted whatever the locale, along with NaN and [-]Infinity. Anything else raises DataError. This is the default when SQL_DBMS_NAME is PostgreSQL, and is as fast as 'binary'. - 'locale': the pre-5.4 path, using setDecimalSeparator, for drivers that add grouping separators or currency symbols. fetch_decimal_as_string is deprecated and will be removed in 6.0. Reading or setting it raises FutureWarning; True selects 'locale' and False 'binary', as before, except that True leaves 'text' alone, since the getter returns True for both text modes and saving and restoring the value should change nothing. decimal_mode accepts the same bools, also with a FutureWarning, until 6.0. Cursor.execute now binds Decimal NaN, Infinity, and -Infinity as text and leaves it to the database to accept or reject them; PostgreSQL stores them and SQL Server raises DataError. fast_executemany and table-valued parameters still raise ProgrammingError, since the struct cannot hold them, and a signaling NaN always raises. Tests check that 'binary' and 'text' reads give identical Decimals, exponent included, on SQL Server and PostgreSQL. --- src/cnxninfo.cpp | 17 +++ src/cnxninfo.h | 3 + src/connection.cpp | 100 ++++++++++++++++-- src/connection.h | 19 +++- src/cursor.cpp | 2 +- src/decimal.cpp | 121 ++++++++++++++++++++- src/decimal.h | 3 +- src/errors.cpp | 9 +- src/getdata.cpp | 24 ++++- src/params.cpp | 71 ++++++++++--- src/pyodbc.pyi | 37 ++++++- tests/mysql_test.py | 4 +- tests/postgresql_test.py | 220 ++++++++++++++++++++++++++++++++++++++- tests/sqlite_test.py | 48 +++++++++ tests/sqlserver_test.py | 66 ++++++++++-- 15 files changed, 692 insertions(+), 52 deletions(-) diff --git a/src/cnxninfo.cpp b/src/cnxninfo.cpp index 6a417062..2ab86a55 100644 --- a/src/cnxninfo.cpp +++ b/src/cnxninfo.cpp @@ -93,6 +93,7 @@ static PyObject* CnxnInfo_New(Connection* cnxn) p->supports_describeparam = false; p->datetime_precision = 19; // default: "yyyy-mm-dd hh:mm:ss" p->need_long_data_len = false; + p->is_postgresql = false; p->varchar_maxlength = 1 * 1024 * 1024 * 1024; p->wvarchar_maxlength = 1 * 1024 * 1024 * 1024; @@ -127,6 +128,22 @@ static PyObject* CnxnInfo_New(Connection* cnxn) if (SQL_SUCCEEDED(SQLGetInfo(cnxn->hdbc, SQL_NEED_LONG_DATA_LEN, szYN, _countof(szYN), &cch))) p->need_long_data_len = (szYN[0] == 'Y'); + // psqlODBC reports "PostgreSQL" for every server it connects to. PostgreSQL numerics can + // hold NaN, Infinity, and more digits than a SQL_NUMERIC_STRUCT, which psqlODBC silently + // turns into 0 or a wrong number, so they are read as text. + // The buffer is large enough for any real name: unixODBC reads past the end of a buffer + // that a long name ("Microsoft SQL Server" is 20 characters) was truncated to fit. + char szDBMS[256]; + if (SQL_SUCCEEDED(SQLGetInfo(cnxn->hdbc, SQL_DBMS_NAME, szDBMS, _countof(szDBMS), &cch))) + { + szDBMS[_countof(szDBMS) - 1] = 0; + const char* pg = "postgresql"; + int i = 0; + while (pg[i] && szDBMS[i] && (szDBMS[i] | 0x20) == pg[i]) + i++; + p->is_postgresql = (pg[i] == 0); + } + GetColumnSize(cnxn, SQL_VARCHAR, &p->varchar_maxlength); GetColumnSize(cnxn, SQL_WVARCHAR, &p->wvarchar_maxlength); GetColumnSize(cnxn, SQL_VARBINARY, &p->binary_maxlength); diff --git a/src/cnxninfo.h b/src/cnxninfo.h index b3802085..fb07aed5 100644 --- a/src/cnxninfo.h +++ b/src/cnxninfo.h @@ -31,6 +31,9 @@ struct CnxnInfo // we'll use SQL_DATA_AT_EXEC when possible. If this is true, however, we'll need to pass the length. bool need_long_data_len; + // True if SQL_DBMS_NAME is PostgreSQL, so DECIMAL and NUMERIC default to DECIMAL_MODE_TEXT. + bool is_postgresql; + // These are from SQLGetTypeInfo.column_size, so the char ones are in characters, not bytes. int varchar_maxlength; int wvarchar_maxlength; diff --git a/src/connection.cpp b/src/connection.cpp index e9cc12eb..c85bcd2a 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -362,7 +362,7 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou cnxn->compat_diagrec_byte_length = false; cnxn->attrs_before = attrs_before_o.Detach(); - cnxn->fetch_decimal_as_string = false; + cnxn->decimal_mode = DECIMAL_MODE_BINARY; // This is an inefficient default, but should work all the time. When we are offered // single-byte text we don't actually know what the encoding is. For example, with SQL @@ -452,6 +452,7 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou cnxn->varchar_maxlength = p->varchar_maxlength; cnxn->wvarchar_maxlength = p->wvarchar_maxlength; cnxn->binary_maxlength = p->binary_maxlength; + cnxn->decimal_mode = p->is_postgresql ? DECIMAL_MODE_TEXT : DECIMAL_MODE_BINARY; return reinterpret_cast(cnxn); } @@ -1179,6 +1180,75 @@ static int Connection_settimeout(PyObject* self, PyObject* value, void* closure) return 0; } +static const char* const DECIMAL_MODE_NAMES[] = { "binary", "text", "locale" }; + +static PyObject* Connection_getdecimalmode(PyObject* self, void* closure) +{ + UNUSED(closure); + + Connection* cnxn = Connection_Validate(self); + if (!cnxn) + return 0; + + return PyUnicode_FromString(DECIMAL_MODE_NAMES[cnxn->decimal_mode]); +} + +static int SetDecimalModeFromBool(Connection* cnxn, PyObject* value, const char* attr) +{ + // The bool values of fetch_decimal_as_string, kept until 6.0. True keeps its old meaning, + // the locale path, rather than becoming "text". Since the getter returns True for both + // text modes, True leaves 'text' alone, so saving and restoring the value changes nothing. + + int isTrue = PyObject_IsTrue(value); + if (isTrue < 0) + return -1; + int mode = !isTrue ? DECIMAL_MODE_BINARY + : cnxn->decimal_mode == DECIMAL_MODE_TEXT ? DECIMAL_MODE_TEXT : DECIMAL_MODE_LOCALE; + if (PyErr_WarnFormat(PyExc_FutureWarning, 1, + "Setting %s to %s is deprecated and will not be supported in pyodbc 6.0; " + "set decimal_mode = '%s' instead", attr, isTrue ? "True" : "False", + DECIMAL_MODE_NAMES[mode]) < 0) + return -1; + cnxn->decimal_mode = mode; + return 0; +} + +static int Connection_setdecimalmode(PyObject* self, PyObject* value, void* closure) +{ + UNUSED(closure); + + Connection* cnxn = Connection_Validate(self); + if (!cnxn) + return -1; + + if (value == 0) + { + PyErr_SetString(PyExc_TypeError, "Cannot delete the decimal_mode attribute."); + return -1; + } + + if (PyBool_Check(value)) + return SetDecimalModeFromBool(cnxn, value, "decimal_mode"); + + if (PyUnicode_Check(value)) + { + for (int i = 0; i < (int)_countof(DECIMAL_MODE_NAMES); i++) + { + if (PyUnicode_CompareWithASCIIString(value, DECIMAL_MODE_NAMES[i]) == 0) + { + cnxn->decimal_mode = i; + return 0; + } + } + PyErr_Format(PyExc_ValueError, + "decimal_mode must be 'binary', 'text', or 'locale', not %R", value); + return -1; + } + + PyErr_Format(PyExc_TypeError, "decimal_mode must be a str, not %s", Py_TYPE(value)->tp_name); + return -1; +} + static PyObject* Connection_getfetchdecimalasstring(PyObject* self, void* closure) { UNUSED(closure); @@ -1187,9 +1257,12 @@ static PyObject* Connection_getfetchdecimalasstring(PyObject* self, void* closur if (!cnxn) return 0; - PyObject* result = cnxn->fetch_decimal_as_string ? Py_True : Py_False; - Py_INCREF(result); - return result; + if (PyErr_WarnEx(PyExc_FutureWarning, + "fetch_decimal_as_string is deprecated and will be removed in pyodbc 6.0; " + "use decimal_mode instead", 1) < 0) + return 0; + + return PyBool_FromLong(cnxn->decimal_mode != DECIMAL_MODE_BINARY); } static int Connection_setfetchdecimalasstring(PyObject* self, PyObject* value, void* closure) @@ -1206,8 +1279,7 @@ static int Connection_setfetchdecimalasstring(PyObject* self, PyObject* value, v return -1; } - cnxn->fetch_decimal_as_string = PyObject_IsTrue(value); - return 0; + return SetDecimalModeFromBool(cnxn, value, "fetch_decimal_as_string"); } static PyObject* Connection_getcompat_diagrec_byte_length(PyObject* self, void* closure) @@ -1632,10 +1704,20 @@ static PyGetSetDef Connection_getseters[] = { { "maxwrite", Connection_getmaxwrite, Connection_setmaxwrite, "The maximum bytes to write before using SQLPutData.", 0 }, { "readvar_initsize", Connection_getreadvarinitsize, Connection_setreadvarinitsize, "The initial buffer size in bytes for reading values from variable-length columns.", 0 }, + { "decimal_mode", Connection_getdecimalmode, Connection_setdecimalmode, + "How DECIMAL and NUMERIC values are read:\n\n" + "'binary': into a SQL_NUMERIC_STRUCT, which is not affected by the locale. This is the\n" + " default except for PostgreSQL. The struct cannot hold NaN or Infinity, or more than\n" + " 38 digits.\n" + "'text': as text with no grouping separators: a sign, digits, and at most one decimal\n" + " point, which can be '.' or ','; or NaN, Infinity, or -Infinity. Other text raises\n" + " DataError. This is the default for PostgreSQL.\n" + "'locale': as text, after removing everything but digits, '-', and the separator from\n" + " setDecimalSeparator, which then becomes the decimal point. For drivers that add\n" + " grouping separators or currency symbols.", 0 }, { "fetch_decimal_as_string", Connection_getfetchdecimalasstring, Connection_setfetchdecimalasstring, - "If True, DECIMAL and NUMERIC values are fetched as strings using the legacy\n" - "locale-aware path. If False (the default), values are fetched using a binary\n" - "representation that is not affected by the locale.", 0 }, + "Deprecated; use decimal_mode. True means decimal_mode is not 'binary'. Setting True\n" + "selects 'locale' and False selects 'binary'.", 0 }, { "compat_diagrec_byte_length", Connection_getcompat_diagrec_byte_length, Connection_setcompat_diagrec_byte_length, "If True, the driver reports byte length instead of character length in SQLGetDiagRecW().", 0 }, { 0 } diff --git a/src/connection.h b/src/connection.h index 44a04f9a..962c18de 100644 --- a/src/connection.h +++ b/src/connection.h @@ -18,6 +18,21 @@ extern PyTypeObject ConnectionType; struct TextEnc; +// Connection.decimal_mode: how DECIMAL and NUMERIC columns are read. +enum +{ + // Into a SQL_NUMERIC_STRUCT, falling back to text for drivers that can't. + DECIMAL_MODE_BINARY, + + // As text with no grouping separators: a sign, digits, and at most one decimal point, + // which can be '.' or ',', or NaN or [-]Infinity. Anything else raises. + DECIMAL_MODE_TEXT, + + // As text cleaned with the decimal separator from setDecimalSeparator, the behavior from + // before 5.4. Grouping separators and currency symbols are removed. + DECIMAL_MODE_LOCALE, +}; + struct Connection { PyObject_HEAD @@ -39,8 +54,8 @@ struct Connection // to insert NULLs into binary columns. bool supports_describeparam; - // Set to true if the driver doesn't handle SQL_NUMERIC_STRUCT properly. - bool fetch_decimal_as_string; + // How DECIMAL and NUMERIC columns are read: one of the DECIMAL_MODE_ values. + int decimal_mode; // The column size of datetime columns, obtained from SQLGetInfo(), used to determine the datetime precision. int datetime_precision; diff --git a/src/cursor.cpp b/src/cursor.cpp index fbbedbcf..38350a10 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -573,7 +573,7 @@ bool InitColumnInfo(Cursor* cursor, SQLUSMALLINT iCol, ColumnInfo* pinfo) // which doesn't make much sense (to me, anyway). So I'm going to follow the lead of // the SQL standard and fall back on fetching the value from the driver as a string // when scale does not fall in the range 0..127. - if (!cursor->cnxn->fetch_decimal_as_string && pinfo->scale >= 0 && pinfo->scale <= 127) + if (cursor->cnxn->decimal_mode == DECIMAL_MODE_BINARY && pinfo->scale >= 0 && pinfo->scale <= 127) { // Set up the ARD once for this column so SQLGetData fills a SQL_NUMERIC_STRUCT. // These settings persist for all rows on this statement handle. diff --git a/src/decimal.cpp b/src/decimal.cpp index ff17e3d5..4b4b10c3 100644 --- a/src/decimal.cpp +++ b/src/decimal.cpp @@ -3,6 +3,9 @@ #include "wrapper.h" #include "textenc.h" #include "decimal.h" +#include "pyodbcmodule.h" +#include "connection.h" +#include "errors.h" static PyObject* decimal = 0; // The Decimal constructor. @@ -135,15 +138,127 @@ static PyObject* DecimalFromUnicode(PyObject* text) return PyObject_CallFunctionObjArgs(decimal, cleaned.Get(), 0); } -PyObject* DecimalFromText(const TextEnc& enc, const byte* pb, Py_ssize_t cb) +static bool MatchesNoCase(const char* pch, Py_ssize_t cch, const char* word) { - // Creates a Decimal object from a text buffer. + // Returns true if the cch characters at pch are `word`, which must be lowercase, ignoring + // ASCII case. + Py_ssize_t i = 0; + for (; i < cch && word[i]; i++) + if ((pch[i] | 0x20) != word[i]) + return false; + return i == cch && word[i] == 0; +} + +PyObject* DecimalFromStrictText(PyObject* text) +{ + // Creates a Decimal object from the text of a driver that never adds grouping separators, + // as Connection.decimal_mode "text" describes: an optional sign, digits with at most one + // decimal point, an optional exponent, or NaN, Inf, or Infinity. Leading and trailing + // spaces are allowed. + // + // Without grouping, the one separator can only be the decimal point, so both '.' and ',' + // are accepted whatever the locale. (psqlODBC, for example, writes the decimal point of the + // process's C locale, while other drivers always write '.'.) Anything else raises rather + // than being guessed at. + + if (!PyUnicode_IS_ASCII(text)) + goto invalid; + + { + const char* pch = (const char*)PyUnicode_1BYTE_DATA(text); + Py_ssize_t start = 0; + Py_ssize_t end = PyUnicode_GET_LENGTH(text); + while (start < end && pch[start] == ' ') + start++; + while (end > start && pch[end - 1] == ' ') + end--; + + Py_ssize_t i = start; + if (i < end && (pch[i] == '-' || pch[i] == '+')) + i++; + + if (i < end && !(pch[i] >= '0' && pch[i] <= '9') && pch[i] != '.' && pch[i] != ',') + { + const char* word = pch + i; + Py_ssize_t cch = end - i; + if (MatchesNoCase(word, cch, "nan") || MatchesNoCase(word, cch, "inf") || + MatchesNoCase(word, cch, "infinity")) + { + return PyObject_CallFunctionObjArgs(decimal, text, 0); + } + goto invalid; + } + + Py_ssize_t cDigits = 0; + Py_ssize_t iComma = -1; + bool point = false; + for (; i < end; i++) + { + char ch = pch[i]; + if (ch >= '0' && ch <= '9') + cDigits++; + else if ((ch == '.' || ch == ',') && !point) + { + point = true; + if (ch == ',') + iComma = i; + } + else + break; + } + if (cDigits == 0) + goto invalid; + + if (i < end && (pch[i] == 'e' || pch[i] == 'E')) + { + i++; + if (i < end && (pch[i] == '-' || pch[i] == '+')) + i++; + Py_ssize_t cExpDigits = 0; + while (i < end && pch[i] >= '0' && pch[i] <= '9') + { + i++; + cExpDigits++; + } + if (cExpDigits == 0) + goto invalid; + } + if (i != end) + goto invalid; + + if (iComma == -1) + return PyObject_CallFunctionObjArgs(decimal, text, 0); + + // Replace the decimal comma, which the Decimal constructor does not accept. + Py_ssize_t cch = end - start; + char* copy = (char*)PyMem_Malloc(cch); + if (!copy) + return PyErr_NoMemory(); + memcpy(copy, pch + start, cch); + copy[iComma - start] = '.'; + Object point_text(PyUnicode_FromStringAndSize(copy, cch)); + PyMem_Free(copy); + if (!point_text) + return 0; + return PyObject_CallFunctionObjArgs(decimal, point_text.Get(), 0); + } + +invalid: + return RaiseErrorV(0, DataError, + "Unexpected text %R for a DECIMAL or NUMERIC value. Set Connection.decimal_mode = " + "'locale' if the driver adds grouping separators or currency symbols.", text); +} + +PyObject* DecimalFromText(const TextEnc& enc, const byte* pb, Py_ssize_t cb, bool strict) +{ + // Creates a Decimal object from a text buffer. If `strict` is true, the text is parsed as + // DecimalFromStrictText describes; otherwise it is cleaned using the decimal separator. Object text(TextBufferToObject(enc, pb, cb)); if (!text) return 0; - return DecimalFromUnicode(text.Get()); + return strict ? DecimalFromStrictText(text.Get()) : DecimalFromUnicode(text.Get()); } PyObject* DecimalFromAsciiText(const char* pch, Py_ssize_t cch) diff --git a/src/decimal.h b/src/decimal.h index b86cef08..7361c439 100644 --- a/src/decimal.h +++ b/src/decimal.h @@ -4,6 +4,7 @@ bool InitializeDecimal(); PyObject* GetDecimalPoint(); bool SetDecimalPoint(PyObject* pNew); -PyObject* DecimalFromText(const TextEnc& enc, const byte* pb, Py_ssize_t cb); +PyObject* DecimalFromText(const TextEnc& enc, const byte* pb, Py_ssize_t cb, bool strict); +PyObject* DecimalFromStrictText(PyObject* text); PyObject* DecimalFromAsciiText(const char* pch, Py_ssize_t cch); PyObject* DecimalFromNumericStruct(const SQL_NUMERIC_STRUCT& num); diff --git a/src/errors.cpp b/src/errors.cpp index eb12872e..9116161a 100644 --- a/src/errors.cpp +++ b/src/errors.cpp @@ -338,14 +338,19 @@ PyObject* GetErrorFromHandle(Connection *conn, const char* szFunction, HDBC hdbc } -static bool GetSqlState(HSTMT hstmt, char* szSqlState) +static bool GetSqlState(HSTMT hstmt, char (&szSqlState)[6]) { + // The buffer length includes the terminator. Passing 5 lets a driver manager that honors + // it truncate the SQLSTATE to 4 characters. SQLSMALLINT cchMsg; SQLRETURN ret; + memset(szSqlState, 0, sizeof(szSqlState)); Py_BEGIN_ALLOW_THREADS - ret = SQLGetDiagField(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_SQLSTATE, (SQLCHAR*)szSqlState, 5, &cchMsg); + ret = SQLGetDiagField(SQL_HANDLE_STMT, hstmt, 1, SQL_DIAG_SQLSTATE, (SQLCHAR*)szSqlState, + sizeof(szSqlState), &cchMsg); Py_END_ALLOW_THREADS + szSqlState[5] = 0; return SQL_SUCCEEDED(ret); } diff --git a/src/getdata.cpp b/src/getdata.cpp index 97102cc6..8b0010ac 100644 --- a/src/getdata.cpp +++ b/src/getdata.cpp @@ -372,7 +372,7 @@ static PyObject* RaiseNotNumericStruct(Py_ssize_t iCol, SQLLEN cbFetched) { return RaiseErrorV(0, Error, "The driver did not return a SQL_NUMERIC_STRUCT for the DECIMAL/NUMERIC column at " - "index %zd (length %ld). Set Connection.fetch_decimal_as_string = True to read " + "index %zd (length %ld). Set Connection.decimal_mode = 'text' or 'locale' to read " "these columns as text.", iCol, (long)cbFetched); } @@ -396,6 +396,14 @@ static PyObject* GetDataDecimalBinary(Cursor* cur, Py_ssize_t iCol) // The buffer is zeroed so that a short text leaves no uninitialized bytes behind it, and has // room for the text of any DECIMAL, because drivers do not return a converted DECIMAL in // pieces. A conforming driver ignores the buffer length for SQL_C_NUMERIC. + // + // A value with more than 38 digits does not fit the struct. psqlODBC, for one, reports + // 01004 for it and leaves a wrong value in the struct, so 01004 raises DataError. The + // column is not read again as text: conforming drivers return SQL_NO_DATA for a column + // already read, and what others return cannot be relied on. + // + // Returns 0 without an exception if SQLGetData failed, and the value should be read as + // text instead, as 5.4.0 did. union { @@ -417,6 +425,14 @@ static PyObject* GetDataDecimalBinary(Cursor* cur, Py_ssize_t iCol) if (cbFetched == SQL_NULL_DATA) Py_RETURN_NONE; + if (ret == SQL_SUCCESS_WITH_INFO && HasSqlState(cur->hstmt, "01004")) + { + return RaiseErrorV("22003", DataError, + "The DECIMAL/NUMERIC value at column index %zd does not fit in a " + "SQL_NUMERIC_STRUCT. Set Connection.decimal_mode = 'text' to read it as text.", + iCol); + } + if (cbFetched > 0 && cbFetched < (SQLLEN)sizeof(buffer) && IsDecimalText(buffer.text, (Py_ssize_t)cbFetched)) { cur->colinfos[iCol].use_decimal_binary = false; @@ -429,7 +445,7 @@ static PyObject* GetDataDecimalBinary(Cursor* cur, Py_ssize_t iCol) return DecimalFromNumericStruct(buffer.num); } -static PyObject* GetDataDecimalString(Cursor* cur, Py_ssize_t iCol) +static PyObject* GetDataDecimalString(Cursor* cur, Py_ssize_t iCol, bool strict) { // The SQL_NUMERIC_STRUCT support is hopeless (SQL Server ignores scale on input parameters // and output columns, Oracle does something else weird, and many drivers don't support it @@ -466,7 +482,7 @@ static PyObject* GetDataDecimalString(Cursor* cur, Py_ssize_t iCol) Py_RETURN_NONE; } - Object result(DecimalFromText(enc, pbData, cbData)); + Object result(DecimalFromText(enc, pbData, cbData, strict)); PyMem_Free(pbData); @@ -842,7 +858,7 @@ PyObject* GetData(Cursor* cur, Py_ssize_t iCol) return NULL; // SQLGetData failed without a Python exception — fall through. } - return GetDataDecimalString(cur, iCol); + return GetDataDecimalString(cur, iCol, cur->cnxn->decimal_mode == DECIMAL_MODE_TEXT); case SQL_BIT: return GetDataBit(cur, iCol); diff --git a/src/params.cpp b/src/params.cpp index b7974ec5..84fd028e 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -41,7 +41,8 @@ struct DAEParam // The largest precision a SQL_NUMERIC_STRUCT is used for (SQL Server's maximum). static const int MAX_NUMERIC_PRECISION = 38; -static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp); +static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp, + const char** special = 0); static void StripDecimalZeros(PyObject* digits, Py_ssize_t& numDigits, Py_ssize_t& exp) { @@ -272,11 +273,16 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) return true; } -static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp) +static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp, + const char** special) { // Calls value.as_tuple() and checks that the result is the (sign, digits, exponent) tuple - // a Decimal returns, since a subclass can override as_tuple. NaN and Infinity have a str - // exponent and cannot be bound. + // a Decimal returns, since a subclass can override as_tuple. + // + // NaN and Infinity have a str exponent. If `special` is not null, it is set to the text to + // send for them, "NaN", "Infinity", or "-Infinity", and to null for any other value. If it + // is null, they raise, since a SQL_NUMERIC_STRUCT cannot hold them. A signaling NaN always + // raises. if (!parts.Attach(PyObject_CallMethod(value, "as_tuple", 0))) return false; @@ -288,14 +294,34 @@ static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject return false; } - if (!PyLong_Check(PyTuple_GET_ITEM(t, 2))) - { - RaiseErrorV(0, ProgrammingError, "Cannot bind a Decimal NaN or Infinity"); + if (special) + *special = 0; + + sign = PyLong_AsLong(PyTuple_GET_ITEM(t, 0)); + if (sign == -1 && PyErr_Occurred()) + return false; + + PyObject* e = PyTuple_GET_ITEM(t, 2); + if (!PyLong_Check(e)) + { + // Decimal uses 'n' for NaN, 'N' for a signaling NaN, and 'F' for Infinity. + bool snan = PyUnicode_Check(e) && PyUnicode_CompareWithASCIIString(e, "N") == 0; + bool inf = PyUnicode_Check(e) && PyUnicode_CompareWithASCIIString(e, "F") == 0; + if (snan) + RaiseErrorV(0, ProgrammingError, "Cannot bind a Decimal signaling NaN"); + else if (!special) + RaiseErrorV(0, ProgrammingError, + "Decimal NaN and Infinity cannot be used with fast_executemany or table-valued " + "parameters"); + else + { + *special = !inf ? "NaN" : sign ? "-Infinity" : "Infinity"; + return true; + } return false; } - sign = PyLong_AsLong(PyTuple_GET_ITEM(t, 0)); - exp = PyLong_AsSsize_t(PyTuple_GET_ITEM(t, 2)); + exp = PyLong_AsSsize_t(e); if (PyErr_Occurred()) return false; @@ -1111,14 +1137,35 @@ static bool GetDecimalInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param long sign; PyObject* digits; Py_ssize_t exp; - if (!GetDecimalParts(param, t, sign, digits, exp)) + const char* special; + if (!GetDecimalParts(param, t, sign, digits, exp, &special)) return false; - Py_ssize_t count = PyTuple_GET_SIZE(digits); - info.ValueType = SQL_C_CHAR; info.ParameterType = SQL_NUMERIC; + if (special) + { + // NaN or Infinity: send the text and leave it to the database to accept it, as + // PostgreSQL does, or raise, as SQL Server does. + size_t cch = strlen(special); + char* text = (char*)PyMem_Malloc(cch + 1); + if (!text) + { + PyErr_NoMemory(); + return false; + } + memcpy(text, special, cch + 1); + info.ColumnSize = MAX_NUMERIC_PRECISION; + info.DecimalDigits = 0; + info.ParameterValuePtr = text; + info.allocated = true; + info.StrLen_or_Ind = (SQLINTEGER)cch; + return true; + } + + Py_ssize_t count = PyTuple_GET_SIZE(digits); + if (exp >= 0) { // (1 2 3) exp = 2 --> '12300' diff --git a/src/pyodbc.pyi b/src/pyodbc.pyi index ecb377dc..ec220e3b 100644 --- a/src/pyodbc.pyi +++ b/src/pyodbc.pyi @@ -2,7 +2,9 @@ # ruff: noqa: E303, N802, N803 from __future__ import annotations from collections.abc import Callable, Generator, Iterable, Iterator, Sequence -from typing import Any, Final, Self +from typing import Any, Final, Literal, Self + +from typing_extensions import deprecated import ctypes # SQLSetConnectAttr attributes @@ -362,14 +364,39 @@ class Connection: ... @property + def decimal_mode(self) -> Literal['binary', 'text', 'locale']: + """How DECIMAL and NUMERIC values are read. + + 'binary': into a SQL_NUMERIC_STRUCT, which is not affected by the locale. This is + the default except for PostgreSQL. The struct cannot hold NaN or Infinity, or more + than 38 digits. A column whose driver returns text in place of the struct is read + as text. + + 'text': as text with no grouping separators: a sign, digits, and at most one decimal + point, which can be '.' or ','; or NaN, Infinity, or -Infinity. Other text raises + DataError. This is the default for PostgreSQL. + + 'locale': as text, after removing everything but digits, '-', and the separator from + setDecimalSeparator, which then becomes the decimal point. For drivers that add + grouping separators or currency symbols. + + Setting True or False is deprecated: they select 'locale' and 'binary', and will not + be accepted in pyodbc 6.0.""" + ... + + @decimal_mode.setter + def decimal_mode(self, value: Literal['binary', 'text', 'locale']) -> None: + ... + + @property + @deprecated("Use decimal_mode; fetch_decimal_as_string will be removed in pyodbc 6.0.") def fetch_decimal_as_string(self) -> bool: - """If True, DECIMAL and NUMERIC values will be fetched as strings using the - legacy local-aware path. If False (the default), values are fetched using a - binary representation that is not affected by the locale. A column whose - driver returns text in place of the binary representation is read as text.""" + """Deprecated; use decimal_mode. True if decimal_mode is not 'binary'. Setting True + selects 'locale' and False selects 'binary'.""" ... @fetch_decimal_as_string.setter + @deprecated("Use decimal_mode; fetch_decimal_as_string will be removed in pyodbc 6.0.") def fetch_decimal_as_string(self, value: bool) -> None: ... diff --git a/tests/mysql_test.py b/tests/mysql_test.py index 732ae89c..b66faed1 100644 --- a/tests/mysql_test.py +++ b/tests/mysql_test.py @@ -121,8 +121,8 @@ def test_decimal(cursor: pyodbc.Cursor): ('-10.0010', '19,4') ] - for mode in (True, False): - cursor.connection.fetch_decimal_as_string = mode + for mode in ('binary', 'text', 'locale'): + cursor.connection.decimal_mode = mode for value, prec in tests: value = Decimal(value) cursor.execute("drop table if exists t1") diff --git a/tests/postgresql_test.py b/tests/postgresql_test.py index f06c7039..75caab6e 100644 --- a/tests/postgresql_test.py +++ b/tests/postgresql_test.py @@ -4,7 +4,7 @@ # -*- coding: utf-8 -*- import ctypes -import os, uuid +import os, random, uuid from decimal import Decimal from typing import Iterator @@ -172,8 +172,8 @@ def test_decimal(cursor: pyodbc.Cursor): params = [Decimal(n) for n in "-1000.10 -1234.56 -1 0 1 1000.10 1234.56 100010 123456789.21".split()] params.append(None) - for mode in (True, False): - cursor.connection.fetch_decimal_as_string = mode + for mode in ('binary', 'text', 'locale'): + cursor.connection.decimal_mode = mode for param in params: cursor.execute("truncate table t1") cursor.execute("insert into t1 values (?)", param) @@ -188,8 +188,8 @@ def test_numeric(cursor: pyodbc.Cursor): params = [Decimal(n) for n in "-1234.56 -1 0 1 1234.56 123456789.21".split()] params.append(None) - for mode in (True, False): - cursor.connection.fetch_decimal_as_string = mode + for mode in ('binary', 'text', 'locale'): + cursor.connection.decimal_mode = mode for param in params: cursor.execute("truncate table t1") cursor.execute("insert into t1 values (?)", param) @@ -706,6 +706,170 @@ def test_handles(cursor: pyodbc.Cursor): assert conn.hdbc is None +# --------------------------------------------------------------------------------------------- +# DECIMAL / NUMERIC reads and writes that 5.4.0 gets wrong. +# +# psqlODBC cannot put NaN, Infinity, or more than 38 digits into a SQL_NUMERIC_STRUCT, and +# formats numeric text using the process's C locale at fetch time. +# --------------------------------------------------------------------------------------------- + +SPECIAL_VALUES = ['NaN', 'Infinity', '-Infinity'] + +# More digits than a SQL_NUMERIC_STRUCT can hold. +BIG_NUMERICS = [ + '123456789012345678901234567890123456789012345', + '-123456789012345678901234567890123456789012345', + '1234567890123456789012345678901234567890.5', +] + +# How each decimal test reads DECIMAL/NUMERIC columns: the connection's default, forced text, +# or forced binary (SQL_NUMERIC_STRUCT). +DECIMAL_MODES = ['default', 'text', 'binary'] + + +def _set_decimal_mode(cnxn, mode): + if mode != 'default': + cnxn.decimal_mode = mode + + +def _skip_without_numeric_infinity(cursor, value): + # PostgreSQL added Infinity to numeric in version 14. + version = int(cursor.execute('show server_version_num').fetchval()) + if 'Infinity' in value and version < 140000: + pytest.skip('numeric Infinity requires PostgreSQL 14') + + +@pytest.fixture() +def comma_locale(): + """ + Sets LC_NUMERIC to a locale whose decimal point is a comma, *after* pyodbc was imported, so + psqlODBC formats numerics as '3656,88' while pyodbc's decimal separator is still '.'. + """ + import locale + saved = locale.setlocale(locale.LC_NUMERIC) + for name in ('de_DE.UTF-8', 'de_DE.utf8', 'German_Germany.1252'): + try: + locale.setlocale(locale.LC_NUMERIC, name) + break + except locale.Error: + pass + else: + pytest.skip('no comma-decimal locale is installed') + try: + yield + finally: + locale.setlocale(locale.LC_NUMERIC, saved) + + +def test_decimal_mode_default(cursor: pyodbc.Cursor): + # psqlODBC cannot put NaN, Infinity, or more than 38 digits in a SQL_NUMERIC_STRUCT. + assert cursor.connection.decimal_mode == 'text' + + +@pytest.mark.parametrize('mode', ['default', 'text']) +@pytest.mark.parametrize('value', SPECIAL_VALUES) +def test_numeric_special_values_read(cursor: pyodbc.Cursor, mode, value): + # 5.4.0 reads these as Decimal('0') in binary mode and raises InvalidOperation in text + # mode. + _skip_without_numeric_infinity(cursor, value) + _set_decimal_mode(cursor.connection, mode) + cursor.execute("create table t1(col numeric)") + cursor.execute(f"insert into t1 values ('{value}')") + result = cursor.execute("select col from t1").fetchval() + assert str(result) == value + + +@pytest.mark.parametrize('mode', DECIMAL_MODES) +@pytest.mark.parametrize('value', BIG_NUMERICS) +def test_numeric_over_38_digits_read(cursor: pyodbc.Cursor, mode, value): + # psqlODBC overflows the struct and returns SQL_SUCCESS_WITH_INFO (01004); 5.4.0 ignores + # the info and returns a wrong number. The binary path raises rather than reading the + # column again as text. + _set_decimal_mode(cursor.connection, mode) + # Both an unconstrained column and one whose declared precision is over 38. + cursor.execute("create table t1(col numeric, col50 numeric(50,1))") + cursor.execute(f"insert into t1 values ({value}, {value})") + for col in ['col', 'col50']: + cursor.execute(f"select {col} from t1") + if mode == 'binary': + with pytest.raises(pyodbc.DataError, match='does not fit'): + cursor.fetchval() + else: + assert cursor.fetchval() == Decimal(value) + + +@pytest.mark.parametrize('mode', DECIMAL_MODES) +def test_numeric_read_comma_locale(cursor: pyodbc.Cursor, comma_locale, mode): + # With a comma-decimal locale set after import, 5.4.0's text path strips the comma and + # reads 3656,88 as 365688. + _set_decimal_mode(cursor.connection, mode) + values = ['3656.88', '-3656.88', '0.5', '-0.5', '1234567', '0'] + cursor.execute("create table t1(n int, col numeric(20,2))") + for i, v in enumerate(values): + cursor.execute(f"insert into t1 values ({i}, {v})") + results = [row.col for row in cursor.execute("select col from t1 order by n")] + assert results == [Decimal(v) for v in values] + + +def test_numeric_read_comma_locale_nan(cursor: pyodbc.Cursor, comma_locale): + # The locale must not break the special values. + cursor.execute("create table t1(col numeric)") + cursor.execute("insert into t1 values ('NaN')") + assert cursor.execute("select col from t1").fetchval().is_nan() + + +def test_numeric_write_comma_locale(cursor: pyodbc.Cursor, comma_locale): + # Writes are not affected by the locale; this guards against a fix that changes that. + cursor.execute("create table t1(col numeric(20,2))") + cursor.execute("insert into t1 values (?)", Decimal('3656.88')) + # A separate cursor, to stay clear of test_fast_executemany_decimal_scale_after_reuse. + fast = cursor.connection.cursor() + fast.fast_executemany = True + fast.executemany("insert into t1 values (?)", [(Decimal('-1234.5'),)]) + results = [row[0] for row in cursor.execute("select col::text from t1 order by 1")] + assert results == ['-1234.50', '3656.88'] + + +@pytest.mark.parametrize('mode', ['default', 'text']) +def test_numeric_read_separator_mismatch(cursor: pyodbc.Cursor, mode): + # The driver sends '3656.88' but pyodbc's separator is ',' (the shape of #753), so 5.4.0's + # text path strips the '.' and reads 365688. + _set_decimal_mode(cursor.connection, mode) + saved = pyodbc.getDecimalSeparator() + pyodbc.setDecimalSeparator(',') + try: + result = cursor.execute("select 3656.88::numeric(10,2)").fetchval() + finally: + pyodbc.setDecimalSeparator(saved) + assert result == Decimal('3656.88') + + +@pytest.mark.parametrize('value', SPECIAL_VALUES) +def test_numeric_special_values_write(cursor: pyodbc.Cursor, value): + # 5.4.0 raises SystemError after inserting 0. + _skip_without_numeric_infinity(cursor, value) + cursor.execute("create table t1(col numeric)") + cursor.execute("insert into t1 values (?)", Decimal(value)) + assert cursor.execute("select col::text from t1").fetchval() == value + + +def test_numeric_snan_write_rejected(cursor: pyodbc.Cursor): + # No database stores a signaling NaN. + cursor.execute("create table t1(col numeric)") + with pytest.raises(pyodbc.ProgrammingError): + cursor.execute("insert into t1 values (?)", Decimal('sNaN')) + + +@pytest.mark.parametrize('value', SPECIAL_VALUES) +def test_numeric_special_values_fast_executemany_rejected(cursor: pyodbc.Cursor, value): + # A SQL_NUMERIC_STRUCT cannot hold these, so fast_executemany raises instead of writing 0. + cursor.execute("create table t1(col numeric)") + cursor.fast_executemany = True + with pytest.raises(pyodbc.ProgrammingError): + cursor.executemany("insert into t1 values (?)", [(Decimal(value),)]) + assert cursor.execute("select count(*) from t1").fetchval() == 0 + + @pytest.mark.parametrize('first', ['execute', 'fast_executemany']) def test_fast_executemany_decimal_scale_after_reuse(cursor: pyodbc.Cursor, first): # psqlODBC does not support SQLDescribeParam. 5.4.0 reuses the scale guessed from an @@ -736,6 +900,36 @@ def test_fast_executemany_decimal_scale_from_values(cursor: pyodbc.Cursor): assert results == [None if v is None else Decimal(v) for v in values] +def _decimal_samples(precision: int, scale: int) -> list[str]: + "Random values that fit decimal(precision, scale), plus zero and the extremes" + rnd = random.Random(precision * 100 + scale) + values = ['0', '9' * (precision - scale) + ('.' + '9' * scale if scale else '') + if precision > scale else '0.' + '9' * scale] + for _ in range(50): + digits = ''.join(rnd.choice('0123456789') for _ in range(rnd.randint(1, precision))) + whole = digits[:max(0, len(digits) - scale)] or '0' + frac = digits[max(0, len(digits) - scale):].rjust(scale, '0') if scale else '' + values.append(rnd.choice(['', '-']) + whole + ('.' + frac if scale else '')) + return values + + +DECIMAL_SHAPES = [(38, 0), (38, 10), (38, 38), (18, 2), (10, 9), (5, 0), (1, 0), (1, 1)] + + +@pytest.mark.parametrize("precision, scale", DECIMAL_SHAPES) +def test_decimal_binary_and_text_identical(cursor: pyodbc.Cursor, precision, scale): + "Binary and text reads give identical Decimals, including the exponent" + values = _decimal_samples(precision, scale) + rows = ', '.join(f"({i}, '{s}')" for i, s in enumerate(values)) + sql = f"select v::numeric({precision}, {scale}) from (values {rows}) t(n, v) order by n" + results = {} + for mode in ('binary', 'text'): + cursor.connection.decimal_mode = mode + results[mode] = [row[0] for row in cursor.execute(sql)] + assert [d.as_tuple() for d in results['binary']] == [d.as_tuple() for d in results['text']] + assert results['text'] == [Decimal(s) for s in values] + + def _fast_executemany_numeric(cursor: pyodbc.Cursor, values, column="numeric"): "Inserts values with fast_executemany and returns them read back in order" cursor.execute(f"create table t1(n int, v {column})") @@ -813,3 +1007,19 @@ def test_fast_executemany_decimal_and_str(cursor: pyodbc.Cursor): results = _fast_executemany_numeric(cursor, values, column="text") assert results == ['x' * 60, '15', 'y' * 60] + +def test_fetch_decimal_as_string_round_trip(cursor: pyodbc.Cursor): + "Saving and restoring the deprecated attribute does not change the mode" + cnxn = cursor.connection + assert cnxn.decimal_mode == 'text' + with pytest.warns(FutureWarning): + saved = cnxn.fetch_decimal_as_string + with pytest.warns(FutureWarning): + cnxn.fetch_decimal_as_string = saved + assert cnxn.decimal_mode == 'text' + with pytest.warns(FutureWarning): + cnxn.fetch_decimal_as_string = False + assert cnxn.decimal_mode == 'binary' + with pytest.warns(FutureWarning): + cnxn.fetch_decimal_as_string = True + assert cnxn.decimal_mode == 'locale' diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 9801dcc3..9e2b44bf 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -922,3 +922,51 @@ def test_fetch_after_column_name_decode_error(cnxn: pyodbc.Connection): assert cursor.description is None with pytest.raises(pyodbc.ProgrammingError): cursor.fetchone() + + +def test_decimal_mode(cursor: pyodbc.Cursor): + cnxn = cursor.connection + assert cnxn.decimal_mode == 'binary' + for mode in ('text', 'locale', 'binary'): + cnxn.decimal_mode = mode + assert cnxn.decimal_mode == mode + with pytest.raises(ValueError): + cnxn.decimal_mode = 'strict' + with pytest.raises(TypeError): + cnxn.decimal_mode = 1 + with pytest.raises(TypeError): + del cnxn.decimal_mode + assert cnxn.decimal_mode == 'binary' + + +@pytest.mark.parametrize('attr', ['decimal_mode', 'fetch_decimal_as_string']) +def test_decimal_mode_bool_deprecated(cursor: pyodbc.Cursor, attr): + # The bool values select the paths fetch_decimal_as_string selected before 5.5. + cnxn = cursor.connection + with pytest.warns(FutureWarning, match=attr): + setattr(cnxn, attr, True) + assert cnxn.decimal_mode == 'locale' + with pytest.warns(FutureWarning, match=attr): + setattr(cnxn, attr, False) + assert cnxn.decimal_mode == 'binary' + + +def test_fetch_decimal_as_string_read_deprecated(cursor: pyodbc.Cursor): + cnxn = cursor.connection + for mode, expected in [('binary', False), ('text', True), ('locale', True)]: + cnxn.decimal_mode = mode + with pytest.warns(FutureWarning, match='fetch_decimal_as_string'): + assert cnxn.fetch_decimal_as_string is expected + + +def test_decimal_mode_bool_warning_as_error(cursor: pyodbc.Cursor): + # An exception raised by the warnings filter propagates and leaves the mode unchanged. + import warnings + cnxn = cursor.connection + with warnings.catch_warnings(): + warnings.simplefilter('error', FutureWarning) + with pytest.raises(FutureWarning): + cnxn.fetch_decimal_as_string = True + with pytest.raises(FutureWarning): + cnxn.fetch_decimal_as_string + assert cnxn.decimal_mode == 'binary' diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index 0f8d53f4..6ee1c124 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -5,6 +5,7 @@ import decimal import gc import os +import random import re import uuid from collections.abc import Iterator @@ -402,13 +403,13 @@ def test_bit(cursor: pyodbc.Cursor): def test_decimal(cursor: pyodbc.Cursor): # From test provided by planders (thanks!) in Issue 91 - for mode in (True, False): + for mode in ('binary', 'text', 'locale'): for (precision, scale, negative) in [ (1, 0, False), (1, 0, True), (6, 0, False), (6, 2, False), (6, 4, True), (6, 6, True), (38, 0, False), (38, 10, False), (38, 38, False), (38, 0, True), (38, 10, True), (38, 38, True)]: - cursor.connection.fetch_decimal_as_string = mode + cursor.connection.decimal_mode = mode try: cursor.execute("drop table t1") except Exception: @@ -448,13 +449,31 @@ def test_decimal_fast_executemany_huge_exponent(cursor: pyodbc.Cursor): cursor.executemany("insert into t1 values (?)", [(value,)]) +@pytest.mark.parametrize("value", ["NaN", "Infinity", "-Infinity"]) +def test_decimal_special_values_rejected(cursor: pyodbc.Cursor, value): + # pyodbc sends NaN and Infinity as text, for databases that store them, and SQL Server + # rejects them. + cursor.execute("create table t1(v decimal(18, 2))") + with pytest.raises(pyodbc.DataError): + cursor.execute("insert into t1 values (?)", Decimal(value)) + assert cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.parametrize("value", ["NaN", "Infinity", "-Infinity"]) +def test_decimal_special_values_fast_executemany_rejected(cursor: pyodbc.Cursor, value): + # A SQL_NUMERIC_STRUCT cannot hold these. + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = True + with pytest.raises(pyodbc.ProgrammingError, match="fast_executemany"): + cursor.executemany("insert into t1 values (?)", [(Decimal(value),)]) + + @pytest.mark.parametrize("fast", [False, True]) -@pytest.mark.parametrize("value", ["NaN", "sNaN", "Infinity", "-Infinity"]) -def test_decimal_special_values_rejected(cursor: pyodbc.Cursor, fast, value): +def test_decimal_snan_rejected(cursor: pyodbc.Cursor, fast): cursor.execute("create table t1(v decimal(18, 2))") cursor.fast_executemany = fast - with pytest.raises(pyodbc.ProgrammingError, match="NaN or Infinity"): - cursor.executemany("insert into t1 values (?)", [(Decimal(value),)]) + with pytest.raises(pyodbc.ProgrammingError, match="signaling NaN"): + cursor.executemany("insert into t1 values (?)", [(Decimal("sNaN"),)]) def test_fast_executemany_cursor_usable_after_dae_error(cursor: pyodbc.Cursor): @@ -2175,3 +2194,38 @@ def test_tvp_row_changes_size(cursor: pyodbc.Cursor, tvp_binary_proc: str): "A row whose length changes after binding raises instead of overrunning the bindings" with pytest.raises(pyodbc.ProgrammingError, match="same size"): cursor.execute(tvp_binary_proc, ([_ShapeShiftingRow()],)) + + +def test_decimal_mode_default(cursor: pyodbc.Cursor): + assert cursor.connection.decimal_mode == 'binary' + + +def _decimal_samples(precision: int, scale: int) -> list[str]: + "Random values that fit decimal(precision, scale), plus zero and the extremes" + rnd = random.Random(precision * 100 + scale) + values = ['0', '9' * (precision - scale) + ('.' + '9' * scale if scale else '') + if precision > scale else '0.' + '9' * scale] + for _ in range(50): + digits = ''.join(rnd.choice('0123456789') for _ in range(rnd.randint(1, precision))) + whole = digits[:max(0, len(digits) - scale)] or '0' + frac = digits[max(0, len(digits) - scale):].rjust(scale, '0') if scale else '' + values.append(rnd.choice(['', '-']) + whole + ('.' + frac if scale else '')) + return values + + +DECIMAL_SHAPES = [(38, 0), (38, 10), (38, 38), (18, 2), (10, 9), (5, 0), (1, 0), (1, 1)] + + +@pytest.mark.parametrize("precision, scale", DECIMAL_SHAPES) +def test_decimal_binary_and_text_identical(cursor: pyodbc.Cursor, precision, scale): + "Binary and text reads give identical Decimals, including the exponent" + values = _decimal_samples(precision, scale) + rows = ', '.join(f"({i}, cast('{s}' as decimal({precision}, {scale})))" + for i, s in enumerate(values)) + sql = f"select v from (values {rows}) t(n, v) order by n" + results = {} + for mode in ('binary', 'text'): + cursor.connection.decimal_mode = mode + results[mode] = [row[0] for row in cursor.execute(sql)] + assert [d.as_tuple() for d in results['binary']] == [d.as_tuple() for d in results['text']] + assert results['text'] == [Decimal(s) for s in values] From aecc0ac5b758b11ad2a9d2124e27a7c1bcc46d5e Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:14:40 -0600 Subject: [PATCH 10/22] getdata: bound ReadVarColumn buffers, fix the GUID length type, and stop variant recursion - ReadVarColumn: with readvar_initsize smaller than one character plus the terminator (1, for any NVARCHAR), the first read computed a length of -1 and the next SQLGetData wrote before the buffer. An odd size split UTF-16 characters, and msodbcsql looped forever on readvar_initsize = 1. Make the buffer at least one element plus the terminator, and a whole number of elements. - ReadVarColumn: don't trust a length the driver reports beyond the space offered, and don't subtract the terminator from a final length that never included it. - The GUID path passed an int for Py_BuildValue's "y#", which reads a Py_ssize_t. - A driver reporting sql_variant as the underlying type of a sql_variant recursed without limit. Raise instead. --- src/getdata.cpp | 24 ++++++++++++++++++++---- tests/sqlite_test.py | 13 +++++++++++++ tests/sqlserver_test.py | 13 +++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/getdata.cpp b/src/getdata.cpp index 8b0010ac..c95fd5f4 100644 --- a/src/getdata.cpp +++ b/src/getdata.cpp @@ -119,6 +119,13 @@ static bool ReadVarColumn(Cursor* cur, Py_ssize_t iCol, SQLSMALLINT ctype, bool& cbAllocated = initsize; } + // The buffer must hold at least one element plus the terminator, and a whole number of + // elements. Otherwise the first read leaves no room, and the loop below computes a + // negative length and has the driver write before the buffer. + if (cbAllocated < cbElement + cbNullTerminator) + cbAllocated = cbElement + cbNullTerminator; + cbAllocated += (cbElement - cbAllocated % cbElement) % cbElement; + Py_ssize_t cbUsed = 0; byte* pb = (byte*)PyMem_Malloc((size_t)cbAllocated); if (!pb) @@ -197,8 +204,8 @@ static bool ReadVarColumn(Cursor* cur, Py_ssize_t iCol, SQLSMALLINT ctype, bool& else { // I would not expect to get here - we apparently read all of the data but the - // driver did not return SQL_SUCCESS? - cbRead = (cbData - cbNullTerminator); + // driver did not return SQL_SUCCESS? cbData does not include the terminator. + cbRead = cbData < 0 ? 0 : (Py_ssize_t)cbData; cbRemaining = 0; } @@ -225,8 +232,12 @@ static bool ReadVarColumn(Cursor* cur, Py_ssize_t iCol, SQLSMALLINT ctype, bool& // // If I'm reading the documentation correctly, SQLGetData is not going to // include the null terminator in cbRead. + // + // A driver should not report more than it was offered, but don't trust it: the + // length is used to read the buffer. - cbUsed += cbData; + Py_ssize_t cbMax = cbAvailable - cbNullTerminator; + cbUsed += (Py_ssize_t)cbData > cbMax ? cbMax : (Py_ssize_t)cbData; } } while (ret == SQL_SUCCESS_WITH_INFO); @@ -621,7 +632,7 @@ static PyObject* GetUUID(Cursor* cur, Py_ssize_t iCol) Py_RETURN_NONE; const char* szFmt = "(yyy#)"; - Object args(Py_BuildValue(szFmt, NULL, NULL, &guid, (int)sizeof(guid))); + Object args(Py_BuildValue(szFmt, NULL, NULL, &guid, (Py_ssize_t)sizeof(guid))); // y# takes a Py_ssize_t if (!args) return 0; @@ -918,6 +929,11 @@ PyObject *GetData_SqlVariant(Cursor *cur, Py_ssize_t iCol) { if (!SQL_SUCCEEDED(retcode)) return RaiseErrorFromHandle(cur->cnxn, "SQLColAttribute", cur->cnxn->hdbc, cur->hstmt); + // A driver reporting a variant inside a variant would recurse without limit. + if (variantType == SQL_SS_VARIANT) + return RaiseErrorV("HY106", ProgrammingError, + "The driver reported sql_variant as the underlying type of a sql_variant value. column-index=%zd", iCol); + // Replace the original SQL_VARIANT data type with the underlying data type then call GetData() again cur->colinfos[iCol].sql_type = static_cast(variantType); decodeResult = GetData(cur, iCol); diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 9e2b44bf..e7a42156 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -970,3 +970,16 @@ def test_decimal_mode_bool_warning_as_error(cursor: pyodbc.Cursor): with pytest.raises(FutureWarning): cnxn.fetch_decimal_as_string assert cnxn.decimal_mode == 'binary' + + +@pytest.mark.parametrize("initsize", [1, 2, 3, 5]) +def test_readvar_initsize_tiny(cursor: pyodbc.Cursor, initsize): + # A buffer smaller than one character plus the terminator made the driver write before the + # buffer, and an odd size split UTF-16 characters. + cursor.execute("create table t1(n varchar(100), b blob)") + values = [("abcdéfghij", b"0123456789"), ("x", b"x"), ("", b"")] + for value in values: + cursor.execute("insert into t1 values (?, ?)", *value) + cursor.connection.readvar_initsize = initsize + rows = cursor.execute("select n, b from t1 order by length(n) desc").fetchall() + assert [tuple(row) for row in rows] == values diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index 6ee1c124..97baa7bb 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -2200,6 +2200,19 @@ def test_decimal_mode_default(cursor: pyodbc.Cursor): assert cursor.connection.decimal_mode == 'binary' +@pytest.mark.parametrize("initsize", [1, 2, 3, 5]) +def test_readvar_initsize_tiny(cursor: pyodbc.Cursor, initsize): + # A buffer smaller than one character plus the terminator made the driver write before the + # buffer, and an odd size split UTF-16 characters. + cursor.execute("create table t1(n nvarchar(max), v varchar(max), b varbinary(max))") + values = [("abcdéfghij", "abcdefghij", b"0123456789"), ("x", "x", b"x"), ("", "", b"")] + for value in values: + cursor.execute("insert into t1 values (?, ?, ?)", *value) + cursor.connection.readvar_initsize = initsize + rows = cursor.execute("select n, v, b from t1 order by len(v) desc").fetchall() + assert [tuple(row) for row in rows] == values + + def _decimal_samples(precision: int, scale: int) -> list[str]: "Random values that fit decimal(precision, scale), plus zero and the extremes" rnd = random.Random(precision * 100 + scale) From 5d7e348b77c0a8b29dca0cedb57ed9b1f4775983 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:16:10 -0600 Subject: [PATCH 11/22] Terminate and bound the names passed to catalog functions - SQLWChar returned PyUnicode_AsUTF8 directly for UTF-8. The buffer goes to W APIs with SQL_NTS, but that string ends in one NUL byte, not a NUL SQLWCHAR, so with setdecoding(SQL_WMETADATA, encoding='utf-8') the driver read past the end of the name. Use the general path, which appends four NULs. - The general path cleared encoding errors, so a name that could not be encoded (a lone surrogate) gave "SystemError: returned NULL without setting an exception". Leave the error set, raise TypeError for an encoding that does not return bytes, and handle a failed allocation. set_attr no longer needs to encode twice to get the error. - tablePrivileges and statistics cast the UTF-16 name length to SQLSMALLINT. Longer names wrapped, and a name of exactly 65533 characters became SQL_NTS, so the driver read past the end looking for a terminator. Raise ValueError for names over 32767 characters. --- src/connection.cpp | 6 +----- src/cursor.cpp | 40 ++++++++++++++++++++++++++++------------ src/textenc.cpp | 26 +++++++++++++++----------- tests/sqlite_test.py | 25 +++++++++++++++++++++++++ 4 files changed, 69 insertions(+), 28 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index c85bcd2a..461e1fcc 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -490,13 +490,9 @@ static PyObject* Connection_set_attr(PyObject* self, PyObject* args) } else if (PyUnicode_Check(value)) { - // SQLWChar clears encoding errors and leaves a NULL buffer, so check first to raise them. - Object check(PyUnicode_AsEncodedString(value, "utf-16le", "strict")); - if (!check) - return 0; sqlchar.set(value, "utf-16le"); if (!sqlchar.isValid()) - return PyErr_NoMemory(); + return 0; Py_BEGIN_ALLOW_THREADS ret = SQLSetConnectAttrW(cnxn->hdbc, id, sqlchar.get(), SQL_NTS); Py_END_ALLOW_THREADS diff --git a/src/cursor.cpp b/src/cursor.cpp index 38350a10..50c9acaa 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -1605,6 +1605,22 @@ static char tablePrivileges_doc[] = " 6) is_grantable"; +static bool GetWideNameLength(PyObject* bytes, SQLSMALLINT& cch) +{ + // Sets `cch` to the length in characters of a UTF-16 catalog function argument. The + // length is a SQLSMALLINT, so a longer name would wrap, and one of exactly 65533 characters + // would become SQL_NTS, making the driver read past the end looking for a terminator. + + Py_ssize_t cchName = PyBytes_GET_SIZE(bytes) / (Py_ssize_t)sizeof(uint16_t); + if (cchName > SHRT_MAX) + { + PyErr_SetString(PyExc_ValueError, "Catalog function names cannot be longer than 32767 characters"); + return false; + } + cch = (SQLSMALLINT)cchName; + return true; +} + static PyObject* Cursor_tablePrivileges(PyObject* self, PyObject* args, PyObject* kwargs) { PyObject* pCatalog = 0; @@ -1653,24 +1669,24 @@ static PyObject* Cursor_tablePrivileges(PyObject* self, PyObject* args, PyObject if (oTable) { szTable = PyBytes_AS_STRING(oTable.Get()); - if (isWide) - cchTable = (SQLSMALLINT)(PyBytes_GET_SIZE(oTable.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oTable.Get(), cchTable)) + return 0; } char* szCatalog = 0; SQLSMALLINT cchCatalog = SQL_NTS; if (oCatalog) { szCatalog = PyBytes_AS_STRING(oCatalog.Get()); - if (isWide) - cchCatalog = (SQLSMALLINT)(PyBytes_GET_SIZE(oCatalog.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oCatalog.Get(), cchCatalog)) + return 0; } char* szSchema = 0; SQLSMALLINT cchSchema = SQL_NTS; if (oSchema) { szSchema = PyBytes_AS_STRING(oSchema.Get()); - if (isWide) - cchSchema = (SQLSMALLINT)(PyBytes_GET_SIZE(oSchema.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oSchema.Get(), cchSchema)) + return 0; } Py_BEGIN_ALLOW_THREADS @@ -1873,24 +1889,24 @@ static PyObject* Cursor_statistics(PyObject* self, PyObject* args, PyObject* kwa if (oTable) { szTable = PyBytes_AS_STRING(oTable.Get()); - if (isWide) - cchTable = (SQLSMALLINT)(PyBytes_GET_SIZE(oTable.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oTable.Get(), cchTable)) + return 0; } char* szCatalog = 0; SQLSMALLINT cchCatalog = SQL_NTS; if (oCatalog) { szCatalog = PyBytes_AS_STRING(oCatalog.Get()); - if (isWide) - cchCatalog = (SQLSMALLINT)(PyBytes_GET_SIZE(oCatalog.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oCatalog.Get(), cchCatalog)) + return 0; } char* szSchema = 0; SQLSMALLINT cchSchema = SQL_NTS; if (oSchema) { szSchema = PyBytes_AS_STRING(oSchema.Get()); - if (isWide) - cchSchema = (SQLSMALLINT)(PyBytes_GET_SIZE(oSchema.Get()) / sizeof(uint16_t)); + if (isWide && !GetWideNameLength(oSchema.Get(), cchSchema)) + return 0; } SQLRETURN ret = 0; diff --git a/src/textenc.cpp b/src/textenc.cpp index 725265f0..2a9faef9 100644 --- a/src/textenc.cpp +++ b/src/textenc.cpp @@ -20,12 +20,9 @@ void SQLWChar::init(PyObject* src, const TextEnc& enc) isNone = false; - // If there are optimized encodings that don't require a temporary object, use them. - if (enc.optenc == OPTENC_UTF8 && PyUnicode_Check(src)) - { - psz = (SQLWCHAR*)PyUnicode_AsUTF8(src); - return; - } + // There is deliberately no shortcut returning PyUnicode_AsUTF8 for UTF-8: these buffers go + // to the W APIs with SQL_NTS, and that string ends in one NUL byte, not the NUL character + // the driver looks for. The bytes below end in four NULs, enough for any SQLWCHAR size. PyObject* pb = 0; @@ -37,14 +34,22 @@ void SQLWChar::init(PyObject* src, const TextEnc& enc) // Careful: Some encodings don't return bytes. if (!PyBytes_Check(pb)) { - // REVIEW: Error or just return null? + PyErr_Format(PyExc_TypeError, "Encoding '%s' did not return bytes", enc.name); psz = 0; Py_DECREF(pb); return; } - if(!nulls) + if (!nulls) + { nulls = PyBytes_FromStringAndSize("\0\0\0\0", 4); + if (!nulls) + { + psz = 0; + Py_DECREF(pb); + return; + } + } PyBytes_Concat(&pb, nulls); if (!pb) @@ -53,9 +58,8 @@ void SQLWChar::init(PyObject* src, const TextEnc& enc) return; } } else { - // If the encoding failed (possibly due to "strict"), it will generate an exception, but - // we're going to continue. - PyErr_Clear(); + // The encoding failed, so leave its exception set. Callers check isValid() and + // return. psz = 0; } diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index e7a42156..5b7aa556 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -983,3 +983,28 @@ def test_readvar_initsize_tiny(cursor: pyodbc.Cursor, initsize): cursor.connection.readvar_initsize = initsize rows = cursor.execute("select n, b from t1 order by length(n) desc").fetchall() assert [tuple(row) for row in rows] == values + + +@pytest.mark.parametrize("method", ["tablePrivileges", "statistics"]) +@pytest.mark.parametrize("length", [32768, 65533, 70000]) +def test_catalog_name_too_long(cursor: pyodbc.Cursor, method, length): + # The length is a SQLSMALLINT. 65533 characters used to become SQL_NTS, so the driver read + # past the end of the name looking for a terminator. + with pytest.raises(ValueError): + getattr(cursor, method)("x" * length) + + +def test_catalog_utf8_metadata(cursor: pyodbc.Cursor): + # Catalog arguments encoded as UTF-8 for a W API used to end in a single NUL byte. + cursor.connection.setdecoding(pyodbc.SQL_WMETADATA, encoding='utf-8') + for name in ("t", "t1", "t12"): + assert isinstance(cursor.columns(table=name).fetchall(), list) + + +@pytest.mark.parametrize("encoding", ["utf-8", "utf-16le"]) +def test_catalog_unencodable_name(cursor: pyodbc.Cursor, encoding): + "A catalog name that cannot be encoded raises the encoding error, not SystemError" + cursor.connection.setdecoding(pyodbc.SQL_WMETADATA, encoding=encoding) + with pytest.raises(UnicodeEncodeError): + cursor.columns(table="t\ud800") + From 980655d8862db4a1c4b5b8eb56bc73402102fc59 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:17:00 -0600 Subject: [PATCH 12/22] decimal: fix a dangling separator reference and escape the separator in the regex - InitializeDecimal wrapped the borrowed decimal_point from localeconv() in an Object, which released it. "." and "," are cached singletons, but with a locale whose decimal point is not Latin-1 (fa_IR, for example) the separator was freed while still in use. The imports and localeconv() result were not checked for NULL either. - SetDecimalPoint put the separator into a character class unescaped, so "]" or "-" changed the class and setDecimalSeparator("z-a") raised after the separator had been replaced. Escape it, and build everything before replacing any global. --- src/decimal.cpp | 64 +++++++++++++++++++++++++------------------- tests/sqlite_test.py | 12 +++++++++ 2 files changed, 49 insertions(+), 27 deletions(-) diff --git a/src/decimal.cpp b/src/decimal.cpp index 4b4b10c3..e78736c7 100644 --- a/src/decimal.cpp +++ b/src/decimal.cpp @@ -38,20 +38,35 @@ bool InitializeDecimal() { // This is called when the module is initialized and creates globals. Object d(PyImport_ImportModule("decimal")); + if (!d) + return false; decimal = PyObject_GetAttrString(d, "Decimal"); if (!decimal) - return 0; + return false; + Object re(PyImport_ImportModule("re")); + if (!re) + return false; re_sub = PyObject_GetAttrString(re, "sub"); re_escape = PyObject_GetAttrString(re, "escape"); re_compile = PyObject_GetAttrString(re, "compile"); + if (!re_sub || !re_escape || !re_compile) + return false; Object module(PyImport_ImportModule("locale")); + if (!module) + return false; Object ldict(PyObject_CallMethod(module, "localeconv", 0)); - Object point(PyDict_GetItemString(ldict, "decimal_point")); + if (!ldict) + return false; + // A borrowed reference, so it is not wrapped in an Object. + PyObject* point = PyDict_GetItemString(ldict, "decimal_point"); if (!point) + { + PyErr_SetString(PyExc_RuntimeError, "locale.localeconv() has no decimal_point"); return false; + } pDecimalPoint = PyUnicode_FromString("."); @@ -71,34 +86,20 @@ PyObject* GetDecimalPoint() { bool SetDecimalPoint(PyObject* pNew) { - if (PyObject_RichCompareBool(pNew, pDecimalPoint, Py_EQ) == 1) - { - // They are the same. - Py_XDECREF(pLocaleDecimal); - pLocaleDecimal = pDecimalPoint; - Py_INCREF(pLocaleDecimal); + // Everything is built before any global is replaced, so a failure leaves the previous + // separator in effect. - Py_XDECREF(pLocaleDecimalEscaped); - pLocaleDecimalEscaped = 0; - } - else - { - // They are different, so we'll need a regular expression to match it so it can be - // replaced in getdata GetDataDecimal. - - Py_XDECREF(pLocaleDecimal); - pLocaleDecimal = pNew; - Py_INCREF(pLocaleDecimal); - - Object e(PyObject_CallFunctionObjArgs(re_escape, pNew, 0)); - if (!e) - return false; + bool isPoint = PyObject_RichCompareBool(pNew, pDecimalPoint, Py_EQ) == 1; + if (PyErr_Occurred()) + return false; - Py_XDECREF(pLocaleDecimalEscaped); - pLocaleDecimalEscaped = e.Detach(); - } + // The separator is escaped for use in a regular expression, both to replace it and inside + // the character class of characters to keep ("]" or "-" would otherwise change the class). + Object escaped(PyObject_CallFunctionObjArgs(re_escape, pNew, 0)); + if (!escaped) + return false; - Object s(PyUnicode_FromFormat("[^0-9%U-]+", pLocaleDecimal)); + Object s(PyUnicode_FromFormat("[^0-9%U-]+", escaped.Get())); if (!s) return false; @@ -106,6 +107,15 @@ bool SetDecimalPoint(PyObject* pNew) if (!r) return false; + Py_INCREF(pNew); + Py_XDECREF(pLocaleDecimal); + pLocaleDecimal = pNew; + + // pLocaleDecimalEscaped is zero when the separator is ".", meaning no replacement is + // needed in DecimalFromUnicode. + Py_XDECREF(pLocaleDecimalEscaped); + pLocaleDecimalEscaped = isPoint ? 0 : escaped.Detach(); + Py_XDECREF(pRegExpRemove); pRegExpRemove = r.Detach(); diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 5b7aa556..2694cf5c 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -1008,3 +1008,15 @@ def test_catalog_unencodable_name(cursor: pyodbc.Cursor, encoding): with pytest.raises(UnicodeEncodeError): cursor.columns(table="t\ud800") + +@pytest.mark.parametrize("sep", ["]", "z-a", "\\", "^"]) +def test_set_decimal_separator_regex_characters(sep): + # The separator was put into a regular expression character class unescaped, so "]" broke + # number cleaning and "z-a" raised after the separator had already been replaced. + saved = pyodbc.getDecimalSeparator() + try: + pyodbc.setDecimalSeparator(sep) + assert pyodbc.getDecimalSeparator() == sep + finally: + pyodbc.setDecimalSeparator(saved) + assert pyodbc.getDecimalSeparator() == saved From 5bc7288930636b22a8d9971b22a03c6dd9028d48 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:18:47 -0600 Subject: [PATCH 13/22] Bound the diagnostic record buffers and lengths GetErrorFromHandle and GetDiagRecs (Cursor.messages) read diagnostic records with SQLGetDiagRecW: - The length returned by the retry with a larger buffer was not checked again, so a driver reporting more than it was offered made the decode read past the buffer. Clamp it. - The new buffer size, a SQLSMALLINT, was computed as length + 1 and wrapped at 32767. - The SQLSTATE and message buffers were sized for a 2-byte SQLWCHAR. pyodbc expects UTF-16, but give them room for a 4-byte one so a driver manager using it cannot write past them. - A message that could not be decoded left its exception set. --- src/cursor.cpp | 23 ++++++++++++++++------- src/errors.cpp | 23 +++++++++++++++++------ tests/sqlserver_test.py | 12 ++++++++++++ 3 files changed, 45 insertions(+), 13 deletions(-) diff --git a/src/cursor.cpp b/src/cursor.cpp index 50c9acaa..05c14fcc 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -644,10 +644,12 @@ int GetDiagRecs(Cursor* cur) PyObject* msg_list; // the "messages" as a Python list of diagnostic records SQLSMALLINT iRecNumber = 1; // the index of the diagnostic records (1-based) - uint16_t cSQLState[6]; // five-character SQLSTATE code (plus terminating NULL) + // The data is UTF-16, but the buffers have room for a 4-byte SQLWCHAR so that a driver + // manager using one cannot write past them. + uint16_t cSQLState[12]; // five-character SQLSTATE code (plus terminating NULL) SQLINTEGER iNativeError; SQLSMALLINT iMessageLen = 1023; - uint16_t *cMessageText = (uint16_t*) PyMem_Malloc((iMessageLen + 1) * sizeof(uint16_t)); + uint16_t *cMessageText = (uint16_t*) PyMem_Malloc((iMessageLen + 1) * sizeof(uint32_t)); SQLSMALLINT iTextLength; SQLRETURN ret; @@ -685,10 +687,11 @@ int GetDiagRecs(Cursor* cur) if (text_length_in_bytes) iTextLength /= sizeof(uint16_t); - // If needed, allocate a bigger error message buffer and retry. - if (iTextLength > iMessageLen - 1) { - iMessageLen = iTextLength + 1; - if (!PyMem_Realloc((BYTE**) &cMessageText, (iMessageLen + 1) * sizeof(uint16_t))) { + // If needed, allocate a bigger error message buffer and retry. The length is a + // SQLSMALLINT, so the longest message that can be read is SHRT_MAX - 1 characters. + if (iTextLength > iMessageLen - 1 && iMessageLen < SHRT_MAX) { + iMessageLen = iTextLength < SHRT_MAX ? (SQLSMALLINT)(iTextLength + 1) : (SQLSMALLINT)SHRT_MAX; + if (!PyMem_Realloc((BYTE**) &cMessageText, (iMessageLen + 1) * sizeof(uint32_t))) { PyMem_Free(cMessageText); PyErr_NoMemory(); return 0; @@ -705,6 +708,12 @@ int GetDiagRecs(Cursor* cur) iTextLength /= sizeof(uint16_t); } + // Don't trust the length beyond the buffer offered: the message is read using it. + if (iTextLength < 0) + iTextLength = 0; + if (iTextLength > iMessageLen - 1) + iTextLength = iMessageLen - 1; + cSQLState[5] = 0; // Not always NULL terminated (MS Access) CopySqlState(cSQLState, sqlstate_ascii); PyObject* msg_class = PyUnicode_FromFormat("[%s] (%ld)", sqlstate_ascii, (long)iNativeError); @@ -717,7 +726,7 @@ int GetDiagRecs(Cursor* cur) if (!msg_value) { // If the char cannot be decoded, return something rather than nothing. - Py_XDECREF(msg_value); + PyErr_Clear(); msg_value = PyBytes_FromStringAndSize((char*)cMessageText, iTextLength * sizeof(uint16_t)); } diff --git a/src/errors.cpp b/src/errors.cpp index 9116161a..c6ba8078 100644 --- a/src/errors.cpp +++ b/src/errors.cpp @@ -202,9 +202,11 @@ PyObject* GetErrorFromHandle(Connection *conn, const char* szFunction, HDBC hdbc SQLINTEGER nNativeError; SQLSMALLINT cchMsg; - uint16_t sqlstateT[6]; + // The data is UTF-16, but the buffers have room for a 4-byte SQLWCHAR so that a driver + // manager using one cannot write past them. + uint16_t sqlstateT[12]; SQLSMALLINT msgLen = 1023; - uint16_t *szMsg = (uint16_t*) PyMem_Malloc((msgLen + 1) * sizeof(uint16_t)); + uint16_t *szMsg = (uint16_t*) PyMem_Malloc((msgLen + 1) * sizeof(uint32_t)); if (!szMsg) { PyErr_NoMemory(); @@ -256,10 +258,11 @@ PyObject* GetErrorFromHandle(Connection *conn, const char* szFunction, HDBC hdbc if (text_length_in_bytes) cchMsg /= sizeof(uint16_t); - // If needed, allocate a bigger error message buffer and retry. - if (cchMsg > msgLen - 1) { - msgLen = cchMsg + 1; - if (!PyMem_Realloc((BYTE**) &szMsg, (msgLen + 1) * sizeof(uint16_t))) { + // If needed, allocate a bigger error message buffer and retry. The length is a + // SQLSMALLINT, so the longest message that can be read is SHRT_MAX - 1 characters. + if (cchMsg > msgLen - 1 && msgLen < SHRT_MAX) { + msgLen = cchMsg < SHRT_MAX ? (SQLSMALLINT)(cchMsg + 1) : (SQLSMALLINT)SHRT_MAX; + if (!PyMem_Realloc((BYTE**) &szMsg, (msgLen + 1) * sizeof(uint32_t))) { PyErr_NoMemory(); PyMem_Free(szMsg); return 0; @@ -273,6 +276,12 @@ PyObject* GetErrorFromHandle(Connection *conn, const char* szFunction, HDBC hdbc cchMsg /= sizeof(uint16_t); } + // Don't trust the length beyond the buffer offered: the message is read using it. + if (cchMsg < 0) + cchMsg = 0; + if (cchMsg > msgLen - 1) + cchMsg = msgLen - 1; + // Not always NULL terminated (MS Access) sqlstateT[5] = 0; @@ -280,6 +289,8 @@ PyObject* GetErrorFromHandle(Connection *conn, const char* szFunction, HDBC hdbc // Note that this will not work if the DM is using a different wide encoding (e.g. UTF-32). const char *unicode_enc = conn ? conn->metadata_enc.name : ENCSTR_UTF16NE; Object msgStr(PyUnicode_Decode((char*)szMsg, cchMsg * sizeof(uint16_t), unicode_enc, "strict")); + if (!msgStr) + PyErr_Clear(); // the record is skipped if (cchMsg != 0 && msgStr.Get()) { diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index 97baa7bb..ab22a2ad 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -2213,6 +2213,18 @@ def test_readvar_initsize_tiny(cursor: pyodbc.Cursor, initsize): assert [tuple(row) for row in rows] == values +@pytest.mark.parametrize("length", [1022, 1023, 1024, 2000]) +def test_long_diagnostic_messages(cursor: pyodbc.Cursor, length): + # Messages longer than the initial 1023-character buffer are read again with a larger one. + text = "x" * (length - 1) + "z" + with pytest.raises(pyodbc.ProgrammingError) as info: + cursor.execute(f"raiserror('{text}', 16, 1)") + assert text in str(info.value) + + cursor.execute(f"print '{text}'") + assert any(m[1].endswith(text) for m in cursor.messages) + + def _decimal_samples(precision: int, scale: int) -> list[str]: "Random values that fit decimal(precision, scale), plus zero and the extremes" rnd = random.Random(precision * 100 + scale) From ed1efafb9e76e0b1f74b54878253b96b6c6939bb Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:27:30 -0600 Subject: [PATCH 14/22] params: snapshot bytearray parameters, validate Decimal parts, and fix length types - bytearray parameters are copied to bytes when bound, including fast_executemany data-at-execution cells, so the buffer the driver reads cannot be resized or freed by another thread while the GIL is released. - Decimal.as_tuple() results are fully checked: the sign must be 0 or 1 and the digits 0-9, since CreateDecimalString sizes its buffer from them (a subclass returning a negative sign overflowed the heap). A scale larger than 32767, which cannot be bound as a SQLSMALLINT, raises ProgrammingError, as does an exponent larger than any Decimal's, which would overflow the arithmetic on it. - String, data-at-execution, and Decimal string lengths are SQLLEN instead of being truncated through SQLINTEGER. SQL statements and TVP names too long for a SQLINTEGER raise ValueError. - Fix printf-style format specifiers for Py_ssize_t and unsigned long values in error messages. --- src/connection.cpp | 2 +- src/cursor.cpp | 12 +++- src/params.cpp | 155 +++++++++++++++++++++++++++------------- tests/sqlserver_test.py | 120 +++++++++++++++++++++++++++++++ 4 files changed, 237 insertions(+), 52 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index 461e1fcc..5364ad76 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -832,7 +832,7 @@ static PyObject* Connection_getinfo(PyObject* self, PyObject* args) } if (i == _countof(aInfoTypes)) - return RaiseErrorV(0, ProgrammingError, "Unsupported getinfo value: %d", infotype); + return RaiseErrorV(0, ProgrammingError, "Unsupported getinfo value: %lu", infotype); char szBuffer[0x1000]; SQLSMALLINT cch = 0; diff --git a/src/cursor.cpp b/src/cursor.cpp index 05c14fcc..3e10fe67 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -594,8 +594,8 @@ bool InitColumnInfo(Cursor* cursor, SQLUSMALLINT iCol, ColumnInfo* pinfo) // SQL_DESC_TYPE must be set first. descRet = SQLSetDescField(hDesc, i, SQL_DESC_TYPE, (void*)SQL_C_NUMERIC, 0) == SQL_SUCCESS && - SQLSetDescField(hDesc, i, SQL_DESC_PRECISION, (void*)precision, 0) == SQL_SUCCESS && - SQLSetDescField(hDesc, i, SQL_DESC_SCALE, (void*)scale, 0) == SQL_SUCCESS + SQLSetDescField(hDesc, i, SQL_DESC_PRECISION, (SQLPOINTER)(SQLLEN)precision, 0) == SQL_SUCCESS && + SQLSetDescField(hDesc, i, SQL_DESC_SCALE, (SQLPOINTER)(SQLLEN)scale, 0) == SQL_SUCCESS ? SQL_SUCCESS : SQL_ERROR; Py_END_ALLOW_THREADS @@ -837,7 +837,13 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski bool isWide = (penc->ctype == SQL_C_WCHAR); const char* pch = PyBytes_AS_STRING(query.Get()); - SQLINTEGER cch = (SQLINTEGER)(PyBytes_GET_SIZE(query.Get()) / (isWide ? sizeof(uint16_t) : 1)); + Py_ssize_t len = PyBytes_GET_SIZE(query.Get()) / (isWide ? sizeof(uint16_t) : 1); + if (len > INT_MAX) + { + PyErr_SetString(PyExc_ValueError, "SQL statement is too long"); + return 0; + } + SQLINTEGER cch = (SQLINTEGER)len; Py_BEGIN_ALLOW_THREADS if (isWide) diff --git a/src/params.cpp b/src/params.cpp index 84fd028e..fe926e36 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -41,6 +41,10 @@ struct DAEParam // The largest precision a SQL_NUMERIC_STRUCT is used for (SQL Server's maximum). static const int MAX_NUMERIC_PRECISION = 38; +// The largest exponent a Decimal can have (decimal.MAX_EMAX), well below the Py_ssize_t limit +// on 64-bit platforms. +static const Py_ssize_t MAX_DECIMAL_EXPONENT = (Py_ssize_t)(PY_SSIZE_T_MAX > 0x7FFFFFFF ? 999999999999999999LL : 0x3FFFFFFF); + static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject*& digits, Py_ssize_t& exp, const char** special = 0); @@ -321,11 +325,62 @@ static bool GetDecimalParts(PyObject* value, Object& parts, long& sign, PyObject return false; } - exp = PyLong_AsSsize_t(e); - if (PyErr_Occurred()) + // An exponent too large for a Py_ssize_t (which a subclass can return, and which is only 32 + // bits on 32-bit platforms) saturates, so the range checks below raise the same errors + // everywhere. + int overflow = 0; + long long llexp = PyLong_AsLongLongAndOverflow(e, &overflow); + if (llexp == -1 && PyErr_Occurred()) + return false; + if (overflow > 0 || llexp > PY_SSIZE_T_MAX) + exp = PY_SSIZE_T_MAX; + else if (overflow < 0 || llexp < PY_SSIZE_T_MIN) + exp = PY_SSIZE_T_MIN; + else + exp = (Py_ssize_t)llexp; + + // The callers size buffers from the sign and digits, so check them too. The scale is + // bound as a SQLSMALLINT. + if (sign != 0 && sign != 1) + { + PyErr_SetString(PyExc_TypeError, "Decimal.as_tuple() returned an invalid sign"); return false; + } digits = PyTuple_GET_ITEM(t, 1); + if (PyTuple_GET_SIZE(digits) == 0) + { + PyErr_SetString(PyExc_TypeError, "Decimal.as_tuple() returned no digits"); + return false; + } + for (Py_ssize_t i = 0, c = PyTuple_GET_SIZE(digits); i < c; i++) + { + PyObject* digit = PyTuple_GET_ITEM(digits, i); + long n = PyLong_Check(digit) ? PyLong_AsLong(digit) : -1; + if (n < 0 || n > 9) + { + PyErr_Clear(); + PyErr_SetString(PyExc_TypeError, "Decimal.as_tuple() returned an invalid digit"); + return false; + } + } + + if (exp > MAX_DECIMAL_EXPONENT) + { + // Larger than any Decimal's, so it can only come from a subclass, and would overflow + // the arithmetic on it. + RaiseErrorV(0, ProgrammingError, "Numeric overflow"); + return false; + } + + if (exp < -SHRT_MAX) + { + RaiseErrorV(0, ProgrammingError, + "Cannot bind a Decimal with more than %d digits after the decimal point", + SHRT_MAX); + return false; + } + return true; } @@ -479,7 +534,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI { if (len > pi->BufferLength) { - RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength); + RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %zd buffer %zd", (Py_ssize_t)len, (Py_ssize_t)pi->BufferLength); return false; } memcpy(*outbuf, PyBytes_AS_STRING(cell), len); @@ -518,7 +573,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI { if (len > pi->BufferLength) { - RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength); + RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %zd buffer %zd", (Py_ssize_t)len, (Py_ssize_t)pi->BufferLength); return false; } memcpy(*outbuf, PyBytes_AS_STRING((PyObject*)encoded), len); @@ -603,7 +658,7 @@ static int PyToCType(Cursor *cur, unsigned char **outbuf, PyObject *cell, ParamI { if (len > pi->BufferLength) { - RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %u buffer %u", len, pi->BufferLength); + RaiseErrorV(0, ProgrammingError, "String data, right truncation: length %zd buffer %zd", (Py_ssize_t)len, (Py_ssize_t)pi->BufferLength); return false; } memcpy(*outbuf, PyByteArray_AS_STRING(cell), len); @@ -867,8 +922,8 @@ static bool GetUnicodeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param { info.ParameterType = (enc.ctype == SQL_C_CHAR) ? SQL_VARCHAR : SQL_WVARCHAR; info.ParameterValuePtr = PyBytes_AS_STRING(info.pObject); - info.BufferLength = (SQLINTEGER)cb; - info.StrLen_or_Ind = (SQLINTEGER)cb; + info.BufferLength = (SQLLEN)cb; + info.StrLen_or_Ind = (SQLLEN)cb; } else { @@ -876,7 +931,7 @@ static bool GetUnicodeInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param info.ParameterType = (enc.ctype == SQL_C_CHAR) ? SQL_LONGVARCHAR : SQL_WLONGVARCHAR; info.ParameterValuePtr = &info; info.BufferLength = sizeof(ParamInfo*); - info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLINTEGER)cb) : SQL_DATA_AT_EXEC; + info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)cb) : SQL_DATA_AT_EXEC; info.maxlength = maxlength; } @@ -1194,39 +1249,8 @@ static bool GetDecimalInfo(Cursor* cur, Py_ssize_t index, PyObject* param, Param return false; info.allocated = true; - info.StrLen_or_Ind = (SQLINTEGER)strlen((char*)info.ParameterValuePtr); - - return true; -} - - -static bool GetByteArrayInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP) -{ - info.ValueType = SQL_C_BINARY; - - Py_ssize_t cb = PyByteArray_Size(param); - - SQLLEN maxlength = cur->cnxn->GetMaxLength(info.ValueType); + info.StrLen_or_Ind = (SQLLEN)strlen((char*)info.ParameterValuePtr); - if (maxlength == 0 || cb <= maxlength || isTVP) - { - info.ParameterType = SQL_VARBINARY; - info.ParameterValuePtr = (SQLPOINTER)PyByteArray_AsString(param); - info.BufferLength = (SQLINTEGER)cb; - info.ColumnSize = isTVP?0:(SQLUINTEGER)max(cb, 1); - info.StrLen_or_Ind = (SQLINTEGER)cb; - } - else - { - info.ParameterType = SQL_LONGVARBINARY; - info.ParameterValuePtr = &info; - info.BufferLength = sizeof(ParamInfo*); - info.ColumnSize = (SQLUINTEGER)cb; - info.StrLen_or_Ind = cur->cnxn->need_long_data_len ? SQL_LEN_DATA_AT_EXEC((SQLLEN)cb) : SQL_DATA_AT_EXEC; - info.pObject = param; - Py_INCREF(info.pObject); - info.maxlength = maxlength; - } return true; } @@ -1317,7 +1341,19 @@ bool GetParameterInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& return GetFloatInfo(cur, index, param, info); if (PyByteArray_Check(param)) - return GetByteArrayInfo(cur, index, param, info, isTVP); + { + // The driver reads the data with the GIL released, when another thread could resize + // the bytearray and free its buffer, so bind a snapshot. info.pObject keeps it alive + // until the parameters are freed. + Object snapshot(PyBytes_FromObject(param)); + if (!snapshot) + return false; + if (!GetBytesInfo(cur, index, snapshot.Get(), info, isTVP)) + return false; + if (!info.pObject) + info.pObject = snapshot.Detach(); + return true; + } PyObject* cls = 0; if (!IsInstanceForThread(param, "decimal", "Decimal", &cls)) @@ -1470,6 +1506,12 @@ static bool SetTVPName(Cursor* cur, SQLHDESC desc, Py_ssize_t index, SQLSMALLINT if (!encoded) return false; + if (PyBytes_GET_SIZE(encoded.Get()) > INT_MAX) + { + PyErr_SetString(PyExc_ValueError, "A TVP's type or schema name is too long"); + return false; + } + SQLRETURN ret = SQLSetDescFieldW(desc, (SQLSMALLINT)(index + 1), field, (SQLPOINTER)PyBytes_AS_STRING(encoded.Get()), (SQLINTEGER)PyBytes_GET_SIZE(encoded.Get())); @@ -1642,8 +1684,8 @@ static bool BindTVPColumns(Cursor* cur, Py_ssize_t index, ParamInfo& info) if (!GetDecimalPrecisionAndScale(value.Get(), precision, scale)) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return false; - RaiseErrorV(0, PyExc_TypeError, "Expected Decimal but got %s (TVP column %d)", - Py_TYPE(value)->tp_name, i); + RaiseErrorV(0, PyExc_TypeError, "Expected Decimal but got %s (TVP column %zd)", + Py_TYPE(value)->tp_name, (Py_ssize_t)i); return false; } SQLULEN integerDigits = max(precision - scale, 0); @@ -1828,7 +1870,13 @@ bool Prepare(Cursor* cur, PyObject* pSql) bool isWide = (penc->ctype == SQL_C_WCHAR); const char* pch = PyBytes_AS_STRING(query.Get()); - SQLINTEGER cch = (SQLINTEGER)(PyBytes_GET_SIZE(query.Get()) / (isWide ? sizeof(uint16_t) : 1)); + Py_ssize_t len = PyBytes_GET_SIZE(query.Get()) / (isWide ? sizeof(uint16_t) : 1); + if (len > INT_MAX) + { + PyErr_SetString(PyExc_ValueError, "SQL statement is too long"); + return false; + } + SQLINTEGER cch = (SQLINTEGER)len; TRACE("SQLPrepare(%s)\n", pch); @@ -1882,8 +1930,8 @@ bool PrepareAndBind(Cursor* cur, PyObject* pSql, PyObject* original_params, bool if (cParams != cur->paramcount) { - RaiseErrorV(0, ProgrammingError, "The SQL contains %d parameter markers, but %d parameters were supplied", - cur->paramcount, cParams); + RaiseErrorV(0, ProgrammingError, "The SQL contains %d parameter markers, but %zd parameters were supplied", + cur->paramcount, (Py_ssize_t)cParams); return false; } @@ -2008,7 +2056,7 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) } if (PySequence_Fast_GET_SIZE(colseq) != cur->paramcount) { - RaiseErrorV(0, ProgrammingError, "Expected %u parameters, supplied %u", cur->paramcount, PySequence_Fast_GET_SIZE(colseq)); + RaiseErrorV(0, ProgrammingError, "Expected %d parameters, supplied %zd", cur->paramcount, PySequence_Fast_GET_SIZE(colseq)); ErrorRet3: Py_XDECREF(colseq); goto ErrorRet2; @@ -2113,7 +2161,7 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) } if (PySequence_Fast_GET_SIZE(colseq) != cur->paramcount) { - RaiseErrorV(0, ProgrammingError, "Expected %u parameters, supplied %u", cur->paramcount, PySequence_Fast_GET_SIZE(colseq)); + RaiseErrorV(0, ProgrammingError, "Expected %d parameters, supplied %zd", cur->paramcount, PySequence_Fast_GET_SIZE(colseq)); Py_XDECREF(colseq); goto ErrorRet5; } @@ -2234,6 +2282,17 @@ bool ExecuteMulti(Cursor* cur, PyObject* pSql, PyObject* paramArrayObj) //TODO: Raise or clear error when bytes == NULL. } + // Another thread could resize a bytearray while the GIL is released for + // SQLPutData, freeing its buffer, so send a snapshot. + Object snapshot; + if (PyByteArray_Check(objCell)) + { + snapshot.Attach(PyBytes_FromObject(objCell)); + if (!snapshot) + goto ErrorRet8; + objCell = snapshot.Get(); + } + szLastFunction = "SQLPutData"; if (PyBytes_Check(objCell) || PyByteArray_Check(objCell)) { diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index ab22a2ad..ada25629 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -2225,6 +2225,126 @@ def test_long_diagnostic_messages(cursor: pyodbc.Cursor, length): assert any(m[1].endswith(text) for m in cursor.messages) +class _BadTupleDecimal(Decimal): + "A Decimal whose as_tuple() returns the given tuple" + def __new__(cls, value, parts): + d = super().__new__(cls, value) + d.parts = parts + return d + + def as_tuple(self): + return self.parts + + +_BAD_DECIMAL_PARTS = [ + pytest.param((-5, (1,), 0), id="negative-sign"), + pytest.param((2, (1,), 0), id="large-sign"), + pytest.param((0, (99,), 0), id="digit-too-large"), + pytest.param((0, (-1,), 0), id="negative-digit"), + pytest.param((0, ("1",), 0), id="str-digit"), + pytest.param((0, (), 0), id="no-digits"), + pytest.param((0, (1, 2)), id="short-tuple"), +] + + +@pytest.mark.parametrize("fast", [False, True]) +@pytest.mark.parametrize("parts", _BAD_DECIMAL_PARTS) +def test_decimal_subclass_bad_as_tuple(cursor: pyodbc.Cursor, fast, parts): + "A Decimal subclass whose as_tuple() returns nonsense raises instead of corrupting memory" + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = fast + with pytest.raises(TypeError, match="as_tuple"): + cursor.executemany("insert into t1 values (?)", [(_BadTupleDecimal("1", parts),)]) + + +@pytest.mark.parametrize("fast", [False, True]) +@pytest.mark.parametrize("exp, match", [ + (2**62, "Numeric overflow"), + (2**70, "Numeric overflow"), + (-2**70, "digits after the decimal point"), +]) +def test_decimal_subclass_huge_exponent(cursor: pyodbc.Cursor, fast, exp, match): + """An exponent larger than any Decimal's, from a subclass, raises instead of overflowing, + with the same error whether or not it fits a Py_ssize_t.""" + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = fast + value = _BadTupleDecimal("1", (0, (1,), exp)) + with pytest.raises(pyodbc.ProgrammingError, match=match): + cursor.executemany("insert into t1 values (?)", [(value,)]) + + +@pytest.mark.parametrize("fast", [False, True]) +def test_decimal_scale_too_large(cursor: pyodbc.Cursor, fast): + "A scale too large to bind raises instead of being truncated to a SQLSMALLINT" + cursor.execute("create table t1(v decimal(18, 2))") + cursor.fast_executemany = fast + with pytest.raises(pyodbc.ProgrammingError, match="digits after the decimal point"): + cursor.executemany("insert into t1 values (?)", [(Decimal("1E-40000"),)]) + + +class _BadUUID(uuid.UUID): + "A UUID whose bytes_le is the wrong length" + @property + def bytes_le(self): + return b"short" + + +def test_uuid_subclass_bad_bytes_le(cursor: pyodbc.Cursor): + cursor.execute("create table t1(v uniqueidentifier)") + with pytest.raises(TypeError, match="bytes_le"): + cursor.execute("insert into t1 values (?)", _BadUUID(int=1)) + + +@pytest.mark.parametrize("fast", [False, True]) +@pytest.mark.parametrize("length", [10, 4000, 100000]) +def test_bytearray_params(cursor: pyodbc.Cursor, fast, length): + "bytearray parameters are copied when bound and inserted correctly, long or short" + cursor.execute("create table t1(n int, v varbinary(max))") + cursor.fast_executemany = fast + values = [bytearray(range(256)) * (length // 256) + bytearray(b"x" * (length % 256)), + bytearray(b"y" * length)] + cursor.executemany("insert into t1 values (?, ?)", list(enumerate(values))) + rows = cursor.execute("select v from t1 order by n").fetchall() + assert [row.v for row in rows] == [bytes(v) for v in values] + + +@pytest.fixture +def tvp_decimal_proc(cursor: pyodbc.Cursor) -> Iterator[str]: + """A procedure taking a one-decimal-column TVP and returning its rows.""" + cursor.execute("drop procedure if exists tvp_decimal_p") + cursor.execute("drop type if exists tvp_decimal_t") + cursor.execute("create type tvp_decimal_t as table (v decimal(20, 4))") + cursor.execute("create procedure tvp_decimal_p @t tvp_decimal_t readonly" + " as select v from @t") + cursor.commit() + yield "{call tvp_decimal_p(?)}" + cursor.execute("drop procedure if exists tvp_decimal_p") + cursor.execute("drop type if exists tvp_decimal_t") + cursor.commit() + + +class _RaisingDecimal(Decimal): + "A Decimal whose as_tuple() raises" + def as_tuple(self): + raise ValueError("as_tuple failed") + + +@pytest.mark.skipif(SQLSERVER_YEAR < 2008, reason="TVP not supported until 2008") +@pytest.mark.skipif(IS_FREETDS, reason="FreeTDS does not support TVP") +def test_tvp_decimal_column_errors(cursor: pyodbc.Cursor, tvp_decimal_proc: str): + "Errors from a later row of a Decimal TVP column are raised, not replaced" + rows = [(Decimal("1.5"),), (Decimal("2.25"),)] + results = [r.v for r in cursor.execute(tvp_decimal_proc, (rows,))] + assert results == [Decimal("1.5000"), Decimal("2.2500")] + with pytest.raises(TypeError, match="Expected Decimal"): + cursor.execute(tvp_decimal_proc, ([(Decimal("1.5"),), (5,)],)) + with pytest.raises(ValueError, match="as_tuple failed"): + cursor.execute(tvp_decimal_proc, ([(Decimal("1.5"),), (_RaisingDecimal("2"),)],)) + with pytest.raises(TypeError, match="invalid sign"): + cursor.execute(tvp_decimal_proc, + ([(Decimal("1.5"),), (_BadTupleDecimal("2", (-5, (2,), 0)),)],)) + + def _decimal_samples(precision: int, scale: int) -> list[str]: "Random values that fit decimal(precision, scale), plus zero and the extremes" rnd = random.Random(precision * 100 + scale) From f391721e114f55ce83b9a914e4f0b3d556a11bbf Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:27:30 -0600 Subject: [PATCH 15/22] Use defaults when module settings are deleted Deleting pyodbc.pooling or pyodbc.odbcversion crashed the first connect, and deleting pyodbc.lowercase or pyodbc.native_uuid left an AttributeError set. Read all four through one helper that clears errors and uses the default. This also fixes a reference leak on every result set from reading pyodbc.lowercase. --- src/pyodbcmodule.cpp | 46 +++++++++++++++++++++++++++++--------------- src/pyodbcmodule.h | 6 ++---- tests/sqlite_test.py | 22 +++++++++++++++++++++ 3 files changed, 55 insertions(+), 19 deletions(-) diff --git a/src/pyodbcmodule.cpp b/src/pyodbcmodule.cpp index 85f1fa84..7d4a74a7 100644 --- a/src/pyodbcmodule.cpp +++ b/src/pyodbcmodule.cpp @@ -170,13 +170,32 @@ bool PyMem_Realloc(BYTE** pp, size_t newlen) +static int GetModuleFlag(const char* name, bool identity) +{ + // Returns 1 if the module attribute `name` is set, 0 if it is not, and -1 (with no + // exception) if it has been deleted or cannot be tested. If `identity` is true, only True + // counts as set. + PyObject* o = PyObject_GetAttrString(pModule, name); + if (!o) + { + PyErr_Clear(); + return -1; + } + int r = identity ? (o == Py_True) : PyObject_IsTrue(o); + Py_DECREF(o); + if (r < 0) + PyErr_Clear(); + return r; +} + bool UseNativeUUID() { - PyObject* o = PyObject_GetAttrString(pModule, "native_uuid"); - // If this fails for some reason, we'll assume false and allow the exception to pop up later. - bool b = o && PyObject_IsTrue(o); - Py_XDECREF(o); - return b; + return GetModuleFlag("native_uuid", false) == 1; +} + +bool lowercase() +{ + return GetModuleFlag("lowercase", true) == 1; } HENV henv = SQL_NULL_HANDLE; @@ -305,9 +324,8 @@ static bool import_types() static bool AllocateEnv() { - PyObject* pooling = PyObject_GetAttrString(pModule, "pooling"); - bool bPooling = pooling == Py_True; - Py_DECREF(pooling); + // pooling defaults to True if it has been deleted. + bool bPooling = GetModuleFlag("pooling", true) != 0; if (bPooling) { @@ -326,13 +344,11 @@ static bool AllocateEnv() SQLPOINTER defaultVersion = (SQLPOINTER)SQL_OV_ODBC3; PyObject* odbcversion = PyObject_GetAttrString(pModule, "odbcversion"); - if (PyObject_TypeCheck(odbcversion, &PyUnicode_Type)) { - if (PyUnicode_CompareWithASCIIString(odbcversion, "3.8") == 0) - { - defaultVersion = (SQLPOINTER)SQL_OV_ODBC3_80; - } - } - Py_DECREF(odbcversion); + if (!odbcversion) + PyErr_Clear(); + else if (PyUnicode_Check(odbcversion) && PyUnicode_CompareWithASCIIString(odbcversion, "3.8") == 0) + defaultVersion = (SQLPOINTER)SQL_OV_ODBC3_80; + Py_XDECREF(odbcversion); if (!SQL_SUCCEEDED(SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, defaultVersion, sizeof(int)))) { diff --git a/src/pyodbcmodule.h b/src/pyodbcmodule.h index 8ccd743f..14e9168b 100644 --- a/src/pyodbcmodule.h +++ b/src/pyodbcmodule.h @@ -53,10 +53,8 @@ extern PyTypeObject ConnectionType; // Thd pyodbc module. extern PyObject* pModule; -inline bool lowercase() -{ - return PyObject_GetAttrString(pModule, "lowercase") == Py_True; -} +bool lowercase(); +// Returns True if pyodbc.lowercase is True, meaning column names should be lowercased. bool UseNativeUUID(); // Returns True if pyodbc.native_uuid is true, meaning uuid.UUID objects should be returned. diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index 2694cf5c..dd9cc7a4 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -22,6 +22,8 @@ import pickle import platform import re +import subprocess +import sys from collections.abc import Iterator from datetime import datetime, time @@ -1020,3 +1022,23 @@ def test_set_decimal_separator_regex_characters(sep): finally: pyodbc.setDecimalSeparator(saved) assert pyodbc.getDecimalSeparator() == saved + + +def test_deleted_module_settings(connection_string: str): + "Deleting pyodbc.pooling, odbcversion, or lowercase uses the defaults instead of crashing" + # The environment is allocated by the first connect, so this needs a new interpreter. + script = """ +import sys, pyodbc +del pyodbc.pooling, pyodbc.odbcversion, pyodbc.lowercase, pyodbc.native_uuid +cnxn = pyodbc.connect(sys.argv[1]) +row = cnxn.execute("select 1 as Abc").fetchone() +print(row.Abc) +""" + env = dict(os.environ) + # Make sure the child imports the same pyodbc build. + env["PYTHONPATH"] = os.pathsep.join([os.path.dirname(pyodbc.__file__), + env.get("PYTHONPATH", "")]) + result = subprocess.run([sys.executable, "-c", script, connection_string], env=env, + capture_output=True, text=True, timeout=60) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "1" From 4bf133cb89ec4c378a3959d74ce634d679bc1fb2 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:28:52 -0600 Subject: [PATCH 16/22] Remove comments about Python 2 pyodbc requires Python 3.11, so remove comments describing Python 2 behavior and Python 2 type names. connect() with a non-str connection string now says "must be a str" instead of "a string or unicode object". --- src/connection.cpp | 1 - src/cursor.cpp | 2 +- src/cursor.h | 2 +- src/decimal.cpp | 5 ----- src/errors.h | 1 - src/params.cpp | 3 +-- src/pyodbc.pyi | 5 ++--- src/pyodbc.rc | 5 ++--- src/pyodbcmodule.cpp | 9 +++------ src/row.cpp | 2 +- 10 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index 5364ad76..2850d026 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -1575,7 +1575,6 @@ static PyObject* Connection_setencoding(PyObject* self, PyObject* args, PyObject { Connection* cnxn = (Connection*)self; - // In Python 3 we only support encodings for Unicode text. char* encoding = 0; int ctype = 0; static char *kwlist[] = { "encoding", "ctype", 0 }; diff --git a/src/cursor.cpp b/src/cursor.cpp index 3e10fe67..c9c34974 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -774,7 +774,7 @@ static PyObject* execute(Cursor* cur, PyObject* pSql, PyObject* params, bool ski // Internal function to execute SQL, called by .execute and .executemany. // // pSql - // A PyString, PyUnicode, or derived object containing the SQL. + // A str or derived object containing the SQL. // // params // Pointer to an optional sequence of parameters, and possibly the SQL statement (see skip_first): diff --git a/src/cursor.h b/src/cursor.h index 958baad8..c87460c3 100644 --- a/src/cursor.h +++ b/src/cursor.h @@ -165,7 +165,7 @@ struct Cursor // The Cursor.rowcount attribute from the DB API specification. int rowcount; - // A dictionary that maps from column name (PyString) to index into the result columns (PyInteger). This is + // A dictionary that maps from column name (str) to index into the result columns (int). This is // constructed during an execute and shared with each row (reference counted) to implement accessing results by // column name. // diff --git a/src/decimal.cpp b/src/decimal.cpp index e78736c7..46457cf8 100644 --- a/src/decimal.cpp +++ b/src/decimal.cpp @@ -14,16 +14,11 @@ static PyObject* re_sub = 0; static PyObject* re_compile = 0; static PyObject* re_escape = 0; -// In Python 2.7, the 3 strings below are bytes objects. In 3.x they are Unicode objects. - - static PyObject* pDecimalPoint = 0; // A "." object which we replace pLocaleDecimal with if they are not the same. static PyObject* pLocaleDecimal = 0; // The decimal character used by the locale. This can be overridden by the user. -// -// In 2.7 this is a bytes object, otherwise unicode. static PyObject* pLocaleDecimalEscaped = 0; // A version of pLocaleDecimal escaped to be used in a regular expression. (The character diff --git a/src/errors.h b/src/errors.h index f2f47a34..f1a383d1 100644 --- a/src/errors.h +++ b/src/errors.h @@ -57,7 +57,6 @@ bool HasSqlState(HSTMT hstmt, const char* szSqlState); inline PyObject* RaiseErrorFromException(PyObject* pError) { - // PyExceptionInstance_Class doesn't exist in 2.4 PyErr_SetObject((PyObject*)Py_TYPE(pError), pError); return 0; } diff --git a/src/params.cpp b/src/params.cpp index fe926e36..192b9cec 100644 --- a/src/params.cpp +++ b/src/params.cpp @@ -136,7 +136,6 @@ static int DetectCType(PyObject *cell, ParamInfo *pi) else if (PyBytes_Check(cell)) { Type_Bytes: - // Assume the SQL type is also character (2.x) or binary (3.x). // If it is a max-type (ColumnSize == 0), use DAE. pi->ValueType = SQL_C_BINARY; pi->BufferLength = pi->ColumnSize ? pi->ColumnSize : sizeof(DAEParam); @@ -851,7 +850,7 @@ static bool GetNullBinaryInfo(Cursor* cur, Py_ssize_t index, ParamInfo& info) static bool GetBytesInfo(Cursor* cur, Py_ssize_t index, PyObject* param, ParamInfo& info, bool isTVP) { - // The Python 3 version that writes bytes as binary data. + // Binds bytes as binary data. Py_ssize_t cb = PyBytes_GET_SIZE(param); info.ValueType = SQL_C_BINARY; diff --git a/src/pyodbc.pyi b/src/pyodbc.pyi index ec220e3b..a064b3e9 100644 --- a/src/pyodbc.pyi +++ b/src/pyodbc.pyi @@ -465,8 +465,7 @@ class Connection: Args: encoding: Text encoding codec, e.g. "utf-8". - ctype: The C data type when passing data - either pyodbc.SQL_CHAR or pyodbc.SQL_WCHAR. More - relevant for Python 2.7. + ctype: The C data type when passing data - either pyodbc.SQL_CHAR or pyodbc.SQL_WCHAR. """ ... @@ -480,7 +479,7 @@ class Connection: sqltype: pyodbc.SQL_CHAR, pyodbc.SQL_WCHAR, or pyodbc.SQL_WMETADATA. encoding: Text encoding codec, e.g. "utf-8". ctype: The C data type to request from SQLGetData - either pyodbc.SQL_CHAR or - pyodbc.SQL_WCHAR. More relevant for Python 2.7. + pyodbc.SQL_WCHAR. """ ... diff --git a/src/pyodbc.rc b/src/pyodbc.rc index 1d346afa..915f025b 100644 --- a/src/pyodbc.rc +++ b/src/pyodbc.rc @@ -1,8 +1,7 @@ // This was a Microsoft Visual C++ generated resource script, but I've hand modified it to -// remove the afxres.h include. Apparently Visual Studio 2008 Express (used to build the -// Python 2.6 version) does not include afxres.h which is part of MFC. This will probably -// not be editable in the Visual Studio resource editor. +// remove the afxres.h include, which is part of MFC and is not always installed. This will +// probably not be editable in the Visual Studio resource editor. #include #include "resource.h" diff --git a/src/pyodbcmodule.cpp b/src/pyodbcmodule.cpp index 7d4a74a7..6221694a 100644 --- a/src/pyodbcmodule.cpp +++ b/src/pyodbcmodule.cpp @@ -299,9 +299,6 @@ static bool import_types() // Note: We can only import types from C extensions since they are shared among all // interpreters. Other classes are imported per-thread via GetClassForThread. - // In Python 2.5 final, PyDateTime_IMPORT no longer works unless the datetime module was previously - // imported (among other problems). - PyObject* pdt = PyImport_ImportModule("datetime"); if (!pdt) @@ -420,7 +417,7 @@ struct keywordmap { const char* oldname; const char* newname; - PyObject* newnameObject; // PyString object version of newname, created as needed. + PyObject* newnameObject; // str version of newname, created as needed. }; static keywordmap keywordmaps[] = @@ -454,8 +451,8 @@ static PyObject* mod_connect(PyObject* self, PyObject* args, PyObject* kwargs) if (size == 1) { - if (!PyUnicode_Check(PyTuple_GET_ITEM(args, 0)) && !PyUnicode_Check(PyTuple_GET_ITEM(args, 0))) - return PyErr_Format(PyExc_TypeError, "argument 1 must be a string or unicode object"); + if (!PyUnicode_Check(PyTuple_GET_ITEM(args, 0))) + return PyErr_Format(PyExc_TypeError, "argument 1 must be a str"); pConnectString.Attach(PyUnicode_FromObject(PyTuple_GetItem(args, 0))); if (!pConnectString.IsValid()) diff --git a/src/row.cpp b/src/row.cpp index d04bc5f1..58ae3442 100644 --- a/src/row.cpp +++ b/src/row.cpp @@ -25,7 +25,7 @@ struct Row // cursor.description, accessed as _description PyObject* description; - // A Python dictionary mapping from column name to a PyInteger, used to access columns by name. + // A Python dictionary mapping from column name to an int, used to access columns by name. PyObject* map_name_to_index; // The number of values in apValues. From 659991381398340d2d86923003db883e73fe0f85 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:31:46 -0600 Subject: [PATCH 17/22] RaiseErrorV: clear any pending exception before creating the new one Creating the exception calls the exception class, which Python 3.12 rejects with SystemError when an exception is already set. The TVP "Expected Decimal" error was raised this way with an AttributeError pending. --- src/errors.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/errors.cpp b/src/errors.cpp index c6ba8078..1a3423db 100644 --- a/src/errors.cpp +++ b/src/errors.cpp @@ -61,6 +61,10 @@ PyObject* RaiseErrorV(const char* sqlstate, PyObject* exc_class, const char* for { PyObject *pAttrs = 0, *pError = 0; + // This replaces any exception already set, as PyErr_SetString does. Creating the new + // exception below calls Python code, which must not be called with an exception set. + PyErr_Clear(); + if (!sqlstate || !*sqlstate) sqlstate = "HY000"; From 76c8566dfc2a93a5abf49c7df42f6f35c2ff39f3 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 15:33:57 -0600 Subject: [PATCH 18/22] nextset: raise on a closed cursor and when SQLNumResultCols fails; free the read buffer on errors nextset() on a closed cursor returned NULL without an exception (SystemError), and a SQLNumResultCols failure returned the exception object instead of raising it. ReadVarColumn leaked its buffer when SQLGetData failed. --- src/cursor.cpp | 9 +++++++-- src/getdata.cpp | 1 + tests/sqlite_test.py | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/cursor.cpp b/src/cursor.cpp index c9c34974..7959f72f 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -2262,7 +2262,7 @@ static PyObject* Cursor_nextset(PyObject* self, PyObject* args) { UNUSED(args); - Cursor* cur = Cursor_Validate(self, 0); + Cursor* cur = Cursor_Validate(self, CURSOR_REQUIRE_OPEN | CURSOR_RAISE_ERROR); if (!cur) return 0; @@ -2333,7 +2333,12 @@ static PyObject* Cursor_nextset(PyObject* self, PyObject* args) PyObject* pError = GetErrorFromHandle(cur->cnxn, "SQLNumResultCols", cur->cnxn->hdbc, cur->hstmt); free_results(cur, FREE_STATEMENT | KEEP_PREPARED | KEEP_MESSAGES); - return pError; + if (pError) + { + RaiseErrorFromException(pError); + Py_DECREF(pError); + } + return 0; } free_results(cur, KEEP_STATEMENT | KEEP_PREPARED | KEEP_MESSAGES); diff --git a/src/getdata.cpp b/src/getdata.cpp index c95fd5f4..31818ec8 100644 --- a/src/getdata.cpp +++ b/src/getdata.cpp @@ -154,6 +154,7 @@ static bool ReadVarColumn(Cursor* cur, Py_ssize_t iCol, SQLSMALLINT ctype, bool& if (!SQL_SUCCEEDED(ret) && ret != SQL_NO_DATA) { RaiseErrorFromHandle(cur->cnxn, "SQLGetData", cur->cnxn->hdbc, cur->hstmt); + PyMem_Free(pb); return false; } diff --git a/tests/sqlite_test.py b/tests/sqlite_test.py index dd9cc7a4..b7a03c81 100644 --- a/tests/sqlite_test.py +++ b/tests/sqlite_test.py @@ -1042,3 +1042,9 @@ def test_deleted_module_settings(connection_string: str): capture_output=True, text=True, timeout=60) assert result.returncode == 0, result.stderr assert result.stdout.strip() == "1" + + +def test_nextset_closed_cursor(cursor: pyodbc.Cursor): + cursor.close() + with pytest.raises(pyodbc.ProgrammingError, match="closed cursor"): + cursor.nextset() From 8c8739cb45d0f81b4fdb526d86885f27b5f2c854 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Fri, 6 Nov 2026 14:52:18 -0600 Subject: [PATCH 19/22] Update version to 5.5.0 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e2986d64..483c4d33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pyodbc" -version = "5.4.0" +version = "5.5.0" requires-python = ">=3.11" # This is used by the GitHub action that builds release artifacts using cibuildwheel. From ced039c8927e56817cdb63da50c96820c0c350a0 Mon Sep 17 00:00:00 2001 From: Michael Kleehammer Date: Sat, 7 Nov 2026 18:52:00 -0600 Subject: [PATCH 20/22] Build the macOS ARM64 wheels on macos-15 GitHub no longer supports the macos-14 runner image: the 5.5.0 artifacts build was rejected with "The configuration 'macos-14-arm64-us-default' is not supported". The wheels' macOS tag (macosx_11_0_arm64) comes from cibuildwheel's Python builds, not the runner. --- .github/workflows/artifacts_build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/artifacts_build.yml b/.github/workflows/artifacts_build.yml index f56eaf16..297bc30e 100644 --- a/.github/workflows/artifacts_build.yml +++ b/.github/workflows/artifacts_build.yml @@ -159,14 +159,14 @@ jobs: build_macos_arm64_wheels: name: Build wheels on macOS ARM64 - runs-on: macos-14 + runs-on: macos-15 steps: - uses: actions/checkout@v7.0.1 - name: Install unixODBC # unixODBC is necessary for the SQL C header files, e.g. sql.h, but doesn't appear - # to be pre-installed on macos-14, hence make sure it really is installed + # to be pre-installed on the macOS runners, hence make sure it really is installed run: brew install unixodbc - name: Build wheels From 6c0439bbefa6df19591e0027108936466ffc4b8c Mon Sep 17 00:00:00 2001 From: Pat Buxton Date: Wed, 3 Jun 2026 08:14:59 +0100 Subject: [PATCH 21/22] Add a low-level SQL Server bulk copy (BCP) API to Connection Adds Connection methods that drive the SQL Server bulk-copy (BCP) API directly, loading rows into a table with explicit host types. They are the building blocks for the BCP fast path for fast_executemany in the next commit, and serve loads that want BCP options of their own (batch size, hints, KEEPNULLS, error limits). Usage (SQL Server with Microsoft ODBC Driver 13 or later): - open the connection with attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON} - cnxn.bcp_init(table, batch_rows=0, keep_nulls=False, hints=None, max_errors=0) - ctx = cnxn.bcp_bind_columns([pyodbc.SQLINT4, pyodbc.SQLNCHAR, ...]) - for each row: cnxn.bcp_setrow(ctx, row), then cnxn.bcp_sendrow() - cnxn.bcp_batch(ctx) and cnxn.bcp_done() return the rows stored The host types are exported as pyodbc.SQLBIT, SQLINT2/4/8, SQLFLT4/8, SQLNCHAR, SQLCHARACTER, SQLBINARY and SQLUNIQUEID, along with DB_IN, SQL_COPT_SS_BCP and SQL_BCP_ON. The driver's bcp_* exports are bound on demand, once per connection, from the library of the driver that connection uses, and only when that is Microsoft ODBC Driver 13 or later for SQL Server; any other driver raises a clear error. SQL Server Native Client and Driver 11 are left out because behind the Windows driver manager's connection pooling, which pyodbc turns on by default, they leave a failed batch without diagnostics. The module is found by the connection's driver name (on Linux, failing that, by its exact path in /proc/self/maps), and elsewhere than Windows is opened with RTLD_NOLOAD, so two SQL Server drivers loaded in one process never share entry points. bcp_initW takes the table name, so names outside the ANSI code page work. Loader diagnostics are gated behind PYODBC_BCP_DEBUG. Safety: - The connection owns the bound buffers until bcp_done, so dropping the context cannot free them under the driver. - In autocommit mode a session runs in its own transaction, committed at each batch, so closing the connection first discards the rows sent since the last batch; in manual-commit mode the rows join the open transaction. autocommit cannot change mid-session. - bcp_setrow converts the whole row before writing any of it, so a value conversion that runs Python code (and might even close the connection) cannot pull the session out from under it, and every bcp_sendrow needs a successful bcp_setrow first. - str goes to SQLNCHAR columns as UTF-16. SQLCHARACTER takes bytes or ASCII str only, since the driver reads it in the client's code page. - Variable-length columns use an 8-byte length prefix plus bcp_collen, which (max) columns need: the driver misreads a zero-length 8-byte prefix on its own. Tests in tests/sqlserver_test.py cover every host type with NULLs, batches, manual-commit mode, misuse, and a conversion that closes the connection mid-row. Co-Authored-By: Claude Opus 4.8 (1M context) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lyo1SXh7BDrSf1BctKfCrz --- src/bcp_support.cpp | 541 +++++++++++++++++++++++++++++++++++++ src/bcp_support.h | 238 ++++++++++++++++ src/connection.cpp | 585 +++++++++++++++++++++++++++++++++++++++- src/connection.h | 5 + src/pyodbc.pyi | 55 ++++ src/pyodbcmodule.cpp | 16 ++ tests/sqlserver_test.py | 269 +++++++++++++++++- 7 files changed, 1696 insertions(+), 13 deletions(-) create mode 100644 src/bcp_support.cpp create mode 100644 src/bcp_support.h diff --git a/src/bcp_support.cpp b/src/bcp_support.cpp new file mode 100644 index 00000000..588e17b8 --- /dev/null +++ b/src/bcp_support.cpp @@ -0,0 +1,541 @@ +#include "pyodbc.h" +#include "wrapper.h" +#include "textenc.h" +#include "connection.h" +#include "pyodbcmodule.h" +#include "bcp_support.h" +#include +#include +#include +#ifndef _WIN32 +#include +#endif + + +/** + * Diagnostic logging toggle, controlled by the PYODBC_BCP_DEBUG environment variable and + * cached on first use. When enabled, driver loading reports to stderr why BCP is unavailable. + */ +static int bcp_debug_enabled(void) +{ + static int cached = -1; + if (cached == -1) { + const char* v = getenv("PYODBC_BCP_DEBUG"); + cached = (v && v[0] && !(v[0] == '0' && v[1] == '\0')) ? 1 : 0; + } + return cached; +} + +#define BCPLOAD_DBG(...) do { if (bcp_debug_enabled()) { fprintf(stderr, "[bcp] " __VA_ARGS__); fflush(stderr); } } while (0) + +static bool get_driver_name(HDBC hdbc, char* buf, SQLSMALLINT buflen) +{ + SQLSMALLINT outlen = 0; + if (SQLGetInfo(hdbc, SQL_DRIVER_NAME, (SQLPOINTER)buf, buflen, &outlen) != SQL_SUCCESS) + return false; + buf[buflen - 1] = '\0'; + return true; +} + +#ifdef __linux__ +/** + * Finds the absolute path of the mapped library whose file name is exactly `soname`. + * + * SQLGetInfo(SQL_DRIVER_NAME) reports a bare versioned soname such as + * "libmsodbcsql-18.5.so.1.1", which dlopen cannot resolve unless its directory is on the loader + * path, but the driver manager has already mapped the library, so /proc/self/maps has its path. + * Only an exact match is accepted, so a process with two driver versions loaded gets the right one. + */ +static bool find_mapped_library(const char* soname, char* out, size_t outcap) +{ + FILE* f = fopen("/proc/self/maps", "r"); + if (!f) + return false; + char line[8192]; + bool found = false; + while (!found && fgets(line, sizeof(line), f)) { + char* path = strchr(line, '/'); + if (!path) + continue; + size_t len = strlen(path); + while (len && (path[len - 1] == '\n' || path[len - 1] == '\r')) + path[--len] = '\0'; + const char* base = strrchr(path, '/') + 1; + if (strcmp(base, soname) == 0 && len < outcap) { + memcpy(out, path, len + 1); + found = true; + } + } + fclose(f); + return found; +} +#endif + +/** + * Returns a handle to the already-loaded driver library, never loading another copy. + */ +static void* find_driver_module(const char* drv) +{ +#ifdef _WIN32 + return (void*)GetModuleHandleA(drv); +#else + void* mod = dlopen(drv, RTLD_NOW | RTLD_NOLOAD); +#ifdef __linux__ + if (!mod) { + const char* slash = strrchr(drv, '/'); + char path[4096]; + if (find_mapped_library(slash ? slash + 1 : drv, path, sizeof(path))) { + BCPLOAD_DBG("load: driver mapped at '%s'\n", path); + mod = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + } + } +#endif + return mod; +#endif +} + +template +static bool resolve(void* mod, const char* name, TFn& out) +{ +#ifdef _WIN32 + out = reinterpret_cast(GetProcAddress((HMODULE)mod, name)); +#else + out = reinterpret_cast(dlsym(mod, name)); +#endif + if (!out) + BCPLOAD_DBG("load: missing %s\n", name); + return out != nullptr; +} + +/** Returns true for the Microsoft ODBC Driver for SQL Server (msodbcsql*.dll, libmsodbcsql*). */ +static bool is_microsoft_driver(const char* drv) +{ + const char* base = strrchr(drv, '/'); + base = base ? base + 1 : drv; + const char* prefix = strncmp(base, "lib", 3) == 0 ? base + 3 : base; + char lower[16] = {0}; + for (int i = 0; i < 9 && prefix[i]; ++i) + lower[i] = (prefix[i] >= 'A' && prefix[i] <= 'Z') ? (char)(prefix[i] + 32) : prefix[i]; + return strncmp(lower, "msodbcsql", 9) == 0; +} + +/** Returns the major version in SQLGetInfo(SQL_DRIVER_VER), "##.##.####", or 0 if unknown. */ +static int get_driver_major_version(HDBC hdbc) +{ + char ver[32] = {0}; + SQLSMALLINT outlen = 0; + if (SQLGetInfo(hdbc, SQL_DRIVER_VER, (SQLPOINTER)ver, sizeof(ver), &outlen) != SQL_SUCCESS) + return 0; + ver[sizeof(ver) - 1] = '\0'; + const long major = strtol(ver, 0, 10); + return major > 0 && major < 10000 ? (int)major : 0; +} + +/** + * Resolves the BCP entry points from the driver behind hdbc. Only the Microsoft ODBC Driver + * 13 or later is used. FreeTDS exports the same functions but differs in its conversions and + * diagnostics, which the fast path's guarantees rest on. SQL Server Native Client and Driver + * 11 leave a failed bcp_batch or bcp_done without diagnostics when the Windows driver manager + * pools connections, as pyodbc has it do by default, so their errors could not be raised. + */ +static bool load_driver_procs(HDBC hdbc, BcpProcs& out) +{ + char drv[256] = {0}; + if (!get_driver_name(hdbc, drv, sizeof(drv))) { + BCPLOAD_DBG("load: SQLGetInfo(SQL_DRIVER_NAME) failed\n"); + return false; + } + BCPLOAD_DBG("load: driver name = '%s'\n", drv); + if (!is_microsoft_driver(drv)) { + BCPLOAD_DBG("load: not the Microsoft ODBC Driver for SQL Server\n"); + return false; + } + int major = get_driver_major_version(hdbc); + if (major < 13) { + BCPLOAD_DBG("load: driver version %d is older than 13\n", major); + return false; + } + + void* mod = find_driver_module(drv); + if (!mod) { + BCPLOAD_DBG("load: driver module '%s' is not loaded\n", drv); + return false; + } + return resolve(mod, "bcp_initW", out.bcp_initW) + && resolve(mod, "bcp_bind", out.bcp_bind) + && resolve(mod, "bcp_collen", out.bcp_collen) + && resolve(mod, "bcp_sendrow", out.bcp_sendrow) + && resolve(mod, "bcp_batch", out.bcp_batch) + && resolve(mod, "bcp_done", out.bcp_done) + && resolve(mod, "bcp_control", out.bcp_control); +} + +bool BcpEnsureLoaded(Connection* cnxn) +{ + if (cnxn->bcp) + return cnxn->bcp->loaded; + if (!cnxn->hdbc) + return false; + BcpState* state = (BcpState*)PyMem_Calloc(1, sizeof(BcpState)); + if (!state) { + PyErr_NoMemory(); + return false; + } + state->loaded = load_driver_procs(cnxn->hdbc, state->procs); + cnxn->bcp = state; + return state->loaded; +} + +bool BcpSetAutocommit(HDBC hdbc, bool on) +{ + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = SQLSetConnectAttr(hdbc, SQL_ATTR_AUTOCOMMIT, + (SQLPOINTER)(uintptr_t)(on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF), SQL_IS_UINTEGER); + Py_END_ALLOW_THREADS + return SQL_SUCCEEDED(rc); +} + +bool BcpEndTransaction(HDBC hdbc, bool commit) +{ + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = SQLEndTran(SQL_HANDLE_DBC, hdbc, commit ? SQL_COMMIT : SQL_ROLLBACK); + Py_END_ALLOW_THREADS + return SQL_SUCCEEDED(rc); +} + +/*=======================================================================================*/ +// Column buffers +/*=======================================================================================*/ + +void write_le(unsigned char* dst, unsigned long long v, int len) +{ + for (int i = 0; i < len; ++i) + dst[i] = (unsigned char)((v >> (8 * i)) & 0xFF); +} + +static DBINT fixed_size_of(int hostType) +{ + switch (hostType) { + case SQLBIT: return 1; + case SQLINT2: return 2; + case SQLINT4: return 4; + case SQLFLT4: return 4; + case SQLINT8: return 8; + case SQLFLT8: return 8; + case SQLUNIQUEID: return 16; + } + return 0; +} + +bool BcpAllocColumn(BcpCol* c) +{ + c->fixedSize = c->prefix ? 0 : fixed_size_of(c->hostType); + c->scratchCap = c->prefix ? (size_t)c->prefix + 256 : (size_t)c->fixedSize; + c->scratch = (unsigned char*)PyMem_Calloc(1, c->scratchCap); + if (!c->scratch) { + PyErr_NoMemory(); + return false; + } + if (c->prefix) + write_le(c->scratch, ~0ULL, c->prefix); + return true; +} + +void BcpFreeColumns(BcpCol* cols, int ncols) +{ + if (!cols) + return; + for (int i = 0; i < ncols; ++i) + PyMem_Free(cols[i].scratch); + PyMem_Free(cols); +} + +bool BcpBindColumn(Connection* cnxn, BcpCol* c) +{ + const DBINT cbData = c->prefix ? SQL_VARLEN_DATA : c->fixedSize; + return cnxn->bcp->procs.bcp_bind(cnxn->hdbc, c->scratch, c->prefix, cbData, nullptr, 0, + c->hostType, c->ordinal) == SUCCEED; +} + +bool BcpPutNull(Connection* cnxn, BcpCol* c) +{ + if (c->prefix) { + write_le(c->scratch, ~0ULL, c->prefix); + return true; + } + if (cnxn->bcp->procs.bcp_collen(cnxn->hdbc, SQL_NULL_DATA, c->ordinal) == FAIL) + return false; + c->wasNull = true; + return true; +} + +bool BcpPutFixed(Connection* cnxn, BcpCol* c, const void* value) +{ + memcpy(c->scratch, value, (size_t)c->fixedSize); + if (c->wasNull) { + if (cnxn->bcp->procs.bcp_collen(cnxn->hdbc, c->fixedSize, c->ordinal) == FAIL) + return false; + c->wasNull = false; + } + return true; +} + +/** + * Makes room for n data bytes after the prefix, rebinding the column to a bigger buffer, and + * writes the prefix (and, for setsCollen columns, bcp_collen). The buffer grows geometrically + * so a column of steadily longer values does not rebind on every row. The old buffer is freed + * only once the driver has taken the new one, so a failed rebind leaves it reading valid memory. + */ +static bool reserve_varlen(Connection* cnxn, BcpCol* c, long long n) +{ + if (n > (long long)INT_MAX - c->prefix) { + PyErr_SetString(PyExc_OverflowError, "value too long for a BCP column"); + return false; + } + const size_t need = (size_t)c->prefix + (size_t)n; + if (need > c->scratchCap) { + const size_t cap = c->scratchCap * 2 > need ? c->scratchCap * 2 : need; + unsigned char* p = (unsigned char*)PyMem_Malloc(cap); + if (!p) { + PyErr_NoMemory(); + return false; + } + unsigned char* old = c->scratch; + const size_t oldCap = c->scratchCap; + c->scratch = p; + c->scratchCap = cap; + if (!BcpBindColumn(cnxn, c)) { + c->scratch = old; + c->scratchCap = oldCap; + PyMem_Free(p); + return false; + } + PyMem_Free(old); + } + write_le(c->scratch, (unsigned long long)n, c->prefix); + return !c->setsCollen || cnxn->bcp->procs.bcp_collen(cnxn->hdbc, (DBINT)n, c->ordinal) != FAIL; +} + +bool BcpPutBytes(Connection* cnxn, BcpCol* c, const void* data, Py_ssize_t n) +{ + if (!reserve_varlen(cnxn, c, n)) + return false; + if (n > 0) + memcpy(c->scratch + c->prefix, data, (size_t)n); + return true; +} + +bool BcpPutWidened(Connection* cnxn, BcpCol* c, const unsigned char* text, Py_ssize_t n) +{ + if (!reserve_varlen(cnxn, c, 2LL * n)) + return false; + unsigned char* dst = c->scratch + c->prefix; + for (Py_ssize_t i = 0; i < n; ++i) { + dst[2 * i] = text[i]; + dst[2 * i + 1] = 0; + } + return true; +} + +/*=======================================================================================*/ +// Low-level API values +/*=======================================================================================*/ + +static bool convert_low_level_integer(const BcpCol* c, PyObject* value, BcpLowLevelValue* out) +{ + if (!PyLong_Check(value)) { + PyErr_Format(PyExc_TypeError, "an int is required for an integer BCP column, not %.100s", Py_TYPE(value)->tp_name); + return false; + } + long long v = PyLong_AsLongLong(value); + if (v == -1 && PyErr_Occurred()) + return false; + if (c->hostType == SQLINT2) { + if (v < SHRT_MIN || v > SHRT_MAX) { + PyErr_SetString(PyExc_OverflowError, "value out of range for a SQLINT2 BCP column"); + return false; + } + short s = (short)v; + memcpy(out->fixed, &s, sizeof(s)); + } else if (c->hostType == SQLINT4) { + if (v < INT_MIN || v > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, "value out of range for a SQLINT4 BCP column"); + return false; + } + int i = (int)v; + memcpy(out->fixed, &i, sizeof(i)); + } else { + memcpy(out->fixed, &v, sizeof(v)); + } + return true; +} + +static bool convert_low_level_float(const BcpCol* c, PyObject* value, BcpLowLevelValue* out) +{ + double d = PyFloat_AsDouble(value); + if (d == -1.0 && PyErr_Occurred()) + return false; + if (c->hostType == SQLFLT8) { + memcpy(out->fixed, &d, sizeof(d)); + return true; + } + if (std::isfinite(d) && std::fabs(d) > FLT_MAX) { + PyErr_SetString(PyExc_OverflowError, "value out of range for a SQLFLT4 BCP column"); + return false; + } + float f = (float)d; + memcpy(out->fixed, &f, sizeof(f)); + return true; +} + +static bool convert_low_level_bit(PyObject* value, BcpLowLevelValue* out) +{ + if (!PyLong_Check(value)) { + PyErr_Format(PyExc_TypeError, "a bool is required for a SQLBIT BCP column, not %.100s", Py_TYPE(value)->tp_name); + return false; + } + long long v = PyLong_AsLongLong(value); + if (v == -1 && PyErr_Occurred()) + return false; + if (v != 0 && v != 1) { + PyErr_SetString(PyExc_ValueError, "SQLBIT BCP columns take True, False, 0 or 1"); + return false; + } + out->fixed[0] = (unsigned char)v; + return true; +} + +static bool convert_low_level_uuid(PyObject* value, BcpLowLevelValue* out) +{ + if (PyBytes_Check(value) && PyBytes_GET_SIZE(value) == 16) { + memcpy(out->fixed, PyBytes_AS_STRING(value), 16); + return true; + } + PyObject* uuid_cls = 0; + if (IsInstanceForThread(value, "uuid", "UUID", &uuid_cls) && uuid_cls) { + Py_DECREF(uuid_cls); + Object le(PyObject_GetAttrString(value, "bytes_le")); + if (!le.IsValid()) + return false; + if (PyBytes_Check(le.Get()) && PyBytes_GET_SIZE(le.Get()) == 16) { + memcpy(out->fixed, PyBytes_AS_STRING(le.Get()), 16); + return true; + } + } + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_TypeError, "a uuid.UUID or 16 bytes is required for a SQLUNIQUEID BCP column"); + return false; +} + +/** Holds a reference to immutable data (bytes or an ASCII/Latin-1 str) without copying it. */ +static void hold(BcpLowLevelValue* out, PyObject* owner, const void* data, Py_ssize_t size) +{ + Py_INCREF(owner); + out->holder = owner; + out->data = (const unsigned char*)data; + out->size = size; +} + +/** Bytes as they are; a bytearray is copied, since later Python code could resize it. */ +static bool convert_low_level_binary(PyObject* value, BcpLowLevelValue* out) +{ + if (PyBytes_Check(value)) { + hold(out, value, PyBytes_AS_STRING(value), PyBytes_GET_SIZE(value)); + return true; + } + PyObject* copy = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(value), PyByteArray_GET_SIZE(value)); + if (!copy) + return false; + out->holder = copy; + out->data = (const unsigned char*)PyBytes_AS_STRING(copy); + out->size = PyBytes_GET_SIZE(copy); + return true; +} + +/** + * SQLCHARACTER data is read in the client's ANSI code page, so only bytes (already encoded by + * the caller) and ASCII str, which every code page shares, can be sent unchanged. + */ +static bool convert_low_level_character(PyObject* value, BcpLowLevelValue* out) +{ + if (PyUnicode_Check(value)) { + if (!PyUnicode_IS_ASCII(value)) { + PyErr_SetString(PyExc_ValueError, + "SQLCHARACTER BCP columns are read in the client code page, so they only take " + "ASCII str or encoded bytes; use SQLNCHAR for other text"); + return false; + } + hold(out, value, PyUnicode_1BYTE_DATA(value), PyUnicode_GET_LENGTH(value)); + return true; + } + if (PyBytes_Check(value) || PyByteArray_Check(value)) + return convert_low_level_binary(value, out); + PyErr_Format(PyExc_TypeError, "a str or bytes is required for a SQLCHARACTER BCP column, not %.100s", Py_TYPE(value)->tp_name); + return false; +} + +/** A str as UTF-16LE: a 1-byte str is widened when written, a wider one encoded now. */ +static bool convert_low_level_wide(PyObject* value, BcpLowLevelValue* out) +{ + if (!PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, "a str is required for a SQLNCHAR BCP column, not %.100s", Py_TYPE(value)->tp_name); + return false; + } + if (PyUnicode_KIND(value) == PyUnicode_1BYTE_KIND) { + hold(out, value, PyUnicode_1BYTE_DATA(value), PyUnicode_GET_LENGTH(value)); + out->widen = true; + return true; + } + PyObject* utf16 = PyUnicode_AsEncodedString(value, "utf-16-le", "strict"); + if (!utf16) + return false; + out->holder = utf16; + out->data = (const unsigned char*)PyBytes_AS_STRING(utf16); + out->size = PyBytes_GET_SIZE(utf16); + return true; +} + +bool BcpConvertLowLevelValue(const BcpCol* c, PyObject* value, BcpLowLevelValue* out) +{ + out->isNull = value == Py_None; + if (out->isNull) + return true; + + switch (c->hostType) { + case SQLBIT: + return convert_low_level_bit(value, out); + case SQLINT2: + case SQLINT4: + case SQLINT8: + return convert_low_level_integer(c, value, out); + case SQLFLT4: + case SQLFLT8: + return convert_low_level_float(c, value, out); + case SQLUNIQUEID: + return convert_low_level_uuid(value, out); + case SQLCHARACTER: + return convert_low_level_character(value, out); + case SQLNCHAR: + return convert_low_level_wide(value, out); + case SQLBINARY: + if (PyBytes_Check(value) || PyByteArray_Check(value)) + return convert_low_level_binary(value, out); + PyErr_Format(PyExc_TypeError, "bytes are required for a SQLBINARY BCP column, not %.100s", Py_TYPE(value)->tp_name); + return false; + } + PyErr_SetString(PyExc_TypeError, "unsupported BCP host type"); + return false; +} + +bool BcpWriteLowLevelValue(Connection* cnxn, BcpCol* c, const BcpLowLevelValue& value) +{ + if (value.isNull) + return BcpPutNull(cnxn, c); + if (!c->prefix) + return BcpPutFixed(cnxn, c, value.fixed); + if (value.widen) + return BcpPutWidened(cnxn, c, value.data, value.size); + return BcpPutBytes(cnxn, c, value.data, value.size); +} diff --git a/src/bcp_support.h b/src/bcp_support.h new file mode 100644 index 00000000..ac24c2f8 --- /dev/null +++ b/src/bcp_support.h @@ -0,0 +1,238 @@ +#pragma once + +// SQL Server bulk copy (BCP) support for the low-level Connection.bcp_* methods +// (connection.cpp). Include after pyodbc.h. +// +// The BCP entry points are exported by the Microsoft ODBC driver itself rather than the driver +// manager, so they are resolved from the loaded driver at run time and no SQL Server SDK +// header is needed to build. The constants below match msodbcsql.h and sqlncli.h. + +#ifndef DB_IN +#define DB_IN 1 +#endif +#ifndef SUCCEED +#define SUCCEED 1 +#endif +#ifndef FAIL +#define FAIL 0 +#endif + +// DBINT is a 32-bit signed integer in the driver: LONG on Windows, INT on Linux. It must be +// `int` here, not `long`, which is 8 bytes on LP64 platforms. +typedef int DBINT; + +#ifndef SQL_COPT_SS_BCP +#define SQL_COPT_SS_BCP 1219 +#endif +#ifndef SQL_BCP_ON +#define SQL_BCP_ON 1 +#endif +#ifndef SQL_VARLEN_DATA +#define SQL_VARLEN_DATA (-10) +#endif + +// Host (program variable) data types for bcp_bind. +#ifndef SQLBIT +#define SQLBIT 0x32 +#endif +#ifndef SQLINT2 +#define SQLINT2 0x34 +#endif +#ifndef SQLINT4 +#define SQLINT4 0x38 +#endif +#ifndef SQLINT8 +#define SQLINT8 0x7F +#endif +#ifndef SQLFLT4 +#define SQLFLT4 0x3B +#endif +#ifndef SQLFLT8 +#define SQLFLT8 0x3E +#endif +#ifndef SQLBINARY +#define SQLBINARY 0x2D +#endif +#ifndef SQLUNIQUEID +#define SQLUNIQUEID 0x24 +#endif +#ifndef SQLCHARACTER +#define SQLCHARACTER 0x2F +#endif +#ifndef SQLNCHAR +#define SQLNCHAR 0xEF +#endif + +// bcp_control options. BCPHINTS is the ANSI variant (BCPHINTSA), taking a char* hint list, and +// BCPHINTSW the wide one, taking a SQLWCHAR* list. +#ifndef BCPMAXERRS +#define BCPMAXERRS 1 +#endif +#ifndef BCPKEEPNULLS +#define BCPKEEPNULLS 5 +#endif +#ifndef BCPHINTS +#define BCPHINTS 10 +#endif +#ifndef BCPHINTSW +#define BCPHINTSW 11 +#endif + +struct Connection; + +/** The driver's BCP entry points. */ +struct BcpProcs +{ + SQLRETURN (SQL_API *bcp_initW)(HDBC, const SQLWCHAR*, const SQLWCHAR*, const SQLWCHAR*, int); + SQLRETURN (SQL_API *bcp_bind)(HDBC, const unsigned char*, int, DBINT, const unsigned char*, int, int, int); + SQLRETURN (SQL_API *bcp_collen)(HDBC, DBINT, int); + SQLRETURN (SQL_API *bcp_sendrow)(HDBC); + DBINT (SQL_API *bcp_batch)(HDBC); + DBINT (SQL_API *bcp_done)(HDBC); + SQLRETURN (SQL_API *bcp_control)(HDBC, int, void*); +}; + +/** + * Per-connection BCP state: the resolved entry points and the low-level API session. + * + * `loaded` is false when the driver does not export the BCP API. A session opened by + * Connection.bcp_init stays open until bcp_done. While it is open the connection owns the + * capsule of the bound context, so the buffers the driver reads from cannot be freed under it. + * In autocommit mode the session runs in its own transaction (`ownsTransaction`), committed by + * each batch, so rows sent since the last batch can be discarded rather than committed. + * `rowReady` is set by a successful bcp_setrow and cleared by bcp_sendrow, so a row is never + * sent half converted or twice by mistake. `tableName` and `hints` are the strings given to + * bcp_init and bcp_control, kept until the session ends since the driver may read them later. + */ +struct BcpState +{ + bool loaded; + BcpProcs procs; + bool sessionOpen; + bool ownsTransaction; + bool rowReady; + PyObject* context; + long batchRows; + long unbatchedRows; + SQLWCHAR* tableName; + SQLWCHAR* hints; +}; + +/** + * One bound column: its host type and the buffer the driver reads on each bcp_sendrow. + * + * Variable-length values are laid out as a little-endian length prefix of `prefix` bytes + * followed by the data; a prefix of -1 is NULL. Fixed-width values (prefix 0) carry no + * length, so NULL is signalled with bcp_collen and `wasNull` remembers to undo it. An 8-byte + * prefix is required for (max) columns, where the driver misreads a zero-length prefix, so + * `setsCollen` also passes every value's length to bcp_collen. + */ +struct BcpCol +{ + int ordinal; + int hostType; + int prefix; + bool setsCollen; + DBINT fixedSize; + unsigned char* scratch; + size_t scratchCap; + bool wasNull; +}; + +/** The columns bound by Connection.bcp_bind_columns, held in a capsule. */ +struct BcpCtx +{ + Connection* conn; + int ncols; + BcpCol* cols; +}; + +/** + * Resolves the driver's BCP entry points once per connection. + * + * @return true if the driver exports them; false if not, or on allocation failure (with a + * Python exception set). + */ +bool BcpEnsureLoaded(Connection* cnxn); + +/** Switches the connection's autocommit mode, leaving the diagnostics on the hdbc on failure. */ +bool BcpSetAutocommit(HDBC hdbc, bool on); + +/** Commits or rolls back the connection's transaction, leaving the diagnostics on failure. */ +bool BcpEndTransaction(HDBC hdbc, bool commit); + +/** + * Sizes and allocates a column's buffer. + * + * The caller sets ordinal, hostType, prefix (0 for the fixed-width host types SQLBIT, SQLINT2, + * SQLINT4, SQLINT8, SQLFLT4, SQLFLT8 and SQLUNIQUEID; 4 or 8 otherwise) and setsCollen. + * + * @return false with MemoryError set on failure. + */ +bool BcpAllocColumn(BcpCol* c); + +/** Frees the buffers of an array of columns and the array itself. */ +void BcpFreeColumns(BcpCol* cols, int ncols); + +/** Binds a column's buffer with bcp_bind. On failure the driver diagnostics are on the hdbc. */ +bool BcpBindColumn(Connection* cnxn, BcpCol* c); + +/** + * Sets a column to NULL for the next row. + * + * Like all the BcpPut functions it returns false either with a Python exception set or, for a + * driver failure, with the diagnostics left on the hdbc. + */ +bool BcpPutNull(Connection* cnxn, BcpCol* c); + +/** Copies a fixed-width value (fixedSize bytes) into the column for the next row. */ +bool BcpPutFixed(Connection* cnxn, BcpCol* c, const void* value); + +/** Copies n bytes of variable-length data into the column, growing its buffer as needed. */ +bool BcpPutBytes(Connection* cnxn, BcpCol* c, const void* data, Py_ssize_t n); + +/** + * Widens 8-bit text to UTF-16LE in a SQLNCHAR column, taking each byte as the code point of + * the same value: exact for ASCII and for the data of a 1-byte (Latin-1) str. + */ +bool BcpPutWidened(Connection* cnxn, BcpCol* c, const unsigned char* text, Py_ssize_t n); + +/** + * A low-level API value converted for its column, ready to be written without running any + * Python code. `holder` keeps variable-length data alive: the immutable str or bytes it points + * into, a copy of a bytearray, or the UTF-16 encoding of a str. `widen` marks 8-bit text (an + * ASCII or Latin-1 str) still to be widened for a SQLNCHAR column. + */ +struct BcpLowLevelValue +{ + bool isNull; + unsigned char fixed[16]; + PyObject* holder; + const unsigned char* data; + Py_ssize_t size; + bool widen; + + BcpLowLevelValue() : isNull(true), holder(0), data(0), size(0), widen(false) {} + BcpLowLevelValue(const BcpLowLevelValue&) = delete; + BcpLowLevelValue& operator=(const BcpLowLevelValue&) = delete; + ~BcpLowLevelValue() { Py_XDECREF(holder); } +}; + +/** + * Converts a Python value for a low-level API column of the given host type. This is where + * user code can run (__float__, uuid attributes), so it touches neither the column buffer nor + * the driver: BcpWriteLowLevelValue does that once the caller has checked the session survived. + * + * @return false with a Python exception set for an unsuitable value. + */ +bool BcpConvertLowLevelValue(const BcpCol* c, PyObject* value, BcpLowLevelValue* out); + +/** + * Writes a converted low-level value into its column for the next row. + * + * @return false with a Python exception set, or with the driver diagnostics on the hdbc. + */ +bool BcpWriteLowLevelValue(Connection* cnxn, BcpCol* c, const BcpLowLevelValue& value); + +/** Writes the low `len` bytes of v to dst, least significant first. */ +void write_le(unsigned char* dst, unsigned long long v, int len); diff --git a/src/connection.cpp b/src/connection.cpp index 2850d026..818e55cd 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -16,7 +16,9 @@ #include "pyodbcmodule.h" #include "errors.h" #include "cnxninfo.h" - +#include "bcp_support.h" +#include +#include static char connection_doc[] = "Connection objects manage connections to the database.\n" @@ -360,6 +362,7 @@ PyObject* Connection_New(PyObject* pConnectString, bool fAutoCommit, long timeou cnxn->map_sqltype_to_converter = 0; cnxn->readvar_initsize = 4096; cnxn->compat_diagrec_byte_length = false; + cnxn->bcp = NULL; cnxn->attrs_before = attrs_before_o.Detach(); cnxn->decimal_mode = DECIMAL_MODE_BINARY; @@ -523,6 +526,9 @@ static PyObject* Connection_conv_clear(PyObject* self, PyObject* args) Py_RETURN_NONE; } +static void ReleaseBcpContext(BcpState* state); +static void AbandonBcpSession(Connection* cnxn); + static int Connection_clear(PyObject* self) { // Internal method for closing the connection. (Not called close so it isn't confused with the external close @@ -530,6 +536,11 @@ static int Connection_clear(PyObject* self) Connection* cnxn = (Connection*)self; + // A bulk copy still in progress would otherwise survive SQLDisconnect in the connection + // pool, holding its locks. + if (cnxn->hdbc != SQL_NULL_HANDLE && cnxn->bcp && cnxn->bcp->sessionOpen) + AbandonBcpSession(cnxn); + if (cnxn->hdbc != SQL_NULL_HANDLE) { TRACE("cnxn.clear cnxn=%p hdbc=%d\n", cnxn, cnxn->hdbc); @@ -563,6 +574,14 @@ static int Connection_clear(PyObject* self) Py_XDECREF(cnxn->map_sqltype_to_converter); cnxn->map_sqltype_to_converter = 0; + if (cnxn->bcp) + { + cnxn->bcp->sessionOpen = false; + ReleaseBcpContext(cnxn->bcp); + PyMem_Free(cnxn->bcp); + cnxn->bcp = nullptr; + } + return 0; } @@ -975,7 +994,16 @@ static int Connection_setautocommit(PyObject* self, PyObject* value, void* closu return -1; } - uintptr_t nAutoCommit = PyObject_IsTrue(value) ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF; + const int on = PyObject_IsTrue(value); + if (on < 0 || !Connection_Validate(self)) + return -1; + if (cnxn->bcp && cnxn->bcp->sessionOpen) + { + PyErr_SetString(ProgrammingError, "Cannot change autocommit while a BCP session is open."); + return -1; + } + + uintptr_t nAutoCommit = on ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF; SQLRETURN ret; Py_BEGIN_ALLOW_THREADS ret = SQLSetConnectAttr(cnxn->hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER)nAutoCommit, SQL_IS_UINTEGER); @@ -1663,24 +1691,557 @@ static PyObject* Connection_exit(PyObject* self, PyObject* args) Py_RETURN_NONE; } +/*=======================================================================================*/ +// Low-level SQL Server bulk copy (BCP) API +/*=======================================================================================*/ + +static const char* BCPCTX_CAPSULE = "pyodbc.BCPContext"; + +static void BcpContext_Free(PyObject* cap) +{ + BcpCtx* ctx = (BcpCtx*)PyCapsule_GetPointer(cap, BCPCTX_CAPSULE); + if (!ctx) + return; + BcpFreeColumns(ctx->cols, ctx->ncols); + PyMem_Free(ctx); +} + +/** + * Drops the connection's reference to the bound context and frees the session's table name and + * hints. Called only once the driver no longer reads them: after bcp_done, or after the + * connection is disconnected. + */ +static void ReleaseBcpContext(BcpState* state) +{ + PyMem_Free(state->tableName); + PyMem_Free(state->hints); + state->tableName = state->hints = 0; + if (!state->context) + return; + BcpCtx* ctx = (BcpCtx*)PyCapsule_GetPointer(state->context, BCPCTX_CAPSULE); + if (ctx) + ctx->conn = 0; + Py_CLEAR(state->context); +} + +/** Returns the connection if it is open and uses a driver BCP works with, raising if not. */ +static Connection* ConnectionWithBcp(PyObject* self) +{ + Connection* cnxn = Connection_Validate(self); + if (!cnxn) + return 0; + if (!BcpEnsureLoaded(cnxn)) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_NotImplementedError, "BCP needs the Microsoft ODBC Driver 13 or later for SQL Server."); + return 0; + } + return cnxn; +} + +/** Returns the connection if it also has a BCP session open, raising if not. */ +static Connection* ConnectionWithBcpSession(PyObject* self) +{ + Connection* cnxn = ConnectionWithBcp(self); + if (cnxn && !cnxn->bcp->sessionOpen) { + PyErr_SetString(ProgrammingError, "No BCP session is open; call bcp_init first."); + return 0; + } + return cnxn; +} + +/** Returns the context in `cap` if it is the one bound on the open session, raising if not. */ +static BcpCtx* BoundBcpContext(Connection* cnxn, PyObject* cap) +{ + if (!cap || cap != cnxn->bcp->context) { + PyErr_SetString(PyExc_ValueError, "Not the BCP context bound on this connection's open session."); + return 0; + } + return (BcpCtx*)PyCapsule_GetPointer(cap, BCPCTX_CAPSULE); +} + +/** + * Ends the session's own transaction, if it has one, and restores autocommit. A failed commit + * is raised (unless an exception is already set) and rolled back. + */ +static bool EndBcpTransaction(Connection* cnxn, bool commit) +{ + BcpState* state = cnxn->bcp; + if (!state->ownsTransaction) + return true; + bool ok = BcpEndTransaction(cnxn->hdbc, commit); + if (!ok && commit) { + if (!PyErr_Occurred()) + RaiseErrorFromHandle(cnxn, "SQLEndTran", cnxn->hdbc, SQL_NULL_HANDLE); + BcpEndTransaction(cnxn->hdbc, false); + } + BcpSetAutocommit(cnxn->hdbc, true); + state->ownsTransaction = false; + return ok || !commit; +} + +/** Closes the session with bcp_done and releases its context, raising if that fails. */ +static bool EndBcpSession(Connection* cnxn, DBINT* rows) +{ + BcpState* state = cnxn->bcp; + DBINT n; + Py_BEGIN_ALLOW_THREADS + n = state->procs.bcp_done(cnxn->hdbc); + Py_END_ALLOW_THREADS + bool ok = n >= 0; + if (!ok) + RaiseErrorFromHandle(cnxn, "bcp_done", cnxn->hdbc, SQL_NULL_HANDLE); + if (!EndBcpTransaction(cnxn, ok)) + ok = false; + state->sessionOpen = false; + ReleaseBcpContext(state); + if (rows) + *rows = n; + return ok; +} + +/** + * Closes the session without keeping the rows sent since the last batch, after an error that + * has already been raised or when the connection closes with the session still open. + */ +static void AbandonBcpSession(Connection* cnxn) +{ + BcpState* state = cnxn->bcp; + Py_BEGIN_ALLOW_THREADS + state->procs.bcp_done(cnxn->hdbc); + Py_END_ALLOW_THREADS + EndBcpTransaction(cnxn, false); + state->sessionOpen = false; + ReleaseBcpContext(state); +} + +/** + * Ends the current batch with bcp_batch, committing it in autocommit mode; raises on failure. + * The batch is over either way, so the count of rows towards the next one restarts first. + */ +static bool BatchBcpSession(Connection* cnxn, DBINT* rows) +{ + BcpState* state = cnxn->bcp; + state->unbatchedRows = 0; + DBINT n; + Py_BEGIN_ALLOW_THREADS + n = state->procs.bcp_batch(cnxn->hdbc); + Py_END_ALLOW_THREADS + if (n < 0) { + RaiseErrorFromHandle(cnxn, "bcp_batch", cnxn->hdbc, SQL_NULL_HANDLE); + return false; + } + if (state->ownsTransaction && !BcpEndTransaction(cnxn->hdbc, true)) { + RaiseErrorFromHandle(cnxn, "SQLEndTran", cnxn->hdbc, SQL_NULL_HANDLE); + return false; + } + if (rows) + *rows = n; + return true; +} + +static char bcp_init_doc[] = +"bcp_init(table, direction=DB_IN, batch_rows=0, keep_nulls=False, hints=None, max_errors=0) -> None\n" +"\n" +"Opens a SQL Server bulk copy (BCP) session loading rows into a table. The connection must have\n" +"been opened with attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}. Connection pooling\n" +"matches on the connection string alone, so give BCP connections their own (e.g. a distinct APP=)\n" +"or a pooled connection opened without the attribute may be returned. Bind the columns with\n" +"bcp_bind_columns(), send each row with bcp_setrow() and bcp_sendrow(), and finish with bcp_done().\n" +"In autocommit mode bcp_batch() and bcp_done() commit the rows sent so far; if the connection is\n" +"closed first, the rows sent since the last batch are discarded.\n" +"\n" +"Arguments:\n" +" table : The destination table, named as in T-SQL (e.g. 'dbo.MyTable').\n" +" direction : Must be pyodbc.DB_IN: only loading into a table is supported.\n" +" batch_rows : If positive, bcp_sendrow() calls bcp_batch() after every batch_rows rows.\n" +" keep_nulls : If true, None is stored as NULL even in a column with a DEFAULT, as an INSERT\n" +" would store it; otherwise BCP stores the column's default.\n" +" hints : BCP hints, e.g. 'TABLOCK'. BCP checks CHECK constraints and fires triggers only\n" +" when given 'CHECK_CONSTRAINTS' and 'FIRE_TRIGGERS'. A fired trigger that rolls\n" +" back the load leaves the connection unusable while the session runs in a\n" +" transaction (always, in either commit mode): the driver loses track of it.\n" +" max_errors : If positive, passed to bcp_control(BCPMAXERRS)."; + +/** + * A copy of `s` as NUL-terminated UTF-16 for the driver, freed with PyMem_Free, or null with an + * error raised. A NUL in `s` raises ValueError, since the driver would stop reading there. + */ +static SQLWCHAR* BcpWideCopy(PyObject* s, const char* what) +{ + if (PyUnicode_FindChar(s, 0, 0, PyUnicode_GET_LENGTH(s), 1) != -1) { + PyErr_Format(PyExc_ValueError, "The %s must not contain a NUL character.", what); + return 0; + } + SQLWChar wide(s, ENCSTR_UTF16NE); + if (!wide.isValid()) { + PyErr_Format(PyExc_ValueError, "The %s cannot be encoded as UTF-16.", what); + return 0; + } + const SQLWCHAR* chars = wide; + size_t n = 0; + while (chars[n]) + ++n; + SQLWCHAR* copy = (SQLWCHAR*)PyMem_Malloc((n + 1) * sizeof(SQLWCHAR)); + if (!copy) { + PyErr_NoMemory(); + return 0; + } + memcpy(copy, chars, (n + 1) * sizeof(SQLWCHAR)); + return copy; +} + +static PyObject* Connection_bcp_init(PyObject* self, PyObject* args, PyObject* kwargs) +{ + PyObject* table = 0; + int direction = DB_IN; + long batch_rows = 0; + int keep_nulls = 0; + PyObject* hints = Py_None; + long max_errors = 0; + + static char* kwlist[] = {"table", "direction", "batch_rows", "keep_nulls", "hints", "max_errors", NULL}; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "U|ilpOl", kwlist, + &table, &direction, &batch_rows, &keep_nulls, &hints, &max_errors)) + return 0; + if (direction != DB_IN) { + PyErr_SetString(PyExc_ValueError, "Only DB_IN is supported."); + return 0; + } + if (batch_rows < 0 || max_errors < 0) { + PyErr_SetString(PyExc_ValueError, "batch_rows and max_errors must not be negative."); + return 0; + } + if (hints != Py_None && !PyUnicode_Check(hints)) { + PyErr_SetString(PyExc_TypeError, "hints must be a str or None."); + return 0; + } + + Connection* cnxn = ConnectionWithBcp(self); + if (!cnxn) + return 0; + BcpState* state = cnxn->bcp; + if (state->sessionOpen) { + PyErr_SetString(ProgrammingError, "A BCP session is already open; call bcp_done first."); + return 0; + } + + state->tableName = BcpWideCopy(table, "table name"); + if (!state->tableName) + return 0; + if (hints != Py_None && PyUnicode_GET_LENGTH(hints) > 0 && !(state->hints = BcpWideCopy(hints, "hints"))) { + ReleaseBcpContext(state); + return 0; + } + state->ownsTransaction = cnxn->nAutoCommit == SQL_AUTOCOMMIT_ON; + if (state->ownsTransaction && !BcpSetAutocommit(cnxn->hdbc, false)) { + state->ownsTransaction = false; + ReleaseBcpContext(state); + return RaiseErrorFromHandle(cnxn, "SQLSetConnectAttr", cnxn->hdbc, SQL_NULL_HANDLE); + } + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = state->procs.bcp_initW(cnxn->hdbc, state->tableName, nullptr, nullptr, DB_IN); + Py_END_ALLOW_THREADS + if (rc != SUCCEED) { + RaiseErrorFromHandle(cnxn, "bcp_init", cnxn->hdbc, SQL_NULL_HANDLE); + EndBcpTransaction(cnxn, false); + ReleaseBcpContext(state); + return 0; + } + state->sessionOpen = true; + state->rowReady = false; + state->batchRows = batch_rows; + state->unbatchedRows = 0; + + const char* failed = 0; + if (keep_nulls && state->procs.bcp_control(cnxn->hdbc, BCPKEEPNULLS, (void*)(uintptr_t)1) != SUCCEED) + failed = "bcp_control(BCPKEEPNULLS)"; + else if (max_errors > 0 && state->procs.bcp_control(cnxn->hdbc, BCPMAXERRS, (void*)(uintptr_t)max_errors) != SUCCEED) + failed = "bcp_control(BCPMAXERRS)"; + else if (state->hints && state->procs.bcp_control(cnxn->hdbc, BCPHINTSW, (void*)state->hints) != SUCCEED) + failed = "bcp_control(BCPHINTS)"; + if (failed) { + RaiseErrorFromHandle(cnxn, failed, cnxn->hdbc, SQL_NULL_HANDLE); + AbandonBcpSession(cnxn); + return 0; + } + Py_RETURN_NONE; +} + +static char bcp_bind_columns_doc[] = +"bcp_bind_columns(types) -> BCPContext\n" +"\n" +"Binds one buffer per table column for the open BCP session, in table column order, and returns\n" +"the context to pass to bcp_setrow(). Columns can be bound once per session.\n" +"\n" +"Arguments:\n" +" types : One host type per column. Each takes these Python values (or None for NULL):\n" +" pyodbc.SQLBIT True, False, 0 or 1\n" +" pyodbc.SQLINT2, pyodbc.SQLINT4, pyodbc.SQLINT8 int\n" +" pyodbc.SQLFLT4, pyodbc.SQLFLT8 float\n" +" pyodbc.SQLNCHAR str, sent as UTF-16\n" +" pyodbc.SQLCHARACTER bytes encoded in the client's code page, or ASCII str\n" +" pyodbc.SQLBINARY bytes or bytearray\n" +" pyodbc.SQLUNIQUEID uuid.UUID, or its 16 bytes_le\n" +"\n" +"Usage:\n" +" conn.bcp_init('dbo.MyTable')\n" +" ctx = conn.bcp_bind_columns([pyodbc.SQLINT4, pyodbc.SQLNCHAR])\n" +" for row in rows:\n" +" conn.bcp_setrow(ctx, row)\n" +" conn.bcp_sendrow()\n" +" count = conn.bcp_done()"; + +static bool IsLowLevelHostType(long t, bool* fixed) +{ + *fixed = t == SQLBIT || t == SQLINT2 || t == SQLINT4 || t == SQLINT8 || t == SQLFLT4 || t == SQLFLT8 || t == SQLUNIQUEID; + return *fixed || t == SQLBINARY || t == SQLCHARACTER || t == SQLNCHAR; +} + +static PyObject* Connection_bcp_bind_columns(PyObject* self, PyObject* args, PyObject* kwargs) +{ + PyObject* types = 0; + static char* kwlist[] = {"types", NULL}; + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O", kwlist, &types)) + return 0; + + Connection* cnxn = ConnectionWithBcpSession(self); + if (!cnxn) + return 0; + BcpState* state = cnxn->bcp; + if (state->context) { + PyErr_SetString(ProgrammingError, "The columns of this BCP session are already bound."); + return 0; + } + + Object seq(PySequence_Tuple(types)); + if (!seq.IsValid()) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + PyErr_Clear(); + PyErr_SetString(PyExc_TypeError, "types must be a sequence of BCP host types"); + } + return 0; + } + const Py_ssize_t ncols = PyTuple_GET_SIZE(seq.Get()); + if (ncols <= 0 || ncols > INT_MAX) { + PyErr_SetString(PyExc_ValueError, "types must not be empty"); + return 0; + } + + BcpCtx* ctx = (BcpCtx*)PyMem_Calloc(1, sizeof(BcpCtx)); + if (!ctx) + return PyErr_NoMemory(); + ctx->cols = (BcpCol*)PyMem_Calloc((size_t)ncols, sizeof(BcpCol)); + if (!ctx->cols) { + PyMem_Free(ctx); + return PyErr_NoMemory(); + } + ctx->ncols = (int)ncols; + Object cap(PyCapsule_New(ctx, BCPCTX_CAPSULE, BcpContext_Free)); + if (!cap.IsValid()) { + BcpFreeColumns(ctx->cols, ctx->ncols); + PyMem_Free(ctx); + return 0; + } + + for (int i = 0; i < ctx->ncols; ++i) { + long t = PyLong_AsLong(PyTuple_GET_ITEM(seq.Get(), i)); + if (t == -1 && PyErr_Occurred()) + return 0; + bool fixed; + if (!IsLowLevelHostType(t, &fixed)) { + PyErr_Format(PyExc_ValueError, "Unsupported BCP host type %ld in types[%d].", t, i); + return 0; + } + BcpCol* c = &ctx->cols[i]; + c->ordinal = i + 1; + c->hostType = (int)t; + c->prefix = fixed ? 0 : 8; + c->setsCollen = !fixed; + } + + if (!ConnectionWithBcpSession(self)) + return 0; + if (cnxn->bcp != state || state->context) { + PyErr_SetString(ProgrammingError, "The BCP session changed while its column types were read."); + return 0; + } + for (int i = 0; i < ctx->ncols; ++i) + if (!BcpAllocColumn(&ctx->cols[i])) + return 0; + + for (int i = 0; i < ctx->ncols; ++i) { + if (!BcpBindColumn(cnxn, &ctx->cols[i])) { + RaiseErrorFromHandle(cnxn, "bcp_bind", cnxn->hdbc, SQL_NULL_HANDLE); + state->context = cap.Detach(); + AbandonBcpSession(cnxn); + return 0; + } + } + + ctx->conn = cnxn; + state->context = cap.Get(); + Py_INCREF(state->context); + return cap.Detach(); +} + +static char bcp_setrow_doc[] = +"bcp_setrow(ctx, row) -> None\n" +"\n" +"Converts one row of values into the buffers bound by bcp_bind_columns(); bcp_sendrow() then\n" +"sends it.\n" +"\n" +"Arguments:\n" +" ctx : The context returned by bcp_bind_columns().\n" +" row : A tuple or list with one value per bound column."; + +static PyObject* Connection_bcp_setrow(PyObject* self, PyObject* args) +{ + PyObject* cap = 0; + PyObject* row = 0; + if (!PyArg_ParseTuple(args, "OO", &cap, &row)) + return 0; + + Connection* cnxn = ConnectionWithBcpSession(self); + if (!cnxn) + return 0; + BcpCtx* ctx = BoundBcpContext(cnxn, cap); + if (!ctx) + return 0; + cnxn->bcp->rowReady = false; + + std::unique_ptr values(new (std::nothrow) BcpLowLevelValue[(size_t)ctx->ncols]); + if (!values) + return PyErr_NoMemory(); + for (int i = 0; i < ctx->ncols; ++i) { + if (!(PyTuple_Check(row) || PyList_Check(row)) || PySequence_Fast_GET_SIZE(row) != ctx->ncols) { + PyErr_SetString(PyExc_TypeError, "row must be a tuple or list with one value per bound column"); + return 0; + } + Object cell(PySequence_Fast_GET_ITEM(row, i)); + Py_INCREF(cell.Get()); + if (!BcpConvertLowLevelValue(&ctx->cols[i], cell, &values[(size_t)i])) + return 0; + } + + if (!cnxn->hdbc || !cnxn->bcp || !cnxn->bcp->sessionOpen || cnxn->bcp->context != cap) { + PyErr_SetString(ProgrammingError, "The BCP session changed while the row was being converted."); + return 0; + } + for (int i = 0; i < ctx->ncols; ++i) { + if (!BcpWriteLowLevelValue(cnxn, &ctx->cols[i], values[(size_t)i])) { + if (!PyErr_Occurred()) + RaiseErrorFromHandle(cnxn, "bcp_collen", cnxn->hdbc, SQL_NULL_HANDLE); + return 0; + } + } + cnxn->bcp->rowReady = true; + Py_RETURN_NONE; +} + +static char bcp_sendrow_doc[] = +"bcp_sendrow() -> None\n" +"\n" +"Sends the row prepared by bcp_setrow(), ending a batch if bcp_init's batch_rows is reached.\n" +"Each row needs its own successful bcp_setrow() first."; + +static PyObject* Connection_bcp_sendrow(PyObject* self, PyObject* args) +{ + UNUSED(args); + Connection* cnxn = ConnectionWithBcpSession(self); + if (!cnxn) + return 0; + BcpState* state = cnxn->bcp; + if (!state->context) { + PyErr_SetString(ProgrammingError, "Bind the columns with bcp_bind_columns first."); + return 0; + } + if (!state->rowReady) { + PyErr_SetString(ProgrammingError, "Prepare the row with bcp_setrow first."); + return 0; + } + state->rowReady = false; + + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = state->procs.bcp_sendrow(cnxn->hdbc); + Py_END_ALLOW_THREADS + if (rc != SUCCEED) + return RaiseErrorFromHandle(cnxn, "bcp_sendrow", cnxn->hdbc, SQL_NULL_HANDLE); + + if (state->batchRows > 0 && ++state->unbatchedRows >= state->batchRows && !BatchBcpSession(cnxn, 0)) + return 0; + Py_RETURN_NONE; +} + +static char bcp_batch_doc[] = +"bcp_batch([ctx]) -> int\n" +"\n" +"Ends the current batch: the server stores the rows sent since the last batch, committing them\n" +"in autocommit mode. Returns the number of rows in the batch. The optional ctx is checked\n" +"to be the bound context."; + +static PyObject* Connection_bcp_batch(PyObject* self, PyObject* args) +{ + PyObject* cap = 0; + if (!PyArg_ParseTuple(args, "|O", &cap)) + return 0; + + Connection* cnxn = ConnectionWithBcpSession(self); + if (!cnxn) + return 0; + if (cap && cap != Py_None && !BoundBcpContext(cnxn, cap)) + return 0; + + DBINT rows = 0; + if (!BatchBcpSession(cnxn, &rows)) + return 0; + return PyLong_FromLong((long)rows); +} + +static char bcp_done_doc[] = +"bcp_done() -> int\n" +"\n" +"Ends the BCP session, storing the rows sent since the last batch, and returns their number.\n" +"In autocommit mode they are committed; in manual-commit mode they join the open transaction."; + +static PyObject* Connection_bcp_done(PyObject* self, PyObject* args) +{ + UNUSED(args); + Connection* cnxn = ConnectionWithBcpSession(self); + if (!cnxn) + return 0; + DBINT rows = 0; + if (!EndBcpSession(cnxn, &rows)) + return 0; + return PyLong_FromLong((long)rows); +} + static struct PyMethodDef Connection_methods[] = { - { "cursor", Connection_cursor, METH_NOARGS, cursor_doc }, - { "close", Connection_close, METH_NOARGS, close_doc }, - { "execute", Connection_execute, METH_VARARGS, execute_doc }, - { "commit", Connection_commit, METH_NOARGS, commit_doc }, - { "rollback", Connection_rollback, METH_NOARGS, rollback_doc }, - { "getinfo", Connection_getinfo, METH_VARARGS, getinfo_doc }, - { "add_output_converter", Connection_conv_add, METH_VARARGS, conv_add_doc }, - { "remove_output_converter", Connection_conv_remove, METH_VARARGS, conv_remove_doc }, - { "get_output_converter", Connection_conv_get, METH_VARARGS, conv_get_doc }, - { "clear_output_converters", Connection_conv_clear, METH_NOARGS, conv_clear_doc }, + { "cursor", Connection_cursor, METH_NOARGS, cursor_doc }, + { "close", Connection_close, METH_NOARGS, close_doc }, + { "execute", Connection_execute, METH_VARARGS, execute_doc }, + { "commit", Connection_commit, METH_NOARGS, commit_doc }, + { "rollback", Connection_rollback, METH_NOARGS, rollback_doc }, + { "getinfo", Connection_getinfo, METH_VARARGS, getinfo_doc }, + { "add_output_converter", Connection_conv_add, METH_VARARGS, conv_add_doc }, + { "remove_output_converter", Connection_conv_remove, METH_VARARGS, conv_remove_doc }, + { "get_output_converter", Connection_conv_get, METH_VARARGS, conv_get_doc }, + { "clear_output_converters", Connection_conv_clear, METH_NOARGS, conv_clear_doc }, { "setdecoding", (PyCFunction)Connection_setdecoding, METH_VARARGS|METH_KEYWORDS, setdecoding_doc }, { "setencoding", (PyCFunction)Connection_setencoding, METH_VARARGS|METH_KEYWORDS, 0 }, { "set_attr", Connection_set_attr, METH_VARARGS, set_attr_doc }, { "__enter__", Connection_enter, METH_NOARGS, enter_doc }, { "__exit__", Connection_exit, METH_VARARGS, exit_doc }, + { "bcp_init", (PyCFunction)Connection_bcp_init, METH_VARARGS|METH_KEYWORDS, bcp_init_doc }, + { "bcp_bind_columns", (PyCFunction)Connection_bcp_bind_columns, METH_VARARGS|METH_KEYWORDS, bcp_bind_columns_doc }, + { "bcp_setrow", Connection_bcp_setrow, METH_VARARGS, bcp_setrow_doc }, + { "bcp_sendrow", Connection_bcp_sendrow, METH_NOARGS, bcp_sendrow_doc }, + { "bcp_batch", Connection_bcp_batch, METH_VARARGS, bcp_batch_doc }, + { "bcp_done", Connection_bcp_done, METH_NOARGS, bcp_done_doc }, + { 0, 0, 0, 0 } }; diff --git a/src/connection.h b/src/connection.h index 962c18de..d1951d54 100644 --- a/src/connection.h +++ b/src/connection.h @@ -12,6 +12,8 @@ #ifndef CONNECTION_H #define CONNECTION_H +struct BcpState; + struct Cursor; extern PyTypeObject ConnectionType; @@ -47,6 +49,9 @@ struct Connection char odbc_major; char odbc_minor; + // SQL Server bulk copy (BCP) state, allocated the first time BCP is used (see bcp_support.h). + BcpState* bcp; + // The escape character from SQLGetInfo. This is not initialized until requested, so this may be zero! PyObject* searchescape; diff --git a/src/pyodbc.pyi b/src/pyodbc.pyi index a064b3e9..37b9ef65 100644 --- a/src/pyodbc.pyi +++ b/src/pyodbc.pyi @@ -129,6 +129,22 @@ SQL_OJ_NOT_ORDERED: int SQL_OJ_INNER: int SQL_OJ_ALL_COMPARISON_OPS: int +# SQL Server bulk copy (BCP): the connection attribute that enables it, and the host types +# for Connection.bcp_bind_columns +SQL_COPT_SS_BCP: int +SQL_BCP_ON: int +DB_IN: int +SQLBIT: int +SQLINT2: int +SQLINT4: int +SQLINT8: int +SQLFLT4: int +SQLFLT8: int +SQLBINARY: int +SQLUNIQUEID: int +SQLCHARACTER: int +SQLNCHAR: int + # other ODBC database constants SQL_SCOPE_CURROW: int SQL_SCOPE_TRANSACTION: int @@ -581,6 +597,45 @@ class Connection: """Close the connection. Any uncommitted SQL statements will be rolled back.""" ... + def bcp_init(self, table: str, direction: int = ..., batch_rows: int = 0, + keep_nulls: bool = False, hints: str | None = None, max_errors: int = 0) -> None: + """Open a SQL Server bulk copy (BCP) session loading rows into `table`. The + connection must have been opened with + attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}; connection pooling matches + on the connection string alone, so give BCP connections their own (e.g. a distinct + APP=). direction must be pyodbc.DB_IN. If batch_rows is positive, bcp_sendrow() ends + a batch every batch_rows rows. keep_nulls stores None as NULL in columns with a + DEFAULT, and hints passes BCP hints such as 'TABLOCK' or + 'CHECK_CONSTRAINTS,FIRE_TRIGGERS'. In autocommit mode bcp_batch() and bcp_done() + commit; closing the connection first discards the rows sent since the last batch.""" + ... + + def bcp_bind_columns(self, types: Sequence[int]) -> Any: + """Bind one buffer per table column, in table order, for the open BCP session and + return the context for bcp_setrow(). Each type is one of pyodbc.SQLBIT, SQLINT2, + SQLINT4, SQLINT8, SQLFLT4, SQLFLT8, SQLNCHAR (str), SQLCHARACTER (bytes in the client + code page, or ASCII str), SQLBINARY or SQLUNIQUEID.""" + ... + + def bcp_setrow(self, ctx: Any, row: tuple[Any, ...] | list[Any]) -> None: + """Convert one row, with a value (or None) per bound column, into the bound buffers.""" + ... + + def bcp_sendrow(self) -> None: + """Send the row prepared by bcp_setrow(); each row needs its own bcp_setrow().""" + ... + + def bcp_batch(self, ctx: Any = None) -> int: + """End the current batch, storing the rows sent since the last one, and return their + number.""" + ... + + def bcp_done(self) -> int: + """End the BCP session, storing the rows sent since the last batch, and return their + number. In autocommit mode they are committed; in manual-commit mode they join the + open transaction.""" + ... + class Cursor: """The class representing database cursors. Cursors are vehicles for executing SQL diff --git a/src/pyodbcmodule.cpp b/src/pyodbcmodule.cpp index 6221694a..df91ce7b 100644 --- a/src/pyodbcmodule.cpp +++ b/src/pyodbcmodule.cpp @@ -21,6 +21,7 @@ #include "params.h" #include "dbspecific.h" #include "decimal.h" +#include "bcp_support.h" #include #include @@ -1241,6 +1242,21 @@ static const ConstantDef aConstants[] = { MAKECONST(SQL_OJ_NOT_ORDERED), MAKECONST(SQL_OJ_INNER), MAKECONST(SQL_OJ_ALL_COMPARISON_OPS), + + // SQL Server bulk copy (BCP) + MAKECONST(SQL_COPT_SS_BCP), + MAKECONST(SQL_BCP_ON), + MAKECONST(DB_IN), + MAKECONST(SQLBIT), + MAKECONST(SQLINT2), + MAKECONST(SQLINT4), + MAKECONST(SQLINT8), + MAKECONST(SQLFLT4), + MAKECONST(SQLFLT8), + MAKECONST(SQLBINARY), + MAKECONST(SQLUNIQUEID), + MAKECONST(SQLCHARACTER), + MAKECONST(SQLNCHAR), }; diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index ada25629..3fe0f308 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -8,7 +8,7 @@ import random import re import uuid -from collections.abc import Iterator +from collections.abc import Callable, Iterator from decimal import Decimal from datetime import date, time, datetime from functools import lru_cache @@ -39,6 +39,7 @@ def connect(autocommit=False, attrs_before=None): DRIVER_VERSION = tuple(int(n) for n in connect().getinfo(pyodbc.SQL_DRIVER_VER).split(".")) IS_FREETDS = bool(re.search(r'(tsodbc|tdsodbc)', DRIVER, flags=re.IGNORECASE)) IS_MSODBCSQL = bool(re.search(r'(msodbcsql|sqlncli|sqlsrv32\.dll)', DRIVER, re.IGNORECASE)) +IS_BCP_DRIVER = bool(re.search(r'msodbcsql', DRIVER, re.I)) and DRIVER_VERSION[0] >= 13 def _get_sqlserver_year(): @@ -81,6 +82,33 @@ def cursor() -> Iterator[pyodbc.Cursor]: cnxn.close() +# The bulk copy (BCP) API needs a connection opened with SQL_COPT_SS_BCP. The connection pool +# matches on the connection string, so BCP connections get their own APP name; otherwise a +# pooled connection opened without the attribute could be handed back. +BCP_CNXNSTR = CNXNSTR + ';APP=pyodbc-bcp-tests' + + +def bcp_connect(autocommit=True): + return pyodbc.connect(BCP_CNXNSTR, autocommit=autocommit, + attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}) + + +@pytest.fixture +def bcp_cursor() -> Iterator[pyodbc.Cursor]: + cnxn = bcp_connect() + cur = cnxn.cursor() + + cur.execute("set lock_timeout 30000") + cur.execute("drop table if exists t1") + cur.execute("drop table if exists t2") + + yield cur + + if not cnxn.closed: + cur.close() + cnxn.close() + + def test_text(cursor: pyodbc.Cursor): _test_vartype(cursor, 'text') @@ -1673,6 +1701,245 @@ def test_emoticons_as_literal(cursor: pyodbc.Cursor): assert result == v +_BCP_SKIP = 'BCP requires the Microsoft ODBC Driver 13 or later for SQL Server' + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_low_level_api(bcp_cursor: pyodbc.Cursor): + """The Connection.bcp_* methods load every host type, with NULLs, and report row counts.""" + cur = bcp_cursor + cur.execute(""" + create table t1(i2 smallint, i4 int, i8 bigint, f4 real, f8 float, b bit, + n nvarchar(max), c varchar(20), v varbinary(20), u uniqueidentifier) + """) + cnxn = cur.connection + types = [pyodbc.SQLINT2, pyodbc.SQLINT4, pyodbc.SQLINT8, pyodbc.SQLFLT4, pyodbc.SQLFLT8, + pyodbc.SQLBIT, pyodbc.SQLNCHAR, pyodbc.SQLCHARACTER, pyodbc.SQLBINARY, + pyodbc.SQLUNIQUEID] + text = "Zürich 東京 \U0001D518" + rows = [ + (1, 2, 2**40, 1.5, 0.1, True, text, "abc", b"\x00\xff", uuid.UUID(int=1)), + (None,) * 10, + (-1, -2, -3, -0.5, 1e300, False, "", b"xyz", bytearray(), uuid.UUID(int=2).bytes_le), + ] + cnxn.bcp_init("t1", keep_nulls=True) + ctx = cnxn.bcp_bind_columns(types) + for row in rows[:2]: + cnxn.bcp_setrow(ctx, row) + cnxn.bcp_sendrow() + assert cnxn.bcp_batch(ctx) == 2 + with bcp_connect() as observer: + assert observer.execute("select count(*) from t1").fetchval() == 2 + cnxn.bcp_setrow(ctx, list(rows[2])) + cnxn.bcp_sendrow() + assert cnxn.bcp_done() == 1 + + stored = [tuple(r) for r in cur.execute("select * from t1")] + assert stored[0] == (1, 2, 2**40, 1.5, 0.1, True, text, "abc", b"\x00\xff", + "00000000-0000-0000-0000-000000000001") + assert stored[1] == (None,) * 10 + assert stored[2] == (-1, -2, -3, -0.5, 1e300, False, "", "xyz", b"", + "00000000-0000-0000-0000-000000000002") + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_low_level_api_manual_commit(bcp_cursor: pyodbc.Cursor): + """In manual-commit mode a low-level session's rows join the open transaction.""" + bcp_cursor.execute("create table t1(id int)") + cnxn = bcp_connect(autocommit=False) + try: + cnxn.bcp_init("t1") + ctx = cnxn.bcp_bind_columns([pyodbc.SQLINT4]) + for i in (1, 2): + cnxn.bcp_setrow(ctx, (i,)) + cnxn.bcp_sendrow() + assert cnxn.bcp_done() == 2 + assert cnxn.execute("select count(*) from t1").fetchval() == 2 + cnxn.rollback() + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + finally: + cnxn.close() + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_low_level_api_misuse(bcp_cursor: pyodbc.Cursor): + """Misuse of the Connection.bcp_* methods raises instead of corrupting data or memory.""" + cur = bcp_cursor + cur.execute("create table t1(c varchar(10), b bit)") + cnxn = cur.connection + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_sendrow() + with pytest.raises(ValueError): + cnxn.bcp_init("t1", direction=2) + + cnxn.bcp_init("t1") + with pytest.raises(ValueError): + cnxn.bcp_bind_columns([12345]) + ctx = cnxn.bcp_bind_columns([pyodbc.SQLCHARACTER, pyodbc.SQLBIT]) + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_bind_columns([pyodbc.SQLCHARACTER, pyodbc.SQLBIT]) + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_sendrow() + cnxn.bcp_setrow(ctx, ("z", False)) + with pytest.raises(ValueError): + cnxn.bcp_setrow(ctx, ("é", True)) + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_sendrow() + with pytest.raises(ValueError): + cnxn.bcp_setrow(ctx, ("a", 5)) + with pytest.raises(TypeError): + cnxn.bcp_setrow(ctx, ("a",)) + with pytest.raises(pyodbc.ProgrammingError): + cnxn.autocommit = False + cnxn.bcp_setrow(ctx, ("a", True)) + del ctx + gc.collect() + cnxn.bcp_sendrow() + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_sendrow() + assert cnxn.bcp_done() == 1 + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_done() + + other = bcp_connect() + other.bcp_init("t1") + stale = other.bcp_bind_columns([pyodbc.SQLCHARACTER, pyodbc.SQLBIT]) + cnxn.bcp_init("t1") + with pytest.raises(ValueError): + cnxn.bcp_setrow(stale, ("x", True)) + cnxn.bcp_done() + other.bcp_setrow(stale, ("b", False)) + other.bcp_sendrow() + other.close() + with pytest.raises(pyodbc.ProgrammingError): + other.bcp_setrow(stale, ("c", True)) + cur.execute("set lock_timeout 5000") + assert cur.execute("select count(*) from t1").fetchval() == 1 + + +class _ClosesConnection: + """A value whose conversion closes a connection, as a hostile __float__ might.""" + + def __init__(self, cnxn: pyodbc.Connection) -> None: + self.cnxn = cnxn + + def __float__(self) -> float: + self.cnxn.close() + return 1.0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_conversion_that_closes_the_connection(bcp_cursor: pyodbc.Cursor): + """ + A value whose conversion closes the connection mid-row raises ProgrammingError instead of + using the connection's freed state. + """ + bcp_cursor.execute("create table t1(f float, s nvarchar(10))") + victim = bcp_connect() + victim.bcp_init("t1") + ctx = victim.bcp_bind_columns([pyodbc.SQLFLT8, pyodbc.SQLNCHAR]) + victim.bcp_setrow(ctx, (None, "first")) + with pytest.raises(pyodbc.ProgrammingError): + victim.bcp_setrow(ctx, (_ClosesConnection(victim), "second")) + assert victim.closed + + +class _HostType: + """A host type whose __index__ runs `action` first, as a hostile int-like value might.""" + + def __init__(self, host_type: int, action: Callable[[], object]) -> None: + self.host_type = host_type + self.action = action + + def __index__(self) -> int: + self.action() + return self.host_type + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_bind_columns_reads_its_types_once(bcp_cursor: pyodbc.Cursor): + """ + bcp_bind_columns binds the types it was given even when reading one empties the list, and + raises when reading one closes the connection. + """ + bcp_cursor.execute("create table t1(a int, b int)") + cnxn = bcp_connect() + types: list = [None, pyodbc.SQLINT4] + types[0] = _HostType(pyodbc.SQLINT4, types.clear) + cnxn.bcp_init("t1") + ctx = cnxn.bcp_bind_columns(types) + cnxn.bcp_setrow(ctx, (1, 2)) + cnxn.bcp_sendrow() + assert cnxn.bcp_done() == 1 + + cnxn.bcp_init("t1") + with pytest.raises(pyodbc.ProgrammingError): + cnxn.bcp_bind_columns([_HostType(pyodbc.SQLINT4, cnxn.close), pyodbc.SQLINT4]) + assert cnxn.closed + assert [tuple(row) for row in bcp_cursor.execute("select a, b from t1")] == [(1, 2)] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_autocommit_is_checked_after_its_value(bcp_cursor: pyodbc.Cursor): + """Setting autocommit to a value whose truth test opens a BCP session raises.""" + bcp_cursor.execute("create table t1(a int)") + cnxn = bcp_connect() + + class OpensSession: + def __bool__(self) -> bool: + cnxn.bcp_init("t1") + return False + + with pytest.raises(pyodbc.ProgrammingError): + cnxn.autocommit = OpensSession() + assert cnxn.autocommit + cnxn.bcp_done() + cnxn.close() + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_init_table_name_and_hints(bcp_cursor: pyodbc.Cursor): + """ + A table name or hints with a NUL raise rather than reach the driver cut short, and hints + naming a non-ASCII column reach the server intact: rows out of an ORDER hint's order fail. + """ + cur = bcp_cursor + cur.execute("create table t1(Größe int primary key)") + cnxn = cur.connection + with pytest.raises(ValueError): + cnxn.bcp_init("t1\x00other") + with pytest.raises(ValueError): + cnxn.bcp_init("t1", hints="TABLOCK\x00") + for rows in ((1, 2), (4, 3)): + cnxn.bcp_init("t1", hints="ORDER([Größe] ASC)") + ctx = cnxn.bcp_bind_columns([pyodbc.SQLINT4]) + for i in rows: + cnxn.bcp_setrow(ctx, (i,)) + cnxn.bcp_sendrow() + if rows == (1, 2): + assert cnxn.bcp_done() == 2 + else: + with pytest.raises(pyodbc.ProgrammingError, match="sorted"): + cnxn.bcp_done() + assert [row[0] for row in cur.execute("select Größe from t1 order by 1")] == [1, 2] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_low_level_api_batch_rows(bcp_cursor: pyodbc.Cursor): + """bcp_init's batch_rows ends a batch every batch_rows rows, and a failing batch raises.""" + cur = bcp_cursor + cur.execute("create table t1(id int primary key)") + cnxn = cur.connection + cnxn.bcp_init("t1", batch_rows=2) + ctx = cnxn.bcp_bind_columns([pyodbc.SQLINT4]) + with pytest.raises(pyodbc.IntegrityError): + for i in (1, 2, 3, 3): + cnxn.bcp_setrow(ctx, (i,)) + cnxn.bcp_sendrow() + cnxn.bcp_done() + assert [r[0] for r in cur.execute("select id from t1 order by id")] == [1, 2] + + def _test_tvp(cursor: pyodbc.Cursor, diff_schema): # Test table value parameters (TVP). I like the explanation here: # From 7f8952fa297986553ee0b0d7814a3dc375d9d975 Mon Sep 17 00:00:00 2001 From: Pat Buxton Date: Wed, 3 Jun 2026 08:14:59 +0100 Subject: [PATCH 22/22] Add an optional SQL Server BCP fast path for fast_executemany Adds an optional bulk-copy (BCP) path for Cursor.executemany with fast_executemany against SQL Server, built on the driver loader and column buffers of the previous commit. When enabled, an INSERT of one parameterized VALUES row is carried out with the SQL Server bulk-copy API instead of parameter arrays, which is much faster for large loads, without the caller having to change code or write data files. The path is an optimisation only: it stores exactly what the plain fast_executemany path stores, and anything it cannot reproduce is left to that path. Usage (SQL Server with Microsoft ODBC Driver 13 or later): - open the connection with attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON} - cursor.fast_executemany = True - cursor.use_bcp_fast = True - optional: cursor.bcp_batch_rows (rows per batch) cursor.bcp_tablock (pass the TABLOCK hint) After a BCP load, cursor.rowcount is the number of rows copied. How a call is decided, all before bcp_init (src/bcp_executemany.cpp): - The statement must be INSERT [INTO] [[db.]schema.]table [(columns)] VALUES (?, ...) with nothing else: TOP, hints, OUTPUT, other sources, literals, expressions, several rows, further statements, quoted or undelimited reserved-word identifiers fall back. - The connection must use Microsoft ODBC Driver 13 or later with SQL_COPT_SS_BCP on; a pooled connection opened without it falls back rather than failing. - The destination's columns come from the catalog views of its own database (tempdb for temporary tables), so values map to columns as the INSERT would: a column list leaves the unlisted columns to the server (identity, computed, DEFAULT, NULL), names folding case only where the database compares identifiers ignoring case, and a positional INSERT skips identity and computed columns. A table with an enabled INSERT trigger falls back: a trigger that rolls back a bulk copy run inside a transaction leaves the driver unable to use the connection. - Every row is scanned once. Each column gets a host type from its destination type and the Python types it holds, only for pairings whose driver conversion stores what the plain path stores; other pairings, other types, malformed rows and values longer than their column (which the plain path rejects, or for numbers in narrow text columns truncates) fall back. Text goes as UTF-16 (SQLNCHAR), since the driver reads SQLCHARACTER data in the client's ANSI code page; text for a char or varchar column with a multi-byte collation falls back when its encoded bytes could exceed the column, which the server rejects but the driver quietly cuts short. Drivers before 17.4 send text for a UTF-8 collation as bytes the server rejects, so with them such columns take only ASCII text. Decimals go as exact text with every digit, whatever the thread's decimal context, as the plain path has sent them since 5.4.0. One the plain path's SQL_NUMERIC_STRUCT cannot hold raises as that path does, before it is formatted, and a Decimal subclass falls back, since the plain path reads its as_tuple rather than its __format__. Dates and times are formatted to the destination's precision with the plain path's rounding, since the driver rejects excess digits and does not carry datetime rounding past midnight. Conversions like these, which the path does itself, are in src/bcp_convert.cpp. uniqueidentifier columns take uuid.UUID values and strings in the canonical 36-character form, the only ones the plain path stores, as their 16 bytes. As SQLAlchemy binds dates and times for SQL Server, date columns also take datetimes whose hours, minutes and seconds are zero, and time columns HH:MM:SS[.fraction] text with no more digits than their scale; the plain path rejects other values of those kinds there. - setinputsizes entries are honoured. Under an entry the plain path sends each value as the entry's SQL type and the server converts it to the column's, so BCP sends what that conversion stores, for str under (SQL_WVARCHAR, n, 0), bool under SQL_BIT, int under SQL_BIGINT, float under SQL_DOUBLE, Decimal under (SQL_NUMERIC or SQL_DECIMAL, p, s), datetime and date under (SQL_TYPE_TIMESTAMP, 27, 7) and date under SQL_TYPE_DATE. Timestamps round half up from seven digits (datetime to its nearest 1/300 s tick). Decimals round half away from zero into decimal and money, truncate into integers, and raise as the plain path does for more places than the entry's scale. Doubles go into decimal as their exact binary value rounded half away from zero, into integers truncated, and into real rounded with subnormals kept. A number stores 1 in a bit column unless it is zero. Text goes into a char or varchar column only when the column's code page holds every character exactly, as the server's substitutes for the rest differ from the driver's best-fit ones. The server converts even NULLs from the entry's type, so a column of NULLs takes an nvarchar entry into anything but a binary column, and other entries only where their own values may go. None entries keep the rules above; other entries and pairings fall back. - datetimeoffset is the one deliberate exception to matching the plain path, whose driver gives a value the client machine's local offset for its date: BCP stores what a user would expect, an aware datetime with its own offset and a naive one or a date at +00:00, and raises for an offset SQL Server cannot hold. Loading: - KEEPNULLS and the CHECK_CONSTRAINTS and FIRE_TRIGGERS hints make BCP store what the INSERT would: explicit NULLs stay NULL, constraints are checked and triggers fire. - A failure once rows are streaming rolls back everything the call sent and raises: the load runs in its own transaction in autocommit mode, and after a savepoint (set in the same round trip as the catalog query) in manual-commit mode. With bcp_batch_rows, each completed batch is committed in autocommit mode and only the failing batch is discarded. - Driver diagnostics are read before bcp_done, which clears them, and bcp_batch failures (-1) are detected. - (max) columns use an 8-byte length prefix plus bcp_collen, because the driver misreads a zero-length 8-byte prefix; an empty string goes to char(n) as a space, because the driver repeats the previous value there. Tests in tests/sqlserver_test.py compare BCP with the plain path across every allowed pairing of value and column type, except text, ntext and image, which the plain path sizes from their 2 GB column size and cannot load on 32-bit Python, so they are checked against the values sent. With setinputsizes they compare both paths for every supported entry and column pairing, with edge cases and a seeded random load, check from cursor.rowcount that BCP ran, and cover the entries it declines and the values both paths reject. They also cover older drivers falling back, the other fall backs, statement shapes, column mapping, table names, INSERT semantics, rollback in both commit modes, a conversion that closes the connection or the cursor mid-load, and a row changed while it is being sent. utils/bcp_benchmark.py is a standalone benchmark. Co-Authored-By: Claude Opus 4.8 (1M context) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lyo1SXh7BDrSf1BctKfCrz --- src/bcp_convert.cpp | 478 +++++++++++ src/bcp_convert.h | 122 +++ src/bcp_executemany.cpp | 1710 +++++++++++++++++++++++++++++++++++++++ src/bcp_support.cpp | 565 ++++++++++++- src/bcp_support.h | 125 ++- src/connection.cpp | 4 + src/cursor.cpp | 23 + src/cursor.h | 10 + src/pyodbc.pyi | 35 + src/pyodbcmodule.cpp | 1 + tests/sqlserver_test.py | 1310 +++++++++++++++++++++++++++++- utils/bcp_benchmark.py | 109 +++ 12 files changed, 4478 insertions(+), 14 deletions(-) create mode 100644 src/bcp_convert.cpp create mode 100644 src/bcp_convert.h create mode 100644 src/bcp_executemany.cpp create mode 100644 utils/bcp_benchmark.py diff --git a/src/bcp_convert.cpp b/src/bcp_convert.cpp new file mode 100644 index 00000000..80b43707 --- /dev/null +++ b/src/bcp_convert.cpp @@ -0,0 +1,478 @@ +// Value conversions for the SQL Server bulk copy (BCP) fast path; see bcp_convert.h. + +#include "pyodbc.h" +#include "wrapper.h" +#include "textenc.h" +#include "connection.h" +#include "pyodbcmodule.h" +#include "errors.h" +#include "bcp_convert.h" +#include +#include + +void BcpConvert_init() +{ + PyDateTime_IMPORT; +} + +/*=======================================================================================*/ +// Dates and times, shaped as the plain fast path stores them +/*=======================================================================================*/ + +/** A wall-clock date and time; any tzinfo is ignored, as the plain fast path ignores it. */ +struct CivilTime +{ + int year, month, day, hour, minute, second, micro; +}; + +static long long days_from_civil(long long y, unsigned m, unsigned d) +{ + y -= m <= 2; + const long long era = (y >= 0 ? y : y - 399) / 400; + const unsigned yoe = (unsigned)(y - era * 400); + const unsigned doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return era * 146097 + (long long)doe - 719468; +} + +static void civil_from_days(long long z, CivilTime& t) +{ + z += 719468; + const long long era = (z >= 0 ? z : z - 146096) / 146097; + const unsigned doe = (unsigned)(z - era * 146097); + const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + const unsigned mp = (5 * doy + 2) / 153; + t.day = (int)(doy - (153 * mp + 2) / 5 + 1); + t.month = (int)(mp < 10 ? mp + 3 : mp - 9); + t.year = (int)((long long)yoe + era * 400 + (t.month <= 2)); +} + +/** Adds up to a day's worth of seconds, carrying into the date. */ +static void add_seconds(CivilTime& t, int seconds) +{ + int sod = t.hour * 3600 + t.minute * 60 + t.second + seconds; + if (sod >= 86400) { + civil_from_days(days_from_civil(t.year, (unsigned)t.month, (unsigned)t.day) + sod / 86400, t); + sod %= 86400; + } + t.hour = sod / 3600; + t.minute = (sod / 60) % 60; + t.second = sod % 60; +} + +static CivilTime civil_of(PyObject* cell, unsigned cls) +{ + CivilTime t = {1900, 1, 1, 0, 0, 0, 0}; + if (cls != VAL_TIME) { + t.year = PyDateTime_GET_YEAR(cell); + t.month = PyDateTime_GET_MONTH(cell); + t.day = PyDateTime_GET_DAY(cell); + } + if (cls == VAL_DATETIME) { + t.hour = PyDateTime_DATE_GET_HOUR(cell); + t.minute = PyDateTime_DATE_GET_MINUTE(cell); + t.second = PyDateTime_DATE_GET_SECOND(cell); + t.micro = PyDateTime_DATE_GET_MICROSECOND(cell); + } else if (cls == VAL_TIME) { + t.hour = PyDateTime_TIME_GET_HOUR(cell); + t.minute = PyDateTime_TIME_GET_MINUTE(cell); + t.second = PyDateTime_TIME_GET_SECOND(cell); + t.micro = PyDateTime_TIME_GET_MICROSECOND(cell); + } + return t; +} + +/** + * The seconds fraction in units of `digits` digits (at most 7), from the 100ns ticks of + * datetime2(7): truncated, as the plain path sends a value without an entry, or rounded half up, + * as the server converts a timestamp entry. Rounding carries into the seconds, except in the + * last second the type holds (of the day for time, of 9999-12-31 otherwise), where the server + * truncates instead. + */ +static int fraction_units(CivilTime& t, int digits, bool rounded, bool withinDay) +{ + static const int ticksPerUnit[8] = { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1 }; + const int unit = ticksPerUnit[digits > 7 ? 7 : digits]; + const int ticks = t.micro * 10; + if (!rounded) + return ticks / unit; + const int units = (ticks + unit / 2) / unit; + if (units * unit < 10000000) + return units; + const bool lastSecond = t.hour == 23 && t.minute == 59 && t.second == 59 && + (withinDay || (t.year == 9999 && t.month == 12 && t.day == 31)); + if (lastSecond) + return ticks / unit; + add_seconds(t, 1); + return 0; +} + +/** Appends a seconds fraction of `digits` digits, or nothing for none. */ +static int format_fraction(char* buf, size_t cap, int units, int digits) +{ + return digits > 0 ? snprintf(buf, cap, ".%0*d", digits, units) : 0; +} + +/** + * Appends the UTC offset a datetimeoffset value keeps, as a user would expect: an aware value's + * own offset, and +00:00 for a naive value or a date, which is SQL Server's rule for a value + * without one. (The plain fast path differs here: the driver drops the tzinfo and applies the + * client machine's local offset for the date.) + * + * @return The characters written, or -1 with an exception set: ValueError for an offset SQL + * Server cannot hold (not whole minutes, or beyond 14 hours), TypeError for a + * utcoffset() that returns something other than a timedelta or None. + */ +static int format_offset(char* buf, size_t cap, PyObject* cell, unsigned cls) +{ + long minutes = 0; + if (cls == VAL_DATETIME && PyDateTime_DATE_GET_TZINFO(cell) != Py_None) { + Object delta(PyObject_CallMethod(cell, "utcoffset", NULL)); + if (!delta.IsValid()) + return -1; + if (delta.Get() != Py_None) { + if (!PyDelta_Check(delta.Get())) { + PyErr_Format(PyExc_TypeError, "utcoffset() returned %.100s, not a timedelta", Py_TYPE(delta.Get())->tp_name); + return -1; + } + const long long seconds = PyDateTime_DELTA_GET_DAYS(delta.Get()) * 86400LL + PyDateTime_DELTA_GET_SECONDS(delta.Get()); + if (PyDateTime_DELTA_GET_MICROSECONDS(delta.Get()) != 0 || seconds % 60 != 0 || llabs(seconds) > 14 * 3600) { + PyErr_SetString(PyExc_ValueError, "datetimeoffset offsets must be whole minutes within 14 hours"); + return -1; + } + minutes = (int)(seconds / 60); + } + } + return snprintf(buf, cap, " %c%02ld:%02ld", minutes < 0 ? '-' : '+', labs(minutes) / 60, labs(minutes) % 60); +} + +/** + * Without an entry, datetime2, datetimeoffset and time keep the destination's digits of the + * fraction, truncated; datetime truncates to milliseconds then rounds to its 1/300 s tick. Under + * a timestamp entry the server converts from all seven digits instead: datetime2, datetimeoffset + * and time round half up (see fraction_units), and datetime rounds to the nearest tick. Either + * way smalldatetime rounds up from 30 seconds, and a datetime that would round past its maximum + * stores the maximum, as the server clamps it. The driver's own conversion rejects excess + * digits, and does not carry datetime rounding past midnight, hence doing it here. A time value + * keeps its full fraction so an unrepresentable one fails as it does on that path. A date + * column takes a datetime's date, for the datetimes bcp_executemany.cpp sends there, and + * datetimeoffset values carry the offset from format_offset. + */ +int BcpFormatTemporal(char* buf, size_t cap, PyObject* cell, unsigned cls, int destination, int scale, bool rounded) +{ + CivilTime t = civil_of(cell, cls); + + if (destination == DEST_DATETIMEOFFSET) { + const int units = fraction_units(t, scale, rounded, false); + int n = snprintf(buf, cap, "%04d-%02d-%02d %02d:%02d:%02d", t.year, t.month, t.day, t.hour, t.minute, t.second); + n += format_fraction(buf + n, cap - (size_t)n, units, scale); + const int offset = format_offset(buf + n, cap - (size_t)n, cell, cls); + return offset < 0 ? -1 : n + offset; + } + + if (destination == DEST_TIME) { + if (cls != VAL_TIME) { + const int units = fraction_units(t, scale, rounded, true); + const int n = snprintf(buf, cap, "%02d:%02d:%02d", t.hour, t.minute, t.second); + return n + format_fraction(buf + n, cap - (size_t)n, units, scale); + } + int n = snprintf(buf, cap, "%02d:%02d:%02d", t.hour, t.minute, t.second); + if (t.micro) { + n += snprintf(buf + n, cap - (size_t)n, ".%06d", t.micro); + while (buf[n - 1] == '0') + --n; + } + return n; + } + if (cls == VAL_DATE || destination == DEST_DATE) + return snprintf(buf, cap, "%04d-%02d-%02d", t.year, t.month, t.day); + + if (destination == DEST_DATETIME) { + int ticks = rounded ? (t.micro * 3 + 5000) / 10000 : ((t.micro / 1000) * 3 + 5) / 10; + if (ticks == 300) { + add_seconds(t, 1); + ticks = 0; + } + if (t.year > 9999) + return snprintf(buf, cap, "9999-12-31 23:59:59.997"); + return snprintf(buf, cap, "%04d-%02d-%02d %02d:%02d:%02d.%03d", + t.year, t.month, t.day, t.hour, t.minute, t.second, (ticks * 10 + 1) / 3); + } + if (destination == DEST_SMALLDATETIME) { + if (t.second >= 30) + add_seconds(t, 60 - t.second); + return snprintf(buf, cap, "%04d-%02d-%02d %02d:%02d:00", t.year, t.month, t.day, t.hour, t.minute); + } + const int units = fraction_units(t, scale, rounded, false); + const int n = snprintf(buf, cap, "%04d-%02d-%02d %02d:%02d:%02d", t.year, t.month, t.day, t.hour, t.minute, t.second); + return n + format_fraction(buf + n, cap - (size_t)n, units, scale); +} + +/*=======================================================================================*/ +// Decimals, converted as the server converts a numeric entry +/*=======================================================================================*/ + +bool BcpRaiseOutOfRange() +{ + RaiseErrorV("22003", 0, "Numeric value out of range"); + return false; +} + +bool BcpSplitDecimalText(const char* text, Py_ssize_t n, BcpDecimalParts& d) +{ + const char* end = text + n; + const char* p = text + (n > 0 && text[0] == '-'); + const char* point = p; + while (point < end && *point != '.') + ++point; + bool digits = point > p; + for (const char* q = p; q < end && digits; ++q) + digits = q == point || (*q >= '0' && *q <= '9'); + if (!digits) { + RaiseErrorV("22018", 0, "Decimal('%s') cannot be stored in a SQL Server number column", text); + return false; + } + d.negative = p > text; + d.whole = p; + d.nwhole = point - p; + while (d.nwhole > 0 && *d.whole == '0') { + ++d.whole; + --d.nwhole; + } + d.fraction = point < end ? point + 1 : end; + d.nfraction = end - d.fraction; + while (d.nfraction > 0 && d.fraction[d.nfraction - 1] == '0') + --d.nfraction; + return true; +} + +Py_ssize_t BcpTrimFractionZeros(const char* text, Py_ssize_t n) +{ + const char* point = (const char*)memchr(text, '.', (size_t)n); + if (!point) + return n; + while (text[n - 1] == '0') + --n; + return text + n - 1 == point ? n - 1 : n; +} + +bool BcpFitsNumericEntry(const BcpDecimalParts& d, long precision, long scale) +{ + if (d.nfraction > scale) { + RaiseErrorV(0, ProgrammingError, "Converting decimal loses precision"); + return false; + } + return d.nwhole <= precision - scale || BcpRaiseOutOfRange(); +} + +/** + * The text has exactly the column's places, so the driver's conversion only checks the range, + * and loses its sign if it is zero. 96 bytes holds the 38 whole digits an entry allows (see + * BcpFitsNumericEntry), a carry and 38 places. + */ +int BcpShapeNumericText(const BcpDecimalParts& d, int scale, bool rounded, char* buf) +{ + char digits[96]; + int n = 0; + digits[n++] = '0'; + memcpy(digits + n, d.whole, (size_t)d.nwhole); + n += (int)d.nwhole; + for (int i = 0; i < scale; ++i) + digits[n++] = i < d.nfraction ? d.fraction[i] : '0'; + if (rounded && d.nfraction > scale && d.fraction[scale] >= '5') { + int i = n - 1; + for (; digits[i] == '9'; --i) + digits[i] = '0'; + ++digits[i]; + } + const int wholeEnd = n - scale; + int start = 0; + while (start < wholeEnd - 1 && digits[start] == '0') + ++start; + bool zero = true; + for (int i = start; i < n && zero; ++i) + zero = digits[i] == '0'; + int len = 0; + if (d.negative && !zero) + buf[len++] = '-'; + memcpy(buf + len, digits + start, (size_t)(wholeEnd - start)); + len += wholeEnd - start; + if (scale) { + buf[len++] = '.'; + memcpy(buf + len, digits + wholeEnd, (size_t)scale); + len += scale; + } + return len; +} + +/*=======================================================================================*/ +// Doubles, converted as the server converts a double entry +/*=======================================================================================*/ + +static const int WIDE_LIMBS = 10; + +/** w = w * factor + addend, for an unsigned integer of WIDE_LIMBS 32-bit limbs, least significant first. */ +static void wide_multiply_add(uint32_t* w, uint32_t factor, uint32_t addend) +{ + uint64_t carry = addend; + for (int i = 0; i < WIDE_LIMBS; ++i) { + const uint64_t v = (uint64_t)w[i] * factor + carry; + w[i] = (uint32_t)v; + carry = v >> 32; + } +} + +static void wide_shift_left(uint32_t* w, int bits) +{ + const int limbs = bits / 32, rest = bits % 32; + for (int i = WIDE_LIMBS - 1; i >= 0; --i) { + uint64_t v = i >= limbs ? (uint64_t)w[i - limbs] << rest : 0; + if (rest && i > limbs) + v |= w[i - limbs - 1] >> (32 - rest); + w[i] = (uint32_t)v; + } +} + +static void wide_shift_right(uint32_t* w, int bits) +{ + const int limbs = bits / 32, rest = bits % 32; + for (int i = 0; i < WIDE_LIMBS; ++i) { + uint64_t v = i + limbs < WIDE_LIMBS ? w[i + limbs] >> rest : 0; + if (rest && i + limbs + 1 < WIDE_LIMBS) + v |= (uint64_t)w[i + limbs + 1] << (32 - rest); + w[i] = (uint32_t)v; + } +} + +static bool wide_bit(const uint32_t* w, int bit) +{ + return bit < 32 * WIDE_LIMBS && (w[bit / 32] >> (bit % 32)) & 1; +} + +/** w = w / divisor, returning the remainder. */ +static uint32_t wide_divide(uint32_t* w, uint32_t divisor) +{ + uint64_t rest = 0; + for (int i = WIDE_LIMBS - 1; i >= 0; --i) { + const uint64_t v = rest << 32 | w[i]; + w[i] = (uint32_t)(v / divisor); + rest = v % divisor; + } + return (uint32_t)rest; +} + +static bool wide_is_zero(const uint32_t* w) +{ + for (int i = 0; i < WIDE_LIMBS; ++i) + if (w[i]) + return false; + return true; +} + +/** The base-10**9 digits an integer of WIDE_LIMBS limbs can have, since 10**9 exceeds 2**29. */ +static const int WIDE_CHUNKS = (32 * WIDE_LIMBS + 28) / 29; + +/** + * Writes w's decimal digits, most significant first and without leading zeros, consuming w. + * `digits` needs 9 * WIDE_CHUNKS bytes, which hold any w, and gets no terminator. + * + * @return The digits written, at least one. + */ +static int wide_to_digits(uint32_t* w, char* digits) +{ + uint32_t chunks[WIDE_CHUNKS]; + int nchunks = 0; + do + chunks[nchunks++] = wide_divide(w, 1000000000u); + while (!wide_is_zero(w)); + + int n = 0; + for (int i = nchunks - 1; i >= 0; --i) { + for (int k = 8; k >= 0; --k) { + digits[n + k] = (char)('0' + chunks[i] % 10); + chunks[i] /= 10; + } + n += 9; + } + int lead = 0; + while (lead < n - 1 && digits[lead] == '0') + ++lead; + memmove(digits, digits + lead, (size_t)(n - lead)); + return n - lead; +} + +/** + * The double's exact binary value rounded half away from zero to the scale. The double is + * m * 2**e for a 53-bit integer m, so the digits are m * 10**scale * 2**e rounded, which below + * 2**128 (> 10**38, more than any decimal column holds) needs at most 255 bits. NaN, the + * infinities and anything larger raise; the driver rejects the rest of what does not fit the + * column. + */ +int BcpFormatDoubleAsDecimal(double value, int scale, char* buf) +{ + if (!std::isfinite(value) || fabs(value) >= ldexp(1.0, 128)) { + BcpRaiseOutOfRange(); + return -1; + } + int exponent = 0; + const uint64_t mantissa = (uint64_t)ldexp(frexp(fabs(value), &exponent), 53); + exponent -= 53; + uint32_t w[WIDE_LIMBS] = { (uint32_t)mantissa, (uint32_t)(mantissa >> 32) }; + for (int i = 0; i < scale; ++i) + wide_multiply_add(w, 10, 0); + if (exponent >= 0) + wide_shift_left(w, exponent); + else { + const bool roundUp = wide_bit(w, -exponent - 1); + if (-exponent >= 32 * WIDE_LIMBS) + memset(w, 0, sizeof(w)); + else + wide_shift_right(w, -exponent); + if (roundUp) + wide_multiply_add(w, 1, 1); + } + + char digits[9 * WIDE_CHUNKS]; + const int ndigits = wide_to_digits(w, digits); + + int len = 0; + if (std::signbit(value) && !(ndigits == 1 && digits[0] == '0')) + buf[len++] = '-'; + const int zeros = ndigits > scale ? 0 : scale + 1 - ndigits; + const int whole = ndigits + zeros - scale; + for (int i = 0; i < zeros; ++i) + buf[len + i] = '0'; + memcpy(buf + len + zeros, digits, (size_t)ndigits); + if (scale) { + memmove(buf + len + whole + 1, buf + len + whole, (size_t)scale); + buf[len + whole] = '.'; + ++len; + } + return len + whole + scale; +} + +/** + * The driver then checks the column's range. NaN, the infinities and values beyond bigint raise, + * where the driver's own conversion would wrap 2**63 to bigint's minimum. + */ +bool BcpTruncateDouble(double d, long long* v) +{ + if (!std::isfinite(d) || d >= 9223372036854775808.0 || d < -9223372036854775808.0) + return BcpRaiseOutOfRange(); + *v = (long long)d; + return true; +} + +/** + * Subnormals included, where the driver's own conversion rejects anything below the least normal + * real. NaN, the infinities and values that round past the largest real (from halfway to 2**128 + * up) raise. + */ +bool BcpNarrowDouble(double d, float* f) +{ + if (!std::isfinite(d) || fabs(d) >= ldexp(33554431.0, 103)) + return BcpRaiseOutOfRange(); + *f = (float)d; + return true; +} diff --git a/src/bcp_convert.h b/src/bcp_convert.h new file mode 100644 index 00000000..ae4dedfe --- /dev/null +++ b/src/bcp_convert.h @@ -0,0 +1,122 @@ +#pragma once + +// Value conversions for the SQL Server bulk copy (BCP) fast path (bcp_executemany.cpp): the +// text and numbers BCP is given so the server stores exactly what the plain fast_executemany +// path would have stored, for the cases where the driver's own conversion of a host value would +// differ. Include after pyodbc.h. +// +// The value classes and destination categories are shared with bcp_executemany.cpp, which +// classifies the rows and plans the columns. + +/** Imports the datetime C API for the conversions; called once at module load. */ +void BcpConvert_init(); + +/** The classes of Python value a column can hold, as bits so a column records all it has seen. */ +enum : unsigned +{ + VAL_NONE = 1u << 0, + VAL_BOOL = 1u << 1, + VAL_INT = 1u << 2, + VAL_FLOAT = 1u << 3, + VAL_STR = 1u << 4, + VAL_BYTES = 1u << 5, + VAL_DECIMAL = 1u << 6, + VAL_DATE = 1u << 7, + VAL_DATETIME = 1u << 8, + VAL_TIME = 1u << 9, + VAL_UUID = 1u << 10, +}; + +/** Destination column categories, by how values must be prepared for them. */ +enum Destination +{ + DEST_UNSUPPORTED, + DEST_CHAR, + DEST_XML, + DEST_BINARY, + DEST_INTEGER, + DEST_BIT, + DEST_FLOAT, + DEST_DECIMAL, + DEST_MONEY, + DEST_DATE, + DEST_TIME, + DEST_DATETIME2, + DEST_DATETIMEOFFSET, + DEST_DATETIME, + DEST_SMALLDATETIME, + DEST_GUID, +}; + +/** + * Formats a date, datetime or time value (of class `cls`) as text for a temporal destination + * with `scale` fractional digits, rounded as the plain fast path's value is. `rounded` says the + * value goes as a setinputsizes timestamp entry, which the server converts from all seven + * digits, rather than as the column's own type. + * + * @return The characters written, or -1 with a Python exception set. + */ +int BcpFormatTemporal(char* buf, size_t cap, PyObject* cell, unsigned cls, int destination, int scale, bool rounded); + +/** Raises the out-of-range error the server reports for a value its column cannot hold. */ +bool BcpRaiseOutOfRange(); + +/** + * A finite Decimal's text in parts: its sign, its whole digits without leading zeros, and its + * fraction digits without trailing zeros. + */ +struct BcpDecimalParts +{ + bool negative; + const char* whole; + Py_ssize_t nwhole; + const char* fraction; + Py_ssize_t nfraction; +}; + +/** Splits a Decimal's text into its parts, or raises for NaN or an infinity. */ +bool BcpSplitDecimalText(const char* text, Py_ssize_t n, BcpDecimalParts& d); + +/** + * The length of a Decimal's fixed-point text without its fraction's trailing zeros, and without + * the point when no fraction digit remains: "1.50" is 1.5 and "0.00" is 0, the text of the value + * normalize() gives when it does not round. + */ +Py_ssize_t BcpTrimFractionZeros(const char* text, Py_ssize_t n); + +/** + * Checks a Decimal against a numeric entry of `precision` and `scale` as the plain path does: it + * raises for more places than the scale before sending anything, and the server rejects more + * whole digits than the precision leaves room for. + */ +bool BcpFitsNumericEntry(const BcpDecimalParts& d, long precision, long scale); + +/** + * Writes a Decimal with exactly `scale` places, as the server converts a numeric entry: rounded + * half away from zero when `rounded` (decimal and money columns), otherwise truncated toward zero + * (integer columns). `d` must have passed BcpFitsNumericEntry, which limits it to 38 whole + * digits, and `scale` must be at most 38, so the text fits buf's 96 bytes. + * + * @return The characters written. + */ +int BcpShapeNumericText(const BcpDecimalParts& d, int scale, bool rounded, char* buf); + +/** + * Writes a double with exactly `scale` places (at most 38), as the server converts a double + * entry into a decimal column. buf needs 96 bytes. + * + * @return The characters written, or -1 with an exception set. + */ +int BcpFormatDoubleAsDecimal(double value, int scale, char* buf); + +/** + * A double truncated toward zero, as the server converts a double entry into an integer column. + * Raises, returning false, for one bigint cannot hold. + */ +bool BcpTruncateDouble(double d, long long* v); + +/** + * A double rounded to the nearest real, as the server converts a double entry into a real column. + * Raises, returning false, for one real cannot hold. + */ +bool BcpNarrowDouble(double d, float* f); diff --git a/src/bcp_executemany.cpp b/src/bcp_executemany.cpp new file mode 100644 index 00000000..08ef3696 --- /dev/null +++ b/src/bcp_executemany.cpp @@ -0,0 +1,1710 @@ +// The SQL Server bulk copy (BCP) fast path for Cursor.executemany. +// +// When cursor.fast_executemany and cursor.use_bcp_fast are set, an INSERT of a single +// parameterized VALUES row is carried out with the BCP API instead of an array of parameter +// sets. The path is an optimisation only: it must store exactly what the plain fast path would, +// so anything it cannot reproduce faithfully is detected before bcp_init and left to that path. +// Once rows are streaming, a failure rolls back everything this call sent and raises. Values +// the path converts itself, where the driver's conversion would differ from the server's, are +// shaped in bcp_convert.cpp. + +#include "pyodbc.h" +#include "wrapper.h" +#include "textenc.h" +#include "pyodbcmodule.h" +#include "connection.h" +#include "cursor.h" +#include "errors.h" +#include "bcp_support.h" +#include "bcp_convert.h" +#include +#include + +void BcpExecuteMany_init() +{ + PyDateTime_IMPORT; + BcpConvert_init(); +} + +/** + * The setinputsizes entry for a parameter, by the SQL type the plain path then sends each value + * as, for the server to convert to the column's type. ENTRY_NONE is a missing or None entry, + * which leaves the parameter typed as its column. + */ +enum Entry +{ + ENTRY_NONE, + ENTRY_TEXT, + ENTRY_BIT, + ENTRY_BIGINT, + ENTRY_DOUBLE, + ENTRY_NUMERIC, + ENTRY_TIMESTAMP, + ENTRY_DATE, +}; + +/** + * One bound column: where it goes, what the rows hold for it, and its capacity in characters + * (text) or bytes (binary), or -1 where no limit applies. `entry` is its parameter's + * setinputsizes entry, with that entry's size (the nvarchar length or numeric precision) and + * digits (the numeric scale). `exactChars` is the bitmap map_exact_chars makes, or null, and + * `asciiText` says the column takes only ASCII text (see takes_only_ascii). + */ +struct ColumnPlan +{ + const BcpTargetColumn* target; + int ordinal; + int destination; + long capacity; + unsigned classes; + PyTypeObject* lastType; + unsigned lastClass; + int entry; + long entrySize; + long entryDigits; + uint32_t* exactChars; + bool asciiText; +}; + +/** + * How the load runs inside a transaction: in autocommit mode autocommit is suspended so the + * load is its own transaction; in manual-commit mode a savepoint marks where it started. + */ +struct LoadTransaction +{ + bool autocommitSuspended; + bool savepoint; +}; + +/** + * Everything a load allocates, freed when it goes out of scope. + * + * `cols` holds the ncols columns the rows' values go to, then nfill filler columns: the table + * columns after the last of those, which BCP requires bound and which are always NULL so the + * server fills them in. keepNulls says whether BCPKEEPNULLS is set. + * + * The load holds its own reference to the connection, as Python code run while a row is filled + * (a UUID subclass's bytes_le, say) can close the cursor, which drops the cursor's reference to + * it. `sizes` is a snapshot of the cursor's setinputsizes entries, which the caller can change + * while the GIL is released. `tableName` is what bcp_init was given, kept until the bulk copy + * ends. While the copy runs the connection's BCP state marks a session open (`sessionMarked`), + * so autocommit and the low-level API are refused and closing the connection abandons the copy. + */ +struct BcpLoad +{ + Object cnxnRef; + Cursor* cursor; + Connection* cnxn; + BcpInsert insert; + bool insertParsed; + BcpTarget target; + ColumnPlan* plans; + BcpCol* cols; + int ncols; + int nfill; + bool keepNulls; + Object sizes; + Object rows; + Object decimalType; + Object decimalFormat; + Object adjustedName; + SQLWCHAR* tableName; + bool sessionMarked; + + explicit BcpLoad(Cursor* cur) + : cnxnRef(Py_NewRef((PyObject*)cur->cnxn)), cursor(cur), cnxn(cur->cnxn), insertParsed(false), + plans(0), cols(0), ncols(0), nfill(0), keepNulls(true), tableName(0), sessionMarked(false) + { + target.ncols = 0; + target.cols = 0; + } + + BcpLoad(const BcpLoad&) = delete; + BcpLoad& operator=(const BcpLoad&) = delete; + + /** Marks the connection's BCP session open for this load, which owns its transaction in autocommit mode. */ + void mark_session(bool ownsTransaction) + { + cnxn->bcp->sessionOpen = cnxn->bcp->fastLoad = true; + cnxn->bcp->ownsTransaction = ownsTransaction; + sessionMarked = true; + } + + ~BcpLoad() + { + if (sessionMarked && cnxn->bcp) + cnxn->bcp->sessionOpen = cnxn->bcp->fastLoad = cnxn->bcp->ownsTransaction = false; + PyMem_Free(tableName); + if (insertParsed) + BcpFreeInsert(&insert); + BcpFreeTarget(&target); + for (int i = 0; plans && i < ncols; ++i) + PyMem_Free(plans[i].exactChars); + PyMem_Free(plans); + BcpFreeColumns(cols, ncols + nfill); + } +}; + +/** + * The category of a destination column, or DEST_UNSUPPORTED for one the path leaves to the + * plain path. + */ +static int destination_of(const BcpTargetColumn& col) +{ + switch (col.systemType) { + case 35: case 99: case 167: case 175: case 231: case 239: + return DEST_CHAR; + case 241: + return DEST_XML; + case 34: case 165: case 173: + return DEST_BINARY; + case 48: case 52: case 56: case 127: + return DEST_INTEGER; + case 104: + return DEST_BIT; + case 59: case 62: + return DEST_FLOAT; + case 106: case 108: + return DEST_DECIMAL; + case 60: case 122: + return DEST_MONEY; + case 40: + return DEST_DATE; + case 41: + return DEST_TIME; + case 42: + return DEST_DATETIME2; + case 43: + return DEST_DATETIMEOFFSET; + case 61: + return DEST_DATETIME; + case 58: + return DEST_SMALLDATETIME; + case 36: + return DEST_GUID; + } + return DEST_UNSUPPORTED; +} + +/** + * The length limit the plain path enforces before sending, in UTF-16 units for char, varchar, + * nchar and nvarchar and in bytes for binary and varbinary; -1 for (max), xml and the legacy + * text, ntext and image types, which have none that matters. + */ +static long capacity_of(const BcpTargetColumn& col) +{ + if (col.maxLength == -1) + return -1; + switch (col.systemType) { + case 167: case 175: case 165: case 173: + return col.maxLength; + case 231: case 239: + return col.maxLength / 2; + } + return -1; +} + +/** Whether a column stores text in its collation's code page: char, varchar and text. */ +static bool is_code_page_text(const BcpTargetColumn& col) +{ + return col.systemType == 35 || col.systemType == 167 || col.systemType == 175; +} + +/** + * Whether the driver can send only ASCII text to a column: one with a UTF-8 collation, before + * Driver 17.4, the first to convert text to UTF-8 for the server. Older drivers send other + * text as bytes the server rejects. + */ +static bool takes_only_ascii(const BcpLoad& load, const BcpTargetColumn& col) +{ + return is_code_page_text(col) && col.codePage == 65001 && load.cnxn->bcp->driverVersion < 1704; +} + +static bool names_equal(const SQLWCHAR* a, const SQLWCHAR* b, bool foldAsciiCase) +{ + for (; *a && *b; ++a, ++b) { + SQLWCHAR ca = *a, cb = *b; + if (foldAsciiCase) { + if (ca >= 'A' && ca <= 'Z') ca = (SQLWCHAR)(ca + 32); + if (cb >= 'A' && cb <= 'Z') cb = (SQLWCHAR)(cb + 32); + } + if (ca != cb) + return false; + } + return *a == 0 && *b == 0; +} + +/** + * Finds the target column a listed name refers to: an exact match, else, in a database that + * compares identifiers ignoring case, the only match that differs in ASCII case. A name that + * matches only by folding other letters is left unmatched, so the plain path resolves it. + * Returns -1 if there is none, -2 on allocation failure. + */ +static int find_target_column(const BcpTarget& target, const char* name) +{ + SQLWCHAR* wname = BcpUtf8ToSqlWChar(name); + if (!wname) + return -2; + int exact = -1, folded = -1, nfolded = 0; + for (int i = 0; i < target.ncols && exact < 0; ++i) { + if (names_equal(target.cols[i].name, wname, false)) + exact = i; + else if (target.caseInsensitive && names_equal(target.cols[i].name, wname, true)) { + folded = i; + ++nfolded; + } + } + PyMem_Free(wname); + if (exact >= 0) + return exact; + return nfolded == 1 ? folded : -1; +} + +static bool is_bindable(const BcpTargetColumn& col) +{ + return !col.identity && !col.computed && destination_of(col) != DEST_UNSUPPORTED; +} + +/** + * Maps the INSERT's values to target columns as the INSERT itself would. + * + * A column list names its columns; the unlisted ones are left for the server to fill in + * (identity, computed, DEFAULT or NULL) exactly as for the INSERT. Without a list the values + * go to every column except identity and computed ones, which is how T-SQL reads a positional + * INSERT. Anything the INSERT would reject is left to the plain path to report. + * + * Unbound columns before the last bound one need nothing, but BCP requires the columns after it + * bound, so those become filler columns bound to NULL, which the server fills in the same way + * (see choose_keep_nulls for columns with a DEFAULT). + * + * @return 1 if mapped, 0 to fall back, -1 on allocation failure (Python exception set). + */ +static int map_columns(BcpLoad& load) +{ + const BcpInsert& ins = load.insert; + const BcpTarget& target = load.target; + load.plans = (ColumnPlan*)PyMem_Calloc((size_t)ins.nmarkers, sizeof(ColumnPlan)); + if (!load.plans) { + PyErr_NoMemory(); + return -1; + } + + int n = 0; + if (ins.nnames) { + if (ins.nnames != ins.nmarkers) + return 0; + for (int i = 0; i < ins.nnames; ++i) { + int t = find_target_column(target, ins.names[i]); + if (t == -2) + return -1; + if (t < 0 || !is_bindable(target.cols[t])) + return 0; + for (int j = 0; j < n; ++j) + if (load.plans[j].ordinal == t + 1) + return 0; + load.plans[n].target = &target.cols[t]; + load.plans[n++].ordinal = t + 1; + } + } else { + for (int t = 0; t < target.ncols; ++t) { + const BcpTargetColumn& col = target.cols[t]; + if (col.identity || col.computed) + continue; + if (n == ins.nmarkers || destination_of(col) == DEST_UNSUPPORTED) + return 0; + load.plans[n].target = &col; + load.plans[n++].ordinal = t + 1; + } + if (n != ins.nmarkers) + return 0; + } + int last = 0; + for (int i = 0; i < n; ++i) { + load.plans[i].destination = destination_of(*load.plans[i].target); + load.plans[i].capacity = capacity_of(*load.plans[i].target); + load.plans[i].asciiText = takes_only_ascii(load, *load.plans[i].target); + if (load.plans[i].ordinal > last) + last = load.plans[i].ordinal; + } + load.ncols = n; + load.nfill = target.ncols - last; + return 1; +} + +/** + * Decides whether to set BCPKEEPNULLS. With it, a NULL bound to a column with a DEFAULT is + * stored as NULL, as an INSERT stores an explicit NULL; without it BCP stores the default, as + * the INSERT does for a column it leaves out. It only affects columns with a default, so it is + * cleared when a filler column has one, which is only safe if no value column with a default + * receives a NULL. + * + * @return false to fall back. + */ +static bool choose_keep_nulls(BcpLoad& load) +{ + bool fillerDefault = false; + for (int t = load.target.ncols - load.nfill; t < load.target.ncols; ++t) + fillerDefault = fillerDefault || load.target.cols[t].hasDefault; + if (!fillerDefault) + return true; + for (int i = 0; i < load.ncols; ++i) + if (load.plans[i].target->hasDefault && (load.plans[i].classes & VAL_NONE)) + return false; + load.keepNulls = false; + return true; +} + +static bool read_entry_field(PyObject* entry, Py_ssize_t i, long* value) +{ + PyObject* item = PyTuple_GET_ITEM(entry, i); + if (!PyLong_Check(item) || PyBool_Check(item)) + return false; + int overflow = 0; + *value = PyLong_AsLongAndOverflow(item, &overflow); + return !overflow; +} + +/** + * The kind of a (type, size, digits) entry, or -1 for one the path does not reproduce. The + * driver ignores the size and digits of bit, bigint, double and date entries, and the digits of + * an nvarchar entry, whose size must be what the plain path can bind (0 for max). A timestamp + * entry is taken only as datetime2(7), which leaves a datetime's microseconds intact. + */ +static int entry_kind(long type, long size, long digits) +{ + switch (type) { + case SQL_WVARCHAR: + return size >= 0 && size <= 4000 ? ENTRY_TEXT : -1; + case SQL_BIT: + return ENTRY_BIT; + case SQL_BIGINT: + return ENTRY_BIGINT; + case SQL_DOUBLE: + return ENTRY_DOUBLE; + case SQL_NUMERIC: + case SQL_DECIMAL: + return size >= 1 && size <= 38 && digits >= 0 && digits <= size ? ENTRY_NUMERIC : -1; + case SQL_TYPE_TIMESTAMP: + return size == 27 && digits == 7 ? ENTRY_TIMESTAMP : -1; + case SQL_TYPE_DATE: + return ENTRY_DATE; + } + return -1; +} + +/** The multi-byte code pages of SQL Server collations: UTF-8 and the four double-byte ones. */ +static bool is_multibyte_code_page(int codePage) +{ + return codePage == 65001 || codePage == 932 || codePage == 936 || codePage == 949 || codePage == 950; +} + +/** + * Records the characters a single-byte code page holds exactly, those its 256 bytes decode to, + * as a bitmap over the BMP for encodes_exactly to look up. A multi-byte code page, or one + * without a Python codec, gets none, and its values are encoded one by one instead. + */ +static void map_exact_chars(ColumnPlan& plan) +{ + const int codePage = plan.target->codePage; + if (is_multibyte_code_page(codePage)) + return; + char codec[16]; + snprintf(codec, sizeof(codec), "cp%d", codePage); + char bytes[256]; + for (int b = 0; b < 256; ++b) + bytes[b] = (char)b; + Object chars(PyUnicode_Decode(bytes, 256, codec, "replace")); + plan.exactChars = chars.IsValid() ? (uint32_t*)PyMem_Calloc(65536 / 32, sizeof(uint32_t)) : 0; + if (!plan.exactChars) { + PyErr_Clear(); + return; + } + for (Py_ssize_t i = 0; i < PyUnicode_GET_LENGTH(chars.Get()); ++i) { + const Py_UCS4 ch = PyUnicode_READ_CHAR(chars.Get(), i); + if (ch != 0xFFFD && ch <= 0xFFFF) + plan.exactChars[ch / 32] |= 1u << (ch % 32); + } +} + +/** + * Records each parameter's setinputsizes entry on its column. An entry may be None, or a + * 3-tuple of ints the path reproduces (see entry_kind); a parameter beyond the list has none. + * + * @return false to fall back, for any other entry or entries that are not a tuple or list. + */ +static bool read_entries(BcpLoad& load, PyObject* sizes) +{ + if (!sizes) + return true; + if (!PyTuple_Check(sizes) && !PyList_Check(sizes)) + return false; + const Py_ssize_t nsizes = PySequence_Fast_GET_SIZE(sizes); + for (int i = 0; i < load.ncols && i < nsizes; ++i) { + PyObject* entry = PySequence_Fast_GET_ITEM(sizes, i); + if (entry == Py_None) + continue; + long type, size, digits; + if (!PyTuple_Check(entry) || PyTuple_GET_SIZE(entry) != 3 || !read_entry_field(entry, 0, &type) || + !read_entry_field(entry, 1, &size) || !read_entry_field(entry, 2, &digits)) + return false; + ColumnPlan& plan = load.plans[i]; + plan.entry = entry_kind(type, size, digits); + if (plan.entry < 0) + return false; + plan.entrySize = size; + plan.entryDigits = digits; + if (plan.entry == ENTRY_TEXT && is_code_page_text(*plan.target)) + map_exact_chars(plan); + } + return true; +} + +/** + * The class of a cell's value, or 0 for a value the path leaves to the plain path. A Decimal + * subclass is one: its __format__ and as_tuple, which the plain path reads, can disagree. + */ +static unsigned class_of(PyObject* cell) +{ + if (cell == Py_None) + return VAL_NONE; + if (PyBool_Check(cell)) + return VAL_BOOL; + if (PyLong_Check(cell)) { + int overflow = 0; + PyLong_AsLongLongAndOverflow(cell, &overflow); + return overflow ? 0 : VAL_INT; + } + if (PyFloat_Check(cell)) + return VAL_FLOAT; + if (PyUnicode_Check(cell)) + return VAL_STR; + if (PyBytes_Check(cell) || PyByteArray_Check(cell)) + return VAL_BYTES; + if (PyDateTime_Check(cell)) + return VAL_DATETIME; + if (PyDate_Check(cell)) + return VAL_DATE; + if (PyTime_Check(cell)) + return VAL_TIME; + PyObject* cls = 0; + if (IsInstanceForThread(cell, "decimal", "Decimal", &cls) && cls) { + const bool exact = Py_TYPE(cell) == (PyTypeObject*)cls; + Py_DECREF(cls); + return exact ? VAL_DECIMAL : 0; + } + PyErr_Clear(); + if (IsInstanceForThread(cell, "uuid", "UUID", &cls) && cls) { + Py_DECREF(cls); + return VAL_UUID; + } + PyErr_Clear(); + return 0; +} + +/** Classifies a cell, reusing the column's last class when the type repeats (ints are range-checked each time). */ +static unsigned classify(ColumnPlan& plan, PyObject* cell) +{ + if (Py_TYPE(cell) == plan.lastType && plan.lastClass != VAL_INT) + return plan.lastClass; + plan.lastType = Py_TYPE(cell); + plan.lastClass = class_of(cell); + return plan.lastClass; +} + +static bool is_row(PyObject* row, int ncols) +{ + return (PyTuple_Check(row) || PyList_Check(row)) && PySequence_Fast_GET_SIZE(row) == ncols; +} + +/** The length of a str in UTF-16 code units, as the plain path measures it. */ +static Py_ssize_t utf16_length(PyObject* s) +{ + const Py_ssize_t n = PyUnicode_GET_LENGTH(s); + if (PyUnicode_KIND(s) != PyUnicode_4BYTE_KIND) + return n; + const Py_UCS4* data = PyUnicode_4BYTE_DATA(s); + Py_ssize_t units = n; + for (Py_ssize_t i = 0; i < n; ++i) + units += data[i] > 0xFFFF; + return units; +} + +/** The number of characters an int (already known to fit 64 bits) takes as decimal text. */ +static long int_text_length(PyObject* cell) +{ + long long v = PyLong_AsLongLong(cell); + long n = v < 0 ? 2 : 1; + unsigned long long u = v < 0 ? 0ULL - (unsigned long long)v : (unsigned long long)v; + while (u >= 10) { + u /= 10; + ++n; + } + return n; +} + +/** + * The most bytes a str can take in a multi-byte code page: exactly its UTF-8 length for a UTF-8 + * collation, and for the double-byte ones two bytes for each UTF-16 unit outside ASCII. -1 for + * a single-byte code page, which takes at most a byte for each UTF-16 unit. + */ +static Py_ssize_t max_encoded_length(PyObject* s, int codePage) +{ + if (!is_multibyte_code_page(codePage)) + return -1; + const Py_ssize_t n = PyUnicode_GET_LENGTH(s); + Py_ssize_t bytes = 0; + for (Py_ssize_t i = 0; i < n; ++i) { + const Py_UCS4 ch = PyUnicode_READ_CHAR(s, i); + if (ch < 0x80) + bytes += 1; + else if (codePage != 65001) + bytes += ch > 0xFFFF ? 4 : 2; + else + bytes += ch < 0x800 ? 2 : (ch > 0xFFFF ? 4 : 3); + } + return bytes; +} + +/** + * Whether a str fits a char or varchar column in bytes. In a multi-byte code page a value can + * have no more characters than the column yet more bytes, which the server rejects but the + * driver quietly cuts short. ASCII takes a byte a character in every code page. + */ +static bool fits_column_bytes(const ColumnPlan& plan, PyObject* s) +{ + if (!is_code_page_text(*plan.target) || PyUnicode_IS_ASCII(s)) + return true; + return max_encoded_length(s, plan.target->codePage) <= plan.capacity; +} + +/** + * Returns false where a value's length means the plain path would not store what BCP would: + * text or bytes longer than the column, which the plain path rejects but the driver quietly + * trims of trailing spaces or zero bytes (or, in a multi-byte code page, cuts short, see + * fits_column_bytes), and a number wider as text than its text column, which the plain path + * truncates but BCP rejects. A double can take 24 characters as text. + */ +static bool fits_capacity(const ColumnPlan& plan, PyObject* cell, unsigned cls) +{ + switch (cls) { + case VAL_STR: + return plan.destination != DEST_CHAR || + (utf16_length(cell) <= plan.capacity && fits_column_bytes(plan, cell)); + case VAL_BYTES: + return plan.destination != DEST_BINARY || + (PyBytes_Check(cell) ? PyBytes_GET_SIZE(cell) : PyByteArray_GET_SIZE(cell)) <= plan.capacity; + case VAL_INT: + return plan.destination != DEST_CHAR || int_text_length(cell) <= plan.capacity; + case VAL_FLOAT: + return plan.destination != DEST_CHAR || plan.capacity >= 24; + } + return true; +} + +static int hex_digit(Py_UCS1 c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; +} + +/** + * Parses a str in the one form the plain path stores in a uniqueidentifier column, + * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx in either case, into the column's byte order (that of + * uuid.UUID.bytes_le). The plain path rejects every other form (braces, no hyphens, padding), + * so those are left to it. `guid` may be null to only check the form. + */ +static bool parse_guid_text(PyObject* s, unsigned char* guid) +{ + static const int byteOrder[16] = { 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15 }; + if (PyUnicode_KIND(s) != PyUnicode_1BYTE_KIND || PyUnicode_GET_LENGTH(s) != 36) + return false; + const Py_UCS1* text = PyUnicode_1BYTE_DATA(s); + unsigned char bytes[16]; + int n = 0; + for (int i = 0; i < 36;) { + if (i == 8 || i == 13 || i == 18 || i == 23) { + if (text[i++] != '-') + return false; + continue; + } + const int high = hex_digit(text[i]), low = hex_digit(text[i + 1]); + if (high < 0 || low < 0) + return false; + bytes[n++] = (unsigned char)(high << 4 | low); + i += 2; + } + if (guid) + for (int k = 0; k < 16; ++k) + guid[k] = bytes[byteOrder[k]]; + return true; +} + +static bool is_two_digits_below(const Py_UCS1* text, int limit) +{ + return text[0] >= '0' && text[0] <= '9' && text[1] >= '0' && text[1] <= '9' && + (text[0] - '0') * 10 + (text[1] - '0') < limit; +} + +/** + * Whether a str is time text the plain path stores exactly in a time column of the given scale + * and the driver's BCP conversion accepts as is: HH:MM:SS with an optional fraction of no more + * digits than the scale, the form str(datetime.time) takes and SQLAlchemy binds. The plain path + * rejects a longer fraction, which does not fit the column's size, and out-of-range fields. + */ +static bool is_time_text(PyObject* s, int scale) +{ + if (PyUnicode_KIND(s) != PyUnicode_1BYTE_KIND) + return false; + const Py_ssize_t n = PyUnicode_GET_LENGTH(s); + const Py_UCS1* text = PyUnicode_1BYTE_DATA(s); + if (n < 8 || text[2] != ':' || text[5] != ':' || !is_two_digits_below(text, 24) || + !is_two_digits_below(text + 3, 60) || !is_two_digits_below(text + 6, 60)) + return false; + if (n == 8) + return true; + if (text[8] != '.' || n == 9 || n - 9 > scale) + return false; + for (Py_ssize_t i = 9; i < n; ++i) + if (text[i] < '0' || text[i] > '9') + return false; + return true; +} + +/** + * Whether the plain path stores a datetime in a date column: when its hours, minutes and seconds + * are zero, ignoring the microseconds and tzinfo. It rejects any other time of day, and SQLAlchemy + * binds a date for such a column as a datetime at midnight. + */ +static bool is_storable_as_date(PyObject* cell) +{ + return PyDateTime_DATE_GET_HOUR(cell) == 0 && PyDateTime_DATE_GET_MINUTE(cell) == 0 && + PyDateTime_DATE_GET_SECOND(cell) == 0; +} + +/** + * Returns false for a value the plain path rejects in its column, or would store differently, + * because of its form rather than its type: a str in a uniqueidentifier column that is not a + * canonical GUID, a str in a time column that is not time text (see is_time_text), or a datetime + * with a time of day in a date column, which the server truncates to its date only when it + * arrives as a timestamp entry. + */ +static bool has_plain_path_form(const ColumnPlan& plan, PyObject* cell, unsigned cls) +{ + if (plan.destination == DEST_GUID && cls == VAL_STR) + return parse_guid_text(cell, 0); + if (plan.destination == DEST_TIME && cls == VAL_STR) + return is_time_text(cell, plan.target->scale); + if (plan.destination == DEST_DATE && cls == VAL_DATETIME) + return plan.entry == ENTRY_TIMESTAMP || is_storable_as_date(cell); + return true; +} + +/** + * Whether the code page of a char, varchar or text column holds every character of a str + * exactly. Under an nvarchar entry the server converts text to that code page itself, and its + * substitutes for characters the code page lacks differ from the driver's best-fit mapping + * (U+2009 becomes '?' rather than a space in code page 1252). ASCII is held exactly by every + * code page; other characters are looked up in the column's exactChars, or for a multi-byte + * code page found by encoding the value. + */ +static bool encodes_exactly(const ColumnPlan& plan, PyObject* s) +{ + if (!is_code_page_text(*plan.target) || PyUnicode_IS_ASCII(s)) + return true; + if (plan.exactChars) { + const unsigned kind = PyUnicode_KIND(s); + const void* data = PyUnicode_DATA(s); + const Py_ssize_t n = PyUnicode_GET_LENGTH(s); + for (Py_ssize_t i = 0; i < n; ++i) { + const Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (ch > 0xFFFF || !((plan.exactChars[ch / 32] >> (ch % 32)) & 1)) + return false; + } + return true; + } + char codec[16]; + if (plan.target->codePage == 65001) + snprintf(codec, sizeof(codec), "utf-8"); + else + snprintf(codec, sizeof(codec), "cp%d", plan.target->codePage); + Object encoded(PyUnicode_AsEncodedString(s, codec, "strict")); + if (!encoded.IsValid()) + PyErr_Clear(); + return encoded.IsValid(); +} + +/** + * Whether a str fits its nvarchar entry, which the plain path binds with room for only that + * many UTF-16 units and rejects anything longer (an entry of 0 is nvarchar(max)), and is text + * the server and the driver both convert exactly (see encodes_exactly). + */ +static bool fits_entry(const ColumnPlan& plan, PyObject* cell, unsigned cls) +{ + if (plan.entry != ENTRY_TEXT || cls != VAL_STR) + return true; + return (plan.entrySize == 0 || utf16_length(cell) <= plan.entrySize) && encodes_exactly(plan, cell); +} + +/** + * Whether a value fits its column and its entry (see fits_capacity and fits_entry), and is + * ASCII if it is text for a column that takes only that (see takes_only_ascii). + */ +static bool fits_column(const ColumnPlan& plan, PyObject* cell, unsigned cls) +{ + return (plan.capacity < 0 || fits_capacity(plan, cell, cls)) && fits_entry(plan, cell, cls) && + (!plan.asciiText || cls != VAL_STR || PyUnicode_IS_ASCII(cell)); +} + +/** + * Scans every row once before anything is sent, recording the classes of value in each column. + * Each value is read afresh and held while it is checked, as the checks can run Python code (a + * first import of decimal, say) that lets another thread change the row. + * + * @return false if a row is not a tuple or list of the right length, or holds a value BCP + * cannot send as the plain path would (an int beyond 64 bits, an unsupported type, a + * value that does not fit its column or its entry, see fits_column, or one whose form + * the plain path rejects, see has_plain_path_form). Filling a row checks its values + * again, as Python code run meanwhile can change them. + */ +static bool scan_rows(BcpLoad& load) +{ + const Py_ssize_t nrows = PyTuple_GET_SIZE(load.rows.Get()); + for (Py_ssize_t r = 0; r < nrows; ++r) { + PyObject* row = PyTuple_GET_ITEM(load.rows.Get(), r); + for (int i = 0; i < load.ncols; ++i) { + if (!is_row(row, load.ncols)) + return false; + Object cell(Py_NewRef(PySequence_Fast_GET_ITEM(row, i))); + ColumnPlan& plan = load.plans[i]; + unsigned cls = classify(plan, cell); + if (!cls || !fits_column(plan, cell, cls) || !has_plain_path_form(plan, cell, cls)) + return false; + plan.classes |= cls; + } + } + return true; +} + +/** + * Picks the host type for a column without a setinputsizes entry from its destination and the + * classes of value it holds. + * + * Only pairs whose driver conversion stores what the plain fast path stores are allowed (see + * test_bcp_matches_plain_path); text goes as UTF-16 (SQLNCHAR) because the driver reads + * SQLCHARACTER data in the client's ANSI code page. SQLCHARACTER is used only for ASCII text + * the path formats itself, Decimals and dates and times shaped to the destination's precision, + * and for time text it has checked (see is_time_text). + * + * @return The host type, or 0 to fall back. + */ +static int choose_untyped_host_type(int destination, unsigned classes) +{ + const unsigned v = classes & ~VAL_NONE; + if (!v) + return SQLCHARACTER; + const bool onlyIntegers = !(v & ~(VAL_INT | VAL_BOOL)); + + switch (destination) { + case DEST_CHAR: + if (v == VAL_STR || v == (VAL_STR | VAL_INT)) + return SQLNCHAR; + if (v == VAL_INT) + return SQLINT8; + if (v == VAL_BOOL) + return SQLBIT; + if (v == VAL_FLOAT) + return SQLFLT8; + return 0; + case DEST_XML: + return v == VAL_STR ? SQLNCHAR : 0; + case DEST_BINARY: + return v == VAL_BYTES ? SQLBINARY : 0; + case DEST_INTEGER: + if (onlyIntegers) + return SQLINT8; + if (v == VAL_FLOAT) + return SQLFLT8; + if (!(v & ~(VAL_DECIMAL | VAL_INT))) + return SQLCHARACTER; + return 0; + case DEST_BIT: + if (onlyIntegers) + return SQLINT8; + return v == VAL_FLOAT ? SQLFLT8 : 0; + case DEST_FLOAT: + if (onlyIntegers) + return SQLINT8; + return !(v & ~(VAL_FLOAT | VAL_INT | VAL_BOOL)) ? SQLFLT8 : 0; + case DEST_DECIMAL: + if (v == VAL_INT) + return SQLINT8; + if (v == VAL_FLOAT) + return SQLFLT8; + return !(v & ~(VAL_DECIMAL | VAL_INT)) ? SQLCHARACTER : 0; + case DEST_MONEY: + if (v == VAL_INT) + return SQLINT8; + return !(v & ~(VAL_DECIMAL | VAL_INT)) ? SQLCHARACTER : 0; + case DEST_TIME: + return !(v & ~(VAL_TIME | VAL_DATETIME | VAL_STR)) ? SQLCHARACTER : 0; + case DEST_DATE: + case DEST_DATETIME2: + case DEST_DATETIMEOFFSET: + case DEST_DATETIME: + case DEST_SMALLDATETIME: + return !(v & ~(VAL_DATE | VAL_DATETIME)) ? SQLCHARACTER : 0; + case DEST_GUID: + return !(v & ~(VAL_UUID | VAL_STR)) ? SQLUNIQUEID : 0; + } + return 0; +} + +static bool is_temporal(int destination) +{ + switch (destination) { + case DEST_DATE: case DEST_TIME: case DEST_DATETIME2: case DEST_DATETIMEOFFSET: + case DEST_DATETIME: case DEST_SMALLDATETIME: + return true; + } + return false; +} + +/** + * Picks the host type for a column whose parameter has a setinputsizes entry, from the classes + * of value other than None it holds. The plain path sends each value as the entry's type and + * the server converts it to the column's, so only values of the entry's own kind are allowed, + * and only into columns whose server conversion the path reproduces (see + * test_bcp_matches_plain_path_with_input_sizes): + * + * - text as UTF-16 into char, varchar, nchar and nvarchar, as without an entry, once the scan + * has checked the code page of a char or varchar column holds it exactly (see + * encodes_exactly); + * - bool into bit, and bigint into the integer types, decimal, money, float and real; + * - double into float and real, the integer types (truncated toward zero), decimal (rounded + * from its exact binary value) and bit; + * - numeric into decimal and money (rounded half away from zero), the integer types + * (truncated toward zero) and float; + * - timestamp into the date and time types, rounded from all seven digits; + * - date into the date and time types other than time. + * + * A number into bit stores 1 when it is not zero. + * + * @return The host type, or 0 to fall back. + */ +static int entry_host_type(const ColumnPlan& plan, unsigned v) +{ + const int dest = plan.destination; + switch (plan.entry) { + case ENTRY_TEXT: + return v == VAL_STR && dest == DEST_CHAR ? SQLNCHAR : 0; + case ENTRY_BIT: + return v == VAL_BOOL && dest == DEST_BIT ? SQLBIT : 0; + case ENTRY_BIGINT: + if (v != VAL_INT) + return 0; + if (dest == DEST_BIT) + return SQLBIT; + return dest == DEST_INTEGER || dest == DEST_DECIMAL || dest == DEST_MONEY || dest == DEST_FLOAT ? SQLINT8 : 0; + case ENTRY_DOUBLE: + if (v != VAL_FLOAT) + return 0; + switch (dest) { + case DEST_BIT: + return SQLBIT; + case DEST_INTEGER: + return SQLINT8; + case DEST_DECIMAL: + return SQLCHARACTER; + case DEST_FLOAT: + return plan.target->systemType == 59 ? SQLFLT4 : SQLFLT8; + } + return 0; + case ENTRY_NUMERIC: + if (v != VAL_DECIMAL) + return 0; + switch (dest) { + case DEST_BIT: + return SQLBIT; + case DEST_INTEGER: + case DEST_DECIMAL: + case DEST_MONEY: + return SQLCHARACTER; + case DEST_FLOAT: + return plan.target->systemType == 62 ? SQLFLT8 : 0; + } + return 0; + case ENTRY_TIMESTAMP: + return !(v & ~(VAL_DATETIME | VAL_DATE)) && is_temporal(dest) ? SQLCHARACTER : 0; + case ENTRY_DATE: + return v == VAL_DATE && is_temporal(dest) && dest != DEST_TIME ? SQLCHARACTER : 0; + } + return 0; +} + +/** The class of value an entry's own type is sent for. */ +static unsigned entry_class(int entry) +{ + switch (entry) { + case ENTRY_TEXT: + return VAL_STR; + case ENTRY_BIT: + return VAL_BOOL; + case ENTRY_BIGINT: + return VAL_INT; + case ENTRY_DOUBLE: + return VAL_FLOAT; + case ENTRY_NUMERIC: + return VAL_DECIMAL; + case ENTRY_TIMESTAMP: + return VAL_DATETIME; + case ENTRY_DATE: + return VAL_DATE; + } + return 0; +} + +/** + * The host type for a column with an entry (see entry_host_type). The server converts even a + * NULL from its entry's type, and rejects one it has no implicit conversion for (nvarchar into + * binary, or date into int), so a column of NULLs takes an nvarchar entry into anything but a + * binary column, and any other entry only where a value of the entry's own kind may go. + */ +static int choose_entry_host_type(const ColumnPlan& plan, unsigned classes) +{ + const unsigned v = classes & ~VAL_NONE; + if (v) + return entry_host_type(plan, v); + if (plan.entry == ENTRY_TEXT) + return plan.destination != DEST_BINARY ? SQLCHARACTER : 0; + return entry_host_type(plan, entry_class(plan.entry)) ? SQLCHARACTER : 0; +} + +/** The host type for a column, or 0 to fall back. */ +static int choose_host_type(const ColumnPlan& plan, unsigned classes) +{ + return plan.entry == ENTRY_NONE ? choose_untyped_host_type(plan.destination, classes) + : choose_entry_host_type(plan, classes); +} + +/** + * Sets up a column per plan, then the NULL filler columns. Variable-length columns take a + * 4-byte length prefix, except (max) columns, which need an 8-byte prefix and, because the + * driver reads a zero-length 8-byte prefix as 64KB, every length passed to bcp_collen as well. + * + * @return 1 if every column has a host type, 0 to fall back, -1 on allocation failure. + */ +static int plan_columns(BcpLoad& load) +{ + load.cols = (BcpCol*)PyMem_Calloc((size_t)(load.ncols + load.nfill), sizeof(BcpCol)); + if (!load.cols) { + PyErr_NoMemory(); + return -1; + } + for (int f = 0; f < load.nfill; ++f) { + BcpCol* c = &load.cols[load.ncols + f]; + c->ordinal = load.target.ncols - load.nfill + f + 1; + c->hostType = SQLCHARACTER; + c->prefix = load.target.cols[c->ordinal - 1].maxLength == -1 ? 8 : 4; + if (!BcpAllocColumn(c)) + return -1; + write_le(c->scratch, ~0ULL, c->prefix); + } + for (int i = 0; i < load.ncols; ++i) { + const ColumnPlan& plan = load.plans[i]; + BcpCol* c = &load.cols[i]; + c->ordinal = plan.ordinal; + c->hostType = choose_host_type(plan, plan.classes); + if (!c->hostType) + return 0; + const bool fixed = c->hostType == SQLBIT || c->hostType == SQLINT8 || c->hostType == SQLFLT8 || + c->hostType == SQLFLT4 || c->hostType == SQLUNIQUEID; + const bool unlimited = plan.target->maxLength == -1; + c->prefix = fixed ? 0 : (unlimited ? 8 : 4); + c->setsCollen = !fixed && unlimited; + if (!BcpAllocColumn(c)) + return -1; + } + return 1; +} + +/*=======================================================================================*/ +// Filling columns +/*=======================================================================================*/ + +static bool unexpected_value(PyObject* cell) +{ + PyErr_Format(PyExc_TypeError, "unexpected %.100s value in a BCP column; the row changed while it was being sent", + Py_TYPE(cell)->tp_name); + return false; +} + +/** ASCII text the path formats itself, for a SQLCHARACTER or SQLNCHAR column. */ +static bool put_ascii(Connection* cnxn, BcpCol* c, const char* text, Py_ssize_t n) +{ + if (c->hostType == SQLNCHAR) + return BcpPutWidened(cnxn, c, (const unsigned char*)text, n); + return BcpPutBytes(cnxn, c, text, n); +} + +static bool put_int_text(Connection* cnxn, BcpCol* c, PyObject* cell) +{ + long long v = PyLong_AsLongLong(cell); + if (v == -1 && PyErr_Occurred()) + return false; + char buf[24]; + int n = snprintf(buf, sizeof(buf), "%lld", v); + return put_ascii(cnxn, c, buf, n); +} + +/** + * Python code run while filling a row (a Decimal subclass's __format__, a tzinfo's utcoffset) + * can close the cursor or the connection, either of which ends the load: the plain path cannot carry on + * either, and nothing may touch a closed connection's handle or BCP state. + */ +static bool load_still_open(const BcpLoad& load) +{ + if (!load.cursor->cnxn) { + PyErr_SetString(ProgrammingError, "The cursor was closed while BCP was sending rows."); + return false; + } + if (load.cnxn->hdbc && load.cnxn->bcp) + return true; + PyErr_SetString(ProgrammingError, "The connection was closed while BCP was sending rows."); + return false; +} + +/** Whether a value is a decimal.Decimal, not a subclass, which class_of leaves to the plain path. */ +static bool is_decimal(BcpLoad& load, PyObject* value) +{ + return Py_TYPE(value) == (PyTypeObject*)load.decimalType.Get(); +} + +/** + * Whether a Decimal is one the plain path's SQL_NUMERIC_STRUCT can hold, raising as that path + * does if not: a non-zero value needs a digit within 38 places and at most 38 whole digits, and + * a zero at most 32767 places. It is checked before formatting, which would otherwise build + * text as long as the exponent. `*zero` says the value is zero. + */ +static bool decimal_fits_numeric_struct(BcpLoad& load, PyObject* cell, bool* zero) +{ + const int nonzero = PyObject_IsTrue(cell); + if (nonzero < 0) + return false; + Object adjusted(PyObject_CallMethodNoArgs(cell, load.adjustedName)); + if (!adjusted.IsValid()) + return false; + int overflow = 0; + const long long e = PyLong_AsLongLongAndOverflow(adjusted, &overflow); + if (e == -1 && PyErr_Occurred()) + return false; + *zero = !nonzero; + const char* error = 0; + if (*zero) + error = overflow < 0 || (!overflow && e < -32767) + ? "Cannot bind a Decimal with more than 32767 digits after the decimal point" : 0; + else if (overflow > 0 || (!overflow && e > 37)) + error = "Numeric overflow"; + else if (overflow < 0 || e < -32767) + error = "Cannot bind a Decimal with more than 32767 digits after the decimal point"; + else if (e < -38) + error = "Converting decimal loses precision"; + if (error) + RaiseErrorV(0, ProgrammingError, "%s", error); + return !error; +} + +/** + * Whether the plain path binds a Decimal with this fixed-point text, raising as it does if not: + * NaN and the infinities have no digits, and more than 32767 places, which the exponent gives + * before trailing zeros are dropped, do not fit a SQLSMALLINT scale. + */ +static bool plain_path_binds_decimal_text(const char* text, Py_ssize_t n) +{ + const char* end = text + n; + const char* p = text + (n > 0 && text[0] == '-'); + if (p == end || *p < '0' || *p > '9') { + RaiseErrorV(0, ProgrammingError, "%s", p < end && *p == 's' ? "Cannot bind a Decimal signaling NaN" + : "Decimal NaN and Infinity cannot be used with fast_executemany or table-valued parameters"); + return false; + } + const char* point = (const char*)memchr(text, '.', (size_t)n); + if (point && end - point - 1 > 32767) { + RaiseErrorV(0, ProgrammingError, "Cannot bind a Decimal with more than 32767 digits after the decimal point"); + return false; + } + return true; +} + +/** + * A Decimal as exact fixed-point text without its fraction's trailing zeros, keeping every digit + * whatever the thread's decimal context, as the plain path does, and a zero as 0. `text` owns + * the characters, of which `*n` are the value's. + */ +static bool get_decimal_text(BcpLoad& load, PyObject* cell, Object& text, const char** chars, Py_ssize_t* n) +{ + if (!is_decimal(load, cell)) + return unexpected_value(cell); + bool zero = false; + if (!decimal_fits_numeric_struct(load, cell, &zero)) + return false; + if (zero) { + *chars = "0"; + *n = 1; + return true; + } + text = PyObject_Format(cell, load.decimalFormat); + if (!text.IsValid() || !load_still_open(load)) + return false; + *chars = PyUnicode_AsUTF8AndSize(text, n); + if (!*chars || !plain_path_binds_decimal_text(*chars, *n)) + return false; + *n = BcpTrimFractionZeros(*chars, *n); + return true; +} + +static bool put_decimal_text(BcpLoad& load, BcpCol* c, PyObject* cell) +{ + Object text; + const char* chars = 0; + Py_ssize_t n = 0; + return get_decimal_text(load, cell, text, &chars, &n) && put_ascii(load.cnxn, c, chars, n); +} + +/** + * A Decimal under a numeric entry, after the plain path's checks against that entry (see + * BcpFitsNumericEntry), converted as the server converts it: for a decimal or money column + * rounded half away from zero to the column's scale (4 for money), for an integer column + * truncated toward zero, for a float column the correctly rounded double, and for a bit column 1 + * unless it is zero. NaN and the infinities raise. + */ +static bool put_entry_decimal(BcpLoad& load, const ColumnPlan& plan, BcpCol* c, PyObject* cell) +{ + Object text; + const char* chars = 0; + Py_ssize_t n = 0; + BcpDecimalParts d; + if (!get_decimal_text(load, cell, text, &chars, &n) || !BcpSplitDecimalText(chars, n, d) || + !BcpFitsNumericEntry(d, plan.entrySize, plan.entryDigits)) + return false; + if (c->hostType == SQLBIT) { + const unsigned char b = d.nwhole > 0 || d.nfraction > 0; + return BcpPutFixed(load.cnxn, c, &b); + } + if (c->hostType == SQLFLT8) { + double value = PyOS_string_to_double(chars, 0, 0); + if (value == -1.0 && PyErr_Occurred()) + return false; + if (value == 0) + value = 0; + return BcpPutFixed(load.cnxn, c, &value); + } + const int scale = plan.destination == DEST_DECIMAL ? plan.target->scale : (plan.destination == DEST_MONEY ? 4 : 0); + char buf[96]; + return put_ascii(load.cnxn, c, buf, BcpShapeNumericText(d, scale, plan.destination != DEST_INTEGER, buf)); +} + +/** + * A value for a SQLBIT column: a bool, or under a bigint, double or numeric entry a number of + * that kind, which the server stores as 1 unless it is zero. A non-finite double raises, as the + * server rejects it. + */ +static bool put_bit(BcpLoad& load, const ColumnPlan& plan, BcpCol* c, PyObject* cell) +{ + unsigned char b; + switch (plan.entry) { + case ENTRY_BIGINT: { + if (!PyLong_Check(cell) || PyBool_Check(cell)) + return unexpected_value(cell); + const long long v = PyLong_AsLongLong(cell); + if (v == -1 && PyErr_Occurred()) + return false; + b = v != 0; + break; + } + case ENTRY_DOUBLE: { + if (!PyFloat_Check(cell)) + return unexpected_value(cell); + const double d = PyFloat_AS_DOUBLE(cell); + if (!std::isfinite(d)) + return BcpRaiseOutOfRange(); + b = d != 0; + break; + } + case ENTRY_NUMERIC: + return put_entry_decimal(load, plan, c, cell); + default: + if (!PyBool_Check(cell)) + return unexpected_value(cell); + b = cell == Py_True; + } + return BcpPutFixed(load.cnxn, c, &b); +} + +static bool suits_host_type(const ColumnPlan& plan, const BcpCol* c, unsigned cls); + +/** + * A uuid.UUID or canonical GUID str for a SQLUNIQUEID column, as the 16 bytes the plain path + * sends: a UUID's bytes_le, which can run Python code in a subclass. A bytes_le that is not 16 + * bytes raises, where the plain path would copy 16 bytes from whatever it was given. + */ +static bool put_guid(BcpLoad& load, const ColumnPlan& plan, BcpCol* c, PyObject* cell) +{ + unsigned char guid[16]; + if (PyUnicode_Check(cell)) + return suits_host_type(plan, c, VAL_STR) && parse_guid_text(cell, guid) ? BcpPutFixed(load.cnxn, c, guid) + : unexpected_value(cell); + const unsigned cls = class_of(cell); + if (!cls || !suits_host_type(plan, c, cls)) + return unexpected_value(cell); + Object bytesLe(PyObject_GetAttrString(cell, "bytes_le")); + if (!bytesLe.IsValid() && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + return unexpected_value(cell); + } + if (!bytesLe.IsValid() || !load_still_open(load)) + return false; + if (!PyBytes_Check(bytesLe.Get()) || PyBytes_GET_SIZE(bytesLe.Get()) != 16) { + PyErr_SetString(PyExc_TypeError, "UUID.bytes_le must be 16 bytes"); + return false; + } + return BcpPutFixed(load.cnxn, c, PyBytes_AS_STRING(bytesLe.Get())); +} + +/** Whether a value of class `cls` would still have given the column its host type. */ +static bool suits_host_type(const ColumnPlan& plan, const BcpCol* c, unsigned cls) +{ + return choose_host_type(plan, plan.classes | cls) == c->hostType; +} + +/** + * A value for a SQLCHARACTER column, as text the path formats or has checked. A row can change + * while it is being sent, so each value must still suit the column's host type and have a form + * the plain path stores, or the call raises. + */ +static bool fill_text(BcpLoad& load, const ColumnPlan& plan, BcpCol* c, PyObject* cell) +{ + if (PyBool_Check(cell)) + return unexpected_value(cell); + if (PyLong_Check(cell)) + return suits_host_type(plan, c, VAL_INT) ? put_int_text(load.cnxn, c, cell) : unexpected_value(cell); + if (PyFloat_Check(cell)) { + if (!suits_host_type(plan, c, VAL_FLOAT)) + return unexpected_value(cell); + char buf[96]; + const int n = BcpFormatDoubleAsDecimal(PyFloat_AS_DOUBLE(cell), plan.target->scale, buf); + return n >= 0 && put_ascii(load.cnxn, c, buf, n); + } + if (PyUnicode_Check(cell)) { + if (plan.destination != DEST_TIME || !suits_host_type(plan, c, VAL_STR) || !is_time_text(cell, plan.target->scale)) + return unexpected_value(cell); + return put_ascii(load.cnxn, c, (const char*)PyUnicode_1BYTE_DATA(cell), PyUnicode_GET_LENGTH(cell)); + } + if (PyDateTime_Check(cell) || PyDate_Check(cell) || PyTime_Check(cell)) { + const unsigned cls = PyDateTime_Check(cell) ? VAL_DATETIME : (PyDate_Check(cell) ? VAL_DATE : VAL_TIME); + if (!suits_host_type(plan, c, cls) || !has_plain_path_form(plan, cell, cls)) + return unexpected_value(cell); + char buf[48]; + const int n = BcpFormatTemporal(buf, sizeof(buf), cell, cls, plan.destination, plan.target->scale, + plan.entry == ENTRY_TIMESTAMP); + return n >= 0 && load_still_open(load) && put_ascii(load.cnxn, c, buf, n); + } + if (!suits_host_type(plan, c, VAL_DECIMAL)) + return unexpected_value(cell); + if (plan.entry == ENTRY_NUMERIC) + return put_entry_decimal(load, plan, c, cell); + return put_decimal_text(load, c, cell); +} + +/** + * A str for a SQLNCHAR column. For a zero-length value the driver stores the previous row's + * value in a char(n) column, which pads with spaces anyway, so an empty string goes there as one + * space, which stores the same. + */ +static bool put_str(Connection* cnxn, const ColumnPlan& plan, BcpCol* c, PyObject* s) +{ + if (PyUnicode_GET_LENGTH(s) == 0 && plan.target->systemType == 175) + return BcpPutWidened(cnxn, c, (const unsigned char*)" ", 1); + return BcpPutWideStr(cnxn, c, s); +} + +/** + * Fills one cell. A None swapped in after the scan raises where the bulk copy runs without + * KEEPNULLS and the column has a default, which the server would store in place of the NULL. + */ +static bool fill_cell(BcpLoad& load, const ColumnPlan& plan, BcpCol* c, PyObject* cell) +{ + Connection* cnxn = load.cnxn; + if (cell == Py_None) + return load.keepNulls || !plan.target->hasDefault ? BcpPutNull(cnxn, c) : unexpected_value(cell); + + switch (c->hostType) { + case SQLBIT: + return put_bit(load, plan, c, cell); + case SQLINT8: { + long long v; + if (plan.entry == ENTRY_DOUBLE) { + if (!PyFloat_Check(cell)) + return unexpected_value(cell); + if (!BcpTruncateDouble(PyFloat_AS_DOUBLE(cell), &v)) + return false; + } + else if (PyBool_Check(cell) && suits_host_type(plan, c, VAL_BOOL)) + v = cell == Py_True; + else if (PyLong_Check(cell) && !PyBool_Check(cell) && suits_host_type(plan, c, VAL_INT) && + fits_column(plan, cell, VAL_INT)) { + v = PyLong_AsLongLong(cell); + if (v == -1 && PyErr_Occurred()) + return false; + } + else + return unexpected_value(cell); + return BcpPutFixed(cnxn, c, &v); + } + case SQLFLT8: { + if (plan.entry == ENTRY_NUMERIC) + return put_entry_decimal(load, plan, c, cell); + double d; + if (PyFloat_Check(cell)) + d = PyFloat_AS_DOUBLE(cell); + else if (PyBool_Check(cell) && suits_host_type(plan, c, VAL_BOOL)) + d = cell == Py_True; + else if (PyLong_Check(cell) && !PyBool_Check(cell) && suits_host_type(plan, c, VAL_INT)) { + d = PyLong_AsDouble(cell); + if (d == -1.0 && PyErr_Occurred()) + return false; + } + else + return unexpected_value(cell); + return BcpPutFixed(cnxn, c, &d); + } + case SQLFLT4: { + float f; + if (!PyFloat_Check(cell)) + return unexpected_value(cell); + return BcpNarrowDouble(PyFloat_AS_DOUBLE(cell), &f) && BcpPutFixed(cnxn, c, &f); + } + case SQLBINARY: + if (!(PyBytes_Check(cell) || PyByteArray_Check(cell)) || !fits_column(plan, cell, VAL_BYTES)) + return unexpected_value(cell); + if (PyBytes_Check(cell)) + return BcpPutBytes(cnxn, c, PyBytes_AS_STRING(cell), PyBytes_GET_SIZE(cell)); + return BcpPutBytes(cnxn, c, PyByteArray_AS_STRING(cell), PyByteArray_GET_SIZE(cell)); + case SQLNCHAR: + if (PyUnicode_Check(cell) && fits_column(plan, cell, VAL_STR)) + return put_str(cnxn, plan, c, cell); + if (PyLong_Check(cell) && !PyBool_Check(cell) && plan.entry == ENTRY_NONE && suits_host_type(plan, c, VAL_INT) && + fits_column(plan, cell, VAL_INT)) + return put_int_text(cnxn, c, cell); + return unexpected_value(cell); + case SQLUNIQUEID: + return put_guid(load, plan, c, cell); + } + return fill_text(load, plan, c, cell); +} + +/*=======================================================================================*/ +// The transaction around a load +/*=======================================================================================*/ + +static bool execute_direct(HDBC hdbc, const char16_t* sql) +{ + HSTMT hstmt = SQL_NULL_HANDLE; + if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt))) + return false; + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = SQLExecDirectW(hstmt, (SQLWCHAR*)sql, SQL_NTS); + Py_END_ALLOW_THREADS + SQLFreeHandle(SQL_HANDLE_STMT, hstmt); + return SQL_SUCCEEDED(rc); +} + +/** + * Starts the load's transaction. In manual-commit mode the savepoint was already set by the + * catalog query in prepare_load, saving a round trip. + */ +static bool begin_load_transaction(Connection* cnxn, LoadTransaction& txn) +{ + if (cnxn->nAutoCommit == SQL_AUTOCOMMIT_ON) { + txn.autocommitSuspended = BcpSetAutocommit(cnxn->hdbc, false); + return txn.autocommitSuspended; + } + txn.savepoint = true; + return true; +} + +/** Commits a completed batch in autocommit mode; in manual-commit mode it stays in the caller's transaction. */ +static bool commit_load_batch(Connection* cnxn, const LoadTransaction& txn) +{ + return !txn.autocommitSuspended || BcpEndTransaction(cnxn->hdbc, true); +} + +static bool finish_load_transaction(Connection* cnxn, LoadTransaction& txn) +{ + if (!txn.autocommitSuspended) + return true; + if (!BcpEndTransaction(cnxn->hdbc, true)) + return false; + txn.autocommitSuspended = false; + BcpSetAutocommit(cnxn->hdbc, true); + return true; +} + +/** + * Undoes what the load sent and restores autocommit. A savepoint that no longer exists (the + * error aborted the whole transaction, as with XACT_ABORT ON) leaves nothing more to undo. + */ +static void rollback_load_transaction(Connection* cnxn, LoadTransaction& txn) +{ + if (txn.autocommitSuspended) { + BcpEndTransaction(cnxn->hdbc, false); + BcpSetAutocommit(cnxn->hdbc, true); + txn.autocommitSuspended = false; + } + if (txn.savepoint) { + execute_direct(cnxn->hdbc, u"IF XACT_STATE() = 1 ROLLBACK TRANSACTION pyodbc_bcp"); + txn.savepoint = false; + } +} + +/*=======================================================================================*/ +// The load +/*=======================================================================================*/ + +/** + * Reports a failure after rows may have been sent: raises (from the driver diagnostics unless a + * Python exception is already set), closes the bulk copy and rolls back everything it sent. + * The diagnostics are read before bcp_done, which clears them. + */ +static bool abandon_load(BcpLoad& load, LoadTransaction& txn, const char* function) +{ + Connection* cnxn = load.cnxn; + if (!PyErr_Occurred()) + RaiseErrorFromHandle(cnxn, function, cnxn->hdbc, SQL_NULL_HANDLE); + if (!cnxn->hdbc || !cnxn->bcp) + return true; + Py_BEGIN_ALLOW_THREADS + cnxn->bcp->procs.bcp_done(cnxn->hdbc); + Py_END_ALLOW_THREADS + rollback_load_transaction(cnxn, txn); + return true; +} + +/** + * Starts the bulk copy and binds the columns. Nothing has been sent yet, so on failure the + * session is closed, the transaction undone and the call falls back to the plain path. + */ +static bool start_bulk_copy(BcpLoad& load, Cursor* cur, LoadTransaction& txn) +{ + Connection* cnxn = load.cnxn; + const BcpProcs procs = cnxn->bcp->procs; + load.tableName = BcpQuotedTableName(load.insert); + if (!load.tableName) + return false; + SQLRETURN rc; + Py_BEGIN_ALLOW_THREADS + rc = procs.bcp_initW(cnxn->hdbc, load.tableName, nullptr, nullptr, DB_IN); + Py_END_ALLOW_THREADS + if (rc != SUCCEED) + return false; + + bool ok = (!load.keepNulls || procs.bcp_control(cnxn->hdbc, BCPKEEPNULLS, (void*)(uintptr_t)1) == SUCCEED) + && procs.bcp_control(cnxn->hdbc, BCPHINTS, + (void*)(cur->bcp_tablock ? "CHECK_CONSTRAINTS,FIRE_TRIGGERS,TABLOCK" + : "CHECK_CONSTRAINTS,FIRE_TRIGGERS")) == SUCCEED; + for (int i = 0; ok && i < load.ncols + load.nfill; ++i) + ok = BcpBindColumn(cnxn, &load.cols[i]); + if (!ok) { + Py_BEGIN_ALLOW_THREADS + procs.bcp_done(cnxn->hdbc); + Py_END_ALLOW_THREADS + } + return ok; +} + +/** + * Sends every row, batching every cur->bcp_batch_rows rows, and finishes the bulk copy. Python + * code can run whenever a reference is dropped, so the connection is checked before each cell + * and before each row is sent. + * + * @return true on success with *copied set; false with an error raised and the load undone. + */ +static bool send_rows(BcpLoad& load, Cursor* cur, LoadTransaction& txn, long long* copied) +{ + Connection* cnxn = load.cnxn; + const BcpProcs procs = cnxn->bcp->procs; + const Py_ssize_t nrows = PyTuple_GET_SIZE(load.rows.Get()); + const long batchRows = cur->bcp_batch_rows; + long unbatched = 0; + SQLRETURN rc; + DBINT count; + + *copied = 0; + for (Py_ssize_t r = 0; r < nrows; ++r) { + PyObject* row = PyTuple_GET_ITEM(load.rows.Get(), r); + for (int i = 0; i < load.ncols; ++i) { + if (!load_still_open(load)) + return !abandon_load(load, txn, "bcp_sendrow"); + if (!is_row(row, load.ncols)) { + PyErr_SetString(PyExc_TypeError, "a row changed length while it was being sent by BCP"); + return !abandon_load(load, txn, "bcp_sendrow"); + } + Object cell(PySequence_Fast_GET_ITEM(row, i)); + Py_INCREF(cell.Get()); + if (!fill_cell(load, load.plans[i], &load.cols[i], cell)) + return !abandon_load(load, txn, "bcp_collen"); + } + if (!load_still_open(load)) + return !abandon_load(load, txn, "bcp_sendrow"); + Py_BEGIN_ALLOW_THREADS + rc = procs.bcp_sendrow(cnxn->hdbc); + Py_END_ALLOW_THREADS + if (rc != SUCCEED) + return !abandon_load(load, txn, "bcp_sendrow"); + + if (batchRows > 0 && ++unbatched == batchRows) { + Py_BEGIN_ALLOW_THREADS + count = procs.bcp_batch(cnxn->hdbc); + Py_END_ALLOW_THREADS + if (count < 0) + return !abandon_load(load, txn, "bcp_batch"); + if (!commit_load_batch(cnxn, txn)) + return !abandon_load(load, txn, "SQLEndTran"); + *copied += count; + unbatched = 0; + } + } + + Py_BEGIN_ALLOW_THREADS + count = procs.bcp_done(cnxn->hdbc); + Py_END_ALLOW_THREADS + if (count < 0) { + RaiseErrorFromHandle(cnxn, "bcp_done", cnxn->hdbc, SQL_NULL_HANDLE); + rollback_load_transaction(cnxn, txn); + return false; + } + *copied += count; + if (*copied != nrows) { + PyErr_Format(PyExc_RuntimeError, "BCP copied %lld of %zd rows", *copied, nrows); + rollback_load_transaction(cnxn, txn); + return false; + } + if (!finish_load_transaction(cnxn, txn)) { + RaiseErrorFromHandle(cnxn, "SQLEndTran", cnxn->hdbc, SQL_NULL_HANDLE); + rollback_load_transaction(cnxn, txn); + return false; + } + return true; +} + +/** + * Prepares a load: parses the INSERT, loads the destination columns, maps the parameters and + * their setinputsizes entries (`inputSizes`, null if none) to columns, scans the rows and picks + * host types, all before anything is sent. A table with an enabled INSERT trigger + * is left to the plain path: a trigger that rolls back a bulk copy run inside a transaction + * leaves the driver unable to use the connection again. So is a call during which the rows' + * Python code opened a BCP session or changed autocommit, on which the catalog query's + * savepoint was decided; closing the connection or the cursor raises. + * + * @return 1 to go ahead, 0 to fall back to the plain path, -1 on error (Python exception set). + */ +static int prepare_load(BcpLoad& load, PyObject* pSql, PyObject* param_seq, PyObject* inputSizes) +{ + Connection* cnxn = load.cnxn; + + Py_ssize_t sqlLen = 0; + const char* sql = PyUnicode_AsUTF8AndSize(pSql, &sqlLen); + if (!sql) { + PyErr_Clear(); + return 0; + } + if ((Py_ssize_t)strlen(sql) != sqlLen) + return 0; + int r = BcpParseInsert(sql, &load.insert); + if (r <= 0) + return r; + load.insertParsed = true; + + if (!BcpEnsureLoaded(cnxn)) + return PyErr_Occurred() ? -1 : 0; + if (cnxn->bcp->sessionOpen || !BcpIsEnabled(cnxn->hdbc)) + return 0; + + const bool manualCommit = cnxn->nAutoCommit == SQL_AUTOCOMMIT_OFF; + if ((r = BcpLoadTarget(cnxn, load.insert, manualCommit, &load.target)) <= 0) + return r; + if (load.target.hasInsertTrigger) + return 0; + if ((r = map_columns(load)) <= 0) + return r; + if (!read_entries(load, inputSizes)) + return 0; + + load.rows = PySequence_Tuple(param_seq); + if (!load.rows.IsValid()) + return -1; + if (!scan_rows(load) || !choose_keep_nulls(load)) + return 0; + if ((r = plan_columns(load)) <= 0) + return r; + + load.decimalType = GetClassForThread("decimal", "Decimal"); + load.decimalFormat = PyUnicode_FromString("f"); + load.adjustedName = PyUnicode_InternFromString("adjusted"); + if (!load.decimalType.IsValid() || !load.decimalFormat.IsValid() || !load.adjustedName.IsValid() || + !load_still_open(load)) + return -1; + return !cnxn->bcp->sessionOpen && (cnxn->nAutoCommit == SQL_AUTOCOMMIT_OFF) == manualCommit; +} + +/** + * A snapshot of the cursor's setinputsizes entries, a tuple or list, for the load to read while + * the GIL is released: true with `*sizes` null if there are none, false for entries of another + * kind, which the path leaves to the plain path. + */ +static bool snapshot_sizes(PyObject* inputSizes, Object& sizes) +{ + if (!inputSizes) + return true; + if (PyTuple_Check(inputSizes)) + sizes = Py_NewRef(inputSizes); + else if (PyList_Check(inputSizes)) + sizes = PyList_AsTuple(inputSizes); + else + return false; + return true; +} + +bool ExecuteMulti_BCP(Cursor* cur, PyObject* pSql, PyObject* param_seq) +{ + if (!cur->use_bcp_fast || !PyUnicode_Check(pSql)) + return false; + + BcpLoad load(cur); + if (!snapshot_sizes(cur->inputsizes, load.sizes)) + return false; + if (cur->inputsizes && !load.sizes.IsValid()) + return true; + int prepared = prepare_load(load, pSql, param_seq, load.sizes.Get()); + if (prepared <= 0) + return prepared < 0; + + LoadTransaction txn = {false, false}; + if (!begin_load_transaction(load.cnxn, txn)) + return false; + load.mark_session(txn.autocommitSuspended); + if (!start_bulk_copy(load, cur, txn)) { + rollback_load_transaction(load.cnxn, txn); + return PyErr_Occurred() != 0; + } + + long long copied = 0; + if (send_rows(load, cur, txn, &copied)) + cur->rowcount = (int)copied; + return true; +} diff --git a/src/bcp_support.cpp b/src/bcp_support.cpp index 588e17b8..faea4e6b 100644 --- a/src/bcp_support.cpp +++ b/src/bcp_support.cpp @@ -119,8 +119,11 @@ static bool is_microsoft_driver(const char* drv) return strncmp(lower, "msodbcsql", 9) == 0; } -/** Returns the major version in SQLGetInfo(SQL_DRIVER_VER), "##.##.####", or 0 if unknown. */ -static int get_driver_major_version(HDBC hdbc) +/** + * Returns the major version in SQLGetInfo(SQL_DRIVER_VER), "##.##.####", times 100 plus the + * minor version (at most 99), or 0 if unknown. + */ +static int get_driver_version(HDBC hdbc) { char ver[32] = {0}; SQLSMALLINT outlen = 0; @@ -128,7 +131,11 @@ static int get_driver_major_version(HDBC hdbc) return 0; ver[sizeof(ver) - 1] = '\0'; const long major = strtol(ver, 0, 10); - return major > 0 && major < 10000 ? (int)major : 0; + const char* point = strchr(ver, '.'); + const long minor = point ? strtol(point + 1, 0, 10) : 0; + if (major <= 0 || major >= 10000 || minor < 0) + return 0; + return (int)(major * 100 + (minor > 99 ? 99 : minor)); } /** @@ -138,7 +145,7 @@ static int get_driver_major_version(HDBC hdbc) * 11 leave a failed bcp_batch or bcp_done without diagnostics when the Windows driver manager * pools connections, as pyodbc has it do by default, so their errors could not be raised. */ -static bool load_driver_procs(HDBC hdbc, BcpProcs& out) +static bool load_driver_procs(HDBC hdbc, int driverVersion, BcpProcs& out) { char drv[256] = {0}; if (!get_driver_name(hdbc, drv, sizeof(drv))) { @@ -150,9 +157,8 @@ static bool load_driver_procs(HDBC hdbc, BcpProcs& out) BCPLOAD_DBG("load: not the Microsoft ODBC Driver for SQL Server\n"); return false; } - int major = get_driver_major_version(hdbc); - if (major < 13) { - BCPLOAD_DBG("load: driver version %d is older than 13\n", major); + if (driverVersion < 1300) { + BCPLOAD_DBG("load: driver version %d is older than 13\n", driverVersion / 100); return false; } @@ -181,11 +187,19 @@ bool BcpEnsureLoaded(Connection* cnxn) PyErr_NoMemory(); return false; } - state->loaded = load_driver_procs(cnxn->hdbc, state->procs); + state->driverVersion = get_driver_version(cnxn->hdbc); + state->loaded = load_driver_procs(cnxn->hdbc, state->driverVersion, state->procs); cnxn->bcp = state; return state->loaded; } +bool BcpIsEnabled(HDBC hdbc) +{ + SQLUINTEGER value = 0; + SQLRETURN rc = SQLGetConnectAttr(hdbc, SQL_COPT_SS_BCP, &value, SQL_IS_UINTEGER, 0); + return SQL_SUCCEEDED(rc) && value == SQL_BCP_ON; +} + bool BcpSetAutocommit(HDBC hdbc, bool on) { SQLRETURN rc; @@ -205,6 +219,531 @@ bool BcpEndTransaction(HDBC hdbc, bool commit) return SQL_SUCCEEDED(rc); } +/*=======================================================================================*/ +// INSERT statement parsing +/*=======================================================================================*/ + +static int is_space(char c) +{ + return c==' ' || c=='\t' || c=='\r' || c=='\n' || c=='\f' || c=='\v'; +} + +static char up(char c) { return (c>='a' && c<='z') ? (char)(c - 'a' + 'A') : c; } + +/** + * Skips whitespace, line comments and block comments. T-SQL block comments nest; an + * inner comment ends this scan early, which leaves text the parser then rejects, so nesting can + * only make the parser fall back, never accept something T-SQL reads differently. + */ +static const char* skip_ws_and_comments(const char* p) +{ + for (;;) { + while (is_space(*p)) + ++p; + if (p[0] == '-' && p[1] == '-') { + p += 2; + while (*p && *p != '\n' && *p != '\r') + ++p; + continue; + } + if (p[0] == '/' && p[1] == '*') { + p += 2; + while (*p && !(p[0] == '*' && p[1] == '/')) + ++p; + if (*p) + p += 2; + continue; + } + return p; + } +} + +/** Case-insensitively matches a whole keyword at *pp, advancing past it on success. */ +static int match_kw(const char** pp, const char* kw) +{ + const char* p = *pp; + for (const char* k = kw; *k; ++k, ++p) + if (up(*p) != *k) + return 0; + char c = *p; + if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || + c == '@' || c == '#' || c == '$' || (unsigned char)c >= 0x80) + return 0; + *pp = p; + return 1; +} + +/** Parses an identifier delimited by `open`/`close`, where a doubled `close` is a literal one. */ +static int parse_delimited_ident(const char** pp, char close, char* buf, int cap) +{ + const char* p = *pp + 1; + int n = 0; + while (*p) { + if (*p == close) { + if (p[1] != close) { + *pp = p + 1; + buf[n] = '\0'; + return n; + } + ++p; + } + if (n + 1 >= cap) + return -1; + buf[n++] = *p++; + } + return -1; +} + +static int is_ident_start(char c) +{ + return (c>='A' && c<='Z') || (c>='a' && c<='z') || c=='_' || c=='#' || c=='@'; +} + +static int is_ident_part(char c) +{ + return is_ident_start(c) || (c>='0' && c<='9') || c=='$'; +} + +/** The T-SQL reserved keywords, sorted, which cannot be used as undelimited identifiers. */ +static const char* const RESERVED_WORDS[] = { + "ADD", "ALL", "ALTER", "AND", "ANY", "AS", "ASC", "AUTHORIZATION", "BACKUP", "BEGIN", + "BETWEEN", "BREAK", "BROWSE", "BULK", "BY", "CASCADE", "CASE", "CHECK", "CHECKPOINT", + "CLOSE", "CLUSTERED", "COALESCE", "COLLATE", "COLUMN", "COMMIT", "COMPUTE", "CONSTRAINT", + "CONTAINS", "CONTAINSTABLE", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CURRENT", + "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", + "DBCC", "DEALLOCATE", "DECLARE", "DEFAULT", "DELETE", "DENY", "DESC", "DISK", "DISTINCT", + "DISTRIBUTED", "DOUBLE", "DROP", "DUMP", "ELSE", "END", "ERRLVL", "ESCAPE", "EXCEPT", "EXEC", + "EXECUTE", "EXISTS", "EXIT", "EXTERNAL", "FETCH", "FILE", "FILLFACTOR", "FOR", "FOREIGN", + "FREETEXT", "FREETEXTTABLE", "FROM", "FULL", "FUNCTION", "GOTO", "GRANT", "GROUP", "HAVING", + "HOLDLOCK", "IDENTITY", "IDENTITYCOL", "IDENTITY_INSERT", "IF", "IN", "INDEX", "INNER", + "INSERT", "INTERSECT", "INTO", "IS", "JOIN", "KEY", "KILL", "LEFT", "LIKE", "LINENO", "LOAD", + "MERGE", "NATIONAL", "NOCHECK", "NONCLUSTERED", "NOT", "NULL", "NULLIF", "OF", "OFF", + "OFFSETS", "ON", "OPEN", "OPENDATASOURCE", "OPENQUERY", "OPENROWSET", "OPENXML", "OPTION", + "OR", "ORDER", "OUTER", "OVER", "PERCENT", "PIVOT", "PLAN", "PRECISION", "PRIMARY", "PRINT", + "PROC", "PROCEDURE", "PUBLIC", "RAISERROR", "READ", "READTEXT", "RECONFIGURE", "REFERENCES", + "REPLICATION", "RESTORE", "RESTRICT", "RETURN", "REVERT", "REVOKE", "RIGHT", "ROLLBACK", + "ROWCOUNT", "ROWGUIDCOL", "RULE", "SAVE", "SCHEMA", "SECURITYAUDIT", "SELECT", + "SEMANTICKEYPHRASETABLE", "SEMANTICSIMILARITYDETAILSTABLE", "SEMANTICSIMILARITYTABLE", + "SESSION_USER", "SET", "SETUSER", "SHUTDOWN", "SOME", "STATISTICS", "SYSTEM_USER", "TABLE", + "TABLESAMPLE", "TEXTSIZE", "THEN", "TO", "TOP", "TRAN", "TRANSACTION", "TRIGGER", "TRUNCATE", + "TRY_CONVERT", "TSEQUAL", "UNION", "UNIQUE", "UNPIVOT", "UPDATE", "UPDATETEXT", "USE", "USER", + "VALUES", "VARYING", "VIEW", "WAITFOR", "WHEN", "WHERE", "WHILE", "WITH", "WITHIN", + "WRITETEXT", +}; + +static int compare_reserved(const void* key, const void* item) +{ + return strcmp((const char*)key, *(const char* const*)item); +} + +static bool is_reserved_word(const char* ident) +{ + char upper[40]; + size_t n = strlen(ident); + if (n >= sizeof(upper)) + return false; + for (size_t i = 0; i <= n; ++i) + upper[i] = up(ident[i]); + return bsearch(upper, RESERVED_WORDS, sizeof(RESERVED_WORDS) / sizeof(RESERVED_WORDS[0]), + sizeof(RESERVED_WORDS[0]), compare_reserved) != 0; +} + +/** + * Parses a regular or bracket-delimited identifier. Regular identifiers are limited to ASCII + * and may not be reserved words; quote-delimited ones are not accepted at all, since their + * meaning depends on the connection's QUOTED_IDENTIFIER setting. Statements using any of + * these are left to the plain path. + */ +static int parse_identifier(const char** pp, char* buf, int cap) +{ + const char* p = *pp; + if (*p == '[') + return parse_delimited_ident(pp, ']', buf, cap); + if (!is_ident_start(*p)) + return -1; + int n = 0; + while (is_ident_part(*p)) { + if (n + 1 >= cap) + return -1; + buf[n++] = *p++; + } + if ((unsigned char)*p >= 0x80) + return -1; + buf[n] = '\0'; + if (is_reserved_word(buf)) + return -1; + *pp = p; + return n; +} + +/** Parses `( ? [, ?]... )`, returning the number of markers or 0 if it is anything else. */ +static int parse_markers(const char** pp) +{ + const char* p = skip_ws_and_comments(*pp); + if (*p != '(') + return 0; + ++p; + int n = 0; + for (;;) { + p = skip_ws_and_comments(p); + if (*p != '?') + return 0; + ++p; + ++n; + p = skip_ws_and_comments(p); + if (*p == ',') { ++p; continue; } + if (*p == ')') { ++p; break; } + return 0; + } + *pp = p; + return n; +} + +static int names_append(BcpInsert* ins, int* cap, const char* s) +{ + if (ins->nnames == *cap) { + int ncap = *cap ? *cap * 2 : 8; + char** np = (char**)PyMem_Realloc(ins->names, (size_t)ncap * sizeof(char*)); + if (!np) + return 0; + ins->names = np; + *cap = ncap; + } + size_t len = strlen(s); + char* copy = (char*)PyMem_Malloc(len + 1); + if (!copy) + return 0; + memcpy(copy, s, len + 1); + ins->names[ins->nnames++] = copy; + return 1; +} + +void BcpFreeInsert(BcpInsert* ins) +{ + for (int i = 0; i < ins->nnames; ++i) + PyMem_Free(ins->names[i]); + PyMem_Free(ins->names); + ins->names = 0; + ins->nnames = 0; +} + +int BcpParseInsert(const char* sql, BcpInsert* out) +{ + memset(out, 0, sizeof(*out)); + + const char* p = skip_ws_and_comments(sql); + if (!match_kw(&p, "INSERT")) + return 0; + p = skip_ws_and_comments(p); + if (match_kw(&p, "TOP")) + return 0; + if (match_kw(&p, "INTO")) + p = skip_ws_and_comments(p); + + char parts[3][sizeof(out->table)]; + int nparts = 0; + for (;;) { + if (nparts == 3 || parse_identifier(&p, parts[nparts], (int)sizeof(parts[0])) <= 0) + return 0; + ++nparts; + p = skip_ws_and_comments(p); + if (*p != '.') + break; + ++p; + p = skip_ws_and_comments(p); + while (nparts < 3 && *p == '.') { + parts[nparts++][0] = '\0'; + p = skip_ws_and_comments(p + 1); + } + } + strcpy(out->table, parts[nparts - 1]); + if (nparts >= 2) + strcpy(out->schema, parts[nparts - 2]); + if (nparts == 3) + strcpy(out->catalog, parts[0]); + if (out->table[0] == '@') + return 0; + if (out->table[0] == '#' && !out->catalog[0]) + strcpy(out->catalog, "tempdb"); + + int cap = 0; + if (*p == '(') { + ++p; + for (;;) { + p = skip_ws_and_comments(p); + char ident[sizeof(out->table)]; + if (parse_identifier(&p, ident, (int)sizeof(ident)) <= 0) { + BcpFreeInsert(out); + return 0; + } + if (!names_append(out, &cap, ident)) { + BcpFreeInsert(out); + PyErr_NoMemory(); + return -1; + } + p = skip_ws_and_comments(p); + if (*p == ',') { ++p; continue; } + if (*p == ')') { ++p; break; } + BcpFreeInsert(out); + return 0; + } + p = skip_ws_and_comments(p); + } + + if (!match_kw(&p, "VALUES") || (out->nmarkers = parse_markers(&p)) == 0) { + BcpFreeInsert(out); + return 0; + } + p = skip_ws_and_comments(p); + if (*p == ';') + p = skip_ws_and_comments(p + 1); + if (*p != '\0') { + BcpFreeInsert(out); + return 0; + } + return 1; +} + +SQLWCHAR* BcpUtf8ToSqlWChar(const char* s) +{ + Object text(PyUnicode_DecodeUTF8(s, (Py_ssize_t)strlen(s), "strict")); + if (!text.IsValid()) + return 0; + Object encoded(PyUnicode_AsEncodedString(text, "utf-16-le", "strict")); + if (!encoded.IsValid()) + return 0; + Py_ssize_t nbytes = PyBytes_GET_SIZE(encoded.Get()); + SQLWCHAR* w = (SQLWCHAR*)PyMem_Malloc((size_t)nbytes + sizeof(SQLWCHAR)); + if (!w) { + PyErr_NoMemory(); + return 0; + } + memcpy(w, PyBytes_AS_STRING(encoded.Get()), (size_t)nbytes); + w[nbytes / (Py_ssize_t)sizeof(SQLWCHAR)] = 0; + return w; +} + +/** Appends `[ident]`, doubling any `]`, to a NUL-terminated buffer of capacity cap. */ +static bool append_quoted(char* dst, size_t cap, const char* ident) +{ + size_t n = strlen(dst); + if (n + 1 >= cap) + return false; + dst[n++] = '['; + for (const char* s = ident; *s; ++s) { + if (n + 3 >= cap) + return false; + dst[n++] = *s; + if (*s == ']') + dst[n++] = ']'; + } + if (n + 2 > cap) + return false; + dst[n++] = ']'; + dst[n] = '\0'; + return true; +} + +/** Builds the quoted table name as UTF-8, e.g. "[db].[dbo].[t]" or "[tempdb]..[#t]". */ +static bool quoted_table_name_utf8(const BcpInsert& ins, char* buf, size_t cap) +{ + buf[0] = '\0'; + if (ins.catalog[0] && (!append_quoted(buf, cap, ins.catalog) || strlen(buf) + 2 > cap)) + return false; + if (ins.catalog[0]) + strcat(buf, "."); + if (ins.schema[0] && !append_quoted(buf, cap, ins.schema)) + return false; + if ((ins.catalog[0] || ins.schema[0]) && strlen(buf) + 2 > cap) + return false; + if (ins.catalog[0] || ins.schema[0]) + strcat(buf, "."); + return append_quoted(buf, cap, ins.table); +} + +SQLWCHAR* BcpQuotedTableName(const BcpInsert& ins) +{ + char name[3 * (2 * sizeof(ins.table) + 3)]; + if (!quoted_table_name_utf8(ins, name, sizeof(name))) { + PyErr_SetString(PyExc_ValueError, "table name too long for BCP"); + return 0; + } + return BcpUtf8ToSqlWChar(name); +} + +/*=======================================================================================*/ +// Destination table metadata +/*=======================================================================================*/ + +void BcpFreeTarget(BcpTarget* target) +{ + PyMem_Free(target->cols); + target->cols = 0; + target->ncols = 0; +} + +static size_t sqlwchar_len(const SQLWCHAR* s) +{ + size_t n = 0; + while (s[n]) + ++n; + return n; +} + +/** + * Runs the catalog query on its own statement handle and collects the rows into *out. A + * column scale outside 0 to 38, which no SQL Server type has, leaves the table to the plain path, + * since the formatters size their buffers from it. + * + * @return 1 for a user table with at least one visible column, 0 otherwise, -1 on allocation + * failure (Python exception set). + */ +static int fetch_target_columns(HDBC hdbc, SQLWCHAR* sql, SQLWCHAR* database, SQLWCHAR* name, BcpTarget* out) +{ + HSTMT hstmt = SQL_NULL_HANDLE; + if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt))) + return 0; + + int result = 0; + int cap = 0; + SQLLEN cbDatabase = SQL_NTS, cbName = SQL_NTS; + char type[4] = {0}; + BcpTargetColumn col; + SQLINTEGER systemType = 0, maxLength = 0, scale = 0, identity = 0, computed = 0, defaultId = 0; + SQLINTEGER hasTrigger = 0, ignoreCase = 0, codePage = 0; + SQLLEN cbType = 0, cbColName = 0, cbSystemType = 0, cbMaxLength = 0, cbScale = 0, cbIdentity = 0, + cbComputed = 0, cbDefault = 0, cbTrigger = 0, cbIgnoreCase = 0, cbCodePage = 0; + SQLSMALLINT resultCols = 0; + SQLRETURN rc; + + SQLULEN databaseChars = (SQLULEN)sqlwchar_len(database); + SQLULEN nameChars = (SQLULEN)sqlwchar_len(name); + if (!SQL_SUCCEEDED(SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_WVARCHAR, + databaseChars ? databaseChars : 1, 0, database, 0, &cbDatabase)) || + !SQL_SUCCEEDED(SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_WVARCHAR, + nameChars ? nameChars : 1, 0, name, 0, &cbName))) + goto done; + Py_BEGIN_ALLOW_THREADS + rc = SQLExecDirectW(hstmt, sql, SQL_NTS); + Py_END_ALLOW_THREADS + while (SQL_SUCCEEDED(rc) && SQL_SUCCEEDED(SQLNumResultCols(hstmt, &resultCols)) && resultCols == 0) { + Py_BEGIN_ALLOW_THREADS + rc = SQLMoreResults(hstmt); + Py_END_ALLOW_THREADS + } + if (!SQL_SUCCEEDED(rc)) + goto done; + + SQLBindCol(hstmt, 1, SQL_C_CHAR, type, sizeof(type), &cbType); + SQLBindCol(hstmt, 2, SQL_C_WCHAR, col.name, sizeof(col.name), &cbColName); + SQLBindCol(hstmt, 3, SQL_C_SLONG, &systemType, 0, &cbSystemType); + SQLBindCol(hstmt, 4, SQL_C_SLONG, &maxLength, 0, &cbMaxLength); + SQLBindCol(hstmt, 5, SQL_C_SLONG, &scale, 0, &cbScale); + SQLBindCol(hstmt, 6, SQL_C_SLONG, &identity, 0, &cbIdentity); + SQLBindCol(hstmt, 7, SQL_C_SLONG, &computed, 0, &cbComputed); + SQLBindCol(hstmt, 8, SQL_C_SLONG, &defaultId, 0, &cbDefault); + SQLBindCol(hstmt, 9, SQL_C_SLONG, &hasTrigger, 0, &cbTrigger); + SQLBindCol(hstmt, 10, SQL_C_SLONG, &ignoreCase, 0, &cbIgnoreCase); + SQLBindCol(hstmt, 11, SQL_C_SLONG, &codePage, 0, &cbCodePage); + + result = 1; + for (;;) { + Py_BEGIN_ALLOW_THREADS + rc = SQLFetch(hstmt); + Py_END_ALLOW_THREADS + if (rc == SQL_NO_DATA) + break; + if (!SQL_SUCCEEDED(rc) || type[0] != 'U' || cbColName == SQL_NULL_DATA) { + result = 0; + break; + } + if (out->ncols == cap) { + int ncap = cap ? cap * 2 : 16; + BcpTargetColumn* np = (BcpTargetColumn*)PyMem_Realloc(out->cols, (size_t)ncap * sizeof(BcpTargetColumn)); + if (!np) { + PyErr_NoMemory(); + result = -1; + break; + } + out->cols = np; + cap = ncap; + } + if (scale < 0 || scale > 38) { + result = 0; + break; + } + col.systemType = (int)systemType; + col.maxLength = (int)maxLength; + col.scale = (int)scale; + col.codePage = cbCodePage == SQL_NULL_DATA ? 0 : (int)codePage; + col.identity = identity != 0; + col.computed = computed != 0; + col.hasDefault = defaultId != 0; + out->cols[out->ncols++] = col; + out->hasInsertTrigger = hasTrigger != 0; + out->caseInsensitive = cbIgnoreCase != SQL_NULL_DATA && ignoreCase != 0; + } + if (result == 1 && out->ncols == 0) + result = 0; + +done: + SQLFreeHandle(SQL_HANDLE_STMT, hstmt); + if (result != 1) + BcpFreeTarget(out); + return result; +} + +int BcpLoadTarget(Connection* cnxn, const BcpInsert& ins, bool setSavepoint, BcpTarget* out) +{ + out->ncols = 0; + out->cols = 0; + out->hasInsertTrigger = false; + out->caseInsensitive = false; + + char db[2 * sizeof(ins.catalog) + 4] = ""; + if (ins.catalog[0] && (!append_quoted(db, sizeof(db) - 1, ins.catalog))) + return 0; + if (ins.catalog[0]) + strcat(db, "."); + + char sql[4 * sizeof(db) + 900]; + snprintf(sql, sizeof(sql), + "%sSELECT o.type, c.name, c.system_type_id, c.max_length, c.scale, c.is_identity, c.is_computed, " + "c.default_object_id, " + "CASE WHEN EXISTS (SELECT 1 FROM %ssys.triggers tr JOIN %ssys.trigger_events te ON te.object_id = tr.object_id " + "WHERE tr.parent_id = o.object_id AND tr.is_disabled = 0 AND te.type = 1) THEN 1 ELSE 0 END, " + "CONVERT(int, COLLATIONPROPERTY((SELECT d.collation_name FROM sys.databases d " + "WHERE d.name = COALESCE(NULLIF(?, N''), DB_NAME())), 'ComparisonStyle')) & 1, " + "CONVERT(int, COLLATIONPROPERTY(c.collation_name, 'CodePage')) " + "FROM %ssys.objects o JOIN %ssys.columns c ON c.object_id = o.object_id " + "WHERE o.object_id = OBJECT_ID(?) ORDER BY c.column_id", + setSavepoint ? "SAVE TRANSACTION pyodbc_bcp; " : "", db, db, db, db); + + SQLWCHAR* wsql = BcpUtf8ToSqlWChar(sql); + if (!wsql) + return -1; + SQLWCHAR* wdatabase = BcpUtf8ToSqlWChar(ins.catalog); + if (!wdatabase) { + PyMem_Free(wsql); + return -1; + } + SQLWCHAR* wname = BcpQuotedTableName(ins); + if (!wname) { + PyMem_Free(wdatabase); + PyMem_Free(wsql); + if (PyErr_ExceptionMatches(PyExc_ValueError)) { + PyErr_Clear(); + return 0; + } + return -1; + } + int result = fetch_target_columns(cnxn->hdbc, wsql, wdatabase, wname, out); + PyMem_Free(wname); + PyMem_Free(wdatabase); + PyMem_Free(wsql); + return result; +} + /*=======================================================================================*/ // Column buffers /*=======================================================================================*/ @@ -339,6 +878,16 @@ bool BcpPutWidened(Connection* cnxn, BcpCol* c, const unsigned char* text, Py_ss return true; } +bool BcpPutWideStr(Connection* cnxn, BcpCol* c, PyObject* s) +{ + if (PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) + return BcpPutWidened(cnxn, c, PyUnicode_1BYTE_DATA(s), PyUnicode_GET_LENGTH(s)); + Object utf16(PyUnicode_AsEncodedString(s, "utf-16-le", "strict")); + if (!utf16.IsValid()) + return false; + return BcpPutBytes(cnxn, c, PyBytes_AS_STRING(utf16.Get()), PyBytes_GET_SIZE(utf16.Get())); +} + /*=======================================================================================*/ // Low-level API values /*=======================================================================================*/ diff --git a/src/bcp_support.h b/src/bcp_support.h index ac24c2f8..afdf5178 100644 --- a/src/bcp_support.h +++ b/src/bcp_support.h @@ -1,7 +1,7 @@ #pragma once -// SQL Server bulk copy (BCP) support for the low-level Connection.bcp_* methods -// (connection.cpp). Include after pyodbc.h. +// SQL Server bulk copy (BCP) support shared by the fast executemany path (bcp_executemany.cpp) +// and the low-level Connection.bcp_* methods (connection.cpp). Include after pyodbc.h. // // The BCP entry points are exported by the Microsoft ODBC driver itself rather than the driver // manager, so they are resolved from the loaded driver at run time and no SQL Server SDK @@ -79,6 +79,25 @@ typedef int DBINT; #endif struct Connection; +struct Cursor; + +/** Imports the datetime C API for the fast executemany path; called once at module load. */ +void BcpExecuteMany_init(); + +/** + * Carries out Cursor.executemany with the BCP API, for a cursor with use_bcp_fast set. + * + * Everything that could make BCP store something other than the plain fast_executemany path + * would is checked before the bulk copy starts, in which case false is returned so the caller + * runs the plain path. That includes the setinputsizes entries in effect, under which the + * plain path sends each value as the entry's type for the server to convert. Once rows are + * being sent, any failure rolls back everything this call sent (its own transaction in + * autocommit mode, a savepoint otherwise) and raises. + * + * @return false to fall back to the plain path (no Python exception set), true when handled: + * either done, with cur->rowcount set, or failed with a Python exception set. + */ +bool ExecuteMulti_BCP(Cursor* cur, PyObject* pSql, PyObject* param_seq); /** The driver's BCP entry points. */ struct BcpProcs @@ -103,12 +122,17 @@ struct BcpProcs * `rowReady` is set by a successful bcp_setrow and cleared by bcp_sendrow, so a row is never * sent half converted or twice by mistake. `tableName` and `hints` are the strings given to * bcp_init and bcp_control, kept until the session ends since the driver may read them later. + * `driverVersion` is the driver's major version times 100 plus its minor version (1704 for + * 17.4), or 0 if unknown. `fastLoad` marks a session the fast_executemany path opened, which + * the low-level API leaves alone. */ struct BcpState { bool loaded; + int driverVersion; BcpProcs procs; bool sessionOpen; + bool fastLoad; bool ownsTransaction; bool rowReady; PyObject* context; @@ -147,6 +171,49 @@ struct BcpCtx BcpCol* cols; }; +/** + * A parsed `INSERT [INTO] [[catalog.]schema.]table [(columns)] VALUES (?, ...)` statement. + * + * Names are unquoted UTF-8; catalog and schema are empty when omitted. + */ +struct BcpInsert +{ + char catalog[520]; + char schema[520]; + char table[520]; + char** names; + int nnames; + int nmarkers; +}; + +/** + * One column of the destination table, from its catalog metadata. codePage is that of the + * column's collation (65001 for a UTF-8 one), or 0 for a column without a collation. + */ +struct BcpTargetColumn +{ + SQLWCHAR name[129]; + int systemType; + int maxLength; + int scale; + int codePage; + bool identity; + bool computed; + bool hasDefault; +}; + +/** + * The columns of a destination user table, in table order, with whether it has an enabled + * INSERT trigger and whether its database compares identifiers ignoring case. + */ +struct BcpTarget +{ + int ncols; + BcpTargetColumn* cols; + bool hasInsertTrigger; + bool caseInsensitive; +}; + /** * Resolves the driver's BCP entry points once per connection. * @@ -155,12 +222,63 @@ struct BcpCtx */ bool BcpEnsureLoaded(Connection* cnxn); +/** Returns true if the connection was opened with SQL_COPT_SS_BCP enabled. */ +bool BcpIsEnabled(HDBC hdbc); + /** Switches the connection's autocommit mode, leaving the diagnostics on the hdbc on failure. */ bool BcpSetAutocommit(HDBC hdbc, bool on); /** Commits or rolls back the connection's transaction, leaving the diagnostics on failure. */ bool BcpEndTransaction(HDBC hdbc, bool commit); +/** + * Parses an INSERT statement the fast path can carry out with BCP. + * + * Only a single parameterized VALUES row of bare ? markers is accepted, optionally followed + * by a semicolon: anything else (TOP, hints, OUTPUT, SELECT/EXEC sources, DEFAULT VALUES, + * literals or expressions, several rows, further statements) means BCP would not do what the + * statement says. + * + * @return 1 if parsed, 0 if the statement is not one BCP can carry out, or -1 on allocation + * failure (Python exception set). On success free with BcpFreeInsert. + */ +int BcpParseInsert(const char* sql, BcpInsert* out); + +/** Frees the column names of a parsed INSERT. */ +void BcpFreeInsert(BcpInsert* ins); + +/** + * Converts a UTF-8 string to a PyMem-allocated, NUL-terminated UTF-16LE SQLWCHAR string. + * + * @return NULL with a Python exception set on failure. + */ +SQLWCHAR* BcpUtf8ToSqlWChar(const char* s); + +/** + * Builds the bracket-quoted name of the INSERT's table, e.g. "[db].[dbo].[t]". + * + * @return A PyMem-allocated, NUL-terminated SQLWCHAR string, or NULL with a Python exception set. + */ +SQLWCHAR* BcpQuotedTableName(const BcpInsert& ins); + +/** + * Loads the destination columns of a parsed INSERT from the catalog views. + * + * Temporary tables are looked up in tempdb and three-part names in their own database. The + * target also records whether the table has an enabled INSERT trigger and whether its database + * compares identifiers ignoring case. With + * `setSavepoint`, the same round trip also sets the savepoint `pyodbc_bcp` in the caller's + * transaction, for the fast path to roll back to if a load fails in manual-commit mode; an + * unused savepoint is harmless, so this costs nothing when the load falls back. + * + * @return 1 if the target is a user table whose columns are visible, 0 otherwise, or -1 on + * allocation failure (Python exception set). On success free with BcpFreeTarget. + */ +int BcpLoadTarget(Connection* cnxn, const BcpInsert& ins, bool setSavepoint, BcpTarget* out); + +/** Frees the columns of a loaded target. */ +void BcpFreeTarget(BcpTarget* target); + /** * Sizes and allocates a column's buffer. * @@ -197,6 +315,9 @@ bool BcpPutBytes(Connection* cnxn, BcpCol* c, const void* data, Py_ssize_t n); */ bool BcpPutWidened(Connection* cnxn, BcpCol* c, const unsigned char* text, Py_ssize_t n); +/** Writes a str as UTF-16LE into a SQLNCHAR column. */ +bool BcpPutWideStr(Connection* cnxn, BcpCol* c, PyObject* s); + /** * A low-level API value converted for its column, ready to be written without running any * Python code. `holder` keeps variable-length data alive: the immutable str or bytes it points diff --git a/src/connection.cpp b/src/connection.cpp index 818e55cd..1ff2637e 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -1735,6 +1735,10 @@ static Connection* ConnectionWithBcp(PyObject* self) PyErr_SetString(PyExc_NotImplementedError, "BCP needs the Microsoft ODBC Driver 13 or later for SQL Server."); return 0; } + if (cnxn->bcp->fastLoad) { + PyErr_SetString(ProgrammingError, "A fast_executemany BCP load is running on this connection."); + return 0; + } return cnxn; } diff --git a/src/cursor.cpp b/src/cursor.cpp index 7959f72f..fce0b368 100644 --- a/src/cursor.cpp +++ b/src/cursor.cpp @@ -22,6 +22,7 @@ #include "params.h" #include "errors.h" #include "getdata.h" +#include "bcp_support.h" #include "dbspecific.h" #include @@ -1202,6 +1203,14 @@ static PyObject* Cursor_executemany(PyObject* self, PyObject* args) if (cursor->fastexecmany) { free_results(cursor, FREE_STATEMENT | KEEP_PREPARED); + // The BCP fast path loads the rows with the SQL Server bulk copy API when it can + // store exactly what the path below would, and otherwise declines so that path runs. + if (cursor->use_bcp_fast && ExecuteMulti_BCP(cursor, pSql, param_seq)) + { + if (PyErr_Occurred()) + return 0; + Py_RETURN_NONE; + } if (!ExecuteMulti(cursor, pSql, param_seq)) return 0; } @@ -2639,6 +2648,17 @@ static PyMemberDef Cursor_members[] = {"fast_executemany",T_BOOL, offsetof(Cursor, fastexecmany), 0, fastexecmany_doc }, {"messages", T_OBJECT_EX, offsetof(Cursor, messages), READONLY, messages_doc }, {"rows_as_dicts", T_BOOL, offsetof(Cursor, rows_as_dicts), 0, rowsasdicts_doc }, + {"use_bcp_fast", T_BOOL, offsetof(Cursor, use_bcp_fast), 0, + "With fast_executemany, load SQL Server INSERTs with the bulk copy (BCP) API whenever that stores the\n" + "same data as the plain path; the connection must be opened with\n" + "attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}, or the plain path runs. Connection\n" + "pooling matches on the connection string alone, so give BCP connections their own (e.g. a distinct\n" + "APP=). A failed load is rolled back in full and raised, and after a load rowcount is the number of\n" + "rows copied." }, + {"bcp_batch_rows", T_LONG, offsetof(Cursor, bcp_batch_rows), 0, + "Rows per BCP batch; 0 sends all rows as one batch. In autocommit mode each completed batch is\n" + "committed, and a failure discards only the batch it occurred in." }, + {"bcp_tablock", T_BOOL, offsetof(Cursor, bcp_tablock), 0, "Pass the TABLOCK hint when using BCP (enables minimal logging)" }, { 0 } }; @@ -2944,6 +2964,9 @@ Cursor_New(Connection* cnxn) cur->fastexecmany = 0; cur->rows_as_dicts = 0; cur->messages = Py_None; + cur->use_bcp_fast = false; + cur->bcp_batch_rows = 0; + cur->bcp_tablock = false; Py_INCREF(cnxn); Py_INCREF(cur->description); diff --git a/src/cursor.h b/src/cursor.h index c87460c3..caf32d0a 100644 --- a/src/cursor.h +++ b/src/cursor.h @@ -113,6 +113,16 @@ struct Cursor // Set to SQL_NULL_HANDLE when the cursor is closed. HSTMT hstmt; + // If true, fast executemany loads INSERTs with the SQL Server bulk copy API when it can. + bool use_bcp_fast = false; + + // Rows per BCP batch; 0 sends all rows as one batch. + long bcp_batch_rows = 0; + + // If true, the BCP fast path passes the TABLOCK hint, which enables a bulk-update + // lock and (with a SIMPLE/BULK_LOGGED recovery model + heap) minimal logging. + bool bcp_tablock = false; + // // SQL Parameters // diff --git a/src/pyodbc.pyi b/src/pyodbc.pyi index 37b9ef65..3c5c1393 100644 --- a/src/pyodbc.pyi +++ b/src/pyodbc.pyi @@ -692,6 +692,41 @@ class Cursor: def fast_executemany(self, value: bool) -> None: ... + @property + def use_bcp_fast(self) -> bool: + """With fast_executemany, load SQL Server INSERTs with the bulk copy (BCP) API whenever + that stores the same data as the plain path; otherwise the plain path runs. The + connection must be opened with attrs_before={pyodbc.SQL_COPT_SS_BCP: + pyodbc.SQL_BCP_ON}, or the plain path runs; connection pooling matches on the + connection string alone, so give BCP connections their own (e.g. a distinct APP=). A + failed load is rolled back in full and raised, and after a load rowcount is the number + of rows copied.""" + ... + + @use_bcp_fast.setter + def use_bcp_fast(self, value: bool) -> None: + ... + + @property + def bcp_batch_rows(self) -> int: + """Rows per BCP batch; 0 sends all rows as one batch. In autocommit mode each + completed batch is committed, and a failure discards only the batch it occurred in.""" + ... + + @bcp_batch_rows.setter + def bcp_batch_rows(self, value: int) -> None: + ... + + @property + def bcp_tablock(self) -> bool: + """Pass the TABLOCK hint when using BCP, which takes a bulk-update table lock and allows + minimal logging.""" + ... + + @bcp_tablock.setter + def bcp_tablock(self, value: bool) -> None: + ... + @property def rows_as_dicts(self) -> bool: """If True, rows are returned as dicts instead of Row objects.""" diff --git a/src/pyodbcmodule.cpp b/src/pyodbcmodule.cpp index df91ce7b..dbc641d6 100644 --- a/src/pyodbcmodule.cpp +++ b/src/pyodbcmodule.cpp @@ -313,6 +313,7 @@ static bool import_types() GetData_init(); if (!Params_init()) return false; + BcpExecuteMany_init(); if (!InitializeDecimal()) return false; diff --git a/tests/sqlserver_test.py b/tests/sqlserver_test.py index 3fe0f308..8cd5de67 100755 --- a/tests/sqlserver_test.py +++ b/tests/sqlserver_test.py @@ -9,8 +9,8 @@ import re import uuid from collections.abc import Callable, Iterator -from decimal import Decimal -from datetime import date, time, datetime +from decimal import Decimal, localcontext +from datetime import date, time, datetime, timedelta, timezone from functools import lru_cache import pyodbc @@ -1702,6 +1702,1280 @@ def test_emoticons_as_literal(cursor: pyodbc.Cursor): _BCP_SKIP = 'BCP requires the Microsoft ODBC Driver 13 or later for SQL Server' +_BCP_TZ = timezone(timedelta(hours=5, minutes=30)) + + +def _executemany(cur: pyodbc.Cursor, sql: str, rows: list, bcp: bool = True) -> int: + """ + Runs executemany with fast_executemany, with or without the BCP fast path, and returns + cursor.rowcount: the number of rows a BCP load copied, or -1 for the plain path, which is + also what a BCP call that declined and fell back to it reports. + """ + cur.fast_executemany = True + cur.use_bcp_fast = bcp + cur.executemany(sql, rows) + return cur.rowcount + + +def _fetch(cur: pyodbc.Cursor, table: str, column_type: str) -> list: + """The v column of a test table by id; datetimeoffset as text, which pyodbc can't fetch.""" + expr = "convert(nvarchar(40), v, 121)" if column_type.startswith("datetimeoffset") else "v" + return [row[0] for row in cur.execute(f"select {expr} from {table} order by id")] + + +def _load_both(cur: pyodbc.Cursor, column_type: str, values: list, + expect_bcp: bool = True, sizes: list | None = None) -> tuple: + """ + Loads (id, value) rows into t1 with the BCP fast path and into t2 with the plain path, + both under the setinputsizes entries `sizes` if given, checks whether BCP carried out the + load, and returns the values each table stored. + """ + for table in ("t1", "t2"): + cur.execute(f"create table {table}(id int, v {column_type})") + rows = list(enumerate(values)) + cur.setinputsizes(sizes) + try: + copied = _executemany(cur, "insert into t1 values (?, ?)", rows) + _executemany(cur, "insert into t2 values (?, ?)", rows, bcp=False) + finally: + cur.setinputsizes(None) + assert copied == (len(rows) if expect_bcp else -1) + return _fetch(cur, "t1", column_type), _fetch(cur, "t2", column_type) + + +_BCP_PARITY_CASES = [ + ("int", [0, -5, 2**31 - 1, True, False]), + ("bigint", [2**40, -(2**63)]), + ("smallint", [4.7, -2.5]), + ("tinyint", [255]), + ("int", [Decimal("5"), Decimal("-0"), 7]), + ("bit", [True, False, 0, 1]), + ("float", [0.1, 1e300, -2.5, 3, 2**60 + 1]), + ("real", [0.1, 16777217]), + ("decimal(10,2)", [Decimal("1.50"), Decimal("-0.01"), Decimal("1E+2"), 7]), + ("decimal(10,2)", [1.235, 2.675, 0.1]), + ("numeric(38,0)", [Decimal(10**37), 5]), + ("numeric(38,10)", [Decimal("1" * 28 + ".5"), Decimal("-" + "1" * 27 + ".25"), + Decimal("1" * 20 + "." + "1" * 10)]), + ("money", [Decimal("1.2345"), 3]), + ("smallmoney", [Decimal("-1.5")]), + ("varchar(50)", ["Zürich", "", "a\x00b"]), + ("varchar(50) collate SQL_Latin1_General_CP1_CI_AS", ["façade ½ £", "東京"]), + ("nvarchar(50)", ["東京 \U0001D518", 42, ""]), + ("nvarchar(50)", [5, -7]), + ("nvarchar(50)", [0.1, 1e20, -0.0]), + ("nvarchar(50)", [True, False]), + ("varchar(3)", [42, -7]), + ("varchar(2)", ["ab", "é"]), + ("char(5)", ["ab", ""]), + ("nchar(3)", ["é", ""]), + ("varbinary(20)", [b"\x00\xff", b"", bytearray(b"ab")]), + ("binary(4)", [b"\x01", b""]), + ("varchar(max)", ["", "x" * 9000]), + ("varchar(max)", [42, -1]), + ("nvarchar(max)", [0.5]), + ("nvarchar(max)", [True]), + ("nvarchar(max)", ["é" * 5000, ""]), + ("varbinary(max)", [b"", b"\x07" * 9000]), + ("xml", ["é", ""]), + ("date", [date(2024, 2, 29), date(1, 1, 1)]), + ("date", [datetime(2024, 2, 29), datetime(2024, 3, 1, 0, 0, 0, 999999), + datetime(2024, 3, 2, tzinfo=_BCP_TZ), date(2024, 3, 3)]), + ("time(0)", [time(3, 4, 5), datetime(2024, 1, 2, 3, 4, 5, 999999)]), + ("time(0)", ["13:14:15", time(3, 4, 5)]), + ("time(3)", [time(3, 4, 5, 500000), datetime(2024, 1, 2, 3, 4, 5, 123456)]), + ("time(3)", ["13:14:15.123", "13:14:15.5"]), + ("time(7)", [time(23, 59, 59, 999999), time(1, 2, 3, tzinfo=_BCP_TZ)]), + ("time(7)", ["13:14:15", "23:59:59.999999", "00:00:00.1234567", time(1, 2, 3)]), + ("datetime2(0)", [datetime(2024, 1, 2, 3, 4, 5, 999999), date(2024, 1, 2)]), + ("datetime2(3)", [datetime(2024, 12, 31, 23, 59, 59, 999999)]), + ("datetime2(7)", [datetime(2024, 1, 2, 3, 4, 5, 123456, tzinfo=_BCP_TZ)]), + ("datetime", [datetime(2024, 1, 2, 3, 4, 5, ms * 1000) for ms in (1, 2, 5, 499, 998)]), + ("datetime", [datetime(2024, 1, 2, 3, 4, 5, 999000), + datetime(2024, 12, 31, 23, 59, 59, 999999), date(2024, 1, 2)]), + ("datetime", [datetime(9999, 12, 31, 23, 59, 59, 999999)]), + ("smalldatetime", [datetime(2024, 1, 2, 3, 4, 29, 999999), datetime(2024, 1, 2, 3, 4, 30), + datetime(2024, 12, 31, 23, 59, 59), date(2024, 1, 2)]), + ("uniqueidentifier", [uuid.UUID("6F9619FF-8B86-D011-B42D-00C04FC964FF"), + uuid.UUID(int=7)]), + ("uniqueidentifier", ["6F9619FF-8B86-D011-B42D-00C04FC964FF", + "6f9619ff-8b86-d011-b42d-00c04fc964fe", uuid.UUID(int=7)]), +] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,values", _BCP_PARITY_CASES, + ids=[f"{i}-{t}" for i, (t, _) in enumerate(_BCP_PARITY_CASES)]) +def test_bcp_matches_plain_path(bcp_cursor: pyodbc.Cursor, column_type: str, values: list): + """ + For every pairing of Python value and column type the BCP fast path carries out itself, it + stores exactly what the plain fast_executemany path stores. This pins the driver's + conversions and the rounding the path reproduces for dates and times. + """ + bcp, plain = _load_both(bcp_cursor, column_type, values + [None]) + assert bcp == plain + + +_BCP_BOTH_FAIL_CASES = [ + ("decimal(10,2)", Decimal("1.234"), True), + ("numeric(38,0)", Decimal("1" * 27 + ".25"), True), + ("int", Decimal("2.5"), True), + ("tinyint", 300, True), + ("bit", 5, True), + ("int", 2.0 ** 40, True), + ("time(3)", time(3, 4, 5, 123456), True), + ("time(3)", "13:14:15.123456", False), + ("time(7)", "24:00:00", False), + ("time(7)", "1:2:3", False), + ("date", datetime(2024, 1, 2, 3, 4, 5), False), + ("varchar(3)", "toolong", False), + ("varchar(2)", "ab ", False), + ("nvarchar(2)", "a ", False), + ("char(2)", "ab ", False), + ("varchar(3)", "\U0001D518\U0001D518", False), + ("varbinary(2)", b"\x01\x02\x00", False), + ("uniqueidentifier", "{6F9619FF-8B86-D011-B42D-00C04FC964FF}", False), + ("uniqueidentifier", "6F9619FF8B86D011B42D00C04FC964FF", False), + ("uniqueidentifier", " 6F9619FF-8B86-D011-B42D-00C04FC964FF", False), + ("uniqueidentifier", "6F9619FF-8B86-D011-B42D-00C04FC964FG", False), + ("uniqueidentifier", 5, False), +] + + +def _raised_by_bcp(exc: pyodbc.Error) -> bool: + """ + Whether an error came from a BCP load rather than the plain path: the driver names the bcp_ + function that failed, and the path's own conversion errors carry their SQLSTATE last. + """ + return "(bcp_" in str(exc) or exc.args[1:] in (("22003",), ("22018",)) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,value,runs", _BCP_BOTH_FAIL_CASES, + ids=[t for t, _, _ in _BCP_BOTH_FAIL_CASES]) +def test_bcp_fails_where_plain_path_fails(bcp_cursor: pyodbc.Cursor, column_type: str, value, + runs: bool): + """ + A value the plain path rejects raises with BCP enabled too: either BCP carries out the load + and stores nothing, or it declines and the plain path stores what it always does. `runs` + says which, as the error shows (see _raised_by_bcp). + """ + cur = bcp_cursor + stored = {} + for bcp in (False, True): + cur.execute("drop table if exists t1") + cur.execute(f"create table t1(id int, v {column_type})") + with pytest.raises(pyodbc.Error) as raised: + _executemany(cur, "insert into t1 values (?, ?)", [(1, None), (2, value)], bcp=bcp) + assert _raised_by_bcp(raised.value) == (bcp and runs) + stored[bcp] = [tuple(r) for r in cur.execute("select id, v from t1")] + assert stored[True] in ([], stored[False]) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_loads_text_ntext_and_image(bcp_cursor: pyodbc.Cursor): + """ + BCP loads the deprecated text, ntext and image types. The plain path sizes their buffers + from the 2 GB column size, so it fails on a large load, and on 32-bit Python on any load, + which is why these aren't compared with it. + """ + cur = bcp_cursor + cur.execute("create table t1(id int, t text, n ntext, i image)") + rows = [(0, "abc", "é", b"\x01\x02"), (1, "", "", b""), (2, None, None, None)] + assert _executemany(cur, "insert into t1 values (?, ?, ?, ?)", rows) == len(rows) + assert [tuple(r) for r in cur.execute("select id, t, n, i from t1 order by id")] == rows + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_datetimeoffset(bcp_cursor: pyodbc.Cursor): + """ + datetimeoffset stores what a user would expect, not what the plain path stores (the driver + gives it the client machine's local offset): an aware datetime keeps its own offset, a + naive one or a date is stored at +00:00, and the fraction is truncated to the column's + scale. An offset SQL Server cannot hold, or a utcoffset() that returns no timedelta, + raises and stores nothing. + """ + cur = bcp_cursor + cur.execute("create table t1(id int, v datetimeoffset(3))") + newfoundland = timezone(-timedelta(hours=3, minutes=30)) + rows = [ + (0, datetime(2024, 4, 2, 3, 4, 5, 123456, tzinfo=_BCP_TZ)), + (1, datetime(2024, 1, 2, 3, 4, 5, tzinfo=newfoundland)), + (2, datetime(2024, 4, 2, 3, 4, 5, 999999)), + (3, date(2024, 1, 2)), + (4, None), + ] + assert _executemany(cur, "insert into t1 values (?, ?)", rows) == len(rows) + assert _fetch(cur, "t1", "datetimeoffset") == [ + "2024-04-02 03:04:05.123 +05:30", + "2024-01-02 03:04:05.000 -03:30", + "2024-04-02 03:04:05.999 +00:00", + "2024-01-02 00:00:00.000 +00:00", + None, + ] + + for offset in (timedelta(hours=15), timedelta(seconds=90)): + with pytest.raises(ValueError): + _executemany(cur, "insert into t1 values (?, ?)", + [(5, None), (6, datetime(2024, 1, 2, tzinfo=timezone(offset)))]) + + class OddOffset(datetime): + def utcoffset(self) -> int: + return 5 + + with pytest.raises(TypeError): + _executemany(cur, "insert into t1 values (?, ?)", + [(7, OddOffset(2024, 1, 2, tzinfo=_BCP_TZ))]) + assert cur.execute("select count(*) from t1").fetchval() == len(rows) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("with_entry", [False, True]) +@pytest.mark.parametrize("prec", [10, 28, 38]) +@pytest.mark.parametrize("scale,value", [ + (10, Decimal("1234567890123456789012345678.1234567891")), + (0, Decimal("9" * 38)), +]) +def test_bcp_decimals_ignore_the_context_precision(bcp_cursor: pyodbc.Cursor, scale: int, + value: Decimal, prec: int, + with_entry: bool): + """ + Like the plain path, BCP keeps every digit of a Decimal whatever the thread's decimal + context precision, with or without a numeric entry: 38 digits survive a 28-digit context, + and 38 nines do not round up past their numeric(38,0) column. + """ + column_type = f"numeric(38,{scale})" + sizes = [None, (pyodbc.SQL_NUMERIC, 38, scale)] if with_entry else None + with localcontext() as context: + context.prec = prec + bcp, plain = _load_both(bcp_cursor, column_type, [value], sizes=sizes) + assert bcp == plain == [value] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_rejects_non_finite_decimal(bcp_cursor: pyodbc.Cursor): + """A NaN or infinite Decimal raises an error through BCP and stores nothing.""" + cur = bcp_cursor + cur.execute("create table t1(id int, v decimal(10, 2))") + for value in (Decimal("NaN"), Decimal("-Infinity")): + with pytest.raises(pyodbc.Error): + rows = [(1, Decimal("1.5")), (2, value)] + _executemany(cur, "insert into t1 values (?, ?)", rows) + assert cur.execute("select count(*) from t1").fetchval() == 0 + + +_BCP_FALLBACK_CASES = [ + ("datetime2(3)", ["2024-01-02 03:04:05"]), + ("time(7)", [" 13:14:15", "13:14:15."]), + ("money", [1.5]), + ("decimal(38,0)", [2 ** 70]), + ("uniqueidentifier", [uuid.UUID(int=7).bytes_le]), + ("nvarchar(36)", [uuid.UUID(int=7)]), + ("varchar(36)", [uuid.UUID(int=7)]), + ("nvarchar(20)", ["a", 1.5]), + ("varchar(1)", [42]), + ("varchar(3)", [12345.678]), + ("varchar(5)", ["ab", 123456]), + ("varchar(12) collate Japanese_CI_AS", ["東京東京東京東"]), + ("char(4) collate Latin1_General_100_CI_AS_SC_UTF8", ["ééé"]), +] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,values", _BCP_FALLBACK_CASES, + ids=[t for t, _ in _BCP_FALLBACK_CASES]) +def test_bcp_declines_values_it_cannot_reproduce(bcp_cursor: pyodbc.Cursor, column_type: str, + values: list): + """Pairings BCP cannot store as the plain path does are left to that path.""" + bcp, plain = _load_both(bcp_cursor, column_type, values, expect_bcp=False) + assert bcp == plain + + +def _one_with_places(places: int) -> Decimal: + """ + 1 written with `places` zeros after the point, built by quantize since Python 3.15 refuses + to convert a string of more than 4300 digits. + """ + with localcontext() as context: + context.prec = places + 1 + return Decimal(1).quantize(Decimal(1).scaleb(-places)) + + +class _NotAUUID: + """An object with a UUID's 16 bytes_le that is not a UUID, which the plain path rejects.""" + + bytes_le = bytes(16) + + +def _swapping_uuid(row: list, index: int, swapped: object) -> uuid.UUID: + """A UUID whose bytes_le, read while BCP sends the row, sets row[index] to `swapped`.""" + + class SwappingUUID(uuid.UUID): + @property + def bytes_le(self) -> bytes: + row[index] = swapped + return super().bytes_le + + return SwappingUUID(int=7) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_rejects_a_null_swapped_into_a_column_with_a_default(bcp_cursor: pyodbc.Cursor): + """ + A None swapped in after the scan raises where the load runs without KEEPNULLS, which a + filler column's default requires, since the server would store the column's default. + """ + row = [1, None, 3] + row[1] = _swapping_uuid(row, 2, None) + bcp_cursor.execute("create table t1(id int, g uniqueidentifier, v int default 5," + " f int default 9)") + with pytest.raises(TypeError): + _executemany(bcp_cursor, "insert into t1 (id, g, v) values (?, ?, ?)", [row]) + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_leaves_decimal_subclasses_to_the_plain_path(bcp_cursor: pyodbc.Cursor): + """ + A Decimal subclass falls back to the plain path, which reads its as_tuple, so a __format__ + that disagrees changes nothing. + """ + + class OddDecimal(Decimal): + def __format__(self, spec: str) -> str: + return "999" + + bcp_cursor.execute("create table t1(id int, d decimal(10, 2))") + rows = [(1, OddDecimal("1.5"))] + assert _executemany(bcp_cursor, "insert into t1 values (?, ?)", rows) == -1 + assert bcp_cursor.execute("select d from t1").fetchval() == Decimal("1.5") + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("with_entry", [False, True]) +@pytest.mark.parametrize("value,error", [ + (Decimal(f"1E+{decimal.MAX_EMAX}"), "Numeric overflow"), + (Decimal("1E+38"), "Numeric overflow"), + (Decimal("1E-50"), "loses precision"), + (Decimal(f"1E{decimal.MIN_EMIN}"), "32767 digits"), + (_one_with_places(40000), "32767 digits"), + (Decimal("0E-32768"), "32767 digits"), + (Decimal("NaN"), "NaN and Infinity"), + (Decimal("-Infinity"), "NaN and Infinity"), + (Decimal("sNaN"), "signaling NaN"), +]) +def test_bcp_rejects_decimals_no_numeric_holds(bcp_cursor: pyodbc.Cursor, value: Decimal, + error: str, with_entry: bool): + """ + A Decimal no SQL_NUMERIC_STRUCT holds raises the plain path's error, checked before BCP + formats it, which would build text as long as its exponent, and neither path stores it. + """ + bcp_cursor.execute("create table t1(id int, d decimal(38, 10))") + bcp_cursor.setinputsizes([None, (pyodbc.SQL_NUMERIC, 38, 10)] if with_entry else None) + rows = [(1, Decimal("1.5")), (2, value)] + try: + for bcp in (True, False): + with pytest.raises(pyodbc.ProgrammingError, match=error): + _executemany(bcp_cursor, "insert into t1 values (?, ?)", rows, bcp=bcp) + finally: + bcp_cursor.setinputsizes(None) + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_stores_zeros_whatever_their_exponent(bcp_cursor: pyodbc.Cursor): + """Zeros the plain path stores, with any exponent it takes, store 0 through BCP too.""" + values = [Decimal("0E-32767"), Decimal("0E+40000"), Decimal("-0E-5"), Decimal(0)] + bcp, plain = _load_both(bcp_cursor, "decimal(38, 10)", values) + assert bcp == plain == [Decimal(0)] * 4 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("autocommit", [True, False]) +def test_bcp_rows_whose_reading_closes_the_connection(bcp_cursor: pyodbc.Cursor, + autocommit: bool): + """Rows whose iteration closes the connection raise before BCP uses it, in either mode.""" + bcp_cursor.execute("create table t1(id int)") + victim = bcp_connect(autocommit=autocommit) + + class ClosingRows(list): + def __iter__(self): + victim.close() + return super().__iter__() + + with pytest.raises(pyodbc.ProgrammingError): + _executemany(victim.cursor(), "insert into t1 values (?)", ClosingRows([(1,)])) + assert victim.closed + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_load_refuses_autocommit_and_the_low_level_api(bcp_cursor: pyodbc.Cursor): + """Python code run mid-load can neither change autocommit nor open a low-level session.""" + bcp_cursor.execute("create table t1(id int, g uniqueidentifier)") + victim = bcp_connect() + refused = [] + meddles = (lambda: setattr(victim, "autocommit", False), lambda: victim.bcp_init("t1")) + + class MeddlingUUID(uuid.UUID): + @property + def bytes_le(self) -> bytes: + for meddle in meddles: + try: + meddle() + except pyodbc.ProgrammingError: + refused.append(True) + return super().bytes_le + + rows = [(1, MeddlingUUID(int=1)), (2, MeddlingUUID(int=2))] + assert _executemany(victim.cursor(), "insert into t1 values (?, ?)", rows) == 2 + assert refused == [True] * 4 + assert victim.autocommit + victim.autocommit = False + victim.autocommit = True + victim.bcp_init("t1") + assert victim.bcp_done() == 0 + victim.close() + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 2 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_closing_the_connection_as_a_value_is_released(bcp_cursor: pyodbc.Cursor): + """ + A connection closed by a finalizer, run once a value has been copied, raises before BCP + uses the connection again, and stores nothing. + """ + bcp_cursor.execute("create table t1(id int, g uniqueidentifier)") + victim = bcp_connect() + + class ClosingBytes(bytes): + def __del__(self) -> None: + victim.close() + + class ReleasingUUID(uuid.UUID): + @property + def bytes_le(self) -> bytes: + return ClosingBytes(super().bytes_le) + + rows = [(1, ReleasingUUID(int=1)), (2, uuid.UUID(int=2))] + with pytest.raises(pyodbc.ProgrammingError, match="connection was closed"): + _executemany(victim.cursor(), "insert into t1 values (?, ?)", rows) + assert victim.closed + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_rows_whose_reading_changes_autocommit_fall_back(bcp_cursor: pyodbc.Cursor): + """ + Rows whose iteration turns autocommit off leave the call to the plain path, which then runs + in the transaction they started, since BCP chose its savepoint before. + """ + bcp_cursor.execute("create table t1(id int)") + victim = bcp_connect() + + class AutocommitOffRows(list): + def __iter__(self): + victim.autocommit = False + return super().__iter__() + + rows = AutocommitOffRows([(1,), (2,)]) + assert _executemany(victim.cursor(), "insert into t1 values (?)", rows) == -1 + victim.rollback() + victim.close() + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,scanned,swapped,entry", [ + ("date", date(2024, 1, 2), time(1, 2, 3), None), + ("date", date(2024, 1, 2), 5, None), + ("date", date(2024, 1, 2), datetime(2024, 1, 2, 3, 4, 5), None), + ("time(3)", "13:14:15", date(2024, 1, 2), None), + ("time(3)", "13:14:15", "13:14:15.123456", None), + ("nvarchar(3)", "abc", "abcd", None), + ("varbinary(2)", b"ab", b"abc", None), + ("datetime2(3)", datetime(2024, 1, 2), Decimal(20240102), + (pyodbc.SQL_TYPE_TIMESTAMP, 27, 7)), + ("nvarchar(10)", "abc", "abcdefgh", (pyodbc.SQL_WVARCHAR, 5, 0)), + ("varchar(20)", "abc", "thin space", (pyodbc.SQL_WVARCHAR, 20, 0)), + ("int", None, 2.5, (pyodbc.SQL_DOUBLE, 15, 0)), + ("varchar(5)", 12345, 1234567, None), + ("varchar(30)", 1.5, 7, None), + ("xml", "", 5, None), + ("uniqueidentifier", uuid.UUID(int=1), _NotAUUID(), None), +]) +def test_bcp_rejects_a_value_changed_while_sending(bcp_cursor: pyodbc.Cursor, column_type: str, + scanned, swapped, entry): + """ + A value swapped into a row after the scan, by Python code run while the row is sent, raises + and the call stores nothing, unless it suits the column, and its entry, as the scan would + have required. + """ + row = [1, None, scanned] + row[1] = _swapping_uuid(row, 2, swapped) + bcp_cursor.execute(f"create table t1(id int, g uniqueidentifier, v {column_type})") + bcp_cursor.setinputsizes([None, None, entry] if entry else None) + try: + with pytest.raises(TypeError): + _executemany(bcp_cursor, "insert into t1 values (?, ?, ?)", [row]) + finally: + bcp_cursor.setinputsizes(None) + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + +_BCP_DECLINED_STATEMENTS = [ + ("insert into t1 values (?, ?); delete from t2", [(1, 2)]), + ("insert into t1 values (?, ? * 2)", [(1, 2)]), + ("insert into t1 values (?, 5)", [(1,)]), + ("insert into t1 (id, v) values (?, ?), (?, ?)", [(1, 2, 3, 4)]), + ("insert top (1) into t1 values (?, ?)", [(1, 2)]), + ("insert into t1 with (tablock) values (?, ?)", [(1, 2)]), + ("insert into t1 select ?, ?", [(1, 2)]), + ("insert into t1 values (?, ?)", [(1, 2, 3)]), + ('insert into "t1" values (?, ?)', [(1, 2)]), + ("insert into t1 (id, key) values (?, ?)", [(1, 2)]), +] + + +def _statement_outcome(cur: pyodbc.Cursor, sql: str, rows: list, bcp: bool) -> tuple: + """ + Runs sql against fresh t1(id, v) and t2(id) tables and returns the rowcount (or the error + class raised) with what both tables then hold. + """ + for table in ("t1", "t2"): + cur.execute(f"drop table if exists {table}") + cur.execute("create table t1(id int, v int)") + cur.execute("create table t2(id int)") + cur.execute("insert into t2 values (0)") + try: + outcome = _executemany(cur, sql, rows, bcp=bcp) + except pyodbc.Error as ex: + outcome = type(ex) + t1 = [tuple(r) for r in cur.execute("select id, v from t1 order by id")] + t2 = [r[0] for r in cur.execute("select id from t2")] + return outcome, t1, t2 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("sql,rows", _BCP_DECLINED_STATEMENTS, + ids=[s for s, _ in _BCP_DECLINED_STATEMENTS]) +def test_bcp_declines_statements_it_cannot_carry_out(bcp_cursor: pyodbc.Cursor, sql: str, + rows: list): + """ + Only `INSERT INTO t [(cols)] VALUES (?, ...)` with one value per marker goes through BCP: + anything else in the statement (more statements, expressions, literals, several rows, TOP, + table hints, other sources, extra values, quoted or reserved identifiers) would not do as + written under a bulk copy, so BCP declines and the outcome is exactly the plain path's. + """ + with_bcp = _statement_outcome(bcp_cursor, sql, rows, bcp=True) + assert with_bcp == _statement_outcome(bcp_cursor, sql, rows, bcp=False) + + +def _bcp_row(i: int) -> tuple: + """One row of the type-coverage test: every Python type the BCP fast path sends.""" + month, day = (i % 12) + 1, (i % 28) + 1 + hms = (i % 24, i % 60, (i * 7) % 60) + return ( + i, + 5_000_000_000 + i, + bool(i % 2), + i + 0.5, + "x" * (i % 400), + "é東\U0001D518" * (i % 50), + Decimal(f"{i}.{i % 10000:04d}"), + Decimal(10 ** 20 + i), + time(i % 24, i % 60, (i * 7) % 60, (i * 101) % 1000000), + date(2020, month, day), + datetime(2021, month, day, *hms, (i * 101) % 1000000), + datetime(2022, month, day, *hms, (i * 101) % 1000000), + datetime(2023, month, day, *hms, (i * 1009) % 1000000, tzinfo=_BCP_TZ), + bytes([i % 256]) * (i % 30), + ) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_fast_executemany(bcp_cursor: pyodbc.Cursor): + """ + A load across every supported type, with a row of NULLs, buffers that grow, values beyond + 32 and 64 bits and manual batching, stores the same rows as the plain fast path. + """ + cur = bcp_cursor + columns = """ + id int, c_bigint bigint, c_bit bit, c_float float, c_varchar varchar(1000), + c_nvarchar nvarchar(200), c_decimal decimal(18, 4), c_numeric numeric(38, 0), + c_time time(7), c_date date, c_datetime2 datetime2(7), c_datetime datetime, + c_smalldatetime smalldatetime, c_varbinary varbinary(50) + """ + cur.execute(f"create table t1({columns})") + cur.execute(f"create table t2({columns})") + + n = 500 + rows = [_bcp_row(i) for i in range(n)] + rows[7] = (7,) + (None,) * 13 + sql = "insert into {} values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + cur.bcp_batch_rows = 100 + assert _executemany(cur, sql.format("t1"), rows) == n + _executemany(cur, sql.format("t2"), rows, bcp=False) + + fetch = ("select id, c_bigint, c_bit, c_float, c_varchar, c_nvarchar, c_decimal, " + "c_numeric, c_time, c_date, c_datetime2, c_datetime, c_smalldatetime, " + "c_varbinary from {} order by id") + loaded = [tuple(r) for r in cur.execute(fetch.format("t1"))] + expected = [tuple(r) for r in cur.execute(fetch.format("t2"))] + assert loaded == expected + assert all(v is None for v in loaded[7][1:]) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_fast_executemany_nvarchar(bcp_cursor: pyodbc.Cursor): + """ + str values reach nvarchar columns intact whatever the client's code page: Latin accents, + CJK, a character outside the BMP, an empty string distinct from NULL, values long enough to + grow the column buffers (one encoded by the codec, a longer one widened from Latin-1), a + short value after them, and a first row whose value is None, which must not decide the + column type. + """ + values = [ + None, + "Zürich, Ångström, façade, naïve", + "東京 北京 서울", + "\U0001D518 lies outside the BMP", + "", + None, + "東京\U0001D518" * 500, + "é" * 3000, + "short again", + ] + cur = bcp_cursor + cur.execute("create table t1(id int, s nvarchar(4000), m nvarchar(max))") + rows = [(i, v, v) for i, v in enumerate(values)] + assert _executemany(cur, "insert into t1 values (?, ?, ?)", rows) == len(rows) + + stored = cur.execute("select s, m from t1 order by id").fetchall() + assert [row.s for row in stored] == values + assert [row.m for row in stored] == values + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_fast_executemany_varchar_latin1(bcp_cursor: pyodbc.Cursor): + """ + str values whose characters all fit code page 1252 reach a varchar column in the default + Latin1 collation as that code page's single bytes, not as UTF-8 read as ANSI text. + """ + values = ["Zürich", "façade, crème brûlée", "Ångström ½ £ ©", "plain ascii"] + cur = bcp_cursor + cur.execute("create table t1(id int, s varchar(50) collate SQL_Latin1_General_CP1_CI_AS)") + rows = list(enumerate(values)) + assert _executemany(cur, "insert into t1 values (?, ?)", rows) == len(values) + + stored = cur.execute("select s, cast(s as varbinary(50)) as raw from t1 order by id") + stored = stored.fetchall() + assert [row.s for row in stored] == values + assert [row.raw for row in stored] == [v.encode("cp1252") for v in values] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_fast_executemany_none_first_row(bcp_cursor: pyodbc.Cursor): + """ + A NULL in the first row does not decide a column's type: nullable int, float, bit and + nvarchar columns with a NULL first value load, and so does a column NULL throughout. + """ + rows = [ + (0, None, None, None, None, None), + (1, 5, 1.5, True, "Zürich", None), + (2, None, None, None, None, None), + (3, -7, 2.5, False, "", None), + ] + cur = bcp_cursor + cur.execute("create table t1(id int, n int, f float, b bit, s nvarchar(20), z int)") + assert _executemany(cur, "insert into t1 values (?, ?, ?, ?, ?, ?)", rows) == len(rows) + assert [tuple(r) for r in cur.execute("select * from t1 order by id")] == rows + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_fast_executemany_column_list(bcp_cursor: pyodbc.Cursor): + """ + A column list is mapped to table ordinals, in any order and as a subset (the SQLAlchemy + shape): the unlisted columns are left to the server, which fills in identity values, + defaults and NULLs exactly as for the INSERT. + """ + cur = bcp_cursor + cur.execute(""" + create table t1(id int identity, a int, b varchar(20), c int, d float default 9.5) + """) + + reordered = [(i * 10, i, f"b{i}", i + 0.5) for i in range(50)] + sql = "insert into t1 (c, a, b, d) values (?, ?, ?, ?)" + assert _executemany(cur, sql, reordered) == 50 + row = cur.execute("select a, b, c, d from t1 where a = 7").fetchone() + assert tuple(row) == (7, "b7", 70, 7.5) + + cur.execute("truncate table t1") + subset = [(i, f"name{i}") for i in range(20)] + assert _executemany(cur, "insert into t1 (a, b) values (?, ?)", subset) == 20 + rows = cur.execute("select id, a, b, c, d from t1 order by id").fetchall() + assert [tuple(r) for r in rows] == [(i + 1, i, f"name{i}", None, 9.5) for i in range(20)] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_positional_insert_skips_identity_and_computed(bcp_cursor: pyodbc.Cursor): + """Without a column list the values go to the columns T-SQL fills, skipping identity and + computed ones.""" + cur = bcp_cursor + cur.execute("create table t1(id int identity, a int, c as a * 2, b nvarchar(10))") + assert _executemany(cur, "insert into t1 values (?, ?)", [(5, "x"), (6, "y")]) == 2 + stored = [tuple(r) for r in cur.execute("select id, a, c, b from t1 order by id")] + assert stored == [(1, 5, 10, "x"), (2, 6, 12, "y")] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_table_names(bcp_cursor: pyodbc.Cursor): + """ + Temporary tables, names outside ASCII and three-part names go through BCP, the last using + the named database's columns even where the current database has a table of the same name + with its columns in another order. + """ + cur = bcp_cursor + cur.execute("create table #bcp_temp(a int, b nvarchar(5))") + assert _executemany(cur, "insert into #bcp_temp values (?, ?)", [(1, "é")]) == 1 + assert tuple(cur.execute("select a, b from #bcp_temp").fetchone()) == (1, "é") + + cur.execute("drop table if exists [bcp_ü]") + cur.execute("create table [bcp_ü](a int)") + try: + assert _executemany(cur, "insert into [bcp_ü] values (?)", [(1,), (2,)]) == 2 + assert cur.execute("select count(*) from [bcp_ü]").fetchval() == 2 + finally: + cur.execute("drop table [bcp_ü]") + + cur.execute("drop table if exists tempdb.dbo.bcp_three_part") + cur.execute("create table tempdb.dbo.bcp_three_part(a int, b int)") + cur.execute("create table t1(b int, a int)") + try: + sql = "insert into tempdb.dbo.bcp_three_part (a, b) values (?, ?)" + assert _executemany(cur, sql, [(1, 2)]) == 1 + row = cur.execute("select a, b from tempdb.dbo.bcp_three_part").fetchone() + assert tuple(row) == (1, 2) + finally: + cur.execute("drop table tempdb.dbo.bcp_three_part") + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_keeps_insert_semantics(bcp_cursor: pyodbc.Cursor): + """ + BCP checks CHECK and foreign key constraints and stores an explicit None as NULL rather + than the column default, as the INSERT it replaces does. + """ + cur = bcp_cursor + cur.execute("create table t2(id int primary key)") + cur.execute("insert into t2 values (1), (2), (3)") + cur.execute("create table t1(id int check (id >= 0) references t2(id), d int default 42)") + + assert _executemany(cur, "insert into t1 values (?, ?)", [(1, None), (2, 5)]) == 2 + stored = [tuple(r) for r in cur.execute("select id, d from t1 order by id")] + assert stored == [(1, None), (2, 5)] + + for bad in (-1, 9): + with pytest.raises(pyodbc.IntegrityError): + _executemany(cur, "insert into t1 values (?, ?)", [(3, 1), (bad, 1)]) + assert cur.execute("select count(*) from t1").fetchval() == 2 + untrusted = cur.execute("select count(*) from sys.check_constraints " + "where is_not_trusted = 1 and parent_object_id = object_id('t1')") + untrusted = untrusted.fetchval() + assert untrusted == 0 + cur.execute("drop table t1") + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_trigger_tables_use_plain_path(bcp_cursor: pyodbc.Cursor): + """ + A table with an enabled INSERT trigger is left to the plain path: a trigger that rolls back + a bulk copy run in a transaction leaves the driver unable to use the connection again. The + trigger fires, and after one rolls back a load the connection still works. + """ + cur = bcp_cursor + cur.execute("create table t1(id int)") + cur.execute("create table t2(id int)") + cur.execute("create trigger t1_audit on t1 after insert as " + "insert into t2 select id from inserted; " + "if exists (select 1 from inserted where id < 0) rollback transaction") + + assert _executemany(cur, "insert into t1 values (?)", [(1,), (2,)]) == -1 + assert [r[0] for r in cur.execute("select id from t2 order by id")] == [1, 2] + with pytest.raises(pyodbc.Error): + _executemany(cur, "insert into t1 values (?)", [(3,), (-4,)]) + assert cur.execute("select count(*) from t1 where id < 0").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_failure_rolls_back_the_call(bcp_cursor: pyodbc.Cursor): + """ + A failure part way through a load raises and leaves nothing from the call; with batching + in autocommit mode, the batches completed before it stay committed and only the failing + one goes. + """ + cur = bcp_cursor + cur.execute("create table t1(id int primary key)") + rows = [(1,), (2,), (3,), (3,), (5,)] + with pytest.raises(pyodbc.IntegrityError): + _executemany(cur, "insert into t1 values (?)", rows) + assert cur.execute("select count(*) from t1").fetchval() == 0 + + cur.bcp_batch_rows = 2 + with pytest.raises(pyodbc.IntegrityError): + _executemany(cur, "insert into t1 values (?)", rows) + assert [r[0] for r in cur.execute("select id from t1 order by id")] == [1, 2] + assert cur.connection.autocommit + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_failure_in_manual_commit_mode(bcp_cursor: pyodbc.Cursor): + """ + In manual-commit mode a failed load is undone but the caller's earlier work is kept, and + a load, batched or not, stays in the caller's transaction until it commits or rolls back. + """ + bcp_cursor.execute("create table t1(id int primary key)") + bcp_cursor.execute("create table t2(id int)") + cnxn = bcp_connect(autocommit=False) + try: + cur = cnxn.cursor() + cur.execute("insert into t2 values (1)") + with pytest.raises(pyodbc.IntegrityError): + _executemany(cur, "insert into t1 values (?)", [(1,), (1,)]) + assert cur.execute("select count(*) from t1").fetchval() == 0 + cnxn.commit() + assert bcp_cursor.execute("select count(*) from t2").fetchval() == 1 + + cur.bcp_batch_rows = 2 + assert _executemany(cur, "insert into t1 values (?)", [(1,), (2,), (3,)]) == 3 + cnxn.rollback() + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + finally: + cnxn.close() + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_falls_back_without_bcp_connection(cursor: pyodbc.Cursor): + """A connection opened without SQL_COPT_SS_BCP runs the plain path instead of failing.""" + cursor.execute("create table t1(id int, s nvarchar(10))") + assert _executemany(cursor, "insert into t1 values (?, ?)", [(1, "é"), (2, None)]) == -1 + stored = [tuple(r) for r in cursor.execute("select id, s from t1 order by id")] + assert stored == [(1, "é"), (2, None)] + + +@pytest.mark.skipif(not IS_MSODBCSQL or IS_BCP_DRIVER, + reason='Needs a SQL Server driver other than Microsoft ODBC Driver 13+') +def test_bcp_falls_back_on_older_drivers(bcp_cursor: pyodbc.Cursor): + """ + With SQL Server Native Client or Microsoft ODBC Driver 11, the fast path runs the plain + path and the low-level API raises NotImplementedError. + """ + cur = bcp_cursor + cur.execute("create table t1(id int, s nvarchar(10))") + assert _executemany(cur, "insert into t1 values (?, ?)", [(1, "é"), (2, None)]) == -1 + stored = [tuple(r) for r in cur.execute("select id, s from t1 order by id")] + assert stored == [(1, "é"), (2, None)] + with pytest.raises(NotImplementedError): + cur.connection.bcp_init("t1") + + +def _entry_for(values: list) -> tuple: + """ + The setinputsizes entry a loader that types each parameter from the values it carries + would pass: nvarchar as long as the longest str in UTF-16 units (max past 4,000), bit, + bigint, double, numeric just wide enough for every Decimal, datetime2(7) or date, and + nvarchar(1) for a column of NULLs, whatever its type. None for anything else or a mix. + """ + present = [v for v in values if v is not None] + kinds = {type(v) for v in present} + if not present: + return (pyodbc.SQL_WVARCHAR, 1, 0) + if kinds == {str}: + longest = max(len(v.encode("utf-16-le")) // 2 for v in present) + return (pyodbc.SQL_WVARCHAR, longest if longest <= 4000 else 0, 0) + if kinds == {bool}: + return (pyodbc.SQL_BIT, 1, 0) + if kinds == {int} and all(-(2**63) <= v < 2**63 for v in present): + return (pyodbc.SQL_BIGINT, 19, 0) + if kinds == {float}: + return (pyodbc.SQL_DOUBLE, 15, 0) + if kinds == {Decimal}: + places = max(max(-v.as_tuple().exponent, 0) for v in present) + whole = max(len(str(int(abs(v)))) if int(abs(v)) else 0 for v in present) + return (pyodbc.SQL_NUMERIC, max(whole + places, 1), places) + if kinds == {datetime} and all(v.tzinfo is None for v in present): + return (pyodbc.SQL_TYPE_TIMESTAMP, 27, 7) + if kinds == {date}: + return (pyodbc.SQL_TYPE_DATE, 10, 0) + return None + + +_BCP_MAX_DATETIME = datetime(9999, 12, 31, 23, 59, 59, 999999) + + +def _day_end(*micros: int) -> list: + """Datetimes in the last second of 2024 with the given microseconds.""" + return [datetime(2024, 12, 31, 23, 59, 59, us) for us in micros] + + +_BCP_ENTRY_CASES = [ + ("nvarchar(20)", ["abc", "東京 \U0001D518", ""]), + ("nvarchar(max)", ["é" * 5000, ""]), + ("nvarchar(max)", ["short"]), + ("nchar(3)", ["é", ""]), + ("varchar(20)", ["Zürich", "™ – “q” €", ""]), + ("varchar(20) collate Polish_CI_AS", ["Łódź", "zażółć"]), + ("varchar(20) collate Japanese_CI_AS", ["東京", "abc", "カナ"]), + ("varchar(max)", ["x" * 9000, "a"]), + ("char(5)", ["ab", ""]), + ("text", ["abc", ""]), + ("ntext", ["é", ""]), + ("int", [0, -5, 2**31 - 1, -(2**31)]), + ("bigint", [2**62, -(2**63), 2**63 - 1]), + ("smallint", [-32768, 32767]), + ("tinyint", [0, 255]), + ("decimal(30,2)", [2**62 + 1, -7]), + ("money", [3, -(2**40)]), + ("smallmoney", [214748, -214748]), + ("float", [2**53 + 1, 2**63 - 1, -(2**63), 12345678901234567]), + ("real", [16777217, 2**62 + 1]), + ("bit", [0, 1, 2, -1, 2**62]), + ("bit", [True, False]), + ("float", [0.1, 1e300, -2.5, 5e-324, -0.0]), + ("real", [0.1, 16777217.0, 1e-40, 1e-46, 3.4028234663852886e38, -1.1754942e-38]), + ("decimal(10,2)", [2.675, 1.235, 0.1, 9.995, -0.004, 0.005]), + ("decimal(38,10)", [2 / 3 * 1e10, 123456789.123456789, 1e27, -86484.03774682874, 1e-11]), + ("decimal(38,30)", [0.1, 1 / 3, 5e-31, 1.5e-30, -5e-324]), + ("decimal(38,0)", [9.9e37, 0.5, -0.5, 2.5, 1.5]), + ("numeric(5,5)", [0.12345, -0.000005, 0.999994]), + ("int", [2.5, -2.5, 2.9999999, -0.5, 1e9]), + ("bigint", [-(2.0**63), 2.0**62 + 2048, 9.2e18]), + ("smallint", [-32768.9, 32767.9]), + ("tinyint", [-0.5, 255.9]), + ("bit", [0.0, 0.5, -2.5, 1e-300, -0.0]), + ("decimal(18,4)", [Decimal(x) for x in ("1.23456", "-1.00005", "9.99995", "0.00004", + "-0.00005")]), + ("decimal(10,0)", [Decimal("2.5"), Decimal("-2.5"), Decimal("0.4999")]), + ("numeric(38,10)", [Decimal("1" * 20 + "." + "15" * 6), Decimal("-0." + "9" * 12)]), + ("money", [Decimal("1.23456"), Decimal("-1.00005"), Decimal("922337203685477.58074")]), + ("smallmoney", [Decimal("-1.99999"), Decimal("214748.36474")]), + ("int", [Decimal("2.5"), Decimal("-2.5"), Decimal(7), Decimal("1E+3")]), + ("tinyint", [Decimal("0.5"), Decimal("-0.999"), Decimal("255.9")]), + ("smallint", [Decimal("-32768.9"), Decimal("32767.9")]), + ("bigint", [Decimal("9223372036854775807.9"), Decimal("-9223372036854775808.9")]), + ("float", [Decimal("0.1"), Decimal("4.35"), Decimal("-0"), Decimal(9007199254740993)]), + ("float", [Decimal("1.0000000000000001110223024625156540424")]), + ("bit", [Decimal(x) for x in ("0", "0.5", "-0.00001", "2", "0.000")]), + ("datetime", _day_end(998600, 998300, 1667, 1666) + [_BCP_MAX_DATETIME]), + ("datetime2(0)", [*_day_end(998600, 499999, 500000), _BCP_MAX_DATETIME, + datetime(2024, 1, 2, 12, 0, 29, 999000)]), + ("datetime2(2)", [datetime(9999, 12, 31, 23, 59, 59, 994999), + datetime(9999, 12, 31, 23, 59, 59, 995000)]), + ("datetime2(3)", [*_day_end(999600, 1500, 1499), + _BCP_MAX_DATETIME.replace(microsecond=999600)]), + ("datetime2(7)", [datetime(2024, 1, 2, 3, 4, 5, 123456)]), + ("smalldatetime", [datetime(2024, 1, 2, 3, 4, 29, 999999), datetime(2024, 1, 2, 3, 4, 30), + datetime(2024, 12, 31, 23, 59, 30)]), + ("date", _day_end(999999) + [datetime(2024, 1, 2)]), + ("datetimeoffset(0)", _day_end(500000) + [_BCP_MAX_DATETIME]), + ("datetimeoffset(3)", _day_end(1500, 999600)), + ("time(0)", _day_end(500000, 499999)), + ("time(3)", _day_end(999600, 1500)), + ("date", [date(2024, 2, 29), date(1, 1, 1)]), + ("datetime2(3)", [date(2024, 1, 2)]), + ("datetime", [date(2024, 1, 2)]), + ("smalldatetime", [date(2024, 1, 2)]), + ("datetimeoffset(2)", [date(2024, 1, 2)]), + ("int", []), + ("datetime2(3)", []), + ("decimal(10,2)", []), + ("uniqueidentifier", []), + ("xml", []), +] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,values", _BCP_ENTRY_CASES, + ids=[f"{i}-{t}" for i, (t, _) in enumerate(_BCP_ENTRY_CASES)]) +def test_bcp_matches_plain_path_with_input_sizes(bcp_cursor: pyodbc.Cursor, column_type: str, + values: list): + """ + Under setinputsizes the plain path sends each value as its entry's type and the server + converts it to the column's, rounding where the plain path without entries truncates. BCP + carries out every pairing of entry and column type it supports and stores exactly what the + plain path stores, including values that round past midnight, and the sign of a zero. A + column of NULLs under an nvarchar entry, which says nothing about its values, makes BCP + decline only for a binary column, which the server rejects it for. + """ + values = values + [None] + sizes = [_entry_for(list(range(len(values)))), _entry_for(values)] + bcp, plain = _load_both(bcp_cursor, column_type, values, sizes=sizes) + assert list(map(repr, bcp)) == list(map(repr, plain)) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("values,ascii_only", + [(["ééé", "Zürich €", "abc"], False), (["abc"], True)]) +@pytest.mark.parametrize("sized", [False, True]) +def test_bcp_text_into_a_utf8_collation(bcp_cursor: pyodbc.Cursor, values: list, + ascii_only: bool, sized: bool): + """ + Text for a varchar column with a UTF-8 collation goes by BCP from Driver 17.4, the first to + convert it to UTF-8; older drivers send bytes the server rejects, so BCP takes only ASCII + text there. Either way the column stores what the plain path stores, with or without an + entry. (Without one the plain path passes text through the database's code page, so these + values stay within code page 1252.) + """ + values = values + [None] + sizes = [None, _entry_for(values)] if sized else None + expect_bcp = ascii_only or DRIVER_VERSION[:2] >= (17, 4) + bcp, plain = _load_both(bcp_cursor, "varchar(20) collate Latin1_General_100_CI_AS_SC_UTF8", + values, expect_bcp=expect_bcp, sizes=sizes) + assert bcp == plain + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_matches_plain_path_with_input_sizes_at_random(): + """ + BCP stores what the plain path stores for random numbers and datetimes under their + entries, across the conversions BCP reproduces itself: doubles into decimal and real, + Decimals into decimal, money, int and float, and datetimes into the date and time types. + """ + rng = random.Random(1496) + floats = [rng.uniform(-1e6, 1e6) for _ in range(300)] + floats += [rng.uniform(-1, 1) * 10 ** rng.randint(-12, 12) for _ in range(300)] + decimals = [Decimal(f"{rng.uniform(-1e7, 1e7):.{rng.randint(0, 9)}f}") for _ in range(600)] + stamps = [datetime(2024, 1, 1) + timedelta(seconds=rng.randint(0, 86400 * 366), + microseconds=rng.randint(0, 999999)) + for _ in range(600)] + stamps += _day_end(*range(999000, 1000000, 7)) + cases = [("decimal(18,4)", floats), ("decimal(38,10)", floats), ("real", floats), + ("decimal(18,4)", decimals), ("money", decimals), ("int", decimals), + ("float", decimals), ("datetime", stamps), ("datetime2(0)", stamps), + ("datetime2(3)", stamps), ("smalldatetime", stamps), ("time(3)", stamps), + ("datetimeoffset(2)", stamps)] + cnxn = bcp_connect(autocommit=False) + cur = cnxn.cursor() + cur.execute("set lock_timeout 30000") + try: + for column_type, values in cases: + for table in ("t1", "t2"): + cur.execute(f"drop table if exists {table}") + bcp, plain = _load_both(cur, column_type, values, + sizes=[None, _entry_for(values)]) + cnxn.commit() + assert list(map(repr, bcp)) == list(map(repr, plain)), column_type + finally: + cnxn.rollback() + for table in ("t1", "t2"): + cur.execute(f"drop table if exists {table}") + cnxn.commit() + cnxn.close() + + +_TIMESTAMP = pyodbc.SQL_TYPE_TIMESTAMP +_BCP_ENTRY_FALLBACK_CASES = [ + ("nvarchar(30)", [0.1, 1e20], None), + ("int", ["5"], None), + ("datetime2(3)", ["2024-01-02 03:04:05"], None), + ("money", [1.23456], None), + ("real", [Decimal("0.1")], None), + ("nvarchar(10)", [5], None), + ("int", [True], None), + ("time(3)", [time(1, 2, 3, 456789)], (_TIMESTAMP, 27, 7)), + ("datetime2(7)", [datetime(2024, 1, 2, 3, 4, 5, 123456)], (_TIMESTAMP, 23, 3)), + ("datetime2(0)", [datetime(2024, 1, 2, 3, 4, 5, 600000)], [_TIMESTAMP, 27, 7]), + ("datetime2(0)", [datetime(2024, 1, 2, 3, 4, 5, 600000)], 27), + ("nvarchar(10)", ["abc"], (pyodbc.SQL_WCHAR, 5, 0)), + ("nvarchar(10)", ["é東"], (pyodbc.SQL_VARCHAR, 5, 0)), + ("float", [0.1], (pyodbc.SQL_REAL, 7, 0)), + ("varchar(3)", ["ab "], None), + ("varchar(12) collate Japanese_CI_AS", ["é" * 7], None), + ("varchar(20)", ["thin space", "łódź ā"], None), + ("char(10) collate Polish_CI_AS", ["a b"], None), + ("text", [" "], None), + ("varchar(20) collate Japanese_CI_AS", ["é"], None), +] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,values,entry", _BCP_ENTRY_FALLBACK_CASES, + ids=[t for t, _, _ in _BCP_ENTRY_FALLBACK_CASES]) +def test_bcp_declines_input_sizes_it_cannot_reproduce(bcp_cursor: pyodbc.Cursor, + column_type: str, values: list, entry): + """ + Entries and pairings whose conversion BCP does not reproduce are left to the plain path: + other entry forms and types, and values whose entry the server converts differently than + BCP would, such as text into a number column, a double into text, or text with characters + a varchar column's code page lacks, which the server and the driver substitute differently. + `entry` None stands for the entry _entry_for gives. + """ + sizes = [None, entry if entry is not None else _entry_for(values)] + bcp, plain = _load_both(bcp_cursor, column_type, values, expect_bcp=False, sizes=sizes) + assert bcp == plain + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,entry", [ + ("varbinary(10)", (pyodbc.SQL_WVARCHAR, 1, 0)), + ("varbinary(max)", (pyodbc.SQL_WVARCHAR, 1, 0)), + ("binary(4)", (pyodbc.SQL_WVARCHAR, 1, 0)), + ("int", (pyodbc.SQL_TYPE_DATE, 10, 0)), + ("int", (_TIMESTAMP, 27, 7)), + ("date", (pyodbc.SQL_BIGINT, 19, 0)), + ("date", (pyodbc.SQL_BIT, 1, 0)), + ("time(3)", (pyodbc.SQL_DOUBLE, 15, 0)), + ("uniqueidentifier", (pyodbc.SQL_NUMERIC, 5, 2)), + ("xml", (pyodbc.SQL_BIGINT, 19, 0)), +]) +def test_bcp_fails_where_plain_path_rejects_an_entry_for_nulls(bcp_cursor: pyodbc.Cursor, + column_type: str, entry): + """ + The server converts even NULLs from their entry's type, so the plain path rejects a column + of NULLs whose entry type has no implicit conversion to the column's, and BCP declines it. + """ + cur = bcp_cursor + for bcp in (False, True): + cur.execute("drop table if exists t1") + cur.execute(f"create table t1(id int, v {column_type})") + cur.setinputsizes([None, entry]) + try: + with pytest.raises(pyodbc.Error): + _executemany(cur, "insert into t1 values (?, ?)", [(1, None), (2, None)], + bcp=bcp) + finally: + cur.setinputsizes(None) + assert cur.execute("select count(*) from t1").fetchval() == 0 + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_input_sizes_follow_the_parameters(bcp_cursor: pyodbc.Cursor): + """ + Entries belong to the statement's parameters, not the table's columns: with a column list + that reorders them, an identity column and a column left to its default, each entry still + applies to its own parameter, as on the plain path. + """ + cur = bcp_cursor + columns = ("id int identity, t datetime2(0), n decimal(10,2), s varchar(10), " + "d int default 7") + rows = [(Decimal("1.005"), datetime(2024, 1, 2, 3, 4, 5, 600000), "abc"), + (Decimal("-2.345"), datetime(2024, 1, 2, 3, 4, 5, 400000), None)] + sizes = [(pyodbc.SQL_NUMERIC, 4, 3), (_TIMESTAMP, 27, 7), (pyodbc.SQL_WVARCHAR, 3, 0)] + stored = {} + for table, bcp in (("t1", True), ("t2", False)): + cur.execute(f"create table {table}({columns})") + cur.setinputsizes(sizes) + try: + copied = _executemany(cur, f"insert into {table}(n, t, s) values (?, ?, ?)", rows, + bcp=bcp) + finally: + cur.setinputsizes(None) + assert copied == (len(rows) if bcp else -1) + stored[bcp] = [tuple(r) for r in cur.execute(f"select * from {table} order by id")] + assert stored[True] == stored[False] == [ + (1, datetime(2024, 1, 2, 3, 4, 6), Decimal("1.01"), "abc", 7), + (2, datetime(2024, 1, 2, 3, 4, 5), Decimal("-2.35"), None, 7), + ] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_without_an_entry_keeps_the_untyped_rules(bcp_cursor: pyodbc.Cursor): + """ + A None entry, or a parameter past the end of the entries, leaves that column to the rules + without setinputsizes, under which datetime2 truncates its fraction as the plain path does. + """ + value = datetime(2024, 1, 2, 3, 4, 5, 999999) + for sizes in ([None, None], [(pyodbc.SQL_BIGINT, 19, 0)]): + bcp_cursor.execute("drop table if exists t1") + bcp_cursor.execute("drop table if exists t2") + bcp, plain = _load_both(bcp_cursor, "datetime2(0)", [value], sizes=sizes) + assert bcp == plain == [datetime(2024, 1, 2, 3, 4, 5)] + + +_BCP_ENTRY_BOTH_FAIL_CASES = [ + ("decimal(5,4)", Decimal("9.99995"), None, True), + ("decimal(10,4)", Decimal("1.234"), (pyodbc.SQL_NUMERIC, 5, 2), None), + ("decimal(10,4)", Decimal("1234.5"), (pyodbc.SQL_NUMERIC, 4, 1), True), + ("tinyint", Decimal("-1.0"), None, True), + ("int", 2**31, None, True), + ("tinyint", 256, None, True), + ("decimal(5,2)", 1000, None, True), + ("bigint", 2.0**63, None, True), + ("int", 2.0**31, None, True), + ("tinyint", -1.5, None, True), + ("decimal(3,2)", 9.996, None, True), + ("decimal(38,10)", 1e300, None, True), + ("real", 1e39, None, True), + ("real", 3.4028235677973366e38, None, True), + ("bit", float("nan"), None, True), + ("float", float("inf"), None, True), + ("smalldatetime", datetime(2079, 6, 6, 23, 59, 30), None, True), + ("smalldatetime", datetime(1899, 12, 31, 23, 59, 29), None, True), + ("datetime", datetime(1752, 12, 31), None, True), + ("time(3)", date(2024, 1, 2), None, False), + ("nvarchar(3)", "abcd", None, False), + ("nvarchar(10)", "abcd", (pyodbc.SQL_WVARCHAR, 2, 0), False), + ("varchar(5) collate Latin1_General_100_CI_AS_SC_UTF8", "ééé", None, False), + ("char(4) collate Japanese_CI_AS", "東京東京", None, False), +] + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +@pytest.mark.parametrize("column_type,value,entry,runs", _BCP_ENTRY_BOTH_FAIL_CASES, + ids=[t for t, _, _, _ in _BCP_ENTRY_BOTH_FAIL_CASES]) +def test_bcp_fails_where_plain_path_fails_with_input_sizes(bcp_cursor: pyodbc.Cursor, + column_type: str, value, entry, + runs: bool | None): + """ + A value the plain path rejects under its entry raises with BCP enabled too, and BCP stores + nothing: overflow after the server's rounding, a Decimal wider than its entry, a non-finite + double, a datetime out of its column's range, and text longer than its column or entry, + counted in bytes for a multi-byte collation. `entry` None stands for the entry _entry_for + gives. `runs` says whether BCP carries out the load or declines it, as the error shows + (see _raised_by_bcp), or is None where both paths raise the same error. + """ + cur = bcp_cursor + sizes = [None, entry if entry is not None else _entry_for([value])] + stored = {} + for bcp in (False, True): + cur.execute("drop table if exists t1") + cur.execute(f"create table t1(id int, v {column_type})") + cur.setinputsizes(sizes) + try: + with pytest.raises(pyodbc.Error) as raised: + rows = [(1, None), (2, value)] + _executemany(cur, "insert into t1 values (?, ?)", rows, bcp=bcp) + finally: + cur.setinputsizes(None) + if runs is not None: + assert _raised_by_bcp(raised.value) == (bcp and runs) + stored[bcp] = [tuple(r) for r in cur.execute("select id, v from t1")] + assert stored[True] in ([], stored[False]) + + +@pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) +def test_bcp_column_names_in_case_sensitive_database(bcp_cursor: pyodbc.Cursor): + """ + Column-list names are matched as the database compares identifiers: ignoring case in the + usual case-insensitive collations, exactly in a case-sensitive one, where a name in the + wrong case is left to the plain path to reject. + """ + cur = bcp_cursor + cur.execute("drop database if exists pyodbc_bcp_cs") + try: + cur.execute("create database pyodbc_bcp_cs collate Latin1_General_CS_AS") + except pyodbc.Error: + pytest.skip("cannot create a database") + try: + cur.execute("create table pyodbc_bcp_cs.dbo.t(id int, abc int)") + sql = "insert into pyodbc_bcp_cs.dbo.t ({}) values (?, ?)" + assert _executemany(cur, sql.format("id, abc"), [(1, 2)]) == 1 + with pytest.raises(pyodbc.ProgrammingError): + _executemany(cur, sql.format("ID, abc"), [(3, 4)]) + cur.execute("create table t1(id int, abc int)") + assert _executemany(cur, "insert into t1 (ID, ABC) values (?, ?)", [(5, 6)]) == 1 + finally: + cur.execute("drop database pyodbc_bcp_cs") @pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) @@ -1831,8 +3105,9 @@ def __float__(self) -> float: @pytest.mark.skipif(not IS_BCP_DRIVER, reason=_BCP_SKIP) def test_bcp_conversion_that_closes_the_connection(bcp_cursor: pyodbc.Cursor): """ - A value whose conversion closes the connection mid-row raises ProgrammingError instead of - using the connection's freed state. + A value whose conversion closes the connection mid-row raises ProgrammingError, in both the + low-level API and the fast path, instead of using the connection's freed state. So does + one that closes the cursor holding the only reference to the connection. """ bcp_cursor.execute("create table t1(f float, s nvarchar(10))") victim = bcp_connect() @@ -1843,6 +3118,33 @@ def test_bcp_conversion_that_closes_the_connection(bcp_cursor: pyodbc.Cursor): victim.bcp_setrow(ctx, (_ClosesConnection(victim), "second")) assert victim.closed + class ClosingUUID(uuid.UUID): + @property + def bytes_le(self) -> bytes: + victim3.close() + return super().bytes_le + + bcp_cursor.execute("drop table t1") + bcp_cursor.execute("create table t1(id int, g uniqueidentifier)") + victim3 = bcp_connect() + with pytest.raises(pyodbc.ProgrammingError): + _executemany(victim3.cursor(), "insert into t1 values (?, ?)", + [(1, uuid.UUID(int=1)), (2, ClosingUUID(int=7))]) + assert victim3.closed + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + + class ClosingCursorUUID(uuid.UUID): + @property + def bytes_le(self) -> bytes: + victim4.close() + gc.collect() + return super().bytes_le + + victim4 = bcp_connect().cursor() + with pytest.raises(pyodbc.ProgrammingError, match="cursor was closed"): + _executemany(victim4, "insert into t1 values (?, ?)", [(1, ClosingCursorUUID(int=7))]) + assert bcp_cursor.execute("select count(*) from t1").fetchval() == 0 + class _HostType: """A host type whose __index__ runs `action` first, as a hostile int-like value might.""" diff --git a/utils/bcp_benchmark.py b/utils/bcp_benchmark.py new file mode 100644 index 00000000..e830e93c --- /dev/null +++ b/utils/bcp_benchmark.py @@ -0,0 +1,109 @@ +"""Standalone benchmark for the SQL Server BCP fast path. + +Compares row-by-row executemany, fast_executemany, and the BCP fast path +(with and without the TABLOCK hint) for a bulk insert into a heap table. + +This is a manual benchmark, not a pytest test; it lives in utils/ rather than +tests/ so it is never collected by pytest. Run it directly: + + PYODBC_SQLSERVER="DRIVER={ODBC Driver 18 for SQL Server};SERVER=...;..." \\ + python utils/bcp_benchmark.py [bulk_rows] + +The connection string is read from the PYODBC_SQLSERVER environment variable +(falling back to the DSN 'pyodbc-sqlserver'); the optional argument overrides +the number of rows used for the bulk methods. +""" + +import os +import sys +from datetime import datetime +from time import perf_counter + +import pyodbc + +CNXNSTR = os.environ.get('PYODBC_SQLSERVER', 'DSN=pyodbc-sqlserver') + +# Number of rows for the row-by-row reference (kept small) and the bulk methods. +SLOW_ROWS = 5_000 +BULK_ROWS = 1_000_000 +BATCH_ROWS = 20_000 + + +def make_data(n: int) -> list[tuple]: + return [ + (i, float(i) * 1.1, f"row {i}", datetime(2020, 1, (i % 28) + 1, 12, 0, 0, i % 1000)) + for i in range(n) + ] + + +def report(label: str, n: int, secs: float) -> None: + rate = n / secs if secs > 0 else float("inf") + print(f"{label:<22} {n:>9,} rows in {secs:8.3f}s ({rate:>12,.0f} rows/s)") + + +def run_method(cursor: pyodbc.Cursor, sql: str, data: list[tuple], *, + fast: bool, bcp: bool, tablock: bool) -> float: + """ + Times one executemany of `data`. The BCP fast path declines anything it cannot store as + fast_executemany would, so a BCP run checks the rowcount it reports to be sure it really + took the BCP path rather than timing fast_executemany under the BCP label. + """ + cursor.execute("truncate table bcp_benchmark") + cursor.fast_executemany = fast + cursor.use_bcp_fast = bcp + if bcp: + cursor.bcp_batch_rows = BATCH_ROWS + cursor.bcp_tablock = tablock + start = perf_counter() + cursor.executemany(sql, data) + elapsed = perf_counter() - start + if bcp and cursor.rowcount != len(data): + raise RuntimeError("the BCP fast path fell back to fast_executemany") + return elapsed + + +def main() -> None: + bulk_rows = int(sys.argv[1]) if len(sys.argv) > 1 else BULK_ROWS + + cnxn = pyodbc.connect(CNXNSTR, autocommit=True, + attrs_before={pyodbc.SQL_COPT_SS_BCP: pyodbc.SQL_BCP_ON}) + cursor = cnxn.cursor() + + rm = cursor.execute( + "select recovery_model_desc from sys.databases where database_id = db_id()" + ).fetchval() + print(f"recovery model: {rm}") + + cursor.execute("drop table if exists bcp_benchmark") + cursor.execute( + """ + create table bcp_benchmark( + id int, + value float, + description varchar(100), + created_at datetime2(7)) + """) + + sql = "insert into bcp_benchmark values (?, ?, ?, ?)" + slow_data = make_data(SLOW_ROWS) + bulk_data = make_data(bulk_rows) + + report("executemany", SLOW_ROWS, + run_method(cursor, sql, slow_data, fast=False, bcp=False, tablock=False)) + report("fast_executemany", bulk_rows, + run_method(cursor, sql, bulk_data, fast=True, bcp=False, tablock=False)) + report("BCP (no TABLOCK)", bulk_rows, + run_method(cursor, sql, bulk_data, fast=True, bcp=True, tablock=False)) + report("BCP (TABLOCK)", bulk_rows, + run_method(cursor, sql, bulk_data, fast=True, bcp=True, tablock=True)) + + count = cursor.execute("select count(*) from bcp_benchmark").fetchval() + print(f"final row count: {count:,} (expected {bulk_rows:,})") + + cursor.execute("drop table if exists bcp_benchmark") + cursor.close() + cnxn.close() + + +if __name__ == "__main__": + main()