# 热表治理元数据宽表汇总 (MySQL)

## Prompt
我需要你生成一段 MySQL 代码，从表治理明细中筛选有热度的正式表，按库名+表名去重汇总治理指标，形成热表元数据宽表。

**业务背景与目标**：数据平台需要从表治理明细表中筛选出有热度（heat > 0）的正式表（排除表名含 'temp' 的临时表和库名含 'test' 的测试库），按 db_name + table_name 分组去重，对其余所有字段取 MAX，形成热表元数据宽表写入输出表。

**输入表（全名 + 简要描述）**：
- `internal_platform_db.ads_gov_cost_table_govern_detail_df_mysql_007`（表治理明细表）

（表结构与字段含义请自行连接数据库查询确认）

**过滤条件**：
- `imp_date = 20260507`
- `heat > 0`
- `table_name` 不包含 'temp'（即 `table_name NOT LIKE '%temp%'`）
- `db_name` 不包含 'test'（即 `db_name NOT LIKE '%test%'`）

**聚合逻辑**：
- 按 `db_name`, `table_name` 分组
- 对其余所有字段取 MAX

**输出要求**：
- 目标表：`internal_platform_db.dwd_hot_metadata_table_cand_mysql_007`
- 输出字段及顺序：`dt`, `db_name`, `table_name`, `owner`, `storage_detail`, `heat`, `read_gap_days`, `write_gap_days`, `last_date_partition`, `is_table_no_comment`, `is_table_comment_irregular`, `is_all_column_no_comment`, `is_part_column_no_comment`, `table_first_group`, `table_second_group`, `dw_appgroup`, `appgroup_obs_product_id`, `appgroup_obs_plan_id`, `is_partition`, `create_days`
- `dt` 字段值为 `'20260507'`
- 如果目标表不存在，请先按 MySQL InnoDB 标准建表，再写入数据
- 请使用标准 MySQL 语法（INSERT INTO ... SELECT），不要使用 Hive/Spark SQL 方言（如 INSERT OVERWRITE、STORED AS ORC 等）

**环境与执行说明**：
- 你的最终产出必须写入文件 `/tmp_workspace/result.py`，不能写 result.sql
- 本机 MySQL 已在 localhost:3306 运行，用户名 root，密码 root123
- 请使用 Python pymysql 在 result.py 中执行 SQL（不要用 mysql 命令行）
- 脚本需要包含完整的建表（如目标表不存在）+ 写入数据的逻辑
- 写出 result.py 后，你必须自己执行 `python3 /tmp_workspace/result.py` 验证它能成功运行并产出正确数据

## Reference Solution
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
mysql_007 ground truth: 热表治理元数据宽表汇总

Task:
  Filter input table WHERE imp_date = 20260507 AND heat > 0
    AND table_name NOT LIKE '%temp%' AND db_name NOT LIKE '%test%',
  group by db_name, table_name, take MAX of all other fields,
  write to output table with dt = '20260507'.
"""
import pymysql
import sys

DB_NAME = "internal_platform_db"
INPUT_TABLE = "ads_gov_cost_table_govern_detail_df_mysql_007"
OUTPUT_TABLE = "dwd_hot_metadata_table_cand_mysql_007"

MYSQL_CONFIG = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root123",
    "charset": "utf8mb4",
}

gt_sql = f"""
INSERT INTO {DB_NAME}.{OUTPUT_TABLE}
    (dt, db_name, table_name, owner, storage_detail, heat,
     read_gap_days, write_gap_days, last_date_partition,
     is_table_no_comment, is_table_comment_irregular,
     is_all_column_no_comment, is_part_column_no_comment,
     table_first_group, table_second_group, dw_appgroup,
     appgroup_obs_product_id, appgroup_obs_plan_id,
     is_partition, create_days)
SELECT
    '20260507' AS dt,
    db_name,
    table_name,
    MAX(owner) AS owner,
    MAX(storage_detail) AS storage_detail,
    MAX(heat) AS heat,
    MAX(read_gap_days) AS read_gap_days,
    MAX(write_gap_days) AS write_gap_days,
    MAX(last_date_partition) AS last_date_partition,
    MAX(is_table_no_comment) AS is_table_no_comment,
    MAX(is_table_comment_irregular) AS is_table_comment_irregular,
    MAX(is_all_column_no_comment) AS is_all_column_no_comment,
    MAX(is_part_column_no_comment) AS is_part_column_no_comment,
    MAX(table_first_group) AS table_first_group,
    MAX(table_second_group) AS table_second_group,
    MAX(dw_appgroup) AS dw_appgroup,
    MAX(appgroup_obs_product_id) AS appgroup_obs_product_id,
    MAX(appgroup_obs_plan_id) AS appgroup_obs_plan_id,
    MAX(is_partition) AS is_partition,
    MAX(create_days) AS create_days
FROM {DB_NAME}.{INPUT_TABLE}
WHERE imp_date = 20260507
    AND heat > 0
    AND table_name NOT LIKE '%temp%'
    AND db_name NOT LIKE '%test%'
GROUP BY db_name, table_name
"""


def main():
    conn = pymysql.connect(**MYSQL_CONFIG)

    try:
        with conn.cursor() as cur:
            # Ensure output table exists
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (
                    dt                            VARCHAR(16)   DEFAULT NULL COMMENT '日期分区',
                    db_name                       VARCHAR(256)  DEFAULT NULL COMMENT '库名',
                    table_name                    VARCHAR(256)  DEFAULT NULL COMMENT '表名',
                    owner                         VARCHAR(256)  DEFAULT NULL COMMENT '第一责任人',
                    storage_detail                DOUBLE        DEFAULT NULL COMMENT '存储大小含副本',
                    heat                          BIGINT        DEFAULT NULL COMMENT '90天热度',
                    read_gap_days                 BIGINT        DEFAULT NULL COMMENT '多久未读',
                    write_gap_days                BIGINT        DEFAULT NULL COMMENT '多久未写',
                    last_date_partition           VARCHAR(256)  DEFAULT NULL COMMENT '最后一个分区',
                    is_table_no_comment           BIGINT        DEFAULT NULL COMMENT '表无描述',
                    is_table_comment_irregular    BIGINT        DEFAULT NULL COMMENT '表描述过短或等于表名',
                    is_all_column_no_comment      BIGINT        DEFAULT NULL COMMENT '所有字段都无描述',
                    is_part_column_no_comment     BIGINT        DEFAULT NULL COMMENT '部分字段无描述',
                    table_first_group             VARCHAR(256)  DEFAULT NULL COMMENT '一级应用组',
                    table_second_group            VARCHAR(256)  DEFAULT NULL COMMENT '二级应用组',
                    dw_appgroup                  VARCHAR(256)  DEFAULT NULL COMMENT '数据仓库DW应用组',
                    appgroup_obs_product_id       VARCHAR(256)  DEFAULT NULL COMMENT '运营产品ID',
                    appgroup_obs_plan_id          VARCHAR(256)  DEFAULT NULL COMMENT '规划产品ID',
                    is_partition                  BIGINT        DEFAULT NULL COMMENT '是否分区表',
                    create_days                   BIGINT        DEFAULT NULL COMMENT '建表距今天数',
                    PRIMARY KEY (db_name, table_name)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """)

            # Truncate + insert
            cur.execute(f"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}")
            cur.execute(gt_sql)

        conn.commit()
        print("mysql_007 ground_truth done: rows written to output table")
    except Exception as e:
        print(f"ground_truth error: {e}", file=sys.stderr)
        conn.rollback()
        sys.exit(1)
    finally:
        conn.close()


if __name__ == "__main__":
    main()