prostgles-server 4.2.483 → 4.2.484

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.
Files changed (40) hide show
  1. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts +1 -0
  2. package/dist/DboBuilder/ViewHandler/ViewHandler.d.ts.map +1 -1
  3. package/dist/DboBuilder/ViewHandler/parseComplexFilter.d.ts.map +1 -1
  4. package/dist/DboBuilder/ViewHandler/parseComplexFilter.js +3 -2
  5. package/dist/DboBuilder/ViewHandler/parseComplexFilter.js.map +1 -1
  6. package/dist/DboBuilder/ViewHandler/prepareWhere.d.ts +1 -0
  7. package/dist/DboBuilder/ViewHandler/prepareWhere.d.ts.map +1 -1
  8. package/dist/DboBuilder/ViewHandler/prepareWhere.js +26 -13
  9. package/dist/DboBuilder/ViewHandler/prepareWhere.js.map +1 -1
  10. package/dist/DboBuilder/getCondition.d.ts +1 -0
  11. package/dist/DboBuilder/getCondition.d.ts.map +1 -1
  12. package/dist/DboBuilder/getCondition.js +10 -8
  13. package/dist/DboBuilder/getCondition.js.map +1 -1
  14. package/dist/DboBuilder/getSubscribeRelatedTables.d.ts.map +1 -1
  15. package/dist/DboBuilder/getSubscribeRelatedTables.js +1 -1
  16. package/dist/DboBuilder/getSubscribeRelatedTables.js.map +1 -1
  17. package/dist/{Filtering.d.ts → Filtering/Filtering.d.ts} +5 -7
  18. package/dist/Filtering/Filtering.d.ts.map +1 -0
  19. package/dist/Filtering/Filtering.js +244 -0
  20. package/dist/Filtering/Filtering.js.map +1 -0
  21. package/dist/Filtering/getFilterItemCondition.d.ts +7 -0
  22. package/dist/Filtering/getFilterItemCondition.d.ts.map +1 -0
  23. package/dist/Filtering/getFilterItemCondition.js +186 -0
  24. package/dist/Filtering/getFilterItemCondition.js.map +1 -0
  25. package/dist/Filtering/parseFilterRightValue.d.ts +8 -0
  26. package/dist/Filtering/parseFilterRightValue.d.ts.map +1 -0
  27. package/dist/Filtering/parseFilterRightValue.js +23 -0
  28. package/dist/Filtering/parseFilterRightValue.js.map +1 -0
  29. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +2 -5
  30. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +30 -15
  31. package/lib/DboBuilder/getCondition.ts +15 -13
  32. package/lib/DboBuilder/getSubscribeRelatedTables.ts +3 -1
  33. package/lib/Filtering/Filtering.ts +286 -0
  34. package/lib/Filtering/getFilterItemCondition.ts +205 -0
  35. package/lib/Filtering/parseFilterRightValue.ts +24 -0
  36. package/package.json +1 -1
  37. package/dist/Filtering.d.ts.map +0 -1
  38. package/dist/Filtering.js +0 -418
  39. package/dist/Filtering.js.map +0 -1
  40. package/lib/Filtering.ts +0 -468
package/lib/Filtering.ts DELETED
@@ -1,468 +0,0 @@
1
- import type { FilterDataType, FullFilter } from "prostgles-types";
2
- import {
3
- BetweenFilterKeys,
4
- CompareFilterKeys,
5
- CompareInFilterKeys,
6
- GeomFilterKeys,
7
- GeomFilter_Funcs,
8
- JsonbFilterKeys,
9
- TextFilterKeys,
10
- TextFilter_FullTextSearchFilterKeys,
11
- getKeys,
12
- includes,
13
- isDefined,
14
- isEmpty,
15
- isObject,
16
- } from "prostgles-types";
17
- import { pgp } from "./DboBuilder/DboBuilderTypes";
18
- import { type SelectItemValidated } from "./DboBuilder/QueryBuilder/QueryBuilder";
19
-
20
- export const FILTER_OPERANDS = [
21
- ...TextFilterKeys,
22
- ...JsonbFilterKeys,
23
- ...CompareFilterKeys,
24
- ...BetweenFilterKeys,
25
- ...CompareInFilterKeys,
26
- ] as const;
27
-
28
- export const FILTER_OPERAND_TO_SQL_OPERAND = Object.fromEntries(
29
- FILTER_OPERANDS.map((filterOperand) => {
30
- let sqlOperand = filterOperand as string;
31
- if (filterOperand === "$eq") sqlOperand = "=";
32
- else if (filterOperand === "$gt") sqlOperand = ">";
33
- else if (filterOperand === "$gte") sqlOperand = ">=";
34
- else if (filterOperand === "$lt") sqlOperand = "<";
35
- else if (filterOperand === "$lte") sqlOperand = "<=";
36
- else if (filterOperand === "$ne") sqlOperand = "<>";
37
- else if (filterOperand === "$like") sqlOperand = "LIKE";
38
- else if (filterOperand === "$ilike") sqlOperand = "ILIKE";
39
- else if (filterOperand === "$nlike") sqlOperand = "NOT LIKE";
40
- else if (filterOperand === "$nilike") sqlOperand = "NOT ILIKE";
41
- else if (filterOperand === "$in") sqlOperand = "IN";
42
- else if (filterOperand === "$nin") sqlOperand = "NOT IN";
43
- else if (filterOperand === "$between") sqlOperand = "BETWEEN";
44
- else if (filterOperand === "$notBetween") sqlOperand = "NOT BETWEEN";
45
- else if (filterOperand === "$isDistinctFrom") sqlOperand = "IS DISTINCT FROM";
46
- else if (filterOperand === "$isNotDistinctFrom") sqlOperand = "IS NOT DISTINCT FROM";
47
- return [filterOperand, sqlOperand];
48
- }),
49
- ) as Record<(typeof FILTER_OPERANDS)[number], string>;
50
-
51
- /**
52
- * Parse a single filter
53
- * Ensure only single key objects reach this point
54
- */
55
- type ParseFilterItemArgs = {
56
- filter: FullFilter<void, void> | undefined;
57
- select: SelectItemValidated[] | undefined;
58
- tableAliasRaw: string | undefined;
59
- allowedColumnNames: string[];
60
- };
61
-
62
- export const parseFilterItem = (args: ParseFilterItemArgs): string => {
63
- const { filter: filterItem, select, tableAliasRaw, allowedColumnNames } = args;
64
-
65
- if (!filterItem || isEmpty(filterItem)) return "";
66
-
67
- const makeError = (msg: string) => {
68
- throw `${msg}: ${JSON.stringify(filterItem, null, 2)}`;
69
- };
70
- const asValue = (v: any) => pgp.as.format("$1", [v]);
71
-
72
- const filterEntries = Object.entries(filterItem);
73
- const [firstFilterEntry, ...otherFilterEnties] = filterEntries;
74
- if (!firstFilterEntry) {
75
- return "";
76
-
77
- /**
78
- * { field1: cond1, field2: cond2 }
79
- */
80
- } else if (otherFilterEnties.length) {
81
- return filterEntries
82
- .map(([filterKey, filterValue]) =>
83
- parseFilterItem({
84
- filter: { [filterKey]: filterValue },
85
- select,
86
- tableAliasRaw,
87
- allowedColumnNames,
88
- }),
89
- )
90
- .sort() /* sorted to ensure duplicate subscription channels are not created due to different condition order */
91
- .join(" AND ");
92
- }
93
-
94
- // const fKey: string = filterKeys[0]!;
95
- const [firstFilterKey, firstFilterValue] = firstFilterEntry;
96
- let selItem: SelectItemValidated | undefined;
97
- if (select) {
98
- selItem = select.find((s) => firstFilterKey === s.alias);
99
- }
100
- let rightF = firstFilterValue;
101
-
102
- const validateSelectedItemFilter = (selectedItem: SelectItemValidated | undefined) => {
103
- const fields = selectedItem?.fields;
104
- if (Array.isArray(fields) && fields.length) {
105
- const dissallowedFields = fields.filter((fname) => !allowedColumnNames.includes(fname));
106
- if (dissallowedFields.length) {
107
- throw new Error(
108
- `Invalid/disallowed columns found in filter: ${dissallowedFields.join(", ")}`,
109
- );
110
- }
111
- }
112
- };
113
- const getLeftQ = (selItm: SelectItemValidated) => {
114
- validateSelectedItemFilter(selItem);
115
- if (selItm.type === "function" || selItm.type === "aggregation") return selItm.getQuery();
116
- return selItm.getQuery(tableAliasRaw);
117
- };
118
-
119
- /**
120
- * Parsed left side of the query
121
- */
122
- let leftQ: string | undefined; // = asName(selItem.alias);
123
-
124
- /*
125
- Select item not found.
126
- Check if dot/json notation. Build obj if necessary
127
- */
128
- const dot_notation_delims = ["->", "."];
129
- if (!selItem) {
130
- /* See if dot notation. Pick the best matching starting string */
131
- if (select) {
132
- selItem = select.find((s) =>
133
- dot_notation_delims.find((delimiter) => firstFilterKey.startsWith(s.alias + delimiter)),
134
- );
135
- validateSelectedItemFilter(selItem);
136
- }
137
- if (!selItem) {
138
- return makeError(
139
- "Bad filter. Could not match to a column or alias or dot notation" +
140
- select?.map((s) => s.alias).join(", "),
141
- );
142
- }
143
-
144
- let remainingStr = firstFilterKey.slice(selItem.alias.length);
145
-
146
- /* Is json path spec */
147
- if (remainingStr.startsWith("->")) {
148
- /** Has shorthand operand 'col->>key.<>' */
149
- const matchingOperand = CompareFilterKeys.find((operand) =>
150
- remainingStr.endsWith(`.${operand}`),
151
- );
152
- if (matchingOperand) {
153
- remainingStr = remainingStr.slice(0, -matchingOperand.length - 1);
154
- rightF = { [matchingOperand]: rightF };
155
- }
156
-
157
- leftQ = getLeftQ(selItem);
158
-
159
- /**
160
- * get json path separators. Expecting -> to come first
161
- */
162
- type GetSepRes = { idx: number; sep: string } | undefined;
163
- const getSep = (fromIdx = 0): GetSepRes => {
164
- const strPart = remainingStr.slice(fromIdx);
165
- let idx = strPart.indexOf("->");
166
- const idxx = strPart.indexOf("->>");
167
- if (idx > -1) {
168
- /* if -> matches then check if it's the last separator */
169
- if (idx === idxx) return { idx: idx + fromIdx, sep: "->>" };
170
- return { idx: idx + fromIdx, sep: "->" };
171
- }
172
- idx = strPart.indexOf("->>");
173
- if (idx > -1) {
174
- return { idx: idx + fromIdx, sep: "->>" };
175
- }
176
-
177
- return undefined;
178
- };
179
-
180
- let currSep = getSep();
181
- while (currSep) {
182
- let nextSep = getSep(currSep.idx + currSep.sep.length);
183
-
184
- let nextIdx = nextSep ? nextSep.idx : remainingStr.length;
185
-
186
- /* If ending in set then add set as well into key */
187
- if (nextSep && nextIdx + nextSep.sep.length === remainingStr.length) {
188
- nextIdx = remainingStr.length;
189
- nextSep = undefined;
190
- }
191
-
192
- leftQ +=
193
- currSep.sep + asValue(remainingStr.slice(currSep.idx + currSep.sep.length, nextIdx));
194
- currSep = nextSep;
195
- }
196
-
197
- /*
198
- Is collapsed filter spec e.g. { "col.$ilike": 'text' }
199
- will transform into { col: { $ilike: ['text'] } }
200
- */
201
- } else if (remainingStr.startsWith(".")) {
202
- leftQ = getLeftQ(selItem);
203
-
204
- const getSep = (fromIdx = 0) => {
205
- const idx = remainingStr.slice(fromIdx).indexOf(".");
206
- if (idx > -1) return fromIdx + idx;
207
- return idx;
208
- };
209
- let currIdx = getSep();
210
- const res: any = {};
211
- let curObj = res;
212
-
213
- while (currIdx > -1) {
214
- let nextIdx = getSep(currIdx + 1);
215
- let nIdx = nextIdx > -1 ? nextIdx : remainingStr.length;
216
-
217
- /* If ending in dot then add dot as well into key */
218
- if (nextIdx + 1 === remainingStr.length) {
219
- nIdx = remainingStr.length;
220
- nextIdx = -1;
221
- }
222
-
223
- const key = remainingStr.slice(currIdx + 1, nIdx);
224
- curObj[key] = nextIdx > -1 ? {} : firstFilterValue;
225
- curObj = curObj[key];
226
-
227
- currIdx = nextIdx;
228
- }
229
-
230
- rightF = res;
231
- } else {
232
- // console.trace(141, select, selItem, remainingStr)
233
- makeError("Bad filter. Could not find the valid col name or alias or col json path");
234
- }
235
- } else {
236
- leftQ = getLeftQ(selItem);
237
- }
238
-
239
- if (!leftQ) makeError("Internal error: leftQ missing?!");
240
-
241
- const parseRightVal = (val: any, expect?: "csv" | "array" | "json" | "jsonb") => {
242
- try {
243
- return parseFilterRightValue(val, { selectItem: selItem, expect });
244
- } catch (e: any) {
245
- return makeError(e);
246
- }
247
- };
248
-
249
- /* Matching sel item */
250
- if (isObject(rightF)) {
251
- const filterKeys = Object.keys(rightF);
252
- let filterOperand = filterKeys[0] as (typeof FILTER_OPERANDS)[number];
253
-
254
- /** JSON cannot be compared so we'll cast it to TEXT */
255
- if (selItem.column_udt_type === "json" || includes(TextFilterKeys, filterOperand)) {
256
- leftQ += "::TEXT ";
257
- }
258
-
259
- /** It's an object key which means it's an equality comparison against a json object */
260
- if (selItem.column_udt_type?.startsWith("json") && !includes(FILTER_OPERANDS, filterOperand)) {
261
- return leftQ + " = " + parseRightVal(rightF);
262
- }
263
-
264
- let filterValue = rightF[filterOperand] as string | null | number | Date | any[];
265
- const ALLOWED_FUNCS = [...GeomFilter_Funcs, ...TextFilter_FullTextSearchFilterKeys] as const;
266
- let funcName: undefined | (typeof ALLOWED_FUNCS)[number];
267
- let funcArgs: undefined | any[];
268
-
269
- if (
270
- selItem.column_udt_type === "interval" &&
271
- isObject(rightF) &&
272
- Object.values(rightF).every((v) => Number.isFinite(v))
273
- ) {
274
- filterOperand = "=";
275
- filterValue = Object.entries(rightF)
276
- .map(([k, v]) => `${v}${k}`)
277
- .join(" ");
278
- } else if (
279
- (filterKeys.length !== 1 || !isDefined(filterOperand)) &&
280
- selItem.column_udt_type !== "jsonb"
281
- ) {
282
- return makeError("Bad filter. Expecting one key only");
283
- } else if (isObject(filterValue) && !(filterValue instanceof Date)) {
284
- /**
285
- * Filter notation
286
- * geom && st_makeenvelope(funcArgs)
287
- */
288
- const filterValueKeys = Object.keys(filterValue);
289
- funcName = filterValueKeys[0] as any;
290
- if (includes(ALLOWED_FUNCS, funcName)) {
291
- funcArgs = filterValue[funcName as any];
292
- } else {
293
- funcName = undefined;
294
- }
295
- }
296
-
297
- /** st_makeenvelope */
298
- if (
299
- includes(GeomFilterKeys, filterOperand) &&
300
- funcName &&
301
- includes(GeomFilter_Funcs, funcName)
302
- ) {
303
- /**
304
- * If leftQ is geography then:
305
- * - err can happen: 'Antipodal (180 degrees long) edge detected!'
306
- * - inacurrate results at large envelopes due to the curvature of the earth
307
- * https://gis.stackexchange.com/questions/78816/maximum-size-on-the-bounding-box-with-st-makeenvelope-and-and-geography-colum
308
- */
309
- if (funcName.toLowerCase() === "st_makeenvelope") {
310
- leftQ += "::geometry";
311
- }
312
-
313
- return `${leftQ} ${filterOperand} ${funcName}${parseRightVal(funcArgs, "csv")}`;
314
- } else if (["=", "$eq"].includes(filterOperand) && !funcName) {
315
- if (filterValue === null) return leftQ + " IS NULL ";
316
- return leftQ + " = " + parseRightVal(filterValue);
317
- } else if (["<>", "$ne"].includes(filterOperand)) {
318
- if (filterValue === null) return leftQ + " IS NOT NULL ";
319
- return leftQ + " <> " + parseRightVal(filterValue);
320
- } else if ([">", "$gt"].includes(filterOperand)) {
321
- return leftQ + " > " + parseRightVal(filterValue);
322
- } else if (["<", "$lt"].includes(filterOperand)) {
323
- return leftQ + " < " + parseRightVal(filterValue);
324
- } else if ([">=", "$gte"].includes(filterOperand)) {
325
- return leftQ + " >= " + parseRightVal(filterValue);
326
- } else if (["<=", "$lte"].includes(filterOperand)) {
327
- return leftQ + " <= " + parseRightVal(filterValue);
328
- } else if (["$in", "$nin"].includes(filterOperand)) {
329
- const isIn = filterOperand === "$in";
330
- if (filterValue !== null && !Array.isArray(filterValue)) {
331
- return makeError("In filter expects an array");
332
- }
333
- if (!filterValue?.length) {
334
- return isIn ? " FALSE " : " TRUE ";
335
- }
336
-
337
- const nonNullFilterValues = filterValue.filter((v) => v !== null);
338
- const conditions: string[] = [];
339
- if (nonNullFilterValues.length) {
340
- conditions.push(
341
- leftQ + (isIn ? " IN " : " NOT IN ") + parseRightVal(nonNullFilterValues, "csv"),
342
- );
343
- }
344
- if (filterValue.includes(null)) {
345
- const comparator = isIn ? " IS NULL " : " IS NOT NULL ";
346
- conditions.push(` ${leftQ} ${comparator} `);
347
- }
348
- const joinedConditions = conditions.join(isIn ? " OR " : " AND ");
349
- return conditions.length > 1 ? `(${joinedConditions})` : joinedConditions;
350
- } else if (["$between"].includes(filterOperand)) {
351
- if (!Array.isArray(filterValue) || filterValue.length !== 2) {
352
- return makeError("Between filter expects an array of two values");
353
- }
354
- return leftQ + " BETWEEN " + asValue(filterValue[0]) + " AND " + asValue(filterValue[1]);
355
- } else if (["$ilike"].includes(filterOperand)) {
356
- return leftQ + " ILIKE " + asValue(filterValue);
357
- } else if (["$like"].includes(filterOperand)) {
358
- return leftQ + " LIKE " + asValue(filterValue);
359
- } else if (["$nilike"].includes(filterOperand)) {
360
- return leftQ + " NOT ILIKE " + asValue(filterValue);
361
- } else if (["$nlike"].includes(filterOperand)) {
362
- return leftQ + " NOT LIKE " + asValue(filterValue);
363
- } else if (filterOperand === "$isDistinctFrom" || filterOperand === "$isNotDistinctFrom") {
364
- const operator = FILTER_OPERAND_TO_SQL_OPERAND[filterOperand];
365
- return leftQ + ` ${operator} ` + asValue(filterValue);
366
-
367
- /* MAYBE TEXT OR MAYBE ARRAY */
368
- } else if (
369
- ["@>", "<@", "$contains", "$containedBy", "$overlaps", "&&", "@@"].includes(filterOperand)
370
- ) {
371
- const operand =
372
- filterOperand === "@@" ? "@@"
373
- : ["@>", "$contains"].includes(filterOperand) ? "@>"
374
- : ["&&", "$overlaps"].includes(filterOperand) ? "&&"
375
- : "<@";
376
-
377
- if (operand === "<@" || operand === "@>") {
378
- if (selItem.column_udt_type === "jsonb") {
379
- const filterValueAsString =
380
- typeof filterValue === "string" ? filterValue : JSON.stringify(filterValue);
381
- return leftQ + operand + parseRightVal(filterValueAsString);
382
- }
383
- }
384
-
385
- /* Array for sure */
386
- if (Array.isArray(filterValue)) {
387
- return leftQ + operand + parseRightVal(filterValue, "array");
388
-
389
- /* FTSQuery */
390
- } else if (
391
- ["@@"].includes(filterOperand) &&
392
- includes(TextFilter_FullTextSearchFilterKeys, funcName)
393
- ) {
394
- let lq = `to_tsvector(${leftQ}::text)`;
395
- if (selItem.columnPGDataType === "tsvector") lq = leftQ!;
396
-
397
- const res = `${lq} ${operand} ` + `${funcName}${parseRightVal(funcArgs, "csv")}`;
398
-
399
- return res;
400
- } else {
401
- return makeError("Unrecognised filter operand: " + filterOperand + " ");
402
- }
403
- } else {
404
- return makeError("Unrecognised filter operand: " + filterOperand + " ");
405
- }
406
- } else {
407
- /* Is an equal filter */
408
- if (rightF === null) {
409
- return leftQ + " IS NULL ";
410
- } else {
411
- /**
412
- * Ensure that when comparing an array to a json column, the array is cast to json
413
- */
414
- let valueStr = asValue(rightF);
415
- if (selItem.column_udt_type?.startsWith("json") && Array.isArray(rightF)) {
416
- valueStr = pgp.as.format(`$1::jsonb`, [JSON.stringify(rightF)]);
417
- }
418
- return `${leftQ} = ${valueStr}`;
419
- }
420
- }
421
- };
422
-
423
- type ParseRightValOpts = {
424
- expect?: "csv" | "array" | "json" | "jsonb";
425
- selectItem: SelectItemValidated | undefined;
426
- };
427
- export const parseFilterRightValue = (val: any, { expect, selectItem }: ParseRightValOpts) => {
428
- const asValue = (v: any) => pgp.as.format("$1", [v]);
429
- const checkIfArr = () => {
430
- if (!Array.isArray(val)) {
431
- throw "This type of filter/column expects an Array of items";
432
- }
433
- };
434
- if (expect === "csv" || expect?.startsWith("json")) {
435
- checkIfArr();
436
- return pgp.as.format(`($1:${expect})`, [val]);
437
- } else if (expect === "array" || selectItem?.columnPGDataType === "ARRAY") {
438
- checkIfArr();
439
- return pgp.as.format(" ARRAY[$1:csv]", [val]);
440
- }
441
-
442
- return asValue(val);
443
- };
444
-
445
- // ensure pgp is not NULL!!!
446
- // const asValue = v => v;// pgp.as.value;
447
-
448
- // const filters: FilterSpec[] = [
449
- // ...(["ilike", "like"].map(op => ({
450
- // operands: ["$" + op],
451
- // tsDataTypes: ["any"] as TSDataType[],
452
- // tsDefinition: ` { $${op}: string } `,
453
- // // data_types:
454
- // getQuery: (leftQuery: string, rightVal: any) => {
455
- // return `${leftQuery}::text ${op.toUpperCase()} ${asValue(rightVal)}::text`
456
- // }
457
- // }))),
458
- // {
459
- // operands: ["", "="],
460
- // tsDataTypes: ["any"],
461
- // tsDefinition: ` { "=": any } | any `,
462
- // // data_types:
463
- // getQuery: (leftQuery: string, rightVal: any) => {
464
- // if(rightVal === null) return`${leftQuery} IS NULL `;
465
- // return `${leftQuery} = ${asValue(rightVal)}`;
466
- // }
467
- // }
468
- // ];