Use hashlib.file_digest for database hashes

Inline the SHA-256 file digest in Database.hash and remove inspect_hash and HASH_BLOCK_SIZE. hashlib.file_digest has been available since Python 3.11.
This commit is contained in:
Simon Willison 2026-10-12 12:12:52 -07:00
commit c435a80030
2 changed files with 2 additions and 19 deletions

View file

@ -17,7 +17,6 @@ import sqlite_utils
from opentelemetry import context as otel_context_api
from opentelemetry.trace import Status, StatusCode
from .inspect import inspect_hash
from .telemetry import (
callback_name,
linked_root_span_kwargs,
@ -835,7 +834,8 @@ class Database:
return self.cached_hash
else:
p = Path(self.path)
self.cached_hash = inspect_hash(p)
with p.open("rb") as fp:
self.cached_hash = hashlib.file_digest(fp, "sha256").hexdigest()
return self.cached_hash
@property

View file

@ -1,5 +1,3 @@
import hashlib
from .utils import (
detect_fts,
detect_primary_keys,
@ -10,21 +8,6 @@ from .utils import (
table_columns,
)
HASH_BLOCK_SIZE = 1024 * 1024
def inspect_hash(path):
"""Calculate the hash of a database, efficiently."""
m = hashlib.sha256()
with path.open("rb") as fp:
while True:
data = fp.read(HASH_BLOCK_SIZE)
if not data:
break
m.update(data)
return m.hexdigest()
def inspect_views(conn):
"""List views in a database."""