diff --git a/README.md b/README.md index 83695256c..09d850067 100644 --- a/README.md +++ b/README.md @@ -555,6 +555,43 @@ strings do not require a character-by-character scan. Wide-character retrieval of `VARCHAR(MAX)` values uses a non-consuming binary length probe to size the conversion buffer, avoiding character loss at truncated UTF-16 conversion boundaries while preserving embedded and trailing NULs. +The experimental bounded-text path uses complete, reusable rowsets for `fetchall()` +and `fetchmany()` when a text column is wider than 256 declared characters. +Each bound cell still reserves its complete declared width. Temporary memory +is reduced by binding fewer rows simultaneously and reusing those buffers, +not by allocating actual-length native cells. +Initial bound storage targets 1 MiB including indicators, with at least one +complete row and at most 100 rows. After the first full batch the row capacity +can grow once to the ordinary 8 MiB target and 1,000 rows. Partial batches do not +trigger growth, and `fetchmany()` never grows beyond its remaining requested rows. +Values are decoded directly into actual-length Python results, without a second +native copy or per-cell length probes. Every driver fetch retains +cancellation and diagnostic handling; rebinding preserves cleanup lifetimes. +Fixed-width and short-text result sets retain rowset batching. Wide-text result +sets save temporary storage at startup and for short results, not throughout +large sparse `fetchall()` results: sustained fetching grows to the normal 8 MiB +target rather than imposing a persistently higher driver-call count. +For `fetchmany()`, that target can still save storage compared with binding the +entire requested row count, but can require multiple driver fetches. +Conversion metadata and processor dispatch are prepared once per native +reusable-rowset call, including +across buffer growth. No per-cell density scan is needed. +The earlier fixed-small-rowset experiment used 0.98 MiB instead of 7.94 MiB for +5,000 rows with an integer ID and eight short values declared `VARCHAR(8000)`, +but increased fetch calls from 78 to 626. The growth policy intentionally gives +up that sustained memory reduction to restore useful batching. +Driver-call counts are not measured network round trips; they do not +establish production latency on the current revision. Profiling-enabled CI +reports are attribution evidence, and a "no signal" result does not rule out +smaller slowdowns. Repeated, matched, profiling-disabled measurements are needed +before claiming a throughput benefit or no regression. +The rowsets do not change the forward-only cursor type or recover truncated +multirow bindings with `SQLGetData`. A row larger than either budget remains +complete; Python results and allocator overhead are outside those targets. +`fetchmany()` retains the native 256 MiB caller-size guard based on the requested +row count and declared row width, even when reusable batches would be smaller. +Result sets containing LOB columns retain their existing streaming path. +The 256-character cutoff is provisional, not a tuned throughput threshold. Explicit `setinputsizes()` SQL types and sizes still take precedence. An explicit `VARCHAR` parameter can lose characters outside the database collation's code page even when inserting into an `NVARCHAR` destination; use `SQL_WVARCHAR` when diff --git a/eng/scripts/normalize_python_lcov.py b/eng/scripts/normalize_python_lcov.py new file mode 100644 index 000000000..320ecee3a --- /dev/null +++ b/eng/scripts/normalize_python_lcov.py @@ -0,0 +1,33 @@ +"""Move LCOV function starts off non-executable docstrings without changing hit counts.""" + +import argparse +from bisect import bisect_left +from pathlib import Path + + +def normalize_function_starts(report: str) -> str: + records = report.split("end_of_record") + if records[-1].strip(): + raise ValueError("Incomplete LCOV record") + normalized = [] + for record in records[:-1]: + lines = record.strip().splitlines() + executable = sorted(int(line[3:].split(",", 1)[0]) for line in lines if line.startswith("DA:")) + for index, line in enumerate(lines): + if not line.startswith("FN:"): + continue + start, end, name = line[3:].split(",", 2) + position = bisect_left(executable, int(start)) + if position == len(executable) or executable[position] > int(end): + raise ValueError(f"Function {name!r} has no executable line in its LCOV range") + lines[index] = f"FN:{executable[position]},{end},{name}" + normalized.append("\n".join([*lines, "end_of_record"])) + return "\n".join(normalized) + "\n" + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path) + args = parser.parse_args() + content = normalize_function_starts(args.report.read_text(encoding="utf-8")) + args.report.write_text(content, encoding="utf-8", newline="\n") diff --git a/generate_codecov.sh b/generate_codecov.sh index 7d684e2d3..b544866da 100644 --- a/generate_codecov.sh +++ b/generate_codecov.sh @@ -64,6 +64,9 @@ python -m pytest -v "$@" \ # Convert Python coverage to LCOV format (restrict to repo only) echo "[ACTION] Converting Python coverage to LCOV" coverage lcov -o python-coverage.info --include="mssql_python/*" +# coverage.py 7.18 can place FN on a docstring with no DA entry. LCOV 2.4 +# cannot categorize that location; use the first executable line in the range. +python eng/scripts/normalize_python_lcov.py python-coverage.info echo "===================================" echo "[STEP 3] Processing C++ coverage (Clang/LLVM)" diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index d597262ad..2746c4508 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -4558,6 +4558,14 @@ static inline bool CanUseSingleRowForFetchMany(SQLSMALLINT dataType, SQLULEN col } } +static size_t CheckedFetchBufferBytes(size_t count, size_t itemSize, size_t terminator); + +static bool IsBoundedFetchText(SQLSMALLINT type, SQLULEN size) { + return size > 0 && size <= SQL_MAX_LOB_SIZE && + (type == SQL_CHAR || type == SQL_VARCHAR || type == SQL_LONGVARCHAR || + type == SQL_WCHAR || type == SQL_WVARCHAR || type == SQL_WLONGVARCHAR); +} + static SQLSMALLINT FixedScalarCType(SQLSMALLINT type) { switch (type) { case SQL_INTEGER: return SQL_C_LONG; @@ -4638,11 +4646,10 @@ static size_t FetchFixedScalarRun(SQLHSTMT statement, StatementOperation* operat return read; } -static SQLRETURN GetRowData( - const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount, +static SQLRETURN GetRowData(const SqlHandlePtr& StatementHandle, SQLUSMALLINT colCount, py::list& row, const std::string& charEncoding, - const std::string& wcharEncoding, int charCtype, - py::handle messages, const ResultMetadataCache::Snapshot& snapshot, + const std::string& wcharEncoding, int charCtype, py::handle messages, + const ResultMetadataCache::Snapshot& snapshot, bool completeResult = false, py::handle converters = {}, bool batchText = false) { PERF_TIMER("SQLGetData_wrap"); @@ -4680,7 +4687,8 @@ static SQLRETURN GetRowData( } auto* operation = StatementOperation::current(hStmt); - const bool groupScalars = operation && metadata && + const bool groupScalars = + operation && metadata && (!converters || converters.is_none() || (PyDict_CheckExact(converters.ptr()) && PyDict_Size(converters.ptr()) == 0)); for (SQLSMALLINT i = 1; i <= colCount; ++i) { @@ -5864,6 +5872,17 @@ SQLRETURN SQLBindColums(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& return ret; } +static void ValidateBoundCellLength(SQLSMALLINT type, SQLLEN indicator, size_t capacity, + bool wide) { + const bool text = IsBoundedFetchText(type, 1); + const bool decimal = type == SQL_DECIMAL || type == SQL_NUMERIC; + const size_t terminator = text ? (wide ? sizeof(SQLWCHAR) : 1) : (decimal ? 1 : 0); + if (indicator != SQL_NULL_DATA && + (indicator < 0 || static_cast(indicator) > capacity - terminator || + (wide && indicator % sizeof(SQLWCHAR)))) + ThrowStdException("Invalid bounded fetch length"); +} + void ValidateFetchedRowCount(const ColumnBuffers& buffers, SQLUSMALLINT numCols, SQLULEN numRowsFetched) { if (numRowsFetched == 0) { @@ -5890,41 +5909,43 @@ void ValidateArrowFetchedRowCount(SQLULEN numRowsFetched, int currentFetchSize, } } -// Fetch rows in batches -// TODO: Move to anonymous namespace, since it is not used outside this file -template -SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, - py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, - const std::vector& lobColumns, - const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, - py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0, - int bufferRows = 0) { - // Pre-cache column metadata to avoid repeated dictionary lookups. - // The vectors below are consumed later by construct_rows, so they are - // declared at function scope; only the population work is wrapped in the - // cache_column_metadata timer's block (an earlier version put the timer at - // function scope, so it stayed active through construct_rows and made - // metadata caching look like a dominant fetch cost). +struct BufferedRowConversion { struct ColumnInfo { SQLSMALLINT dataType; SQLULEN columnSize; SQLULEN processedColumnSize; uint64_t fetchBufferSize; + size_t bufferBytes; size_t fixedValueSize; bool isLob; }; - const bool useWideChar = (charCtype == SQL_C_WCHAR); - std::vector columnInfos(numCols); - // Performance: Build function pointer dispatch table (once per batch). - // This eliminates the switch statement from the hot loop - 10,000 rows × 10 - // cols reduces from 100,000 switch evaluations to just 10 switch evaluations. - std::vector columnProcessors(numCols); - std::vector columnInfosExt(numCols); - // Compute effective char encoding once for the batch (same for all columns) - const std::string effectiveCharEnc = GetEffectiveCharDecoding(charEncoding); + std::vector columnInfos; + std::vector columnProcessors; + std::vector columnInfosExt; + bool prepared = false; +}; - { +// Fetch rows in batches +// TODO: Move to anonymous namespace, since it is not used outside this file +template +SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, + py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, + const std::vector& lobColumns, + const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, + py::handle messages = {}, py::handle converters = {}, SQLULEN firstRow = 0, + int bufferRows = 0, BufferedRowConversion* reusableConversion = nullptr) { + BufferedRowConversion localConversion; + auto& conversion = reusableConversion ? *reusableConversion : localConversion; + auto& columnInfos = conversion.columnInfos; + auto& columnProcessors = conversion.columnProcessors; + auto& columnInfosExt = conversion.columnInfosExt; + if (!conversion.prepared) { PERF_TIMER("FetchBatchData::cache_column_metadata"); + const bool useWideChar = (charCtype == SQL_C_WCHAR); + const std::string effectiveCharEnc = GetEffectiveCharDecoding(charEncoding); + columnInfos.resize(numCols); + columnProcessors.resize(numCols); + columnInfosExt.resize(numCols); for (SQLUSMALLINT col = 0; col < numCols; col++) { const auto& columnMeta = GetFetchColumnMetadata(columnNames, col); columnInfos[col].dataType = GetFetchColumnType(columnMeta); @@ -5937,6 +5958,9 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta HandleZeroColumnSizeAtFetch(columnInfos[col].processedColumnSize); SQLSMALLINT dt = columnInfos[col].dataType; + columnInfos[col].bufferBytes = + strictLengths ? BoundColumnBufferBytes(dt, columnInfos[col].columnSize, charCtype) + : 0; if (dt == SQL_CHAR || dt == SQL_VARCHAR || dt == SQL_LONGVARCHAR || dt == SQL_WCHAR || dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR) { const bool wide = useWideChar || @@ -6028,7 +6052,8 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta break; } } - } // end cache_column_metadata timer scope + conversion.prepared = true; + } // Performance: Single-phase row creation pattern // Create each row, fill it completely, then append to results list @@ -6066,6 +6091,10 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta // functions This eliminates redundant NULL checks inside each // processor and improves CPU branch prediction SQLLEN dataLen = buffers.indicators[col - 1][i]; + if constexpr (strictLengths) + ValidateBoundCellLength(columnInfos[col - 1].dataType, dataLen, + columnInfos[col - 1].bufferBytes, + !buffers.wcharBuffers[col - 1].empty()); const auto type = columnInfos[col - 1].dataType; if (dataLen != SQL_NULL_DATA && (type == SQL_DECIMAL || type == SQL_NUMERIC)) { ValidateDecimalDataLength(dataLen); @@ -6256,12 +6285,14 @@ static py::list TestBoundDecimalRows(SQLSMALLINT dataType, SQLLEN indicator) { return rows; } -template +template SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& columnNames, py::list& rows, SQLUSMALLINT numCols, SQLULEN& numRowsFetched, const std::vector& lobColumns, const std::string& charEncoding = "utf-16le", int charCtype = SQL_C_WCHAR, - py::handle messages = {}, py::handle converters = {}) { + py::handle messages = {}, py::handle converters = {}, + size_t maximumRows = 0, + BufferedRowConversion* reusableConversion = nullptr) { PERF_TIMER("FetchBatchData"); LOG("FetchBatchData: Fetching data in batches"); SQLRETURN ret; @@ -6274,13 +6305,19 @@ SQLRETURN FetchBatchData(SQLHSTMT hStmt, ColumnBuffers& buffers, const Metadata& if (!SQL_SUCCEEDED(ret)) { return ret; } - ConvertBufferedRows(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, - lobColumns, charEncoding, charCtype, messages, converters); + if constexpr (strictLengths) { + if (numRowsFetched == 0 || numRowsFetched > maximumRows) + ThrowStdException("Invalid bounded fetch row count"); + } + ConvertBufferedRows(hStmt, buffers, columnNames, rows, numCols, numRowsFetched, + lobColumns, charEncoding, charCtype, messages, converters, + 0, 0, reusableConversion); return ret; } -static size_t BoundRowBufferBytes(const py::list& columnNames, SQLUSMALLINT numCols, - int charCtype) { +template +static size_t BoundRowBufferBytes(const Metadata& columnNames, SQLUSMALLINT numCols, + int charCtype) { size_t rowSize = 0; const size_t limit = static_cast(std::numeric_limits::max()); for (SQLUSMALLINT col = 0; col < numCols; ++col) { @@ -6391,6 +6428,75 @@ struct FetchStateGuard { } }; +// Start with a small rowset, then use normal batching after the first complete batch. +// Full-width bindings preserve values without SQLGetData recovery or cursor changes. +static SQLRETURN FetchReusableTextRows(const SqlHandlePtr& handle, SQLUSMALLINT numCols, + py::list& rows, size_t limit, + const std::string& charEncoding, + const std::string& wcharEncoding, int charCtype, + py::handle messages, py::handle converters) { + PERF_TIMER("FetchReusableTextRows"); + (void)wcharEncoding; + if (limit == 0) + return SQL_SUCCESS; + const auto metadata = handle->resultMetadata.snapshot().metadata; + if (!metadata || metadata->columns.size() != numCols) + ThrowStdException("Column metadata count does not match result column count"); + const auto& columns = metadata->columns; + constexpr size_t maximumRows = 1000; + constexpr size_t maximumBudget = size_t{8} * 1024 * 1024; + constexpr size_t initialBudget = size_t{1} * 1024 * 1024; + const size_t boundBytes = BoundRowBufferBytes(columns, numCols, charCtype); + const size_t maximumBatchRows = + std::clamp(maximumBudget / boundBytes, 1, maximumRows); + const size_t initialBatchRows = + std::clamp(initialBudget / boundBytes, 1, maximumBatchRows); + size_t boundRows = std::min({limit, size_t{100}, initialBatchRows}); + FetchStateGuard guard(handle, messages, numCols, static_cast(boundRows)); + SQLHSTMT statement = handle->get(); + size_t reservedBytes = 0; + ReserveNativeFetchBytes(reservedBytes, numCols, boundRows * sizeof(SQLLEN)); + SQLRETURN ret = SQLBindColums(statement, guard.storage->columns, columns, numCols, + static_cast(boundRows), reservedBytes, charCtype, messages); + guard.observe(ret); + guard.configure(boundRows); + size_t configuredRows = boundRows; + // Strides and conversion settings stay fixed across complete-cell rebindings. + // Keep this plan local to the call; it owns no pointers into bound storage. + BufferedRowConversion conversion; + for (size_t count = 0; count < limit;) { + const size_t rowArray = std::min(boundRows, limit - count); + if (rowArray != configuredRows) { + guard.setRowArraySize(rowArray); + configuredRows = rowArray; + } + ret = FetchBatchData(statement, guard.storage->columns, columns, rows, numCols, + guard.storage->rowsFetched, {}, charEncoding, charCtype, messages, + converters, rowArray, &conversion); + CheckFetchError(handle, ret); + if (ret == SQL_NO_DATA) + break; + if (!SQL_SUCCEEDED(ret)) + return ret; + const size_t fetched = guard.storage->rowsFetched; + count += fetched; + if (count < limit && fetched == rowArray && boundRows < maximumBatchRows) { + const size_t batchRows = std::min(limit - count, maximumBatchRows); + if (batchRows <= boundRows) + continue; + guard.observe(SQLFreeStmt_ptr(statement, SQL_UNBIND)); + guard.storage->columns = ColumnBuffers(numCols, static_cast(batchRows)); + reservedBytes = 0; + ReserveNativeFetchBytes(reservedBytes, numCols, batchRows * sizeof(SQLLEN)); + ret = SQLBindColums(statement, guard.storage->columns, columns, numCols, + static_cast(batchRows), reservedBytes, charCtype, messages); + guard.observe(ret); + boundRows = batchRows; + } + } + guard.close(); + return SQL_SUCCESS; +} SQLRETURN DrainPendingArrowRows(SqlHandlePtr handle, py::list& rows, SQLULEN limit, const std::string& charEncoding, py::handle messages, py::handle converters); @@ -6472,6 +6578,7 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, py::handl std::vector lobColumns; bool singleRowEligible = fetchSize == 1; + bool dynamicText = false; for (SQLSMALLINT i = 0; i < numCols; i++) { const auto& column = columnNames.at(i); if (IsLobOrVariantColumn(column.dataType, column.columnSize)) { @@ -6479,6 +6586,18 @@ SQLRETURN FetchMany_wrap(SqlHandlePtr StatementHandle, py::list& rows, py::handl } singleRowEligible = singleRowEligible && CanUseSingleRowForFetchMany(column.dataType, column.columnSize); + dynamicText = dynamicText || + (IsBoundedFetchText(column.dataType, column.columnSize) && + column.columnSize > 256); + } + + if (dynamicText && lobColumns.empty()) { + // Preserve the caller-size limit before selecting smaller reusable batches. + size_t requestedBytes = 0; + ReserveNativeFetchBytes(requestedBytes, static_cast(fetchSize), + BoundRowBufferBytes(columnNames, numCols, charCtype)); + return FetchReusableTextRows(StatementHandle, numCols, rows, fetchSize, charEncoding, + wcharEncoding, charCtype, messages, converters); } if (singleRowEligible) { @@ -8353,6 +8472,7 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, } std::vector lobColumns; + bool dynamicText = false; for (SQLSMALLINT i = 0; i < numCols; i++) { auto colMeta = columnNames[i].cast(); SQLSMALLINT dataType = colMeta["DataType"].cast(); @@ -8363,13 +8483,14 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, if (IsLobOrVariantColumn(dataType, columnSize)) { lobColumns.push_back(i + 1); // 1-based } + dynamicText = dynamicText || + (IsBoundedFetchText(dataType, columnSize) && columnSize > 256); } // If we have LOBs → fall back to row-by-row fetch + SQLGetData_wrap - if (!lobColumns.empty()) { - LOG("FetchAll_wrap: LOB columns detected (%zu columns), using per-row " - "SQLGetData path", - lobColumns.size()); + if (!lobColumns.empty() || dynamicText) { + LOG("FetchAll_wrap: LOB columns=%zu, reusable bounded text=%d", lobColumns.size(), + dynamicText); if (numCols < 0 || columnNames.size() != static_cast(numCols)) { LOG("FetchAll_wrap: Column metadata count does not match result column count"); ThrowStdException("Column metadata count does not match result column count"); @@ -8388,6 +8509,10 @@ SQLRETURN FetchAll_wrap(SqlHandlePtr StatementHandle, py::list& rows, type == SQL_SS_VARIANT ? 0 : column["ColumnSize"].cast()}); } StatementHandle->resultMetadata.publish(metadataSnapshot.generation, std::move(metadata)); + if (lobColumns.empty()) + return FetchReusableTextRows(StatementHandle, numCols, rows, + std::numeric_limits::max(), charEncoding, + wcharEncoding, charCtype, messages, converters); while (true) { ret = CancellableCall(hStmt, [&] { return SQLFetch_ptr(hStmt); }); CaptureFetchDiagnostics(hStmt, ret, messages); diff --git a/tests/test_004_cursor.py b/tests/test_004_cursor.py index 539b603a4..91a96b31d 100644 --- a/tests/test_004_cursor.py +++ b/tests/test_004_cursor.py @@ -1780,11 +1780,14 @@ def test_executemany_rejects_text_for_binary_parameter(db_connection): cursor.executemany("SELECT CAST(? AS VARBINARY(10))", [("text",)]) -def test_fetchmany_rejects_excessive_native_buffer(cursor): - cursor.execute("SELECT CAST('x' AS VARCHAR(8000))") +@pytest.mark.parametrize("sql_type", ["VARCHAR(8000)", "NVARCHAR(4000)"]) +@pytest.mark.parametrize("column_count", [1, 8]) +def test_fetchmany_rejects_excessive_native_buffer(cursor, sql_type, column_count): + cursor.execute("SELECT " + ", ".join([f"CAST('x' AS {sql_type})"] * column_count)) with pytest.raises(RuntimeError, match="256 MiB allocation limit"): cursor.fetchmany(100_000) - assert cursor.fetchone()[0] == "x" + assert [tuple(row) for row in cursor.fetchmany(1)] == [("x",) * column_count] + assert cursor.fetchone() is None def test_fetchall_clamps_wide_result_batch_to_native_buffer_budget(cursor): diff --git a/tests/test_004_cursor_arrow.py b/tests/test_004_cursor_arrow.py index 701983d0c..3a11a0b38 100644 --- a/tests/test_004_cursor_arrow.py +++ b/tests/test_004_cursor_arrow.py @@ -39,9 +39,13 @@ import mssql_python import pyarrow.compute as pc -def wide_query(sql_type, columns, count=8192, identifiers=False, extra=""): +# Three-byte UTF-8 characters cross the Arrow byte budget with fewer ODBC rows. +ROW_COUNT = 2560 +PAYLOAD = "\\u0800" * 4000 + +def wide_query(sql_type, columns, count=ROW_COUNT, identifiers=False, extra=""): payload = ", ".join( - f"CAST(REPLICATE(N'A', 4000) AS {sql_type}) AS c{i}" for i in range(columns) + f"CAST(REPLICATE(NCHAR(2048), 4000) AS {sql_type}) AS c{i}" for i in range(columns) ) return f''' WITH digits(d) AS ( @@ -57,7 +61,7 @@ def wide_query(sql_type, columns, count=8192, identifiers=False, extra=""): def check_payload(value, columns, offset=0): for column in range(offset, offset + columns): - assert pc.all(pc.equal(value.column(column), "A" * 4000)).as_py() + assert pc.all(pc.equal(value.column(column), PAYLOAD)).as_py() """ @@ -141,10 +145,10 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column cur.execute(wide_query(sql_type, columns)) if method == "arrow": value = cur.arrow() - assert value.num_rows == 8192 + assert value.num_rows == ROW_COUNT check_payload(value, columns) if columns == 7: - assert value.nbytes == 229841920 + assert value.nbytes == 215185600, value.nbytes else: assert value.nbytes > 256 * 1024 * 1024 assert len(value.column(0).chunks) > 1 @@ -154,10 +158,10 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column total_bytes = 0 first = True while True: - value = cur.arrow_batch(8192) + value = cur.arrow_batch(ROW_COUNT) count = value.num_rows if first: - assert count == 8192 if columns == 7 else 0 < count < 8192 + assert count == ROW_COUNT if columns == 7 else 0 < count < ROW_COUNT first = False if not count: break @@ -167,9 +171,9 @@ def test_arrow_native_budget_lossless_batches(conn_str, sql_type, method, column assert value.nbytes <= 256 * 1024 * 1024 assert cur.rownumber == total - 1 del value - assert total == 8192 + assert total == ROW_COUNT if columns == 7: - assert total_bytes == 229841920 + assert total_bytes == 215185600, total_bytes else: assert total_bytes > 256 * 1024 * 1024 assert cur.fetchone() is None @@ -189,7 +193,7 @@ def test_arrow_native_budget_pending_mixed_fetches(conn_str, sql_type, remaining """ sql_type = sys.argv[1] remaining = sys.argv[2] - row_count = 8192 + row_count = ROW_COUNT extra = ''' , CAST('123.45' AS DECIMAL(10,2)) amount , CAST('2025-01-02' AS DATE) day @@ -200,7 +204,7 @@ def test_arrow_native_budget_pending_mixed_fetches(conn_str, sql_type, remaining ''' def check_row(row, expected): assert row[0] == expected - assert all(value == "A" * 4000 for value in row[1:10]) + assert all(value == PAYLOAD for value in row[1:10]) assert row[10] == Decimal("123.45") assert row[11] == date(2025, 1, 2) assert row[12] == UUID("58185E0D-3A91-44D8-BC46-7107217E0A6D") @@ -213,7 +217,7 @@ def check_row(row, expected): cur.execute( wide_query(sql_type, 9, count=row_count, identifiers=True, extra=extra) ) - first = cur.arrow_batch(8192) + first = cur.arrow_batch(ROW_COUNT) n = first.num_rows assert 0 < n < row_count assert first.column(0).to_pylist() == list(range(1, n + 1)) @@ -287,7 +291,7 @@ def test_arrow_native_budget_pending_scroll_skip(conn_str, sql_type): cur.execute(wide_query(sql_type, 9, identifiers=True)) first = cur.arrow_batch(8192) position = first.num_rows - assert 0 < position < 8192 + assert 0 < position < ROW_COUNT del first cur.scroll(0) cur.skip(0) @@ -319,8 +323,8 @@ def test_arrow_native_budget_pending_scroll_skip(conn_str, sql_type): position += 2 del rows assert cur.rownumber == position - 1 - cur.skip(8192 - position) - assert cur.rownumber == 8191 + cur.skip(ROW_COUNT - position) + assert cur.rownumber == ROW_COUNT - 1 assert cur.fetchone() is None try: cur.scroll(1) @@ -344,7 +348,7 @@ def test_arrow_native_budget_pending_raw_fetches(conn_str, sql_type): from mssql_python import ddbc_bindings as ddbc from mssql_python.constants import ConstantsDDBC as C sql_type = sys.argv[1] - row_count = 8192 + row_count = ROW_COUNT unsupported = ( (C.SQL_FETCH_RELATIVE.value, 0), (C.SQL_FETCH_RELATIVE.value, 1), (C.SQL_FETCH_RELATIVE.value, 67), (C.SQL_FETCH_RELATIVE.value, -1), @@ -396,7 +400,7 @@ def get_data(cur, count): assert ddbc.DDBCSQLSetStmtAttr( cur.hstmt, C.SQL_ATTR_QUERY_TIMEOUT.value, 0 ) in (0, 1) - assert get_data(cur, 3) == [position, "A" * 4000, "A" * 4000] + assert get_data(cur, 3) == [position, PAYLOAD, PAYLOAD] try: get_data(cur, 11) except RuntimeError as exc: @@ -405,7 +409,7 @@ def get_data(cur, count): raise AssertionError("Invalid prefix count was accepted") row = get_data(cur, 10) assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row row = [] assert ddbc.DDBCSQLFetchScroll( @@ -413,7 +417,7 @@ def get_data(cur, count): ) in (0, 1) position += 1 assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row assert cur.fetchone()[0] == position + 1 position += 1 @@ -437,7 +441,7 @@ def get_data(cur, count): ) in (0, 1) position += 1 assert row[0] == position - assert row[1:] == ["A" * 4000] * 9 + assert row[1:] == [PAYLOAD] * 9 del row # NEXT ignores its offset, and a nonempty output suppresses materialization. for offset in (0, 1, 67, -1, 123): @@ -481,7 +485,7 @@ def test_arrow_native_budget_pending_fetchall_after_raw_fetch(conn_str, sql_type from mssql_python import ddbc_bindings as ddbc from mssql_python.constants import ConstantsDDBC as C sql_type = sys.argv[1] - row_count = 8192 + row_count = ROW_COUNT with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, count=row_count, identifiers=True)) @@ -498,7 +502,7 @@ def test_arrow_native_budget_pending_fetchall_after_raw_fetch(conn_str, sql_type assert row == [position] rows = cur.fetchall() assert [row[0] for row in rows] == list(range(position + 1, row_count + 1)) - assert all(all(value == "A" * 4000 for value in row[1:]) for row in rows) + assert all(all(value == PAYLOAD for value in row[1:]) for row in rows) del rows assert cur.fetchone() is None """, @@ -553,17 +557,17 @@ def test_arrow_native_budget_resumes_partial_lob(conn_str, recovery): conn_str, """ recovery = sys.argv[1] - query = wide_query("nvarchar(max)", 7, count=6002, identifiers=True) + query = wide_query("nvarchar(max)", 7, count=2002, identifiers=True) query = query.replace( - "CAST(REPLICATE(N'A', 4000) AS nvarchar(max)) AS c0", - "CASE WHEN id = 6001 THEN REPLICATE(CAST(N'A' AS nvarchar(max)), " - "40 * 1024 * 1024) ELSE CAST(REPLICATE(N'A', 4000) AS nvarchar(max)) END AS c0" + "CAST(REPLICATE(NCHAR(2048), 4000) AS nvarchar(max)) AS c0", + "CASE WHEN id = 2001 THEN REPLICATE(CAST(N'A' AS nvarchar(max)), " + "40 * 1024 * 1024) ELSE CAST(REPLICATE(NCHAR(2048), 4000) AS nvarchar(max)) END AS c0" ) with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(query) first = cur.arrow_batch(8192) - assert first.num_rows == 6000 + assert first.num_rows == 2000 del first if recovery != "arrow_batch": if recovery == "raw_fetch": @@ -574,22 +578,22 @@ def test_arrow_native_budget_resumes_partial_lob(conn_str, recovery): assert ddbc.DDBCSQLGetData( cur.hstmt, 1, prefix, "utf-16le", "utf-16le", C.SQL_WCHAR.value ) in (0, 1) - assert prefix == [6001] + assert prefix == [2001] row = [] assert ddbc.DDBCSQLGetData( cur.hstmt, 8, row, "utf-16le", "utf-16le", C.SQL_WCHAR.value ) in (0, 1) else: row = cur.fetchone() - assert row[0] == 6001 + assert row[0] == 2001 assert len(row[1]) == 40 * 1024 * 1024 assert row[1].count("A") == len(row[1]) - assert all(value == "A" * 4000 for value in row[2:]) + assert all(value == PAYLOAD for value in row[2:]) del row - assert cur.fetchone()[0] == 6002 + assert cur.fetchone()[0] == 2002 else: batch = cur.arrow_batch(8192) - assert batch.column(0).to_pylist() == [6001, 6002] + assert batch.column(0).to_pylist() == [2001, 2002] value = batch.column(1)[0].as_py() assert len(value) == 40 * 1024 * 1024 assert value.count("A") == len(value) @@ -660,7 +664,7 @@ def test_arrow_native_budget_pending_reset_cleanup(conn_str, sql_type, operation """ sql_type = sys.argv[1] operation = sys.argv[2] - row_count = 8192 + row_count = ROW_COUNT with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn: with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, count=row_count) + "; SELECT 42 AS answer") @@ -707,7 +711,7 @@ def fetch_after_change(generic): with conn.cursor() as cur: cur.execute(wide_query(sql_type, 9, identifiers=True)) first = cur.arrow_batch(8192) - assert 0 < first.num_rows < 8192 + assert 0 < first.num_rows < ROW_COUNT del first if generic: conn._conn.set_attr( @@ -749,7 +753,7 @@ def test_arrow_native_budget_idempotent_autocommit_preserves_rows(conn_str, auto cur.execute(wide_query("nvarchar(4000)", 9, identifiers=True)) first = cur.arrow_batch(8192) count = first.num_rows - assert 0 < count < 8192 + assert 0 < count < ROW_COUNT assert first.column(0).to_pylist() == list(range(1, count + 1)) del first @@ -762,7 +766,7 @@ def test_arrow_native_budget_idempotent_autocommit_preserves_rows(conn_str, auto while rows := cur.fetchmany(64): assert [row[0] for row in rows] == list(range(next_id, next_id + len(rows))) next_id += len(rows) - assert next_id == 8193 + assert next_id == ROW_COUNT + 1 """, str(autocommit), ) diff --git a/tests/test_017_fetch_bounded_text.py b/tests/test_017_fetch_bounded_text.py index 38845af54..a9988a2f2 100644 --- a/tests/test_017_fetch_bounded_text.py +++ b/tests/test_017_fetch_bounded_text.py @@ -14,6 +14,88 @@ from mssql_python import SQL_CHAR, SQL_WCHAR +def test_native_invalid_size_wide_fetch_preserves_pending_rows(db_connection): + from mssql_python import ddbc_bindings + + with db_connection.cursor() as cursor: + cursor.execute("SELECT CAST(N'pending' AS nvarchar(4000))") + rows = [] + with pytest.raises(RuntimeError, match="Fetch size must be between 1 and 1000000"): + ddbc_bindings.DDBCSQLFetchMany(cursor.hstmt, rows, 0) + assert rows == [] + assert [tuple(row) for row in cursor.fetchall()] == [("pending",)] + + +@pytest.mark.parametrize("batch_size", [101, 129]) +@pytest.mark.parametrize("narrow", [False, True], ids=["wide", "narrow"]) +def test_dense_fetchmany_growth_preserves_tail_and_converter_storage( + db_connection, batch_size, narrow +): + retained = [] + db_connection.add_output_converter( + str, lambda raw: retained.append(raw) or raw.decode("utf-16le") + ) + value = "\u00e9" * (8000 if narrow else 4000) + expression = "CAST(? AS varchar(8000))" if narrow else "CAST(? AS nvarchar(4000))" + try: + with db_connection.cursor() as cursor: + cursor.execute( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)) " + f"SELECT n, {', '.join([expression] * 8)} " + "FROM (SELECT a.n+10*b.n+100*c.n AS n " + "FROM d a CROSS JOIN d b CROSS JOIN d c) v WHERE n < 137 ORDER BY n", + (value,) * 8, + ) + first = cursor.fetchmany(batch_size) + assert len(first) == batch_size + tail = cursor.fetchall() + assert [tuple(row) for row in first + tail] == [(n,) + (value,) * 8 for n in range(137)] + assert cursor.fetchall() == [] + cursor.execute("SELECT N'reused'") + assert cursor.fetchone()[0] == "reused" + assert len(retained) == 137 * 8 + 1 + assert all(raw == value.encode("utf-16le") for raw in retained[:-1]) + finally: + db_connection.remove_output_converter(str) + + +@pytest.mark.parametrize("dense_first", [False, True]) +@pytest.mark.parametrize("batch_size", [None, 7, 9, 65], ids=["all", "many7", "many9", "many65"]) +def test_reusable_rowsets_preserve_density_transitions(db_connection, dense_first, batch_size): + full = "x" * 3998 + "\U0001f642" + expression = ( + f"CAST(CASE WHEN {'n < 16' if dense_first else 'n >= 16'} THEN ? " + "WHEN n % 4 = 0 THEN NULL WHEN n % 4 = 1 THEN N'' " + "WHEN n % 4 = 2 THEN N'A' + NCHAR(0) + N'B' " + "ELSE CAST(0x3DD842DE AS nvarchar(2)) END AS nvarchar(4000))" + ) + sql = ( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)), " + "numbers AS (SELECT a.n + 10*b.n + 100*c.n AS n " + "FROM d a CROSS JOIN d b CROSS JOIN d c) " + f"SELECT n, {', '.join([expression] * 8)} FROM numbers WHERE n < 137 ORDER BY n" + ) + with db_connection.cursor() as cursor: + cursor.execute(sql, (full,) * 8) + if batch_size is None: + rows = cursor.fetchall() + else: + rows = [] + while batch := cursor.fetchmany(batch_size): + assert len(batch) <= batch_size + rows.extend(batch) + expected = [] + for n in range(137): + dense = n < 16 if dense_first else n >= 16 + value = full if dense else (None, "", "A\0B", "\U0001f642")[n % 4] + expected.append((n,) + (value,) * 8) + assert [tuple(row) for row in rows] == expected + assert cursor.fetchmany(9) == [] + assert cursor.fetchone() is None + + @pytest.fixture(scope="module") def utf8_collation(db_connection): with db_connection.cursor() as cursor: @@ -27,6 +109,51 @@ def utf8_collation(db_connection): return row[0] +def test_reusable_rowset_mixed_native_types_and_nulls(db_connection): + from datetime import date, datetime, time + from decimal import Decimal + from uuid import UUID + + columns = [ + ("N'wide'", "nvarchar(4000)", "wide"), + ("1", "int", 1), + ("2", "smallint", 2), + ("3", "bigint", 3), + ("4", "tinyint", 4), + ("1", "bit", True), + ("1.5", "real", 1.5), + ("2.5", "float", 2.5), + ("12.50", "decimal(10,2)", Decimal("12.50")), + ("0x0001", "varbinary(2)", b"\0\x01"), + ("'2026-01-02'", "date", date(2026, 1, 2)), + ("'03:04:05.123456'", "time(6)", time(3, 4, 5, 123456)), + ( + "'2026-01-02T03:04:05.123456'", + "datetime2(6)", + datetime(2026, 1, 2, 3, 4, 5, 123456), + ), + ( + "'2026-01-02T03:04:05.123456+05:30'", + "datetimeoffset(6)", + datetime.fromisoformat("2026-01-02T03:04:05.123456+05:30"), + ), + ( + "'00112233-4455-6677-8899-aabbccddeeff'", + "uniqueidentifier", + UUID("00112233-4455-6677-8899-aabbccddeeff"), + ), + ] + expressions = [ + f"CAST(CASE WHEN n = 0 THEN {literal} END AS {sqltype})" for literal, sqltype, _ in columns + ] + with db_connection.cursor() as cursor: + cursor.execute(f"SELECT {', '.join(expressions)} FROM (VALUES (0),(1)) AS v(n) ORDER BY n") + assert [tuple(row) for row in cursor.fetchall()] == [ + tuple(value for _, _, value in columns), + (None,) * len(columns), + ] + + def _fetch_rows(cursor, method): if method == "fetchall": rows = cursor.fetchall() @@ -219,9 +346,10 @@ def test_bounded_nvarchar_strict_decode_error(db_connection, raw, method, forced ], ids=["explicit-cold", "explicit-warm", "default-cold", "default-warm", "batch", "all"], ) -def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, warmed): +@pytest.mark.parametrize("width", [64, 4000]) +def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, warmed, width): """Preserve the existing platform-specific batch behavior for unpaired surrogates.""" - expression = f"CAST(0x{raw} AS nvarchar(64))" + expression = f"CAST(0x{raw} AS nvarchar({width}))" raw_bytes = bytes.fromhex(raw) with db_connection.cursor() as cursor: cursor.execute(f"SELECT DATALENGTH({expression}), CAST({expression} AS varbinary(64))") @@ -261,3 +389,89 @@ def test_bounded_nvarchar_batch_malformed_fallback(db_connection, raw, method, w assert cursor.fetchone() is None cursor.execute("SELECT CAST(N'recovered' AS nvarchar(64))") assert cursor.fetchone()[0] == "recovered" + + +@pytest.mark.parametrize("method", ["fetchall", "fetchmany", "interleave"]) +@pytest.mark.parametrize("converted", [False, True]) +def test_wide_bounded_text_actual_lengths(db_connection, method, converted): + payloads = [None, "", "\ufeffA\0B\ufffe", "A\U0001f642Z", "x" * 3998 + "\U0001f642"] + cases = " ".join( + f"WHEN {i} THEN " + + ( + "NULL" + if value is None + else f"CAST(0x{value.encode('utf-16le').hex()} AS nvarchar(4000))" + ) + for i, value in enumerate(payloads) + ) + observed = [] + if converted: + db_connection.add_output_converter( + str, lambda raw: observed.append(raw) or raw.decode("utf-16le") + "!" + ) + db_connection.add_output_converter(int, lambda value: value + 10000) + try: + with db_connection.cursor() as cursor: + cursor.execute( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) AS v(n)) " + f"SELECT n, CAST(CASE n % 5 {cases} END AS nvarchar(4000)), " + "CAST(NCHAR(233) COLLATE Latin1_General_100_BIN2 AS varchar(8000)), " + "CAST(0x0001FF AS varbinary(8)), CAST(n AS decimal(10,2)) " + "FROM (SELECT a.n+10*b.n+100*c.n AS n FROM d a CROSS JOIN d b CROSS JOIN d c) v " + "WHERE n < 207 ORDER BY n" + ) + actual = [] + if method == "interleave": + actual.append(cursor.fetchone()) + if method == "fetchall": + actual.extend(cursor.fetchall()) + else: + while batch := cursor.fetchmany(7): + actual.extend(batch) + assert [(row[0], row[1], row[2], row[3], int(row[4])) for row in actual] == [ + ( + n + (10000 if converted else 0), + ( + None + if payloads[n % 5] is None + else payloads[n % 5] + ("!" if converted else "") + ), + "\u00e9" + ("!" if converted else ""), + b"\0\x01\xff", + n, + ) + for n in range(207) + ] + assert cursor.fetchone() is None + assert cursor.fetchall() == [] + if converted: + assert observed == [ + value.encode("utf-16le") + for n in range(207) + for value in (payloads[n % 5], "\u00e9") + if value is not None + ] + finally: + if converted: + db_connection.remove_output_converter(str) + db_connection.remove_output_converter(int) + + +@pytest.mark.parametrize("method", ["fetchall", "fetchmany"]) +@pytest.mark.parametrize("sqltype", ["nvarchar(4000)", "varchar(8000)"]) +@pytest.mark.parametrize("offset", [253, 254, 255, 256, 511]) +def test_wide_text_continuation_boundaries(db_connection, utf8_collation, method, sqltype, offset): + payload = "a" * offset + "\U0001f642" + "\0" + "\u00e9\u20ac" + "z" * 550 + expected = ["before", payload, "after"] + values = ", ".join( + f"({i}, CAST(CAST(0x{value.encode('utf-16le').hex()} AS nvarchar(4000)) " + f"COLLATE {utf8_collation} AS {sqltype}))" + for i, value in enumerate(expected) + ) + with db_connection.cursor() as cursor: + cursor.execute(f"SELECT n, payload FROM (VALUES {values}) v(n, payload) ORDER BY n") + rows = cursor.fetchall() if method == "fetchall" else cursor.fetchmany(3) + assert [tuple(row) for row in rows] == list(enumerate(expected)) + assert cursor.messages == [] + assert cursor.fetchone() is None diff --git a/tests/test_017_fetch_buffer_sizing.py b/tests/test_017_fetch_buffer_sizing.py index c20285439..2a104d058 100644 --- a/tests/test_017_fetch_buffer_sizing.py +++ b/tests/test_017_fetch_buffer_sizing.py @@ -23,6 +23,7 @@ "SQLDescribeCol_ptr", "SQLFreeHandle_ptr", "SQLFetch_ptr", + "SQLGetData_ptr", ) _RETAINED_CASES = ( @@ -76,6 +77,23 @@ def test_checked_fetch_buffer_preconditions(item_size, terminator): "parent-cleanup-failure", "repeat-cleanup", "lob", + "compact-wide", + "compact-large", + "compact-boundary", + "compact-partial", + "compact-medium", + "compact-small-dense", + "compact-warning", + "compact-dense-rebind-failure", + "compact-no-total", + "compact-invalid-length", + "compact-truncated", + "compact-invalid-scalar", + "compact-fetch-error", + "compact-odd-wide-length", + "compact-zero-rows", + "compact-excess-rows", + "compact-dense-truncated", ], ) def test_fetchall_buffer_contract(conn_str, case): @@ -124,9 +142,13 @@ def _run_case(case): bindings = [] rowsets = [] fetches = [] + bound_cells = {} + text_reads = [] + length_probes = [] events = [] current_size = 1 statement = None + fetched_pointer = None lifetime = None persistent = case in _RETAINED_CASES sql_len = ct.c_ssize_t @@ -135,8 +157,21 @@ def _run_case(case): count = {"empty": 0, "small": 3, "initial-boundary": 100}.get(case, 1207) if case == "oversized-row": count = 2 - if case in ("overflow-cell", "overflow-row", "lob"): + if case in ("overflow-cell", "overflow-row", "lob") or case.startswith("compact-"): count = 3 + if case in ( + "compact-wide", + "compact-medium", + "compact-dense-truncated", + "compact-dense-rebind-failure", + ): + count = 1207 + if case == "compact-small-dense": + count = 1 + if case == "compact-large": + count = 5000 + if case in ("compact-boundary", "compact-partial"): + count = 8 if case == "compact-boundary" else 7 def install(name, args, handler): pointer = pointers[name] @@ -151,11 +186,17 @@ def bind(original, handle, col, ctype, data, length, indicator): nonlocal statement statement = handle bindings.append((col, ctype, length)) + bound_cells[col] = (length, indicator, data) events.append("bind") if case == "bind-failure" and fetches: return -2 if ( - case in ("partial-bind-failure", "partial-bind-cleanup-failure") + case + in ( + "partial-bind-failure", + "partial-bind-cleanup-failure", + "compact-dense-rebind-failure", + ) and fetches and col == 2 ): @@ -163,7 +204,9 @@ def bind(original, handle, col, ctype, data, length, indicator): return original(handle, col, ctype, data, length, indicator) def attr(original, handle, attribute, value, length): - nonlocal current_size + nonlocal current_size, fetched_pointer + if attribute == 26 and value: + fetched_pointer = value if ( case in ("persistent-rows-fetched-failure", "arrow-cleanup-failure") and attribute == 26 @@ -205,12 +248,41 @@ def free_handle(original, kind, handle): def fetch(original, handle, orientation, offset): fetches.append(current_size) events.append("fetch") - return original(handle, orientation, offset) + result = original(handle, orientation, offset) + if result in (0, 1): + if case == "compact-warning" and len(fetches) == 1: + return 1 # Valid bound values with SQL_SUCCESS_WITH_INFO. + if case in ("compact-zero-rows", "compact-excess-rows"): + output_count = ct.cast(fetched_pointer, ct.POINTER(sql_ulen)) + output_count[0] = 0 if case == "compact-zero-rows" else current_size + 1 + if case == "compact-fetch-error": + return -2 + column = 1 if case == "compact-invalid-scalar" else 2 + capacity, indicator, _ = bound_cells[column] + output_length = ct.cast(indicator, ct.POINTER(sql_len)) + if case == "compact-no-total": + output_length[0] = -4 + elif case in ("compact-invalid-length", "compact-invalid-scalar"): + output_length[0] = -99 + elif case == "compact-truncated": + output_length[0] = capacity + 2 + elif case == "compact-odd-wide-length": + output_length[0] = 1 + elif case == "compact-dense-truncated" and len(fetches) > 1: + output_length[0] = capacity + 2 + return result def arrow_fetch(original, handle): fetches.append(current_size) return original(handle) + def getdata(original, handle, col, ctype, data, length, indicator): + if ctype == -2 and length == 0: + length_probes.append(col) + if ctype in (1, -8) and length: + text_reads.append((ctype, data, length)) + return original(handle, col, ctype, data, length, indicator) + def describe(original, handle, col, name, capacity, actual, dtype, size, scale, nullable): result = original(handle, col, name, capacity, actual, dtype, size, scale, nullable) if result in (0, 1) and case == "zero-width" and col == 2: @@ -231,7 +303,7 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, connection.setdecoding(ms.SQL_CHAR, encoding="cp1252", ctype=ms.SQL_CHAR) columns = ["CAST('x' AS varchar(32))"] expected = ["x"] - if case in ("wide", "narrow"): + if case in ("wide", "narrow", "compact-dense-truncated", "compact-dense-rebind-failure"): columns = [ "CAST(REPLICATE(CAST(NCHAR(233) AS nvarchar(max)), 8000) " "COLLATE Latin1_General_100_BIN2 AS varchar(8000))" @@ -271,6 +343,17 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, elif case == "lob": columns += ["CAST(REPLICATE(CAST(N'y' AS nvarchar(max)), 12000) AS nvarchar(max))"] expected += ["y" * 12000] + elif case in ("compact-wide", "compact-large", "compact-boundary", "compact-partial"): + columns = ["CAST('x' AS varchar(8000))"] * 8 + expected = ["x"] * 8 + elif case == "compact-medium": + columns = ["CAST('x' AS varchar(257))"] * 8 + expected = ["x"] * 8 + elif case == "compact-small-dense": + columns = ["CAST(REPLICATE(N'x', 4000) AS nvarchar(4000))"] + expected = ["x" * 4000] + elif case.startswith("compact-"): + columns = ["CAST('x' AS varchar(8000))"] sql = ( "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," "(5),(6),(7),(8),(9)) AS v(n)) " @@ -296,6 +379,11 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, if case == "arrow-cleanup-failure": install("SQLFetch_ptr", [ct.c_void_p], arrow_fetch) install("SQLFetchScroll_ptr", [ct.c_void_p, ct.c_short, sql_len], fetch) + install( + "SQLGetData_ptr", + [ct.c_void_p, ct.c_ushort, ct.c_short, ct.c_void_p, sql_len, ct.c_void_p], + getdata, + ) install( "SQLDescribeCol_ptr", [ @@ -321,11 +409,38 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, cursor.fetchall() assert not bindings assert not fetches + elif case in ( + "compact-no-total", + "compact-invalid-length", + "compact-truncated", + "compact-invalid-scalar", + "compact-odd-wide-length", + "compact-dense-truncated", + ): + with pytest.raises(RuntimeError, match="Invalid bounded fetch length"): + cursor.fetchall() + if case == "compact-dense-truncated": + assert fetches == rowsets[:2] + else: + assert fetches == [rowsets[0]] + elif case in ("compact-zero-rows", "compact-excess-rows"): + with pytest.raises(RuntimeError, match="Invalid bounded fetch row count"): + cursor.fetchall() + assert fetches == [rowsets[0]] + elif case == "compact-fetch-error": + with pytest.raises(ms.Error): + cursor.fetchall() + assert fetches == [rowsets[0]] elif case.endswith("-failure"): error = ( RuntimeError if case - in ("bind-failure", "partial-bind-failure", "partial-bind-cleanup-failure") + in ( + "bind-failure", + "partial-bind-failure", + "partial-bind-cleanup-failure", + "compact-dense-rebind-failure", + ) else ms.Error ) with pytest.raises(error) as failure: @@ -339,6 +454,9 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert "Failed to bind column" in str(failure.value) if case == "arrow-cleanup-failure": assert fetches == [64] + elif case == "compact-dense-rebind-failure": + assert fetches == [rowsets[0]] + assert bindings[len(columns) + 2][0] == 2 elif case not in ("persistent-rows-fetched-failure", "rowset-reset-failure"): assert fetches == [100] if case in ("partial-bind-failure", "partial-bind-cleanup-failure"): @@ -375,7 +493,74 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert tuple(sibling.fetchone()) == (42,) return - if not case.startswith("overflow-") and case != "lob" and not case.endswith("-failure"): + if case in ( + "compact-wide", + "compact-large", + "compact-boundary", + "compact-partial", + "compact-medium", + "compact-small-dense", + "compact-warning", + "wide", + "narrow", + "unicode", + "mixed", + "oversized-row", + ): + assert not text_reads and not length_probes + ncols = len(columns) + 1 + first = bindings[:ncols] + if case in ("wide", "narrow", "unicode", "compact-wide", "compact-medium"): + assert first[0] == (1, -16, 4) # SQL_C_SLONG + if case == "narrow": + ctype = 1 # SQL_C_CHAR + capacity = 8001 if sys.platform == "win32" else 32001 + else: + ctype = -8 # SQL_C_WCHAR + declared_width = { + "unicode": 4000, + "compact-medium": 257, + }.get(case, 8000) + capacity = (declared_width + 1) * 2 + assert first[1:] == [(col, ctype, capacity) for col in range(2, ncols + 1)] + row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) + initial = max(1, min(100, 1024 * 1024 // row_bytes)) + assert rowsets[0] == initial + assert initial * row_bytes <= 1024 * 1024 or initial == 1 + target = max(1, min(1000, budget // row_bytes)) + expected_fetches = [] + expected_bindings = [initial] + remaining = count + size = initial + while True: + expected_fetches.append(size) + fetched = min(remaining, size) + remaining -= fetched + if not fetched: + break + if fetched == size and size < target: + size = target + expected_bindings.append(size) + expected_fetches.append(initial) # Exhausted second fetchall. + assert fetches == expected_fetches + assert len(bindings) == (len(expected_bindings) + 1) * ncols + for index in range(len(expected_bindings) + 1): + assert bindings[index * ncols : (index + 1) * ncols] == first + if len(expected_bindings) > 1: + assert rowsets[: len(expected_bindings)] == expected_bindings + first_fetch = events.index("fetch") + second_bind = events.index("bind", first_fetch + 1) + assert "unbind" in events[first_fetch + 1 : second_bind] + if case == "compact-large": + # Ordinary 8 MiB batching needs 78 calls for this shape. + # Small startup adds one, not the previous 548 extra calls. + assert len(fetches) - 1 == 79 + assert all(size * row_bytes <= budget or size == 1 for size in fetches) + elif ( + not case.startswith(("overflow-", "compact-")) + and case != "lob" + and not case.endswith("-failure") + ): ncols = len(columns) + 1 first = bindings[:ncols] row_bytes = sum(length + ct.sizeof(sql_len) for _, _, length in first) @@ -396,13 +581,6 @@ def describe(original, handle, col, name, capacity, actual, dtype, size, scale, assert fetches[:batches] == [initial] + [subsequent] * (batches - 1) assert len(fetches) == batches + 1 assert target * row_bytes <= budget or target == 1 - if case == "wide": - assert first[1][1:] == (-8, 16002) # SQL_C_WCHAR, including terminator. - elif case == "narrow": - width = 32001 if sys.platform != "win32" else 8001 - assert first[1][1:] == (1, width) - elif case == "oversized-row": - assert row_bytes > budget and initial == target == 1 elif case == "lob": assert not bindings and not fetches cursor.execute("SELECT 42") diff --git a/tests/test_025_profiler.py b/tests/test_025_profiler.py index 1db0ebce1..a6c7d33ab 100644 --- a/tests/test_025_profiler.py +++ b/tests/test_025_profiler.py @@ -394,6 +394,36 @@ def test_cpp_profiling_captures_query(): assert sample["calls"] >= 1 +@_needs_cpp +@_needs_db +@pytest.mark.parametrize("fetch_size", [None, 129], ids=["fetchall", "fetchmany"]) +@pytest.mark.parametrize("dense", [False, True]) +def test_reusable_fetch_prepares_conversion_once_per_call(db_connection, fetch_size, dense): + value = "x" * 3998 + "\U0001f642" if dense else "short" + sql = ( + "WITH d(n) AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4)," + "(5),(6),(7),(8),(9)) v(n)) " + "SELECT n, " + + ", ".join(["CAST(? AS NVARCHAR(4000))"] * 8) + + " FROM (SELECT a.n+10*b.n+100*c.n AS n FROM d a CROSS JOIN d b CROSS JOIN d c) v " + "WHERE n < 137 ORDER BY n" + ) + with db_connection.cursor() as cursor: + for expected in (value, "different"): + cursor.execute(sql, (expected,) * 8) + ddbc.profiling.reset() + ddbc.profiling.enable() + try: + rows = cursor.fetchall() if fetch_size is None else cursor.fetchmany(fetch_size) + finally: + ddbc.profiling.disable() + stats = ddbc.profiling.get_stats() + count = 137 if fetch_size is None else fetch_size + assert [tuple(row) for row in rows] == [(n,) + (expected,) * 8 for n in range(count)] + assert stats["ddbc::FetchBatchData::SQLFetchScroll_call"]["calls"] > 1 + assert stats["ddbc::FetchBatchData::cache_column_metadata"]["calls"] == 1 + + @_needs_cpp @_needs_db def test_cpp_timeline_captures_events(): diff --git a/tests/test_pr_code_coverage_workflow.py b/tests/test_pr_code_coverage_workflow.py index 9f116b6db..eaf9e881c 100644 --- a/tests/test_pr_code_coverage_workflow.py +++ b/tests/test_pr_code_coverage_workflow.py @@ -26,6 +26,42 @@ } +def test_python_lcov_function_docstrings_render(tmp_path): + if not shutil.which("genhtml"): + pytest.skip("requires genhtml") + source = tmp_path / "example.py" + source.write_text( + 'def covered():\n """Covered function."""\n return 42\n\n' + 'def uncovered():\n """Uncovered function."""\n return 0\n\ncovered()\n', + encoding="utf-8", + ) + for args in ( + ["coverage", "run", "--rcfile=/dev/null", str(source)], + ["coverage", "lcov", "--rcfile=/dev/null", "-o", "python.info"], + ): + subprocess.run([sys.executable, "-m", *args], cwd=tmp_path, check=True, capture_output=True) + report = (tmp_path / "python.info").read_text(encoding="utf-8") + for record in ("LF:5", "LH:4", "FNF:2", "FNH:1"): + assert record in report.splitlines() + normalizer = WORKFLOW.parents[2] / "eng" / "scripts" / "normalize_python_lcov.py" + subprocess.run( + [sys.executable, str(normalizer), str(tmp_path / "python.info")], + check=True, + capture_output=True, + ) + normalized = (tmp_path / "python.info").read_text(encoding="utf-8") + assert [line for line in report.splitlines() if not line.startswith("FN:")] == [ + line for line in normalized.splitlines() if not line.startswith("FN:") + ] + subprocess.run( + ["genhtml", "python.info", "--output-directory", "html", "--quiet"], + cwd=tmp_path, + check=True, + capture_output=True, + ) + assert (tmp_path / "html" / "index.html").is_file() + + def _build(build_id=174262, sha=SHA, pr="779", branch="refs/pull/779/merge", definition=2128): return { "id": build_id, diff --git a/tests/test_python_lcov.py b/tests/test_python_lcov.py new file mode 100644 index 000000000..b3c10d249 --- /dev/null +++ b/tests/test_python_lcov.py @@ -0,0 +1,31 @@ +"""LCOV function-location compatibility without altering measured coverage.""" + +import pytest + +from eng.scripts.normalize_python_lcov import normalize_function_starts + + +def test_docstring_function_starts_use_executable_lines(): + report = ( + "SF:example.py\nDA:1,1\nDA:3,1\nDA:5,1\nDA:7,0\n" + "FN:2,3,covered\nFNDA:1,covered\nFN:6,7,uncovered\nFNDA:0,uncovered\n" + "FNF:2\nFNH:1\nLF:4\nLH:3\nend_of_record\n" + "SF:other.py\nDA:10,1\nFN:10,10,other\nFNDA:1,other\nend_of_record\n" + ) + normalized = normalize_function_starts(report) + assert "FN:3,3,covered\n" in normalized + assert "FN:7,7,uncovered\n" in normalized + assert "FN:10,10,other\n" in normalized + assert [line for line in report.splitlines() if not line.startswith("FN:")] == [ + line for line in normalized.splitlines() if not line.startswith("FN:") + ] + assert normalize_function_starts(normalized) == normalized + + +@pytest.mark.parametrize( + "report", + ["SF:example.py\nDA:1,1\n", "SF:example.py\nDA:1,1\nFN:2,3,missing\nend_of_record\n"], +) +def test_invalid_function_reports_fail_explicitly(report): + with pytest.raises(ValueError): + normalize_function_starts(report) diff --git a/tests/test_query_cancellation.py b/tests/test_query_cancellation.py index f9b72455c..902584f4f 100644 --- a/tests/test_query_cancellation.py +++ b/tests/test_query_cancellation.py @@ -142,13 +142,16 @@ def observe(frame, event, argument): @pytest.mark.parametrize("method", ["fetchone", "fetchmany", "fetchall"]) -def test_grouped_scalar_reads_preserve_mixed_values_and_chunk_boundaries(method): +@pytest.mark.parametrize("text_width", [10, 4000]) +def test_grouped_scalar_reads_preserve_mixed_values_and_chunk_boundaries(method, text_width): scalar_types = ("int", "smallint", "bigint", "real", "float") columns = [ f"CAST({index if index % 3 else 'NULL'} AS {scalar_types[index % 5]})" for index in range(20) ] - columns.extend(("CAST('text' AS nvarchar(10))", "CAST(-9 AS int)", "CAST(NULL AS bigint)")) + columns.extend( + (f"CAST('text' AS nvarchar({text_width}))", "CAST(-9 AS int)", "CAST(NULL AS bigint)") + ) expected = tuple(None if index % 3 == 0 else index for index in range(20)) + ( "text", -9, @@ -423,12 +426,13 @@ def test_native_cancellation_recovery_allocation_failure_retires_connection(): _run("_native_recovery_allocation_probe") -def test_grouped_scalar_cancel_prevents_later_column_calls(): +@pytest.mark.parametrize("kind", ["scalar", "text"]) +def test_grouped_scalar_cancel_prevents_later_column_calls(kind): _pointers() - _run("_grouped_scalar_boundary_probe") + _run("_grouped_scalar_boundary_probe", kind) -def _grouped_scalar_boundary_probe(): +def _grouped_scalar_boundary_probe(kind="scalar"): pointers = _pointers() callback = ctypes.WINFUNCTYPE if os.name == "nt" else ctypes.CFUNCTYPE getdata_type = callback( @@ -441,12 +445,16 @@ def _grouped_scalar_boundary_probe(): ctypes.c_void_p, ) cancel_type = callback(ctypes.c_short, ctypes.c_void_p) + fetch_type = callback(ctypes.c_short, ctypes.c_void_p, ctypes.c_short, ctypes.c_ssize_t) with _connection() as connection, connection.cursor() as cursor: - cursor.execute("SELECT 1, 2, 3, 4 FROM (VALUES (1), (2)) AS source(n)") - assert tuple(cursor.fetchone()) == (1, 2, 3, 4) + value = "CAST(N'text' AS nvarchar(4000))" if kind == "text" else "2" + cursor.execute(f"SELECT 1, {value}, 3, 4 FROM (VALUES (1), (2)) AS source(n)") + assert tuple(cursor.fetchone()) == (1, "text" if kind == "text" else 2, 3, 4) original_getdata = pointers["SQLGetData_ptr"].value + original_fetch = pointers["SQLFetchScroll_ptr"].value original_cancel = pointers["SQLCancel_ptr"].value getdata = getdata_type(original_getdata) + fetch = fetch_type(original_fetch) reads = [] @getdata_type @@ -457,6 +465,13 @@ def cancel_after_second_column(*args): cursor.cancel() return result + @fetch_type + def cancel_after_first_row(handle, orientation, offset): + reads.append("block") + result = fetch(handle, orientation, offset) + cursor.cancel() + return result + @cancel_type def cancel(_): return 0 @@ -465,21 +480,33 @@ def cancel(_): if profiling is not None: profiling.reset() profiling.enable() - pointers["SQLGetData_ptr"].value = ctypes.cast( - cancel_after_second_column, ctypes.c_void_p - ).value + if kind == "text": + pointers["SQLFetchScroll_ptr"].value = ctypes.cast( + cancel_after_first_row, ctypes.c_void_p + ).value + else: + pointers["SQLGetData_ptr"].value = ctypes.cast( + cancel_after_second_column, ctypes.c_void_p + ).value pointers["SQLCancel_ptr"].value = ctypes.cast(cancel, ctypes.c_void_p).value try: with pytest.raises(OperationalError, match="Operation canceled"): - cursor.fetchone() + if kind == "text": + cursor.fetchall() + else: + cursor.fetchone() finally: pointers["SQLGetData_ptr"].value = original_getdata + pointers["SQLFetchScroll_ptr"].value = original_fetch pointers["SQLCancel_ptr"].value = original_cancel if profiling is not None: profiling.disable() - assert reads == [1, 2] + assert reads == (["block"] if kind == "text" else [1, 2]) if profiling is not None: - assert profiling.get_stats()["ddbc::SQLGetData::scalar_group"]["calls"] == 1 + if kind == "scalar": + assert profiling.get_stats()["ddbc::SQLGetData::scalar_group"]["calls"] == 1 + else: + assert profiling.get_stats()["ddbc::FetchReusableTextRows"]["calls"] == 1 assert cursor._query_slot.active is None assert not connection._query_state.busy assert cursor.execute("SELECT 99").fetchone()[0] == 99