Repository navigation
FEAT: Add native JSON support for synchronous Python APIs - #916
Conversation
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>
There was a problem hiding this comment.
🟡 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
Jsoninputs, 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
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>
PR Performance Report✅ No regression detectedNo 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 diagnosticsPhase 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 timingsUnix / SQL Server 2022
Unix / SQL Server 2025
Build and measurement detailsPR head:
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 |
There was a problem hiding this comment.
🔵 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 resolved since last review
Review effort: Balanced
📊 Code Coverage Report
Diff CoverageDiff: main...HEAD, staged and unstaged changes
Summary
mssql_python/_native_fetch.pyLines 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.pyLines 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 pyarrowLines 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 = generationLines 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 continueLines 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.valueLines 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 continueLines 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 NoneLines 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_columnsLines 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 = FalseLines 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 = Falsemssql_python/json.pyLines 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.hppLines 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
|
Nandana Rao Lingampelli (NandanaRaol)
left a comment
There was a problem hiding this comment.
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_WCHARreads cut inside a surrogate pair:SQLGetDatawrites a full buffer ending in the lone high surrogate (ind = SQL_NO_TOTAL), and the next chunk starts with the low surrogate.FetchLobColumnDataconcatenates 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
Noneinto a json column of a permanent table, no hint:SQLDescribeParamreturns-157, size 0, and NULL bound asSQL_C_DEFAULT+-157executes. PyList_SetIteminDetectParamTypesonly replaces items in the cursor's internallist(...)copy, never the caller's list.- Fetch paths: every fetch path sends JSON through the per-row LOB
SQLGetDatapath, 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 asstr.
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.py50.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 noSQL_SS_JSONcase. 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 toSQL_SS_XMLwould guard against that. - The executemany memory issue Copilot flagged (thread on
cursor.py) is real; I've confirmed it there.
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>
|
Pushed review corrections in 72d031e and replied in all nine inline threads. For the unanchored points in the driver review:
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:
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 |
There was a problem hiding this comment.
🟡 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
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>
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>
Integrate release wheel-test and runtime compatibility updates while preserving JSON-specific coverage. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🔵 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>
There was a problem hiding this comment.
🔵 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>
There was a problem hiding this comment.
🔵 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
There was a problem hiding this comment.
🔵 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>
There was a problem hiding this comment.
🔵 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
Sumit Sarabhai (sumitmsft)
left a comment
There was a problem hiding this comment.
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.



Work Item / Issue Reference
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:
3f8b245c2cc2f4e3d83ed54fd17d9cb9a25d86fdremoves 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.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.SQL_JSON/SQL_SS_JSON = -157; bind throughSQL_C_WCHARwith execute/executemany, typed NULLs, large parameters and complete LOB retrieval.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.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.
mssql_python\pybind\build.bat x64withMSSQL_ARROW_TEST_INTERPOSITION=1and development interpreter/library environmentpython -m pytest tests/test_query_cancellation.py tests/test_json.py::test_json_unsupported_bind_preserves_diagnostics_and_cursor_reuse -q -ra --tb=shortwithMSSQL_ARROW_TEST_INTERPOSITION=1and native JSON preview opt-in unsetpython -m pytest tests\test_json.py -q --tb=short -rawithMSSQL_TEST_NATIVE_JSON=1python -m pre_commit run black-check --all-files --hook-stage pre-pushgit diff --checkThese 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.