etl_ods.py 21.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
# -*- coding: utf-8 -*-
"""
ETL 脚本: 从生产库 dj_smartcarlife 抽取数据 → 写入数仓 test_excel 的 ODS 层
支持: 全量同步 + 增量同步(按 updated_date)

用法:
    python etl_ods.py                              # 全量同步全部表
    python etl_ods.py --incremental                # 增量同步(只拉取上次同步后有更新的数据)
    python etl_ods.py --incremental --since 2026-06-01  指定增量起始时间
    python etl_ods.py --tables staff_info,service_merchant  # 指定表
    python etl_ods.py --batch-size 10000           # 自定义批次大小

增量同步机制:
    1. 每张表记录上次同步时间到 sync_meta 表
    2. 增量模式下按 updated_date >= 上次同步时间 拉取
    3. 写入时用 INSERT ... ON DUPLICATE KEY UPDATE 覆盖旧数据
    4. 同步完成后更新 sync_meta 中的 last_sync_time
"""

import argparse
import sys
import time
import pymysql
from pymysql.cursors import DictCursor
from datetime import datetime, timedelta

# ============================================================================
# 数据库连接配置
# ============================================================================
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表名, 业务主键列名, 是否有updated_date)
# 业务主键用于 ON DUPLICATE KEY UPDATE (UPSERT)
# ============================================================================
TABLE_MAPPINGS = [
    # --- 维度表 ---
    ('dj_car_life_service_merchant',              'ods_service_merchant',              'id', True),
    ('dj_car_life_shop_merchant_director_config',  'ods_shop_merchant_director_config', 'id', True),
    ('dj_car_life_merchant_brand_model',           'ods_merchant_brand_model',          'id', True),
    ('dj_car_life_staff_info',                     'ods_staff_info',                    'id', True),
    # --- 产品信息表 ---
    ('dj_car_life_base_goods',                     'ods_base_goods',                    'id', True),
    ('dj_car_life_goods_info',                     'ods_goods_info',                    'id', True),
    ('dj_car_life_upgrade_goods',                  'ods_upgrade_goods',                 'id', True),
    ('dj_car_life_merchant_goods_info',            'ods_merchant_goods_info',           'id', True),
    ('dj_car_life_merchant_package_goods_info',    'ods_merchant_package_goods_info',   'id', True),
    # --- 日报表 ---
    ('dj_car_life_staff_daily_report_huawei',      'ods_staff_daily_report_huawei',     'id', True),
    ('dj_car_life_staff_daily_report',             'ods_staff_daily_report',            'id', True),
    ('dj_car_life_merchant_daily_report_huawei',   'ods_merchant_daily_report_huawei',  'id', True),
    # --- 订单表 ---
    ('dj_car_life_goods_order',                    'ods_goods_order',                   'id', True),
    ('dj_car_life_goods_sub_order',                'ods_goods_sub_order',               'id', True),
    ('dj_car_life_goods_order_customer',           'ods_goods_order_customer',          'id', True),
    # --- 目标配置表 ---
    ('dj_car_life_merchant_deliver_target_config', 'ods_merchant_deliver_target_config','id', True),
    ('dj_car_life_merchant_output_target_config',  'ods_merchant_output_target_config', 'id', True),
    # --- 成交率表 ---
    ('employee_delivery_deal_rate',                'ods_employee_delivery_deal_rate',   'id', True),
]

SHORT_NAMES = {
    'service_merchant':         'dj_car_life_service_merchant',
    'director_config':          'dj_car_life_shop_merchant_director_config',
    'brand_model':              'dj_car_life_merchant_brand_model',
    'staff_info':               'dj_car_life_staff_info',
    'base_goods':               'dj_car_life_base_goods',
    'goods_info':               'dj_car_life_goods_info',
    'upgrade_goods':            'dj_car_life_upgrade_goods',
    'merchant_goods_info':      'dj_car_life_merchant_goods_info',
    'package_goods_info':       'dj_car_life_merchant_package_goods_info',
    'staff_report_huawei':      'dj_car_life_staff_daily_report_huawei',
    'staff_report':             'dj_car_life_staff_daily_report',
    'merchant_report_huawei':   'dj_car_life_merchant_daily_report_huawei',
    'goods_order':              'dj_car_life_goods_order',
    'goods_sub_order':          'dj_car_life_goods_sub_order',
    'goods_order_customer':     'dj_car_life_goods_order_customer',
    'deliver_target_config':    'dj_car_life_merchant_deliver_target_config',
    'output_target_config':     'dj_car_life_merchant_output_target_config',
    'deal_rate':                'employee_delivery_deal_rate',
}


def log(msg):
    msg = msg.replace('[OK]', '[OK]').replace('[FAIL]', '[FAIL]').replace('[WARN]', '[WARN]')
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


# ============================================================================
# 同步元数据管理
# ============================================================================
def init_sync_meta(target_conn):
    """创建同步元数据表"""
    with target_conn.cursor() as cur:
        cur.execute("""
            CREATE TABLE IF NOT EXISTS `_sync_meta` (
                `source_table`  VARCHAR(128) NOT NULL COMMENT '源表名',
                `target_table`  VARCHAR(128) NOT NULL COMMENT '目标表名',
                `last_sync_time` DATETIME    DEFAULT NULL COMMENT '上次同步时间(源库updated_date最大值)',
                `last_sync_rows` INT         DEFAULT 0 COMMENT '上次同步行数',
                `sync_mode`      VARCHAR(16) DEFAULT 'full' COMMENT '同步模式: full/incremental',
                `updated_at`     DATETIME    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY (`source_table`, `target_table`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ETL同步元数据'
        """)
    target_conn.commit()


def get_last_sync_time(target_conn, source_table, target_table):
    """获取上次同步时间"""
    with target_conn.cursor() as cur:
        cur.execute(
            "SELECT last_sync_time FROM `_sync_meta` WHERE source_table=%s AND target_table=%s",
            (source_table, target_table)
        )
        row = cur.fetchone()
        return row['last_sync_time'] if row else None


def update_sync_meta(target_conn, source_table, target_table, sync_time, rows, mode):
    """更新同步元数据"""
    with target_conn.cursor() as cur:
        cur.execute("""
            INSERT INTO `_sync_meta` (source_table, target_table, last_sync_time, last_sync_rows, sync_mode)
            VALUES (%s, %s, %s, %s, %s)
            ON DUPLICATE KEY UPDATE
                last_sync_time = VALUES(last_sync_time),
                last_sync_rows = VALUES(last_sync_rows),
                sync_mode = VALUES(sync_mode)
        """, (source_table, target_table, sync_time, rows, mode))
    target_conn.commit()


# ============================================================================
# 表结构管理
# ============================================================================
def get_table_columns(conn, table_name):
    with conn.cursor() as cur:
        cur.execute(f"SHOW COLUMNS FROM `{table_name}`")
        return cur.fetchall()


def ensure_ods_table(target_conn, source_columns, target_table):
    """
    确保目标表存在,不存在则创建。
    datetime/timestamp 列统一改为 DEFAULT NULL,兼容 0000-00-00 脏数据。
    """
    with target_conn.cursor() as cur:
        cur.execute(f"SHOW TABLES LIKE '{target_table}'")
        exists = cur.fetchone()

    if exists:
        return [c['Field'] for c in source_columns]

    # 不存在则创建
    col_defs = []
    for col in source_columns:
        col_name = col['Field']
        col_type = col['Type']
        col_type_lower = col_type.lower()

        if 'datetime' in col_type_lower or 'timestamp' in col_type_lower:
            col_defs.append(f"  `{col_name}` {col_type} DEFAULT NULL")
        else:
            nullable = '' if col['Null'] == 'YES' else ' NOT NULL'
            default = ''
            if col['Default'] is not None:
                val = col['Default']
                if isinstance(val, str):
                    if 'current_timestamp' in val.lower():
                        default = f" DEFAULT {val}"
                    else:
                        default = f" DEFAULT '{val}'"
                else:
                    default = f" DEFAULT {val}"
            elif col['Null'] == 'YES':
                default = ' DEFAULT NULL'
            col_defs.append(f"  `{col_name}` {col_type}{nullable}{default}")

    col_defs.append("  `etl_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'ETL抽取时间'")

    create_ddl = f"CREATE TABLE `{target_table}` (\n"
    create_ddl += ",\n".join(col_defs)
    if source_columns and source_columns[0]['Field'] == 'id' and 'int' in source_columns[0]['Type'].lower():
        create_ddl += ",\n  PRIMARY KEY (`id`)"
    create_ddl += f"\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ODS层-{target_table}'"

    with target_conn.cursor() as cur:
        cur.execute(create_ddl)
    target_conn.commit()
    log(f"  创建目标表 {target_table}")

    return [c['Field'] for c in source_columns]


def add_indexes(target_conn, target_table):
    """为目标表添加常用索引"""
    index_map = {
        'ods_service_merchant': [('merchant_id',), ('province_name',), ('store_code',), ('deleted_flag',)],
        'ods_shop_merchant_director_config': [('merchant_id', 'director_type'), ('director_user_id',), ('deleted_flag',)],
        'ods_merchant_brand_model': [('merchant_id',), ('brand_id', 'child_id'), ('series_id',), ('deleted_flag',)],
        'ods_staff_info': [('staff_uuid',), ('deleted_flag',)],
        'ods_base_goods': [('goods_type', 'secondary_goods_type', 'third_level_goods_type'), ('goods_code',), ('deleted_flag',)],
        'ods_goods_info': [('goods_type', 'secondary_goods_type', 'third_level_goods_type'), ('goods_code',), ('deleted_flag',)],
        'ods_upgrade_goods': [('base_goods_id',), ('goods_code',), ('status',), ('deleted_flag',)],
        'ods_merchant_goods_info': [('merchant_id', 'scene_type'), ('upgrade_goods_id',), ('status',), ('deleted_flag',)],
        'ods_merchant_package_goods_info': [('package_code',), ('scene_type',), ('status',), ('deleted_flag',)],
        'ods_staff_daily_report_huawei': [
            ('merchant_id', 'report_date'),
            ('staff_uuid', 'report_date'),
            ('first_brand_id', 'brand_id'),
            ('scene_type',),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_staff_daily_report': [
            ('merchant_id', 'staff_uuid', 'report_date'),
            ('report_date',),
            ('scene_type',),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_merchant_daily_report_huawei': [
            ('merchant_id', 'report_date'),
            ('first_brand_id', 'brand_id'),
            ('scene_type',),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_goods_order': [
            ('order_code',),
            ('merchant_id', 'install_upgrade_time'),
            ('seller_user_id',),
            ('scene_type',),
            ('status',),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_goods_sub_order': [
            ('order_code',),
            ('upgrade_goods_type',),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_goods_order_customer': [
            ('order_code',),
            ('car_brand_id', 'car_childs_brand_id'),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_merchant_deliver_target_config': [
            ('merchant_id', 'target_month'),
            ('brand_id', 'child_id'),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_merchant_output_target_config': [
            ('merchant_id', 'target_month'),
            ('deleted_flag',),
            ('updated_date',),
        ],
        'ods_employee_delivery_deal_rate': [
            ('merchant_id', 'staff_uuid', 'deal_month'),
            ('brand_id', 'brand_child_id'),
            ('deleted_flag',),
            ('updated_date',),
        ],
    }

    indexes = index_map.get(target_table, [])
    added = 0
    with target_conn.cursor() as cur:
        for i, idx_cols in enumerate(indexes):
            idx_name = f"idx_{target_table}_{i}"
            col_list = ", ".join(f"`{c}`" for c in idx_cols)
            try:
                cur.execute(f"CREATE INDEX `{idx_name}` ON `{target_table}` ({col_list})")
                added += 1
            except Exception:
                pass  # 索引已存在
    target_conn.commit()
    if added:
        log(f"  添加 {added} 个索引")


# ============================================================================
# 数据抽取与加载
# ============================================================================
def clean_value(v):
    """清洗数据: 将 0000-00-00 日期转为 None"""
    if v is not None and hasattr(v, 'year') and v.year == 0:
        return None
    if isinstance(v, str) and v.startswith('0000-00-00'):
        return None
    return v


def extract_load_table(source_conn, target_conn, source_table, target_table,
                       batch_size=10000, incremental=False, since=None):
    """抽取单张表的数据"""
    mode = "增量" if incremental else "全量"
    log(f"=== [{mode}] {source_table} -> {target_table} ===")

    # 1. 获取源表列信息
    source_columns = get_table_columns(source_conn, source_table)
    if not source_columns:
        log(f"  [FAIL] 源表 {source_table} 无列信息,跳过")
        return 0

    col_names = [c['Field'] for c in source_columns]
    col_fields = {c['Field']: c for c in source_columns}

    # 2. 确保目标表存在
    ensure_ods_table(target_conn, source_columns, target_table)
    add_indexes(target_conn, target_table)

    # 3. 构建查询条件
    where_clause = "WHERE 1=1"
    params = []

    if incremental:
        # 增量模式: 按 updated_date 过滤
        if 'updated_date' not in col_fields:
            log(f"  [WARN] 源表无 updated_date 列,改为全量同步")
        else:
            last_sync = since
            if last_sync is None:
                last_sync = get_last_sync_time(target_conn, source_table, target_table)
            if last_sync:
                where_clause += f" AND `updated_date` >= %s"
                params.append(last_sync)
                log(f"  增量起始时间: {last_sync}")
            else:
                log(f"  无上次同步记录,改为全量同步")
                incremental = False
                mode = "全量"

    # 软删除也同步(不加 deleted_flag 过滤,保留全部数据)

    # 4. 获取总行数
    with source_conn.cursor() as cur:
        count_sql = f"SELECT COUNT(*) AS cnt FROM `{source_table}` {where_clause}"
        cur.execute(count_sql, params)
        total = cur.fetchone()['cnt']
    log(f"  待同步行数: {total:,}")

    if total == 0:
        log(f"  [OK] 无数据需同步")
        # 更新元数据
        if incremental:
            update_sync_meta(target_conn, source_table, target_table, datetime.now(), 0, 'incremental')
        return 0

    # 5. 构建UPSERT SQL
    col_list = ", ".join(f"`{c}`" for c in col_names)
    placeholders = ", ".join(["%s"] * len(col_names))
    update_cols = ", ".join(f"`{c}`=VALUES(`{c}`)" for c in col_names if c != 'id')

    if incremental and update_cols:
        insert_sql = f"INSERT INTO `{target_table}` ({col_list}) VALUES ({placeholders}) ON DUPLICATE KEY UPDATE {update_cols}, `etl_time`=NOW()"
    else:
        insert_sql = f"INSERT INTO `{target_table}` ({col_list}) VALUES ({placeholders})"

    # 6. 分批抽取
    inserted = 0
    max_updated = None
    offset = 0
    batch_num = 0

    # 增量模式用 updated_date 排序保证一致性
    order_clause = "ORDER BY `id`" if 'id' in col_fields else ""

    with source_conn.cursor() as src_cur:
        with target_conn.cursor() as tgt_cur:
            while offset < total:
                query = f"SELECT {col_list} FROM `{source_table}` {where_clause} {order_clause} LIMIT %s OFFSET %s"
                src_cur.execute(query, params + [batch_size, offset])
                rows = src_cur.fetchall()
                if not rows:
                    break

                batch_data = []
                for row in rows:
                    vals = tuple(clean_value(row[c]) for c in col_names)
                    batch_data.append(vals)

                    # 跟踪最大 updated_date
                    if incremental and 'updated_date' in col_fields:
                        ud = row.get('updated_date')
                        if ud and (max_updated is None or ud > max_updated):
                            max_updated = ud

                tgt_cur.executemany(insert_sql, batch_data)
                target_conn.commit()

                inserted += len(batch_data)
                batch_num += 1
                if batch_num % 10 == 0 or offset + batch_size >= total:
                    log(f"  批次 {batch_num}: 写入 {len(batch_data):,} 行, 累计 {inserted:,}/{total:,}")

                offset += batch_size

    # 7. 更新同步元数据
    sync_time = max_updated if (incremental and max_updated) else datetime.now()
    update_sync_meta(target_conn, source_table, target_table, sync_time, inserted, 'incremental' if incremental else 'full')

    log(f"  [OK] 完成: {target_table} 共同步 {inserted:,} 行, 同步时间点: {sync_time}")
    return inserted


# ============================================================================
# 主流程
# ============================================================================
def main():
    parser = argparse.ArgumentParser(description='ODS层ETL抽数脚本(支持增量同步)')
    parser.add_argument('--incremental', action='store_true', help='增量同步模式(按updated_date)')
    parser.add_argument('--since', type=str, default='', help='增量起始时间(YYYY-MM-DD HH:MM:SS)')
    parser.add_argument('--tables', type=str, default='', help='指定表(简称逗号分隔)')
    parser.add_argument('--batch-size', type=int, default=10000, help='批次大小')
    args = parser.parse_args()

    since = None
    if args.since:
        try:
            since = datetime.strptime(args.since, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            since = datetime.strptime(args.since, '%Y-%m-%d')

    mode = "增量" if args.incremental else "全量"
    log("=" * 60)
    log(f"ODS层 ETL抽数脚本启动 [{mode}模式]")
    log(f"源库: {SOURCE_CONFIG['host']}:{SOURCE_CONFIG['port']}/{SOURCE_CONFIG['database']}")
    log(f"目标库: {TARGET_CONFIG['host']}:{TARGET_CONFIG['port']}/{TARGET_CONFIG['database']}")
    log(f"批次大小: {args.batch_size}")
    if since:
        log(f"增量起始时间: {since}")
    log("=" * 60)

    # 确定要抽取的表
    if args.tables:
        short_list = [s.strip() for s in args.tables.split(',')]
        mappings = []
        for short_name in short_list:
            src_table = SHORT_NAMES.get(short_name)
            if not src_table:
                log(f"[FAIL] 未知表简称: {short_name}")
                log(f"  可用: {', '.join(SHORT_NAMES.keys())}")
                sys.exit(1)
            for m in TABLE_MAPPINGS:
                if m[0] == src_table:
                    mappings.append(m)
                    break
        if not mappings:
            log("[FAIL] 没有匹配的表")
            sys.exit(1)
    else:
        mappings = TABLE_MAPPINGS

    log(f"待同步表数: {len(mappings)}")
    log("-" * 60)

    # 连接数据库
    try:
        source_conn = pymysql.connect(**SOURCE_CONFIG)
        target_conn = pymysql.connect(**TARGET_CONFIG)
        log("数据库连接成功")
    except Exception as e:
        log(f"[FAIL] 数据库连接失败: {e}")
        sys.exit(1)

    # 初始化同步元数据表
    init_sync_meta(target_conn)

    # 执行抽取
    total_rows = 0
    success_tables = 0
    failed_tables = []
    start_time = time.time()

    for src_table, tgt_table, pk_col, has_updated in mappings:
        try:
            rows = extract_load_table(
                source_conn, target_conn, src_table, tgt_table,
                args.batch_size, args.incremental, since
            )
            total_rows += rows
            success_tables += 1
        except Exception as e:
            log(f"[FAIL] {src_table} -> {tgt_table}: {e}")
            failed_tables.append(src_table)
            target_conn.rollback()

    elapsed = time.time() - start_time

    log("=" * 60)
    log(f"ETL完成! 耗时 {elapsed:.1f}s")
    log(f"成功: {success_tables}/{len(mappings)} 表, 总行数: {total_rows:,}")
    if failed_tables:
        log(f"失败: {', '.join(failed_tables)}")
    log("=" * 60)

    source_conn.close()
    target_conn.close()


if __name__ == '__main__':
    main()