Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 35 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -376,12 +376,41 @@ ordinary application SQL is not rewritten or retried.

The synchronous `SQL_JSON` constant maps to `SQL_SS_JSON` (`-157`). The existing
`mssql_python.async_query.SQL_JSON` is a separate Rust-backed symbol; do not pass
type codes between backends. JSON support for Arrow, TVPs, async execution and
bulk copy remains deferred. Bulk copy adds no Python JSON scan; the core's
unsupported-`Json` diagnostic becomes `NotSupportedError` when that row is
consumed. Other core errors propagate unchanged. The full design's Arrow
text-retrieval release gate and wider platform/sanitizer qualification remain
open.
type codes between backends. TVPs and async execution do not support `Json`.

Arrow fetching returns native JSON as `large_string()` text, including with
`json_output="objects"`; it does not parse documents or produce an extension
array. SQL NULL remains Arrow null. JSON is streamed through the wide-character
LOB path, including when a provider reports a small column size.

**Typed JSON bulk input is release-gated.** The pinned `mssql-python-rs==0.5.0`
predates the merged JSON carrier and fail-fast source handling. The Python bridge
is disabled until an exact published runtime containing **both** is qualified and
pinned; finding a `BulkCopyJson` symbol is not enough. On the current pin, public
`Json` cells remain untouched and only the core's exact mapped unsupported-`Json`
diagnostic becomes `NotSupportedError`. Other errors propagate unchanged.

With a qualified runtime, the bridge passes each mapped `Json` value's immutable
serialized snapshot to the core without parsing or serializing it again.
Unmapped cells are untouched, and bare string/dict/list conversions keep their
existing behavior. Rows are consumed lazily, without look-ahead or replay;
mutable legacy cells may be reused between yields.

JSON Arrow bulk input requires that qualified runtime and **PyArrow >= 21.0.0**.
It accepts serialized `string()`, `large_string()` and `string_view()` values,
plain or wrapped in canonical `pa.json_()`. Struct, List and Dictionary JSON
serialization is not supported. Mapped field names, storage types and logical
annotations are checked on every batch, including empty ones; unrelated metadata
and unmapped fields are ignored. SQL Server validates object/array roots, so
malformed text and scalar JSON such as `123`, `true` and textual `null` fail.
Arrow null cells remain SQL NULL.

Bulk copy uses a separate connection: the parent connection's rollback cannot
undo it. On a qualified runtime, producer/import failures abort rather than
returning a truncated success. Internal transactions roll back the active failing
batch when the connection remains usable, but earlier committed batches may
remain. Without internal transactions, do not assume rollback of accepted rows.
There is no whole-load atomicity or zero-write guarantee.

### Native vector values

Expand Down
1 change: 1 addition & 0 deletions mssql_python/_pycore_types.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class AsyncCoreConnection(Protocol):

class PyCoreModule(Protocol):
__name__: str
BulkCopyJson: Callable[[str], object]
PyCoreConnection: type[CoreConnection]
PyCoreCursor: type[CoreCursor]
PyAsyncConnection: type[AsyncCoreConnection]
Expand Down
31 changes: 25 additions & 6 deletions mssql_python/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
DataError,
)
from mssql_python.row import Row, OutputConverter, _ColumnNames
from mssql_python.json import Json, _decode_json
from mssql_python.json import Json, _bulkcopy_json_rows, _decode_json
from mssql_python.vector import Vector, _vector_from_hint
from mssql_python.table_valued_parameter import TableValuedParameter
from mssql_python.perf_timer import perf_phase
Expand Down Expand Up @@ -92,6 +92,10 @@ class _ArrowModule(Protocol):
MAX_NATIVE_ROW_COUNT: int = 1_000_000
MAX_NATIVE_PARAMETER_SIZE: int = 256 * 1024 * 1024

# Enable only with an exact published runtime pin qualified for both BulkCopyJson
# and fail-fast source handling. The current 0.5.0 pin predates that contract.
_BULKCOPY_JSON_RUNTIME_QUALIFIED = False


def _encoded_length_exceeds(value: str, encoding: str, limit: int) -> bool:
encoder = codecs.getincrementalencoder(encoding)(errors="strict")
Expand Down Expand Up @@ -1423,10 +1427,6 @@ def _ensure_pyarrow(self) -> _ArrowModule:
"""
Import and return pyarrow or raise ImportError accordingly.
"""
if self._column_sql_types and ddbc_sql_const.SQL_SS_JSON.value in self._column_sql_types:
raise NotSupportedError(
"Native JSON Arrow results are not supported; use row fetch APIs", ""
)
try:
import pyarrow

Expand Down Expand Up @@ -3902,6 +3902,8 @@ def arrow_batch(self, batch_size: int = 8192) -> "pyarrow.RecordBatch":

Returns:
A pyarrow RecordBatch object containing up to batch_size rows.
Native JSON columns contain large_string text, independent of
json_output; SQL NULL remains Arrow null.
"""
batch = self._fetch_arrow_batch(batch_size)
assert batch is not None
Expand Down Expand Up @@ -4452,6 +4454,8 @@ def bulkcopy(
position), unless column_mappings is specified
- The number of values in each row must match the number of columns
in the target table
- Typed Json bulk input is release-gated pending a qualified Rust
runtime. Bare str/dict/list conversions are unchanged.

batch_size: Rows per batch/commit, an integer from 0 to 1,000,000,
not bool. Default 0 uses native core defaults. This does not
Expand Down Expand Up @@ -4488,6 +4492,9 @@ def bulkcopy(
fire_triggers: Fire insert triggers on the target table.

use_internal_transaction: Use an internal transaction for each batch.
Bulk copy uses a separate connection; the parent connection's
rollback cannot undo its writes. Earlier committed batches may
remain after a later source or server error.

Returns:
Dictionary with bulk copy results including:
Expand Down Expand Up @@ -4541,6 +4548,8 @@ def _validated_vector_rows(
) -> Iterator[tuple[Any, ...]]:
nonlocal vector_validation_error
try:
if _BULKCOPY_JSON_RUNTIME_QUALIFIED:
rows = _bulkcopy_json_rows(rows, mssql_py_core.BulkCopyJson, column_mappings)
yield from self._validate_bulkcopy_vectors(rows)
except NotSupportedError as error:
vector_validation_error = error
Expand Down Expand Up @@ -4621,7 +4630,7 @@ def _prepare_row_iterator(
# Rust can replace Python iterator exceptions with RuntimeError.
if vector_validation_error is not None and vector_validation_error is not e:
raise vector_validation_error from e
# The pinned Rust core validates every cell, including later iterator rows.
# Older cores reject mapped Json cells inside the writer.
# Translate only its exact unsupported-Json diagnostic; do not scan rows twice.
if (
isinstance(e, ValueError)
Expand Down Expand Up @@ -4673,6 +4682,14 @@ def bulkcopy_arrow(
column-mapping semantics, the options, and the returned dictionary are
identical to :meth:`bulkcopy`.

JSON text input (string, large_string, string_view and canonical
``pa.json_()`` over those storages) requires a qualified Rust runtime
and PyArrow >= 21.0.0. The current runtime pin is not yet qualified.
No nested Struct/List/Dictionary serialization is performed. SQL Server
validates object/array roots; Arrow null is SQL NULL, not JSON ``null``.
Mapped field names, storage types and logical annotations must remain
compatible across batches, including empty batches.

Args:
table_name: Target table name (may include schema, e.g. 'dbo.MyTable').
source: Arrow source (see above).
Expand All @@ -4689,6 +4706,8 @@ def bulkcopy_arrow(
keep_nulls: Preserve null values instead of using column defaults.
fire_triggers: Fire insert triggers on the target table.
use_internal_transaction: Use an internal transaction per batch.
Earlier committed batches may remain after an error. This uses
a separate connection, unaffected by the parent's rollback.

Returns:
Dictionary with ``rows_copied``, ``batch_count``, ``elapsed_time``
Expand Down
29 changes: 28 additions & 1 deletion mssql_python/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from __future__ import annotations

import json
from collections.abc import Mapping, Sequence
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, final

Expand Down Expand Up @@ -78,3 +78,30 @@ def _reject_json_parameters(values: Any, backend: str) -> None:
return
if any(isinstance(value, Json) for value in values):
raise NotSupportedError(f"Json parameters are not supported by {backend}", "")


def _bulkcopy_json_rows(
rows: Iterable[tuple[Any, ...]],
carrier: Callable[[str], object],
column_mappings: list[str] | list[tuple[int, str]] | None,
) -> Iterator[tuple[Any, ...]]:
mapped = (
None
if column_mappings is None
else {
index if isinstance(mapping, str) else mapping[0]
for index, mapping in enumerate(column_mappings)
}
)
for row in rows:
if not isinstance(row, tuple):
# Preserve invalid row shapes for the native writer to reject.
yield row
continue
converted = None
for index, value in enumerate(row):
if (mapped is None or index in mapped) and type(value) is Json:
if converted is None:
converted = list(row)
converted[index] = carrier(value._text)
yield row if converted is None else tuple(converted)
13 changes: 10 additions & 3 deletions mssql_python/pybind/ddbc_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5951,7 +5951,7 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta
const bool wide = ((dt == SQL_CHAR || dt == SQL_VARCHAR ||
dt == SQL_LONGVARCHAR) && useWideChar) || dt == SQL_WCHAR ||
dt == SQL_WVARCHAR || dt == SQL_WLONGVARCHAR ||
dt == SQL_SS_XML;
dt == SQL_SS_XML || dt == SQL_SS_JSON;
columnInfos[col].fetchBufferSize =
wide ? buffers.wcharBuffers[col].size() / bufferRows
: buffers.charBuffers[col].size() / bufferRows;
Expand Down Expand Up @@ -6013,6 +6013,7 @@ SQLRETURN ConvertBufferedRows(SQLHSTMT hStmt, ColumnBuffers& buffers, const Meta
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
case SQL_SS_XML:
case SQL_SS_JSON:
columnProcessors[col] = ColumnProcessors::ProcessWChar;
break;
case SQL_SS_UDT:
Expand Down Expand Up @@ -6834,6 +6835,7 @@ SQLRETURN ReadArrowLobColumn(SQLHSTMT stmt, PendingArrowRows& pending,
}
[[fallthrough]];
case SQL_SS_XML:
case SQL_SS_JSON:
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
Expand Down Expand Up @@ -7462,10 +7464,11 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules,
fixedValueSizes[i] = FixedFetchValueSize(dataType);
columnNullable[i] = (nullable != SQL_NO_NULLS);

if ((dataType == SQL_WVARCHAR || dataType == SQL_WLONGVARCHAR || dataType == SQL_VARCHAR ||
if (dataType == SQL_SS_JSON ||
((dataType == SQL_WVARCHAR || dataType == SQL_WLONGVARCHAR || dataType == SQL_VARCHAR ||
dataType == SQL_LONGVARCHAR || dataType == SQL_VARBINARY ||
dataType == SQL_LONGVARBINARY || dataType == SQL_SS_XML || dataType == SQL_SS_UDT) &&
(columnSize == 0 || columnSize == SQL_NO_TOTAL || columnSize > SQL_MAX_LOB_SIZE)) {
(columnSize == 0 || columnSize == SQL_NO_TOTAL || columnSize > SQL_MAX_LOB_SIZE))) {
hasLobColumns = true;
if (fetchSize > 1) {
fetchSize = 1; // LOBs require row-by-row fetch
Expand All @@ -7485,6 +7488,7 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules,
case SQL_VARCHAR:
case SQL_LONGVARCHAR:
case SQL_SS_XML:
case SQL_SS_JSON:
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
Expand Down Expand Up @@ -7776,6 +7780,7 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules,
bytes = 37;
} else if (type == SQL_WCHAR || type == SQL_WVARCHAR ||
type == SQL_WLONGVARCHAR || type == SQL_SS_XML ||
type == SQL_SS_JSON ||
((type == SQL_CHAR || type == SQL_VARCHAR ||
type == SQL_LONGVARCHAR) && charCtype == SQL_C_WCHAR)) {
if (bytes % sizeof(SQLWCHAR) != 0) {
Expand Down Expand Up @@ -7823,6 +7828,7 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules,
case SQL_VARCHAR:
case SQL_LONGVARCHAR:
case SQL_SS_XML:
case SQL_SS_JSON:
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
Expand Down Expand Up @@ -7928,6 +7934,7 @@ SQLRETURN FetchArrowBatch_wrap(SqlHandlePtr StatementHandle, py::list& capsules,
// else fall through to SQL_C_WCHAR case
}
case SQL_SS_XML:
case SQL_SS_JSON:
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR: {
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def finalize_options(self):
f"mssql-python-rs=={_read_mssql_python_rs_version()}",
],
extras_require={
"pyarrow": ["pyarrow>=14.0.0"],
"pyarrow": ["pyarrow>=21.0.0"],
},
classifiers=[
"Operating System :: Microsoft :: Windows",
Expand Down
25 changes: 25 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,28 @@ def cursor(db_connection):
cursor = db_connection.cursor()
yield cursor
cursor.close()


@pytest.fixture
def qualified_bulk_runtime():
from mssql_python import cursor as cursor_module

if not cursor_module._BULKCOPY_JSON_RUNTIME_QUALIFIED:
pytest.skip("Requires a runtime qualified for JSON bulk and fail-fast source handling")


@pytest.fixture
def json_bulk_connection(qualified_bulk_runtime, conn_str):
from mssql_python import ProgrammingError

if not conn_str:
pytest.skip("DB_CONNECTION_STRING not set")
with connect(conn_str, autocommit=True) as connection:
with connection.cursor() as cursor:
try:
cursor.execute("SELECT CAST(N'{}' AS JSON) OPTION (RECOMPILE)")
except ProgrammingError as error:
if "Type JSON is not a defined system type" not in str(error):
raise
pytest.skip("The test server does not support native JSON")
yield connection
85 changes: 85 additions & 0 deletions tests/test_004_cursor_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,91 @@ def _run_arrow_budget_script(conn_str, script, *args):
assert result.returncode == 0, result.stdout + result.stderr


@pytest.mark.parametrize("column_size", [0, 1, 4000])
@pytest.mark.parametrize("method", ["arrow", "arrow_batch", "arrow_reader"])
def test_native_json_arrow_streams_text_with_small_metadata(conn_str, column_size, method):
"""Interpose JSON metadata over real wide-text SQLGetData in an isolated process."""
_require_arrow_interposition()
_run_arrow_budget_script(
conn_str,
r"""
import ctypes
import json
import pyarrow as pa
from mssql_python import SQL_SS_JSON, ddbc_bindings as ddbc

column_size, method = int(sys.argv[1]), sys.argv[2]
callback = ctypes.WINFUNCTYPE if os.name == "nt" else ctypes.CFUNCTYPE
short_pointer = ctypes.POINTER(ctypes.c_short)
describe_type = callback(
ctypes.c_short, ctypes.c_void_p, ctypes.c_ushort, ctypes.c_void_p,
ctypes.c_short, short_pointer, short_pointer,
ctypes.POINTER(ctypes.c_size_t), short_pointer, short_pointer,
)
data_type = callback(
ctypes.c_short, ctypes.c_void_p, ctypes.c_ushort, ctypes.c_short,
ctypes.c_void_p, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_ssize_t),
)
with mssql_python.connect(os.environ["DB_CONNECTION_STRING"]) as conn:
conn.setdecoding(mssql_python.SQL_CHAR, encoding="utf-8", ctype=mssql_python.SQL_CHAR)
addresses = ddbc.module._arrow_test_pointer_addresses
describe_pointer = ctypes.c_void_p.from_address(addresses["SQLDescribeCol_ptr"])
data_pointer = ctypes.c_void_p.from_address(addresses["SQLGetData_ptr"])
original_describe, original_data = describe_pointer.value, data_pointer.value
describe, get_data = describe_type(original_describe), data_type(original_data)
ctypes_seen = []

@describe_type
def describe_json(stmt, ordinal, name, size, name_length, sql_type, width, scale, nullable):
result = describe(stmt, ordinal, name, size, name_length, sql_type, width, scale, nullable)
if result in (0, 1) and ordinal == 1:
sql_type[0] = SQL_SS_JSON
width[0] = column_size
return result

@data_type
def read_json(stmt, ordinal, ctype, buffer, length, indicator):
if ordinal == 1:
ctypes_seen.append(ctype)
return get_data(stmt, ordinal, ctype, buffer, length, indicator)

text = json.dumps({"text": "\u03bb\U0001f600" * 6000, "escaped": "\0"}, ensure_ascii=False)
try:
describe_pointer.value = ctypes.cast(describe_json, ctypes.c_void_p).value
data_pointer.value = ctypes.cast(read_json, ctypes.c_void_p).value
with conn.cursor() as cur:
cur.json_output = "objects"
cur.execute(
"SELECT CAST(? AS NVARCHAR(MAX)) AS doc, 0 AS id "
"UNION ALL SELECT NULL, 1 UNION ALL SELECT N'[]', 2 ORDER BY id", text
)
assert cur._column_sql_types[0] == SQL_SS_JSON
schema_only = cur.arrow_batch(0)
assert schema_only.num_rows == 0
assert schema_only.schema.field("doc").type == pa.large_string()
if method == "arrow":
result = cur.arrow(batch_size=2)
elif method == "arrow_reader":
with cur.arrow_reader(batch_size=2) as reader:
result = reader.read_all()
else:
batches = [cur.arrow_batch(2), cur.arrow_batch(2)]
result = pa.Table.from_batches(batches)
assert result.column("doc").to_pylist() == [text, None, "[]"]
assert result.column("id").to_pylist() == [0, 1, 2]
assert ctypes_seen and set(ctypes_seen) == {-8}, ctypes_seen
cur.execute("SELECT CAST(NULL AS NVARCHAR(MAX)) AS doc WHERE 1=0")
empty = cur.arrow()
assert empty.num_rows == 0
assert empty.schema.field("doc").type == pa.large_string()
finally:
describe_pointer.value, data_pointer.value = original_describe, original_data
""",
str(column_size),
method,
)


def test_wide_lob_probe_respects_native_budget(conn_str):
from mssql_python import ddbc_bindings as ddbc

Expand Down
Loading
Loading