Transactions

Creating and using transactions

Transactions are created using Connection or EntityManager.Examples:

  1. import {getConnection} from "typeorm";
  2. await getConnection().transaction(async transactionalEntityManager => {
  3. });

or

  1. import {getManager} from "typeorm";
  2. await getManager().transaction(async transactionalEntityManager => {
  3. });

Everything you want to run in a transaction must be executed in a callback:

  1. import {getManager} from "typeorm";
  2. await getManager().transaction(async transactionalEntityManager => {
  3. await transactionalEntityManager.save(users);
  4. await transactionalEntityManager.save(photos);
  5. // ...
  6. });

The most important restriction when working in an transaction is, to ALWAYS use the provided instance of entity manager -transactionalEntityManager in this example.If you’ll use global manager (from getManager or manager from connection) you’ll have problems.You also cannot use classes which use global manager or connection to execute their queries.All operations MUST be executed using the provided transactional entity manager.

Specifying Isolation Levels

Specifying the isolation level for the transaction can be done by supplying it as the first parameter:

  1. import {getManager} from "typeorm";
  2. await getManager().transaction("SERIALIZABLE", transactionalEntityManager => {
  3. });

Isolation level implementations are not agnostic across all databases.

The following database drivers support the standard isolation levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE):

  • MySQL
  • Postgres
  • SQL Server

SQlite defaults transactions to SERIALIZABLE, but if shared cache mode is enabled, a transaction can use the READ UNCOMMITTED isolation level.

Oracle only supports the READ COMMITTED and SERIALIZABLE isolation levels.

Transaction decorators

There are a few decorators which can help you organize your transactions -@Transaction, @TransactionManager and @TransactionRepository.

@Transaction wraps all its execution into a single database transaction,and @TransactionManager provides a transaction entity manager which must be used to execute queries inside this transaction:

  1. @Transaction()
  2. save(@TransactionManager() manager: EntityManager, user: User) {
  3. return manager.save(user);
  4. }

with isolation level:

  1. @Transaction({ isolation: "SERIALIZABLE" })
  2. save(@TransactionManager() manager: EntityManager, user: User) {
  3. return manager.save(user);
  4. }

You must always use the manager provided by @TransactionManager.

However, you can also inject transaction repository (which uses transaction entity manager under the hood),using @TransactionRepository:

  1. @Transaction()
  2. save(user: User, @TransactionRepository(User) userRepository: Repository<User>) {
  3. return userRepository.save(user);
  4. }

You can inject both built-in TypeORM’s repositories like Repository, TreeRepository and MongoRepository(using @TransactionRepository(Entity) entityRepository: Repository<Entity>)or custom repositories (classes extending the built-in TypeORM’s repositories classes and decorated with @EntityRepository)using the @TransactionRepository() customRepository: CustomRepository.

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:

  1. import {getConnection} from "typeorm";
  2. // get a connection and create a new query runner
  3. const connection = getConnection();
  4. const queryRunner = connection.createQueryRunner();
  5. // establish real database connection using our new query runner
  6. await queryRunner.connect();
  7. // now we can execute any queries on a query runner, for example:
  8. await queryRunner.query("SELECT * FROM users");
  9. // we can also access entity manager that works with connection created by a query runner:
  10. const users = await queryRunner.manager.find(User);
  11. // lets now open a new transaction:
  12. await queryRunner.startTransaction();
  13. try {
  14. // execute some operations on this transaction:
  15. await queryRunner.manager.save(user1);
  16. await queryRunner.manager.save(user2);
  17. await queryRunner.manager.save(photos);
  18. // commit transaction now:
  19. await queryRunner.commitTransaction();
  20. } catch (err) {
  21. // since we have errors lets rollback changes we made
  22. await queryRunner.rollbackTransaction();
  23. } finally {
  24. // you need to release query runner which is manually created:
  25. await queryRunner.release();
  26. }

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.