fix_comments.py 10.9 KB
# -*- coding: utf-8 -*-
"""
修复ODS表字段注释: 从源库获取列注释, 批量ALTER TABLE补到目标库ODS表
"""
import pymysql
from pymysql.cursors import DictCursor

SOURCE_CONFIG = {
    'host': '192.168.5.23', 'port': 3306,
    'user': 'user_jiangmy', 'password': 'VMziLJun',
    'database': 'dj_smartcarlife', 'charset': 'utf8mb4',
    'cursorclass': DictCursor,
}

TARGET_CONFIG = {
    'host': '192.168.2.155', 'port': 3308,
    'user': 'user_jiangmy', 'password': 'PYuxMTB1',
    'database': 'test_excel', 'charset': 'utf8mb4',
    'cursorclass': DictCursor,
}

# 源表 -> ODS表映射
MAPPINGS = [
    ('dj_car_life_service_merchant',              'ods_service_merchant'),
    ('dj_car_life_shop_merchant_director_config',  'ods_shop_merchant_director_config'),
    ('dj_car_life_merchant_brand_model',           'ods_merchant_brand_model'),
    ('dj_car_life_staff_info',                     'ods_staff_info'),
    ('dj_car_life_base_goods',                     'ods_base_goods'),
    ('dj_car_life_goods_info',                     'ods_goods_info'),
    ('dj_car_life_upgrade_goods',                  'ods_upgrade_goods'),
    ('dj_car_life_merchant_goods_info',            'ods_merchant_goods_info'),
    ('dj_car_life_merchant_package_goods_info',    'ods_merchant_package_goods_info'),
    ('dj_car_life_staff_daily_report_huawei',      'ods_staff_daily_report_huawei'),
    ('dj_car_life_staff_daily_report',             'ods_staff_daily_report'),
    ('dj_car_life_merchant_daily_report_huawei',   'ods_merchant_daily_report_huawei'),
    ('dj_car_life_goods_order',                    'ods_goods_order'),
    ('dj_car_life_goods_sub_order',                'ods_goods_sub_order'),
    ('dj_car_life_goods_order_customer',           'ods_goods_order_customer'),
    ('dj_car_life_merchant_deliver_target_config', 'ods_merchant_deliver_target_config'),
    ('dj_car_life_merchant_output_target_config',  'ods_merchant_output_target_config'),
    ('employee_delivery_deal_rate',                'ods_employee_delivery_deal_rate'),
]

# etl_time 列的注释
ETL_TIME_COMMENT = 'ETL抽取时间'


def log(msg):
    print(msg, flush=True)


def get_source_columns(source_conn, table_name):
    """从源库获取列的完整信息(含注释)"""
    with source_conn.cursor() as cur:
        cur.execute(f"""
            SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, 
                   COLUMN_KEY, EXTRA, COLUMN_COMMENT
            FROM information_schema.columns
            WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
            ORDER BY ORDINAL_POSITION
        """, (SOURCE_CONFIG['database'], table_name))
        return cur.fetchall()


def get_target_columns(target_conn, table_name):
    """获取目标表当前列信息"""
    with target_conn.cursor() as cur:
        cur.execute(f"""
            SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, 
                   COLUMN_KEY, EXTRA, COLUMN_COMMENT
            FROM information_schema.columns
            WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s
            ORDER BY ORDINAL_POSITION
        """, (TARGET_CONFIG['database'], table_name))
        return cur.fetchall()


def build_modify_sql(table_name, col):
    """构建 ALTER TABLE MODIFY COLUMN 语句"""
    col_name = col['COLUMN_NAME']
    col_type = col['COLUMN_TYPE']
    nullable = '' if col['IS_NULLABLE'] == 'YES' else ' NOT NULL'
    
    default = ''
    if col['COLUMN_DEFAULT'] is not None:
        val = col['COLUMN_DEFAULT']
        if isinstance(val, str):
            if 'CURRENT_TIMESTAMP' in val.upper():
                default = f' DEFAULT {val}'
            else:
                # 转义单引号
                val_escaped = val.replace("'", "''")
                default = f" DEFAULT '{val_escaped}'"
        else:
            default = f' DEFAULT {val}'
    elif col['IS_NULLABLE'] == 'YES':
        default = ' DEFAULT NULL'
    
    # 处理 EXTRA (如 auto_increment, on update CURRENT_TIMESTAMP)
    extra = ''
    if col['EXTRA']:
        extra_str = col['EXTRA'].lower()
        if 'auto_increment' in extra_str:
            extra += ' AUTO_INCREMENT'
        elif 'on update current_timestamp' in extra_str:
            extra += ' ON UPDATE CURRENT_TIMESTAMP'
    
    comment = col['COLUMN_COMMENT'] or col_name
    
    # 转义注释中的单引号
    comment_escaped = comment.replace("'", "''").replace('\\', '\\\\')
    
    sql = f"ALTER TABLE `{table_name}` MODIFY COLUMN `{col_name}` {col_type}{nullable}{default}{extra} COMMENT '{comment_escaped}'"
    return sql


def fix_table_comments(source_conn, target_conn, source_table, target_table):
    """修复单张表的注释"""
    source_cols = get_source_columns(source_conn, source_table)
    target_cols = get_target_columns(target_conn, target_table)
    
    if not source_cols:
        log(f"  [WARN] 源表 {source_table} 无列信息")
        return 0
    
    # 构建源表列名->注释的映射
    source_map = {c['COLUMN_NAME']: c for c in source_cols}
    
    fixed = 0
    with target_conn.cursor() as cur:
        for tcol in target_cols:
            col_name = tcol['COLUMN_NAME']
            current_comment = tcol['COLUMN_COMMENT'] or ''
            
            # etl_time 列特殊处理
            if col_name == 'etl_time':
                if not current_comment:
                    try:
                        cur.execute(f"ALTER TABLE `{target_table}` MODIFY COLUMN `etl_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '{ETL_TIME_COMMENT}'")
                        target_conn.commit()
                        fixed += 1
                    except Exception as e:
                        log(f"    [WARN] etl_time 修改失败: {e}")
                continue
            
            # 从源表获取注释
            if col_name in source_map:
                scol = source_map[col_name]
                source_comment = scol['COLUMN_COMMENT'] or ''
                
                # 如果注释不同(源表有注释但目标表没有,或注释内容不一致)
                if source_comment and source_comment != current_comment:
                    try:
                        sql = build_modify_sql(target_table, scol)
                        cur.execute(sql)
                        target_conn.commit()
                        fixed += 1
                    except Exception as e:
                        # 如果MODIFY失败(可能是类型不兼容), 只改注释
                        try:
                            col_type = tcol['COLUMN_TYPE']
                            nullable = '' if tcol['IS_NULLABLE'] == 'YES' else ' NOT NULL'
                            default = ''
                            if tcol['COLUMN_DEFAULT'] is not None:
                                val = tcol['COLUMN_DEFAULT']
                                if isinstance(val, str):
                                    if 'CURRENT_TIMESTAMP' in str(val).upper():
                                        default = f' DEFAULT {val}'
                                    else:
                                        val_escaped = str(val).replace("'", "''")
                                        default = f" DEFAULT '{val_escaped}'"
                                else:
                                    default = f' DEFAULT {val}'
                            elif tcol['IS_NULLABLE'] == 'YES':
                                default = ' DEFAULT NULL'
                            
                            extra = ''
                            if tcol['EXTRA']:
                                extra_str = tcol['EXTRA'].lower()
                                if 'auto_increment' in extra_str:
                                    extra += ' AUTO_INCREMENT'
                                elif 'on update current_timestamp' in extra_str:
                                    extra += ' ON UPDATE CURRENT_TIMESTAMP'
                            
                            comment_escaped = source_comment.replace("'", "''").replace('\\', '\\\\')
                            sql2 = f"ALTER TABLE `{target_table}` MODIFY COLUMN `{col_name}` {col_type}{nullable}{default}{extra} COMMENT '{comment_escaped}'"
                            cur.execute(sql2)
                            target_conn.commit()
                            fixed += 1
                        except Exception as e2:
                            log(f"    [WARN] {col_name} 注释修改失败: {e2}")
                            target_conn.rollback()
            elif not current_comment:
                # 源表没有这列, 且目标表也没注释, 用列名做注释
                try:
                    col_type = tcol['COLUMN_TYPE']
                    nullable = '' if tcol['IS_NULLABLE'] == 'YES' else ' NOT NULL'
                    default = ''
                    if tcol['COLUMN_DEFAULT'] is not None:
                        val = tcol['COLUMN_DEFAULT']
                        if isinstance(val, str):
                            if 'CURRENT_TIMESTAMP' in str(val).upper():
                                default = f' DEFAULT {val}'
                            else:
                                val_escaped = str(val).replace("'", "''")
                                default = f" DEFAULT '{val_escaped}'"
                        else:
                            default = f' DEFAULT {val}'
                    elif tcol['IS_NULLABLE'] == 'YES':
                        default = ' DEFAULT NULL'
                    
                    comment_escaped = col_name.replace("'", "''")
                    sql = f"ALTER TABLE `{target_table}` MODIFY COLUMN `{col_name}` {col_type}{nullable}{default} COMMENT '{comment_escaped}'"
                    cur.execute(sql)
                    target_conn.commit()
                    fixed += 1
                except Exception as e:
                    log(f"    [WARN] {col_name} 注释设置失败: {e}")
                    target_conn.rollback()
    
    return fixed


def main():
    log("=" * 60)
    log("ODS表字段注释修复脚本启动")
    log(f"源库: {SOURCE_CONFIG['host']}:{SOURCE_CONFIG['port']}/{SOURCE_CONFIG['database']}")
    log(f"目标库: {TARGET_CONFIG['host']}:{TARGET_CONFIG['port']}/{TARGET_CONFIG['database']}")
    log("=" * 60)
    
    source_conn = pymysql.connect(**SOURCE_CONFIG)
    target_conn = pymysql.connect(**TARGET_CONFIG)
    log("数据库连接成功")
    
    total_fixed = 0
    for source_table, target_table in MAPPINGS:
        log(f"\n--- {target_table} ---")
        fixed = fix_table_comments(source_conn, target_conn, source_table, target_table)
        log(f"  修复 {fixed} 个字段注释")
        total_fixed += fixed
    
    log(f"\n{'=' * 60}")
    log(f"全部完成! 共修复 {total_fixed} 个字段注释")
    log("=" * 60)
    
    source_conn.close()
    target_conn.close()


if __name__ == '__main__':
    main()