diff --git a/docs/web/integrations/data/pydantic.mdx b/docs/web/integrations/data/pydantic.mdx index 132ce7801..2789d6dec 100644 --- a/docs/web/integrations/data/pydantic.mdx +++ b/docs/web/integrations/data/pydantic.mdx @@ -76,6 +76,8 @@ Current supported type conversions: | `list` | `pyarrow.List` | | `BaseModel` | `pyarrow.Struct` | | `Vector(n)` | `pyarrow.FixedSizeList(float32, n)` | +| `Literal["a", "b"]` | the Arrow type of its values, here `pyarrow.utf8()`; every value must have the same type | +| `Literal["a", None]` | the same type, nullable, like `Optional[Literal["a"]]` | LanceDB supports to create Apache Arrow Schema from a `pydantic.BaseModel` diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index df38ec53b..c5f25224a 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -257,7 +257,8 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: return pa.duration("us") elif get_origin(py_type) is Literal: # Store a Literal as the type of its values, e.g. Literal["a", "b"] as utf8. - value_types = {type(value) for value in get_args(py_type)} + # A None value makes the field nullable and has no type of its own. + value_types = {type(value) for value in _literal_values_without_none(py_type)} if len(value_types) != 1: raise TypeError( "Converting Pydantic type to Arrow Type: unsupported type " @@ -346,7 +347,29 @@ def _pydantic_list_child_to_arrow(child: Any, field: FieldInfo) -> pa.DataType: return pa.list_(_pydantic_type_to_arrow_type(child, field)) +def _literal_values_without_none(literal: Any) -> tuple: + """Return the values of a Literal, dropping None, which makes it nullable. + + A plain Enum member is stored as its value and does not equal it, so a + nullable Literal of one could not be read back. Its None is kept, and the + Literal is rejected for mixing value types, as it was before None counted + as nullability. + """ + values = get_args(literal) + non_none = tuple(value for value in values if value is not None) + if any(isinstance(v, Enum) and not isinstance(v, type(v.value)) for v in non_none): + return values + return non_none + + def _unwrap_optional_annotation(annotation: Any) -> Any | None: + if get_origin(annotation) is Literal: + # Literal["a", None] is the same type as Optional[Literal["a"]] (PEP 586). + values = get_args(annotation) + non_none = _literal_values_without_none(annotation) + if non_none and len(non_none) != len(values): + return Literal[non_none] + return None if isinstance(annotation, (_GenericAlias, GenericAlias)): origin = annotation.__origin__ args = annotation.__args__ diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index ed0423868..aea874586 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -1254,6 +1254,67 @@ def test_literal_with_mixed_value_types_raises_type_error(annotation): pydantic_to_schema(TestModel) +def test_literal_with_none_is_nullable(): + # Literal["a", None] is the same type as Optional[Literal["a"]] (PEP 586) + class TestModel(pydantic.BaseModel): + status: Literal["todo", "done", None] = None + opt_status: Optional[Literal["todo", None]] = None + tags: List[Literal["a", "b", None]] + + schema = pydantic_to_schema(TestModel) + + assert schema.field("status").type == pa.utf8() + assert schema.field("status").nullable + assert schema.field("opt_status").type == pa.utf8() + assert schema.field("opt_status").nullable + assert schema.field("tags").type == pa.list_(pa.field("item", pa.utf8(), True)) + + +def test_literal_with_none_round_trip(mem_db): + class TestModel(LanceModel): + status: Literal["todo", "done", None] = None + vector: Vector(2) + + rows = [ + TestModel(status="done", vector=[1.0, 2.0]), + TestModel(status=None, vector=[3.0, 4.0]), + ] + tbl = mem_db.create_table("test", schema=TestModel) + tbl.add(rows) + + assert tbl.search().to_pydantic(TestModel) == rows + + +def test_literal_of_plain_enum_with_none_raises_type_error(): + # The stored value "red" would not validate against Color.RED on read. + class Color(Enum): + RED = "red" + + for annotation in (Literal[Color.RED, None], Optional[Literal[Color.RED, None]]): + TestModel = pydantic.create_model("TestModel", color=(annotation, None)) + + with pytest.raises(TypeError, match="same type"): + pydantic_to_schema(TestModel) + + +def test_literal_of_str_enum_with_none_round_trip(mem_db): + class Color(str, Enum): + RED = "red" + + class TestModel(LanceModel): + color: Literal[Color.RED, None] = None + vector: Vector(2) + + rows = [ + TestModel(color=Color.RED, vector=[1.0, 2.0]), + TestModel(color=None, vector=[3.0, 4.0]), + ] + tbl = mem_db.create_table("test", schema=TestModel) + tbl.add(rows) + + assert tbl.search().to_pydantic(TestModel) == rows + + def test_literal_time_and_timedelta_round_trip(mem_db): class TestModel(LanceModel): status: Literal["todo", "done"]