-
Notifications
You must be signed in to change notification settings - Fork 2
/
DBTransaction.js
80 lines (76 loc) · 2.07 KB
/
DBTransaction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright 2015 Shyp, Inc.
*
* Transaction interface heavily based on Go's database/sql library
*
* Get a transaction
*
* DBConnection.begin (err, txn) ->
* ... Work with the transaction object..
*
* The DBTransaction object has three methods:
*
* - query, which has the same interface as client.query in the node-postgres library
* - commit, which commits the transaction
* - rollback, which aborts the transaction
*
* Example usage:
*
* DBConnection.begin (err, txn) ->
* txn.query 'UPDATE foo WHERE bar='baz', (err, result) ->
* txn.query 'UPDATE bankaccounts WHERE bar='baz', (err, result) ->
* if result.rows is 0
* txn.rollback cb
* else
* txn.commit cb
*
* Open transactions are extremely harmful to performance, and should be
* avoided. The caller should ensure all code paths are calling commit() or
* rollback(). Better yet, just use normal database queries for situations where
* it's not critical that two records are updated in sync.
*
* A transaction will also be aborted in the event of a Postgres syntax error
* or a connection error.
*/
var DBTransaction;
var Metrics = require('./Metrics');
module.exports = DBTransaction = function (conn) {
this.conn = conn;
};
DBTransaction.prototype.rollback = function(cb) {
var that = this;
return this.conn.query('ROLLBACK', function(err) {
if (err) {
Metrics.increment('db.txn.rollback.error');
if (cb) {
cb(err);
}
return;
}
Metrics.increment('db.txn.rollback.success');
that.conn.release(true);
if (cb) {
return cb(null);
}
});
};
DBTransaction.prototype.query = function() {
this.conn.query.apply(this.conn, arguments);
};
DBTransaction.prototype.commit = function(cb) {
var that = this;
return this.conn.query('COMMIT', function(err) {
if (err) {
Metrics.increment('db.txn.commit.error');
if (cb) {
cb(err);
}
return;
}
Metrics.increment('db.txn.commit.success');
that.conn.release(true);
if (cb) {
return cb(null);
}
});
};