forked from yadomi/anon-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·104 lines (86 loc) · 2.41 KB
/
index.js
File metadata and controls
executable file
·104 lines (86 loc) · 2.41 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#! /usr/bin/env node
const argv = require("minimist")(process.argv.slice(2));
const { resolve, basename } = require("path");
const {
existsSync: exists,
createReadStream,
createWriteStream
} = require("fs");
const Stream = require("stream");
const Readline = require("readline");
const bin = basename(process.argv[1]);
const transfomer = argv["t"];
const input = argv["i"];
const output = argv["o"];
const force = argv["f"];
function usage() {
console.log(
`usage: ${bin} -t ./transfomers.js -i input.sql -o output.sql [-f]`
);
}
if (!input || !output || !transfomer) {
usage();
process.exit(2);
}
const inputfile = resolve(input);
const outputfile = resolve(output);
const transfomerfile = resolve(transfomer);
if (!exists(transfomerfile)) {
console.log(`${bin}: no such file or directory: ${transfomer}`);
process.exit(2);
}
if (!exists(inputfile)) {
console.log(`${bin}: no such file or directory: ${input}`);
process.exit(2);
}
if (exists(outputfile) && !force) {
console.log(`${bin}: file exist: ${output}. Use -f to force`);
process.exit(2);
}
const transfomers = require(transfomerfile);
const instream = createReadStream(inputfile);
const outstream = createWriteStream(outputfile);
const lines = Readline.createInterface(instream, outstream);
const RE = {
TABLE: /COPY\spublic\."?([a-z_]*)"?\s\(/,
COLUMNS: /COPY public.*\((.*)\)/
};
let currentTable = null;
let currentColumns = [];
lines.on("line", line => {
/**
* Reset the currentTable at the end of the insert/copy statement
*/
if (line === "\\.") {
currentColumns = [];
currentTable = null;
}
/**
* Replace/Redact data in specfied column from transfomers
*/
if (currentTable) {
const transforms = transfomers[currentTable];
const data = line.split("\t");
for (const column of currentColumns) {
if (column in transforms) {
const from = data[currentColumns.indexOf(column)];
const to = transforms[column](from);
if (!from || from === `\\N`) continue;
line = line.replace(from, to);
}
}
}
/**
* Match data insertion start
*/
if (/COPY public/.test(line)) {
const tableName = line.match(RE.TABLE)[1];
if (tableName in transfomers) {
currentTable = tableName;
const raw = line.match(RE.COLUMNS)[1];
const columns = raw.replace(/['"]+/g, "").split(", ");
currentColumns = columns;
}
}
outstream.write(line + "\n");
});