diff --git a/python/python/lancedb/util.py b/python/python/lancedb/util.py index a68c9ec49..67bffbc97 100644 --- a/python/python/lancedb/util.py +++ b/python/python/lancedb/util.py @@ -11,6 +11,7 @@ import pathlib import warnings from datetime import date, datetime, time, timedelta from decimal import Decimal +from enum import Enum from functools import singledispatch from typing import Tuple, Union, Optional, Any, List from urllib.parse import urlparse @@ -384,7 +385,8 @@ def _(value: bytes): @value_to_sql.register(int) def _(value: int): - return str(value) + # int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH". + return str(int(value)) @value_to_sql.register(float) @@ -396,7 +398,7 @@ def _(value: float): return ( "CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)" ) - return str(value) + return str(float(value)) @value_to_sql.register(Decimal) @@ -417,6 +419,12 @@ def _(value: type(None)): return "NULL" +@value_to_sql.register(Enum) +def _(value: Enum): + # Write the member's value, as model_to_dict does for a LanceModel field. + return value_to_sql(value.value) + + @value_to_sql.register(datetime) def _(value: datetime): return f"'{value.isoformat()}'" diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index 5f444ac44..17758c41e 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path): assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0 +def test_value_to_sql_enum_members(tmp_path): + # str() of an int- or float-valued Enum member is its name, which SQL reads + # as a field access, and a plain Enum member raised NotImplementedError. + import enum + + class Priority(int, enum.Enum): + LOW = 1 + HIGH = 2 + + class Weight(float, enum.Enum): + HALF = 0.5 + + class Color(enum.Enum): + RED = "red" + + assert value_to_sql(Priority.HIGH) == "2" + assert value_to_sql(Weight.HALF) == "0.5" + assert value_to_sql(Color.RED) == "'red'" + + db = lancedb.connect(tmp_path) + table = db.create_table( + "test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]}) + ) + table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED}) + assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}] + + def test_append_vector_columns(): registry = EmbeddingFunctionRegistry.get_instance() registry.register("test")(MockTextEmbeddingFunction)