事务
创建并使用事务
事务通过 DataSource 或 EntityManager 创建。示例:
await myDataSource.transaction(async (transactionalEntityManager) => {
// 使用 transactionalEntityManager 执行查询
})或者
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
// 使用 transactionalEntityManager 执行查询
})你想在事务中运行的一切都必须在回调里执行:
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
await transactionalEntityManager.save(users)
await transactionalEntityManager.save(photos)
// ...
})在事务中工作时最重要的限制是:始终使用所提供的 entity manager 实例——本例中即 transactionalEntityManager。不要使用全局的 ENTITY MANAGER。所有操作 必须 通过所提供的事务型 entity manager 执行。
指定隔离级别
可以通过把隔离级别作为第一个参数传入来为事务指定它:
await myDataSource.manager.transaction(
"SERIALIZABLE",
(transactionalEntityManager) => {},
)受支持的隔离级别
隔离级别的实现并非在所有数据库上都一致。每个驱动会声明它支持哪些级别,如果你请求了不受支持的级别,TypeORM 会抛出错误。
CockroachDB
READ COMMITTED—— 需要集群设置sql.txn.read_committed_isolation.enabled,近期版本中默认启用REPEATABLE READ—— 需要集群设置sql.txn.repeatable_read_isolation.enabled,默认禁用(在 v24.3.0 中引入)SERIALIZABLE(默认)
CockroachDB 会把较弱的 SQL 隔离请求映射到更强的级别。回退行为取决于相应的集群设置。例如,当你通过 SQL 请求 READ UNCOMMITTED、READ COMMITTED 或 REPEATABLE READ 时(例如 BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED),CockroachDB 会接受该语法,但可能改用更严格的级别来运行该事务:
READ COMMITTED→ 实际运行为:- 当
sql.txn.read_committed_isolation.enabled为 false 且sql.txn.repeatable_read_isolation.enabled为 false 时,为SERIALIZABLE - 当
sql.txn.repeatable_read_isolation.enabled为 true 且sql.txn.read_committed_isolation.enabled为 false 时,为REPEATABLE READ
- 当
READ UNCOMMITTED→ 实际运行为:- 当
sql.txn.read_committed_isolation.enabled为 false 且sql.txn.repeatable_read_isolation.enabled为 false 时,为SERIALIZABLE - 当
sql.txn.read_committed_isolation.enabled为 true 时,为READ COMMITTED - 当
sql.txn.repeatable_read_isolation.enabled为 true 且sql.txn.read_committed_isolation.enabled为 false 时,为REPEATABLE READ
- 当
REPEATABLE READ→ 当sql.txn.repeatable_read_isolation.enabled为 false 时,实际运行为SERIALIZABLE
进一步了解
Google Spanner
REPEATABLE READ*SERIALIZABLE
* Spanner 上的 REPEATABLE READ 目前处于预览阶段,尚未正式发布。它提供快照隔离并允许写偏斜(write-skew)异常——当这会产生影响时,请使用 SELECT ... FOR UPDATE。
进一步了解
MariaDB
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
进一步了解
MS SQL Server
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
驱动专属选项
SQL Server 还支持驱动专属的 options.isolationLevel 和 options.connectionIsolationLevel 配置,但它们受制于一个上游连接池限制。本页介绍的顶层 isolationLevel 选项不受影响,因为它会在每个事务上显式应用。
进一步了解
MySQL
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
通过 RDS Data API 的 Aurora MySQL
aurora-mysql 驱动不支持隔离级别。 请求任何级别都会抛出校验错误。
这是传输层的限制,而非引擎层的限制。Aurora MySQL 数据库引擎完全支持标准的那一组隔离级别,但 aurora-mysql 驱动是通过无状态的 RDS Data API而不是常驻的 MySQL 协议连接与集群通信的,而 Data API 没有提供把隔离级别附加到事务上的方法:
BeginTransaction只接受resourceArn、secretArn、database和schema——没有隔离级别参数。- Data API 以不透明的方式池化后端连接。在
BeginTransaction之前作为单独一条ExecuteStatement发送的SET TRANSACTION ISOLATION LEVEL ...,无法保证与该事务实际运行的后端会话亲和,因此该设置会被静默丢弃。 - 不支持多语句 SQL,所以
SET TRANSACTION ...; START TRANSACTION;也无法作为单次调用发送。 - MySQL 会以错误 1568拒绝在已开始的事务内部执行
SET TRANSACTION ISOLATION LEVEL,因此 Aurora PostgreSQL 所采用的做法(把SET作为已开启事务内的第一条语句发出)在 MySQL 上不可用。
通过 mysql 驱动的 Aurora MySQL
如果确实需要针对 Aurora MySQL 集群使用按事务的隔离级别,请改用指向集群写入端点的标准 mysql 驱动,而不是 aurora-mysql。该路径使用常规的 MySQL 协议连接(通过 mysql2),并支持上面列出的完整隔离级别集合。
进一步了解
Oracle
READ COMMITTEDSERIALIZABLE
进一步了解
PostgreSQL
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
Aurora PostgreSQL
aurora-postgres 驱动同样支持这一组隔离级别,它通过 RDS Data API 与 Aurora PostgreSQL 集群通信。
进一步了解
SAP HANA
READ COMMITTEDREPEATABLE READSERIALIZABLE
进一步了解
SQLite
READ UNCOMMITTED—— 只有在启用共享缓存模式时才生效;在默认模式下 SQLite 始终使用SERIALIZABLESERIALIZABLE
进一步了解
默认隔离级别
你可以通过在 DataSource 选项中设置 isolationLevel,为所有事务配置默认隔离级别:
const dataSource = new DataSource({
type: "postgres",
isolationLevel: "SERIALIZABLE",
// ...
})设置后,所有未显式指定隔离级别就启动的事务都会使用该默认值。传给 transaction() 或 startTransaction() 的显式隔离级别会覆盖默认值。
用 QueryRunner 创建并控制单个数据库连接的状态
QueryRunner 提供单个数据库连接。事务是借助 query runner 组织起来的。单个事务只能建立在单个 query runner 上。你可以手动创建 query runner 实例,并用它手动控制事务状态。示例:
// 创建一个新的 query runner
const queryRunner = dataSource.createQueryRunner()
// 用我们新建的 query runner 建立真实的数据库连接
await queryRunner.connect()
// 现在我们可以在 query runner 上执行任何查询,例如:
await queryRunner.query("SELECT * FROM users")
// 我们也可以访问与该 query runner 所创建连接协同工作的 entity manager:
const users = await queryRunner.manager.find(User)
// 现在开启一个新事务:
await queryRunner.startTransaction()
try {
// 在该事务上执行一些操作:
await queryRunner.manager.save(user1)
await queryRunner.manager.save(user2)
await queryRunner.manager.save(photos)
// 现在提交事务:
await queryRunner.commitTransaction()
} catch (err) {
// 既然出错了,就回滚我们所做的改动
await queryRunner.rollbackTransaction()
} finally {
// 你需要释放手动创建的 query runner:
await queryRunner.release()
}QueryRunner 中有 3 个控制事务的方法:
startTransaction- 在该 query runner 实例内部开启一个新事务。commitTransaction- 提交使用该 query runner 实例所做的所有改动。rollbackTransaction- 回滚使用该 query runner 实例所做的所有改动。
进一步了解 Query Runner。
Creating and using transactions
Transactions are created using DataSource or EntityManager. Examples:
await myDataSource.transaction(async (transactionalEntityManager) => {
// execute queries using transactionalEntityManager
})or
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
// execute queries using transactionalEntityManager
})Everything you want to run in a transaction must be executed in a callback:
await myDataSource.manager.transaction(async (transactionalEntityManager) => {
await transactionalEntityManager.save(users)
await transactionalEntityManager.save(photos)
// ...
})The most important restriction when working in a transaction is to ALWAYS use the provided instance of entity manager - transactionalEntityManager in this example. DO NOT USE GLOBAL ENTITY MANAGER. All operations MUST be executed using the provided transactional entity manager.
Specifying isolation level
Specifying the isolation level for the transaction can be done by supplying it as the first parameter:
await myDataSource.manager.transaction(
"SERIALIZABLE",
(transactionalEntityManager) => {},
)Supported isolation levels
Isolation level implementations are not agnostic across all databases. Each driver declares which levels it supports, and TypeORM will throw an error if you request an unsupported level.
CockroachDB
READ COMMITTED— requires the cluster settingsql.txn.read_committed_isolation.enabled, which is enabled by default in recent versionsREPEATABLE READ— requires the cluster settingsql.txn.repeatable_read_isolation.enabled, which is disabled by default (introduced in v24.3.0)SERIALIZABLE(default)
CockroachDB maps weaker SQL isolation requests to stronger levels. The fallback behavior depends on the corresponding cluster settings. For example, when you request READ UNCOMMITTED, READ COMMITTED or REPEATABLE READ via SQL (e.g. BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED), CockroachDB accepts the syntax and may run the transaction at a stricter level instead:
READ COMMITTED→ runs as:SERIALIZABLEifsql.txn.read_committed_isolation.enabledis false andsql.txn.repeatable_read_isolation.enabledis falseREPEATABLE READifsql.txn.repeatable_read_isolation.enabledis true andsql.txn.read_committed_isolation.enabledis false
READ UNCOMMITTED→ runs as:SERIALIZABLEifsql.txn.read_committed_isolation.enabledis false andsql.txn.repeatable_read_isolation.enabledis falseREAD COMMITTEDifsql.txn.read_committed_isolation.enabledis trueREPEATABLE READifsql.txn.repeatable_read_isolation.enabledis true andsql.txn.read_committed_isolation.enabledis false
REPEATABLE READ→ runs asSERIALIZABLEifsql.txn.repeatable_read_isolation.enabledis false
Learn more
Google Spanner
REPEATABLE READ*SERIALIZABLE
* REPEATABLE READ on Spanner is currently in Preview and not yet generally available. It provides snapshot isolation and permits write-skew anomalies — use SELECT ... FOR UPDATE when that matters.
Learn more
MariaDB
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
Learn more
MS SQL Server
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLESNAPSHOT
Driver-specific options
SQL Server also supports driver-specific options.isolationLevel and options.connectionIsolationLevel settings, but these are subject to an upstream pool limitation. The top-level isolationLevel option covered on this page is not affected, because it is applied explicitly on each transaction.
Learn more
MySQL
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
Aurora MySQL via RDS Data API
Isolation levels are not supported on the aurora-mysql driver. Requesting any level throws a validation error.
This is a transport limitation, not an engine limitation. Aurora MySQL the database engine fully supports the standard set, but the aurora-mysql driver talks to the cluster over the stateless RDS Data API instead of a persistent MySQL protocol connection, and the Data API provides no way to attach an isolation level to a transaction:
BeginTransactionaccepts onlyresourceArn,secretArn,database, andschema— there is no isolation parameter.- The Data API pools backend connections opaquely. A
SET TRANSACTION ISOLATION LEVEL ...sent as a separateExecuteStatementbeforeBeginTransactionhas no guaranteed affinity to the backend session that the transaction will run on, so the setting is silently dropped. - Multi-statement SQL is not supported, so
SET TRANSACTION ...; START TRANSACTION;cannot be sent as a single call either. - MySQL rejects
SET TRANSACTION ISOLATION LEVELinside an already-started transaction with error 1568, so the approach used for Aurora PostgreSQL (issuingSETas the first statement inside the started transaction) is not available on MySQL.
Aurora MySQL via the mysql driver
If per-transaction isolation levels are needed against an Aurora MySQL cluster, use the standard mysql driver pointed at the cluster writer endpoint instead of aurora-mysql. That path uses a regular MySQL protocol connection (via mysql2) and supports the full set of isolation levels listed above.
Learn more
Oracle
READ COMMITTEDSERIALIZABLE
Learn more
PostgreSQL
READ UNCOMMITTEDREAD COMMITTEDREPEATABLE READSERIALIZABLE
Aurora PostgreSQL
The same set of isolation levels is supported by the aurora-postgres driver, which talks to Aurora PostgreSQL clusters through the RDS Data API.
Learn more
SAP HANA
READ COMMITTEDREPEATABLE READSERIALIZABLE
Learn more
SQLite
READ UNCOMMITTED— only takes effect when shared-cache mode is enabled; in the default mode SQLite always usesSERIALIZABLEregardlessSERIALIZABLE
Learn more
Default isolation level
You can configure a default isolation level for all transactions by setting isolationLevel in the DataSource options:
const dataSource = new DataSource({
type: "postgres",
isolationLevel: "SERIALIZABLE",
// ...
})When set, all transactions started without an explicit isolation level will use this default. An explicit isolation level passed to transaction() or startTransaction() will override the default.
Using QueryRunner to create and control state of single database connection
QueryRunner provides a single database connection. Transactions are organized using query runners. Single transactions can only be established on a single query runner. You can manually create a query runner instance and use it to manually control transaction state. Example:
// create a new query runner
const queryRunner = dataSource.createQueryRunner()
// establish real database connection using our new query runner
await queryRunner.connect()
// now we can execute any queries on a query runner, for example:
await queryRunner.query("SELECT * FROM users")
// we can also access entity manager that works with connection created by a query runner:
const users = await queryRunner.manager.find(User)
// lets now open a new transaction:
await queryRunner.startTransaction()
try {
// execute some operations on this transaction:
await queryRunner.manager.save(user1)
await queryRunner.manager.save(user2)
await queryRunner.manager.save(photos)
// commit transaction now:
await queryRunner.commitTransaction()
} catch (err) {
// since we have errors let's rollback changes we made
await queryRunner.rollbackTransaction()
} finally {
// you need to release query runner which is manually created:
await queryRunner.release()
}There are 3 methods to control transactions in QueryRunner:
startTransaction- starts a new transaction inside the query runner instance.commitTransaction- commits all changes made using the query runner instance.rollbackTransaction- rolls all changes made using the query runner instance back.
Learn more about Query Runner.