forked from codeschool/sqlite-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreaming.js
More file actions
81 lines (74 loc) · 1.95 KB
/
streaming.js
File metadata and controls
81 lines (74 loc) · 1.95 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
import { Transform } from 'stream';
import parser from './index';
const NEXT_QUERY = /[^\;]+(\;)?/g;
export class SqliteParserTransform extends Transform {
constructor(options) {
super(options);
this.carryover = '';
this.lastError = null;
}
_transform(data, encoding, callback) {
let nextQuery = this.carryover;
let currentData = data.toString();
while (currentData !== '') {
const nextMatch = currentData.indexOf(';');
if (nextMatch !== -1) {
nextQuery += currentData.slice(0, nextMatch + 1);
currentData = currentData.slice(nextMatch + 1);
} else if (currentData.length > 0) {
nextQuery += currentData;
currentData = '';
}
let nextAst;
try {
nextAst = parser(nextQuery, {
streaming: true
});
} catch (e) {
// Continue to the next semicolon
this.lastError = e;
}
if (nextAst != null) {
let serialized;
try {
serialized = JSON.stringify(nextAst, null, 2);
} catch (e) {
// Serialize error
return callback(e);
}
this.push(serialized);
nextQuery = '';
}
}
this.carryover = nextQuery;
callback();
}
_flush(callback) {
// If there is still a little bit of query left in the buffer then
// return the last error we saw.
if (this.carryover.trim() !== '') {
callback(this.lastError);
}
callback();
}
}
export class SingleNodeTransform extends Transform {
constructor(options) {
super(options);
this.push(`{\n "type": "statement",\n "variant": "list",\n "statement": [\n `);
this.queries = 0;
}
_transform(data, encoding, callback) {
data = data.toString();
if (this.queries !== 0) {
data = `,\n${data}`;
}
this.queries += 1;
this.push(data.replace(/\n/g, '\n '));
callback();
}
_flush(callback) {
this.push(`\n ]\n}\n`);
callback();
}
}