# prestart_db_cleanup.py
import os
import time
import psycopg
DB_URL = os.getenv("KEYLOGGER_DB_URL")
if not DB_URL:
raise RuntimeError("KEYLOGGER_DB_URL is not set")
DELETES = [
"""
DELETE FROM keystrokes
WHERE timestamp IN (
SELECT timestamp
FROM keystrokes
ORDER BY timestamp ASC
LIMIT 20
);
""",
"""
DELETE FROM hourly_summary
WHERE hour_key IN (
SELECT hour_key
FROM hourly_summary
ORDER BY hour_key ASC
LIMIT 20
);
""",
"""
DELETE FROM daily_summary
WHERE first_recorded IN (
SELECT first_recorded
FROM daily_summary
ORDER BY first_recorded ASC
LIMIT 20
);
""",
]
def main() -> None:
retries = 20
delay = 1.5
last_err = None
for _ in range(retries):
try:
with psycopg.connect(DB_URL) as conn:
with conn.cursor() as cur:
for stmt in DELETES:
try:
cur.execute(stmt)
except psycopg.errors.UndefinedTable:
conn.rollback()
continue
conn.commit()
return
except Exception as e:
last_err = e
time.sleep(delay)
raise SystemExit(f"DB cleanup failed: {last_err!r}")
if __name__ == "__main__":
main()