Proper way to execute relational database function inside a transaction

29 Views Asked by At

I am using typeorm version ^0.2.22. What I want to achieve is, executing a database function that contain some procedure of inserting records into tables, and the function itself will be executed inside a Transactions. The code that I've wrote, sometimes it suceeded, but many times it was failed. So here is my code:

const connection = getConnection(); 
const queryRunner = connection.createQueryRunner();
await queryRunner.startTransaction();

try {
    // Fetch User records from database
    const someUsersArray = await userRepository.find({ where: { active: true } });

    // Loop the array 
    for (let index = 0; index < someUsersArray.length; index++) {
        const user = someUsersArray[index];

        // Create a new contact entity object
        const contact = new Contact();
        // Assign user_id into contact
        contact.user_id = user.user_id;

        // Save a new contact into a database table, and return the saved contact entity with new contact ID
        await queryRunner.manager.save(contact).then(result => {
        // >>>>>>>>>>>>> HERE
            // Somehow sometimes it succeeded in this line, 
            // but most of times it failed due to "contact_id" was not found
            // and if I do commitTransaction here, it obviously going to be succeeded. 
            // But if I commitTransaction here, then the transaction won't be able to be rolled back
            await queryRunner.query(`SELECT * FROM some_db_function(${result.contact_id})`);
        })
    }
    await queryRunner.commitTransaction();

} catch (error) {
    await queryRunner.rollbackTransaction();
    throw new Error(console.log(error.message));
}

So, from my codes, it seems that I supposed to do commit first, before continuing into a line that executing db function. But if I do commit in the middle of a loop, than I won't be able to do rolling back the transaction. So, what is the best and proper way to achieve this? Thanks for the help and answer.

Regards.

0

There are 0 best solutions below