import sys import time from sqlalchemy import text from kis_trader.database.db_manager import TradeDB db = TradeDB() try: tables = [list(r._mapping.values())[0] for r in db.conn.execute(text("SHOW TABLES")).fetchall()] target_prefixes = ( 'ws_ticks', 'ws_orderbook', 'ws_candles', 'ls_ws_ticks', 'ls_ws_orderbook', 'ls_ws_candles', 'ws_price_validation' ) for table in tables: if not table.startswith(target_prefixes): continue cols = [dict(r._mapping)["Field"] for r in db.conn.execute(text(f"SHOW COLUMNS FROM {table}")).fetchall()] time_col = None for candidate in ('tick_time', 'ob_time', 'candle_time', 'timestamp', 'recv_ts', 'datetime'): if candidate in cols: time_col = candidate break if time_col: cutoff = '20260808' # Print count before deletion count_q = text(f"SELECT COUNT(*) as cnt FROM {table} WHERE {time_col} < :cutoff") count = db.conn.execute(count_q, {"cutoff": cutoff}).fetchone()._mapping['cnt'] if count > 0: print(f"Deleting {count} rows from {table} (using column {time_col})") deleted = 0 while True: del_q = text(f"DELETE FROM {table} WHERE {time_col} < :cutoff LIMIT 100000") res = db.conn.execute(del_q, {"cutoff": cutoff}) db.conn.commit() rows_affected = res.rowcount if rows_affected <= 0: break deleted += rows_affected print(f" ... deleted {deleted}/{count} rows in {table}") time.sleep(0.1) print(f"Finished deleting from {table}.") else: print(f"No rows to delete in {table} before {cutoff}") else: print(f"Warning: No time column found for {table}, columns: {cols}") finally: db.close()