-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstringtree-migrate-driver-postgres.js
58 lines (51 loc) · 1.58 KB
/
stringtree-migrate-driver-postgres.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
const pg = require('pg');
module.exports = function (options) {
return {
open: function (cb) {
const self = this;
if (!self.client) {
new pg.Client(options).connect(function (err, _client) {
if (err) return cb(err);
self.client = _client;
cb(null, _client);
});
} else {
cb(null, self.client);
}
},
close: function (cb) {
const self = this;
if (!self.client) return cb();
self.client.end();
delete self.client;
cb();
},
check: function (cb) {
this.execute('select * from pg_catalog.pg_tables where tablename LIKE \'st_migrate\'', function (err, tables) {
if (err) return cb(err);
if (!tables) return cb(new Error('could not read table data from db'));
cb(null, tables[0]);
});
},
create: function (cb) {
this.execute('create table st_migrate ( level integer )', cb);
},
current: function (cb) {
this.execute('select level from st_migrate order by level desc', function (err, levels) {
if (err) return cb(err);
const current = levels[0] || { level: 0 };
cb(null, current.level);
});
},
update: function (level, cb) {
this.execute('insert into st_migrate (level) values ($1)', [level], cb);
},
execute: function (sql, params, cb) {
if (arguments.length === 2) return this.execute(arguments[0], [], arguments[1]);
this.client.query(sql, params, function (err, result) {
if (err) return cb(err);
cb(err, result.rows);
});
}
};
};