Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Node.js MySQL-Transaktion

Aktualisieren

Siehe die Bearbeitung unten für die async/await-Syntax

Ich habe einige Zeit damit verbracht, eine verallgemeinerte Version des Transaktionsbeispiels von node mysql zu schreiben, also dachte ich, ich würde es hier teilen. Ich verwende Bluebird als meine Promise-Bibliothek und benutzte sie, um das Connection-Objekt zu „promisifizieren“, was die asynchrone Logik stark vereinfachte.

const Promise = ('bluebird');
const mysql = ('mysql');

/**
 * Run multiple queries on the database using a transaction. A list of SQL queries
 * should be provided, along with a list of values to inject into the queries.
 * @param  {array} queries     An array of mysql queries. These can contain `?`s
 *                              which will be replaced with values in `queryValues`.
 * @param  {array} queryValues An array of arrays that is the same length as `queries`.
 *                              Each array in `queryValues` should contain values to
 *                              replace the `?`s in the corresponding query in `queries`.
 *                              If a query has no `?`s, an empty array should be provided.
 * @return {Promise}           A Promise that is fulfilled with an array of the
 *                              results of the passed in queries. The results in the
 *                              returned array are at respective positions to the
 *                              provided queries.
 */
function transaction(queries, queryValues) {
    if (queries.length !== queryValues.length) {
        return Promise.reject(
            'Number of provided queries did not match the number of provided query values arrays'
        )
    }

    const connection = mysql.createConnection(databaseConfigs);
    Promise.promisifyAll(connection);
    return connection.connectAsync()
    .then(connection.beginTransactionAsync())
    .then(() => {
        const queryPromises = [];

        queries.forEach((query, index) => {
            queryPromises.push(connection.queryAsync(query, queryValues[index]));
        });
        return Promise.all(queryPromises);
    })
    .then(results => {
        return connection.commitAsync()
        .then(connection.endAsync())
        .then(() => {
            return results;
        });
    })
    .catch(err => {
        return connection.rollbackAsync()
        .then(connection.endAsync())
        .then(() => {
            return Promise.reject(err);
        });
    });
}

Wenn Sie das Pooling verwenden möchten, wie Sie es in der Frage vorgeschlagen haben, können Sie einfach die createConnection wechseln Zeile mit myPool.getConnection(...) , und wechseln Sie das connection.end Zeilen mit connection.release() .

Bearbeiten

Ich habe eine weitere Iteration des Codes mit mysql2 erstellt Bibliothek (gleiche API wie mysql aber mit Promise-Unterstützung) und die neuen async/await-Operatoren. Hier ist das

const mysql = require('mysql2/promise')

/** See documentation from original answer */
async function transaction(queries, queryValues) {
    if (queries.length !== queryValues.length) {
        return Promise.reject(
            'Number of provided queries did not match the number of provided query values arrays'
        )
    }
    const connection = await mysql.createConnection(databaseConfigs)
    try {
        await connection.beginTransaction()
        const queryPromises = []

        queries.forEach((query, index) => {
            queryPromises.push(connection.query(query, queryValues[index]))
        })
        const results = await Promise.all(queryPromises)
        await connection.commit()
        await connection.end()
        return results
    } catch (err) {
        await connection.rollback()
        await connection.end()
        return Promise.reject(err)
    }
}