transaction

김재혁 (Paul Jaehyuk Kim) ·2023년 5월 13일
async deleteBookmarkFolder(folder_id: number): Promise<void> {
    try {
        const transaction = await db.sequelize.transaction();

        try {
            // Update all bookmarks in the folder to have a null folder_id
            await db.BookMark.update(
                { folder_id: null },
                { where: { folder_id: folder_id } },
                { transaction }
            );

            // Delete the folder
            await db.BookMarkFolder.destroy(
                { where: { id: folder_id } },
                { transaction }
            );

            await transaction.commit();
        } catch (err) {
            await transaction.rollback();
            throw err;
        }
    } catch (err) {
        return dbException(err);
    }
}

In this code, we use a transaction to ensure that both operations (updating the bookmarks and deleting the folder) are atomic, meaning that if an error occurs during either operation, the changes made within the transaction are rolled back, keeping the database consistent.

In database systems, a transaction is a sequence of one or more operations (such as queries, insertions, updates, or deletions) that is executed as a single, atomic unit of work.

The concept of transactions brings several crucial properties, often referred to by the acronym ACID:

Atomicity: This means that within a transaction, all operations are treated as a single "atomic" unit, which either succeeds completely, or fails completely. If any part of the transaction fails, the entire transaction fails, and the database state is left unchanged.

Consistency: This ensures that a transaction brings the database from one valid state to another, maintaining database invariants: any data written to the database must be valid according to defined rules, including constraints, cascades, triggers, and any combination thereof.

Isolation: This means that concurrent execution of transactions leaves the database in the same state that would have been obtained if the transactions were executed sequentially. This property ensures that each transaction executes in its own 'bubble', isolated from other transactions.

Durability: This ensures that once a transaction has been committed, it will remain committed even in the case of a system failure (e.g., power outage or crash).

The use of transactions helps to manage complex operations, prevent data inconsistencies and handle errors more effectively. In Sequelize, you can create a transaction and pass it to several operations to make sure all of them are applied, or none of them are in case of an error.

0개의 댓글