Search code examples
postgresqlnestjstypeorm

Does TypeOrm/Postgres bulk insert use transaction behind the scene?


E.g) if you do:

repository.create([ ...list of entities]); await repository.save()

Would it be considered as a single action or multiple? Or if something fails, would it roll back or not? e.g) creation of row 1, 2, 3 successful, then row 4 fails...

I can't find info regarding this. Thank you.


Solution

  • The repository.save() method is indeed commit in a single transaction(for bulk insert) as described here:

    save - Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.

    *Note: In case of single entity is provided to the save(), the manager will simply run insert/update query without transaction.

    However, you can disable this feature by passing an extra SaveOption to the save() method as described in here:

    /** * By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. * You can disable this behaviour by setting { transaction: false } in the persistence options. */ transaction?: boolean

    So, regard your question on whether it will partially commit or rollback entire transaction, the answer is yes if one entity fail to upsert to db, the whole transaction will be rollback (if you not explicitly set transaction option to false).