update 03-28 11:38
This commit is contained in:
@@ -34,6 +34,26 @@ class TradeDB:
|
||||
self._ensure_tables()
|
||||
self._log.info("database_ready")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def close(self) -> None:
|
||||
"""Flush WAL and close the underlying SQLite connection."""
|
||||
try:
|
||||
if self._db and hasattr(self._db, "conn") and self._db.conn:
|
||||
self._db.conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
self._db.conn.close()
|
||||
self._log.info("database_closed")
|
||||
except Exception:
|
||||
self._log.exception("database_close_error")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Schema
|
||||
# ------------------------------------------------------------------
|
||||
@@ -321,3 +341,23 @@ class TradeDB:
|
||||
[today],
|
||||
).fetchone()
|
||||
return int(row[0])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Maintenance
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def periodic_maintenance(self, retention_days: int = 7) -> None:
|
||||
"""Prune old time-series data and checkpoint WAL."""
|
||||
cutoff = time.time() - retention_days * 86400
|
||||
pruned = {}
|
||||
for table in ("oracle_snapshots", "balance_history"):
|
||||
if table in self._db.table_names():
|
||||
before = self._db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||
self._db.execute(f"DELETE FROM {table} WHERE timestamp < ?", [cutoff])
|
||||
after = self._db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||
pruned[table] = before - after
|
||||
try:
|
||||
self._db.conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
except Exception:
|
||||
pass
|
||||
self._log.info("db_maintenance", pruned=pruned, retention_days=retention_days)
|
||||
|
||||
Reference in New Issue
Block a user