PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Schließen der postgres (pg)-Client-Verbindung in node.js

Eine Promise-basierte Schnittstelle wie pg-promise ist der richtige Weg:

var bluebird = require('bluebird');
var pgp = require('pg-promise')({
    promiseLib: bluebird
});
var db = pgp(/*connection details*/);

db.tx(t => {
    // BEGIN executed
    return t.map('SELECT id, chain FROM mytable where state_ready = $1 and transaction_id = $2', [true, 123], a => {
        var chain = data.chain;
        var pg_record = data.id;
        return t.none('UPDATE mytable SET transaction_id = $1::text where id=$2::int', [transactionHash, pg_record]);
    }).then(t.batch); // settling all internal queries
})
    .then(data => {
        // success, COMMIT executed
    })
    .catch(error => {
        // error, ROLLBACK executed
    })
    .finally(pgp.end); // shuts down the connection pool

Das obige Beispiel macht genau das, worum Sie gebeten haben, und verwendet außerdem eine Transaktion. Aber in Wirklichkeit möchten Sie aus Leistungsgründen alles in einer Abfrage erledigen;)

Siehe weitere Beispiele .