1 | 'use strict'
|
2 |
|
3 | const collectFileInfo = require('./collect-file-info')
|
4 | const generateScriptStatements = require('./generate-script-statements')
|
5 | const path = require('path')
|
6 | const fs = require('fs')
|
7 | const copyStream = require('./copy-stream')
|
8 | const promisify = require('util').promisify
|
9 |
|
10 | function preprocess (options) {
|
11 | const outputPath = path.resolve(options.sourceDir, 'inserts')
|
12 | createFolders(outputPath)
|
13 | }
|
14 |
|
15 | function createFolders (targetDir) {
|
16 | const sep = path.sep
|
17 | const initDir = path.isAbsolute(targetDir) ? sep : ''
|
18 | targetDir.split(sep).reduce((parentDir, childDir) => {
|
19 | const curDir = path.resolve(parentDir, childDir)
|
20 | if (!fs.existsSync(curDir)) {
|
21 | fs.mkdirSync(curDir)
|
22 | }
|
23 | return curDir
|
24 | }, initDir)
|
25 | }
|
26 |
|
27 | function annotateCopyStatements (statements) {
|
28 | for (const statement of statements) {
|
29 | if (statement.sql.startsWith('COPY ')) {
|
30 | statement.action = copyStream
|
31 | }
|
32 | }
|
33 | return statements
|
34 | }
|
35 |
|
36 | async function supercopy (options, callback) {
|
37 | try {
|
38 | preprocess(options)
|
39 |
|
40 | const fileInfo = await collectFileInfo(options)
|
41 | let statements = generateScriptStatements(fileInfo, options)
|
42 | statements = annotateCopyStatements(statements)
|
43 |
|
44 | await options.client.run(statements)
|
45 | callback(null)
|
46 | } catch (err) {
|
47 | callback(err)
|
48 | }
|
49 | }
|
50 |
|
51 | const NotSet = 'NotSet'
|
52 | const supercopyP = promisify(supercopy)
|
53 |
|
54 | module.exports = (options, callback = NotSet) => {
|
55 | if (callback === NotSet) {
|
56 | return supercopyP(options)
|
57 | }
|
58 | supercopy(options, callback)
|
59 | }
|