-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbigquery.js
More file actions
153 lines (123 loc) · 4.45 KB
/
bigquery.js
File metadata and controls
153 lines (123 loc) · 4.45 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
const { BigQuery } = require('@google-cloud/bigquery');
const iconv = require('iconv-lite');
const { pipeline } = require('stream');
const readline = require('readline');
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson();
const { bigqueryConfig } = require('./config/bigquery');
if (Object.values(bigqueryConfig).includes(undefined)) {
console.error('no connection settings in env');
process.exit(100);
}
const db = new BigQuery({
projectId: bigqueryConfig.projectID,
credentials: {
client_email: bigqueryConfig.client_email,
private_key: bigqueryConfig.private_key,
},
clientOptions: {
clientId: bigqueryConfig.clientId,
},
});
const createTable = (tableConfig) => {
const options = {
schema: tableConfig.settlementsSchema,
};
console.log('creating table', tableConfig.tableID);
return db.dataset(bigqueryConfig.datasetID).createTable(tableConfig.tableID, options);
};
module.exports.getTable = async (tableConfig) => {
const exists = await db.dataset(bigqueryConfig.datasetID).table(tableConfig.tableID).exists();
if (exists[0]) {
console.log('Drop table');
await db.dataset(bigqueryConfig.datasetID).table(tableConfig.tableID).delete();
}
return createTable(tableConfig);
};
module.exports.insertData = (fileStream, tableConfig) => {
const entityTag = 'SUBJECT';
const bqStream = db.dataset(bigqueryConfig.datasetID).table(tableConfig.tableID).createWriteStream({
sourceFormat: 'NEWLINE_DELIMITED_JSON',
});
bqStream.on('error', function (e) {
console.log(e);
process.exit(1);
});
const iconvStream = iconv.decodeStream('win1251');
const pl = pipeline(
fileStream,
iconvStream,
(err) => {
if (err) {
console.error('Pipeline failed', err);
} else {
console.log('Pipeline succeeded');
}
},
);
const rl = readline.createInterface({
input: pl,
});
const get = (obj, path) => path ? path.split('.').reduce((a, v) => Array.isArray(a) ? a.map(e => e[v]) : a[v], obj) : obj;
const set = (obj, path, val) => {
const arr = path.split('.');
const last = arr.pop();
if (typeof val !== 'function') val = () => val;
const target = get(obj, arr.join('.'));
Array.isArray(target) ? target.map(e => e[last] = val(e[last])) : target[last] = val(target[last]);
};
let count = 0;
rl.on('line', (line) => {
parser.xmlToJson(line, (err, json) => {
try {
if (typeof json === 'undefined') return;
if (!Object.keys(json).includes(entityTag)) return;
const entity = json[entityTag];
for (const field of tableConfig.repeated) {
const value = get(entity, field.toUpperCase());
if (typeof value === 'object' && Object.keys(value).length === 1) {
set(entity, field.toUpperCase(), (v) => Object.entries(v)[0][1]);
}
if (!Array.isArray(entity[field.toUpperCase()])) {
set(entity, field.toUpperCase(), []);
}
}
for (const field of tableConfig.record) {
if (typeof get(entity, field.toUpperCase()) !== 'object') {
set(entity, field.toUpperCase(), {});
}
}
const getStrings = (prefix, elems) => (
elems.flatMap(e => e.fields ? getStrings(prefix + e.name.toUpperCase() + '.', e.fields) : prefix + e.name.toUpperCase())
);
const names = getStrings('', tableConfig.settlementsSchema);
for (const name of names) {
if (!tableConfig.repeated.includes(name.toLowerCase()) && Array.isArray(get(entity, name))) {
set(entity, name, e => Array.isArray(e) ? e[0] : e);
}
}
count++;
if (count % 1000 === 0) {
console.log(count);
}
const writable = bqStream.write(JSON.stringify(entity) + '\n', 'utf8');
} catch (error) {
console.log(error);
process.exit(1);
}
});
});
bqStream.once('complete', () => {
console.log('bq end');
});
bqStream.on('error', (e) => console.log(e));
fileStream.on('error', () => (console.log('File stream error'), bqStream.end()));
fileStream.on('end', () => (console.log('File stream end'), bqStream.end()));
iconvStream.on('error', () => (console.log('Iconv stream error'), bqStream.end()));
iconvStream.on('end', () => (console.log('Iconv stream end'), bqStream.end()));
process.on('SIGINT', () => {
bqStream.end();
console.info('SIGINT signal received.');
process.exit(0);
});
};