# Exposure Log First Exposure Time Computation (MySQL)

## Prompt
I need you to generate a MySQL script that computes the first exposure time for each advertisement from the exposure log table.

**Business Background and Objective**: The advertising system periodically writes exposure logs into a summary table. Downstream consumers need to compute the first exposure time per ad ID dimension and output the corresponding minute-level timestamp string. This task filters records from the input table that meet the specified partition and conditions, groups by ad ID to obtain the minimum exposure time, formats it as a minute-level string, and writes the results to the output table.

**Input Table (full name + brief description)**:
- `internal_platform_db.etl_pageview_exposure_mysql_015` (exposure log detail table)

(Please connect to the database and query to confirm the table structure and field semantics.)

**Processing Rules**:
- Single-table processing, no joins
- Filter condition: `partition_time = 2026060914` AND `ad_data_model_version = 3` AND `ad_optimization_goal > 0`
- Group by `ad_aid`, compute `MIN(action_imp_time)` as the first exposure time
- Format the first exposure time (millisecond timestamp divided by 1000 to convert to seconds) as a `yyyyMMddHHmm` string

**Column Mapping Rules**:
- Input column `ad_aid` → output column `aid`
- Aggregation result `MIN(action_imp_time)` → output column `first_time`
- Formatted string `FROM_UNIXTIME(MIN(action_imp_time)/1000, '%Y%m%d%H%i')` → output column `first_fen`
- Fixed value `2026060914` → output column `dt`

**Output Requirements**:
- Target table: `internal_platform_db.first_expo_time_cand_mysql_015`
- Output field order: `aid`, `first_time`, `first_fen`, `dt`
- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data
- Use standard MySQL syntax; do not use Hive/Spark SQL dialects

**Environment and Execution Notes**:
- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`
- The local MySQL is running at localhost:3306, username `root`, password `root123`
- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)
- The script must include complete table creation (if the target table does not exist) and data writing logic
- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data

## Reference Solution
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
mysql_015 ground truth: 曝光日志首次曝光时间计算

Task:
  Filter input table WHERE partition_time = 2026060914
    AND ad_data_model_version = 3 AND ad_optimization_goal > 0,
  group by ad_aid, compute MIN(action_imp_time) as first_time,
  format as FROM_UNIXTIME(MIN/1000, '%Y%m%d%H%i') as first_fen,
  write to output table with dt = 2026060914.
"""
import pymysql
import sys

DB_NAME = "internal_platform_db"
INPUT_TABLE = "etl_pageview_exposure_mysql_015"
OUTPUT_TABLE = "first_expo_time_cand_mysql_015"

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

gt_sql = f"""
INSERT INTO {DB_NAME}.{OUTPUT_TABLE}
    (aid, first_time, first_fen, dt)
SELECT
    ad_aid AS aid,
    MIN(action_imp_time) AS first_time,
    FROM_UNIXTIME(MIN(action_imp_time) / 1000, '%Y%m%d%H%i') AS first_fen,
    2026060914 AS dt
FROM {DB_NAME}.{INPUT_TABLE}
WHERE partition_time = 2026060914
  AND ad_data_model_version = 3
  AND ad_optimization_goal > 0
GROUP BY ad_aid
ORDER BY ad_aid
"""


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

    try:
        with conn.cursor() as cur:
            # Ensure consistent timezone (Hive cluster was UTC+8)
            cur.execute("SET SESSION time_zone = '+08:00'")

            # Ensure output table exists
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (
                    aid          BIGINT       NOT NULL,
                    first_time   BIGINT       NOT NULL,
                    first_fen    VARCHAR(32) NOT NULL,
                    dt           BIGINT       NOT NULL,
                    PRIMARY KEY (aid, dt)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
            """)

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

        conn.commit()
        print("mysql_015 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()