import pymysql
import sys

# 数据库配置
DB_CONFIG = {
    "host": "m-f8ze60yirdj8786u2.mysql.rds.aliyuncs.com",
    "port": 3306,
    "user": "root",
    "password": "csqz@20255",
    "db": "csqz-client",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor
}

def update_schema():
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor() as cursor:
            # 1. Add family_rank (堂内排行)
            try:
                cursor.execute("ALTER TABLE family_member_info ADD COLUMN family_rank VARCHAR(50) DEFAULT NULL COMMENT '堂内排行'")
                print("Added column: family_rank")
            except pymysql.err.OperationalError as e:
                if e.args[0] != 1060: # Duplicate column name
                    raise e
                print("Column family_rank already exists.")

            # 2. Add tags (标签)
            try:
                cursor.execute("ALTER TABLE family_member_info ADD COLUMN tags VARCHAR(255) DEFAULT NULL COMMENT '标签'")
                print("Added column: tags")
            except pymysql.err.OperationalError as e:
                if e.args[0] != 1060:
                    raise e
                print("Column tags already exists.")

            # 3. Add notes (人员备注)
            try:
                cursor.execute("ALTER TABLE family_member_info ADD COLUMN notes TEXT DEFAULT NULL COMMENT '人员备注'")
                print("Added column: notes")
            except pymysql.err.OperationalError as e:
                if e.args[0] != 1060:
                    raise e
                print("Column notes already exists.")

        conn.commit()
        print("Schema update completed successfully.")
        return True
    except Exception as e:
        print(f"Error updating schema: {e}")
        return False
    finally:
        conn.close()

if __name__ == "__main__":
    if update_schema():
        sys.exit(0)
    else:
        sys.exit(1)
