Defer DB initialization to first use

Move SQLite schema creation from import time to the first
actual DB operation, which happens in a background thread.
Avoids blocking ComfyUI startup on slow storage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-22 14:03:11 +01:00
parent 43a4fdee16
commit 161da60537

View File

@@ -33,16 +33,19 @@ class UsageTracker:
def __init__(self, db_path=DB_PATH): def __init__(self, db_path=DB_PATH):
self._db_path = db_path self._db_path = db_path
self._lock = threading.Lock() self._lock = threading.Lock()
self._init_db() self._initialized = False
def _init_db(self): def _ensure_db(self):
with self._lock: """Create tables on first use. Called under self._lock."""
conn = sqlite3.connect(self._db_path) if self._initialized:
try: return
conn.executescript(SCHEMA) conn = sqlite3.connect(self._db_path)
conn.commit() try:
finally: conn.executescript(SCHEMA)
conn.close() conn.commit()
finally:
conn.close()
self._initialized = True
def _connect(self): def _connect(self):
return sqlite3.connect(self._db_path) return sqlite3.connect(self._db_path)
@@ -51,6 +54,7 @@ class UsageTracker:
"""Record usage of a set of class_types from a single prompt execution.""" """Record usage of a set of class_types from a single prompt execution."""
now = datetime.now(timezone.utc).isoformat() now = datetime.now(timezone.utc).isoformat()
with self._lock: with self._lock:
self._ensure_db()
conn = self._connect() conn = self._connect()
try: try:
for ct in class_types: for ct in class_types:
@@ -74,6 +78,7 @@ class UsageTracker:
def get_node_stats(self): def get_node_stats(self):
"""Return raw per-node usage data.""" """Return raw per-node usage data."""
with self._lock: with self._lock:
self._ensure_db()
conn = self._connect() conn = self._connect()
try: try:
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
@@ -171,6 +176,7 @@ class UsageTracker:
def _get_first_prompt_time(self): def _get_first_prompt_time(self):
"""Return the timestamp of the earliest recorded prompt, or None.""" """Return the timestamp of the earliest recorded prompt, or None."""
with self._lock: with self._lock:
self._ensure_db()
conn = self._connect() conn = self._connect()
try: try:
row = conn.execute( row = conn.execute(
@@ -183,6 +189,7 @@ class UsageTracker:
def reset(self): def reset(self):
"""Clear all tracked data.""" """Clear all tracked data."""
with self._lock: with self._lock:
self._ensure_db()
conn = self._connect() conn = self._connect()
try: try:
conn.execute("DELETE FROM node_usage") conn.execute("DELETE FROM node_usage")