/
index.js
114 lines (96 loc) · 2.63 KB
/
index.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Module dependencies
*/
var
pgClient = require('pg').Client
, EventEmitter = require('events').EventEmitter
, util = require('util')
;
var Transaction = module.exports = function(client) {
this.client = client;
};
util.inherits(Transaction, EventEmitter);
/**
* Execute a query, re-emit the events that the client is receiving from this
* EventEmitter
*/
Transaction.prototype.query = function(){
var self = this;
var query = this.client.query.apply(this.client, arguments);
var callback = query.callback;
if(callback == null){
query.on('error', function(err){
self.emit('error', err);
});
}
return query;
};
/**
* Start a transaction block
* @param {String} transaction mode [optional] mode of transaction
* @param {Function} callback
*/
Transaction.prototype.begin = function(mode,callback){
if(typeof(mode) === 'function'){
callback=mode;
mode=null;
}
var begin="BEGIN";
if (mode) { begin+=" "+mode; }
this.query(begin, callback);
};
/**
* Define a new savepoint within the current transaction
* @param {String} savepoint name of the savepoint
* @param {Function} callback
*/
Transaction.prototype.savepoint = function(savepoint, callback) {
this.query('SAVEPOINT ' + savepoint, callback);
};
/**
* Destroy a previously defined savepoint
* @param {String} savepoint name of the savepoint
* @param {Function} callback
*/
Transaction.prototype.release = function(savepoint, callback) {
this.query('RELEASE SAVEPOINT ' + savepoint, callback);
};
/**
* Commit the current transaction
* @param {Function} callback
*/
Transaction.prototype.commit = function(callback){
var self = this;
this.query('COMMIT', function(err){
if (callback) return callback(err);
if (err) return self.emit('error', err);
});
};
/**
* Abort the current transaction or rollback to a previous savepoint
* @param {String} savepoint [optional] name of the savepoint to rollback to
* @param {Function} callback
*/
Transaction.prototype.rollback = function(savepoint, callback){
var self = this;
if(typeof(savepoint) === 'function'){
savepoint = null;
callback = savepoint;
}
var query = (savepoint != null) ? 'ROLLBACK TO SAVEPOINT ' + savepoint : 'ROLLBACK';
this.query(query, function(err){
if (callback) return callback(err);
if (err) return self.emit('error', err);
});
};
/**
* Abort the current transaction
* @param {Function} callback
*/
Transaction.prototype.abort = function(callback) {
var self = this;
this.query('ABORT TRANSACTION', function(err){
if (callback) return callback(err);
if (err) return self.emit('error', err);
});
};