search
HomeDatabaseMysql TutorialMySQL数据库InnoDB存储引擎在线加字段实现原理详解

腾讯互娱内部维护了一个MySQL分支,基于官方5.5.24,实现了类似于Oracle 11g的快速加字段功能,这个分支我们内部称为TMySQL。该功

腾讯互娱内部维护了一个MySQL分支,基于官方5.5.24,实现了类似于Oracle 11g的快速加字段功能,这个分支我们内部称为TMySQL。该功能通过扩展存储格式来实现,原理类似于Oracle 11g,以下介绍下其实现原理。

1. GCS行格式

需要在innodb中实现类似oracle的快速加字段功能,仅仅基于原来的行格式是不行的,必须对其进行扩展。为了保证原MySQL和innodb的兼容性,不改变原存储格式的行为,在线加字段功能是通过新增一种innodb行格式GCS(Game Cloud Storage)来实现,从而避免对其他格式造成影响。

虽然说是新增格式,但该格式与原默认的compact是基本一样的,只是新增了关键的Field Count(字段数)控制信息。

下面先回顾下compact行格式

compact聚集索引记录的格式由下图所示,由记录头和记录内容组成。

记录头记录了解析字段的关键信息,其结构下图所示。

Record Extra Bytes:是固定的5字节,表示记录的额外信息。
Nullable Bitmap:记录可空位图,,使用1个bit来表示一个可空字段是否为NULL。
non-NULL Variable-Length Array:非空变长字段数组,表示非空变长字段(如varchar、varbinary)在该行的长度。

关于Compact格式的详细介绍可以参考文章。

compact格式有很重要的两个特点:

字段的定义顺序与存储顺序基本一致(主键除外)
 字段为NULL不占存储空间,只需通过Nullable Bitmap记录。

基于以上特点,实现快速加字段功能GCS格式只需在记录头添加Field Count(字段数),来表示当前记录的字段数,占用1~2字节(若大于127,则使用2字节)。

那么,解析GCS记录的关键逻辑就变为:

假设某GCS记录的Field count记录为x,表字段数为y,那么x

如果x == y或非GCS格式,按原来compact方式解析
 如果x  mysql> create table t1(c1 int, c2 int);
Query OK, 0 rows affected (0.00 sec)

mysql> show table status like 't1'G
*************************** 1. row ***************************
Name: t1
Engine: InnoDB
Version: 10
Row_format: Gcs
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 0
Auto_increment: NULL
Create_time: 2013-09-10 11:44:21
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)

# 插入大量数据
mysql> insert into t1 values(1,1);
Query OK, 1 row affected (0.00 sec)

# 快速加字段
mysql> alter table t1 add column d1 int not null default 0, add column d2 int;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> select * from t1 limit 1;
+------+------+----+------+
| c1 | c2 | d1 | d2 |
+------+------+----+------+
|1 |1 | 0 | NULL |
+------+------+----+------+
1 row in set (0.00 sec)

--------------------------------------分割线 --------------------------------------

Ubuntu 14.04下安装MySQL

《MySQL权威指南(原书第2版)》清晰中文扫描版 PDF

Ubuntu 14.04 LTS 安装 LNMP Nginx\PHP5 (PHP-FPM)\MySQL

Ubuntu 14.04下搭建MySQL主从服务器

Ubuntu 12.04 LTS 构建高可用分布式 MySQL 集群

Ubuntu 12.04下源代码安装MySQL5.6以及Python-MySQLdb

MySQL-5.5.38通用二进制安装

--------------------------------------分割线 --------------------------------------

2. 兼容性

仅仅新增GCS存储格式,必定导致原来数据的不兼容(每行增加Field Count),只能通过重导数据或alter table来使其支持在线加字段功能。

# compact格式转换为GCS格式
mysql> alter table t_compact row_format=gcs;

如果数据量越大,上述语句所花时间就会越长,这样对升级和使用都带来困难。

为了解决这个问题,GCS格式实现了对compact格式的全面兼容。

在innodb实现中,compact格式记录头的Record Extra Bytes首字节最高位和次高位是保留的,总是为0。因此,GCS记录占用了其中的最高bit,若为1表示使用GCS格式,记录中会包含Field count信息,这里称该bit为控制位。

然而GCS行格式新增的Field Count仅仅是为了表示记录的字段数,如果表不执行加字段操作,该部分其实是不起作用的(记录字段数恒等于表字段数)。换句话说,如果GCS表不执行快速加字段操作,记录其实并不需要存储Field Count信息。

因此,当表第一次快速加字段前,GCS记录可以与compact完全相同,即控制位为0;当第一次快速加字段时,可将加字段前的字段数存储在扩展的数据字典中,用来解析控制位为0的GCS记录(充当记录上的field count信息);新插入或修改的记录,则按照第一节介绍的存储格式进行构建。

最后,这个设计中的GCS记录在第一次快速加字段前可以跟Compact格式是完全一致的。这样做,有两个好处:

第一次在线加字段前,减少每条GCS记录Field Count 1~2字节的存储消耗
 可以支持Compact表快速转换为GCS表,实现快速升级

由于存储格式完全兼容,不管原来的compact表数据量有多少,仅需执行以下命令,修改表的元数据信息,就能将格式快速转换为GCS,从而获得快速加字段功能。

mysql> create table t_compact(c1 int, c2 int) row_format=compact;
 Query OK, 0 rows affected (0.00 sec)

mysql> insert into t_compact values(1,1);
 Query OK, 1 row affected (0.00 sec)

# compact格式非onlie操作,需要拷贝数据
mysql> alter table t_compact add column d1 int;
 Query OK, 1 row affected (0.01 sec)
 Records: 1 Duplicates: 0 Warnings: 0

# online操作,只需修改元数据,不需拷贝数据
mysql> alter table t_compact row_format = gcs;
 Query OK, 0 rows affected (0.00 sec)
 Records: 0 Duplicates: 0 Warnings: 0

# online操作
mysql> alter table t_compact add column d2 int not null default 0;
 Query OK, 0 rows affected (0.00 sec)
 Records: 0 Duplicates: 0 Warnings: 0

这样,TMySQL可实现基于5.5的覆盖升级,对于compact表只需执行alter table row_format = gcs命令就能快速支持在线加字段功能,大大降低升级成本,并且实现加字段前没有存储空间的额外消耗!
3 DML操作

存储格式得以支持,相应的DML操作逻辑需要修改。

select:按照GCS格式进行解析
insert:根据当前表的字段数构造记录中field count和标记控制位
delete:不变
update:原地更新不变;非原地更新走delete+insert,会更新为新的field count

更多详情见请继续阅读下一页的精彩内容:

linux

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version