Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
dedupe_keys,
find_spatialite,
hash_record,
np,
progressbar,
sqlite3,
suggest_column_types,
Expand Down Expand Up @@ -174,12 +175,6 @@ def resolve_casing(name: str, candidates: Iterable[str]) -> str:
except ImportError:
pd = None

np: Any = None
try:
np = importlib.import_module("numpy")
except ImportError:
np = None

Column = namedtuple(
"Column", ("cid", "name", "type", "notnull", "default_value", "is_pk")
)
Expand Down Expand Up @@ -411,6 +406,7 @@ def _iter_complete_sql_statements(sql: str) -> Generator[str, None, None]:
try:
COLUMN_TYPE_MAPPING.update(
{
np.bool_: "INTEGER",
np.int8: "INTEGER",
np.int16: "INTEGER",
np.int32: "INTEGER",
Expand Down Expand Up @@ -5695,7 +5691,7 @@ def drop(self, ignore: bool = False) -> None:
def jsonify_if_needed(value: object) -> object:
if isinstance(value, decimal.Decimal):
return float(value)
if np is not None and isinstance(value, (np.integer, np.floating)):
if np is not None and isinstance(value, (np.integer, np.floating, np.bool_)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize NumPy booleans in lookup predicates too

For a lookup table pre-created with an enabled column typed as bool, calling table.lookup({'enabled': np.bool_(True)}) twice now raises IntegrityError on the second call instead of returning the existing ID. This conversion stores integer 1, but Table.lookup() still forwards the original scalar to rows_where(), where SQLite binds it as a BLOB. The query therefore misses the row and attempts an insertion that violates the unique index. Previously both operations used the BLOB representation and the lookup succeeded. Normalize lookup predicate values with the same conversion to preserve idempotency.

Useful? React with 👍 / 👎.

# sqlite3 would otherwise store the raw buffer as a BLOB
return cast(Any, value).item()
if isinstance(value, (dict, list, tuple)):
Expand Down
12 changes: 12 additions & 0 deletions sqlite_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@
OperationalError = dbapi2.OperationalError


np: Any = None
try:
np = importlib.import_module("numpy")
except ImportError:
np = None

_NUMPY_BOOL_TYPE: type | None = getattr(np, "bool_", None)


SPATIALITE_PATHS = (
"/usr/lib/x86_64-linux-gnu/mod_spatialite.so",
"/usr/lib/aarch64-linux-gnu/mod_spatialite.so",
Expand Down Expand Up @@ -142,6 +151,9 @@ def types_for_column_types(
) -> dict[str, type]:
column_types: dict[str, type] = {}
for key, types in all_column_types.items():
if _NUMPY_BOOL_TYPE is not None and _NUMPY_BOOL_TYPE in types:
types.remove(_NUMPY_BOOL_TYPE)
types.add(bool)
# Ignore null values if at least one other type present:
if len(types) > 1:
types.discard(None.__class__)
Expand Down
18 changes: 18 additions & 0 deletions tests/test_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -1822,3 +1822,21 @@ def test_insert_raw_numpy_scalars(fresh_db):
("integer", "real"),
("integer", "real"),
]


@pytest.mark.parametrize("schema", ["inferred", "python_bool", "numpy_bool", "mixed"])
def test_insert_numpy_booleans(fresh_db, schema):
np = pytest.importorskip("numpy")
table = fresh_db.table("t")
if schema == "python_bool":
table.create({"enabled": bool})
elif schema == "numpy_bool":
table.create({"enabled": np.bool_})

values = [True if schema == "mixed" else np.bool_(True), np.bool_(False)]
table.insert_all([{"enabled": value} for value in values])

assert table.columns_dict == {"enabled": int}
assert fresh_db.execute(
"select enabled, typeof(enabled) from t order by rowid"
).fetchall() == [(1, "integer"), (0, "integer")]
Loading