Search code examples
typeormrollbackpg

TypeORM is not rollback on failure's


I am new to TypeORM with pg, I have declared a class 'User' extending BaseEntity. I create a instance (user) of the class added values (user.name = 'Arun'), then on user.save() fails with DB constraints. It seems like the TypeORM is not reverting the commit. here the autogenerated IDs are not incremental since there is no rollback. Have I missed any configuration for rollback? And I would like to know any better example for creating TypeORM models with constructors.


Solution

  • By default, TypeORM queries not transactional.

    If you want to use transactions to rollback queries if something fail, you need EntityManager

    import {getManager} from "typeorm";
    
    await getManager().transaction(async transactionalEntityManager => {
        await transactionalEntityManager.save(users);
        await transactionalEntityManager.save(photos);
        // ...
    });
    

    Docs here for more about TypeORM Transactions.