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,222 @@
|
|
|
1
|
+
|
|
2
|
+
/*---------------------------------------------------------------------------------------------
|
|
3
|
+
* Copyright (c) Stefan L. All rights reserved.
|
|
4
|
+
* Licensed under the MIT License. See LICENSE in the project root for license information.
|
|
5
|
+
*--------------------------------------------------------------------------------------------*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
AnyObject,
|
|
9
|
+
PG_COLUMN_UDT_DATA_TYPE,
|
|
10
|
+
ProstglesError,
|
|
11
|
+
TS_PG_Types,
|
|
12
|
+
getKeys,
|
|
13
|
+
isObject,
|
|
14
|
+
omitKeys
|
|
15
|
+
} from "prostgles-types";
|
|
16
|
+
import {
|
|
17
|
+
DB,
|
|
18
|
+
} from "../Prostgles";
|
|
19
|
+
import { pickKeys } from "../PubSubManager/PubSubManager";
|
|
20
|
+
import { LocalParams, SortItem, pgp } from "./DboBuilderTypes";
|
|
21
|
+
import { asNameAlias } from "./QueryBuilder/QueryBuilder";
|
|
22
|
+
import { ViewHandler } from "./ViewHandler/ViewHandler";
|
|
23
|
+
import { getSchemaFilter } from "./getTablesForSchemaPostgresSQL";
|
|
24
|
+
|
|
25
|
+
import { ProstglesInitOptions } from "../ProstglesTypes";
|
|
26
|
+
import { sqlErrCodeToMsg } from "./sqlErrCodeToMsg";
|
|
27
|
+
import { TableHandler } from "./TableHandler/TableHandler";
|
|
28
|
+
export function escapeTSNames(str: string, capitalize = false): string {
|
|
29
|
+
let res = str;
|
|
30
|
+
res = (capitalize ? str[0]?.toUpperCase() : str[0]) + str.slice(1);
|
|
31
|
+
if (canBeUsedAsIsInTypescript(res)) return res;
|
|
32
|
+
return JSON.stringify(res);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const getErrorAsObject = (rawError: any, includeStack = false) => {
|
|
36
|
+
if(["string", "boolean", "number"].includes(typeof rawError)){
|
|
37
|
+
return { message: rawError };
|
|
38
|
+
}
|
|
39
|
+
if(rawError instanceof Error){
|
|
40
|
+
const result = JSON.parse(JSON.stringify(rawError, Object.getOwnPropertyNames(rawError)));
|
|
41
|
+
if(!includeStack){
|
|
42
|
+
return omitKeys(result, ["stack"]);
|
|
43
|
+
}
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return rawError;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type GetSerializedClientErrorFromPGErrorArgs = {
|
|
51
|
+
type: "sql";
|
|
52
|
+
} | {
|
|
53
|
+
type: "tableMethod";
|
|
54
|
+
localParams: LocalParams | undefined;
|
|
55
|
+
view: ViewHandler | Partial<TableHandler> | undefined;
|
|
56
|
+
allowedKeys?: string[];
|
|
57
|
+
canRunSql?: boolean;
|
|
58
|
+
} | {
|
|
59
|
+
type: "method";
|
|
60
|
+
localParams: LocalParams | undefined;
|
|
61
|
+
allowedKeys?: string[];
|
|
62
|
+
view?: undefined;
|
|
63
|
+
canRunSql?: boolean;
|
|
64
|
+
}
|
|
65
|
+
export function getSerializedClientErrorFromPGError(rawError: any, args: GetSerializedClientErrorFromPGErrorArgs): AnyObject {
|
|
66
|
+
const err = getErrorAsObject(rawError);
|
|
67
|
+
if(err.code) {
|
|
68
|
+
err.code_info = sqlErrCodeToMsg(err.code);
|
|
69
|
+
}
|
|
70
|
+
if (process.env.PRGL_DEBUG) {
|
|
71
|
+
console.trace(err)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const isServerSideRequest = args.type !== "sql" && !args.localParams;
|
|
75
|
+
if(args.type === "sql" || isServerSideRequest){
|
|
76
|
+
return err;
|
|
77
|
+
}
|
|
78
|
+
const { view, allowedKeys } = args;
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
const sensitiveErrorKeys = ["hint", "detail", "context"];
|
|
82
|
+
const otherKeys = ["column", "code", "code_info", "table", "constraint", "severity", "message", "name"];
|
|
83
|
+
const finalKeys = otherKeys
|
|
84
|
+
.concat(allowedKeys ?? [])
|
|
85
|
+
.concat(args.canRunSql? sensitiveErrorKeys : []);
|
|
86
|
+
|
|
87
|
+
const errObject = pickKeys(err, finalKeys);
|
|
88
|
+
if (view?.dboBuilder?.constraints && errObject.constraint && !errObject.column) {
|
|
89
|
+
const constraint = view.dboBuilder.constraints
|
|
90
|
+
.find(c => c.conname === errObject.constraint && c.relname === view.name);
|
|
91
|
+
if (constraint) {
|
|
92
|
+
const cols = view.columns?.filter(c =>
|
|
93
|
+
(!allowedKeys || allowedKeys.includes(c.name)) &&
|
|
94
|
+
constraint.conkey.includes(c.ordinal_position)
|
|
95
|
+
);
|
|
96
|
+
const [firstCol] = cols ?? [];
|
|
97
|
+
if (firstCol) {
|
|
98
|
+
errObject.column = firstCol.name;
|
|
99
|
+
errObject.columns = cols?.map(c => c.name);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return errObject;
|
|
104
|
+
}
|
|
105
|
+
export function getClientErrorFromPGError(rawError: any, args: GetSerializedClientErrorFromPGErrorArgs) {
|
|
106
|
+
const errorObj = getSerializedClientErrorFromPGError(rawError, args);
|
|
107
|
+
return Promise.reject(errorObj);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* @deprecated
|
|
112
|
+
*/
|
|
113
|
+
export function parseError(e: any, _caller: string): ProstglesError {
|
|
114
|
+
|
|
115
|
+
const errorObject = isObject(e) ? e : undefined;
|
|
116
|
+
const message = typeof e === "string" ? e : e instanceof Error ? e.message :
|
|
117
|
+
isObject(errorObject) ? (errorObject.message ?? errorObject.txt ?? JSON.stringify(errorObject) ?? "") : "";
|
|
118
|
+
|
|
119
|
+
const result: ProstglesError = {
|
|
120
|
+
...errorObject,
|
|
121
|
+
message,
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export type PGConstraint = {
|
|
127
|
+
/**
|
|
128
|
+
* Constraint type
|
|
129
|
+
*/
|
|
130
|
+
contype:
|
|
131
|
+
| "u" // Unique
|
|
132
|
+
| "p" // Primary key
|
|
133
|
+
| "c" // Check
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Column ordinal positions
|
|
137
|
+
*/
|
|
138
|
+
conkey: number[];
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Constraint name
|
|
142
|
+
*/
|
|
143
|
+
conname: string;
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Table name
|
|
147
|
+
*/
|
|
148
|
+
relname: string;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
export const getConstraints = async (db: DB, schema: ProstglesInitOptions["schema"]): Promise<PGConstraint[]> => {
|
|
152
|
+
const { sql, schemaNames } = getSchemaFilter(schema);
|
|
153
|
+
return db.any(`
|
|
154
|
+
SELECT rel.relname, con.conkey, con.conname, con.contype
|
|
155
|
+
FROM pg_catalog.pg_constraint con
|
|
156
|
+
INNER JOIN pg_catalog.pg_class rel
|
|
157
|
+
ON rel.oid = con.conrelid
|
|
158
|
+
INNER JOIN pg_catalog.pg_namespace nsp
|
|
159
|
+
ON nsp.oid = connamespace
|
|
160
|
+
WHERE nsp.nspname ${sql}
|
|
161
|
+
`, { schemaNames });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* @deprecated
|
|
166
|
+
* use isObject
|
|
167
|
+
*/
|
|
168
|
+
export function isPlainObject(o: any): o is Record<string, any> {
|
|
169
|
+
return Object(o) === o && Object.getPrototypeOf(o) === Object.prototype;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function postgresToTsType(udt_data_type: PG_COLUMN_UDT_DATA_TYPE): keyof typeof TS_PG_Types {
|
|
173
|
+
return getKeys(TS_PG_Types).find(k => {
|
|
174
|
+
// @ts-ignore
|
|
175
|
+
return TS_PG_Types[k].includes(udt_data_type)
|
|
176
|
+
}) ?? "any";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export const prepareOrderByQuery = (items: SortItem[], tableAlias?: string): string[] => {
|
|
180
|
+
if (!items.length) return [];
|
|
181
|
+
return ["ORDER BY " + items.map(d => {
|
|
182
|
+
|
|
183
|
+
const orderType = d.asc ? " ASC " : " DESC ";
|
|
184
|
+
const nullOrder = d.nulls ? ` NULLS ${d.nulls === "first" ? " FIRST " : " LAST "}` : "";
|
|
185
|
+
if(d.type === "query" && d.nested){
|
|
186
|
+
return d.fieldQuery;
|
|
187
|
+
}
|
|
188
|
+
return `${asNameAlias(d.key, tableAlias)} ${orderType} ${nullOrder}`;
|
|
189
|
+
}).join(", ")]
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export const getCanExecute = async (db: DB) => {
|
|
193
|
+
|
|
194
|
+
try {
|
|
195
|
+
await db.task(t => t.any(`DO $$ BEGIN EXECUTE 'select 1'; END $$;`));
|
|
196
|
+
return true;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
console.warn(error)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export const withUserRLS = (localParams: LocalParams | undefined, query: string) => {
|
|
205
|
+
|
|
206
|
+
const user = localParams?.isRemoteRequest?.user;
|
|
207
|
+
const queryPrefix = `SET SESSION "prostgles.user" \nTO`
|
|
208
|
+
let firstQuery = `${queryPrefix} '';`;
|
|
209
|
+
if (user) {
|
|
210
|
+
firstQuery = pgp.as.format(`${queryPrefix} \${user};`, { user });
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return [firstQuery, query].join("\n");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
function canBeUsedAsIsInTypescript(str: string): boolean {
|
|
218
|
+
if (!str) return false;
|
|
219
|
+
const isAlphaNumericOrUnderline = str.match(/^[a-z0-9_]+$/i);
|
|
220
|
+
const startsWithCharOrUnderscore = str[0]?.match(/^[a-z_]+$/i);
|
|
221
|
+
return Boolean(isAlphaNumericOrUnderline && startsWithCharOrUnderscore);
|
|
222
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AnyObject, PG_COLUMN_UDT_DATA_TYPE,
|
|
3
|
+
ValidatedColumnInfo, _PG_geometric, isObject
|
|
4
|
+
} from "prostgles-types";
|
|
5
|
+
import { TableRule } from "../PublishParser/PublishParser";
|
|
6
|
+
import { LocalParams, getClientErrorFromPGError, getErrorAsObject, getSerializedClientErrorFromPGError, postgresToTsType } from "./DboBuilder";
|
|
7
|
+
import { TableHandler } from "./TableHandler/TableHandler";
|
|
8
|
+
import { ViewHandler } from "./ViewHandler/ViewHandler";
|
|
9
|
+
|
|
10
|
+
export const isTableHandler = (v: any): v is TableHandler => "parseUpdateRules" in v;
|
|
11
|
+
|
|
12
|
+
export async function getColumns(
|
|
13
|
+
this: ViewHandler,
|
|
14
|
+
lang?: string,
|
|
15
|
+
params?: { rule: "update", filter: AnyObject, data: AnyObject },
|
|
16
|
+
_param3?: undefined,
|
|
17
|
+
tableRules?: TableRule,
|
|
18
|
+
localParams?: LocalParams
|
|
19
|
+
): Promise<ValidatedColumnInfo[]> {
|
|
20
|
+
const start = Date.now();
|
|
21
|
+
try {
|
|
22
|
+
|
|
23
|
+
const p = this.getValidatedRules(tableRules, localParams);
|
|
24
|
+
|
|
25
|
+
if (!p.getColumns) throw "Not allowed";
|
|
26
|
+
|
|
27
|
+
let dynamicUpdateFields = this.column_names;
|
|
28
|
+
|
|
29
|
+
if (params && tableRules && isTableHandler(this)) {
|
|
30
|
+
if (
|
|
31
|
+
!isObject(params) ||
|
|
32
|
+
!isObject(params.filter) ||
|
|
33
|
+
params.rule !== "update"
|
|
34
|
+
) {
|
|
35
|
+
throw "params must be { rule: 'update', filter: object } but received: " + JSON.stringify(params);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!tableRules?.update) {
|
|
39
|
+
dynamicUpdateFields = [];
|
|
40
|
+
} else {
|
|
41
|
+
const { filter } = params;
|
|
42
|
+
const updateRules = await this.parseUpdateRules(filter, undefined, tableRules, localParams);
|
|
43
|
+
dynamicUpdateFields = updateRules.fields;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const columns = this.columns
|
|
48
|
+
.filter(c => {
|
|
49
|
+
const { insert, select, update } = p || {};
|
|
50
|
+
|
|
51
|
+
return [
|
|
52
|
+
...(insert?.fields || []),
|
|
53
|
+
...(select?.fields || []),
|
|
54
|
+
...(update?.fields || []),
|
|
55
|
+
].includes(c.name)
|
|
56
|
+
})
|
|
57
|
+
.map(_c => {
|
|
58
|
+
const c = { ..._c };
|
|
59
|
+
|
|
60
|
+
const label = c.comment || capitalizeFirstLetter(c.name, " ");
|
|
61
|
+
|
|
62
|
+
const select = !!c.privileges.SELECT;
|
|
63
|
+
const insert = !!c.privileges.INSERT;
|
|
64
|
+
const _delete = !!this.tableOrViewInfo.privileges.delete;
|
|
65
|
+
let update = !!c.privileges.UPDATE;
|
|
66
|
+
|
|
67
|
+
delete (c as any).privileges;
|
|
68
|
+
|
|
69
|
+
const prostgles = this.dboBuilder?.prostgles;
|
|
70
|
+
const fileConfig = prostgles.fileManager?.getColInfo({ colName: c.name, tableName: this.name });
|
|
71
|
+
|
|
72
|
+
/** Do not allow updates to file table unless it's to delete fields */
|
|
73
|
+
if (prostgles.fileManager?.config && prostgles.fileManager.tableName === this.name) {
|
|
74
|
+
update = false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const nonOrderableUD_Types: PG_COLUMN_UDT_DATA_TYPE[] = [..._PG_geometric, "xml" as any];
|
|
78
|
+
|
|
79
|
+
const result: ValidatedColumnInfo = {
|
|
80
|
+
...c,
|
|
81
|
+
label,
|
|
82
|
+
tsDataType: postgresToTsType(c.udt_name),
|
|
83
|
+
insert: insert && Boolean(p.insert?.fields?.includes(c.name)) && tableRules?.insert?.forcedData?.[c.name] === undefined && c.is_updatable,
|
|
84
|
+
select: select && Boolean(p.select?.fields?.includes(c.name)),
|
|
85
|
+
orderBy: select && Boolean(p.select?.fields && p.select.orderByFields.includes(c.name)) && !nonOrderableUD_Types.includes(c.udt_name),
|
|
86
|
+
filter: Boolean(p.select?.filterFields?.includes(c.name)),
|
|
87
|
+
update: update && Boolean(p.update?.fields?.includes(c.name)) && tableRules?.update?.forcedData?.[c.name] === undefined && c.is_updatable && dynamicUpdateFields.includes(c.name),
|
|
88
|
+
delete: _delete && Boolean(p.delete && p.delete.filterFields && p.delete.filterFields.includes(c.name)),
|
|
89
|
+
...(prostgles?.tableConfigurator?.getColInfo({ table: this.name, col: c.name, lang }) || {}),
|
|
90
|
+
...(fileConfig && { file: fileConfig })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return result;
|
|
94
|
+
}).filter(c => c.select || c.update || c.delete || c.insert)
|
|
95
|
+
|
|
96
|
+
await this._log({ command: "getColumns", localParams, data: { lang, params }, duration: Date.now() - start });
|
|
97
|
+
return columns;
|
|
98
|
+
|
|
99
|
+
} catch (e) {
|
|
100
|
+
await this._log({ command: "getColumns", localParams, data: { lang, params }, duration: Date.now() - start, error: getErrorAsObject(e) });
|
|
101
|
+
throw getSerializedClientErrorFromPGError(e, { type: "tableMethod", localParams, view: this });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
function replaceNonAlphaNumeric(string: string, replacement = "_"): string {
|
|
109
|
+
return string.replace(/[\W_]+/g, replacement);
|
|
110
|
+
}
|
|
111
|
+
function capitalizeFirstLetter(string: string, nonalpha_replacement?: string) : string {
|
|
112
|
+
const str = replaceNonAlphaNumeric(string, nonalpha_replacement);
|
|
113
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
114
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { pickKeys } from "prostgles-types";
|
|
2
|
+
import { parseFilterItem } from "../Filtering";
|
|
3
|
+
import { TableRule } from "../PublishParser/PublishParser";
|
|
4
|
+
import { ExistsFilterConfig, LocalParams, pgp } from "./DboBuilder";
|
|
5
|
+
import { FUNCTIONS } from "./QueryBuilder/Functions";
|
|
6
|
+
import { SelectItem } from "./QueryBuilder/QueryBuilder";
|
|
7
|
+
import { ViewHandler } from "./ViewHandler/ViewHandler";
|
|
8
|
+
import { getExistsCondition } from "./ViewHandler/getExistsCondition";
|
|
9
|
+
import { getExistsFilters } from "./ViewHandler/getExistsFilters";
|
|
10
|
+
import { parseComplexFilter } from "./ViewHandler/parseComplexFilter";
|
|
11
|
+
|
|
12
|
+
const FILTER_FUNCS = FUNCTIONS.filter(f => f.canBeUsedForFilter);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* parses a single filter
|
|
16
|
+
* @example
|
|
17
|
+
* { fff: 2 } => "fff" = 2
|
|
18
|
+
* { fff: { $ilike: 'abc' } } => "fff" ilike 'abc'
|
|
19
|
+
*/
|
|
20
|
+
export async function getCondition(
|
|
21
|
+
this: ViewHandler,
|
|
22
|
+
params: {
|
|
23
|
+
filter: any,
|
|
24
|
+
select: SelectItem[] | undefined,
|
|
25
|
+
allowed_colnames: string[],
|
|
26
|
+
tableAlias?: string,
|
|
27
|
+
localParams?: LocalParams,
|
|
28
|
+
tableRules?: TableRule,
|
|
29
|
+
isHaving?: boolean,
|
|
30
|
+
},
|
|
31
|
+
): Promise<{ exists: ExistsFilterConfig[]; condition: string }> {
|
|
32
|
+
const { filter: rawFilter, select, allowed_colnames, tableAlias, localParams, tableRules, isHaving } = params;
|
|
33
|
+
|
|
34
|
+
const filter = { ... (rawFilter as any) } as any;
|
|
35
|
+
|
|
36
|
+
const existsConfigs = getExistsFilters(filter, this);
|
|
37
|
+
|
|
38
|
+
const funcConds: string[] = [];
|
|
39
|
+
const funcFilter = FILTER_FUNCS.filter(f => f.name in filter);
|
|
40
|
+
|
|
41
|
+
funcFilter.map(f => {
|
|
42
|
+
const funcArgs = filter[f.name];
|
|
43
|
+
if (!Array.isArray(funcArgs)) {
|
|
44
|
+
throw `A function filter must contain an array. E.g: { $funcFilterName: ["col1"] } \n but got: ${JSON.stringify(pickKeys(filter, [f.name]))} `;
|
|
45
|
+
}
|
|
46
|
+
const fields = this.parseFieldFilter(f.getFields(funcArgs), true, allowed_colnames);
|
|
47
|
+
|
|
48
|
+
const dissallowedCols = fields.filter(fname => !allowed_colnames.includes(fname))
|
|
49
|
+
if (dissallowedCols.length) {
|
|
50
|
+
throw `Invalid/disallowed columns found in function filter: ${dissallowedCols}`
|
|
51
|
+
}
|
|
52
|
+
funcConds.push(f.getQuery({ args: funcArgs, allColumns: this.columns, allowedFields: allowed_colnames, tableAlias }));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
let existsCond = "";
|
|
57
|
+
if (existsConfigs.length) {
|
|
58
|
+
existsCond = (await Promise.all(existsConfigs.map(async existsConfig => await getExistsCondition.bind(this)(existsConfig, localParams)))).join(" AND ");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/* Computed field queries ($rowhash) */
|
|
62
|
+
const p = this.getValidatedRules(tableRules, localParams);
|
|
63
|
+
const computedFields = p.allColumns.filter(c => c.type === "computed");
|
|
64
|
+
const computedColConditions: string[] = [];
|
|
65
|
+
Object.keys(filter || {}).map(key => {
|
|
66
|
+
const compCol = computedFields.find(cf => cf.name === key);
|
|
67
|
+
if (compCol) {
|
|
68
|
+
computedColConditions.push(
|
|
69
|
+
compCol.getQuery({
|
|
70
|
+
tableAlias,
|
|
71
|
+
allowedFields: p.select.fields,
|
|
72
|
+
allColumns: this.columns,
|
|
73
|
+
|
|
74
|
+
/* CTID not available in AFTER trigger */
|
|
75
|
+
// ctidField: this.is_view? undefined : "ctid"
|
|
76
|
+
|
|
77
|
+
ctidField: undefined,
|
|
78
|
+
}) + ` = ${pgp.as.format("$1", [(filter as any)[key]])}`
|
|
79
|
+
);
|
|
80
|
+
delete (filter as any)[key];
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
let allowedSelect: SelectItem[] = [];
|
|
85
|
+
/* Select aliases take precedence over col names. This is to ensure filters work correctly even on computed cols*/
|
|
86
|
+
if (select) {
|
|
87
|
+
/* Allow filtering by selected fields/funcs */
|
|
88
|
+
allowedSelect = select.filter(s => {
|
|
89
|
+
if (["function", "computed", "column"].includes(s.type) || isHaving && s.type === "aggregation") {
|
|
90
|
+
/** Selected computed cols are allowed for filtering without checking. Why not allow all?! */
|
|
91
|
+
if (s.type !== "column" || allowed_colnames.includes(s.alias)) {
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/* Add remaining allowed fields */
|
|
100
|
+
const remainingNonSelectedColumns: SelectItem[] = p.allColumns.filter(c =>
|
|
101
|
+
allowed_colnames.includes(c.name) &&
|
|
102
|
+
!allowedSelect.find(s => s.alias === c.name)
|
|
103
|
+
).map(f => ({
|
|
104
|
+
type: f.type,
|
|
105
|
+
alias: f.name,
|
|
106
|
+
columnName: f.type === "column"? f.name : undefined as any,
|
|
107
|
+
getQuery: (tableAlias) => f.getQuery({
|
|
108
|
+
tableAlias,
|
|
109
|
+
allColumns: this.columns,
|
|
110
|
+
allowedFields: allowed_colnames
|
|
111
|
+
}),
|
|
112
|
+
selected: false,
|
|
113
|
+
getFields: () => [f.name],
|
|
114
|
+
column_udt_type: f.type === "column" ? this.columns.find(c => c.name === f.name)?.udt_name : undefined
|
|
115
|
+
}))
|
|
116
|
+
allowedSelect = allowedSelect.concat(
|
|
117
|
+
remainingNonSelectedColumns
|
|
118
|
+
);
|
|
119
|
+
const complexFilters: string[] = [];
|
|
120
|
+
const complexFilterKey = "$filter";
|
|
121
|
+
if (complexFilterKey in filter) {
|
|
122
|
+
|
|
123
|
+
const complexFilterCondition = parseComplexFilter({
|
|
124
|
+
filter,
|
|
125
|
+
complexFilterKey,
|
|
126
|
+
tableAlias,
|
|
127
|
+
allowed_colnames,
|
|
128
|
+
columns: this.columns,
|
|
129
|
+
});
|
|
130
|
+
complexFilters.push(complexFilterCondition);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/* Parse join filters
|
|
134
|
+
{ $joinFilter: { $ST_DWithin: [table.col, foreignTable.col, distance] }
|
|
135
|
+
will make an exists filter
|
|
136
|
+
*/
|
|
137
|
+
|
|
138
|
+
const filterKeys = Object.keys(filter)
|
|
139
|
+
.filter(k =>
|
|
140
|
+
k !== complexFilterKey &&
|
|
141
|
+
!funcFilter.find(ek => ek.name === k) &&
|
|
142
|
+
!computedFields.find(cf => cf.name === k) &&
|
|
143
|
+
!existsConfigs.find(ek => ek.existType === k)
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const validFieldNames = allowedSelect.map(s => s.alias);
|
|
147
|
+
const invalidColumn = filterKeys
|
|
148
|
+
.find(fName => !validFieldNames.find(c =>
|
|
149
|
+
c === fName ||
|
|
150
|
+
(
|
|
151
|
+
fName.startsWith(c) && (
|
|
152
|
+
fName.slice(c.length).includes("->") ||
|
|
153
|
+
fName.slice(c.length).includes(".")
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
));
|
|
157
|
+
|
|
158
|
+
if (invalidColumn) {
|
|
159
|
+
const selItem = select?.find(s => s.alias === invalidColumn);
|
|
160
|
+
let isComplexFilter = false;
|
|
161
|
+
if(selItem?.type === "aggregation"){
|
|
162
|
+
if(!params.isHaving){
|
|
163
|
+
throw new Error(`Filtering by ${invalidColumn} is not allowed. Aggregations cannot be filtered. Use HAVING clause instead.`);
|
|
164
|
+
} else {
|
|
165
|
+
isComplexFilter = true;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if(!isComplexFilter){
|
|
170
|
+
const allowedCols = allowedSelect.map(s => s.type === "column" ? s.getQuery() : s.alias).join(", ");
|
|
171
|
+
const errMessage = `Table: ${this.name} -> disallowed/inexistent columns in filter: ${invalidColumn} \n Expecting one of: ${allowedCols}`;
|
|
172
|
+
throw errMessage;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/* TODO: Allow filter funcs */
|
|
177
|
+
// see isComplexFilter above where they are allowed
|
|
178
|
+
// const singleFuncs = FUNCTIONS.filter(f => f.singleColArg);
|
|
179
|
+
|
|
180
|
+
const f = pickKeys(filter, filterKeys);
|
|
181
|
+
const q = parseFilterItem({
|
|
182
|
+
filter: f,
|
|
183
|
+
tableAlias,
|
|
184
|
+
select: allowedSelect,
|
|
185
|
+
allowedColumnNames: !tableRules? this.column_names.slice(0) : this.parseFieldFilter(tableRules.select?.filterFields ?? tableRules.select?.fields),
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
let templates: string[] = [q].filter(q => q);
|
|
189
|
+
|
|
190
|
+
if (existsCond) templates.push(existsCond);
|
|
191
|
+
templates = templates.concat(funcConds);
|
|
192
|
+
templates = templates.concat(computedColConditions);
|
|
193
|
+
templates = templates.concat(complexFilters);
|
|
194
|
+
|
|
195
|
+
/* sorted to ensure duplicate subscription channels are not created due to different condition order */
|
|
196
|
+
return {
|
|
197
|
+
exists: existsConfigs,
|
|
198
|
+
condition: templates.sort().join(" AND \n")
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
}
|