forked from ukrbublik/react-awesome-query-builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.js
More file actions
289 lines (259 loc) · 9.77 KB
/
sql.js
File metadata and controls
289 lines (259 loc) · 9.77 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
import {
getFieldConfig, getOperatorConfig, getFieldWidgetConfig, getFuncConfig
} from "../utils/configUtils";
import {
getFieldPath, getFieldPathLabels, getWidgetForFieldOp, formatFieldName
} from "../utils/ruleUtils";
import omit from "lodash/omit";
import pick from "lodash/pick";
import {defaultValue} from "../utils/stuff";
import {defaultConjunction} from "../utils/defaultUtils";
import {completeValue} from "../utils/funcUtils";
import {List, Map} from "immutable";
import {SqlString} from "../utils/export";
export const sqlFormat = (tree, config) => {
return _sqlFormat(tree, config, false);
};
export const _sqlFormat = (tree, config, returnErrors = true) => {
//meta is mutable
let meta = {
errors: []
};
const res = formatItem(tree, config, meta);
if (returnErrors) {
return [res, meta.errors];
} else {
if (meta.errors.length)
console.warn("Errors while exporting to SQL:", meta.errors);
return res;
}
};
const formatItem = (item, config, meta) => {
if (!item) return undefined;
const type = item.get("type");
const children = item.get("children1");
if ((type === "group" || type === "rule_group")) {
return formatGroup(item, config, meta);
} else if (type === "rule") {
return formatRule(item, config, meta);
}
return undefined;
};
const formatGroup = (item, config, meta) => {
const type = item.get("type");
const properties = item.get("properties") || new Map();
const children = item.get("children1") || new List();
const isRuleGroup = (type === "rule_group");
const groupField = isRuleGroup ? properties.get("field") : null;
const groupFieldDef = getFieldConfig(config, groupField) || {};
const mode = groupFieldDef.mode;
if (mode == "array") {
meta.errors.push(`Aggregation is not supported for ${groupField}`);
}
const not = properties.get("not");
const canHaveEmptyChildren = false; //isRuleGroup && mode == "array";
const list = children
.map((currentChild) => formatItem(currentChild, config, meta))
.filter((currentChild) => typeof currentChild !== "undefined");
if (!canHaveEmptyChildren && !list.size)
return undefined;
let conjunction = properties.get("conjunction");
if (!conjunction)
conjunction = defaultConjunction(config);
const conjunctionDefinition = config.conjunctions[conjunction];
return conjunctionDefinition.sqlFormatConj(list, conjunction, not);
};
const buildFnToFormatOp = (operator, operatorDefinition) => {
const sqlOp = operatorDefinition.sqlOp || operator;
const cardinality = defaultValue(operatorDefinition.cardinality, 1);
let fn;
if (cardinality == 0) {
fn = (field, op, values, valueSrc, valueType, opDef, operatorOptions, fieldDef) => {
return `${field} ${sqlOp}`;
};
} else if (cardinality == 1) {
fn = (field, op, value, valueSrc, valueType, opDef, operatorOptions, fieldDef) => {
return `${field} ${sqlOp} ${value}`;
};
} else if (cardinality == 2) {
// between
fn = (field, op, values, valueSrc, valueType, opDef, operatorOptions, fieldDef) => {
const valFrom = values.first();
const valTo = values.get(1);
return `${field} ${sqlOp} ${valFrom} AND ${valTo}`;
};
}
return fn;
};
const formatRule = (item, config, meta) => {
const properties = item.get("properties") || new Map();
const field = properties.get("field");
let operator = properties.get("operator");
const operatorOptions = properties.get("operatorOptions");
const iValueSrc = properties.get("valueSrc");
const iValueType = properties.get("valueType");
const iValue = properties.get("value");
const asyncListValues = properties.get("asyncListValues");
if (field == null || operator == null)
return undefined;
const fieldDefinition = getFieldConfig(config, field) || {};
let opDef = getOperatorConfig(config, operator, field) || {};
let reversedOp = opDef.reversedOp;
let revOpDef = getOperatorConfig(config, reversedOp, field) || {};
const cardinality = defaultValue(opDef.cardinality, 1);
// check op
let isRev = false;
const canFormatOp = opDef.sqlOp || opDef.sqlFormatOp;
const canFormatRevOp = revOpDef.sqlOp || revOpDef.sqlFormatOp;
if (!canFormatOp && !canFormatRevOp) {
meta.errors.push(`Operator ${operator} is not supported`);
return undefined;
}
if (!canFormatOp && canFormatRevOp) {
isRev = true;
[operator, reversedOp] = [reversedOp, operator];
[opDef, revOpDef] = [revOpDef, opDef];
}
//format value
let valueSrcs = [];
let valueTypes = [];
const fvalue = iValue.map((currentValue, ind) => {
const valueSrc = iValueSrc ? iValueSrc.get(ind) : null;
const valueType = iValueType ? iValueType.get(ind) : null;
const cValue = completeValue(currentValue, valueSrc, config);
const widget = getWidgetForFieldOp(config, field, operator, valueSrc);
const fieldWidgetDefinition = omit(getFieldWidgetConfig(config, field, operator, widget, valueSrc), ["factory"]);
let fv = formatValue(
meta, config, cValue, valueSrc, valueType, fieldWidgetDefinition, fieldDefinition, operator, opDef, asyncListValues
);
if (fv !== undefined) {
valueSrcs.push(valueSrc);
valueTypes.push(valueType);
}
return fv;
});
const hasUndefinedValues = fvalue.filter(v => v === undefined).size > 0;
if (hasUndefinedValues || fvalue.size < cardinality)
return undefined;
const formattedValue = (cardinality == 1 ? fvalue.first() : fvalue);
//find fn to format expr
const fn = opDef.sqlFormatOp || buildFnToFormatOp(operator, opDef);
if (!fn) {
meta.errors.push(`Operator ${operator} is not supported`);
return undefined;
}
//format field
const formattedField = formatField(meta, config, field);
//format expr
const args = [
formattedField,
operator,
formattedValue,
(valueSrcs.length > 1 ? valueSrcs : valueSrcs[0]),
(valueTypes.length > 1 ? valueTypes : valueTypes[0]),
omit(opDef, ["formatOp", "mongoFormatOp", "sqlFormatOp", "jsonLogic", "spelFormatOp"]),
operatorOptions,
fieldDefinition,
];
let ret;
ret = fn.call(config.ctx, ...args);
if (isRev) {
ret = config.settings.sqlFormatReverse(ret);
}
if (ret === undefined) {
meta.errors.push(`Operator ${operator} is not supported for value source ${valueSrcs.join(", ")}`);
return undefined;
}
return ret;
};
const formatValue = (meta, config, currentValue, valueSrc, valueType, fieldWidgetDef, fieldDef, operator, operatorDef, asyncListValues) => {
if (currentValue === undefined)
return undefined;
let ret;
if (valueSrc == "field") {
ret = formatField(meta, config, currentValue);
} else if (valueSrc == "func") {
ret = formatFunc(meta, config, currentValue);
} else {
if (typeof fieldWidgetDef.sqlFormatValue === "function") {
const fn = fieldWidgetDef.sqlFormatValue;
const args = [
currentValue,
{
...pick(fieldDef, ["fieldSettings", "listValues"]),
asyncListValues
},
//useful options: valueFormat for date/time
omit(fieldWidgetDef, ["formatValue", "mongoFormatValue", "sqlFormatValue", "jsonLogic", "elasticSearchFormatValue", "spelFormatValue"]),
];
if (operator) {
args.push(operator);
args.push(operatorDef);
}
if (valueSrc == "field") {
const valFieldDefinition = getFieldConfig(config, currentValue) || {};
args.push(valFieldDefinition);
}
ret = fn.call(config.ctx, ...args);
} else {
if (Array.isArray(currentValue)) {
ret = currentValue.map(v => SqlString.escape(v));
} else {
ret = SqlString.escape(currentValue);
}
}
}
return ret;
};
const formatField = (meta, config, field) => {
if (!field) return;
const {fieldSeparator} = config.settings;
const fieldDefinition = getFieldConfig(config, field) || {};
const fieldParts = Array.isArray(field) ? field : field.split(fieldSeparator);
const _fieldKeys = getFieldPath(field, config);
const fieldPartsLabels = getFieldPathLabels(field, config);
const fieldFullLabel = fieldPartsLabels ? fieldPartsLabels.join(fieldSeparator) : null;
const formatFieldFn = config.settings.formatField;
const fieldName = formatFieldName(field, config, meta, null, {useTableName: true});
const formattedField = formatFieldFn(fieldName, fieldParts, fieldFullLabel, fieldDefinition, config);
return formattedField;
};
const formatFunc = (meta, config, currentValue) => {
const funcKey = currentValue.get("func");
const args = currentValue.get("args");
const funcConfig = getFuncConfig(config, funcKey);
const funcName = funcConfig.sqlFunc || funcKey;
let formattedArgs = {};
for (const argKey in funcConfig.args) {
const argConfig = funcConfig.args[argKey];
const fieldDef = getFieldConfig(config, argConfig);
const argVal = args ? args.get(argKey) : undefined;
const argValue = argVal ? argVal.get("value") : undefined;
const argValueSrc = argVal ? argVal.get("valueSrc") : undefined;
const argAsyncListValues = argVal ? argVal.get("asyncListValues") : undefined;
const formattedArgVal = formatValue(
meta, config, argValue, argValueSrc, argConfig.type, fieldDef, argConfig, null, null, argAsyncListValues
);
if (argValue != undefined && formattedArgVal === undefined) {
meta.errors.push(`Can't format value of arg ${argKey} for func ${funcKey}`);
return undefined;
}
if (formattedArgVal !== undefined) { // skip optional in the end
formattedArgs[argKey] = formattedArgVal;
}
}
let ret;
if (typeof funcConfig.sqlFormatFunc === "function") {
const fn = funcConfig.sqlFormatFunc;
const args = [
formattedArgs
];
ret = fn.call(config.ctx, ...args);
} else {
const argsStr = Object.entries(formattedArgs)
.map(([k, v]) => v)
.join(", ");
ret = `${funcName}(${argsStr})`;
}
return ret;
};