diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index e325e7361..5ab32d81c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -790,6 +790,47 @@ def _cast_to_target_schema( return pa.RecordBatchReader.from_batches(reordered_schema, gen()) +_PRIMARY_KEY_METADATA_KEYS = ( + b"lance-schema:unenforced-primary-key", + b"lance-schema:unenforced-primary-key:position", +) + + +def _drop_nullable_primary_key(reader: pa.RecordBatchReader) -> pa.RecordBatchReader: + """Remove the table's primary key markers from source fields that allow nulls. + + Casting to the table schema copies the table's field metadata but keeps the + source's nullability, and Lance rejects a schema with a nullable primary key. + merge_insert reads the key from the table, and the write still rejects null + keys. + """ + schema = pa.schema( + [_drop_primary_key(field, False) for field in reader.schema], + metadata=reader.schema.metadata, + ) + if schema.equals(reader.schema, check_metadata=True): + return reader + return pa.RecordBatchReader.from_batches( + schema, + (pa.RecordBatch.from_arrays(batch.columns, schema=schema) for batch in reader), + ) + + +def _drop_primary_key(field: pa.Field, nullable_ancestor: bool) -> pa.Field: + nullable = nullable_ancestor or field.nullable + if pa.types.is_struct(field.type): + field = field.with_type( + pa.struct([_drop_primary_key(child, nullable) for child in field.type]) + ) + metadata = field.metadata or {} + if nullable and any(key in metadata for key in _PRIMARY_KEY_METADATA_KEYS): + kept = { + k: v for k, v in metadata.items() if k not in _PRIMARY_KEY_METADATA_KEYS + } + field = field.with_metadata(kept) if kept else field.remove_metadata() + return field + + def _preserve_blob_v2_fields( inferred_schema: pa.Schema, existing_schema: pa.Schema ) -> pa.Schema: @@ -8965,6 +9006,7 @@ class AsyncTable: ) if isinstance(data, pa.Table): data = pa.RecordBatchReader.from_batches(data.schema, data.to_batches()) + data = _drop_nullable_primary_key(data) return await self._inner.execute_merge_insert( data, dict( diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 5aae68a1c..684702d78 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -470,6 +470,61 @@ async def test_merge_retry_override_isolation(sync_api): await check(await db.open_table("test")) +@pytest.mark.parametrize("sync_api", [False, True]) +@pytest.mark.asyncio +async def test_merge_insert_nullable_source_into_primary_key(sync_api): + # The table's primary key marker must not reach the server on a nullable + # source field: Lance rejects that schema before merging. + sent = [] + + def handler(request): + if request.path == "/v1/table/test/describe/": + key = {"lance-schema:unenforced-primary-key:position": "1"} + fields = [ + { + "name": "id", + "type": {"type": "int64"}, + "nullable": False, + "metadata": key, + }, + {"name": "n", "type": {"type": "int64"}, "nullable": True}, + ] + send_json(request, {"version": 1, "schema": {"fields": fields}}) + return + assert urlparse(request.path).path == "/v1/table/test/merge_insert/" + body = bytearray() + if request.headers.get("Transfer-Encoding") == "chunked": + while size := int(request.rfile.readline().split(b";")[0], 16): + body.extend(request.rfile.read(size)) + request.rfile.read(2) + else: + body.extend( + request.rfile.read(int(request.headers.get("Content-Length", 0))) + ) + sent.append(pa.ipc.open_stream(body).read_all()) + send_json(request, {"version": 2}) + + rows = [{"id": 1, "n": 10}, {"id": 2, "n": 20}] + if sync_api: + with mock_lancedb_connection(handler) as db: + merge = db.open_table("test").merge_insert("id") + merge.when_matched_update_all().when_not_matched_insert_all().execute(rows) + else: + async with mock_lancedb_connection_async(handler) as db: + merge = (await db.open_table("test")).merge_insert("id") + await ( + merge.when_matched_update_all() + .when_not_matched_insert_all() + .execute(rows) + ) + + assert len(sent) == 1 + assert sent[0].to_pylist() == rows + key = sent[0].schema.field("id") + assert key.nullable + assert not key.metadata + + @pytest.fixture def missing_table_handler(cached, namespace_path): request_ids = [] diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 7ec1e8dd6..e1ee08711 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4206,6 +4206,119 @@ def test_merge_insert_nullable_pandas_into_pydantic_schema(mem_db: DBConnection) assert table.to_arrow().sort_by("id") == expected +_PK_POSITION = {b"lance-schema:unenforced-primary-key:position": b"1"} + + +def _primary_key_table(db: DBConnection) -> LanceTable: + schema = pa.schema( + [pa.field("id", pa.string(), nullable=False), pa.field("n", pa.int64())] + ) + table = db.create_table( + "pk", pa.Table.from_pylist([{"id": "a", "n": 1}, {"id": "b", "n": 2}], schema) + ) + table.set_unenforced_primary_key("id") + return table + + +@pytest.mark.parametrize("source", ["pandas", "pylist", "arrow"]) +@pytest.mark.parametrize("where", [None, "target.n < source.n"]) +def test_merge_insert_nullable_source_into_primary_key( + mem_db: DBConnection, source, where +): + # Pandas, dicts and inferred Arrow give a nullable key column. Lance rejects + # a source schema that marks a nullable field as the primary key, so the + # table's key marker must not be copied onto it. + table = _primary_key_table(mem_db) + rows = [{"id": "b", "n": 20}, {"id": "c", "n": 30}] + if source == "pandas": + rows = pytest.importorskip("pandas").DataFrame(rows) + elif source == "arrow": + rows = pa.Table.from_pylist(rows) + + result = ( + table.merge_insert("id") + .when_matched_update_all(where=where) + .when_not_matched_insert_all() + .execute(rows) + ) + + assert (result.num_updated_rows, result.num_inserted_rows) == (1, 1) + assert table.to_arrow().sort_by("id").to_pylist() == [ + {"id": "a", "n": 1}, + {"id": "b", "n": 20}, + {"id": "c", "n": 30}, + ] + assert table.schema.field("id").metadata == _PK_POSITION + + +def test_merge_insert_null_primary_key_rejected(mem_db: DBConnection): + table = _primary_key_table(mem_db) + rows = [{"id": None, "n": 9}, {"id": "c", "n": 30}] + with pytest.raises(ValueError, match="contained null values"): + ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(rows) + ) + assert table.count_rows() == 2 + + +def test_merge_insert_nullable_struct_source_into_nested_primary_key( + mem_db: DBConnection, +): + # Lance also rejects a primary key under a nullable ancestor, whatever the + # merge key is. + key = pa.field("s", pa.struct([pa.field("id", pa.int64(), nullable=False)]), False) + schema = pa.schema([key, pa.field("n", pa.int64())]) + table = mem_db.create_table( + "pk", pa.Table.from_pylist([{"s": {"id": 1}, "n": 1}], schema) + ) + table.set_unenforced_primary_key("s.id") + + result = ( + table.merge_insert("n") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute([{"s": {"id": 5}, "n": 1}, {"s": {"id": 2}, "n": 20}]) + ) + + assert (result.num_updated_rows, result.num_inserted_rows) == (1, 1) + assert table.to_arrow().sort_by("n").to_pylist() == [ + {"s": {"id": 5}, "n": 1}, + {"s": {"id": 2}, "n": 20}, + ] + + +@pytest.mark.asyncio +async def test_merge_insert_nullable_source_into_primary_key_async( + mem_db_async: AsyncConnection, +): + pd = pytest.importorskip("pandas") + schema = pa.schema( + [pa.field("id", pa.string(), nullable=False), pa.field("n", pa.int64())] + ) + table = await mem_db_async.create_table( + "pk", pa.Table.from_pylist([{"id": "a", "n": 1}, {"id": "b", "n": 2}], schema) + ) + await table.set_unenforced_primary_key("id") + + result = await ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(pd.DataFrame({"id": ["b", "c"], "n": [20, 30]})) + ) + + assert (result.num_updated_rows, result.num_inserted_rows) == (1, 1) + assert (await table.to_arrow()).sort_by("id").to_pylist() == [ + {"id": "a", "n": 1}, + {"id": "b", "n": 20}, + {"id": "c", "n": 30}, + ] + assert (await table.schema()).field("id").metadata == _PK_POSITION + + def test_merge_insert_by_source_delete_expr(mem_db: DBConnection): table = mem_db.create_table( "my_table",