forked from featurist/sworm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgDriver.js
98 lines (83 loc) · 2.38 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
var promisify = require('./promisify');
var optionalRequire = require("./optionalRequire");
var debug = require('debug')('sworm:pg');
var urlUtils = require('url');
module.exports = function() {
var pg = optionalRequire("pg");
return {
query: function(query, params) {
var self = this;
var paramList = [];
if (params) {
var indexedParams = {};
var keys = Object.keys(params);
for (var n = 0; n < keys.length; ++n) {
var key = keys[n];
var value = params[key];
indexedParams[key] = {
index: n + 1,
value: value
};
paramList.push(value);
}
query = query.replace(new RegExp('@([a-zA-Z_0-9]+)\\b', 'g'), function(_, paramName) {
var param = indexedParams[paramName];
if (!param) {
throw new Error('no such parameter @' + paramName);
}
return '$' + indexedParams[paramName].index;
});
}
return promisify(function(cb) {
debug(query, paramList);
return self.connection.query(query, paramList, cb);
}).then(function(result) {
return result.rows;
});
},
insert: function(query, params, options) {
var id = options.id;
return this.query(query + ' returning ' + id, params).then(function (rows) {
return rows[0][id];
});
},
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;
}
}