-- card_id: SQL-MY-03
-- title: MySQL 8.x 慢查询指纹摘要（只读、脱敏）
-- engine: MySQL
-- versions: 8.0, 8.4
-- risk: R2
-- purpose: 从最近 24 小时摘要中列出总耗时最高的最多 50 个 SQL 指纹，供人工复核。
-- input: 把 replace_with_schema 改为已获授权的目标 schema；不要使用客户原始资料。
-- output: 观察状态、schema 哈希、digest、调用次数、总/平均耗时、扫描行数、最近观察时间；不含 SQL 文本。
-- permission: performance_schema.events_statements_summary_by_digest 的 SELECT 权限。
-- resource_limit: 固定 24 小时、Top 50，建议客户端超时 10 秒。
-- validation: 已在 MySQL 8.0/8.4 隔离合成负载验证；5.7、生产及客户环境未验证。
-- failure: performance_schema 未启用时返回明确状态行，权限不足时报错；目标 schema 无样本时返回空结果。
-- prohibited: 不得开启消费者、慢日志或修改参数；不得据此自动加索引、改 SQL、KILL 会话或输出 SQL 文本。

SELECT
    'ready' AS observation_status,
    SHA2(CONCAT('sql-card-v1:', s.SCHEMA_NAME), 256) AS schema_fingerprint,
    s.DIGEST AS statement_digest,
    s.COUNT_STAR AS call_count,
    ROUND(s.SUM_TIMER_WAIT / 1000000000000, 6) AS total_seconds,
    ROUND(s.AVG_TIMER_WAIT / 1000000000000, 6) AS avg_seconds,
    s.SUM_ROWS_EXAMINED AS rows_examined,
    s.LAST_SEEN AS last_seen
FROM performance_schema.events_statements_summary_by_digest AS s
WHERE s.SCHEMA_NAME = 'replace_with_schema'
  AND s.DIGEST IS NOT NULL
  AND s.LAST_SEEN >= CURRENT_TIMESTAMP - INTERVAL 24 HOUR
UNION ALL
SELECT
    'performance_schema_disabled' AS observation_status,
    SHA2(CONCAT('sql-card-v1:', 'replace_with_schema'), 256) AS schema_fingerprint,
    NULL AS statement_digest,
    0 AS call_count,
    NULL AS total_seconds,
    NULL AS avg_seconds,
    NULL AS rows_examined,
    NULL AS last_seen
WHERE @@performance_schema = 0
ORDER BY
    total_seconds DESC,
    statement_digest
LIMIT 50;
