CartoDB-SQL-API/app/services/stream_copy.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-05-25 23:42:30 +08:00
const PSQL = require('cartodb-psql');
const copyTo = require('pg-copy-streams').to;
const copyFrom = require('pg-copy-streams').from;
2018-06-14 02:12:21 +08:00
module.exports = class StreamCopy {
2018-06-12 22:56:18 +08:00
constructor (sql, userDbParams) {
this.pg = new PSQL(userDbParams);
this.sql = sql;
this.connectionClosedByClient = false;
2018-06-12 22:56:18 +08:00
}
2018-06-13 00:39:50 +08:00
to(cb) {
2018-06-12 22:56:18 +08:00
this.pg.connect((err, client, done) => {
2018-06-08 22:58:32 +08:00
if (err) {
return cb(err);
2018-06-08 22:58:32 +08:00
}
2018-06-12 22:56:18 +08:00
const copyToStream = copyTo(this.sql);
2018-06-08 22:58:32 +08:00
const pgstream = client.query(copyToStream);
2018-06-08 22:58:32 +08:00
pgstream
2018-06-14 06:54:03 +08:00
.on('end', () => done())
.on('error', err => done(err));
2018-06-08 22:58:32 +08:00
cb(null, pgstream, copyToStream, client, done);
2018-06-08 22:58:32 +08:00
});
2018-06-12 22:56:18 +08:00
}
2018-06-08 17:09:51 +08:00
2018-06-13 00:39:50 +08:00
from(cb) {
2018-06-12 22:56:18 +08:00
this.pg.connect((err, client, done) => {
2018-06-08 22:50:12 +08:00
if (err) {
return cb(err);
2018-06-08 22:50:12 +08:00
}
2018-06-12 22:56:18 +08:00
const copyFromStream = copyFrom(this.sql);
2018-06-08 22:50:12 +08:00
const pgstream = client.query(copyFromStream);
pgstream
2018-06-14 06:54:03 +08:00
.on('end', () => done())
.on('error', err => done(err));
2018-06-08 22:50:12 +08:00
cb(null, pgstream, copyFromStream, client, done);
2018-06-08 22:50:12 +08:00
});
2018-05-25 23:42:30 +08:00
}
2018-05-26 00:50:56 +08:00
};