MySQL 8.0 Reference Manual(讀書筆記83節-- InnoDB and Online DDL (3))

来源:https://www.cnblogs.com/xuliuzai/p/18111648
-Advertisement-
Play Games

概述 在主從複製中,一般有一個主資料庫(Master)和一個或多個從資料庫(Slave),主資料庫負責接收和處理寫操作,從資料庫複製主資料庫的日誌文件,將寫操作在自身的資料庫重演,從而實現數據的同步 複製類型 STATEMENT:把主資料庫執行的 sql 複製到從資料庫,是預設類型 ROW:直接把數 ...


1. Foreign Key Operations

The following table provides an overview of online DDL support for foreign key operations. An asterisk【ˈæstərɪsk 星號(置於詞語旁以引起註意或另有註釋);】 indicates additional information, an exception, or a dependency.

Operation Instant In Place Rebuilds Table Permits Concurrent DML Only Modifies Metadata
Adding a foreign key constraint No Yes* No Yes Yes
Dropping a foreign key constraint No Yes No Yes Yes

• Adding a foreign key constraint

The INPLACE algorithm is supported when foreign_key_checks is disabled. Otherwise, only the COPY algorithm is supported.

ALTER TABLE tbl1 ADD CONSTRAINT fk_name FOREIGN KEY index (col1)
 REFERENCES tbl2(col2) referential_actions;

• Dropping a foreign key constraint

ALTER TABLE tbl DROP FOREIGN KEY fk_name;

Dropping a foreign key can be performed online with the foreign_key_checks option enabled or disabled.

If you do not know the names of the foreign key constraints on a particular table, issue the following statement and find the constraint name in the CONSTRAINT clause for each foreign key:

SHOW CREATE TABLE table\G

Or, query the Information Schema TABLE_CONSTRAINTS table and use the CONSTRAINT_NAME and CONSTRAINT_TYPE columns to identify the foreign key names.

You can also drop a foreign key and its associated index in a single statement:

ALTER TABLE table DROP FOREIGN KEY constraint, DROP INDEX index;

補充說明

If foreign keys are already present in the table being altered (that is, it is a child table containing a FOREIGN KEY ... REFERENCE clause), additional restrictions【riˈstrɪkʃənz 限制;約束;制約因素;限制規定;限製法規;】 apply to online DDL operations, even those not directly involving the foreign key columns:

• An ALTER TABLE on the child table could wait for another transaction to commit, if a change to the parent table causes associated changes in the child table through an ON UPDATE or ON DELETE clause using the CASCADE or SET NULL parameters.

• In the same way, if a table is the parent table in a foreign key relationship, even though it does not contain any FOREIGN KEY clauses, it could wait for the ALTER TABLE to complete if an INSERT, UPDATE, or DELETE statement causes an ON UPDATE or ON DELETE action in the child table.

2. Table Operations

The following table provides an overview of online DDL support for table operations. An asterisk indicates additional information, an exception, or a dependency【dɪˈpendənsi (尤指不正常或不必要的)依靠,依賴;附屬國;附屬地;】.

Operation Instant In Place Rebuilds Table Permits Concurrent DML Only Modifies Metadata
Changing the ROW_FORMAT No Yes Yes Yes No
Changing the KEY_BLOCK_SIZE No Yes Yes Yes No
Setting persistent table statistics No Yes No Yes Yes
Specifying a character set No Yes Yes* Yes No
Converting a character set No No Yes* No No
Optimizing a table No Yes* Yes Yes No
Rebuilding with the FORCE option No Yes* Yes Yes No
Performing a null rebuild No Yes* Yes Yes No
Renaming a table Yes Yes No Yes Yes

• Changing the ROW_FORMAT

ALTER TABLE tbl_name ROW_FORMAT = row_format, ALGORITHM=INPLACE, LOCK=NONE;

Data is reorganized substantially【səbˈstænʃəli 基本上;大體上;非常;大大地;總的來說;】, making it an expensive operation.

• Changing the KEY_BLOCK_SIZE

ALTER TABLE tbl_name KEY_BLOCK_SIZE = value, ALGORITHM=INPLACE, LOCK=NONE;

Data is reorganized substantially, making it an expensive operation.

• Setting persistent【pərˈsɪstənt 持續的;持久的;堅持不懈的;執著的;不屈不撓的;反覆出現的;連綿的;】 table statistics options

ALTER TABLE tbl_name STATS_PERSISTENT=0, STATS_SAMPLE_PAGES=20, STATS_AUTO_RECALC=1, ALGORITHM=INPLACE, LOCK=NONE;

Only modifies table metadata.

Persistent statistics include STATS_PERSISTENT, STATS_AUTO_RECALC, and STATS_SAMPLE_PAGES.

• Specifying a character set

ALTER TABLE tbl_name CHARACTER SET = charset_name, ALGORITHM=INPLACE, LOCK=NONE;

Rebuilds the table if the new character encoding is different.

• Converting a character set

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name, ALGORITHM=COPY;

Rebuilds the table if the new character encoding is different.

• Optimizing a table

OPTIMIZE TABLE tbl_name;

In-place operation is not supported for tables with FULLTEXT indexes. The operation uses the INPLACE algorithm, but ALGORITHM and LOCK syntax is not permitted.

• Rebuilding a table with the FORCE option

ALTER TABLE tbl_name FORCE, ALGORITHM=INPLACE, LOCK=NONE;

Uses ALGORITHM=INPLACE as of MySQL 5.6.17. ALGORITHM=INPLACE is not supported for tables with FULLTEXT indexes.

• Performing a "null" rebuild

ALTER TABLE tbl_name ENGINE=InnoDB, ALGORITHM=INPLACE, LOCK=NONE;

Uses ALGORITHM=INPLACE as of MySQL 5.6.17. ALGORITHM=INPLACE is not supported for tables with FULLTEXT indexes.

• Renaming a table

ALTER TABLE old_tbl_name RENAME TO new_tbl_name, ALGORITHM=INSTANT;

Renaming a table can be performed instantly or in place. MySQL renames files that correspond to the table tbl_name without making a copy. (You can also use the RENAME TABLE statement to rename tables.) Privileges granted specifically for the renamed table are not migrated to the new name. They must be changed manually.

3.Tablespace Operations

The following table provides an overview of online DDL support for tablespace operations.

Operation Instant In Place Rebuilds Table Permits Concurrent DML Only Modifies Metadata
Renaming a general tablespace No Yes No Yes Yes
Enabling or disabling general tablespace encryption No Yes No Yes No
Enabling or disabling file-per-table tablespace encryption No No Yes No No

• Renaming a general tablespace

ALTER TABLESPACE tablespace_name RENAME TO new_tablespace_name;

ALTER TABLESPACE ... RENAME TO uses the INPLACE algorithm but does not support the ALGORITHM clause.

• Enabling or disabling general tablespace encryption

ALTER TABLESPACE tablespace_name ENCRYPTION='Y';

ALTER TABLESPACE ... ENCRYPTION uses the INPLACE algorithm but does not support the ALGORITHM clause.

• Enabling or disabling file-per-table tablespace encryption

ALTER TABLE tbl_name ENCRYPTION='Y', ALGORITHM=COPY;

 

4.Online DDL Performance and Concurrency

Online DDL improves several aspects of MySQL operation:

• Applications that access the table are more responsive【rɪˈspɑːnsɪv 反應敏捷的;反應熱烈的;熱情的;反應敏捷;反應積極;】 because queries and DML operations on the table can proceed while the DDL operation is in progress. Reduced locking and waiting for MySQL server resources leads to greater scalability, even for operations that are not involved in the DDL operation. 

• Instant operations only modify metadata in the data dictionary. An exclusive metadata lock on the table may be taken briefly during the execution phase of the operation. Table data is unaffected, making operations instantaneous. Concurrent DML is permitted.

• Online operations avoid the disk I/O and CPU cycles associated with the table-copy method, which minimizes overall load on the database. Minimizing load helps maintain good performance and high throughput during the DDL operation.

• Online operations read less data into the buffer pool than table-copy operations, which reduces purging of frequently accessed data from memory. Purging of frequently accessed data can cause a temporary performance dip after a DDL operation.

4.1 The LOCK clause

 By default, MySQL uses as little locking as possible during a DDL operation. The LOCK clause can be specified for in-place operations and some copy operations to enforce more restrictive locking, if required. If the LOCK clause specifies a less restrictive level of locking than is permitted for a particular DDL operation, the statement fails with an error. LOCK clauses are described below, in order of least to most restrictive:

 • LOCK=NONE:

Permits concurrent【kənˈkɜːrənt 同時發生的;同意的,一致的;】 queries and DML. For example, use this clause for tables involving【ɪnˈvɑːlvɪŋ 需要;影響;(使)參加,加入;包含;牽涉;牽連;使成為必然部分(或結果);】 customer signups or purchases【ˈpɜːrtʃəsɪz 購買;採購;買;】, to avoid making the tables unavailable during lengthy DDL operations.

• LOCK=SHARED:

Permits concurrent queries but blocks DML.

For example, use this clause on data warehouse tables, where you can delay data load operations until the DDL operation is finished, but queries cannot be delayed for long periods【ˈpɪriədz 時期;(人生或國家歷史的)階段,時代;一段時間;紀(地質年代,代下分紀);】.

• LOCK=DEFAULT:

Permits as much concurrency【併發】 as possible (concurrent queries, DML, or both). Omitting【əˈmɪtɪŋ 忽略;遺漏;刪除;漏掉;不做;未能做;】 the LOCK clause is the same as specifying LOCK=DEFAULT.

Use this clause when you do not expect the default locking level of the DDL statement to cause any availability problems for the table.

• LOCK=EXCLUSIVE:

Blocks concurrent queries and DML.

Use this clause if the primary concern is finishing the DDL operation in the shortest amount of time possible, and concurrent query and DML access is not necessary. You might also use this clause if the server is supposed to be idle【ˈaɪdl 空閑的;閑置的;懶惰的;閑散的;懈怠的;沒有工作的;漫無目的的;】, to avoid unexpected table accesses.

 4.2 Online DDL and Metadata Locks

Online DDL operations can be viewed as having three phases【ˈfeɪzɪz 階段;時期;】:

• Phase 1: Initialization

In the initialization phase, the server determines how much concurrency【併發;】 is permitted during the operation, taking into account【考慮到;慮及;】 storage engine capabilities, operations specified in the statement, and user-specified ALGORITHM and LOCK options. During this phase, a shared upgradeable metadata lock is taken to protect the current table definition.

• Phase 2: Execution

In this phase, the statement is prepared and executed. Whether the metadata lock is upgraded to exclusive depends on the factors assessed in the initialization phase. If an exclusive metadata lock is required, it is only taken briefly during statement preparation.

• Phase 3: Commit Table Definitio

In the commit table definition phase, the metadata lock is upgraded to exclusive to evict the old table definition and commit the new one. Once granted, the duration of the exclusive metadata lock is brief.

Due to the exclusive metadata lock requirements outlined above, an online DDL operation may have to wait for concurrent transactions that hold metadata locks on the table to commit or rollback. Transactions started before or during the DDL operation can hold metadata locks on the table being altered. In the case of a long running or inactive transaction, an online DDL operation can time out waiting for an exclusive metadata lock. Additionally, a pending exclusive metadata lock requested by an online DDL operation blocks subsequent transactions on the table.

The following example demonstrates an online DDL operation waiting for an exclusive metadata lock, and how a pending metadata lock blocks subsequent transactions on the table.

Session 1:

mysql> CREATE TABLE t1 (c1 INT) ENGINE=InnoDB;
mysql> START TRANSACTION;
mysql> SELECT * FROM t1;

The session 1 SELECT statement takes a shared metadata lock on table t1.

Session 2:

mysql> ALTER TABLE t1 ADD COLUMN x INT, ALGORITHM=INPLACE, LOCK=NONE;

The online DDL operation in session 2, which requires an exclusive metadata lock on table t1 to commit table definition changes, must wait for the session 1 transaction to commit or roll back.

Session 3:

mysql> SELECT * FROM t1;

The SELECT statement issued in session 3 is blocked waiting for the exclusive metadata lock requested by the ALTER TABLE operation in session 2 to be granted.

You can use SHOW FULL PROCESSLIST to determine if transactions are waiting for a metadata lock.

mysql> SHOW FULL PROCESSLIST\G
...
*************************** 2. row ***************************
 Id: 5
 User: root
 Host: localhost
 db: test
Command: Query
 Time: 44
 State: Waiting for table metadata lock
 Info: ALTER TABLE t1 ADD COLUMN x INT, ALGORITHM=INPLACE, LOCK=NONE
...
*************************** 4. row ***************************
 Id: 7
 User: root
 Host: localhost
 db: test
Command: Query
 Time: 5
 State: Waiting for table metadata lock
 Info: SELECT * FROM t1
4 rows in set (0.00 sec)

Metadata lock information is also exposed【ɪkˈspoʊzd 暴露;露出;揭露;使面臨,使遭受(危險或不快);顯露;揭穿;】 through the Performance Schema metadata_locks table【通過系統表也可以查看】, which provides information about metadata lock dependencies between sessions, the metadata lock a session is waiting for, and the session that currently holds the metadata lock.

4.3 Online DDL Performance

The performance of a DDL operation is largely determined by【很大程度上被...所決定】 whether the operation is performed instantly, in place, and whether it rebuilds the table.

To assess the relative performance of a DDL operation, you can compare results using ALGORITHM=INSTANT, ALGORITHM=INPLACE, and ALGORITHM=COPY. A statement can also be run with old_alter_table enabled to force the use of ALGORITHM=COPY.

For DDL operations that modify table data, you can determine whether a DDL operation performs changes in place or performs a table copy by looking at the “rows affected” value displayed after the command finishes. For example:

• Changing the default value of a column (fast, does not affect the table data):

Query OK, 0 rows affected (0.07 sec)

• Adding an index (takes time, but 0 rows affected shows that the table is not copied):

Query OK, 0 rows affected (21.42 sec)

• Changing the data type of a column (takes substantial time and requires rebuilding all the rows of the table):

Query OK, 1671168 rows affected (1 min 35.54 sec)

Before running a DDL operation on a large table, check whether the operation is fast or slow as follows:

1. Clone the table structure.

2. Populate the cloned table with a small amount of data.

3. Run the DDL operation on the cloned table.

4. Check whether the “rows affected” value is zero or not. A nonzero value means the operation copies table data, which might require special planning. For example, you might do the DDL operation during a period of scheduled downtime, or on each replica server one at a time.

說明

For a greater understanding of the MySQL processing associated with a DDL operation, examine Performance Schema and INFORMATION_SCHEMA tables related to InnoDB before and after DDL operations to see the number of physical reads, writes, memory allocations, and so on.

Because there is some processing work involved with recording the changes made by concurrent DML operations, then applying those changes at the end, an online DDL operation could take longer overall than the table-copy mechanism that blocks table access from other sessions. The reduction in raw performance is balanced against better responsiveness for applications that use the table. When evaluating the techniques for changing table structure, consider end-user perception of performance, based on factors such as load times for web pages.

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文分享自華為雲社區《openGauss 5.0 單點企業版部署_Centos7_x86》,本文作者:董小姐 本文檔環境:CentOS7.9 x86_64 4G1C40G python2.7.5 互動式初始化環境方式 1、介紹 openGauss是一款開源關係型資料庫管理系統,採用木蘭寬鬆許可證v2 ...
  • 引言 在當前的IT行業,無論是校園招聘還是社會招聘,MySQL的重要性不言而喻。 面試過程中,MySQL相關的問題經常出現,這不僅因為它是最流行的關係型資料庫之一,而且在日常的軟體開發中,MySQL的應用廣泛,尤其是對於Java後端開發者來說,熟練掌握MySQL已成為他們技術能力評估的重要指標。 因 ...
  • 不同於Oracle:SEQUENCE的區別 前言 在使用Oracle資料庫SEQUENCE功能時,發現Oracle對邊界處理比較奇怪。剛好GreatSQL也支持SEQUENCE,就拿來一起比較一下。 先說結論:GreatSQL 的使用基本和Oracle基本一致,但是對 START WITH 的邊界限 ...
  • 1.綜述 Hive的聚合函數衍生的視窗函數在我們進行數據處理和數據分析過程中起到了很大的作用 在Hive中,視窗函數允許你在結果集的行上進行計算,這些計算不會影響你查詢的結果集的行數。 Hive提供的視窗和分析函數可以分為聚合函數類視窗函數,分組排序類視窗函數,偏移量計算類視窗函數。 本節主要介紹聚 ...
  • 使用 mysqldump 備份表 powershell 下使用 | Out-file -Encoding utf8 設置字元格式 .\mysqldump.exe --single-transaction --user=root --password=123456 --host 127.0.0.1 - ...
  • 本篇文章主要介紹了GaussDB(DWS)性能調優涉及到的優化器和系統級GUC參數,通過合理配置這些GUC參數,能夠充分利用好CPU、記憶體、磁碟IO和網路IO等資源,提升語句的執行性能和GaussDB(DWS)集群的整體性能。 ...
  • 本文詳細記錄一次在Mac中安裝MySQL Server的過程,安裝環境如下: MacOS 14.4 x86, core i7 在MySQL資料庫實驗環境下通常都要安裝其MySQL Server,安裝方式五花八門,最簡單的有通過系統包管理工具一鍵安裝,例如apt和yum等,這種安裝方法會使得MySQL ...
  • 第4章 Hadoop文件參數配置 實驗一:hadoop 全分佈配置 1.1 實驗目的 完成本實驗,您應該能夠: 掌握 hadoop 全分佈的配置 掌握 hadoop 全分佈的安裝 掌握 hadoop 配置文件的參數意義 1.2 實驗要求 熟悉 hadoop 全分佈的安裝 瞭解 hadoop 配置文件 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...