Pergunta

I'm using node-postgres to make SQL queries with callback style. I have a function that takes in a list of queries and executes them within a transaction block. My understanding is that I submit the query "BEGIN" using node-postgres, submit all the queries I need within my transaction block, and then submit the query "COMMIT".

However, event though my queries are valid (simple inserts, well-tested as stand-alone queries), and everything is definitely getting executed in the right order, when I test the state of the database after the transaction block, I'm getting inconsistent states. Sometimes all of my inserts occurred, and sometimes only some of them did. My understanding is that the transaction block is atomic, so the inserts within a block should be all or nothing on looking for them with a SELECT immediately after the commit.

Here's my function:

Db.prototype.makeTransaction = function (queries, callback) {
    var thisDb = this;
    thisDb.tryQuery("BEGIN", [], function () {
        async.forEach(queries, function (query, arrayCallback) {
            thisDb.tryQuery(query.sql, query.values, arrayCallback);
        }, function (err) {
            if (err) {
                thisDb.tryQuery("ROLLBACK", [], function () {
                    callback(err);
                });
            } else {
                thisDb.tryQuery("COMMIT", [], callback);
            }
        });
    });
};

With helper function tryQuery:

Db.prototype.tryQuery = function (query, values, callback) {
    pg.connect(this.conn, function (err, client) {
        if (!err) {
            client.query(query, values, callback);
        } else {
            // Failed to connect to the database
            callback(err);
        }
    });
};

Any thoughts on what is going wrong?

Foi útil?

Solução

Thanks to araqnid for answering my question: a transaction must be done on the same connection.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top