-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathsql_parser.js
More file actions
333 lines (296 loc) · 9.49 KB
/
sql_parser.js
File metadata and controls
333 lines (296 loc) · 9.49 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { _ } from 'meteor/underscore';
const cutOff =
/(\sgroup by\s|\sorder by\s|\swhere\s|\shaving\s|\slimit\s|\soffset\s)+[\w([\])"'`.,/=<>\s]+$/i;
export default {
parse(query) {
const objectSQL = {
select: getSelect(query),
from: getFrom(query),
having: getHaving(query),
where: getWhere(query),
limit: getLimit(query),
offset: getOffset(query),
join: getJoin(query),
};
objectSQL.groupBy = getGroupBy(query, objectSQL.select);
objectSQL.orderBy = getOrderBy(query, objectSQL.select);
return objectSQL;
},
parseToQueryObject(rawQuery, fields) {
const query = this.parse(rawQuery);
const queryObject = {};
const having = getHavingObj(query);
queryObject.pagination = getPagination(query);
queryObject.fields = getFields(query, having);
query.groupBy && query.groupBy.forEach(fieldIndex => {
queryObject.fields[fieldIndex].grouping = true;
});
query.orderBy && query.orderBy.forEach(field => {
queryObject.fields[field.index].sort = field.type;
});
queryObject.collectionFields = getCollectionFields(query, fields);
queryObject.join = query.join;
return queryObject;
},
};
function getSelect(query) {
let select = query.match(/^\s*select\s+([\w([\])"'`*:&;.,/\s]+)from\s/i);
if (!select) return { error: 'Wrong syntax: "SELECT <fields> FROM <collections>" expected' };
select = select[1];
const asNames = select.match(/\s+as\s+\w+/ig);
let names = [];
let expressions = [];
if (asNames) {
names = asNames.map(item => item.replace(/(^\s+as\s|\s)+/ig, ''));
expressions = [select.slice(0, select.indexOf(asNames[0]))];
for (let i = 0; i < asNames.length - 1; i++) {
expressions.push(select.slice(select.indexOf(asNames[i]) + asNames[i].length,
select.indexOf(asNames[i + 1])));
}
} else {
expressions = select.match(/\w+\.\w+/ig);
if (expressions) {
names = expressions.map(exp => exp.match(/\w+\.(\w+)/i)[1]);
} else {
return { error: 'Wrong fields!' };
}
}
return names.map((name, i) => ({
name: names[i],
expression: expressions[i].replace(/(^,|\s)/g, ''),
}));
}
const getParamName = (queryPartial) => queryPartial.match(/\s+as\s+(\w+)/i);
const parseQueryPartial = (partial, paramName) =>
partial.slice(0, paramName.index).match(/(\w+)\/(\w+)/i);
function getFrom(query) {
const matchRes = query.match(/\sfrom\s+([\w([\])"'`.,/=<>\s]+$)/im);
if (!matchRes) return null;
const from = matchRes[1].replace(cutOff, '');
const name = getParamName(from);
const path = parseQueryPartial(from, name);
return { db: path[1], collection: path[2], name: name[1] };
}
function getJoin(query) {
const matchRes = query.match(/\sjoin\s+([\w([\])"'`.,/=<>\s]+$)/im);
if (!matchRes) return null;
const from = matchRes[1].replace(cutOff, '');
const name = getParamName(from);
const path = parseQueryPartial(from, name);
return path[2];
}
function getGroupBy(query, select) {
let groupBy = query.match(/^\s*group by\s+([\w([\])"'`*:&;.,/\s]+)/im);
if (groupBy) {
groupBy = groupBy[1].replace(cutOff, '')
.replace(/\s/g, '');
return select.reduce((previous, field, i) => {
if (~groupBy.indexOf(field.expression)) previous.push(i);
return previous;
}, []);
}
return null;
}
function getOrderBy(query, select) {
let orderBy = query.match(/\sorder by\s+([\w([\])"'`.,/=<>\s]+$)/i);
if (orderBy) {
orderBy = orderBy[1].replace(cutOff, '');
return select.reduce((previous, field, index) => {
if (~orderBy.indexOf(field.name)) {
const obj = { index };
const regex = new RegExp(`${field.name}\\s+(asc|desc)(\\s|,|$)`, 'i');
const match = orderBy.match(regex);
if (match) obj.type = match[1].toLowerCase();
previous.push(obj);
}
return previous;
}, []);
}
return null;
}
function getHaving(query) {
let having = query.match(/^\s*having\s+([\w([\])"'`*:&;.,-<>%@=\/\s]+)limit\s/im);
if (having) {
having = having[1].replace(cutOff, '');
having = removeBraces(having);
return parseHaveingConditions(having);
}
return null;
function removeBraces(queryPart) {
let result = '';
if (isCountExist(queryPart)) {
const countWordINdex = getWordIndex(queryPart, 'count(');
const afterCountIndex = getWordIndex(queryPart, ')', countWordINdex);
result += removebracesWithRegex(queryPart.substr(0, countWordINdex));
result += queryPart.substring(countWordINdex, afterCountIndex + 1);
result += removeBraces(queryPart.substring(afterCountIndex + 1));
} else {
result += removebracesWithRegex(queryPart);
}
return result;
}
function isCountExist(queryToCheck) {
return queryToCheck.match(/COUNT[(]/gi);
}
function removebracesWithRegex(line) {
return line.replace(/[()]/g, '');
}
function getWordIndex(line, word, fromPosition = 0) {
let result = line.indexOf(word, fromPosition);
if (result === -1) {
result = line.indexOf(word.toUpperCase(), fromPosition);
}
return result;
}
}
function getWhere(query) {
let where = query.match(/\swhere\s+([\w([\])"'`.,/=<>\s]+$)/im);
if (where) {
where = where[1].replace(cutOff, '');
const parsed = parseFiltering(where);
parsed.forEach( (item) => {
item.exp2 = item.exp2.replace(/^["]/i, '').replace(/["]$/i, '');
});
return parsed;
}
return null;
}
function getLimit(query) {
const limit = query.match(/\slimit\s+(\d+)/i);
if (limit) return +limit[1];
return null;
}
function getOffset(query) {
const offset = query.match(/\soffset\s+(\d+)/i);
if (offset) return +offset[1];
return null;
}
function parseHaveingConditions(str) {
const filters = [];
const andOr = str.match(/\s+(and|or)\s+/gi);
if (andOr) {
let rest = str.slice();
andOr.forEach(item => {
const part = rest.slice(0, rest.indexOf(item));
filters.push(part);
rest = rest.slice(rest.indexOf(item) + item.length);
});
filters.push(rest);
} else {
filters.push(str);
}
return filters.map((filter, i) => {
const obj = { operator: filter.match(/(=|<>|<|>|\slike\s)/i)[1] };
const regex = new RegExp(`${obj.operator}([\\w([\\])"'\`*:&;%@.,-/\\s]+)`, 'i');
obj.exp2 = filter.match(regex)[1];
obj.exp1 = filter.replace(obj.operator, '').replace(obj.exp2, '').replace(/\s/g, '');
obj.operator = obj.operator.replace(/\s/g, '');
obj.exp2 = obj.exp2.replace(/^\s+|\s+$/g, '');
if (andOr && i < andOr.length) obj.join = andOr[i].replace(/\s/g, '');
return obj;
});
}
function parseFiltering(str) {
const filters = [];
const andOr = str.match(/\s+(and|or)\s+/gi);
if (andOr) {
let rest = str.slice();
andOr.forEach(item => {
const part = rest.slice(0, rest.indexOf(item));
filters.push(part);
rest = rest.slice(rest.indexOf(item) + item.length);
});
filters.push(rest);
} else {
filters.push(str);
}
return filters.map((filter, i) => {
const obj = { operator: filter.match(/(=|<>|<|>|\slike\s)/i)[1] };
const regex = new RegExp(`${obj.operator}([\\w([\\])"'\`.,/\\s]+)`, 'i');
obj.exp2 = filter.match(regex)[1];
obj.exp1 = filter.replace(obj.operator, '').replace(obj.exp2, '').replace(/\s/g, '');
obj.operator = obj.operator.replace(/\s/g, '');
obj.exp2 = obj.exp2.replace(/^\s+|\s+$/g, '');
if (andOr && i < andOr.length) obj.join = andOr[i].replace(/\s/g, '');
return obj;
});
}
function getPagination(query) {
return {
limit: query.limit,
page: query.skip ? query.skip / query.limit : 1,
};
}
function getHavingObj(query) {
const having = {};
if (query.having) {
query.having.forEach(item => {
if (!having[item.exp1]) having[item.exp1] = [];
having[item.exp1].push({
value: item.exp2,
joinOperator: item.join,
operator: item.operator,
});
});
}
return having;
}
function getFields(query, having) {
return query.select.map((field, i) => (
{
id: i,
name: field.name,
expression: field.expression,
grouping: field.date ? field.date : false,
sort: false,
filters: having[field.expression],
}
));
}
function getCollectionFields(query, fields) {
const collectionFields = {};
if (query.where) {
query.where.forEach(item => {
const expression = item.exp1;
if (!collectionFields[expression]) {
collectionFields[expression] = {
filters: [],
name: _.last(expression.split('.')),
constructorType: 'filters',
type: getType(expression, fields[0]),
expression,
};
collectionFields[expression].filters = [];
}
collectionFields[expression].filters.push({
value: item.exp2,
joinOperator: item.join,
operator: item.operator,
});
});
}
return collectionFields;
}
function getType(expression, fields) {
let currentValue = fields;
const path = expression.split('.');
path.forEach(pathItem => {
currentValue = currentValue[pathItem];
});
return getItemType(currentValue);
}
function getItemType(value) {
if (_.isNumber(value)) return 'number';
if (_.isDate(value)) return 'date';
if (isDate(value)) return 'date';
if (_.isString(value)) return 'string';
if (_.isBoolean(value)) return 'boolean';
if (_.isArray(value)) return 'array';
if (_.isObject(value)) return 'object';
return null;
}
function isDate(value) {
const dateObj = new Date(value);
return dateObj.toString() !== 'Invalid Date' &&
dateObj.toISOString().replace('.000', '') === value;
}