UNPKG

879 BPlain TextView Raw
1'use strict'
2
3const debug = require('debug')('supercopy')
4const fs = require('fs')
5const copyFrom = require('pg-copy-streams').from
6
7function copyStream(statement, params, client) {
8 return new Promise((resolve, reject) => {
9 const components = statement.match(/COPY (.*?) FROM '([^']*)'/)
10 const tableAndCols = components[1]
11 const filename = components[2]
12 const newStatement = `COPY ${tableAndCols} FROM STDIN CSV HEADER;`
13 debug(`Stream-Copy: ${newStatement} -- (${filename})`)
14 const stream = client.query(
15 copyFrom(newStatement)
16 )
17 stream.on('end', function () {
18 resolve()
19 }).on('error', function (err) {
20 reject(err)
21 })
22
23 const fileStream = fs.createReadStream(filename)
24 fileStream.on('error', function (err) {
25 reject(err)
26 })
27
28 fileStream.pipe(stream)
29 })
30} // copyStream
31
32module.exports = copyStream
\No newline at end of file