Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions TOC.md
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,7 @@
- [Pessimistic Transactions](/pessimistic-transaction.md)
- [Non-Transactional DML Statements](/non-transactional-dml.md)
- [Pipelined DML](/pipelined-dml.md)
- [Database-Level Read-Only Mode](/database-read-only.md)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- [Views](/views.md)
- [Partitioning](/partitioned-table.md)
- [Temporary Tables](/temporary-tables.md)
Expand Down Expand Up @@ -922,6 +923,7 @@
- [`RESOURCE_GROUPS`](/information-schema/information-schema-resource-groups.md)
- [`RUNAWAY_WATCHES`](/information-schema/information-schema-runaway-watches.md)
- [`SCHEMATA`](/information-schema/information-schema-schemata.md)
- [`SCHEMATA_EXTENSIONS`](/information-schema/information-schema-schemata-extensions.md)
- [`SEQUENCES`](/information-schema/information-schema-sequences.md)
- [`SESSION_VARIABLES`](/information-schema/information-schema-session-variables.md)
- [`SLOW_QUERY`](/information-schema/information-schema-slow-query.md)
Expand Down
111 changes: 111 additions & 0 deletions database-read-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
---
title: Database-Level Read-Only Mode
summary: Learn how to set individual TiDB databases to read-only for migration and validation, and understand write restrictions and privileges.
---

# Database-Level Read-Only Mode

Starting from v8.5.9, TiDB supports database-level read-only mode, which restricts writes to an individual database while keeping ordinary queries available. Use it for migration cutover or validation while other databases remain writable.

New databases are writable. The setting persists across TiDB nodes and restarts. For cluster-wide control, use [`tidb_super_read_only`](/system-variables.md#tidb_super_read_only-new-in-v531) or [`tidb_restricted_read_only`](/system-variables.md#tidb_restricted_read_only-new-in-v520).

## Prerequisites

- All TiDB nodes must support this feature before you enable it or restore read-only database metadata.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- Changing the setting requires the `ALTER` privilege on the database.
- System databases, including `mysql`, `sys`, `INFORMATION_SCHEMA`, `PERFORMANCE_SCHEMA`, and `METRICS_SCHEMA`, cannot be set to read-only.

## Set and check read-only mode

Create a database and enable read-only mode:

```sql
CREATE DATABASE app;
CREATE TABLE app.orders (id INT PRIMARY KEY);
INSERT INTO app.orders VALUES (1);
ALTER DATABASE app READ ONLY = 1;
```

Queries remain available:

```sql
SELECT * FROM app.orders;
```

Without the bypass privilege, writes fail:

```sql
INSERT INTO app.orders VALUES (2);
```

```text
ERROR 3989 (HY000): Schema 'app' is in read only mode.
```

Check [`INFORMATION_SCHEMA.SCHEMATA_EXTENSIONS`](/information-schema/information-schema-schemata-extensions.md):

```sql
SELECT SCHEMA_NAME, OPTIONS
FROM INFORMATION_SCHEMA.SCHEMATA_EXTENSIONS
WHERE SCHEMA_NAME = 'app';
```

`OPTIONS` is `READ ONLY=1` for a read-only database, or empty for a writable database. [`SHOW CREATE DATABASE app`](/sql-statements/sql-statement-show-create-database.md) also shows `/* READ ONLY = 1 */` for read-only databases.

To restore write access:

```sql
ALTER DATABASE app READ ONLY = 0;
```

`READ ONLY = DEFAULT` also restores write access. For complete syntax, see [`ALTER DATABASE`](/sql-statements/sql-statement-alter-database.md).

## Transaction behavior

Enabling read-only mode waits for existing transactions that accessed tables in the database to finish, including read transactions on other nodes. After the flag propagates, writes from new transactions without the bypass privilege are rejected. Existing transactions may still issue ordinary writes to tables they accessed before the transition while the DDL waits for them to finish. Wait for `ALTER DATABASE ... READ ONLY = 1` to complete before treating the transition as finished.

Finish blocking transactions or cancel the DDL using [`ADMIN CANCEL DDL JOBS`](/sql-statements/sql-statement-admin-cancel-ddl.md). Failed or canceled transitions roll back the setting. Disabling read-only mode does not require transaction draining.

An older transaction first accessing the database after a state change can fail with error `8028`. Retry the transaction.

## SQL behavior and privileges

Without the bypass privilege, the following restrictions apply:

| Operation | Behavior |
| --- | --- |
| Ordinary `SELECT`, `SHOW`, and `USE` | Allowed. |
| `INSERT`, `REPLACE`, `UPDATE`, `DELETE`, `LOAD DATA`, and `IMPORT INTO` | Rejected for read-only write targets. |
| DDL that changes databases, tables, views, indexes, or sequences | Rejected, except changing `READ ONLY` itself or compacting TiFlash replicas. |
| Locking reads | Rejected when the actual lock target is in a read-only database. |
| `NEXTVAL` and `SETVAL` | Rejected for sequences in a read-only database. |
| Temporary tables | Creation and writes are restricted, including writes to existing local temporary tables. |
| TTL deletion | Cannot delete rows in a read-only database. |

Cross-database checks cover write targets, foreign-key cascades, and both databases in table moves. Reading a read-only database while writing to a writable database is allowed.

Explicitly granting [`RESTRICTED_REPLICA_WRITER_ADMIN`](/privilege-management.md#dynamic-privileges) to a user or active role permits bypassing read-only restrictions. Operation-specific privileges are still required. `SUPER` alone is insufficient. Prepared execution rechecks current bypass privileges and roles.

## Compatibility and limitations

- `READ ONLY` is supported by `ALTER DATABASE`, but not `CREATE DATABASE`. Specify it separately from character set, collation, or placement options.
- Compared with MySQL 8.0, TiDB also restricts local temporary tables and can reject write statements during `PREPARE`. `EXPLAIN` of restricted writes can also return error `3989`.
- Cluster-wide read-only restrictions still apply. Setting a database to writable does not override them.
- `IMPORT INTO` checks read-only mode at statement entry. A physical import that already started can continue after the database becomes read-only. Finish or cancel such imports before relying on unchanged data.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- With the deprecated batch DML feature enabled (`tidb_enable_batch_dml = ON` and `tidb_dml_batch_size > 0`), an `INSERT` with `tidb_batch_insert = ON` or a `DELETE` with `tidb_batch_delete = ON` can partially commit before a read-only transition and then fail when it runs outside an explicit transaction. Previously committed batches are not rolled back. Let the statement finish before enabling read-only mode, and check for committed changes before retrying a failed statement.

### Interaction with other tools

| Tool | Behavior |
| --- | --- |
| TiDB Lightning | Physical imports using the `local` backend can write directly to TiKV into existing tables despite read-only mode. Control these imports separately. Logical imports obey SQL restrictions. |
| BR and SQL `BACKUP` / `RESTORE` | Snapshot restore preserves backed-up read-only metadata when it creates a database. If the target database already exists, restore retains its current read-only setting. Authorized restores can restore tables and sequences into read-only databases; ordinary writes to read-only databases remain restricted afterward. If you require read-only protection during and after restoring to an existing database, run `ALTER DATABASE ... READ ONLY = 1` and wait for it to complete before starting the restore. If the target database is writable, restored tables can accept ordinary writes before read-only protection takes effect. After restoring, check `INFORMATION_SCHEMA.SCHEMATA_EXTENSIONS`. PITR retains the current read-only setting of reused target databases; do not assume it matches the source setting at the selected time. |
Comment thread
expxiaoli marked this conversation as resolved.
Resolved
| Dumpling | Can export read-only databases. Replaying the SQL read-only comment does not enable read-only mode. |
| TiCDC v8.5.8 | Does not replicate database read-only DDL to MySQL downstream databases. |
| DM v8.5.8 | Pauses with a parsing error on upstream `ALTER DATABASE ... READ ONLY` statements. Explicitly skip these statements to resume. Writes to a read-only downstream database are rejected without the bypass privilege. |

## See also

- [`ALTER DATABASE`](/sql-statements/sql-statement-alter-database.md)
- [`SCHEMATA_EXTENSIONS`](/information-schema/information-schema-schemata-extensions.md)
- [Privilege Management](/privilege-management.md)
40 changes: 40 additions & 0 deletions information-schema/information-schema-schemata-extensions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: SCHEMATA_EXTENSIONS
summary: Learn how to query the SCHEMATA_EXTENSIONS table to check database-level read-only settings for databases visible to your TiDB user.
---

# SCHEMATA_EXTENSIONS

The `SCHEMATA_EXTENSIONS` table provides [database-level read-only settings](/database-read-only.md) for databases visible to the current user.

| Column | Type | Description |
| --- | --- | --- |
| `CATALOG_NAME` | `varchar(64)` | The catalog name. This value is always `def`. |
| `SCHEMA_NAME` | `varchar(64)` | The database name. |
| `OPTIONS` | `varchar(256)` | `READ ONLY=1` if the database is read-only; an empty string if the database is writable. |

## Example

```sql
CREATE DATABASE app;
ALTER DATABASE app READ ONLY = 1;
SELECT CATALOG_NAME, SCHEMA_NAME, OPTIONS
FROM INFORMATION_SCHEMA.SCHEMATA_EXTENSIONS
WHERE SCHEMA_NAME = 'app';
```

```text
+--------------+-------------+-------------+
| CATALOG_NAME | SCHEMA_NAME | OPTIONS |
+--------------+-------------+-------------+
| def | app | READ ONLY=1 |
+--------------+-------------+-------------+
```

`OPTIONS` describes the database-level setting. It does not indicate whether cluster-wide read-only restrictions are enabled.

## See also

- [`SCHEMATA`](/information-schema/information-schema-schemata.md)
- [`ALTER DATABASE`](/sql-statements/sql-statement-alter-database.md)
- [Database-Level Read-Only Mode](/database-read-only.md)
1 change: 1 addition & 0 deletions information-schema/information-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Many `INFORMATION_SCHEMA` tables have a corresponding `SHOW` statement. The bene
| `REFERENTIAL_CONSTRAINTS` | Provides information on `FOREIGN KEY` constraints. |
| `ROUTINES` | Not implemented by TiDB. Returns zero rows. |
| [`SCHEMATA`](/information-schema/information-schema-schemata.md) | Provides similar information to `SHOW DATABASES`. |
| [`SCHEMATA_EXTENSIONS`](/information-schema/information-schema-schemata-extensions.md) | Provides database-level read-only settings. |
| `SCHEMA_PRIVILEGES` | Not implemented by TiDB. Returns zero rows. |
| `SESSION_STATUS` | Not implemented by TiDB. Returns zero rows. |
| [`SESSION_VARIABLES`](/information-schema/information-schema-session-variables.md) | Provides similar functionality to the command `SHOW SESSION VARIABLES` |
Expand Down
2 changes: 1 addition & 1 deletion privilege-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ Dynamic privileges include:
* `RESTRICTED_VARIABLES_ADMIN` allows privilege owners to view all system variables when SEM is enabled.
* `RESTRICTED_USER_ADMIN` prohibits privilege owners to have their access revoked by SUPER users when SEM is enabled.
* `RESTRICTED_CONNECTION_ADMIN` allows privilege owners to kill connections of `RESTRICTED_USER_ADMIN` users. This privilege affects `KILL` and `KILL TIDB` statements.
* `RESTRICTED_REPLICA_WRITER_ADMIN` allows privilege owners to perform write or update operations without being affected when the read-only mode is enabled in the TiDB cluster. For details, see [`tidb_restricted_read_only`](/system-variables.md#tidb_restricted_read_only-new-in-v520).
* `RESTRICTED_REPLICA_WRITER_ADMIN` allows privilege owners to perform write or update operations when cluster-wide or [database-level read-only mode](/database-read-only.md) is enabled. For database-level read-only mode, this privilege must be explicitly granted to the user or an active role; `SUPER` alone does not provide the bypass. The privileges required for each operation still apply. For more information about cluster-wide read-only mode, see [`tidb_restricted_read_only`](/system-variables.md#tidb_restricted_read_only-new-in-v520).
* `TRAFFIC_CAPTURE_ADMIN` allows privilege owners to create, view, and cancel traffic capture jobs. For details, see [TiProxy traffic replay](/tiproxy/tiproxy-traffic-replay.md).
* `TRAFFIC_REPLAY_ADMIN` allows privilege owners to create, view, and cancel traffic replay jobs. For details, see [TiProxy traffic replay](/tiproxy/tiproxy-traffic-replay.md).
* `AUDIT_ADMIN` allows managing database audit logs when [Security Enhanced Mode (SEM)](https://docs.pingcap.com/tidb/stable/glossary/#security-enhanced-mode-sem) is disabled, including modifying system variables related to audit logs, manually rotating audit logs, creating or deleting audit log filters, and creating, deleting, enabling, or disabling audit log filtering rules. This privilege is available only in products that provide the database audit logging feature, including TiDB Self-Managed Enterprise Edition, {{{ .dedicated }}}, {{{ .premium }}}, and {{{ .essential }}}. The [database audit logging feature of {{{ .essential }}}](https://docs.pingcap.com/tidbcloud/essential-database-audit-logging/?plan=essential) is currently in Private Preview and requires application for access. {{{ .starter }}} does not support database audit logging.
Expand Down
32 changes: 29 additions & 3 deletions sql-statements/sql-statement-alter-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,32 @@ aliases: ['/docs/dev/sql-statements/sql-statement-alter-database/','/docs/dev/re

# ALTER DATABASE

`ALTER DATABASE` is used to specify or modify the default character set and collation of the current database. `ALTER SCHEMA` has the same effect as `ALTER DATABASE`.
`ALTER DATABASE` is used to specify or modify the default character set and collation of a database, or to change its read-only setting. `ALTER SCHEMA` has the same effect as `ALTER DATABASE`.

## Synopsis

```ebnf+diagram
AlterDatabaseStmt ::=
'ALTER' 'DATABASE' DBName? DatabaseOptionList
'ALTER' ( 'DATABASE' | 'SCHEMA' ) DBName? AlterDatabaseOptionList

AlterDatabaseOptionList ::=
DatabaseOptionList
| 'READ' 'ONLY' '='? ( '0' | '1' | 'DEFAULT' )

DatabaseOption ::=
DefaultKwdOpt ( CharsetKw '='? CharsetName | 'COLLATE' '='? CollationName | 'ENCRYPTION' '='? EncryptionOpt )
```

## Read-only setting

Use `READ ONLY = 1` to enable database-level read-only mode. Use `READ ONLY = 0` or `READ ONLY = DEFAULT` to restore write access. The equals sign is optional. If you omit the database name, the statement applies to the current database.

Changing the setting requires the `ALTER` privilege on the database. System databases cannot be set to read-only. Enabling read-only mode waits for existing transactions that have accessed the database to finish across TiDB nodes.

Specify `READ ONLY` separately from other database options. The option is not supported in `CREATE DATABASE`.

For write restrictions, privileges, and operational limitations, see [Database-Level Read-Only Mode](/database-read-only.md).

## Examples

Modify the test database schema to use the utf8mb4 character set:
Expand All @@ -34,9 +48,21 @@ Query OK, 0 rows affected (0.00 sec)

Currently, TiDB only supports some character sets and collations. See [Character Set and Collation Support](/character-set-and-collation.md) for details.

Enable read-only mode for the `test` database:

```sql
ALTER DATABASE test READ ONLY = 1;
```

Restore write access:

```sql
ALTER DATABASE test READ ONLY = DEFAULT;
```

## MySQL compatibility

The `ALTER DATABASE` statement in TiDB is fully compatible with MySQL. If you find any compatibility differences, [report a bug](https://docs.pingcap.com/tidb/stable/support).
The `READ ONLY` option accepts `0`, `1`, and `DEFAULT`, as in MySQL 8.0. However, TiDB also restricts local temporary tables in read-only databases and can reject write statements during `PREPARE`. For more information, see [Compatibility and limitations](/database-read-only.md#compatibility-and-limitations).

## See also

Expand Down
2 changes: 2 additions & 0 deletions sql-statements/sql-statement-show-create-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ SHOW CREATE SCHEMA IF NOT EXISTS test;
1 row in set (0.00 sec)
```

When [database-level read-only mode](/database-read-only.md) is enabled, the output includes `/* READ ONLY = 1 */`. This is a regular SQL comment. Executing the returned `CREATE DATABASE` statement does not enable read-only mode; use [`ALTER DATABASE ... READ ONLY = 1`](/sql-statements/sql-statement-alter-database.md#read-only-setting) separately.

## MySQL compatibility

`SHOW CREATE DATABASE` is expected to be fully compatible with MySQL. If you find any compatibility differences, you can [report a bug](https://docs.pingcap.com/tidb/stable/support).
Expand Down
2 changes: 2 additions & 0 deletions system-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -5830,6 +5830,7 @@ SHOW WARNINGS;
- Type: Boolean
- Default value: `OFF`
- `tidb_restricted_read_only` and [`tidb_super_read_only`](#tidb_super_read_only-new-in-v531) behave similarly. In most cases, you should use [`tidb_super_read_only`](#tidb_super_read_only-new-in-v531) only.
- To restrict writes to an individual database, see [Database-Level Read-Only Mode](/database-read-only.md). Setting a database to writable does not override cluster-wide read-only restrictions.
- Users with the `SUPER` or `SYSTEM_VARIABLES_ADMIN` privilege can modify this variable. However, if the [Security Enhanced Mode](#tidb_enable_enhanced_security) is enabled, the additional `RESTRICTED_VARIABLES_ADMIN` privilege is required to read or modify this variable.
- `tidb_restricted_read_only` affects [`tidb_super_read_only`](#tidb_super_read_only-new-in-v531) in the following cases:
- Setting `tidb_restricted_read_only` to `ON` will update [`tidb_super_read_only`](#tidb_super_read_only-new-in-v531) to `ON`.
Expand Down Expand Up @@ -6540,6 +6541,7 @@ For details, see [Identify Slow Queries](/identify-slow-queries.md).
- Type: Boolean
- Default value: `OFF`
- `tidb_super_read_only` aims to be implemented as a replacement of the MySQL variable `super_read_only`. However, because TiDB is a distributed database, `tidb_super_read_only` does not make the database read-only immediately after execution, but eventually.
- To restrict writes to an individual database, see [Database-Level Read-Only Mode](/database-read-only.md). Setting a database to writable does not override cluster-wide read-only restrictions.
- Users with the `SUPER` or `SYSTEM_VARIABLES_ADMIN` privilege can modify this variable.
- This variable controls the read-only status of the entire cluster. When the variable is `ON`, all TiDB servers in the entire cluster are in the read-only mode. In this case, TiDB only executes the statements that do not modify data, such as `SELECT`, `USE`, and `SHOW`. For other statements such as `INSERT` and `UPDATE`, TiDB rejects executing those statements in the read-only mode.
- Enabling the read-only mode using this variable only ensures that the entire cluster finally enters the read-only status. If you have changed the value of this variable in a TiDB cluster but the change has not yet propagated to other TiDB servers, the un-updated TiDB servers are still **not** in the read-only mode.
Expand Down