-1

I saw the following code, which seems to insert data to the repository.

I tried to search the document of this code.

https://typeorm.delightful.studio/index.html

But I couldn't found any documentation.

 const queryRunner = this.connection.createQueryRunner();  
 await queryRunner.connect();
 await queryRunner.startTransaction();
 
 const newChild = await queryRunner.manager.insert<Child>('child', child);

What does this code do in this sentence ?

Are there any materials about them ?

If someone has opinion,please let me know.

Thanks

Heisenberg
  • 4,787
  • 9
  • 47
  • 76

1 Answers1

0

I think if you are familiar with the notion of Transactions in databases then those lines of code are relatively straight-forward. Below lines are provided in Typeorm docs which I copied some of it for you here:

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:

import {getConnection} from "typeorm";

// get a connection and create a new query runner
const connection = getConnection();
const queryRunner = connection.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.

Mahdi Ghajary
  • 2,717
  • 15
  • 20