mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix(python): handle JSON schema callbacks on LanceModel fields (#5300)
Fixes #5299. Pydantic accepts a callback in `Field(json_schema_extra=...)` for customizing a field's JSON Schema. Creating an Embedded table from a model with such a field raised `AttributeError` when LanceDB tried to read embedding metadata with `.get()`. Read LanceDB metadata from mapping-style extras and leave callbacks to Pydantic. The regression test creates a table with the expected Arrow string column, then verifies that the callback still removes the field's default from its JSON Schema. ### Validation - The new test failed with the reported exception on `9a79107` before the fix. - All 97 tests in `test_pydantic.py` and `test_embedding_field_metadata.py` passed on Python 3.11.15 with Pydantic 2.13.4, using the checkout's Python sources and the published 0.42.0b38 native extension. - Verified create, insert and read-back on Python 3.12.7 with Pydantic 2.14.4. Ruff lint and formatting checks passed for the Python SDK.
This commit is contained in:
@@ -9,6 +9,7 @@ import inspect
|
||||
import sys
|
||||
import types
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Mapping
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from enum import Enum
|
||||
from typing import (
|
||||
@@ -570,10 +571,9 @@ class LanceModel(pydantic.BaseModel):
|
||||
|
||||
|
||||
def get_extras(field_info: FieldInfo, key: str) -> Any:
|
||||
"""
|
||||
Get the extra metadata from a Pydantic FieldInfo.
|
||||
"""
|
||||
return (field_info.json_schema_extra or {}).get(key)
|
||||
"""Read LanceDB metadata from the mapping form of Pydantic's JSON Schema extras."""
|
||||
extras = field_info.json_schema_extra
|
||||
return extras.get(key) if isinstance(extras, Mapping) else None
|
||||
|
||||
|
||||
def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]:
|
||||
|
||||
@@ -592,6 +592,19 @@ def test_lance_model():
|
||||
assert t == TestModel(vec=[0.0] * 16, li=[1, 2, 3])
|
||||
|
||||
|
||||
def test_lance_model_with_json_schema_callback(mem_db):
|
||||
def remove_default(schema):
|
||||
del schema["default"]
|
||||
|
||||
class Document(LanceModel):
|
||||
text: str = Field(default="", json_schema_extra=remove_default)
|
||||
|
||||
table = mem_db.create_table("documents", schema=Document)
|
||||
assert table.schema == pa.schema([pa.field("text", pa.string(), nullable=False)])
|
||||
field_schema = Document.model_json_schema()["properties"]["text"]
|
||||
assert "default" not in field_schema
|
||||
|
||||
|
||||
def test_optional_nested_model():
|
||||
class WAMedia(BaseModel):
|
||||
url: str
|
||||
|
||||
Reference in New Issue
Block a user