search-input-query-parser 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/first-pass-parser.js +77 -0
- package/dist/cjs/lexer.js +322 -0
- package/dist/cjs/parse-in-values.js +65 -0
- package/dist/cjs/parse-primary.js +154 -0
- package/dist/cjs/parse-range-expression.js +174 -0
- package/dist/cjs/parser.js +85 -0
- package/dist/cjs/search-query-to-sql.js +346 -0
- package/dist/cjs/transform-to-expression.js +130 -0
- package/dist/cjs/validate-expression-fields.js +244 -0
- package/dist/cjs/validate-in-expression.js +33 -0
- package/dist/cjs/validate-string.js +65 -0
- package/dist/cjs/validate-wildcard.js +40 -0
- package/dist/cjs/validator.js +34 -0
- package/dist/esm/first-pass-parser.js +73 -0
- package/dist/esm/lexer.js +315 -0
- package/dist/esm/parse-in-values.js +61 -0
- package/dist/esm/parse-primary.js +147 -0
- package/dist/esm/parse-range-expression.js +170 -0
- package/dist/esm/parser.js +81 -0
- package/dist/esm/search-query-to-sql.js +341 -0
- package/dist/esm/transform-to-expression.js +126 -0
- package/dist/esm/validate-expression-fields.js +240 -0
- package/dist/esm/validate-in-expression.js +29 -0
- package/dist/esm/validate-string.js +61 -0
- package/dist/esm/validate-wildcard.js +36 -0
- package/dist/esm/validator.js +30 -0
- package/dist/types/first-pass-parser.d.ts +40 -0
- package/dist/types/lexer.d.ts +27 -0
- package/dist/types/parse-in-values.d.ts +3 -0
- package/dist/types/parse-primary.d.ts +6 -0
- package/dist/types/parse-range-expression.d.ts +2 -0
- package/dist/types/parser.d.ts +68 -0
- package/dist/types/search-query-to-sql.d.ts +18 -0
- package/dist/types/transform-to-expression.d.ts +3 -0
- package/dist/types/validate-expression-fields.d.ts +4 -0
- package/dist/types/validate-in-expression.d.ts +3 -0
- package/dist/types/validate-string.d.ts +3 -0
- package/dist/types/validate-wildcard.d.ts +3 -0
- package/dist/types/validator.d.ts +8 -0
- package/package.json +52 -0
- package/src/first-pass-parser.test.ts +441 -0
- package/src/first-pass-parser.ts +144 -0
- package/src/lexer.test.ts +439 -0
- package/src/lexer.ts +387 -0
- package/src/parse-in-values.ts +74 -0
- package/src/parse-primary.ts +179 -0
- package/src/parse-range-expression.ts +187 -0
- package/src/parser.test.ts +982 -0
- package/src/parser.ts +219 -0
- package/src/search-query-to-sql.test.ts +503 -0
- package/src/search-query-to-sql.ts +506 -0
- package/src/transform-to-expression.ts +153 -0
- package/src/validate-expression-fields.ts +296 -0
- package/src/validate-in-expression.ts +36 -0
- package/src/validate-string.ts +73 -0
- package/src/validate-wildcard.ts +45 -0
- package/src/validator.test.ts +192 -0
- package/src/validator.ts +53 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { tokenize, createStream, currentToken, TokenType } from "./lexer";
|
|
2
|
+
import { parseExpression, } from "./first-pass-parser";
|
|
3
|
+
import { validateSearchQuery } from "./validator";
|
|
4
|
+
import { validateExpressionFields } from "./validate-expression-fields";
|
|
5
|
+
import { transformToExpression } from "./transform-to-expression";
|
|
6
|
+
// Helper function to stringify expressions
|
|
7
|
+
const stringify = (expr) => {
|
|
8
|
+
var _a;
|
|
9
|
+
switch (expr.type) {
|
|
10
|
+
case "SEARCH_TERM":
|
|
11
|
+
return expr.value;
|
|
12
|
+
case "WILDCARD":
|
|
13
|
+
return `${expr.prefix}*`;
|
|
14
|
+
case "FIELD_VALUE":
|
|
15
|
+
return `${expr.field.value}:${expr.value.value}`;
|
|
16
|
+
case "RANGE":
|
|
17
|
+
if (expr.operator === "BETWEEN") {
|
|
18
|
+
return `${expr.field.value}:${expr.value.value}..${(_a = expr.value2) === null || _a === void 0 ? void 0 : _a.value}`;
|
|
19
|
+
}
|
|
20
|
+
return `${expr.field.value}:${expr.operator}${expr.value.value}`;
|
|
21
|
+
case "NOT":
|
|
22
|
+
return `NOT (${stringify(expr.expression)})`;
|
|
23
|
+
case "AND":
|
|
24
|
+
return `(${stringify(expr.left)} AND ${stringify(expr.right)})`;
|
|
25
|
+
case "OR":
|
|
26
|
+
return `(${stringify(expr.left)} OR ${stringify(expr.right)})`;
|
|
27
|
+
case "IN": {
|
|
28
|
+
const values = expr.values.map((v) => v.value).join(",");
|
|
29
|
+
return `${expr.field.value}:IN(${values})`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
// Main parse function
|
|
34
|
+
export const parseSearchInputQuery = (input, fieldSchemas = []) => {
|
|
35
|
+
try {
|
|
36
|
+
const tokens = tokenize(input);
|
|
37
|
+
const stream = createStream(tokens);
|
|
38
|
+
if (currentToken(stream).type === TokenType.EOF) {
|
|
39
|
+
return { type: "SEARCH_QUERY", expression: null };
|
|
40
|
+
}
|
|
41
|
+
const result = parseExpression(stream);
|
|
42
|
+
const finalToken = currentToken(result.stream);
|
|
43
|
+
if (finalToken.type !== TokenType.EOF) {
|
|
44
|
+
throw {
|
|
45
|
+
message: 'Unexpected ")"',
|
|
46
|
+
position: finalToken.position,
|
|
47
|
+
length: finalToken.length,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const errors = validateSearchQuery(result.result);
|
|
51
|
+
const fieldErrors = [];
|
|
52
|
+
const allowedFields = fieldSchemas.map((s) => s.name.toLowerCase());
|
|
53
|
+
if (allowedFields.length > 0) {
|
|
54
|
+
const columnSet = new Set(allowedFields.map((col) => col.toLowerCase()));
|
|
55
|
+
const schemaMap = new Map(fieldSchemas.map((s) => [s.name.toLowerCase(), s]));
|
|
56
|
+
validateExpressionFields(result.result, columnSet, fieldErrors, schemaMap);
|
|
57
|
+
}
|
|
58
|
+
const fieldErrorKeys = fieldErrors.map(({ position, length }) => `${position}-${length}`);
|
|
59
|
+
const errorsToRemove = errors.filter(({ position, length }) => fieldErrorKeys.includes(`${position}-${length}`));
|
|
60
|
+
const fieldErrorsFiltered = fieldErrors.filter(({ position, length }) => !errorsToRemove.some((error) => error.position === position && error.length === length));
|
|
61
|
+
const allErrors = [...errors, ...fieldErrorsFiltered].sort((a, b) => a.position - b.position);
|
|
62
|
+
if (allErrors.length > 0) {
|
|
63
|
+
return {
|
|
64
|
+
type: "SEARCH_QUERY_ERROR",
|
|
65
|
+
expression: null,
|
|
66
|
+
errors: allErrors,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const schemaMap = new Map(fieldSchemas.map((s) => [s.name.toLowerCase(), s]));
|
|
70
|
+
const expression = transformToExpression(result.result, schemaMap);
|
|
71
|
+
return { type: "SEARCH_QUERY", expression };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
return {
|
|
75
|
+
type: "SEARCH_QUERY_ERROR",
|
|
76
|
+
expression: null,
|
|
77
|
+
errors: [error],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
export { stringify, };
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { parseSearchInputQuery, } from "./parser";
|
|
2
|
+
// Constants
|
|
3
|
+
const SPECIAL_CHARS = ["%", "_"];
|
|
4
|
+
const ESCAPE_CHAR = "\\";
|
|
5
|
+
// Helper Functions
|
|
6
|
+
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
7
|
+
const escapeSpecialChars = (value) => SPECIAL_CHARS.reduce((escaped, char) => escaped.replace(new RegExp(escapeRegExp(char), "g"), ESCAPE_CHAR + char), value);
|
|
8
|
+
// Helper to escape special characters for ParadeDB query syntax
|
|
9
|
+
const escapeParadeDBChars = (value) => {
|
|
10
|
+
const specialChars = [
|
|
11
|
+
"+",
|
|
12
|
+
"^",
|
|
13
|
+
"`",
|
|
14
|
+
":",
|
|
15
|
+
"{",
|
|
16
|
+
"}",
|
|
17
|
+
'"',
|
|
18
|
+
"[",
|
|
19
|
+
"]",
|
|
20
|
+
"(",
|
|
21
|
+
")",
|
|
22
|
+
"<",
|
|
23
|
+
">",
|
|
24
|
+
"~",
|
|
25
|
+
"!",
|
|
26
|
+
"\\",
|
|
27
|
+
"*",
|
|
28
|
+
];
|
|
29
|
+
return specialChars.reduce((escaped, char) => escaped.replace(new RegExp(escapeRegExp(char), "g"), `\\${char}`), value);
|
|
30
|
+
};
|
|
31
|
+
const stripQuotes = (value) => {
|
|
32
|
+
if (value.startsWith('"') && value.endsWith('"')) {
|
|
33
|
+
return value.slice(1, -1);
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
};
|
|
37
|
+
const cleanQuotedString = (value, stripOuterQuotes = true) => {
|
|
38
|
+
// First strip the outer quotes if requested
|
|
39
|
+
let cleaned = stripOuterQuotes ? stripQuotes(value) : value;
|
|
40
|
+
// Replace escaped quotes with regular quotes
|
|
41
|
+
cleaned = cleaned.replace(/\\"/g, '"');
|
|
42
|
+
// Clean up any remaining escape characters
|
|
43
|
+
cleaned = cleaned.replace(/\\\\/g, "\\");
|
|
44
|
+
return cleaned;
|
|
45
|
+
};
|
|
46
|
+
const isQuotedString = (value) => {
|
|
47
|
+
return value.startsWith('"') && value.endsWith('"');
|
|
48
|
+
};
|
|
49
|
+
const prepareParadeDBString = (value, includeWildcard = false) => {
|
|
50
|
+
// First clean up the string
|
|
51
|
+
const cleaned = cleanQuotedString(value);
|
|
52
|
+
// For ParadeDB, we need to:
|
|
53
|
+
// 1. Escape special characters (except wildcards)
|
|
54
|
+
// 2. Wrap in quotes
|
|
55
|
+
// 3. Add wildcard if needed
|
|
56
|
+
const escaped = escapeParadeDBChars(cleaned);
|
|
57
|
+
const result = `"${escaped}"`;
|
|
58
|
+
return includeWildcard ? `${result}*` : result;
|
|
59
|
+
};
|
|
60
|
+
// Create a new parameter placeholder and update state
|
|
61
|
+
const nextParam = (state) => {
|
|
62
|
+
const paramName = `$${state.paramCounter}`;
|
|
63
|
+
const newState = {
|
|
64
|
+
...state,
|
|
65
|
+
paramCounter: state.paramCounter + 1,
|
|
66
|
+
};
|
|
67
|
+
return [paramName, newState];
|
|
68
|
+
};
|
|
69
|
+
// Add a value to the state and return updated state
|
|
70
|
+
const addValue = (state, value) => ({
|
|
71
|
+
...state,
|
|
72
|
+
values: [...state.values, value],
|
|
73
|
+
});
|
|
74
|
+
/**
|
|
75
|
+
* Convert a wildcard pattern to SQL
|
|
76
|
+
*/
|
|
77
|
+
const wildcardPatternToSql = (expr, state) => {
|
|
78
|
+
if (expr.prefix === "") {
|
|
79
|
+
return ["1=1", state];
|
|
80
|
+
}
|
|
81
|
+
const [paramName, newState] = nextParam(state);
|
|
82
|
+
const cleanedPrefix = cleanQuotedString(expr.prefix);
|
|
83
|
+
switch (state.searchType) {
|
|
84
|
+
case "paradedb": {
|
|
85
|
+
const queryValue = prepareParadeDBString(cleanedPrefix, true);
|
|
86
|
+
const conditions = state.searchableColumns.map((column) => `${column} @@@ ${paramName}`);
|
|
87
|
+
const sql = conditions.length === 1
|
|
88
|
+
? conditions[0]
|
|
89
|
+
: `(${conditions.join(" OR ")})`;
|
|
90
|
+
return [sql, addValue(newState, queryValue)];
|
|
91
|
+
}
|
|
92
|
+
case "tsvector": {
|
|
93
|
+
const langConfig = state.language || "english";
|
|
94
|
+
const conditions = state.searchableColumns.map((column) => `to_tsvector('${langConfig}', ${column})`);
|
|
95
|
+
const tsvectorCondition = `(${conditions.join(" || ")}) @@ to_tsquery('${langConfig}', ${paramName})`;
|
|
96
|
+
return [tsvectorCondition, addValue(newState, `${cleanedPrefix}:*`)];
|
|
97
|
+
}
|
|
98
|
+
default: {
|
|
99
|
+
// ILIKE behavior
|
|
100
|
+
const escapedPrefix = escapeSpecialChars(cleanedPrefix);
|
|
101
|
+
const conditions = state.searchableColumns.map((column) => `lower(${column}) LIKE lower(${paramName})`);
|
|
102
|
+
const sql = conditions.length === 1
|
|
103
|
+
? conditions[0]
|
|
104
|
+
: `(${conditions.join(" OR ")})`;
|
|
105
|
+
return [sql, addValue(newState, `${escapedPrefix}%`)];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Convert a search term to SQL conditions based on search type
|
|
111
|
+
*/
|
|
112
|
+
const searchTermToSql = (value, state) => {
|
|
113
|
+
const [paramName, newState] = nextParam(state);
|
|
114
|
+
const hasWildcard = value.endsWith("*");
|
|
115
|
+
const isQuoted = isQuotedString(value);
|
|
116
|
+
const cleanedValue = cleanQuotedString(value);
|
|
117
|
+
const baseValue = hasWildcard ? cleanedValue.slice(0, -1) : cleanedValue;
|
|
118
|
+
switch (state.searchType) {
|
|
119
|
+
case "paradedb": {
|
|
120
|
+
const queryValue = prepareParadeDBString(baseValue, hasWildcard);
|
|
121
|
+
const conditions = state.searchableColumns.map((column) => `${column} @@@ ${paramName}`);
|
|
122
|
+
const sql = conditions.length === 1
|
|
123
|
+
? conditions[0]
|
|
124
|
+
: `(${conditions.join(" OR ")})`;
|
|
125
|
+
return [sql, addValue(newState, queryValue)];
|
|
126
|
+
}
|
|
127
|
+
case "tsvector": {
|
|
128
|
+
const langConfig = state.language || "english";
|
|
129
|
+
const conditions = state.searchableColumns.map((column) => `to_tsvector('${langConfig}', ${column})`);
|
|
130
|
+
const tsvectorCondition = `(${conditions.join(" || ")}) @@ ${hasWildcard ? "to_tsquery" : "plainto_tsquery"}('${langConfig}', ${paramName})`;
|
|
131
|
+
return [
|
|
132
|
+
tsvectorCondition,
|
|
133
|
+
addValue(newState, hasWildcard ? `${baseValue}:*` : baseValue),
|
|
134
|
+
];
|
|
135
|
+
}
|
|
136
|
+
case "ilike": {
|
|
137
|
+
// Use lower() for case-insensitive search in SQLite
|
|
138
|
+
const escapedTerm = escapeSpecialChars(baseValue);
|
|
139
|
+
const conditions = state.searchableColumns.map((column) => `lower(${column}) LIKE lower(${paramName})`);
|
|
140
|
+
const sql = conditions.length === 1
|
|
141
|
+
? conditions[0]
|
|
142
|
+
: `(${conditions.join(" OR ")})`;
|
|
143
|
+
if (hasWildcard) {
|
|
144
|
+
return [sql, addValue(newState, `${escapedTerm}%`)];
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
return [sql, addValue(newState, `%${escapedTerm}%`)];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Convert a field:value pair to SQL based on search type
|
|
154
|
+
*/
|
|
155
|
+
const fieldValueToSql = (field, value, state) => {
|
|
156
|
+
const [paramName, newState] = nextParam(state);
|
|
157
|
+
const schema = state.schemas.get(field.toLowerCase());
|
|
158
|
+
const hasWildcard = value.endsWith("*");
|
|
159
|
+
const cleanedValue = cleanQuotedString(value);
|
|
160
|
+
const baseValue = hasWildcard ? cleanedValue.slice(0, -1) : cleanedValue;
|
|
161
|
+
if (state.searchType === "paradedb") {
|
|
162
|
+
switch (schema === null || schema === void 0 ? void 0 : schema.type) {
|
|
163
|
+
case "date": {
|
|
164
|
+
// Use parameter binding for dates
|
|
165
|
+
const [dateParam, dateState] = nextParam(state);
|
|
166
|
+
return [
|
|
167
|
+
`${field} @@@ '"' || ${dateParam} || '"'`,
|
|
168
|
+
addValue(dateState, baseValue),
|
|
169
|
+
];
|
|
170
|
+
}
|
|
171
|
+
case "number":
|
|
172
|
+
return [`${field} @@@ '${baseValue}'`, newState];
|
|
173
|
+
default: {
|
|
174
|
+
const queryValue = prepareParadeDBString(baseValue, hasWildcard);
|
|
175
|
+
return [`${field} @@@ ${paramName}`, addValue(newState, queryValue)];
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Rest of the function remains the same...
|
|
180
|
+
switch (schema === null || schema === void 0 ? void 0 : schema.type) {
|
|
181
|
+
case "date":
|
|
182
|
+
return [
|
|
183
|
+
`${field} = ${paramName}`,
|
|
184
|
+
addValue(newState, cleanedValue),
|
|
185
|
+
];
|
|
186
|
+
case "number":
|
|
187
|
+
return [
|
|
188
|
+
`${field} = ${paramName}`,
|
|
189
|
+
addValue(newState, Number(cleanedValue)),
|
|
190
|
+
];
|
|
191
|
+
default:
|
|
192
|
+
if (state.searchType === "tsvector" &&
|
|
193
|
+
state.searchableColumns.includes(field)) {
|
|
194
|
+
const langConfig = state.language || "english";
|
|
195
|
+
return [
|
|
196
|
+
`to_tsvector('${langConfig}', ${field}) @@ ${hasWildcard ? "to_tsquery" : "plainto_tsquery"}('${langConfig}', ${paramName})`,
|
|
197
|
+
addValue(newState, hasWildcard ? `${baseValue}:*` : baseValue),
|
|
198
|
+
];
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
const escapedValue = escapeSpecialChars(baseValue);
|
|
202
|
+
return [
|
|
203
|
+
`lower(${field}) LIKE lower(${paramName})`,
|
|
204
|
+
addValue(newState, hasWildcard ? `${escapedValue}%` : `%${escapedValue}%`),
|
|
205
|
+
];
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* Convert a range expression to SQL
|
|
211
|
+
*/
|
|
212
|
+
const rangeToSql = (field, operator, value, value2, state) => {
|
|
213
|
+
const schema = state.schemas.get(field.toLowerCase());
|
|
214
|
+
const isDateField = (schema === null || schema === void 0 ? void 0 : schema.type) === "date";
|
|
215
|
+
if (state.searchType === "paradedb") {
|
|
216
|
+
if (operator === "BETWEEN" && value2) {
|
|
217
|
+
const [param1, state1] = nextParam(state);
|
|
218
|
+
const [param2, state2] = nextParam(state1);
|
|
219
|
+
let val1 = isDateField ? value : Number(value);
|
|
220
|
+
let val2 = isDateField ? value2 : Number(value2);
|
|
221
|
+
return [
|
|
222
|
+
`${field} @@@ '[' || ${param1} || ' TO ' || ${param2} || ']'`,
|
|
223
|
+
addValue(addValue(state2, val1), val2),
|
|
224
|
+
];
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
const [paramName, newState] = nextParam(state);
|
|
228
|
+
const rangeOp = operator.replace(">=", ">=").replace("<=", "<=");
|
|
229
|
+
const val = isDateField ? value : Number(value);
|
|
230
|
+
return [
|
|
231
|
+
`${field} @@@ '${rangeOp}' || ${paramName}`,
|
|
232
|
+
addValue(newState, val),
|
|
233
|
+
];
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (operator === "BETWEEN" && value2) {
|
|
237
|
+
const [param1, state1] = nextParam(state);
|
|
238
|
+
const [param2, state2] = nextParam(state1);
|
|
239
|
+
let val1 = isDateField ? value : Number(value);
|
|
240
|
+
let val2 = isDateField ? value2 : Number(value2);
|
|
241
|
+
return [
|
|
242
|
+
`${field} BETWEEN ${param1} AND ${param2}`,
|
|
243
|
+
addValue(addValue(state2, val1), val2),
|
|
244
|
+
];
|
|
245
|
+
}
|
|
246
|
+
const [paramName, newState] = nextParam(state);
|
|
247
|
+
const val = isDateField ? value : Number(value);
|
|
248
|
+
return [
|
|
249
|
+
`${field} ${operator} ${paramName}`,
|
|
250
|
+
addValue(newState, val),
|
|
251
|
+
];
|
|
252
|
+
};
|
|
253
|
+
const inExpressionToSql = (field, values, state) => {
|
|
254
|
+
let currentState = state;
|
|
255
|
+
const cleanedValues = values.map((v) => cleanQuotedString(v));
|
|
256
|
+
if (state.searchType === "paradedb") {
|
|
257
|
+
const paramNames = [];
|
|
258
|
+
for (const value of cleanedValues) {
|
|
259
|
+
const [paramName, newState] = nextParam(currentState);
|
|
260
|
+
paramNames.push(paramName);
|
|
261
|
+
currentState = addValue(newState, value);
|
|
262
|
+
}
|
|
263
|
+
const concatExpr = paramNames.join(" || ' ' || ");
|
|
264
|
+
return [`${field} @@@ 'IN[' || ${concatExpr} || ']'`, currentState];
|
|
265
|
+
}
|
|
266
|
+
const paramNames = [];
|
|
267
|
+
const schema = state.schemas.get(field.toLowerCase());
|
|
268
|
+
for (const value of cleanedValues) {
|
|
269
|
+
const [paramName, newState] = nextParam(currentState);
|
|
270
|
+
paramNames.push(paramName);
|
|
271
|
+
currentState = addValue(newState, (schema === null || schema === void 0 ? void 0 : schema.type) === "number" ? Number(value) : value);
|
|
272
|
+
}
|
|
273
|
+
return [
|
|
274
|
+
`${field} IN (${paramNames
|
|
275
|
+
.map((p) => p)
|
|
276
|
+
.join(", ")})`,
|
|
277
|
+
currentState,
|
|
278
|
+
];
|
|
279
|
+
};
|
|
280
|
+
/**
|
|
281
|
+
* Convert a binary operation (AND/OR) to SQL
|
|
282
|
+
*/
|
|
283
|
+
const binaryOpToSql = (operator, left, right, state) => {
|
|
284
|
+
const [leftText, leftState] = expressionToSql(left, state);
|
|
285
|
+
const [rightText, rightState] = expressionToSql(right, leftState);
|
|
286
|
+
return [`(${leftText} ${operator} ${rightText})`, rightState];
|
|
287
|
+
};
|
|
288
|
+
/**
|
|
289
|
+
* Convert a single expression to SQL
|
|
290
|
+
*/
|
|
291
|
+
const expressionToSql = (expr, state) => {
|
|
292
|
+
var _a;
|
|
293
|
+
switch (expr.type) {
|
|
294
|
+
case "SEARCH_TERM":
|
|
295
|
+
return searchTermToSql(expr.value, state);
|
|
296
|
+
case "WILDCARD":
|
|
297
|
+
return wildcardPatternToSql(expr, state);
|
|
298
|
+
case "IN":
|
|
299
|
+
return inExpressionToSql(expr.field.value, expr.values.map((v) => v.value), state);
|
|
300
|
+
case "FIELD_VALUE":
|
|
301
|
+
return fieldValueToSql(expr.field.value, expr.value.value, state);
|
|
302
|
+
case "RANGE":
|
|
303
|
+
return rangeToSql(expr.field.value, expr.operator, expr.value.value, (_a = expr.value2) === null || _a === void 0 ? void 0 : _a.value, state);
|
|
304
|
+
case "AND":
|
|
305
|
+
return binaryOpToSql("AND", expr.left, expr.right, state);
|
|
306
|
+
case "OR":
|
|
307
|
+
return binaryOpToSql("OR", expr.left, expr.right, state);
|
|
308
|
+
case "NOT": {
|
|
309
|
+
const [sqlText, newState] = expressionToSql(expr.expression, state);
|
|
310
|
+
return [`NOT ${sqlText}`, newState];
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* Convert a SearchQuery to a SQL WHERE clause with specified search type
|
|
316
|
+
*/
|
|
317
|
+
export const searchQueryToSql = (query, searchableColumns, schemas = [], options = {}) => {
|
|
318
|
+
const initialState = {
|
|
319
|
+
paramCounter: 1,
|
|
320
|
+
values: [],
|
|
321
|
+
searchableColumns,
|
|
322
|
+
schemas: new Map(schemas.map((s) => [s.name.toLowerCase(), s])),
|
|
323
|
+
searchType: options.searchType || "ilike",
|
|
324
|
+
language: options.language,
|
|
325
|
+
};
|
|
326
|
+
if (!query.expression) {
|
|
327
|
+
return { text: "1=1", values: [] };
|
|
328
|
+
}
|
|
329
|
+
const [text, finalState] = expressionToSql(query.expression, initialState);
|
|
330
|
+
return { text, values: finalState.values };
|
|
331
|
+
};
|
|
332
|
+
/**
|
|
333
|
+
* Convert a search string directly to SQL
|
|
334
|
+
*/
|
|
335
|
+
export const searchStringToSql = (searchString, searchableColumns, schemas = [], options = {}) => {
|
|
336
|
+
const query = parseSearchInputQuery(searchString, schemas);
|
|
337
|
+
if (query.type === "SEARCH_QUERY_ERROR") {
|
|
338
|
+
throw new Error(`Parse error: ${query.errors[0].message}`);
|
|
339
|
+
}
|
|
340
|
+
return searchQueryToSql(query, searchableColumns, schemas, options);
|
|
341
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { parseRangeExpression } from "./parse-range-expression";
|
|
2
|
+
// Helper to transform FirstPassExpression into Expression
|
|
3
|
+
export const transformToExpression = (expr, schemas) => {
|
|
4
|
+
switch (expr.type) {
|
|
5
|
+
case "NOT":
|
|
6
|
+
return {
|
|
7
|
+
type: "NOT",
|
|
8
|
+
expression: transformToExpression(expr.expression, schemas),
|
|
9
|
+
position: expr.position,
|
|
10
|
+
length: expr.length,
|
|
11
|
+
};
|
|
12
|
+
case "WILDCARD":
|
|
13
|
+
// Check if this is part of a field:value pattern by looking at the prefix
|
|
14
|
+
const colonIndex = expr.prefix.indexOf(":");
|
|
15
|
+
if (colonIndex !== -1) {
|
|
16
|
+
const field = expr.prefix.substring(0, colonIndex).trim();
|
|
17
|
+
const prefix = expr.prefix.substring(colonIndex + 1).trim();
|
|
18
|
+
return {
|
|
19
|
+
type: "FIELD_VALUE",
|
|
20
|
+
field: {
|
|
21
|
+
type: "FIELD",
|
|
22
|
+
value: field,
|
|
23
|
+
position: expr.position - colonIndex - 1, // Adjust for the field part
|
|
24
|
+
length: colonIndex,
|
|
25
|
+
},
|
|
26
|
+
value: {
|
|
27
|
+
type: "VALUE",
|
|
28
|
+
value: prefix + "*", // Preserve the wildcard in the value
|
|
29
|
+
position: expr.position,
|
|
30
|
+
length: prefix.length + 1,
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
// If not a field:value pattern, return as a wildcard search term
|
|
35
|
+
return {
|
|
36
|
+
type: "WILDCARD",
|
|
37
|
+
prefix: expr.prefix,
|
|
38
|
+
quoted: expr.quoted,
|
|
39
|
+
position: expr.position,
|
|
40
|
+
length: expr.length,
|
|
41
|
+
};
|
|
42
|
+
case "STRING": {
|
|
43
|
+
// Check if the string is a field:value pattern
|
|
44
|
+
const colonIndex = expr.value.indexOf(":");
|
|
45
|
+
if (colonIndex !== -1) {
|
|
46
|
+
const field = expr.value.substring(0, colonIndex).trim();
|
|
47
|
+
let value = expr.value.substring(colonIndex + 1).trim();
|
|
48
|
+
// Remove quotes if present
|
|
49
|
+
value =
|
|
50
|
+
value.startsWith('"') && value.endsWith('"')
|
|
51
|
+
? value.slice(1, -1)
|
|
52
|
+
: value;
|
|
53
|
+
const schema = schemas.get(field.toLowerCase());
|
|
54
|
+
// Check for range patterns when we have a numeric or date field
|
|
55
|
+
if (schema && (schema.type === "number" || schema.type === "date")) {
|
|
56
|
+
return parseRangeExpression(field, value, schema, expr.position, colonIndex);
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
type: "FIELD_VALUE",
|
|
60
|
+
field: {
|
|
61
|
+
type: "FIELD",
|
|
62
|
+
value: field,
|
|
63
|
+
position: expr.position,
|
|
64
|
+
length: colonIndex,
|
|
65
|
+
},
|
|
66
|
+
value: {
|
|
67
|
+
type: "VALUE",
|
|
68
|
+
value,
|
|
69
|
+
position: expr.position + colonIndex + 1,
|
|
70
|
+
length: value.length,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
type: "SEARCH_TERM",
|
|
76
|
+
value: expr.value,
|
|
77
|
+
position: expr.position,
|
|
78
|
+
length: expr.length,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
case "AND":
|
|
82
|
+
return {
|
|
83
|
+
type: "AND",
|
|
84
|
+
left: transformToExpression(expr.left, schemas),
|
|
85
|
+
right: transformToExpression(expr.right, schemas),
|
|
86
|
+
position: expr.position,
|
|
87
|
+
length: expr.length,
|
|
88
|
+
};
|
|
89
|
+
case "OR":
|
|
90
|
+
return {
|
|
91
|
+
type: "OR",
|
|
92
|
+
left: transformToExpression(expr.left, schemas),
|
|
93
|
+
right: transformToExpression(expr.right, schemas),
|
|
94
|
+
position: expr.position,
|
|
95
|
+
length: expr.length,
|
|
96
|
+
};
|
|
97
|
+
case "IN": {
|
|
98
|
+
const schema = schemas.get(expr.field.toLowerCase());
|
|
99
|
+
const transformedValues = expr.values.map((value, index) => {
|
|
100
|
+
let transformedValue = value;
|
|
101
|
+
// Handle type conversion based on schema
|
|
102
|
+
if ((schema === null || schema === void 0 ? void 0 : schema.type) === "number") {
|
|
103
|
+
transformedValue = String(Number(value));
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
type: "VALUE",
|
|
107
|
+
value: transformedValue,
|
|
108
|
+
position: expr.position + expr.field.length + 3 + index * (value.length + 1), // +3 for ":IN"
|
|
109
|
+
length: value.length,
|
|
110
|
+
};
|
|
111
|
+
});
|
|
112
|
+
return {
|
|
113
|
+
type: "IN",
|
|
114
|
+
field: {
|
|
115
|
+
type: "FIELD",
|
|
116
|
+
value: expr.field,
|
|
117
|
+
position: expr.position,
|
|
118
|
+
length: expr.field.length,
|
|
119
|
+
},
|
|
120
|
+
values: transformedValues,
|
|
121
|
+
position: expr.position,
|
|
122
|
+
length: expr.length,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|