Skip to content

FEAT: Add native JSON support for synchronous Python APIs - #916

Merged
Jahnvi Thakkar (jahnvi480) merged 15 commits into
mainfrom
jahnvi/json-native-implementation
Nov 26, 2026
Merged

Jahnvi Thakkar (jahnvi480) merged 15 commits into
mainfrom
jahnvi/json-native-implementation

Conversation

@jahnvi480

@jahnvi480 Jahnvi Thakkar (jahnvi480) commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Work Item / Issue Reference

Not applicable; linked GitHub issue below.

GitHub Issue: #261


Summary

Add native JSON support to the synchronous Python API with an explicitly qualified JSON-capable classic ODBC preview. Ready for review; this does not claim verification of the original Fabric environment or production readiness of preview binaries.

Latest correction: 3f8b245c2cc2f4e3d83ed54fd17d9cb9a25d86fd removes this PR's LOB error-translation changes, their dedicated regression tests, and associated documentation claims, as requested. LOB error handling and cancellation behavior now match main. Some LOB failures therefore raise RuntimeError without SQLSTATE/native diagnostic metadata. JSON-specific HY004 binding diagnostics remain intact. The cancellation tests from main were not changed to accommodate the PR.

  • Add immutable Json(dict | list | str) inputs. Dict/list values are strictly validated and serialized once. Strings are already-serialized JSON text, retained without Python parsing or rewriting; invalid syntax/scalar roots fail during execution. Strict Unicode validation remains enforced.
  • Expose synchronous SQL_JSON / SQL_SS_JSON = -157; bind through SQL_C_WCHAR with execute/executemany, typed NULLs, large parameters and complete LOB retrieval.
  • Keep text as the default. Cursor-only json_output='objects' captures the mode for an execution, including buffered callproc results and nextset. Decode only native JSON metadata, once per non-NULL value, preserving independent cells and converter precedence (including str/WVARCHAR fallbacks). Ordinary character columns stay text; description type remains str.
  • Preserve normal unwrapped sequences/mappings. Reject bare strings hinted as JSON and mixed Json/bare-value batch columns. Keep provider-first dispatch and normal-CI numeric inference-count and mocked bulk-copy regressions.
  • Add column context to JSON DataError without payloads. Cover procedure decoding, converter snapshots, later Unicode read boundaries, unhinted NULLs and shipped-driver JSON-as-VARCHAR retrieval. Native JSON binding rejected with HY004 retains its NotSupportedError translation and native diagnostic metadata.
  • Keep README JSON guidance and CHANGELOG entries; the separate preview guide remains removed. Document numeric decoding loss, constructor/LOB costs, whole-batch streaming for oversized outliers, and provider/catalog/cache qualification limits.
  • Preserve main's merged cancellation and Rust runtime compatibility behavior; this PR does not introduce async JSON execution.

Validation of the LOB removal: native Windows Release bindings rebuilt with the same cancellation fault-injection controls enabled in CI. Tests ran against isolated owned SQL Server instances; shipped binaries and dependency pins remain unchanged.

Check Exact command Result
Windows native build mssql_python\pybind\build.bat x64 with MSSQL_ARROW_TEST_INTERPOSITION=1 and development interpreter/library environment Passed
Shipped-driver cancellation and JSON binding rejection python -m pytest tests/test_query_cancellation.py tests/test_json.py::test_json_unsupported_bind_preserves_diagnostics_and_cursor_reuse -q -ra --tb=short with MSSQL_ARROW_TEST_INTERPOSITION=1 and native JSON preview opt-in unset 121 passed, no skips; includes the previously failing lob-unavailable completion-fence case
Preview JSON regression suite python -m pytest tests\test_json.py -q --tb=short -ra with MSSQL_TEST_NATIVE_JSON=1 263 passed, 8 expected shipped-driver-only skips
Pinned formatting python -m pre_commit run black-check --all-files --hook-stage pre-push Passed, including push hook
Patch hygiene git diff --check Passed

These runs used Windows x64/Python 3.13.17. Cancellation/rejection checks used shipped ODBC 18.06.0002 on SQL Server 2022 16.0.4225.2; JSON success checks used preview ODBC 18.07.0001 on SQL Server 2025 17.0.5005.3. New hosted CI is pending, not claimed green.

Earlier qualification: before the LOB removal, JSON/native-fetch/cancellation/cursor merge checks passed 1,179 cases with 90 skips, and strict source/stub typing passed 9 cases. The original local merge build skipped fault-control-only cancellation cases; the latest validation above explicitly enables those controls and runs them. Earlier Linux preview, shipped-driver and stable/nightly async qualification has not been repeated after this removal. Earlier claims that this PR improves LOB read/probe exception classification are withdrawn.

Performance and qualification limits: main/vector integration and provider-first dispatch are included. A prior same-integration Linux release A/B run measured a median paired 6.99% improvement in its setinputsizes workload, not a universal JSON speedup. Strict wrapper validation, per-row LOB reads, object parsing and whole-batch row-wise streaming for oversized outliers remain explicit costs; no speculative batch splitter or LOB-buffer redesign is included.

Shipped dependency pins/binaries are unchanged and no preview binaries are committed. Earlier previews omit JSON catalog rows without vector negotiation; the updated ODBC policy uses sp_*170 on SQL Server 2025+ regardless of vector negotiation. Catalog rows are not a Python capability gate. A bounded local mixed-client literal-query check did not reproduce reported cache interference, but does not disprove the reviewer's table/CU findings: preview/shipped CI should use separate servers, the capability probe recompiles, and application SQL is not rewritten/retried.

Rust/async, bulk, TVP and Arrow JSON implementation remains deferred. macOS preview execution, wider preview architectures, complete ASan/UBSan qualification and the Arrow release gate remain open. Local SQL Server does not support FLOAT16, so opt-in FLOAT16 qualification is not claimed. The whole repository suite was not rerun locally for this correction; being ready for review does not mean every release gate is complete.

Add explicit Json inputs, native JSON binding, execution-scoped object decoding, focused regressions, and preview-provider documentation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 10:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Oversized JSON-only batches bypass data-at-execution streaming and can exhaust memory through padded allocations, while unhinted columns also perform duplicate type inference.

2 open issues
What changed in this PR

Adds preview native JSON support to the synchronous Python API and ODBC bindings, addressing the scenario in #261 without claiming verification of the original Fabric environment. Shipped provider binaries and dependency pins remain unchanged.

Changes:

  • Adds immutable Json inputs, synchronous JSON constants, parameter binding, and large-value retrieval.
  • Adds execution-scoped object decoding while preserving text defaults, SQL NULLs, and custom converters.
  • Adds regression tests, public typing, preview setup guidance, and explicit unsupported-backend guards.
File Description
tests/​test_typing.py Checks public JSON API typing.
tests/​test_json.py Covers validation, binding, fetching, and backend boundaries.
tests/​test_004_cursor.py Initializes JSON mode in an existing cursor test.
README.md Documents JSON behavior and preview limitations.
mssql_python/​pybind/​py_type_cache.hpp Caches the Python Json type for native detection.
mssql_python/​pybind/​param_detect.hpp Detects JSON inputs, hints, and streaming requirements.
mssql_python/​pybind/​ddbc_bindings.h Defines the native JSON type code.
mssql_python/​pybind/​ddbc_bindings.cpp Adds JSON binding and streamed retrieval.
mssql_python/​mssql_python.pyi Exposes JSON APIs in public stubs.
mssql_python/​json.py Implements immutable inputs, decoding, and rejection helpers.
mssql_python/​cursor.py Integrates JSON execution, batching, and result conversion.
mssql_python/​constants.py Defines and exports synchronous JSON constants.
mssql_python/​async_query/​async_execute.py Rejects synchronous JSON wrappers in async execution.
mssql_python/​async_query/​async_cursor.py Rejects synchronous JSON input-size hints.
mssql_python/​_native_fetch.py Uses the conversion-aware fallback for JSON decoding.
mssql_python/​_ddbc_types.pyi Allows unset entries in native input-size hints.
mssql_python/​__init__.py Exports Json and JSON constants.
docs/​native-json-preview.md Describes isolated preview setup and qualification.

Review effort: Balanced

Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/cursor.py Resolved
Preserve lossless batch inference, TVP support, numeric buffer sizing and explicit text lengths alongside native JSON. Keep JSON NULL hints aligned with original columns during row-wise fallback and add focused mixed-column/numeric regressions.

Validation: Windows native build, 231 JSON tests, 1563 affected regression tests, and 7 typing tests passed. Linux Release build and 1719 affected tests passed. Pinned formatting passed; platform/fault-only skips remain.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 10:36
@github-actions github-actions Bot added the pr-size: large Substantial code update label Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Performance Report

✅ No regression detected

No consistent slowdowns detected across all 2 environments.

0 IMPROVEMENTS 0 SLOWDOWNS 2/2 ENVIRONMENTS

Coverage: 2 of 2 environments completed. Advisory result; does not block merging.

Performance diagnostics

Phase times are inclusive diagnostics and must not be added together. They identify where measured time changed, not why it changed.

No affected phases or call-count changes were recorded.

All database tasks and timings

Unix / SQL Server 2022

Database task Before After Paired change Result
Connection opening 10.450 ms 10.247 ms -1.4% no signal
SELECT queries 1.259 ms 1.252 ms -1.3% no signal
Row insertion 32.615 ms 32.462 ms -1.1% no signal
Executemany inserts 166.139 ms 162.369 ms -4.0% no signal
Fetch-all queries 123.022 ms 121.735 ms -1.7% no signal
Row-by-row fetching 5.974 ms 5.977 ms +0.9% no signal
Batched row fetching 117.806 ms 118.554 ms +0.7% no signal
Transaction commit and rollback 109.518 ms 109.839 ms +0.7% no signal
Arrow row fetching 89.605 ms 91.763 ms +4.3% no signal
100,000-row insertion 371.829 ms 366.613 ms -2.6% no signal
Row fetching in batches of 100 127.546 ms 125.450 ms +0.4% no signal
Row fetching in batches of 10,000 127.878 ms 144.403 ms +13.3% no signal
Repeated positional queries 34.464 ms 33.996 ms +1.2% no signal
Repeated named-parameter queries 33.678 ms 34.487 ms +1.0% no signal
Legacy 100,000-row insertion 272.301 ms 280.384 ms +3.0% no signal
Insertion with explicit input sizes 429.049 ms 428.024 ms +2.1% no signal
Joined aggregation queries 197.906 ms 179.927 ms -9.6% no signal
Large joined-result fetching 193.654 ms 190.027 ms -2.2% no signal
1.2-million-row fetching 3519.286 ms 3483.130 ms -0.6% no signal
Common table expression queries 5.704 ms 5.483 ms -6.0% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.357 ms 1.006 ms -21.9% no signal
10,000 scalar values / fetchval() (debug disabled) 19.213 ms 19.094 ms -0.6% no signal
10,000 output-converted rows / fetchall() 19.019 ms 19.511 ms +1.4% no signal
10,000 output-converted rows / fetchmany(1000) 23.949 ms 23.999 ms -0.8% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 28.044 ms 27.392 ms -1.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 34.911 ms 31.907 ms -8.2% no signal

Unix / SQL Server 2025

Database task Before After Paired change Result
Connection opening 80.990 ms 81.555 ms +0.7% no signal
SELECT queries 1.266 ms 1.382 ms +8.2% no signal
Row insertion 31.864 ms 31.874 ms -0.2% no signal
Executemany inserts 148.665 ms 152.102 ms +4.0% no signal
Fetch-all queries 117.973 ms 119.410 ms +0.8% no signal
Row-by-row fetching 5.946 ms 5.931 ms -0.3% no signal
Batched row fetching 116.864 ms 117.706 ms +0.3% no signal
Transaction commit and rollback 109.397 ms 109.572 ms -0.0% no signal
Arrow row fetching 89.155 ms 89.780 ms +0.5% no signal
100,000-row insertion 370.191 ms 364.986 ms +0.2% no signal
Row fetching in batches of 100 123.912 ms 125.496 ms +0.5% no signal
Row fetching in batches of 10,000 122.083 ms 133.797 ms +4.8% no signal
Repeated positional queries 33.155 ms 33.506 ms +1.0% no signal
Repeated named-parameter queries 33.654 ms 33.771 ms +1.2% no signal
Legacy 100,000-row insertion 276.789 ms 274.639 ms +0.4% no signal
Insertion with explicit input sizes 426.645 ms 434.202 ms +1.8% no signal
Joined aggregation queries 164.616 ms 166.852 ms +0.9% no signal
Large joined-result fetching 185.139 ms 185.361 ms +0.1% no signal
1.2-million-row fetching 3485.409 ms 3454.750 ms -0.9% no signal
Common table expression queries 5.341 ms 5.290 ms -1.6% no signal
256 KiB VARCHAR(MAX) / fetchall() 1.739 ms 1.692 ms -2.6% no signal
10,000 scalar values / fetchval() (debug disabled) 18.741 ms 18.856 ms +0.7% no signal
10,000 output-converted rows / fetchall() 19.394 ms 19.029 ms -0.5% no signal
10,000 output-converted rows / fetchmany(1000) 22.982 ms 23.118 ms -0.9% no signal
10,000 INT/NVARCHAR rows / fetchmany(1) 27.277 ms 27.279 ms +0.2% no signal
10,000 rows x 32 columns / dict(row._mapping) (warm) 33.912 ms 30.913 ms -9.5% no signal
Build and measurement details

ADO build 195179

PR head: 3f8b245c2cc2f4e3d83ed54fd17d9cb9a25d86fd
Base: 451d8e99d32b34500f0929a369186f53d69461fd
Measured merge: 3b854830f331dd43faeed00dda82323049a42faa

  • Unix / SQL Server 2022: Python 3.12.3, x86_64, SQL 16.0.4325.4; 5 paired comparisons and 1 warmup.
  • Unix / SQL Server 2025: Python 3.12.3, x86_64, SQL 17.0.5065.9; 5 paired comparisons and 1 warmup.

A consistent change requires more than 20% median paired movement, at least 1 ms between the median runtimes, and at least 80% of pairs exceeding the relative threshold in the same direction. A slowdown without enough pair agreement is reported as inconsistent.

The displayed change is the median of paired before-and-after ratios. It is not recalculated from the two displayed median runtimes.

Both revisions use profiling-enabled builds on the same agent and database, with alternating order and discarded warmups. Results are diagnostic and do not represent production-wheel latency.

Raw samples and logs are attached to the ADO run as profiler-* artifacts.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Large JSON values bypass the streaming fallback, causing critical native-memory amplification because array binding allocates space for the largest value across every row, including NULL rows.

1 open issue
1 resolved since last review

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

📊 Code Coverage Report

🔥 Diff Coverage

86%


🎯 Overall Coverage

86%


📈 Total Lines Covered: 13532 out of 15704
📁 Project: mssql-python


Diff Coverage

Diff: main...HEAD, staged and unstaged changes

  • mssql_python/init.py (100%)
  • mssql_python/_native_fetch.py (50.0%): Missing lines 243
  • mssql_python/async_query/async_cursor.py (100%)
  • mssql_python/async_query/async_execute.py (100%)
  • mssql_python/constants.py (100%)
  • mssql_python/cursor.py (76.3%): Missing lines 615,1397,1705,1713-1719,3001,3007,3016,3207-3208,3211,3419,3471,3583,3602-3603,3707-3708
  • mssql_python/json.py (96.3%): Missing lines 71,78
  • mssql_python/pybind/ddbc_bindings.cpp (100%)
  • mssql_python/pybind/ddbc_bindings.h (100%)
  • mssql_python/pybind/param_detect.hpp (90.0%): Missing lines 394,396,401,409
  • mssql_python/pybind/py_type_cache.hpp (100%)

Summary

  • Total: 230 lines
  • Missing: 30 lines
  • Coverage: 86%

mssql_python/_native_fetch.py

Lines 239-247

  239             return None
  240         if self._conversion_ineligible(data):
  241             return None
  242         if data.get("_json_decode_indices"):
! 243             return None
  244         runtime = _query_operation._NATIVE_QUERY_RUNTIME
  245         if not (self._policy_eligible(runtime) if isinstance(runtime, tuple) else self.unchanged()):
  246             return None
  247         if self.logger.is_debug_enabled:

mssql_python/cursor.py

Lines 611-619

  611         Registered converters (including str and SQL_WVARCHAR fallbacks) take
  612         precedence. Object decoding uses json.loads and is not lossless for
  613         arbitrary JSON numbers; use text mode when preserving numeric text.
  614         """
! 615         return self._json_output
  616 
  617     @json_output.setter
  618     def json_output(self, value: Literal["text", "objects"]) -> None:
  619         if not isinstance(value, str) or value not in ("text", "objects"):

Lines 1393-1401

  1393         """
  1394         Import and return pyarrow or raise ImportError accordingly.
  1395         """
  1396         if self._column_sql_types and ddbc_sql_const.SQL_SS_JSON.value in self._column_sql_types:
! 1397             raise NotSupportedError(
  1398                 "Native JSON Arrow results are not supported; use row fetch APIs", ""
  1399             )
  1400         try:
  1401             import pyarrow

Lines 1701-1709

  1701                 and json_objects
  1702                 and sql_type_codes is not None
  1703                 and sql_type_codes[i] == ddbc_sql_const.SQL_SS_JSON.value
  1704             ):
! 1705                 json_indices.append(i)
  1706             converter_map.append(converter)
  1707 
  1708         self._json_decode_indices = tuple(json_indices)
  1709         self._cached_converters_generation = generation

Lines 1709-1723

  1709         self._cached_converters_generation = generation
  1710         return converter_map if any(converter is not None for converter in converter_map) else ()
  1711 
  1712     def _decode_json_row(self, values: list[Any]) -> None:
! 1713         for index in self._json_decode_indices:
! 1714             if values[index] is not None:
! 1715                 try:
! 1716                     values[index] = _decode_json(values[index])
! 1717                 except DataError as error:
! 1718                     name = self.description[index][0] if self.description else None
! 1719                     raise DataError(
  1720                         f"{error.driver_error} in column {index + 1} ({name!r})", ""
  1721                     ) from error
  1722 
  1723     def _compute_uuid_str_indices(self) -> tuple[int, ...] | None:

Lines 2997-3005

  2997                         has_json
  2998                         and size_override
  2999                         and size_override[0] != ddbc_sql_const.SQL_SS_JSON.value
  3000                     ):
! 3001                         raise TypeError("Json requires SQL_JSON input sizing")
  3002                     max_units = 1
  3003                     for value in column:
  3004                         if value is None:
  3005                             continue

Lines 3003-3011

  3003                     for value in column:
  3004                         if value is None:
  3005                             continue
  3006                         if not isinstance(value, Json):
! 3007                             raise TypeError("SQL_JSON requires Json or None")
  3008                         max_units = max(max_units, value._utf16_length)
  3009                     paraminfo = param_info()
  3010                     paraminfo.paramSQLType = ddbc_sql_const.SQL_SS_JSON.value
  3011                     paraminfo.paramCType = ddbc_sql_const.SQL_C_WCHAR.value

Lines 3012-3020

  3012                     paraminfo.columnSize = max_units
  3013                     paraminfo.inputOutputType = ddbc_sql_const.SQL_PARAM_INPUT.value
  3014                     paraminfo.isDAE = max_units > MAX_INLINE_CHAR
  3015                     if paraminfo.isDAE:
! 3016                         requires_rowwise = True
  3017                     parameters_type.append(paraminfo)
  3018                     json_columns.append(col_index)
  3019                     continue

Lines 3203-3215

  3203                 "Batch parameters require row-by-row execution to preserve their types and sizes.",
  3204             )
  3205             input_sizes = self._inputsizes
  3206             if json_columns:
! 3207                 if any(len(row) != param_count for row in seq_of_parameters):
! 3208                     raise ValueError("Inconsistent parameter row size in executemany()")
  3209                 # Preserve inferred JSON NULLs during row-wise fallback.
  3210                 # None entries leave companion parameters on their ordinary detection path.
! 3211                 input_sizes = [
  3212                     (
  3213                         (ddbc_sql_const.SQL_SS_JSON.value, ddbc_sql_const.SQL_C_WCHAR.value, 0, 0)
  3214                         if i in json_columns
  3215                         else input_sizes[i] if input_sizes and i < len(input_sizes) else None

Lines 3415-3423

  3415                 self._increment_rownumber()
  3416             self.rowcount = self._next_row_index
  3417             column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
  3418             if self._json_decode_indices:
! 3419                 self._decode_json_row(row_data)
  3420             if deferred_text and not converter_map:
  3421                 ddbc_bindings.restore_output_converter_text(row_data)
  3422                 deferred_text = False
  3423             with perf_phase("py::fetchone::row_wrap"):

Lines 3467-3475

  3467 
  3468     def _wrap_fetchone(self, row_data: list[Any]) -> Row:
  3469         column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
  3470         if self._json_decode_indices:
! 3471             self._decode_json_row(row_data)
  3472         with perf_phase("py::fetchone::row_wrap"):
  3473             if not converter_map and not self._uuid_str_indices:
  3474                 return Row._fast_create(
  3475                     row_data, column_map, self, column_map_lower, self._cached_result_columns

Lines 3579-3587

  3579         rows = []
  3580         for _ in range(min(size, len(procedure_rows))):
  3581             buffered_row = procedure_rows.popleft()
  3582             if self._json_decode_indices:
! 3583                 self._decode_json_row(buffered_row)
  3584             self._increment_rownumber()
  3585             self.rowcount = self._next_row_index
  3586             rows.append(
  3587                 Row(

Lines 3598-3607

  3598 
  3599     def _wrap_fetchmany(self, rows_data: list[list[Any]], deferred_text: bool = False) -> list[Row]:
  3600         column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
  3601         if self._json_decode_indices:
! 3602             for row_data in rows_data:
! 3603                 self._decode_json_row(row_data)
  3604         if deferred_text and not converter_map:
  3605             for row_data in rows_data:
  3606                 ddbc_bindings.restore_output_converter_text(row_data)
  3607             deferred_text = False

Lines 3703-3712

  3703 
  3704             # Get column and converter maps
  3705             column_map, converter_map, column_map_lower = self._get_column_and_converter_maps()
  3706             if self._json_decode_indices:
! 3707                 for row_data in rows_data:
! 3708                     self._decode_json_row(row_data)
  3709             if deferred_text and not converter_map:
  3710                 for row_data in rows_data:
  3711                     ddbc_bindings.restore_output_converter_text(row_data)
  3712                 deferred_text = False

mssql_python/json.py

Lines 67-75

  67     except ValueError as error:
  68         raise DataError("Invalid native JSON result", "") from error
  69     if not isinstance(result, (dict, list)):
  70         raise DataError("Native JSON result must have an object or array root", "")
! 71     return result
  72 
  73 
  74 def _reject_json_parameters(values: Any, backend: str) -> None:
  75     if isinstance(values, Mapping):

Lines 74-81

  74 def _reject_json_parameters(values: Any, backend: str) -> None:
  75     if isinstance(values, Mapping):
  76         values = values.values()
  77     elif not isinstance(values, Sequence):
! 78         return
  79     if any(isinstance(value, Json) for value in values):
  80         raise NotSupportedError(f"Json parameters are not supported by {backend}", "")

mssql_python/pybind/param_detect.hpp

Lines 390-405

  390             PyLong_AsLong(PyTuple_GET_ITEM(inputSize, 0)) == SQL_SS_JSON;
  391         if (PyErr_Occurred()) throw py::error_already_set();
  392         if (isJson || jsonOverride) {
  393             if (isJson && inputSize != Py_None && !jsonOverride)
! 394                 throw py::type_error("Json requires SQL_JSON input sizing");
  395             if (!isJson && obj != Py_None)
! 396                 throw py::type_error("SQL_JSON requires Json or None");
  397             if (isJson) {
  398                 py::object text = steal(PyObject_GetAttrString(obj, "_text"));
  399                 if (!text) throw py::error_already_set();
  400                 if (PyList_SetItem(params, i, text.release().ptr()) != 0)
! 401                     throw py::error_already_set();
  402                 obj = PyList_GET_ITEM(params, i);
  403             }
  404             info.paramSQLType = SQL_SS_JSON;
  405             info.paramCType = SQL_C_WCHAR;

Lines 405-413

  405             info.paramCType = SQL_C_WCHAR;
  406             info.columnSize = 0;
  407             if (obj != Py_None) {
  408                 if (!PyUnicode_Check(obj))
! 409                     throw py::type_error("Json snapshot must be text");
  410                 info.utf16Len = UnicodeUtf16Length(obj);
  411                 info.isDAE = info.utf16Len > MAX_INLINE_CHAR;
  412                 if (info.isDAE) info.dataPtr = borrow(obj);
  413             }


📋 Files Needing Attention

📉 Files with overall lowest coverage (click to expand)
mssql_python.pybind.performance_counter.hpp: 0.7%
mssql_python.pybind.logger_bridge.cpp: 57.9%
mssql_python.pybind.vector_support.hpp: 59.5%
mssql_python.pybind.ddbc_bindings.h: 69.2%
mssql_python._native_fetch.py: 80.1%
mssql_python.pybind.ddbc_bindings.cpp: 80.2%
mssql_python.pybind.row_mapping_cache.hpp: 81.5%
mssql_python.pybind.connection.connection_pool.cpp: 82.5%
mssql_python.pybind.connection.connection.cpp: 84.1%
mssql_python.logging.py: 86.8%

🔗 Quick Links

⚙️ Build Summary 📋 Coverage Details

View Azure DevOps Build

Browse Full Coverage Report

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed against head 85df0246. I'm on the ODBC driver side (msodbcsql), so I focused on interop with the JSON-capable driver and checked the driver-facing assumptions with small ODBC programs against the JSON preview build (feature/JsonFeature ee87e0c6b, retail) and against shipped 18.6.2, on SQL Server 2025. I did not build the extension or run tests/test_json.py.

Checked and found fine

  • Chunked SQL_C_WCHAR reads cut inside a surrogate pair: SQLGetData writes a full buffer ending in the lone high surrogate (ind = SQL_NO_TOTAL), and the next chunk starts with the low surrogate. FetchLobColumnData concatenates raw units and decodes once, so text comes back intact with no stray U+0000. Tested at the real 8192-byte chunk for json, nvarchar(max) and UTF-8 varchar(max).
  • Bare None into a json column of a permanent table, no hint: SQLDescribeParam returns -157, size 0, and NULL bound as SQL_C_DEFAULT + -157 executes.
  • PyList_SetItem in DetectParamTypes only replaces items in the cursor's internal list(...) copy, never the caller's list.
  • Fetch paths: every fetch path sends JSON through the per-row LOB SQLGetData path, and Arrow is rejected before the XML-only C++ sites. Output-converter deferral applies only to columns that have a converter, so decoded JSON columns always arrive as str.

Inline comments below. A few more items with no good diff line:

  • Question: live JSON tests in CI. Nothing sets MSSQL_TEST_NATIVE_JSON, so CI skips every live JSON test (diff coverage 64%, cursor.py 50.6%). Is a CI leg with the preview driver planned? Until then, a regression in this feature can only be caught by manual runs.
  • Question: driver with JSON, server without it (e.g. SQL Server 2022). The driver still sends the parameter with the JSON wire type and the server rejects it; the connection stays usable. What does Python surface there? A line in the README would help.
  • Nit: calculateRowSize (ddbc_bindings.cpp) has no SQL_SS_JSON case. It's unreachable today because JSON always takes the LOB path first, but it would throw "Unsupported data type" if that ever changed. Adding the case next to SQL_SS_XML would guard against that.
  • The executemany memory issue Copilot flagged (thread on cursor.py) is real; I've confirmed it there.
Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/cursor.py Resolved
Comment thread mssql_python/json.py Resolved
Comment thread mssql_python/pybind/param_detect.hpp Resolved
Comment thread mssql_python/pybind/param_detect.hpp Resolved
Comment thread mssql_python/cursor.py Resolved
Comment thread docs/native-json-preview.md Resolved
Copilot AI balanced review requested due to automatic review settings November 24, 2026 12:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Independent runtime validation was blocked by the unavailable authorized preview provider and live SQL Server, while sanitizer and broader platform qualification remain unresolved.

1 open issue

Review effort: Balanced

Stream oversized JSON batches, remove bulk iterator scanning, avoid redundant sizing encodes, validate native hints, and improve unsupported-driver diagnostics and result-state cleanup. Add focused regressions and document preview qualification gates.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:20
@jahnvi480

Copy link
Copy Markdown
Contributor Author

Pushed review corrections in 72d031e and replied in all nine inline threads. For the unanchored points in the driver review:

  • Older server: the qualified preview against SQL Server 2022 (16.0.4225.2) surfaces ProgrammingError, SQLSTATE 42000, for native JSON input. Subsequent ordinary execution succeeds. The README now documents this; there is no text retry or provider switch.
  • Row-size switch: added SQL_SS_JSON beside SQL_SS_XML in calculateRowSize. JSON still takes its existing LOB fetch path.
  • Live CI: still a release prerequisite, not silently solved by local testing. The preview guide now records the tested artifact hashes, required authorized/checksum-pinned provisioning, and the command/flag for a native JSON CI leg. Minimum fixed preview-build confirmation, production Linux filename adoption, and macOS qualification remain open. No development binaries or private download locations were added.

Fresh qualification used actual preview 18.7.1.1 libraries, owned SQL Server 2025 (17.0.5005.3), rebuilt Release extensions, and pinned Rust core 0.5.0:

Run Result
Windows CPython 3.13.17, python -m pytest tests/test_json.py -q --tb=short -ra 240 passed, no skips
Windows affected cursor/bulk/auth-cleanup/TVP/rebinding/native-fetch/converter suites, including JSON 1,304 passed, 27 skipped, 1 deselected
Linux x64 CPython 3.13.15, rebuilt native extension; affected suites including JSON, bulk, exceptions and encoding 1,758 passed, 26 skipped, 1 deselected; no JSON skips
python -m pytest tests/test_typing.py -m typing -q --tb=short 7 passed
python -m pre_commit run black-check --all-files --hook-stage pre-push Passed

Broader-suite skips are reported, not counted as coverage: separate fault-injection builds/exported Windows pointers, platform-specific cases, existing skipped tests and numeric-range cases. This pass did not rerun the entire repository suite or establish sanitizer qualification. The previously unresolved sanitizer/platform gaps remain; this PR stays draft.

The legacy-driver JSON-as-VARCHAR fetch failure is separately documented and reproduced on rebuilt pre-JSON main, rather than presented as working compatibility. The explicit Json(text) contract is unchanged.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new HY004-to-NotSupportedError translation lacks normal-CI regression coverage for unsupported execute() and array-bound executemany() calls, leaving SQLSTATE, diagnostic preservation, and cursor reuse unverified.

1 open issue
1 resolved since last review

Review effort: Balanced

Comment thread mssql_python/pybind/ddbc_bindings.cpp Resolved
Exercise scalar and array-bound HY004 translation with the shipped provider, preserve diagnostics, verify zero writes and immediate same-statement recovery, and document the separate legacy and preview test legs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The authorized preview provider is unavailable for independent runtime validation, leaving native streaming, cleanup, sanitizer, and cross-platform qualification unresolved and requiring human review.

1 open issue

Review effort: Balanced

Check provider routing before scanning parameters and input hints; preserve native validation and guard ordinary execution with deterministic operation-count regressions.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Preserve native JSON routing optimization and vector behavior; handle sparse JSON hints in vector batch scanning.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 22:57
Integrate release wheel-test and runtime compatibility updates while preserving JSON-specific coverage.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 15:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The cross-cutting native JSON changes need maintainer evaluation because independent native/preview-server validation was unavailable and final-head CI, broader platform coverage, and sanitizer qualification remain outstanding.

No open issues 🎉

Review effort: Balanced

Use the standard database fixture for mocked bulk-core translation and iterator-boundary tests instead of requiring a native JSON preview.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 15:50
Copilot stopped reviewing on behalf of Jahnvi Thakkar (jahnvi480) due to an error November 25, 2026 15:52
Copilot stopped reviewing on behalf of Jahnvi Thakkar (jahnvi480) due to an error November 25, 2026 15:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The native JSON/LOB changes still require final-head CI and qualified preview-provider runtime validation, with the original Fabric reproduction and cross-platform qualification unverified in this environment.

No open issues 🎉

Review effort: Balanced

Preserve JSON object-decoding fallback alongside cancellation-aware native fetch policy and retain typing coverage for both APIs.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 03:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native JSON binding and LOB changes depend on an unshipped ODBC preview, with live-provider validation unavailable and final-head CI, broader platform coverage, and sanitizer qualification still outstanding.

No open issues 🎉

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 05:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native JSON changes span binding, streaming, and shared LOB/error paths, but required preview-driver SQL Server validation cannot be reproduced here, and outstanding CI, platform, and sanitizer evidence requires human assessment.

No open issues 🎉

Review effort: Balanced

Remove PR-specific LOB exception translation and its tests and documentation claims. Preserve main cancellation behavior and JSON binding diagnostics.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 05:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Native JSON binding, streaming, and fetch changes depend on preview ODBC behavior, but runtime evidence covers only Windows x64, leaving broader platform support and the original Fabric failure unverified and requiring human release-risk review.

No open issues 🎉

Review effort: Balanced

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the PR for correctness, security, reliability, performance, test coverage, repository conventions, and applicable architecture and design specifications. No actionable issues were identified. The implementation is consistent with repository standards and the applicable approved design requirements.

Recommendation: Approve

Scope: Synchronous preview only; not full JSON-design or release-qualification approval.

@jahnvi480
Jahnvi Thakkar (jahnvi480) merged commit 76b2dd8 into main Nov 26, 2026
39 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-size: large Substantial code update

5 participants