#!/opt/imh-python/bin/python3
"""repairs database tables"""
from argparse import ArgumentParser
from typing import Literal
from pymysql.cursors import Cursor
# specify the socket file for pymysql
if Path("/etc/redhat-release").exists():
SOCK = "/var/lib/mysql/mysql.sock"
SOCK = "/run/mysqld/mysqld.sock"
conn: pymysql.Connection, dbcmd: Literal['OPTIMIZE', 'REPAIR']
with conn.cursor(Cursor) as cur:
cur.execute("SHOW TABLES")
tablenames = [x[0] for x in cur.fetchall()]
except pymysql.Error as exc:
escaped = str(table).replace('`', '``')
cur.execute(f"{dbcmd} TABLE `{escaped}`")
except pymysql.Error as exc:
f"Error running {dbcmd} TABLE on {table}: {exc}",
def parse_args() -> tuple[Literal['OPTIMIZE', 'REPAIR'], str]:
parser = ArgumentParser(description=__doc__)
dbcmd = parser.add_mutually_exclusive_group(required=True)
'--repair', action='store_const', const='REPAIR', dest='dbcmd'
'--optimize', action='store_const', const='OPTIMIZE', dest='dbcmd'
parser.add_argument('dbname')
args = parser.parse_args()
return args.dbcmd, args.dbname
dbcmd, dbname = parse_args()
read_default_file="/root/.my.cnf",
rcode = repair_tables(conn, dbcmd)
if __name__ == '__main__':