information_schema.tables 视图中,表的最后修改时间靠谱吗?
information_schema.tables 视图中,update_time
字段记录了表的最后修改时间,即某个表最后一次插入、更新、删除记录的事务提交时间。
update_time 字段有个问题,就是它记录的表的最后修改时间不一定靠谱。
从省事的角度来说,既然它太不靠谱,我们不用它就好了。
但是,本着不放过一个坏蛋,不错过一个好蛋的原则,我们可以花点时间,摸清楚它的底细。
接下来,我们围绕下面 2 个问题,对 update_time
做个深入了解:
- 它记录的表的最后修改时间从哪里来?
- 它为什么不靠谱?
本文基于 MySQL 8.0.32 源码,存储引擎为 InnoDB。
转载请联系『一树一溪』公众号作者,转载后请标明来源。
目录
[TOC]
正文
1. 准备工作
创建测试表:
1USE `test`;
2
3CREATE TABLE `t1` (
4 `id` int unsigned NOT NULL AUTO_INCREMENT,
5 `i1` int DEFAULT '0',
6 PRIMARY KEY (`id`) USING BTREE
7) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
插入测试数据:
1INSERT INTO `t1`(i1) VALUES (10), (20), (30);
顺便看一眼 information_schema.tables 视图的 update_time 字段:
1-- 第 1 步:设置缓存时间为 0
2-- 忽略 mysql.table_stats 中
3-- 持久化的 update_time 字段值
4-- 直接从 InnoDB 中获取
5-- update_time 字段的最新值
6SET information_schema_stats_expiry = 0;
7
8-- 第 2 步:执行查询
9SELECT * FROM information_schema.tables
10WHERE table_schema = 'test'
11AND table_name = 't1'\G
12
13-- 查询结果
14**************************[ 1. row ]***************************
15TABLE_CATALOG | def
16TABLE_SCHEMA | test
17TABLE_NAME | t1
18TABLE_TYPE | BASE TABLE
19ENGINE | InnoDB
20VERSION | 10
21ROW_FORMAT | Dynamic
22TABLE_ROWS | 3
23AVG_ROW_LENGTH | 5461
24DATA_LENGTH | 16384
25MAX_DATA_LENGTH | 0
26INDEX_LENGTH | 0
27DATA_FREE | 6291456
28AUTO_INCREMENT | 4
29CREATE_TIME | 2023-06-18 15:49:17
30UPDATE_TIME | 2023-06-18 15:50:37
31CHECK_TIME | <null>
32TABLE_COLLATION | utf8mb3_general_ci
33CHECKSUM | <null>
34CREATE_OPTIONS |
35TABLE_COMMENT |
因为系统变量 information_schema_stats_expiry
的值已经设置为 0
,所以能够读取到 t1 表最新的 update_time。
上面查询结果中,update_time 就是插入测试数据的事务的提交时间
。
2. 来龙去脉
2.1 标记表发生了变化
某个表插入、更新、删除记录的过程中,写 undo 日志之前,trx_undo_report_row_operation()
会先记下来这个表的数据发生了变化:
1// storage/innobase/trx/trx0rec.cc
2dberr_t trx_undo_report_row_operation(...)
3{
4 ...
5 bool is_temp_table = index->table->is_temporary();
6 ...
7 if (!is_temp_table) {
8 trx->mod_tables.insert(index->table);
9 }
10 ...
11}
有一点需要说明:只有非临时表的数据发生变化,才会被标记。对于临时表,就不管了。
trx->mod_tables 是个集合,类型是 std::set,定义如下:
1// storage/innobase/include/trx0trx.h
2// 为了方便阅读,这个定义经过了格式化
3typedef std::set<
4 dict_table_t *,
5 std::less<dict_table_t *>,
6 ut::allocator<dict_table_t *>>
7trx_mod_tables_t;
8
9// storage/innobase/include/trx0trx.h
10struct trx_t {
11 ...
12 trx_mod_tables_t mod_tables;
13 ...
14}
集合中保存的是 InnoDB 表对象的指针 dict_table_t *
,dict_table_t 结构体的 update_time
属性用于保存表的最后修改时间:
1// storage/innobase/include/dict0mem.h
2struct dict_table_t {
3 ...
4 /** Timestamp of the last modification of this table. */
5 // 为了方便阅读,这个定义经过了格式化
6 std::atomic<
7 std::chrono::system_clock::time_point>
8 update_time;
9 ...
10}
trx_undo_report_row_operation() 只会标记表的数据发生了变化,不会
修改表的 dict_table_t 对象的 update_time
属性。
2.2 确定变化时间
1// storage/innobase/trx/trx0trx.cc
2dberr_t trx_commit_for_mysql(trx_t *trx) /*!< in/out: transaction */
3{
4 ...
5 // 获取事务状态
6 switch (trx->state.load(std::memory_order_relaxed)) {
7 ...
8 // 事务为活跃状态
9 case TRX_STATE_ACTIVE:
10 // 事务处于二阶段提交的 PREPARE 阶段
11 case TRX_STATE_PREPARED:
12 trx->op_info = "committing";
13 ...
14 // 说明是读写事务
15 if (trx->id != 0) {
16 // 确定表的最后修改时间
17 trx_update_mod_tables_timestamp(trx);
18 }
19
20 trx_commit(trx);
21
22 MONITOR_DEC(MONITOR_TRX_ACTIVE);
23 trx->op_info = "";
24 return (DB_SUCCESS);
25 case TRX_STATE_COMMITTED_IN_MEMORY:
26 break;
27 }
28 ...
29}
读写事务提交时,trx_commit_for_mysql()
调用 trx_update_mod_tables_timestamp()
,把当前时间保存到表的 dict_table_t 对象的 update_time
属性中。
1// storage/innobase/trx/trx0trx.cc
2static void trx_update_mod_tables_timestamp(trx_t *trx) /*!< in: transaction */
3{
4 ...
5 // 获取当前时间
6 const auto now = std::chrono::system_clock::from_time_t(time(nullptr));
7
8 trx_mod_tables_t::const_iterator end = trx->mod_tables.end();
9 // 迭代 trx->mod_tables 集合中的每个表
10 for (trx_mod_tables_t::const_iterator it = trx->mod_tables.begin(); it != end;
11 ++it) {
12 // 把当前时间赋值给 dict_table_t 对象
13 // 的 update_time 属性
14 (*it)->update_time = now;
15 }
16
17 trx->mod_tables.clear();
18}
trx->mod_tables 中保存的是数据发生变化的表的 dict_table_t
对象指针,for 循环每迭代一个对象指针,都把该对象的 update_time 属性值设置为当前时间。
这就说明了 update_time 属性中保存的表的最后修改时间是执行 DML SQL 的事务提交时间。
循环结束之后,清空 trx->mod_tables
集合。
执行流程进行到这里,表的最后修改时间还只是存在于它的 dict_table_t 对象中,也就是仅仅位于内存中。
此时,如果某个(些)表的 dict_table_t 对象被从 InnoDB 的缓存中移除了,它(们)的 update_time
也就丢失了。
如果发生了更不幸的事:MySQL 挂了,或者服务器突然断电了,所有表的 update_time 属性值就全都丢失了。
那要怎么办呢?当然只能是持久化了。
2.3 持久化
dict_table_t 对象的 update_time 属性值,会被保存(持久化
)到 mysql.table_stats
表中,这个操作包含于
表的统计信息持久化过程中,有两种方式:
- 主动持久化。
- 被动持久化。
2.3.1 主动持久化
analyze table <table_name>
执行过程中,会把表的统计信息持久化到 mysql.table_stats
表中,这些统计信息里就包含了 dict_table_t 对象的 update_time 属性。
我们把这种场景称为主动持久化
,部分堆栈如下:
1| > mysql_execute_command() sql/sql_parse.cc:4688
2| + > Sql_cmd_analyze_table::execute() sql/sql_admin.cc:1735
3| + - > mysql_admin_table() sql/sql_admin.cc:1128
4| + - x > handler::ha_analyze(THD*, HA_CHECK_OPT*) sql/handler.cc:4783
5| + - x = > ha_innobase::analyze(THD*, HA_CHECK_OPT*) storage/innobase/handler/ha_innodb.cc:18074
6| + - x = | > ha_innobase::info_low(unsigned int, bool) storage/innobase/handler/ha_innodb.cc:17221
7| + - x > info_schema::update_table_stats(THD*, Table_ref*) sql/dd/info_schema/table_stats.cc:338
8| + - x = > setup_table_stats_record() sql/dd/info_schema/table_stats.cc:179
9| + - x = > Dictionary_client::store<dd::Table_stat>() sql/dd/impl/cache/dictionary_client.cc:2595
10| + - x = | > Storage_adapter::store<dd::Table_stat>() sql/dd/impl/cache/storage_adapter.cc:334
11| + - x = | + > dd::Weak_object_impl_<true>::store() sql/dd/impl/types/weak_object_impl.cc:106
12| + - x = | + - > Table_stat_impl::store_attributes() sql/dd/impl/types/table_stat_impl.cc:81
ha_innobase::analyze() 调用 ha_innobase::info_low()
,从 dict_table_t 对象中获取 update_time
属性值(即表的最后修改时间)。
1// storage/innobase/handler/ha_innodb.cc
2int ha_innobase::info_low(uint flag, bool is_analyze) {
3 dict_table_t *ib_table;
4 ...
5 if (flag & HA_STATUS_TIME) {
6 ...
7 stats.update_time = (ulong)std::chrono::system_clock::to_time_t(
8 ib_table->update_time.load());
9 }
10 ...
11}
ib_table 是 dict_table_t 对象,事务提交过程中,trx_update_mod_tables_timestamp()
会把事务提交时间保存到 ib_table->update_time
中。
这里,dict_table_t 对象的 update_time 属性值会转移阵地,保存到 stats 对象中备用
,stats 对象的类型为 ha_statistics
。
说到备用,我马上想到的是教人做菜的节目,比如:炸好的茄子捞出沥油,放在一旁备用。你想到了什么?
1// sql/dd/info_schema/table_stats.cc
2bool update_table_stats(THD *thd, Table_ref *table) {
3 // Update the object properties
4 HA_CREATE_INFO create_info;
5
6 TABLE *analyze_table = table->table;
7 handler *file = analyze_table->file;
8 // ha_innobase::info()
9 if (analyze_table->file->info(
10 HA_STATUS_VARIABLE |
11 HA_STATUS_TIME |
12 HA_STATUS_VARIABLE_EXTRA |
13 HA_STATUS_AUTO) != 0)
14 return true;
15
16 file->update_create_info(&create_info);
17
18 // 构造 Table_stat 对象
19 std::unique_ptr<Table_stat> ts_obj(create_object<Table_stat>());
20
21 // 为 Table_stat 对象的各属性赋值
22 setup_table_stats_record(
23 thd, ts_obj.get(),
24 dd::String_type(table->db, strlen(table->db)),
25 dd::String_type(table->alias, strlen(table->alias)),
26 file->stats, file->checksum(),
27 file->ha_table_flags() & (ulong)HA_HAS_CHECKSUM,
28 analyze_table->found_next_number_field
29 );
30
31 // 持久化
32 return thd->dd_client()->store(ts_obj.get()) &&
33 report_error_except_ignore_dup(thd, "table");
34}
update_table_stats() 调用 ha_innobase::info()
,从 InnoDB 中获取表的信息。
ha_innobase::info() 会调用 ha_innobase::info_low()
,把 dict_table_t 对象的 update_time 属性值保存到 stats 对象中(类型为 ha_statistics
),也就是上面代码中的 file->stats
。
这是 update_time 属性值第 1 次转移阵地:
- dict_table_t -> ha_statistics
analyze 过程中,ha_innobase::analyze()
、ha_innobase::info()
都会调用 ha_innobase::info_low()
,看起来是重复调用了,不过,这两次调用的参数值
不完全一样,我们就不深究了。
create_object<Table_stat>() 构造一个空的 Table_stat
对象,setup_table_stats_record() 为该对象的各属性赋值。
1inline void setup_table_stats_record(THD *thd, dd::Table_stat *obj, ...) {
2 ...
3 // stats 的类型为 ha_statistics
4 if (stats.update_time) {
5 // obj 的类型为 Table_stat
6 obj->set_update_time(dd::my_time_t_to_ull_datetime(stats.update_time));
7 }
8 ...
9}
setup_table_stats_record() 调用 obj->set_update_time()
把 stats.update_time 赋值给 obj.update_time
。
obj 对象的类型为 Table_stat,到这里,update_time
属性值已经是第 2 次转移阵地了:
- dict_table_t -> ha_statistics
- ha_statistics -> Table_stat
setup_table_stats_record() 为 Table_stat 对象各属性赋值完成之后,update_table_stats() 接着调用 thd->dd_client()->store()
,经过多级之后,调用 Weak_object_impl_<use_pfs>::store()
执行持久化操作。
1// sql/dd/impl/types/weak_object_impl.cc
2// 为了方便介绍,我们以 t1 表为例
3// 介绍表的统计信息持久化过程
4template <bool use_pfs>
5bool Weak_object_impl_<use_pfs>::store(Open_dictionary_tables_ctx *otx) {
6 ...
7 const Object_table &obj_table = this->object_table();
8 // obj_table.name() 的返回值为 table_stats
9 // 即 mysql 库的 table_stats 表
10 Raw_table *t = otx->get_table(obj_table.name());
11 ...
12 do {
13 ...
14 // 构造主键作为查询条件
15 // 数据库名:test、表名:t1
16 std::unique_ptr<Object_key> obj_key(this->create_primary_key());
17 ...
18 //
19 // 从 mysql.table_stats 表中
20 // 查询之前持久化的 t1 表的统计信息
21 std::unique_ptr<Raw_record> r;
22 if (t->prepare_record_for_update(*obj_key, r)) return true;
23 // 如果 mysql.table_stats 表中
24 // 不存在 t1 表的统计信息
25 // 则结束循环
26 if (!r.get()) break;
27
28 // Existing record found -- do an UPDATE.
29 // 如果 mysql.table_stats 表中
30 // 存在 t1 表的统计信息
31 // 则用 this 对象中 t1 表的最新统计信息
32 // 替换 Raw_record 对象中对应的字段值
33 if (this->store_attributes(r.get())) {
34 my_error(ER_UPDATING_DD_TABLE, MYF(0), obj_table.name().c_str());
35 return true;
36 }
37 // 把 Raw_record 对象中 t1 表的最新统计信息
38 // 更新到 mysql.table_stats 表中
39 if (r->update()) return true;
40
41 return store_children(otx);
42 } while (false);
43
44 // No existing record exists -- do an INSERT.
45 std::unique_ptr<Raw_new_record> r(t->prepare_record_for_insert());
46
47 // Store attributes.
48 // Table_stat_impl::store_attributes()
49 if (this->store_attributes(r.get())) {
50 my_error(ER_UPDATING_DD_TABLE, MYF(0), obj_table.name().c_str());
51 return true;
52 }
53
54 // t1 表的最新统计信息
55 // 插入到 mysql.table_stats 表中
56 if (r->insert()) return true;
57 ...
58}
在代码注释中,我们说明了以 t1 表为例,来介绍 Weak_object_impl_<use_pfs>::store()
的代码逻辑。
obj_key 是一个包含数据库名、表名的对象,用于调用 t->prepare_record_for_update()
从 mysql.table_stats
中查询之前持久化的 t1 表的统计信息。
如果查询到了 t1 表的统计信息,则保存到 Raw_record
对象中(指针 r 引用的对象),调用 this->store_attributes()
,用 t1 表的最新统计信息替换 Raw_record 对象的相应字段值,得到代表 t1 表最新统计信息的 Raw_record 对象。
这里,update_time 属性值会第 3 次转移阵地:
- dict_table_t -> ha_statistics
- ha_statistics -> Table_stat
- Table_stat -> Raw_record
1// sql/dd/impl/types/table_stat_impl.cc
2bool Table_stat_impl::store_attributes(Raw_record *r) {
3 return r->store(Table_stats::FIELD_SCHEMA_NAME, m_schema_name) ||
4 r->store(Table_stats::FIELD_TABLE_NAME, m_table_name) ||
5 r->store(Table_stats::FIELD_TABLE_ROWS, m_table_rows) ||
6 r->store(Table_stats::FIELD_AVG_ROW_LENGTH, m_avg_row_length) ||
7 r->store(Table_stats::FIELD_DATA_LENGTH, m_data_length) ||
8 r->store(Table_stats::FIELD_MAX_DATA_LENGTH, m_max_data_length) ||
9 r->store(Table_stats::FIELD_INDEX_LENGTH, m_index_length) ||
10 r->store(Table_stats::FIELD_DATA_FREE, m_data_free) ||
11 r->store(Table_stats::FIELD_AUTO_INCREMENT, m_auto_increment,
12 m_auto_increment == (ulonglong)-1) ||
13 r->store(Table_stats::FIELD_CHECKSUM, m_checksum, m_checksum == 0) ||
14 r->store(Table_stats::FIELD_UPDATE_TIME, m_update_time,
15 m_update_time == 0) ||
16 r->store(Table_stats::FIELD_CHECK_TIME, m_check_time,
17 m_check_time == 0) ||
18 r->store(Table_stats::FIELD_CACHED_TIME, m_cached_time);
19}
调用 this->store_attributes()
得到 t1 表的最新统计信息之后,Weak_object_impl_<use_pfs>::store()
接下来调用 r->update()
把 t1 表的最新统计信息更新到 mysql.table_stats
中,完成持久化操作。
如果 t->prepare_record_for_update()
没有查询到表的统计信息,执行流程在 if (!r.get()) break
处会结束 while 循环。
之后,调用 t->prepare_record_for_insert()
构造一个初始化状态的 Raw_record 对象(指针 r 引用的对象),再调用 this->store_attributes()
把 t1 表的最新统计信息赋值给 Raw_record 对象的相应字段。
最后,调用 r->insert() 把 t1 表的统计信息插入到 mysql.table_stats
中,完成持久化操作。
2.3.2 被动持久化
从 information_schema.tables 视图查询一个或多个表的信息时,对于每一个表,如果该表的统计信息从来没有持久化过,或者上次持久化的统计信息已经过期,MySQL 会从 InnoDB 中获取该表的最新统计信息,并持久化到 mysql.table_stats
中。
上面的描述有一个前提:对于每一个表,该表的统计信息需要持久化。
那么,怎么判断 mysql.table_stats 中某个表的统计信息是否过期?
逻辑是这样的:对于每一个表,如果距离该表上一次持久化统计信息的时间,大于
系统变量 information_schema_stats_expiry
的值,说明该表的统计信息已经过期了。
information_schema_stats_expiry 的默认值为 86400s。
因为这种持久化是在查询 information_schema.tables
视图过程中触发的,为了区分,我们把这种持久化称为被动持久化
。
被动持久化介绍起来会复杂一点点,我们以查询 t1 表的信息为例,SQL 如下:
1SELECT * FROM information_schema.tables
2WHERE table_schema = 'test' AND
3table_name = 't1'\G
被动持久化的部分堆栈如下:
1| > Query_expression::ExecuteIteratorQuery() sql/sql_union.cc:1763
2| + > NestedLoopIterator::Read() sql/iterators/composite_iterators.cc:465
3| + > Query_result_send::send_data() sql/query_result.cc:100
4| + - > THD::send_result_set_row() sql/sql_class.cc:2878
5| + - x > Item_view_ref::send() sql/item.cc:8682
6| + - x = > Item_ref::send() sql/item.cc:8327
7| + - x = | > Item::send() sql/item.cc:7299
8| + - x = | + > Item_func_if::val_int() sql/item_cmpfunc.cc:3516
9| + - x = | + - > Item_func_internal_table_rows::val_int() sql/item_func.cc:9283
10| + - x = | + - x > get_table_statistics() sql/item_func.cc:9268
11| + - x = | + - x = > Table_statistics::read_stat() sql/dd/info_schema/table_stats.h:208
12| + - x = | + - x = | > Table_statistics::read_stat() sql/dd/info_schema/table_stats.cc:457
13| + - x = | + - x = | + > is_persistent_statistics_expired() sql/dd/info_schema/table_stats.cc:86
14| + - x = | + - x = | + > Table_statistics::read_stat_from_SE() sql/dd/info_schema/table_stats.cc:563
15| + - x = | + - x = | + - > innobase_get_table_statistics() storage/innobase/handler/ha_innodb.cc:17642
16| + - x = | + - x = | + - > Table_statistics::cache_stats_in_mem() sql/dd/info_schema/table_stats.h:163
17| + - x = | + - x = | + - > persist_i_s_table_stats() sql/dd/info_schema/table_stats.cc:247
18| + - x = | + - x = | + - x > store_statistics_record<dd::Table_stat>() sql/dd/info_schema/table_stats.cc:147
19| + - x = | + - x = | + - x = > Dictionary_client::store<dd::Table_stat>() sql/dd/impl/cache/dictionary_client.cc:2595
20| + - x = | + - x = | + - x = | > Storage_adapter::store<dd::Table_stat>() sql/dd/impl/cache/storage_adapter.cc:334
21| + - x = | + - x = | + - x = | + > dd::Weak_object_impl_<true>::store() sql/dd/impl/types/weak_object_impl.cc:106
NestedLoopIterator::Read() 从 mysql.table_stats
表中读取 t1 表的统计信息。
information_schema.tables 视图会从 5 个基表(base table)中读取数据,执行流程会嵌套调用
NestedLoopIterator::Read()
,共5
层,以实现嵌套循环连接,为了简洁,这里只保留了 1 层。
NestedLoopIterator::Read() 从 information_schema.tables
视图的 5 个基表各读取一条对应的记录,并从中抽取客户端需要的字段,合并成为一条记录,用于发送给客户端。
MySQL 中实际只有抽取字段的过程,没有合并成为一条记录的过程,只是为了方便理解,才引入了
合并
这一描述。
不过,最终发送给客户端的记录的各个字段,不一定取自 5 个基表中读取的记录。
因为,从其中一个基表(mysql.table_stats)读取的 t1 表的统计信息,带有过期逻辑,如果统计信息过期了,会触发从 InnoDB 获取 t1 表的最新统计信息,替换掉从 mysql.table_stats 中读取到的相应字段,用于发送给客户端。
information_schema.tables 视图定义中,table_rows
是从基表 mysql.table_stats 读取的第 1 个字段,所以,发送 table_rows 字段值给客户端的过程中,会调用 is_persistent_statistics_expired()
判断 mysql.table_stats 中持久化的 t1 表的统计信息是否过期。
1// sql/dd/info_schema/table_stats.cc
2// 为了方便理解,以 t1 表为例,
3// 介绍判断持久化统计信息是否过期的逻辑
4inline bool is_persistent_statistics_expired(
5 THD *thd, const ulonglong &cached_timestamp) {
6 // Consider it as expired if timestamp or timeout is ZERO.
7 // !cached_timestamp = true,
8 // 表示 t1 表的统计信息从来没有持久化过
9 // !information_schema_stats_expiry = true,
10 // 表示不需要持久化任何表的统计信息
11 if (!cached_timestamp || !thd->variables.information_schema_stats_expiry)
12 return true;
13
14 // Convert longlong time to MYSQL_TIME format
15 // cached_timestamp 表示上次持久化
16 // t1 表统计信息的时间,
17 // 对应 mysql.table_stats
18 // 表的 cached_time 字段,
19 // 变量值的格式为 20230619063657
20 // 这里会从 cached_timestamp 中抽取
21 // 年、月、日、时、分、秒,
22 // 分别保存到 cached_mysql_time 对象的相应属性中
23 MYSQL_TIME cached_mysql_time;
24 my_longlong_to_datetime_with_warn(cached_timestamp, &cached_mysql_time,
25 MYF(0));
26
27 /*
28 Convert MYSQL_TIME to epoc second according to local time_zone as
29 cached_timestamp value is with local time_zone
30 */
31 my_time_t cached_epoc_secs;
32 bool not_used;
33 // 上次持久化 t1 表的时间,转换为时间戳
34 cached_epoc_secs =
35 thd->variables.time_zone->TIME_to_gmt_sec(&cached_mysql_time, ¬_used);
36 // 当前 SQL 开始执行的时间戳
37 // 在 dispatch_command() 中赋值
38 long curtime = thd->query_start_in_secs();
39 ulonglong time_diff = curtime - static_cast<long>(cached_epoc_secs);
40 // 当前 SQL 开始执行的时间戳
41 // - 上一次持久化 t1 表的时间戳
42 // 是否大于系统变量 information_schema_stats_expiry 的值
43 return (time_diff > thd->variables.information_schema_stats_expiry);
44}
is_persistent_statistics_expired() 有 3 个判断条件:
条件 1:!cached_timestamp = true
,说明 t1 表的统计信息从来没有持久化过,接下来需要从 InnoDB 获取 t1 表的最新统计信息,用于持久化和返回给客户端。
条件 2:!thd->variables.information_schema_stats_expiry = true
,说明系统变量 information_schema_stats_expiry
的值为 0,表示不需要
持久化任何表(当然包含 t1 表)的统计信息,接下来需要从 InnoDB 获取 t1 表的最新统计信息,用于返回给客户端。
条件 3:time_diff > thd->variables.information_schema_stats_expiry
,这是 return 语句中的判断条件。
如果此条件值为 true,说明当前 SQL 的开始执行时间减去
上一次持久化 t1 表统计信息的时间,大于
系统变量 information_schema_stats_expiry
的值,说明之前持久化的 t1 表统计信息已经过期,接下来需要从 InnoDB 获取 t1 表的最新统计信息,用于持久化和返回给客户端。
对于 t1 表,不管上面 3 个条件中哪一个成立,is_persistent_statistics_expired()
都会返回 true
。
接下来,Table_statistics::read_stat() 都会调用 Table_statistics::read_stat_from_SE()
从 InnoDB 获取 t1 表的最新统计信息。
1// sql/dd/info_schema/table_stats.cc
2// 为了方便理解,同样以 t1 表为例
3// 代码中 table_name_ptr 对应的表就是 t1
4ulonglong Table_statistics::read_stat_from_SE(...) {
5 ...
6 if (error == 0) {
7 ...
8 if ...
9 // 调用 innobase_get_table_statistics()
10 // 从 InnoDB 获取 t1 表的统计信息
11 else if (!hton->get_table_statistics(
12 schema_name_ptr.ptr(),
13 table_name_ptr.ptr(),
14 se_private_id,
15 *ts_se_private_data_obj.get(),
16 *tbl_se_private_data_obj.get(),
17 HA_STATUS_VARIABLE | HA_STATUS_TIME |
18 HA_STATUS_VARIABLE_EXTRA | HA_STATUS_AUTO,
19 &ha_stat)) {
20 error = 0;
21 }
22 ...
23 }
24
25 // Cache and return the statistics
26 if (error == 0) {
27 if (stype != enum_table_stats_type::INDEX_COLUMN_CARDINALITY) {
28 cache_stats_in_mem(schema_name_ptr, table_name_ptr, ha_stat);
29 ...
30 // 调用 can_persist_I_S_dynamic_statistics()
31 // 判断是否要持久化 t1 表的统计信息
32 // 如果需要持久化,
33 // 则调用 persist_i_s_table_stats()
34 // 把 t1 表的最新统计信息
35 // 保存到 mysql.table_stats 表中
36 if (can_persist_I_S_dynamic_statistics(...) &&
37 persist_i_s_table_stats(...)) {
38 error = -1;
39 } else
40 // 持久化成功之后,从 ha_stat 中读取
41 // stype 对应的字段值返回
42 // 对于 SELECT * FROM information_schema.tables
43 // stype 的值为
44 // enum_table_stats_type::TABLE_ROWS
45 return_value = get_stat(ha_stat, stype);
46 }
47 ...
48 }
49 ...
50}
Table_statistics::read_stat_from_SE()
先调用 hton->get_table_statistics()
从存储引擎获取 t1 表的统计信息,对于 InnoDB,对应的方法为 innobase_get_table_statistics()
。
获取 t1 表的统计信息之后,先调用 can_persist_I_S_dynamic_statistics()
判断是否需要持久化表的统计信息到 mysql.table_stats 中。
1// sql/dd/info_schema/table_stats.cc
2// 为了方便阅读,以下代码的格式被修改过了
3inline bool can_persist_I_S_dynamic_statistics(...) {
4 handlerton *ddse = ha_resolve_by_legacy_type(thd, DB_TYPE_INNODB);
5 if (ddse == nullptr || ddse->is_dict_readonly()) return false;
6
7 return (/* 1 */ thd->variables.information_schema_stats_expiry &&
8 /* 2 */ !thd->variables.transaction_read_only &&
9 /* 3 */ !super_read_only &&
10 /* 4 */ !thd->in_sub_stmt &&
11 /* 5 */ !read_only &&
12 /* 6 */ !partition_name &&
13 /* 7 */ !thd->in_multi_stmt_transaction_mode() &&
14 /* 8 */ (strcmp(schema_name, "performance_schema") != 0));
15}
return 语句中,所有判断条件的值都必须为 true
,t1 表的统计信息才会被持久化到 mysql.table_stats
中,这些条件的含义如下:
条件 1:thd->variables.information_schema_stats_expiry = true
,表示系统变量 information_schema_stats_expiry
的值大于 0。
条件 2:!thd->variables.transaction_read_only = true
,表示系统变量 transaction_read_only
的值为 false,MySQL 能够执行读写事务。
条件 3、5:!super_read_only = true
,并且 !read_only = true
,表示系统变量 super_read_only
、read_only
的值都为 false,MySQL 没有
被设置为只读模式。
条件 4:!thd->in_sub_stmt = true
,表示当前执行的 SQL 不是触发器触发执行的、也不是存储过程中的 SQL。
条件 6:!partition_name = true
,表示 t1 表不是分区表。
条件 7:!thd->in_multi_stmt_transaction_mode()
,表示当前事务是自动提交事务,即一个事务只会执行一条 SQL。
条件 8:strcmp(schema_name, "performance_schema") != 0)
,表示 t1 表的数据库名不是 performance_schema
。
如果 Table_statistics::read_stat_from_SE() 调用 can_persist_I_S_dynamic_statistics()
得到的返回值为 true,说明需要持久化 t1 表的统计信息,调用 persist_i_s_table_stats()
执行持久化操作。
1// sql/dd/info_schema/table_stats.cc
2static bool persist_i_s_table_stats(...) {
3 // Create a object to be stored.
4 std::unique_ptr<dd::Table_stat> ts_obj(dd::create_object<dd::Table_stat>());
5
6 setup_table_stats_record(
7 thd, ts_obj.get(),
8 dd::String_type(schema_name_ptr.ptr(), schema_name_ptr.length()),
9 dd::String_type(table_name_ptr.ptr(), table_name_ptr.length()), stats,
10 checksum, true, true);
11
12 return store_statistics_record(thd, ts_obj.get());
13}
persist_i_s_table_stats() 调用 setup_table_stats_record()
构造 Table_stat 对象,其中包含统计信息的各个字段。
然后,调用 store_statistics_record()
,经过多级之后,最终会调用 Weak_object_impl_<use_pfs>::store()
方法执行持久化操作。
主动持久化
小节已经介绍过 setup_table_stats_record()
、Weak_object_impl_<use_pfs>::store()
这 2 个方法的代码,这里就不再重复了。
3. 为什么不靠谱
上一小节,我们以 t1 表为例,介绍了一个表的统计信息的持久化过程。
持久化的统计信息中包含 update_time,按理来说,既然已经持久化了,那它没有理由不靠谱对不对?
其实,update_time 之所以不靠谱,有 2 个原因:
原因 1
:某个表的 update_time 发生变化之后,并不会马上被持久化。
需要执行 analyze table
,才会触发主动持久化,而这个操作并不会经常执行。
从 information_schema.tables
视图读取表的信息(其中包含统计信息),这个操作也不一定会经常执行,退一步说,就算是监控场景下,会频繁查询这个视图,但也不会每次都触发被动持久化
。
因为被动持久化还要受到系统变量 information_schema_stats_expiry
的控制,它的默认值是 86400s。
information_schema_stats_expiry 使用默认值的情况下,即使频繁查询 information_schema.tables
视图,一个表的统计信息,一天最多只会更新一次。
这里的统计信息,单指 mysql.table_stats 表中保存的统计信息。
原因 2
:持久化之前,update_time 只位于内存中的 dict_table_t 对象中。
一旦 MySQL 挂了、服务器断电了,下次启动之后,所有表的 update_time 都丢了。
以及,如果打开的 InnoDB 表过多,缓存的 dict_table_t
对象数量达到上限(由系统变量 table_definition_cache
控制),导致 dict_table_t 对象被从 InnoDB 的缓存中移除,这些对象对应表的 update_time 也就丢了。
那么,既然都已经把表的统计信息持久化到 mysql.table_stats
中了,为什么不做的彻底一点,保证该表中的持久化信息和 InnoDB 内存中的信息一致呢?
根据代码中的实现逻辑来看,mysql.table_stats
中的持久化信息只是作为缓存使用,表中多数字段值都来源于其它持久化信息,而 update_time
字段值来源于内存中,这就决定了它的不靠谱。
我认为 update_time 的不靠谱行为是个 bug,给官方提了 bug,但是官方回复说这不是 bug。
感兴趣的读者可以了解一下,bug 链接如下:
https://bugs.mysql.com/bug.php?id=111476
4. 说说 mysql.table_stats 表
默认情况下,我们是没有权限查看 mysql.table_stats
表的,因为这是 MySQL 内部使用的表。
但是,MySQL 也给我们留了个小门。
如果我们通过源码编译 Debug 包,并且告诉 MySQL 不检查数据字典表的权限,我们就能一睹 mysql.table_stats
表的芳容了。
关闭数据字典表的权限检查之前
,看不到:
1SELECT * FROM mysql.table_stats LIMIT 1\G
2
3(3554, "Access to data dictionary table
4 'mysql.table_stats' is rejected.")
关闭数据字典表的权限检查之后
,看到了:
1SET SESSION debug='+d,skip_dd_table_access_check';
2
3SELECT * FROM mysql.table_stats LIMIT 1\G
4
5***************************[ 1. row ]***************************
6schema_name | test
7table_name | city
8table_rows | 462
9avg_row_length | 177
10data_length | 81920
11max_data_length | 0
12index_length | 16384
13data_free | 0
14auto_increment | 3013
15checksum | <null>
16update_time | <null>
17check_time | <null>
18cached_time | 2023-06-20 06:09:14
5. 总结
为了方便介绍和理解,依然以 t1 表为例进行总结。
t1 表插入、更新、删除记录过程中,写 undo 日志之前,它的 dict_table_t
对象指针会被保存到 trx->mod_tables
集合中。
事务提交过程中,迭代 trx->mod_tables
集合(只包含 t1 表),把当前时间
赋值给 t1 表 dict_table_t
对象的 update_time 属性,这就是 t1 表的最后修改时间。
如果执行 analyze table t1
,会触发主动持久化,把 t1 表的统计信息持久化到 mysql.table_stats
表中。
如果通过 information_schema.tables 视图读取 t1 表的信息,其中的统计信息来源于 mysql.table_stats
表,从 mysql.table_stats
中读取 t1 表的统计信息之后,把 table_rows
字段值发送给客户端之前,会判断 t1 表的统计信息是否已过期。
如果已经过期,会触发被动持久化,把 t1 表的最新统计信息持久化到 mysql.table_stats
表中。
t1 表的统计信息中包含 update_time 字段,不管是主动还是被动持久化,t1 表 dict_table_t 对象的 update_time 属性值都会随着统计信息的持久化保存到 mysql.table_stats
表的 update_time
字段中。
虽然 t1 表 dict_table_t 对象的 update_time 属性值会持久化到 mysql.table_stats
表中,但是在持久化之前,update_time 只存在于内存中,一旦 MySQL 挂了、服务器断电了,或者 t1 表的 dict_table_t
对象被从 InnoDB 的缓存中移除了,未持久化的 update_time
属性值也就丢失了,这就是 update_time
不靠谱的原因。
欢迎扫码关注公众号,我们一起学习更多 MySQL 知识: