Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions mssql_python/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,10 +673,10 @@ def _map_sql_type( # pylint: disable=too-many-arguments,too-many-positional-arg

if isinstance(param, datetime.time):
return (
ddbc_sql_const.SQL_TIME.value,
ddbc_sql_const.SQL_C_TYPE_TIME.value,
8,
0,
ddbc_sql_const.SQL_TYPE_TIME.value,
ddbc_sql_const.SQL_C_CHAR.value,
16,
6,
False,
)

Expand Down Expand Up @@ -941,6 +941,16 @@ def _create_parameter_types_list( # pylint: disable=too-many-arguments,too-many
parameter, parameters_list, i, min_val=min_val, max_val=max_val
)

# If TIME values are being bound via text C-types, normalize them to a
# textual representation expected by SQL_C_CHAR/SQL_C_WCHAR binding.
if isinstance(parameter, datetime.time) and c_type in (
ddbc_sql_const.SQL_C_CHAR.value,
ddbc_sql_const.SQL_C_WCHAR.value,
):
time_text = parameter.isoformat(timespec="microseconds")
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
parameters_list[i] = time_text
column_size = max(column_size, len(time_text))

paraminfo.paramCType = c_type
paraminfo.paramSQLType = sql_type
paraminfo.inputOutputType = ddbc_sql_const.SQL_PARAM_INPUT.value
Expand Down Expand Up @@ -2250,6 +2260,12 @@ def executemany( # pylint: disable=too-many-locals,too-many-branches,too-many-s
for i, val in enumerate(processed_row):
if val is None:
continue
if isinstance(val, datetime.time) and parameters_type[i].paramCType in (
ddbc_sql_const.SQL_C_CHAR.value,
ddbc_sql_const.SQL_C_WCHAR.value,
):
processed_row[i] = val.isoformat(timespec="microseconds")
continue
if (
isinstance(val, decimal.Decimal)
and parameters_type[i].paramSQLType == ddbc_sql_const.SQL_VARCHAR.value
Expand Down
104 changes: 98 additions & 6 deletions mssql_python/pybind/ddbc_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "logger_bridge.hpp"

#include <cstdint>
#include <cctype>
#include <cstring> // For std::memcpy
#include <filesystem>
#include <iomanip> // std::setw, std::setfill
Expand All @@ -28,6 +29,7 @@
#define SQL_MAX_NUMERIC_LEN 16
#define SQL_SS_XML (-152)
#define SQL_SS_UDT (-151)
#define SQL_TIME_TEXT_MAX_LEN 32

#define STRINGIFY_FOR_CASE(x) \
case x: \
Expand All @@ -53,6 +55,69 @@
#endif
}

namespace PythonObjectCache {
py::object get_time_class();
}

inline py::object ParseSqlTimeTextToPythonObject(const char* timeText, SQLLEN timeTextLen) {
if (!timeText || timeTextLen <= 0) {
return py::none();
}

size_t len = static_cast<size_t>(timeTextLen);
if (timeTextLen == SQL_NO_TOTAL) {
len = std::strlen(timeText);

Check notice

Code scanning / devskim

If a string is missing a null terminator, strlen will read past the end of the buffer Note

Problematic C function detected (strlen)
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
}

std::string value(timeText, len);

size_t start = value.find_first_not_of(" \t\r\n");
if (start == std::string::npos) {
return py::none();
}
size_t end = value.find_last_not_of(" \t\r\n");
value = value.substr(start, end - start + 1);

size_t firstColon = value.find(':');
size_t secondColon = (firstColon == std::string::npos) ? std::string::npos
: value.find(':', firstColon + 1);
if (firstColon == std::string::npos || secondColon == std::string::npos) {
ThrowStdException("Failed to parse TIME/TIME2 value: missing ':' separators");
}

int hour = std::stoi(value.substr(0, firstColon));
int minute = std::stoi(value.substr(firstColon + 1, secondColon - firstColon - 1));

size_t dotPos = value.find('.', secondColon + 1);
int second = 0;
int microsecond = 0;

if (dotPos == std::string::npos) {
second = std::stoi(value.substr(secondColon + 1));
} else {
second = std::stoi(value.substr(secondColon + 1, dotPos - secondColon - 1));
std::string frac = value.substr(dotPos + 1);

size_t digitCount = 0;
while (digitCount < frac.size() && std::isdigit(static_cast<unsigned char>(frac[digitCount]))) {
++digitCount;
}
frac = frac.substr(0, digitCount);

if (frac.size() > 6) {
frac = frac.substr(0, 6);
}
while (frac.size() < 6) {
frac.push_back('0');
}
if (!frac.empty()) {
microsecond = std::stoi(frac);
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
}
}

return PythonObjectCache::get_time_class()(hour, minute, second, microsecond);
}

//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Logging Infrastructure:
Expand Down Expand Up @@ -3244,9 +3309,23 @@
}
break;
}
case SQL_TIME:
case SQL_TYPE_TIME:
case SQL_SS_TIME2: {
char timeTextBuffer[SQL_TIME_TEXT_MAX_LEN] = {0};
SQLLEN timeDataLen = 0;
ret = SQLGetData_ptr(hStmt, i, SQL_C_CHAR, &timeTextBuffer, sizeof(timeTextBuffer),
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
&timeDataLen);
if (SQL_SUCCEEDED(ret) && timeDataLen != SQL_NULL_DATA) {
row.append(ParseSqlTimeTextToPythonObject(timeTextBuffer, timeDataLen));
} else {
LOG("SQLGetData: Error retrieving SQL_SS_TIME2 for column "
"%d - SQLRETURN=%d",
i, ret);
row.append(py::none());
}
Comment thread
jahnvi480 marked this conversation as resolved.
Outdated
break;
}
case SQL_TIME:
case SQL_TYPE_TIME: {
SQL_TIME_STRUCT timeValue;
ret =
SQLGetData_ptr(hStmt, i, SQL_C_TYPE_TIME, &timeValue, sizeof(timeValue), NULL);
Expand Down Expand Up @@ -3523,7 +3602,7 @@
ret = SQLBindCol_ptr(hStmt, col, SQL_C_WCHAR, buffers.wcharBuffers[col - 1].data(),
fetchBufferSize * sizeof(SQLWCHAR),
buffers.indicators[col - 1].data());
break;

Check notice

Code scanning / devskim

A "TODO" or similar was left in source code, possibly indicating incomplete functionality Note

Suspicious comment
}
case SQL_INTEGER:
buffers.intBuffers[col - 1].resize(fetchSize);
Expand Down Expand Up @@ -3587,12 +3666,16 @@
break;
case SQL_TIME:
case SQL_TYPE_TIME:
case SQL_SS_TIME2:
buffers.timeBuffers[col - 1].resize(fetchSize);
ret =
SQLBindCol_ptr(hStmt, col, SQL_C_TYPE_TIME, buffers.timeBuffers[col - 1].data(),
sizeof(SQL_TIME_STRUCT), buffers.indicators[col - 1].data());
break;
case SQL_SS_TIME2:
buffers.charBuffers[col - 1].resize(fetchSize * SQL_TIME_TEXT_MAX_LEN);
ret = SQLBindCol_ptr(hStmt, col, SQL_C_CHAR, buffers.charBuffers[col - 1].data(),
SQL_TIME_TEXT_MAX_LEN, buffers.indicators[col - 1].data());
break;
case SQL_GUID:
buffers.guidBuffers[col - 1].resize(fetchSize);
ret = SQLBindCol_ptr(hStmt, col, SQL_C_GUID, buffers.guidBuffers[col - 1].data(),
Expand Down Expand Up @@ -3896,8 +3979,7 @@
break;
}
case SQL_TIME:
case SQL_TYPE_TIME:
case SQL_SS_TIME2: {
case SQL_TYPE_TIME: {
PyObject* timeObj =
PythonObjectCache::get_time_class()(buffers.timeBuffers[col - 1][i].hour,
buffers.timeBuffers[col - 1][i].minute,
Expand All @@ -3907,6 +3989,14 @@
PyList_SET_ITEM(row, col - 1, timeObj);
break;
}
case SQL_SS_TIME2: {
const char* rawData = reinterpret_cast<const char*>(
&buffers.charBuffers[col - 1][i * SQL_TIME_TEXT_MAX_LEN]);
SQLLEN timeDataLen = buffers.indicators[col - 1][i];
py::object timeObj = ParseSqlTimeTextToPythonObject(rawData, timeDataLen);
PyList_SET_ITEM(row, col - 1, timeObj.release().ptr());
break;
}
case SQL_SS_TIMESTAMPOFFSET: {
SQLULEN rowIdx = i;
const DateTimeOffset& dtoValue = buffers.datetimeoffsetBuffers[col - 1][rowIdx];
Expand Down Expand Up @@ -4036,9 +4126,11 @@
break;
case SQL_TIME:
case SQL_TYPE_TIME:
case SQL_SS_TIME2:
rowSize += sizeof(SQL_TIME_STRUCT);
break;
case SQL_SS_TIME2:
rowSize += SQL_TIME_TEXT_MAX_LEN;
break;
case SQL_GUID:
rowSize += sizeof(SQLGUID);
break;
Expand Down
Loading
Loading