temptable engine

我们知道UNION, DERIVED TABLE, CTE, 子查询或者distinct order by之类的查询都可能用到临时表来存储中间结果,官方文档中列举了几种场景。内存引擎可以通过参数
internal_tmp_mem_storage_engine来选择: temptable(default) 或者memory引擎。本文只讨论temptable引擎

当内存超出temptable引擎限制( temptable_max_ram, 默认1GB)时,将转换成磁盘数据,这里也可以选择是存储成innodb还是myisam(参数). 但COMMON TABLE EXPRESSION(CTE)不允许使用myisam引擎

Note: 由于innodb有行长度限制,可能报row size too large 或者too many columns之类的错误,可以通过设置internal_tmp_disk_storage_engine来绕过限制。

MySQL8.0.16引入了新的参数temptable_use_mmap,用来控制temptable引擎是否磁盘数据转换成Innodb存储,还是内存映射文件。

temptable引擎和memory引擎本质上类似,但最大的不同时可以支持变长类型(例如blob, text, json, geometry等),例如varchar(100)的数据"abcd"应该只占用4个字节而非100个字节。

在之前的版本中当存在Lob类型时,数据会直接转换成磁盘存储。而WL#11613对此做了修改:在内存中使用数组来维护大字段,每个字段包含数据长度和数据指针。在数组之后连续的存储列值,没有padding(如果使用memory引擎,则会padding)。官方博客的评测中由于无需在遇到lob时转换成磁盘存储,相比之前的版本可能获得数倍的性能提升。

从设计上temptable引擎支持hash Index和tree index,允许一个inserter和多个reader, 插入不影响reader的cursor。

笔者的主要关注点在innodb,由于从5.7开始MySQL对Innodb做了大量的优化(cursor优化,无redo log, 去除代码路径上的各种锁),因此默认情况下使用innodb作为内部临时表的磁盘存储.

可以通过查询performance schema表来监控内存和磁盘上的临时表占用空间:

mysql> SELECT * FROM performance_schema.memory_summary_global_by_event_name WHERE event_name like '%temptable%'\G
*************************** 1. row ***************************EVENT_NAME: memory/temptable/physical_diskCOUNT_ALLOC: 0COUNT_FREE: 0SUM_NUMBER_OF_BYTES_ALLOC: 0SUM_NUMBER_OF_BYTES_FREE: 0LOW_COUNT_USED: 0CURRENT_COUNT_USED: 0HIGH_COUNT_USED: 0LOW_NUMBER_OF_BYTES_USED: 0
CURRENT_NUMBER_OF_BYTES_USED: 0HIGH_NUMBER_OF_BYTES_USED: 0
*************************** 2. row ***************************EVENT_NAME: memory/temptable/physical_ramCOUNT_ALLOC: 2COUNT_FREE: 0SUM_NUMBER_OF_BYTES_ALLOC: 2097152SUM_NUMBER_OF_BYTES_FREE: 0LOW_COUNT_USED: 0CURRENT_COUNT_USED: 2HIGH_COUNT_USED: 2LOW_NUMBER_OF_BYTES_USED: 0
CURRENT_NUMBER_OF_BYTES_USED: 2097152HIGH_NUMBER_OF_BYTES_USED: 2097152
2 rows in set (0.03 sec)

temptable引擎实现了自己的内存分配器来减少对系统的内存分配释放调用,封装从磁盘上通过mmap进行分配的策略。先从系统分配大块的内存,然后通过这些内存块来提供malloc/free请求. 每个block包含一个header以及一系列的chunk:

  1. 每个block的结构如下:(quoted from worklog)
- bytes [0, 3]: 4 bytes for the block size (set at block creation and neverchanged later).
- bytes [4, 7]: 4 bytes for the number of used/allocated chunks from thisblock (set to 0 at block creation).
- bytes [8, 11]: 4 bytes for the offset of the first byte from the blockstart that is free and can be used by the next allocation request (setto 12 at block creation (3 * 4 bytes)). We call this first pristine offset.
- bytes [12, block size) a sequence of chunks appended to each other.
  1. 每个chunk的结构
- bytes [0, 3]: 4 bytes that designate the offset of the chunk fromthe start of the block. This is used in order to be able to deducethe block start from a given chunk. The offset of the first chunk is12 (appended after the block size (4), number of allocated chunks (4)and the first pristine offset (4)).
- bytes [4, chunk size): user data, pointer to this is returned to theuser after a successfull allocation request.
  1. 分配内存:
- if the current block does not have enough space:create a new block and make it the current (lose the pointer to theprevious current block).
- increment the number of allocated chunks by 1.
- in the first pristine location - write its offset from the blockstart (4 bytes).
- increment the first pristine offset with 4 + requested bytes by the user.
- return a pointer to the previous first pristine + 4 to the user.
  1. 释放内存:
- read 4 bytes before the provided pointer and derive the block start.
- decrement the number of used chunks by 1.
- if this was the last chunk in the block and this is not the last block:destroy the block, returning the memory to the OS.
- keep the last block for reuse even if all chunks from it are removed, itwill be destroyed when the thread terminates. When the last chunk fromthe last block is removed, instead of destroying the block reset its firstpristine byte offset to 12.

内存分配器的定义和实现在文件storage/temptable/include/temptable/allocator.h

其他模块的定义都在目录storage/temptable/include/下,如果想深入了解该引擎的实现,可以阅读这些头文件代码,有比较详细的注释

InnoDB临时表

在innodb的代码里有大量使用dict_table_t::is_intrinsic()来判定执行路径,对于内部临时表而言,会去消除不必要的开销,例如表锁和事务开销等等。这里简单介绍下相关的代码。

插入操作

当插入临时表时,直接使用cursor进行操作,跳过事务和锁相关操作:

row_insert_for_mysql |--> row_insert_for_mysql_using_cursor

对于临时表记录:

  • 其row_id取自表上递增计数器dict_table_t::sess_row_id, 事务id取自dict_table_t::sess_trx_id而非全局计数器(trx_sys->max_trx_id). 事务Id写入到记录中。

为什么还需要trx id ? 代码中的解释:

Intrinsic table are not shared so don't need a central trx-id
but just need a increased counter to track consistent view while
proceeding SELECT as part of UPDATE
  • 插入操作无需记录undo log, 因此需要通过插入的记录显式回滚(row_explicit_rollback),实际上就是将插入的记录进行标记删除
  • 索引上dict_index_t::last_ins_cur维护了上次插入位点的cursor, 这样对于顺序插入操作,无需每次都commit mtr,并能快速定位到btre上的插入点(row_ins_sorted_clust_index_entry)

    • delete/update操作会自动把cursor提交掉
    • 当存在blob/text类型时,不能cache cursor

查询操作

函数:

row_search_for_mysql|--> row_search_no_mvcc

由于表只对当前session可见,因此无需走mvcc判断。 查询在满足一定条件时也使用了缓存策略cursor的策略, 上次查询的cursor存储在dict_index_t::last_sel_cur中,无需频繁提交mini transaction, 该特性仅限于auto-generated clust index

临时表空间

在当前版本(8.0.15)的MySQL中,有两类临时表空间:

ibtmp1

在data目录下,具有固定的space id(s_temp_space_id = 0xFFFFFFFD)

Note: 在之前的版本中(例如5.7),使用ibtmp1来存储临时表数据和undo信息等,在每次重启时重新创建并使用新的space id.

在内存中对应的对象为srv_tmp_space,目前用于存储临时表的Undo log:

  • 正常shutdown(innodb_space_shutdown())或者重启时(srv_open_tmp_tablespace())重建文件
  • 回滚段初始化(trx_rseg_adjust_rollback_segments())
  • 回滚段内存对象在trx_sys_t::tmp_rsegs中,默认128个回滚段,与正常回滚段在事务开始时分配不同,临时表回滚段是在使用时才分配(trx_undo_report_row_operation() --> trx_assign_rseg_temp() -->get_next_temp_rseg)
Note: 通常查询产生的内部中间表只有插入和查询,因此无需记录undo log。但对于用户显式创建的临时表依然需要
innodb_temp目录下的临时表空间文件

这些文件以temp_{id}.ibt命名,主要是避免所有文件都存储在ibtmp1中,而ibtmp1是在重启时才会重置,就算表被删除了也不会缩减空间。

  • 在实例启动时,这些文件在目录innodb_temp_tablespaces_dir或者#innodb_temp(如果未显式指定)下被创建(ibt::open_or_create), 初始化创建10个文件.
  • 每个session在第一次请求创建临时表时,会从池中分配一个tablespace. 当这个tablespace被attach到该session时,所有临时表都创建在其中. 每个session最多可以有两个独立的tablespace,一个用于显式创建临时表,一个用于优化器创建的临时表。需要两个独立表空间的原因是未来可以在链接断开之前就单独回收优化器表的空间
dict_build_tablespace_for_table |--> innodb_session->get_instrinsic_temp_tblsp()|--> innodb_session->get_usr_temp_tblsp()
  • 当pool中space不够用时,会自动进行扩展,每次扩展单位为10个文件
  • 在session断开时,将tablespace truncate并放回到pool中。所以如果临时表空间占用过大,可以通过中断链接的方式来释放
  • 可以通过is表查询tablespace占用的session id
mysql> SELECT * FROM INFORMATION_SCHEMA.INNODB_SESSION_TEMP_TABLESPACES;
+----+------------+----------------------------+-------+----------+-----------+
| ID | SPACE      | PATH                       | SIZE  | STATE    | PURPOSE   |
+----+------------+----------------------------+-------+----------+-----------+
| 72 | 4294566162 | ./#innodb_temp/temp_10.ibt | 81920 | ACTIVE   | INTRINSIC |
|  0 | 4294566153 | ./#innodb_temp/temp_1.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566154 | ./#innodb_temp/temp_2.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566155 | ./#innodb_temp/temp_3.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566156 | ./#innodb_temp/temp_4.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566157 | ./#innodb_temp/temp_5.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566158 | ./#innodb_temp/temp_6.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566159 | ./#innodb_temp/temp_7.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566160 | ./#innodb_temp/temp_8.ibt  | 81920 | INACTIVE | NONE      |
|  0 | 4294566161 | ./#innodb_temp/temp_9.ibt  | 81920 | INACTIVE | NONE      |
+----+------------+----------------------------+-------+----------+-----------+
10 rows in set (0.00 sec)
  • temp tablespace有单独space id 段,内部预留了400k的space id 给temporary tablespace (s_min_temp_space_id , s_max_temp_space_id),足够使用.
  • space pool中大小不会缩小,也就是说只会扩展,不会收缩!

Reference

WL#8117: Compact In-Memory Temporary Tables
WL#11452 Support for BLOBs in temptable engine
WL#11613: InnoDB: Reclaim disk space occupied by temporary tables online
MySQL 8.0: Support for BLOBs in TempTable engine
Internal Temporary Table Use in MySQL
InnoDB Temporary Tablespaces

MySQL8.0 - 新特性 - 临时表改进 1相关推荐

  1. MySQL8.0 - 新特性 - 临时表改进

    temptable engine 我们知道UNION, DERIVED TABLE, CTE, 子查询或者distinct order by之类的查询都可能用到临时表来存储中间结果,官方文档中列举了几 ...

  2. MySQL基础篇13【MySQL8.0新特性】

    目录 1. MySQL8新特性概述 1.1 MySQL8.0 新增特性 1.2 MySQL8.0移除的旧特性 新特性1:窗口函数 2.1 使用窗口函数前后对比 2.2 窗口函数分类 2.3 语法结构 ...

  3. MySQL8.0 - 新特性 - 安全及权限相关改进

    MySQL8.0里引入了不少关于权限的改动,从这些改动可以看出来,权限管理更加的规范和遍历了,这和我们之前为rds mysql增加了大量权限管理很类似,想来Oracle也是通过这些改动为其云业务服务的 ...

  4. Mysql基础篇(10)—— MySQL8.0新特性概览

    新增的新特性 更简便的NoSQL支持. 更好的索引,新增了隐藏索引和降序索引.隐藏索引可以用来去掉索引对查询性能的影响.在查询中混合存在多列索引时,使用降序索引可以提高查询的性能. 更完善的JSON支 ...

  5. MySQL8.0 - 新特性 - Instant Add Column

    MySQL8.0开始对一些DDL操作做了大量的优化,例如原子DDL, 快速DDL(只修改元数据),前者解决了长期以来mysql的一大诟病,后者则提升了dba同学的生活品质 官方文档列出了一些可以快速d ...

  6. Mysql8.0新特性之详细版本

    1. 账户与安全 用户创建与授权 之前:创建用户并授权 1 grant all privileges on *.* to 'myuser'@'%' identified by '3edc #EDC'; ...

  7. mysql8.0 新特性

    1.  账户与安全# 用户创建与授权 之前:创建用户并授权 1 grant all privileges on *.* to 'myuser'@'%' identified by '3edc#EDC' ...

  8. MySQL8.0新特性——默认使用caching_sha2_password作为身份验证插件

    mysql5.8开始将caching_sha2_password作为默认的身份验证插件 该caching_sha2_password和 sha256_password认证插件提供比mysql_nati ...

  9. 深入解读MySQL8.0 新特性 :Crash Safe DDL

    前言 在MySQL8.0之前的版本中,由于架构的原因,mysql在server层使用统一的frm文件来存储表元数据信息,这个信息能够被不同的存储引擎识别.而实际上innodb本身也存储有元数据信息.这 ...

  10. 深入解读MySQL8.0 新特性 :Crash Safe DDL 1

    前言 在MySQL8.0之前的版本中,由于架构的原因,mysql在server层使用统一的frm文件来存储表元数据信息,这个信息能够被不同的存储引擎识别.而实际上innodb本身也存储有元数据信息.这 ...

最新文章

  1. Android Service 服务(二)—— BroadcastReceiver
  2. Live Wallpaper HD for Mac(天气动态壁纸软件)
  3. 02、体验Spark shell下RDD编程
  4. iOS 修改项目名称
  5. 前端学习(1956)vue之电商管理系统电商系统之添加代码到仓库中
  6. python大神的成长之路_我的Python成长之路
  7. Windows 平台下基于MinGW和Qt 的OpenCV 之CMake 项目配置
  8. 刷题总结——湫湫系列故事——设计风景线(hdu4514 并差集判环+树的直径)
  9. 【java】Java 中的 Exchanger 线程同步使用方法 线程之间交换数据
  10. 开机时自动运行shell_病毒究竟是怎么自动执行的(上)?
  11. 杨振宁与清华计算机系,他是顶级计算机专家,清华最受欢迎教授,在国际上与杨振宁齐名...
  12. MySQL高级知识(十一)——Show Profile
  13. CCF NOI1079 合法C标识符
  14. 电商网站前台模板_电商热潮汹涌,兴长信达PEC零售商城系统为企业注入新力量...
  15. 顺序容器和关联容器添加新元素方法详解
  16. xp计算机位数,XP查看电脑系统版本是32位还是64位的方法
  17. 分享帝国CMS采集教程(图文详解)
  18. 开源库TinyXML2简介及使用
  19. 806管理学原理考研复习资料
  20. Linux下配置JSHOP2环境

热门文章

  1. Swift 5 Dictionary用法大全
  2. 2021-09-1364. 最小路径和
  3. 213.打家劫舍II
  4. python最常用的版本是_在下列选项中,( ) 是最常用的 Python版本,也称之为CIassicPython。_学小易找答案...
  5. 皮尔逊系数皮尔逊系数---K近算法之皮尔逊系数
  6. DL实战(2):SiamFC - TensorFlow配置
  7. CCPC-Wannafly Winter Camp Day1 (Div2, onsite)【流流流动】
  8. Matrix Cookbook 公式推导
  9. 能力提升综合题单Part 8.3.1 二叉树Part 8.3.2 树的直径
  10. nginx服务无法停止(Windows)