From 276cd3c685af2e833a98eb078217df621ba50fac Mon Sep 17 00:00:00 2001 From: LH-kevin <186923068+LH-kevin@users.noreply.github.com> Date: Mon, 24 Aug 2026 11:45:36 +0800 Subject: [PATCH] fix(python): coerce JSON columns before writes --- python/python/lancedb/table.py | 77 +++++++++++++++++++++++++++---- python/python/tests/test_table.py | 66 ++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 10 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 0c84b4036..806674e2b 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -27,7 +27,7 @@ from typing import ( ) from urllib.parse import urlparse -from lancedb.scannable import _register_optional_converters, to_scannable +from lancedb.scannable import Scannable, _register_optional_converters, to_scannable from . import __version__ from ._blob import ( @@ -448,6 +448,64 @@ def _field_extension_name(field: pa.Field) -> Optional[str]: return extension_name +def _coerce_json_field(field: pa.Field, target_field: pa.Field) -> Optional[pa.Field]: + """Promote compatible JSON input to Arrow's logical JSON type.""" + if _field_extension_name(target_field) != "lance.json": + return None + + if _field_extension_name(field) == "arrow.json": + return field + + if not hasattr(pa, "json_"): + return None + + is_string_like = ( + pa.types.is_string(field.type) + or pa.types.is_large_string(field.type) + or (hasattr(pa.types, "is_string_view") and pa.types.is_string_view(field.type)) + ) + if is_string_like or pa.types.is_null(field.type): + return pa.field( + field.name, + pa.json_(), + nullable=field.nullable, + metadata=field.metadata, + ) + + return None + + +def _coerce_json_scannable(data: Scannable, target_schema: pa.Schema) -> Scannable: + """Promote JSON-compatible columns without sanitizing unrelated columns.""" + target_fields = {field.name: field for field in target_schema} + fields = [] + changed = False + + for field in data.schema: + target_field = target_fields.get(field.name) + coerced = ( + _coerce_json_field(field, target_field) + if target_field is not None + else None + ) + if coerced is not None: + fields.append(coerced) + changed = changed or coerced != field + else: + fields.append(field) + + if not changed: + return data + + schema = pa.schema(fields, metadata=data.schema.metadata) + return Scannable( + schema=schema, + num_rows=data.num_rows, + reader=lambda: _cast_to_target_schema(data.reader(), schema), + rescannable=data.rescannable, + ) + + def _align_field_types( fields: List[pa.Field], target_fields: List[pa.Field], @@ -460,15 +518,12 @@ def _align_field_types( target_field = next((f for f in target_fields if f.name == field.name), None) if target_field is None: raise ValueError(f"Field '{field.name}' not found in target schema") - # Preserve arrow.json input until it reaches Lance. LanceDB exposes stored - # JSON columns as lance.json (JSONB-backed LargeBinary), but casting the - # input to that storage type here merely relabels the raw JSON bytes as - # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. - if ( - _field_extension_name(field) == "arrow.json" - and _field_extension_name(target_field) == "lance.json" - ): - new_fields.append(field) + # LanceDB exposes stored JSON columns as lance.json (JSONB-backed + # LargeBinary). Keep logical JSON input as arrow.json so Lance performs + # the JSONB encoding instead of relabeling raw UTF-8 bytes as JSONB. + json_field = _coerce_json_field(field, target_field) + if json_field is not None: + new_fields.append(json_field) continue if pa.types.is_struct(target_field.type): if pa.types.is_struct(field.type): @@ -5413,6 +5468,8 @@ class AsyncTable: ) _register_optional_converters() data = to_scannable(data) + if mode in (None, "append"): + data = _coerce_json_scannable(data, schema) progress, owns = _normalize_progress(progress) try: return await self._inner.add( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 0f98219bf..9e4919bf0 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2822,6 +2822,72 @@ async def test_add_sanitization_encodes_json(mem_db_async: AsyncConnection): assert rows == [{"id": "c", "j": '{"k":3}'}] +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +@pytest.mark.parametrize("input_kind", ["arrow", "pylist"]) +@pytest.mark.parametrize("mode", ["append", None]) +@pytest.mark.asyncio +async def test_add_coerces_string_json( + mem_db_async: AsyncConnection, input_kind: str, mode: str | None +): + json_type = pa.json_() + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", json_type)]) + table = await mem_db_async.create_table(f"json_add_{input_kind}", schema=schema) + + if input_kind == "arrow": + data = pa.table({"id": ["a"], "j": ['{"k": 4}']}) + else: + data = [{"id": "a", "j": '{"k": 4}'}] + + await table.add(data, mode=mode) + + rows = await table.query().where("json_extract(j, '$.k') = '4'").to_list() + assert rows == [{"id": "a", "j": '{"k":4}'}] + + +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +@pytest.mark.asyncio +async def test_add_coerces_null_json(mem_db_async: AsyncConnection): + json_type = pa.json_() + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", json_type)]) + table = await mem_db_async.create_table("json_add_null", schema=schema) + + await table.add([{"id": "a", "j": None}]) + + rows = await table.query().where("j IS NULL").to_list() + assert rows == [{"id": "a", "j": None}] + + +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +@pytest.mark.asyncio +async def test_merge_insert_coerces_string_json(mem_db_async: AsyncConnection): + json_type = pa.json_() + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", json_type)]) + + json_values = pa.ExtensionArray.from_storage( + json_type, + pa.array(['{"k": 1}', None], type=json_type.storage_type), + ) + initial = pa.Table.from_arrays( + [pa.array(["a", "b"]), json_values], + schema=schema, + ) + + table = await mem_db_async.create_table("json_merge_string", schema=schema) + await table.add(initial) + + await ( + table.merge_insert("id") + .when_matched_update_all() + .execute(pa.table({"id": ["a"], "j": ['{"k": 5}']})) + ) + + rows = await table.query().where("json_extract(j, '$.k') = '5'").to_list() + assert rows == [{"id": "a", "j": '{"k":5}'}] + + null_rows = await table.query().where("j IS NULL").to_list() + assert null_rows == [{"id": "b", "j": None}] + + def test_create_with_embedding_function(mem_db: DBConnection): class MyTable(LanceModel): text: str