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
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,41 @@ before releasing its buffers. `executemany()` and `setinputsizes()` overrides
for statements containing TVPs are not supported. The `mssql-odbc` provider does
not currently support this ODBC TVP path.

### Native JSON columns in synchronous TVPs

Declare a JSON column with `SQL_JSON` and pass `Json(...)` snapshots or `None`
for its cells. The server table type must already exist, for example
`CREATE TYPE dbo.DocumentBatch AS TABLE (id int, doc json)`:

```python
from mssql_python import Json, TableValuedParameter, SQL_INTEGER, SQL_JSON

documents = TableValuedParameter(
"dbo.DocumentBatch",
[("id", SQL_INTEGER), ("doc", SQL_JSON)],
[(1, Json({"tags": ["new"], "optional": None})), (2, Json('{"ready":true}')), (3, None)],
)
cursor.execute("SELECT id, doc FROM ?", documents)
```

This uses **native JSON ODBC child-column binding**, not an NVARCHAR fallback.
It requires a JSON-TVP-capable `msodbcsql18` provider and a server with native JSON
support. The bundled released provider does not currently support this binding;
unsupported-driver errors retain their ODBC diagnostics. Successful scalar JSON
binding alone does not establish a provider's JSON TVP capability.

JSON size and scale must be omitted or zero. Bare dictionaries, lists and strings
are rejected for JSON cells: use `Json(...)` explicitly. `Json(dict/list)` is
serialized once at construction; `Json(str)` is already serialized and is not
parsed or serialized again. Only bare `None` represents SQL NULL. The server
validates serialized JSON, including the object/array root requirement.

The existing lazy-row and large-cell streaming rules apply. Caller rows and
snapshots are not modified. Native JSON results use the existing execution-scoped
`cursor.json_output` policy (text by default, objects opt-in) and converter
precedence. This does not add async TVP support or `callproc()` TVP parameters;
invoke procedures with `execute("EXEC ...", documents)` instead.

## Cancelling a synchronous query

`cursor.cancel()` requests cancellation of that cursor's active synchronous
Expand Down
9 changes: 8 additions & 1 deletion mssql_python/pybind/tvp.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ struct TableParamState {
if (declared.paramCType == SQL_C_GUID) {
row[i] = row[i].attr("bytes_le");
}
if (declared.paramSQLType == SQL_SS_JSON) {
// Unwrap only the copied binding row, never the caller's snapshot.
row[i] = row[i].attr("_text");
}
// ApplyInputSizeOverride preserves decimal coefficients (no float or
// decimal-context arithmetic) and fractional time via isoformat.
ParamInfo converted;
Expand Down Expand Up @@ -137,7 +141,10 @@ static SQLRETURN BindTableValuedParameter(const SqlHandlePtr& handle, int paramI
hStmt, static_cast<SQLUSMALLINT>(i + 1), SQL_PARAM_INPUT,
column.paramCType, column.paramSQLType, column.columnSize, column.decimalDigits,
&table.columns[i], 0, &table.indicators[i]);
if (!SQL_SUCCEEDED(rc)) ThrowParameterError(handle, rc, "Failed to bind TVP column");
if (!SQL_SUCCEEDED(rc)) {
if (column.paramSQLType == SQL_SS_JSON) CheckJsonBindError(hStmt, rc);
ThrowParameterError(handle, rc, "Failed to bind TVP column");
}
}
} catch (...) {
SQLSetStmtAttr_ptr(hStmt, SQL_SOPT_SS_PARAM_FOCUS, nullptr, SQL_IS_INTEGER);
Expand Down
5 changes: 5 additions & 0 deletions mssql_python/table_valued_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from uuid import UUID

from .constants import ConstantsDDBC as SQL
from .json import Json

_TVPColumn: TypeAlias = tuple[str, int] | tuple[str, int, int] | tuple[str, int, int, int]
_TVPRow: TypeAlias = list[Any] | tuple[Any, ...]
Expand All @@ -21,6 +22,7 @@ class TableValuedParameter:
Columns are ``(name, sql_type[, size_or_precision[, scale]])`` tuples.
Variable-length columns require a size (0 means MAX); DECIMAL/NUMERIC
require precision and scale. Temporal scale defaults to 7.
JSON columns accept ``Json`` or ``None``; size and scale must be omitted or zero.
``type_name`` accepts an unquoted ``schema.Type`` or a type name with the
separate ``schema`` keyword (default ``dbo``). Binding is positional.
"""
Expand Down Expand Up @@ -81,6 +83,8 @@ def __init__(
raise TypeError(f"TVP column {name}: size and scale must be integers")
if not 0 <= size <= 2147483647 or scale < 0:
raise ValueError(f"TVP column {name}: invalid size or scale")
if sql_type == SQL.SQL_JSON.value and (size or scale):
raise ValueError(f"TVP column {name}: JSON size and scale must be zero")
if numeric and not (1 <= size <= 38 and 0 <= scale <= size):
raise ValueError(
f"TVP column {name}: require 1 <= precision <= 38 and scale <= precision"
Expand Down Expand Up @@ -166,6 +170,7 @@ def _validate_row(self, row: _TVPRow, index: int) -> _TVPRow:
93: datetime,
-155: datetime,
-11: UUID,
SQL.SQL_JSON.value: Json,
}
_sizes: ClassVar[dict[int, int]] = {
-7: 1,
Expand Down
191 changes: 191 additions & 0 deletions tests/test_028_table_valued_parameters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Live SQL Server coverage for explicit TVPs and synchronous ODBC streaming."""

import datetime
import json
import os
import subprocess
import sys
Expand All @@ -9,6 +10,7 @@
import weakref
from collections import UserList
from decimal import Decimal, localcontext
from unittest.mock import Mock

import pytest

Expand All @@ -17,6 +19,7 @@
OperationalError,
NotSupportedError,
TableValuedParameter,
Json,
connect,
SQL_INTEGER,
SQL_CHAR,
Expand All @@ -33,6 +36,7 @@
SQL_TYPE_TIME,
SQL_TYPE_TIMESTAMP,
SQL_GUID,
SQL_JSON,
)
from mssql_python.constants import ConstantsDDBC
from test_023_ssh_tunnel_gil_release import (
Expand Down Expand Up @@ -427,6 +431,193 @@ def test_column_sequences_match_public_contract(container):
assert columns == container([("id", SQL_INTEGER), ("label", SQL_WVARCHAR, 100)])


def test_json_column_contract():
snapshot = Json({"v": [None, True]})
row = [snapshot]
for column in (("doc", SQL_JSON), ("doc", SQL_JSON, 0), ("doc", SQL_JSON, 0, 0)):
value = TableValuedParameter("Documents", [column], [row])
assert value._validate_row(row, 0) is row
assert row[0] is snapshot
assert value._validate_row((None,), 1) == (None,)
for invalid in ("{}", {}, [], b"{}", 244):
with pytest.raises(TypeError, match="row 2, column doc"):
value._validate_row((invalid,), 2)
for column in (("doc", SQL_JSON, 1), ("doc", SQL_JSON, 0, 1)):
with pytest.raises(ValueError, match="size and scale"):
TableValuedParameter("Documents", [column], [])
text = TableValuedParameter("Documents", [("doc", SQL_WVARCHAR, 0)], [])
with pytest.raises(TypeError, match="incompatible Python value"):
text._validate_row((snapshot,), 0)


@pytest.fixture
def json_tvp_schema(request):
if os.environ.get("MSSQL_TEST_NATIVE_JSON") != "1":
pytest.skip("Set MSSQL_TEST_NATIVE_JSON=1 with a qualified JSON provider and server")
cursor = request.getfixturevalue("cursor")
cursor.execute("SELECT CAST(N'{}' AS JSON) OPTION (RECOMPILE)")
assert cursor._column_sql_types == [SQL_JSON], "Provider must report native JSON"
schema = request.getfixturevalue("tvp_schema")
connection = request.getfixturevalue("db_connection")
cursor.execute(f"CREATE TYPE [{schema}].Documents AS TABLE (id int, doc json)")
cursor.execute(f"""
CREATE PROCEDURE [{schema}].EchoJson @items [{schema}].Documents READONLY
AS BEGIN
SET NOCOUNT ON;
INSERT INTO [{schema}].Calls VALUES (1);
SELECT id, doc FROM @items ORDER BY id;
SELECT COUNT_BIG(*) FROM @items;
END
""")
connection.commit()
try:
yield schema
finally:
cursor.execute(f"DROP PROCEDURE [{schema}].EchoJson")
cursor.execute(f"DROP TYPE [{schema}].Documents")
connection.commit()


def json_items(schema, rows):
return TableValuedParameter(
"Documents", [("id", SQL_INTEGER), ("doc", SQL_JSON)], rows, schema=schema
)


@pytest.mark.parametrize("empty", [False, True])
@pytest.mark.parametrize("mode", ["text", "objects"])
def test_json_tvp_snapshots_null_lob_results_and_reuse(
json_tvp_schema, cursor, monkeypatch, empty, mode
):
source = {"v": [None, True, "\U0001f600" * 17000]}
snapshot = Json(source)
source["v"].append("not in snapshot")
rows = (
[]
if empty
else [
[1, snapshot],
[2, None],
[3, Json("[]")],
[4, Json(' \n{"key":1,"escaped":"\\u0000\\u03bb"}\t')],
]
)
value = json_items(json_tvp_schema, rows)
for _ in range(2):
cursor.json_output = mode
dumps, loads = Mock(wraps=json.dumps), Mock(wraps=json.loads)
with monkeypatch.context() as patch:
patch.setattr(json, "dumps", dumps)
patch.setattr(json, "loads", loads)
cursor.execute(f"EXEC [{json_tvp_schema}].EchoJson %(items)s", {"items": value})
cursor.json_output = "objects" if mode == "text" else "text"
assert cursor._column_sql_types == [SQL_INTEGER, SQL_JSON]
result = cursor.fetchall()
dumps.assert_not_called()
assert loads.call_count == (3 if mode == "objects" and not empty else 0)
assert cursor.nextset()
assert cursor.fetchval() == len(rows)
assert cursor.nextset() is False
expected = [None if row[1] is None else json.loads(row[1]._text) for row in rows]
actual = [
json.loads(row[1]) if mode == "text" and row[1] is not None else row[1]
for row in result
]
assert actual == expected
if not empty:
assert rows[0][1] is snapshot
assert rows[3][1]._text.startswith(" \n")
cursor.json_output = "text"
assert cursor.execute(f"SELECT COUNT(*) FROM [{json_tvp_schema}].Calls").fetchval() == 2


def test_json_tvp_generator_bounded_and_mixed_parameters(json_tvp_schema, cursor):
live = weakref.WeakSet()
seen = []

class LiveRow(list):
__hash__ = object.__hash__

def rows():
for i in range(1000):
row = LiveRow((i, Json({"n": i})))
live.add(row)
assert len(live) <= 2, "The driver retained earlier JSON rows"
seen.append(i)
yield row

value = json_items(json_tvp_schema, rows())
assert seen == []
cursor.execute(f"EXEC [{json_tvp_schema}].EchoJson ?", value)
assert [json.loads(row[1])["n"] for row in cursor.fetchall()] == list(range(1000))
assert cursor.nextset()
assert cursor.fetchval() == 1000
assert cursor.nextset() is False
assert len(seen) == 1000 and not live
assert cursor.execute(f"SELECT COUNT(*) FROM [{json_tvp_schema}].Calls").fetchval() == 1
scalar = Json({"large": "\U0001f600" * 5000})
cursor.execute(
"SELECT a.doc, b.doc, ? FROM ? AS a CROSS JOIN ? AS b",
scalar,
json_items(json_tvp_schema, [(1, Json({}))]),
json_items(json_tvp_schema, [(2, None)]),
)
row = cursor.fetchone()
assert cursor._column_sql_types == [SQL_JSON, SQL_JSON, SQL_JSON]
assert json.loads(row[0]) == {} and row[1] is None
assert json.loads(row[2]) == json.loads(scalar._text)


@pytest.mark.parametrize("failure", ["source", "cell", "syntax", "null-root"])
def test_json_tvp_failure_preserves_error_and_recovers(json_tvp_schema, cursor, failure):
error = ValueError("JSON row source failed")

def rows():
yield 1, Json({})
if failure == "source":
raise error
yield 2, {"cell": {}, "syntax": Json("{"), "null-root": Json("null")}[failure]

expected_error = {"source": ValueError, "cell": TypeError}.get(failure, DatabaseError)
with pytest.raises(expected_error) as caught:
cursor.execute(f"EXEC [{json_tvp_schema}].EchoJson ?", json_items(json_tvp_schema, rows()))
if failure == "source":
assert caught.value is error
assert cursor.execute("SELECT 42").fetchval() == 42
assert cursor.execute(f"SELECT COUNT(*) FROM [{json_tvp_schema}].Calls").fetchval() == 0
cursor.execute("SELECT doc FROM ?", json_items(json_tvp_schema, [(3, Json([]))]))
assert cursor.fetchval() == "[]"


@pytest.mark.skipif(
os.environ.get("MSSQL_TEST_NATIVE_JSON") == "1",
reason="Unsupported JSON TVP binding requires the shipped driver, not the preview",
)
def test_json_tvp_unsupported_bind_does_not_consume_or_fallback(cursor, tvp_schema):
from mssql_python import get_native_provider_info

if get_native_provider_info()["id"] != "msodbcsql18":
pytest.skip("Tests classic driver's native JSON binding, not alternate-provider guard")
seen = []

def rows():
seen.append(1)
yield 1, Json({})

value = TableValuedParameter(
"Items", [("id", SQL_INTEGER), ("label", SQL_JSON)], rows(), schema=tvp_schema
)
with pytest.raises(NotSupportedError) as caught:
cursor.execute(f"EXEC [{tvp_schema}].CountRows ?", value)
assert caught.value.sqlstate == "HY004"
assert "does not support native JSON binding" in str(caught.value)
assert caught.value.ddbc_error
assert seen == []
assert cursor.execute(f"SELECT COUNT(*) FROM [{tvp_schema}].Calls").fetchval() == 0
cursor.execute(f"EXEC [{tvp_schema}].CountRows ?", items(tvp_schema, [(1, "recovered")]))
assert tuple(cursor.fetchone()) == (1, 1)


def test_row_sequences_match_public_contract(cursor, tvp_schema):
rows = UserList([(1, "one"), [2, None]])
cursor.execute(f"EXEC [{tvp_schema}].CountRows ?", items(tvp_schema, rows))
Expand Down
5 changes: 5 additions & 0 deletions tests/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ def supported_calls(cursor: Cursor) -> None:
)
rows: list[tuple[int]] = [(1,), (2,)]
TableValuedParameter("dbo.IntValues", [("value", SQL_INTEGER)], rows)
documents: list[tuple[int, Json | None]] = [(1, Json({{}})), (2, None)]
cursor.execute(
"SELECT * FROM ?",
TableValuedParameter("dbo.Documents", [("id", SQL_INTEGER), ("doc", SQL_JSON)], documents),
)
""",
encoding="utf-8",
)
Expand Down
Loading