-- MySQL 数据库事务状态检查和处理 SQL 语句

-- 1. 查看当前所有连接和进程
SHOW PROCESSLIST;

-- 2. 查看当前正在运行的事务
SELECT 
    trx_id,
    trx_state,
    trx_started,
    trx_requested_lock_id,
    trx_wait_started,
    trx_weight,
    trx_mysql_thread_id,
    trx_query
FROM INFORMATION_SCHEMA.INNODB_TRX;

-- 3. 查看锁等待情况
SELECT 
    waiting_trx_id,
    waiting_thread,
    waiting_query,
    blocking_trx_id,
    blocking_thread,
    blocking_query
FROM INFORMATION_SCHEMA.INNODB_LOCK_WAITS;

-- 4. 查看当前锁定状态
SELECT 
    lock_id,
    lock_trx_id,
    lock_mode,
    lock_type,
    lock_table,
    lock_index,
    lock_space,
    lock_page,
    lock_rec,
    lock_data
FROM INFORMATION_SCHEMA.INNODB_LOCKS;

-- 5. 查看详细的锁等待信息（MySQL 8.0+）
SELECT 
    OBJECT_SCHEMA,
    OBJECT_NAME,
    LOCK_TYPE,
    LOCK_MODE,
    LOCK_STATUS,
    LOCK_DATA,
    ENGINE_TRANSACTION_ID,
    THREAD_ID,
    EVENT_ID
FROM performance_schema.data_locks;

-- 6. 查看锁等待关系（MySQL 8.0+）
SELECT 
    requesting_engine_transaction_id,
    requesting_thread_id,
    requesting_event_id,
    blocking_engine_transaction_id,
    blocking_thread_id,
    blocking_event_id
FROM performance_schema.data_lock_waits;

-- 7. 查看长时间运行的事务（超过30秒）
SELECT 
    trx_id,
    trx_state,
    trx_started,
    TIMESTAMPDIFF(SECOND, trx_started, NOW()) as duration_seconds,
    trx_mysql_thread_id,
    trx_query
FROM INFORMATION_SCHEMA.INNODB_TRX
WHERE TIMESTAMPDIFF(SECOND, trx_started, NOW()) > 30;

-- 8. 查看阻塞其他事务的连接
SELECT 
    p1.ID as blocking_thread_id,
    p1.USER as blocking_user,
    p1.HOST as blocking_host,
    p1.DB as blocking_db,
    p1.COMMAND as blocking_command,
    p1.TIME as blocking_time,
    p1.STATE as blocking_state,
    p1.INFO as blocking_query,
    p2.ID as blocked_thread_id,
    p2.USER as blocked_user,
    p2.HOST as blocked_host,
    p2.DB as blocked_db,
    p2.COMMAND as blocked_command,
    p2.TIME as blocked_time,
    p2.STATE as blocked_state,
    p2.INFO as blocked_query
FROM INFORMATION_SCHEMA.PROCESSLIST p1
JOIN INFORMATION_SCHEMA.INNODB_LOCK_WAITS w ON p1.ID = w.blocking_thread
JOIN INFORMATION_SCHEMA.PROCESSLIST p2 ON p2.ID = w.waiting_thread;

-- ===== 处理锁定事务的操作 =====

-- 9. 杀死指定的连接（替换 CONNECTION_ID 为实际的连接ID）
-- KILL CONNECTION_ID;

-- 示例：杀死连接ID为123的连接
-- KILL 123;

-- 10. 强制杀死指定连接（即使在事务中）
-- KILL CONNECTION CONNECTION_ID;

-- 11. 回滚指定事务（需要在对应连接中执行）
-- ROLLBACK;

-- 12. 设置锁等待超时（秒）
SET innodb_lock_wait_timeout = 50;

-- 13. 查看当前锁等待超时设置
SHOW VARIABLES LIKE 'innodb_lock_wait_timeout';

-- ===== 预防措施 =====

-- 14. 查看死锁信息
SHOW ENGINE INNODB STATUS;

-- 15. 开启死锁检测
SET GLOBAL innodb_deadlock_detect = ON;

-- 16. 查看事务隔离级别
SELECT @@tx_isolation;

-- 17. 设置事务隔离级别（如果需要）
-- SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

-- ===== 使用步骤说明 =====
/*
1. 首先运行查询1-4来了解当前事务状态
2. 找出长时间运行或阻塞的事务ID和连接ID
3. 使用KILL命令终止问题连接
4. 确认锁定已解除

注意：
- 在生产环境中谨慎使用KILL命令
- 优先尝试让应用程序正常提交或回滚事务
- 如果必须强制终止，确保了解可能的数据影响
*/ 