diff --git a/sqlit/domains/connections/providers/mssql/adapter.py b/sqlit/domains/connections/providers/mssql/adapter.py index ce02c3d1..538efe4d 100644 --- a/sqlit/domains/connections/providers/mssql/adapter.py +++ b/sqlit/domains/connections/providers/mssql/adapter.py @@ -103,6 +103,35 @@ def _is_use_unsupported_error(exc: Exception) -> bool: return "USE statement is not supported" in str(exc) +# SQL Server returns `SELECT ... FOR JSON` / `FOR XML` output as a single +# column with this fixed name, split over many rows of roughly 2,033 +# characters each. No single row is a valid document on its own. +_DOCUMENT_COLUMNS = { + "JSON_F52E2B61-18A1-11D1-B105-00805F49916B", + "XML_F52E2B61-18A1-11D1-B105-00805F49916B", +} + + +def _fetch_result(cursor: Any, max_rows: int | None) -> tuple[list[str], list[tuple], bool]: + """Fetch the current result set, joining FOR JSON/FOR XML chunks into one cell.""" + columns = [col[0] for col in cursor.description] + if len(columns) == 1 and isinstance(columns[0], str) and columns[0].upper() in _DOCUMENT_COLUMNS: + # The chunks are one document: fetch them all, whatever the row limit, + # so the value viewer gets complete JSON/XML it can format. + chunks = cursor.fetchall() + document = "".join(str(row[0]) for row in chunks if row[0] is not None) + return columns, [(document,)] if chunks else [], False + if max_rows is not None: + rows = cursor.fetchmany(max_rows + 1) + truncated = len(rows) > max_rows + if truncated: + rows = rows[:max_rows] + else: + rows = cursor.fetchall() + truncated = False + return columns, [tuple(row) for row in rows], truncated + + class SQLServerAdapter(DatabaseAdapter): """Adapter for Microsoft SQL Server using the mssql-python driver.""" @@ -824,15 +853,7 @@ def execute_query(self, conn: Any, query: str, max_rows: int | None = None) -> t result: tuple[list[str], list[tuple], bool] | None = None while True: if cursor.description and result is None: - columns = [col[0] for col in cursor.description] - if max_rows is not None: - rows = cursor.fetchmany(max_rows + 1) - truncated = len(rows) > max_rows - rows = rows[:max_rows] - else: - rows = cursor.fetchall() - truncated = False - result = (columns, [tuple(row) for row in rows], truncated) + result = _fetch_result(cursor, max_rows) nextset = getattr(cursor, "nextset", None) if not callable(nextset) or not nextset(): @@ -840,16 +861,7 @@ def execute_query(self, conn: Any, query: str, max_rows: int | None = None) -> t return result or ([], [], False) if cursor.description: - columns = [col[0] for col in cursor.description] - if max_rows is not None: - rows = cursor.fetchmany(max_rows + 1) - truncated = len(rows) > max_rows - if truncated: - rows = rows[:max_rows] - else: - rows = cursor.fetchall() - truncated = False - return columns, [tuple(row) for row in rows], truncated + return _fetch_result(cursor, max_rows) return [], [], False def execute_non_query(self, conn: Any, query: str) -> int: diff --git a/tests/unit/test_mssql_for_json.py b/tests/unit/test_mssql_for_json.py new file mode 100644 index 00000000..0d665a5c --- /dev/null +++ b/tests/unit/test_mssql_for_json.py @@ -0,0 +1,59 @@ +"""SQL Server splits FOR JSON / FOR XML output over many rows; sqlit shows one document (#336).""" + +from __future__ import annotations + +import json + +from sqlit.domains.connections.providers.mssql.adapter import SQLServerAdapter + +FOR_JSON_COLUMN = "JSON_F52E2B61-18A1-11d1-B105-00805F49916B" + + +class _Cursor: + def __init__(self, column: str, rows: list[tuple]): + self.description = [(column, None, None, None, None, None, None)] + self._rows = rows + + def execute(self, query): + pass + + def fetchall(self): + rows, self._rows = self._rows, [] + return rows + + def fetchmany(self, n): + rows, self._rows = self._rows[:n], self._rows[n:] + return rows + + +class _Conn: + def __init__(self, cursor): + self._cursor = cursor + + def cursor(self): + return self._cursor + + +def _chunks(document: str, size: int = 2033) -> list[tuple]: + return [(document[i : i + size],) for i in range(0, len(document), size)] + + +def test_for_json_chunks_become_one_valid_document_even_past_the_row_limit(): + document = json.dumps([{"id": i, "name": f"Customer {i}"} for i in range(500)], separators=(",", ":")) + conn = _Conn(_Cursor(FOR_JSON_COLUMN, _chunks(document))) + + columns, rows, truncated = SQLServerAdapter().execute_query(conn, "SELECT * FROM t FOR JSON PATH", max_rows=3) + + assert columns == [FOR_JSON_COLUMN] + assert rows == [(document,)] + assert truncated is False + assert len(json.loads(rows[0][0])) == 500 + + +def test_ordinary_single_column_results_are_untouched(): + conn = _Conn(_Cursor(FOR_JSON_COLUMN + "_label", [("a",), ("b",), ("c",)])) + + columns, rows, truncated = SQLServerAdapter().execute_query(conn, "SELECT name FROM t", max_rows=2) + + assert rows == [("a",), ("b",)] + assert truncated is True