-
Notifications
You must be signed in to change notification settings - Fork 31
/
pgDriver.js
102 lines (87 loc) · 2.47 KB
/
pgDriver.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
var promisify = require('./promisify');
var optionalRequire = require("./optionalRequire");
var debug = require('debug')('sworm:pg');
var urlUtils = require('url');
var _ = require('underscore')
var paramRegex = require('./paramRegex')
module.exports = function() {
var pg = optionalRequire("pg");
return {
query: function(query, params, options) {
var self = this;
var paramList = [];
if (params) {
var paramIndexes = _.mapObject(params, function (value) {
paramList.push(value);
return paramList.length
})
query = query.replace(paramRegex, function(_, name) {
if (paramIndexes.hasOwnProperty(name)) {
return '$' + paramIndexes[name]
} else {
throw new Error('no such parameter @' + name);
}
});
}
return promisify(function(cb) {
debug(query, paramList);
return self.connection.query(query, paramList, cb);
}).then(function(result) {
if (options.statement || options.insert) {
var r = {}
if (options.statement) {
r.changes = result.rowCount
}
if (options.insert) {
r.id = result.rows[0][options.id]
}
return r
} else {
return result.rows;
}
});
},
insert: function(query, params, options) {
var id = options.id;
return this.query(query + ' returning ' + id, params, options)
},
connect: function(config) {
var self = this;
var options = connectionOptions(config);
if (options.pool) {
return new Promise(function(result, error) {
pg.connect(config.url || config.config, function(err, client, done) {
if (err) {
return error(err);
} else {
self.connection = client;
self.done = done;
return result();
}
});
});
} else {
self.connection = new pg.Client(config.url || config.config);
self.done = function () {
self.connection.end();
};
return promisify(function (cb) {
self.connection.connect(cb);
});
}
},
close: function() {
if (this.done) {
this.done();
}
return Promise.resolve();
}
};
};
function connectionOptions(config) {
if (config.url) {
return urlUtils.parse(config.url, true).query;
} else {
return config.config;
}
}