-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmssql-processor.ts
83 lines (78 loc) · 2.81 KB
/
mssql-processor.ts
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
import { Readable } from 'stream';
import { IMssqlProcessorConfig, IMssqlDbConnection, processStream } from '../types';
import { closeDbConnection, getDb } from '../utils';
import { DatabaseProcessor } from './base/database-processor';
export class MssqlProcessor extends DatabaseProcessor {
protected connection: IMssqlDbConnection;
constructor(config: IMssqlProcessorConfig) {
super(config);
this.connection = config.connection;
}
async process(processStream: processStream) {
let done = false;
const readStream = new Readable({
objectMode: true,
async read() {
if (data.length === 0) {
if (!done) {
try {
await processRows();
} catch (err) {
this.emit('error', err);
}
} else {
return this.push(null);
}
}
const rowData = data.shift() || null;
this.push(rowData);
},
});
const data: any[] = [];
const db = await getDb(this.connection, 'mssql');
const dbRequest = db.request();
dbRequest.on('error', (err: any) => {
if (err.code !== 'ECANCEL') {
readStream.emit('error', err);
}
});
readStream.on('close', () => {
dbRequest.cancel();
});
dbRequest.stream = true;
dbRequest.query(this.query);
const processRows = async () => {
return new Promise<void>(async (resolve, reject) => {
function removeListeners() {
dbRequest.removeListener('row', onRow);
dbRequest.removeListener('done', onDone);
dbRequest.removeListener('error', onError);
};
async function onRow(row: any) {
data.push(row);
if (data.length >= 1000) {
dbRequest.pause();
removeListeners();
resolve();
}
};
async function onDone() {
done = true;
removeListeners();
resolve();
};
async function onError(err: any) {
removeListeners();
reject(err);
};
dbRequest.on('row', onRow);
dbRequest.on('done', onDone);
dbRequest.on('error', onError);
dbRequest.resume();
});
};
dbRequest.pause();
await processStream(readStream);
await closeDbConnection(this.connection);
}
}