diff --git a/README.md b/README.md index dfdd4113f..0763bec4e 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/mssql_python/_pycore_types.pyi b/mssql_python/_pycore_types.pyi index d18f36760..a11901316 100644 --- a/mssql_python/_pycore_types.pyi +++ b/mssql_python/_pycore_types.pyi @@ -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] diff --git a/mssql_python/cursor.py b/mssql_python/cursor.py index 651e96498..2ee2f89da 100644 --- a/mssql_python/cursor.py +++ b/mssql_python/cursor.py @@ -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 @@ -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") @@ -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 @@ -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 @@ -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 @@ -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: @@ -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 @@ -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) @@ -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). @@ -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`` diff --git a/mssql_python/json.py b/mssql_python/json.py index 5ce67d7d8..0c1be9569 100644 --- a/mssql_python/json.py +++ b/mssql_python/json.py @@ -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 @@ -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) diff --git a/mssql_python/pybind/ddbc_bindings.cpp b/mssql_python/pybind/ddbc_bindings.cpp index 823b47eea..bfe53d181 100644 --- a/mssql_python/pybind/ddbc_bindings.cpp +++ b/mssql_python/pybind/ddbc_bindings.cpp @@ -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; @@ -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: @@ -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: @@ -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 @@ -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: @@ -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) { @@ -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: @@ -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: { diff --git a/setup.py b/setup.py index 7001212db..27c7691f2 100644 --- a/setup.py +++ b/setup.py @@ -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", diff --git a/tests/conftest.py b/tests/conftest.py index 96dff10dd..a8c27e0e2 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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 diff --git a/tests/test_004_cursor_arrow.py b/tests/test_004_cursor_arrow.py index 701983d0c..2f989909f 100644 --- a/tests/test_004_cursor_arrow.py +++ b/tests/test_004_cursor_arrow.py @@ -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 diff --git a/tests/test_024_bulkcopy_arrow.py b/tests/test_024_bulkcopy_arrow.py index b7432c73c..38093b03a 100644 --- a/tests/test_024_bulkcopy_arrow.py +++ b/tests/test_024_bulkcopy_arrow.py @@ -17,6 +17,7 @@ import os import secrets +import uuid from unittest.mock import MagicMock, patch import pytest @@ -36,6 +37,160 @@ SAMPLE_TOKEN = secrets.token_hex(44) +@pytest.mark.parametrize("kind", ["rows", "reader", "c_stream"]) +@pytest.mark.parametrize("batch_size", [0, 2]) +@pytest.mark.parametrize("good_rows", [0, 1, 2, 3, 4]) +@LIVE_DB +def test_bulk_source_failure_preserves_committed_batches( + qualified_bulk_runtime, conn_str, kind, batch_size, good_rows +): + from mssql_python import connect + + table = "bulk_source_failure_" + uuid.uuid4().hex + failure = ValueError("intentional producer failure") + pulls = [] + + def source(): + for index in range(good_rows): + pulls.append(index) + if kind == "rows": + yield (index,) + else: + yield pa.record_batch({"id": pa.array([index], type=pa.int32())}) + pulls.append(good_rows) + raise failure + + with connect(conn_str) as connection, connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (id INT NOT NULL)") + connection.commit() + try: + data = source() + if kind != "rows": + data = pa.RecordBatchReader.from_batches(pa.schema([("id", pa.int32())]), data) + if kind == "c_stream": + data = _CStreamOnly(data) + method = cursor.bulkcopy if kind == "rows" else cursor.bulkcopy_arrow + with pytest.raises( + (ValueError, pa.ArrowInvalid), match="intentional producer failure" + ) as caught: + method( + table, + data, + batch_size=batch_size, + column_mappings=[(0, "id")], + use_internal_transaction=True, + ) + if kind in ("rows", "reader"): + assert caught.value is failure + assert pulls == list(range(good_rows + 1)) + connection.rollback() + committed = good_rows // batch_size * batch_size if batch_size else 0 + cursor.execute(f"SELECT id FROM {table} ORDER BY id") + assert [row[0] for row in cursor.fetchall()] == list(range(committed)) + finally: + cursor.execute(f"DROP TABLE {table}") + connection.commit() + + +def _json_arrow_types(): + if not hasattr(pa, "json_"): + return [] + return [ + pa.string(), + pa.large_string(), + pa.string_view(), + pa.json_(pa.string()), + pa.json_(pa.large_string()), + pa.json_(pa.string_view()), + ] + + +@pytest.mark.parametrize("arrow_type", _json_arrow_types()) +@pytest.mark.parametrize( + "producer", ["table", "batch", "reader", "iterable", "c_array", "c_stream"] +) +def test_bulk_arrow_json_producers_slices_nulls(json_bulk_connection, arrow_type, producer): + table = "bulk_arrow_json_" + uuid.uuid4().hex + values = ['{"text":"\\u03bb\\ud83d\\ude00"}', None] + batch = pa.record_batch( + [pa.array(["unused", *values], type=arrow_type).slice(1)], names=["doc"] + ) + source = { + "table": lambda: pa.Table.from_batches([batch]), + "batch": lambda: batch, + "reader": lambda: pa.RecordBatchReader.from_batches(batch.schema, [batch]), + "iterable": lambda: iter([batch]), + "c_array": lambda: _CArrayOnly(batch), + "c_stream": lambda: _CStreamOnly(pa.Table.from_batches([batch])), + }[producer]() + with json_bulk_connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (doc JSON)") + try: + assert cursor.bulkcopy_arrow(table, source, keep_nulls=True)["rows_copied"] == 2 + cursor.execute(f"SELECT JSON_VALUE(doc, '$.text') FROM {table}") + assert {row[0] for row in cursor.fetchall()} == {"\u03bb\U0001f600", None} + finally: + cursor.execute(f"DROP TABLE {table}") + + +@pytest.mark.parametrize("arrow_type", _json_arrow_types()) +@pytest.mark.parametrize("values", [[], [None, None]]) +def test_bulk_arrow_json_empty_and_null(json_bulk_connection, arrow_type, values): + table = "bulk_arrow_empty_" + uuid.uuid4().hex + with json_bulk_connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (doc JSON)") + try: + result = cursor.bulkcopy_arrow( + table, pa.table({"doc": pa.array(values, type=arrow_type)}), keep_nulls=True + ) + assert result["rows_copied"] == len(values) + finally: + cursor.execute(f"DROP TABLE {table}") + + +@pytest.mark.parametrize("empty", [False, True]) +@pytest.mark.parametrize("drift", ["name", "storage", "extension"]) +def test_bulk_arrow_json_checks_later_reader_schema(json_bulk_connection, empty, drift): + table = "bulk_arrow_schema_" + uuid.uuid4().hex + first = pa.record_batch({"doc": ["{}"]}) + field = pa.field( + "renamed" if drift == "name" else "doc", + pa.large_string() if drift == "storage" else pa.string(), + metadata={"ARROW:extension:name": "unknown"} if drift == "extension" else None, + ) + later = pa.record_batch( + [pa.array([] if empty else ["{}"], type=field.type)], schema=pa.schema([field]) + ) + source = pa.RecordBatchReader.from_batches(first.schema, [first, later]) + with json_bulk_connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (doc JSON)") + try: + with pytest.raises( + ValueError, match="Mapped Arrow source column|unsupported extension" + ): + cursor.bulkcopy_arrow(table, source, batch_size=10, use_internal_transaction=True) + assert cursor.execute(f"SELECT COUNT(*) FROM {table}").fetchval() == 0 + finally: + cursor.execute(f"DROP TABLE {table}") + + +@pytest.mark.parametrize("bad_text", ["123", "true", "null", "{"]) +def test_bulk_arrow_json_server_rejects_non_documents(json_bulk_connection, bad_text): + table = "bulk_arrow_invalid_" + uuid.uuid4().hex + with json_bulk_connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (doc JSON)") + try: + with pytest.raises(RuntimeError): + cursor.bulkcopy_arrow( + table, + pa.table({"doc": pa.array([bad_text], type=pa.json_())}), + use_internal_transaction=True, + ) + assert cursor.execute(f"SELECT COUNT(*) FROM {table}").fetchval() == 0 + finally: + cursor.execute(f"DROP TABLE {table}") + + # ── helpers ────────────────────────────────────────────────────────────────── diff --git a/tests/test_json.py b/tests/test_json.py index 989f5d022..b22c93bec 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -930,11 +930,16 @@ def test_json_rejects_conflicting_hints_before_execution(json_connection, batch) @pytest.mark.parametrize("method", ["arrow", "arrow_batch", "arrow_reader"]) def test_json_arrow_boundary_does_not_consume_rows(json_connection, method): + pa = pytest.importorskip("pyarrow") with json_connection.cursor() as cursor: - cursor.execute("SELECT CAST(N'{}' AS JSON)") - with pytest.raises(NotSupportedError, match="Arrow"): - getattr(cursor, method)() + cursor.execute("SELECT CAST(N'{}' AS JSON) AS doc") + result = getattr(cursor, method)(batch_size=0) + if method != "arrow_reader": + assert result.num_rows == 0 + assert result.schema.field("doc").type == pa.large_string() assert json.loads(cursor.fetchone()[0]) == {} + if method == "arrow_reader": + result.close() @pytest.mark.parametrize("base", [dict, list, str, int, float]) @@ -1255,6 +1260,8 @@ def test_json_streamed_batch_row_shape_rejected_before_writes(json_connection): def test_json_bulk_guard_preserves_iterator_boundary(db_connection, monkeypatch): import mssql_python.cursor as cursor_module + monkeypatch.setattr(cursor_module, "_BULKCOPY_JSON_RUNTIME_QUALIFIED", False) + consumed = [] json_checks = [] original_isinstance = isinstance @@ -1291,7 +1298,10 @@ def consume(_table, parameters, **_kwargs): @pytest.mark.parametrize("later_row", [False, True]) -def test_json_bulk_core_rejects_without_consuming_tail(json_connection, later_row): +def test_json_bulk_core_rejects_without_consuming_tail(json_connection, later_row, monkeypatch): + import mssql_python.cursor as cursor_module + + monkeypatch.setattr(cursor_module, "_BULKCOPY_JSON_RUNTIME_QUALIFIED", False) name = "json_bulk_" + uuid.uuid4().hex consumed = [] @@ -1328,3 +1338,255 @@ def test_bulk_unrelated_value_error_is_preserved(db_connection, monkeypatch): with pytest.raises(ValueError) as caught: cursor.bulkcopy("unused", [(object(),)]) assert caught.value is error + + +@pytest.fixture +def bulk_json_cursor(monkeypatch): + from mssql_python._query_operation import QueryConnectionState, QuerySlot + + cursor = Cursor.__new__(Cursor) + cursor._query_slot = QuerySlot() + cursor._connection = SimpleNamespace( + _query_state=QueryConnectionState(), _is_connected=True, closed=False + ) + cursor.closed = False + cursor.hstmt = None + core = Mock() + monkeypatch.setattr(cursor, "_bulkcopy_core_and_validate", lambda *args: core) + monkeypatch.setattr(cursor, "_build_pycore_context", dict) + return cursor, core + + +@pytest.mark.parametrize("as_row", [False, True]) +@pytest.mark.parametrize("mappings", [None, ["doc"], [(1, "doc")]]) +def test_bulk_json_bridge_snapshots_are_lazy_and_mapped( + bulk_json_cursor, monkeypatch, as_row, mappings +): + from mssql_python import Row + import mssql_python.cursor as cursor_module + + cursor, core = bulk_json_cursor + monkeypatch.setattr(cursor_module, "_BULKCOPY_JSON_RUNTIME_QUALIFIED", True) + original = {"value": [1]} + snapshot = Json(original) + original["value"].append(2) + text = Json(' {"escaped":"\\u0000\\u03bb","key":1,"key":2} ') + documents = [snapshot, text, snapshot, None] + consumed = [] + seen = [] + core.BulkCopyJson.side_effect = lambda value: SimpleNamespace(text=value) + monkeypatch.setattr(json, "loads", Mock(side_effect=AssertionError("No JSON parse"))) + monkeypatch.setattr(json, "dumps", Mock(side_effect=AssertionError("No JSON serialization"))) + + def rows(): + for index, document in enumerate(documents): + consumed.append(index) + values = ( + (text, document, original) + if mappings == [(1, "doc")] + else (document, text, original) if mappings else (document,) + ) + yield Row._fast_create(values, None, None) if as_row else values + + def consume(_table, rows, **kwargs): + assert consumed == [0] # Existing wrapper reads only the first row for representation. + mapped = 1 if mappings == [(1, "doc")] else 0 + for index, row in enumerate(rows): + assert consumed == list(range(index + 1)) + seen.append(row) + document = documents[index] + assert row[mapped] is None if document is None else row[mapped].text is document._text + if mappings: + assert row[1 - mapped] is text + assert row[2] is original + return {"rows_copied": len(seen)} + + native = core.PyCoreConnection.return_value.cursor.return_value + native.bulkcopy.side_effect = consume + assert cursor.bulkcopy("unused", rows(), column_mappings=mappings)["rows_copied"] == 4 + assert [call.args[0] for call in core.BulkCopyJson.call_args_list] == [ + snapshot._text, + text._text, + snapshot._text, + ] + assert snapshot._text == '{"value":[1]}' + native.close.assert_called_once() + core.PyCoreConnection.return_value.close.assert_called_once() + + +def test_bulk_json_unqualified_runtime_does_not_use_carrier(bulk_json_cursor, monkeypatch): + import mssql_python.cursor as cursor_module + + cursor, core = bulk_json_cursor + monkeypatch.setattr(cursor_module, "_BULKCOPY_JSON_RUNTIME_QUALIFIED", False) + value = Json({}) + consumed = [] + + def rows(): + yield (value,) + consumed.append("tail") + yield (None,) + + def consume(_table, rows, **kwargs): + assert next(rows)[0] is value + raise ValueError("Unsupported Python type for bulk copy: Json") + + core.PyCoreConnection.return_value.cursor.return_value.bulkcopy.side_effect = consume + with pytest.raises(NotSupportedError, match="bulk copy"): + cursor.bulkcopy("unused", rows()) + core.BulkCopyJson.assert_not_called() + assert consumed == [] + + +def test_bulk_json_legacy_cells_are_not_snapshotted_or_prefetched(): + from mssql_python.json import _bulkcopy_json_rows + + cell = {"value": 0} + carrier = Mock(side_effect=AssertionError("Legacy cells must reach native conversion")) + + def rows(): + for value in range(3): + cell["value"] = value + yield (cell, [value], "{}", None) + + for index, row in enumerate(_bulkcopy_json_rows(rows(), carrier, None)): + assert row[0] is cell + assert row == ({"value": index}, [index], "{}", None) + carrier.assert_not_called() + + +@pytest.mark.parametrize("value", [Json("{}"), "{}"], ids=["typed-json", "text"]) +def test_bulk_json_bridge_preserves_invalid_row_shape(value): + from mssql_python.json import _bulkcopy_json_rows + + invalid_row = [value] + carrier = Mock() + rows = _bulkcopy_json_rows([(None,), invalid_row], carrier, None) + + assert next(rows) == (None,) + assert next(rows) is invalid_row + carrier.assert_not_called() + + +def test_bulk_json_bridge_preserves_vector_rejection(bulk_json_cursor, monkeypatch): + from mssql_python import Vector + import mssql_python.cursor as cursor_module + + cursor, core = bulk_json_cursor + monkeypatch.setattr(cursor_module, "_BULKCOPY_JSON_RUNTIME_QUALIFIED", True) + native = core.PyCoreConnection.return_value.cursor.return_value + native.bulkcopy.side_effect = lambda _table, rows, **kwargs: list(rows) + with pytest.raises(NotSupportedError, match="Vector bulk copy"): + cursor.bulkcopy("unused", [(Json({}), Vector([1, 2]))]) + native.close.assert_called_once() + + +def test_bulk_json_native_snapshots_and_mutable_legacy_cells(json_bulk_connection, monkeypatch): + table = "json_bulk_" + uuid.uuid4().hex + original = {"value": 1} + snapshot = Json(original) + original["value"] = 99 + mutable = {"value": 0} + original_dumps = json.dumps + + def serialize_legacy(value, *args, **kwargs): + assert value is mutable + return original_dumps(value, *args, **kwargs) + + legacy_dumps = Mock(side_effect=serialize_legacy) + + def rows(): + for index in range(3): + mutable["value"] = index + yield (index, snapshot, mutable, Json("invalid but unmapped")) + + with json_bulk_connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (id INT, doc JSON, legacy JSON)") + try: + with monkeypatch.context() as patch: + patch.setattr(json, "loads", Mock(side_effect=AssertionError("No parse"))) + patch.setattr(json, "dumps", legacy_dumps) + result = cursor.bulkcopy( + table, + rows(), + column_mappings=["id", "doc", "legacy"], + batch_size=2, + use_internal_transaction=True, + ) + assert result["rows_copied"] == 3 + assert legacy_dumps.call_count == 3 + cursor.execute( + f"SELECT id, JSON_VALUE(doc, '$.value'), JSON_VALUE(legacy, '$.value') " + f"FROM {table} ORDER BY id" + ) + assert [tuple(row) for row in cursor.fetchall()] == [ + (0, "1", "0"), + (1, "1", "1"), + (2, "1", "2"), + ] + finally: + cursor.execute(f"DROP TABLE {table}") + + +def test_bulk_json_native_mapping_and_wrong_destination(qualified_bulk_runtime, conn_str): + table = "json_bulk_mapping_" + uuid.uuid4().hex + with connect(conn_str, autocommit=True) as connection, connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (id INT, doc NVARCHAR(MAX))") + try: + result = cursor.bulkcopy( + table, + [(Json("invalid unmapped"), 1, "legacy")], + column_mappings=[(1, "id"), (2, "doc")], + use_internal_transaction=True, + ) + assert result["rows_copied"] == 1 + with pytest.raises(ValueError, match="requires a JSON destination"): + cursor.bulkcopy(table, [(2, Json({}))], use_internal_transaction=True) + cursor.execute(f"SELECT id, doc FROM {table}") + assert [tuple(row) for row in cursor.fetchall()] == [(1, "legacy")] + finally: + cursor.execute(f"DROP TABLE {table}") + + +@pytest.mark.parametrize("value", [Json("{}"), "{}"], ids=["typed-json", "text"]) +def test_bulk_json_native_rejects_later_list_row(qualified_bulk_runtime, conn_str, value): + table = "json_bulk_row_shape_" + uuid.uuid4().hex + tail_consumed = [] + + def rows(): + yield (None,) + yield [value] + tail_consumed.append(True) + yield (None,) + + with connect(conn_str, autocommit=True) as connection, connection.cursor() as cursor: + cursor.execute(f"CREATE TABLE {table} (doc NVARCHAR(MAX))") + try: + with pytest.raises(ValueError, match="Expected tuple"): + cursor.bulkcopy(table, rows(), batch_size=0, use_internal_transaction=True) + assert tail_consumed == [] + assert cursor.execute(f"SELECT COUNT(*) FROM {table}").fetchval() == 0 + finally: + cursor.execute(f"DROP TABLE {table}") + + +@pytest.mark.parametrize("method", ["arrow", "arrow_batch", "arrow_reader"]) +@pytest.mark.parametrize("output", ["text", "objects"]) +def test_json_arrow_returns_text_not_decoded_objects(json_connection, method, output): + pa = pytest.importorskip("pyarrow") + text = json.dumps({"text": "\u03bb\U0001f600" * 6000}, ensure_ascii=False) + with json_connection.cursor() as cursor: + cursor.json_output = output + cursor.execute( + "SELECT CAST(? AS JSON) AS doc, 0 AS id " + "UNION ALL SELECT NULL, 1 UNION ALL SELECT CAST(N'[]' AS JSON), 2 ORDER BY id", + text, + ) + assert cursor._column_sql_types[0] == SQL_SS_JSON + result = getattr(cursor, method)() + if method == "arrow_reader": + result = result.read_all() + assert result.schema.field("doc").type == pa.large_string() + values = result.column("doc").to_pylist() + assert json.loads(values[0]) == json.loads(text) + assert values[1:] == [None, "[]"]