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-21 19:01:59 +08:00
|
|
|
const { Client } = require('pg');
|
2018-05-25 23:42:30 +08:00
|
|
|
|
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;
|
2018-06-12 23:04:44 +08:00
|
|
|
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) {
|
2018-06-14 00:26:58 +08:00
|
|
|
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-14 00:26:58 +08:00
|
|
|
|
2018-06-08 22:58:32 +08:00
|
|
|
pgstream
|
2018-06-14 06:54:03 +08:00
|
|
|
.on('end', () => done())
|
2018-06-21 19:01:59 +08:00
|
|
|
.on('error', err => done(err))
|
|
|
|
.on('cancelQuery', err => {
|
|
|
|
// See https://www.postgresql.org/docs/9.5/static/protocol-flow.html#PROTOCOL-COPY
|
|
|
|
const cancelingClient = new Client(client.connectionParameters);
|
|
|
|
cancelingClient.cancel(client, pgstream);
|
|
|
|
|
|
|
|
// see https://node-postgres.com/api/pool#releasecallback
|
|
|
|
done(err);
|
|
|
|
});
|
2018-06-08 22:58:32 +08:00
|
|
|
|
2018-06-21 19:13:16 +08:00
|
|
|
cb(null, pgstream, copyToStream);
|
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) {
|
2018-06-14 00:26:58 +08:00
|
|
|
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
|
|
|
|
2018-06-14 02:11:01 +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
|
|
|
};
|