欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL找出未提交事务的SQL实例浅析

程序员文章站 2022-06-22 09:55:25
很久之前曾经总结过一篇博客“mysql如何找出未提交事务信息”,现在看来,这篇文章中不少知识点或观点都略显肤浅,或者说不够深入,甚至部分结论是错误的。下面重新探讨一下这个话题。那么我们还是以之前的例子...

很久之前曾经总结过一篇博客“mysql如何找出未提交事务信息”,现在看来,这篇文章中不少知识点或观点都略显肤浅,或者说不够深入,甚至部分结论是错误的。下面重新探讨一下这个话题。那么我们还是以之前的例子来介绍。

--准备测试环境数据(实验环境为mysql 8.0.18社区版)

mysql> create table kkk(id int , name varchar(12));
query ok, 0 rows affected (0.34 sec)
 
mysql> insert into kkk values(1, 'kerry');
query ok, 1 row affected (0.01 sec)
 
mysql> insert into kkk values(2, 'jerry');
query ok, 1 row affected (0.00 sec)
 
mysql> insert into kkk values(3, 'ken');
query ok, 1 row affected (0.00 sec)
 
mysql> 
 
mysql> create table t(a varchar(10));
query ok, 0 rows affected (0.47 sec)
 
mysql> insert into t values('test');
query ok, 1 row affected (0.00 sec)

在一个会话窗口(连接id=38)执行下面sql

mysql> select connection_id() from dual;
+-----------------+
| connection_id() |
+-----------------+
|  38 |
+-----------------+
1 row in set (0.00 sec)
 
mysql> set session autocommit=0;
query ok, 0 rows affected (0.00 sec)
 
mysql> delete from kkk where id =1;
query ok, 1 row affected (0.00 sec)
 
mysql> 

在另外一个会话窗口(连接id=39)执行下面sql

mysql> select t.trx_mysql_thread_id
 -> ,t.trx_id
 -> ,t.trx_state
 -> ,t.trx_tables_in_use
 -> ,t.trx_tables_locked
 -> ,t.trx_query
 -> ,t.trx_rows_locked 
 -> ,t.trx_rows_modified
 -> ,t.trx_lock_structs
 -> ,t.trx_started
 -> ,t.trx_isolation_level
 -> ,p.time 
 -> ,p.user
 -> ,p.host
 -> ,p.db
 -> ,p.command
 -> from information_schema.innodb_trx t 
 -> inner join information_schema.processlist p 
 ->  on t.trx_mysql_thread_id = p.id 
 -> where t.trx_state = 'running' 
 -> and p.time > 4 
 -> and p.command = 'sleep'\g 
*************************** 1. row ***************************
trx_mysql_thread_id: 38
  trx_id: 7981581
  trx_state: running
 trx_tables_in_use: 0
 trx_tables_locked: 1
  trx_query: null
 trx_rows_locked: 4
 trx_rows_modified: 1
 trx_lock_structs: 2
 trx_started: 2020-12-03 15:39:37
trx_isolation_level: repeatable read
  time: 23
  user: root
  host: localhost
   db: mydb
  command: sleep
1 row in set (0.00 sec)

虽然上面这个sql找不出事务执行过的sql,其实呢,mysql中未提交事务的最后执行的一个sql是可以通过下面脚本准确查找出来的。如下所示:

select t.trx_mysql_thread_id   as connection_id
 ,t.trx_id     as trx_id  
 ,t.trx_state     as trx_state 
 ,t.trx_started    as trx_started 
 ,timestampdiff(second,t.trx_started, now()) as "trx_run_time(s)" 
 ,t.trx_requested_lock_id   as trx_requested_lock_id
 ,t.trx_operation_state   as trx_operation_state
 ,t.trx_tables_in_use    as trx_tables_in_use
 ,t.trx_tables_locked    as trx_tables_locked
 ,t.trx_rows_locked    as trx_rows_locked
 ,t.trx_isolation_level   as trx_isolation_level
 ,t.trx_is_read_only    as trx_is_read_only
 ,t.trx_autocommit_non_locking   as trx_autocommit_non_locking
 ,e.event_name     as event_name
 ,e.timer_wait / 1000000000000   as timer_wait
 ,e.sql_text 
from information_schema.innodb_trx t, 
 performance_schema.events_statements_current e, 
 performance_schema.threads c 
where t.trx_mysql_thread_id = c.processlist_id 
 and e.thread_id = c.thread_id\g;

如下截图所示:

在会话窗口(连接id=38)继续执行下面sql:"select * from t;"。 如下所示

mysql> set session autocommit=0;
query ok, 0 rows affected (0.01 sec)
 
mysql> delete from kkk where id =1;
query ok, 1 row affected (0.00 sec)
 
mysql> select * from t;
+------+
| a |
+------+
| test |
+------+
1 row in set (0.00 sec)
 
mysql> 

在会话窗口(连接id=39)上继续执行下面sql,你会发现捕获的是事务最后执行的sql语句“select * from t”

mysql> select t.trx_mysql_thread_id   as connection_id
 -> ,t.trx_id     as trx_id  
 -> ,t.trx_state     as trx_state 
 -> ,t.trx_started    as trx_started 
 -> ,timestampdiff(second,t.trx_started, now()) as "trx_run_time(s)" 
 -> ,t.trx_requested_lock_id   as trx_requested_lock_id
 -> ,t.trx_operation_state   as trx_operation_state
 -> ,t.trx_tables_in_use    as trx_tables_in_use
 -> ,t.trx_tables_locked    as trx_tables_locked
 -> ,t.trx_rows_locked    as trx_rows_locked
 -> ,t.trx_isolation_level   as trx_isolation_level
 -> ,t.trx_is_read_only    as trx_is_read_only
 -> ,t.trx_autocommit_non_locking   as trx_autocommit_non_locking
 -> ,e.event_name     as event_name
 -> ,e.timer_wait / 1000000000000   as timer_wait
 -> ,e.sql_text 
 -> from information_schema.innodb_trx t, 
 -> performance_schema.events_statements_current e, 
 -> performance_schema.threads c 
 -> where t.trx_mysql_thread_id = c.processlist_id 
 -> and e.thread_id = c.thread_id\g; 
*************************** 1. row ***************************
  connection_id: 38
   trx_id: 7981581
   trx_state: running
  trx_started: 2020-12-03 15:39:37
  trx_run_time(s): 237
 trx_requested_lock_id: null
 trx_operation_state: null
  trx_tables_in_use: 0
  trx_tables_locked: 1
  trx_rows_locked: 4
 trx_isolation_level: repeatable read
  trx_is_read_only: 0
trx_autocommit_non_locking: 0
  event_name: statement/sql/select
  timer_wait: 0.0002
   sql_text: select * from t
1 row in set (0.00 sec)
 
error: 
no query specified

也是说上面sql只能获取未提交事务最后执行的一个sql语句,生产环境中,一个事务中往往不止一个sql语句,而是多个sql语句的集合。如果想将一个未提交事务里面所有执行过的sql找出来怎么办呢?其实在mysql中还是有办法的。下面sql语句就可以找出或者

select trx.trx_mysql_thread_id as processlist_id
 ,sc.thread_id
 ,trx.trx_started
 ,to_seconds(now())-to_seconds(trx_started) as trx_last_time 
 ,pc1.user
 ,pc1.host
 ,pc1.db
 ,sc.sql_text as current_sql_text
 ,sh.history_sql_test
from information_schema.innodb_trx trx
inner join information_schema.processlist pc1 on trx.trx_mysql_thread_id=pc1.id
inner join performance_schema.threads th on th.processlist_id = trx.trx_mysql_thread_id
inner join performance_schema.events_statements_current sc on sc.thread_id = th.thread_id
inner join (
  select thread_id as thread_id, group_concat(sql_text separator ';') as history_sql_test
  from performance_schema.events_statements_history 
  group by thread_id 
  ) sh on sh.thread_id = th.thread_id
where trx_mysql_thread_id != connection_id()
 and to_seconds(now())-to_seconds(trx_started) >= 0 ;

但是这两个sql有个问题:它会找出当前连接历史上所有执行过的sql(当然前提是这些sql还保存在performance_schema.events_statements_history表中),也就是说这个sql,不仅查询出未提交事务所有执行过的脚本,而且会查询出很多历史sql脚本,例如,这个会话(连接)之前事务的sql语句,而且还有一个比较头疼的问题:这里不好区分哪些sql对应哪些事务。需要借助其他信息来甄别。比较费时费力。如下截图所示。

因为只有information_schema.innodb_trx系统表中包含事务的开始时间(trx_started),其它系统表没有跟事务相关的时间,只能借助performance_schema.events_statements_history中的timer_start字段来获取事件的sql开始执行的时间,而这个时间必然是小于或等于对应事务的开始时间(trx_started)的。所以从这个突破口来找出未提交事务的所有sql,下面是关于timer_start等字段的详细介绍。

关于timer_start,timer_end,timer_wait的介绍如下:

timer_start,timer_end,timer_wait:事件的时间信息。这些值的单位是皮秒(万亿分之一秒)。

timer_start和timer_end值表示事件的开始时间和结束时间。

timer_wait是事件执行消耗的时间(持续时间)

如果事件未执行完成,则timer_end为当前时间,timer_wait为当前为止所经过的时间(timer_end - timer_start)。

如果监视仪器配置表setup_instruments中对应的监视器timed字段被设置为 no,则不会收集该监视器的时间信息,那么对于该事件采集的信息记录中,timer_start,timer_end和timer_wait字段值均为null

测试、折腾了好久,终于搞出了一个几乎完美的sql:

select @dt_ts:=unix_timestamp(now());
select 
 @dt_timer:=max(sh.timer_start)
from performance_schema.threads as t
inner join performance_schema.events_statements_history as sh
on t.`thread_id`=sh.`thread_id`
where t.processlist_id=connection_id();
 
 
select sh.current_schema  as database_name
 ,t.thread_id
 ,it.trx_mysql_thread_id  as connection_id
 ,it.trx_id
 ,sh.event_id
 ,it.trx_state
 ,replace(replace(replace(sh.`sql_text`,'\n',' '),'\r',' '),'\t',' ') as executed_sql
 ,it.trx_started
 ,from_unixtime(@dt_ts-cast((@dt_timer-sh.timer_start)/1000000000000 as signed)) as start_time
 ,from_unixtime(@dt_ts-cast((@dt_timer-sh.timer_end) /1000000000000 as signed)) as end_time
 ,(sh.timer_end-sh.timer_start)/1000000000000 as used_seconds
 ,sh.timer_wait/1000000000000 as wait_seconds
 ,sh.lock_time/1000000000000 as lock_seconds
 ,sh.rows_affected as affected_rows
 ,sh.rows_sent as send_rows
from performance_schema.threads as t
inner join information_schema.innodb_trx it on it.trx_mysql_thread_id = t.processlist_id 
inner join performance_schema.events_statements_history as sh
 on t.`thread_id`=sh.`thread_id`
where t.processlist_id in (
  select 
   p.id as conn_id
  from `information_schema`.`innodb_trx` t
  inner join `information_schema`.`processlist` p
   on t.trx_mysql_thread_id=p.id
  where t.trx_state='running'
   and p.command='sleep'
   and p.time>2
  )
and sh.timer_start<@dt_timer
and from_unixtime(@dt_ts-cast((@dt_timer-sh.timer_start)/1000000000000 as signed)) >=it.trx_started
order by it.trx_id asc, sh.timer_start asc;

它能找出未提交事务的sql,简单测试完全没有问题,同时构造几个未提交事务测试也ok。但是上面sql由三个sql组成,总感觉有点别扭,研究了一下,可以改造成下面sql。

select sh.current_schema  as database_name
 ,t.thread_id
 ,it.trx_mysql_thread_id as connection_id
 ,it.trx_id
 ,sh.event_id
 ,it.trx_state
 ,replace(replace(replace(sh.`sql_text`,'\n',' '),'\r',' '),'\t',' ') as executed_sql
 ,it.trx_started
 ,date_sub(now(), interval (select variable_value from performance_schema.global_status where variable_name='uptime') - sh.timer_start*10e-13 second) as start_time
 ,date_sub(now(), interval (select variable_value from performance_schema.global_status where variable_name='uptime') - sh.timer_end*10e-13 second) as end_time
 ,(sh.timer_end-sh.timer_start)/1000000000000 as used_seconds
 ,sh.timer_wait/1000000000000 as wait_seconds
 ,sh.lock_time/1000000000000 as lock_seconds
 ,sh.rows_affected as affected_rows
 ,sh.rows_sent as send_rows
from performance_schema.threads as t
inner join information_schema.innodb_trx it on it.trx_mysql_thread_id = t.processlist_id 
inner join performance_schema.events_statements_history as sh
 on t.`thread_id`=sh.`thread_id`
where t.processlist_id in (
  select 
   p.id as conn_id
  from `information_schema`.`innodb_trx` t
  inner join `information_schema`.`processlist` p
   on t.trx_mysql_thread_id=p.id
  where t.trx_state='running'
   and p.command='sleep'
   and p.time>2
  )
and sh.timer_start<(select variable_value*1000000000000 from performance_schema.global_status where variable_name='uptime')
and date_sub(now(), interval (select variable_value from performance_schema.global_status where variable_name='uptime') - sh.timer_start*10e-13 second) >=it.trx_started
order by it.trx_id asc, sh.timer_start asc;

注意:performance_schema.global_status是mysql 5.7引入的,如果数据库是mysql 5.6的话,可以用information_schema.global_status替换sql中的performance_schema.global_status

那么是否这个sql就一定完美了呢? 网友mssql123反馈在一个测试环境中,发现上面这种sql居然查不出任何数据,因为from_unixtime(@dt_ts-cast((@dt_timer-sh.timer_start)/1000000000000 as signed)) >=it.trx_started会将数据过滤掉,检查发现对应的trx_started值都大于start_time

-------------------------------------------------------------------------补充资料--------------------------------------------------------------------------------------------------------

那么同一个测试环境,隔天测试的时候,突然发现上面第一个sql正常,第二个sql就由于不同的写法,start_time有细微的差别,导致查询结果完全不同(第二个sql语句精确到毫秒,对比的时候由于偏差过滤掉一批数据)

------------------------------------------------------------------------------------------------------------------------------------------------

搜索相关文档,了解到timer_start字段值可能有波动或偏差,那么这个波动或偏差可能影响查询结果,下面内容来自http://porthos.ist.utl.pt/docs/mysql/performance-schema.html

modifications to the setup_timers table affect monitoring immediately. events already in progress may use the original timer for the begin time and the new timer for the end time. to avoid unpredictable results after you make timer changes, use truncate table to reset performance schema statistics.

the timer baseline (“time zero”) occurs at performance schema initialization during server startup. timer_start and timer_end values in events represent picoseconds since the baseline. timer_wait values are durations in picoseconds.

picosecond values in events are approximate. their accuracy is subject to the usual forms of error associated with conversion from one unit to another. if the cycle timer is used and the processor rate varies, there might be drift. for these reasons, it is not reasonable to look at the timer_start value for an event as an accurate measure of time elapsed since server startup. on the other hand, it is reasonable to use timer_start or timer_wait values in order by clauses to order events by start time or duration.

the choice of picoseconds in events rather than a value such as microseconds has a performance basis. one implementation goal was to show results in a uniform time unit, regardless of the timer. in an ideal world this time unit would look like a wall-clock unit and be reasonably precise; in other words, microseconds. but to convert cycles or nanoseconds to microseconds, it would be necessary to perform a division for every instrumentation. division is expensive on many platforms. multiplication is not expensive, so that is what is used. therefore, the time unit is an integer multiple of the highest possible timer_frequency value, using a multiplier large enough to ensure that there is no major precision loss. the result is that the time unit is “picoseconds.” this precision is spurious, but the decision enables overhead to be minimized.

before mysql 5.7.8, while a wait, stage, statement, or transaction event is executing, the respective current-event tables display the event with timer_start populated, but with timer_end and timer_wait set to null

其中一段内容翻译如下:

事件中的皮秒值是近似值。它们的准确性受与从一个单位转换到另一单位相关的常见误差形式的影响。如果使用了cycle定时器,并且处理器速率有所变化,则可能会有偏差。由于这些原因,将事件的timer_start值视为自服务器启动以来经过的时间的准确度量是不合理的。另一方面,在order by子句中使用timer_start或timer_wait值来按开始时间或持续时间对事件进行排序是合理的。

我们往往想一击必杀的解决问题,但是由于复杂的环境和一些不可控因素,现实往往就是“没有银弹”这么残酷。如果遇到timer_start的波动或偏差影响查询结果时,那么我们必须通过文章前面的sql找出大量sql,然后通过其它字段或信息人工甄别哪些才是未提交事务的sql。

参考资料:

https://*.com/questions/25607249/mysql-performance-schema-how-to-get-event-time-from-events-statements-current-ta

http://porthos.ist.utl.pt/docs/mysql/performance-schema.html

https://dev.mysql.com/doc/refman/5.7/en/performance-schema-timing.html

https://dev.mysql.com/doc/refman/8.0/en/performance-schema-timing.html

到此这篇关于mysql找出未提交事务sql的文章就介绍到这了,更多相关mysql找出未提交事务sql内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!