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