diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index ce0866c8f..9f3cddfc1 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -49,6 +49,7 @@ dedupe_keys, find_spatialite, hash_record, + np, progressbar, sqlite3, suggest_column_types, @@ -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") ) @@ -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", @@ -5345,11 +5341,19 @@ def lookup( self.create_index(lookup_values.keys(), unique=True) # IS rather than = so that null values are matched correctly wheres = [f"{quote_identifier(column)} IS ?" for column in lookup_values] - rows = list( - self.rows_where( - " and ".join(wheres), [value for _, value in lookup_values.items()] - ) - ) + where = " and ".join(wheres) + raw_params = list(lookup_values.values()) + params = [] + has_numpy_bool = False + for value in raw_params: + if np is not None and isinstance(value, np.bool_): + value = jsonify_if_needed(value) + has_numpy_bool = True + params.append(value) + rows = list(self.rows_where(where, params)) + if not rows and has_numpy_bool: + # Older versions let SQLite bind NumPy booleans as one-byte blobs. + rows = list(self.rows_where(where, raw_params)) try: return rows[0][resolve_casing(pk, rows[0])] except IndexError: @@ -5695,7 +5699,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_)): # sqlite3 would otherwise store the raw buffer as a BLOB return cast(Any, value).item() if isinstance(value, (dict, list, tuple)): diff --git a/sqlite_utils/utils.py b/sqlite_utils/utils.py index 49c218750..6d56ff222 100644 --- a/sqlite_utils/utils.py +++ b/sqlite_utils/utils.py @@ -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", @@ -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__) diff --git a/tests/test_create.py b/tests/test_create.py index fcd9eee34..35f01a234 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -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")] diff --git a/tests/test_lookup.py b/tests/test_lookup.py index f96cfefaf..bdd3eeefa 100644 --- a/tests/test_lookup.py +++ b/tests/test_lookup.py @@ -171,6 +171,31 @@ def test_lookup_null_value_idempotent(fresh_db): assert list(species.rows) == [{"id": first_id, "name": None}] +def test_lookup_numpy_boolean_idempotent(fresh_db): + np = pytest.importorskip("numpy") + settings = fresh_db.table("settings") + false_id = settings.lookup({"enabled": np.bool_(False)}) + true_id = settings.lookup({"enabled": np.bool_(True)}) + + assert false_id != true_id + assert settings.lookup({"enabled": np.bool_(False)}) == false_id + assert settings.lookup({"enabled": np.bool_(True)}) == true_id + assert settings.lookup({"enabled": True}) == true_id + assert list(settings.rows) == [ + {"id": false_id, "enabled": 0}, + {"id": true_id, "enabled": 1}, + ] + + +def test_lookup_numpy_boolean_finds_legacy_blob(fresh_db): + np = pytest.importorskip("numpy") + settings = fresh_db.table("settings").create({"id": int, "enabled": bool}, pk="id") + settings.insert({"id": 7, "enabled": b"\x01"}) + + assert settings.lookup({"enabled": np.bool_(True)}) == 7 + assert settings.count == 1 + + def test_lookup_compound_key_with_null_idempotent(fresh_db): species = fresh_db.table("species") palm_id = species.lookup({"name": "Palm", "type": None})