prostgles-server 4.2.157 → 4.2.159

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 (159) hide show
  1. package/dist/Auth/AuthHandler.js +2 -2
  2. package/dist/Auth/AuthHandler.js.map +1 -1
  3. package/dist/Auth/AuthTypes.d.ts +4 -8
  4. package/dist/Auth/AuthTypes.d.ts.map +1 -1
  5. package/dist/Auth/setAuthProviders.d.ts +1 -1
  6. package/dist/Auth/setAuthProviders.d.ts.map +1 -1
  7. package/dist/Auth/setAuthProviders.js +6 -7
  8. package/dist/Auth/setAuthProviders.js.map +1 -1
  9. package/dist/Auth/setEmailProvider.d.ts +1 -1
  10. package/dist/Auth/setEmailProvider.d.ts.map +1 -1
  11. package/dist/Auth/setEmailProvider.js +22 -2
  12. package/dist/Auth/setEmailProvider.js.map +1 -1
  13. package/dist/Auth/setupAuthRoutes.js +1 -1
  14. package/dist/Auth/setupAuthRoutes.js.map +1 -1
  15. package/dist/Prostgles.d.ts +1 -0
  16. package/dist/Prostgles.d.ts.map +1 -1
  17. package/dist/Prostgles.js +6 -0
  18. package/dist/Prostgles.js.map +1 -1
  19. package/dist/initProstgles.d.ts.map +1 -1
  20. package/dist/initProstgles.js +2 -6
  21. package/dist/initProstgles.js.map +1 -1
  22. package/package.json +1 -1
  23. package/lib/Auth/AuthHandler.ts +0 -436
  24. package/lib/Auth/AuthTypes.ts +0 -285
  25. package/lib/Auth/getSafeReturnURL.ts +0 -35
  26. package/lib/Auth/sendEmail.ts +0 -83
  27. package/lib/Auth/setAuthProviders.ts +0 -129
  28. package/lib/Auth/setEmailProvider.ts +0 -63
  29. package/lib/Auth/setupAuthRoutes.ts +0 -161
  30. package/lib/DBEventsManager.ts +0 -178
  31. package/lib/DBSchemaBuilder.ts +0 -225
  32. package/lib/DboBuilder/DboBuilder.ts +0 -319
  33. package/lib/DboBuilder/DboBuilderTypes.ts +0 -361
  34. package/lib/DboBuilder/QueryBuilder/Functions.ts +0 -1153
  35. package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +0 -288
  36. package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +0 -263
  37. package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +0 -271
  38. package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +0 -136
  39. package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +0 -22
  40. package/lib/DboBuilder/QueryStreamer.ts +0 -250
  41. package/lib/DboBuilder/TableHandler/DataValidator.ts +0 -428
  42. package/lib/DboBuilder/TableHandler/TableHandler.ts +0 -205
  43. package/lib/DboBuilder/TableHandler/delete.ts +0 -115
  44. package/lib/DboBuilder/TableHandler/insert.ts +0 -183
  45. package/lib/DboBuilder/TableHandler/insertTest.ts +0 -78
  46. package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +0 -62
  47. package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +0 -134
  48. package/lib/DboBuilder/TableHandler/update.ts +0 -126
  49. package/lib/DboBuilder/TableHandler/updateBatch.ts +0 -49
  50. package/lib/DboBuilder/TableHandler/updateFile.ts +0 -48
  51. package/lib/DboBuilder/TableHandler/upsert.ts +0 -34
  52. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +0 -393
  53. package/lib/DboBuilder/ViewHandler/count.ts +0 -38
  54. package/lib/DboBuilder/ViewHandler/find.ts +0 -153
  55. package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +0 -73
  56. package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +0 -74
  57. package/lib/DboBuilder/ViewHandler/getInfo.ts +0 -32
  58. package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +0 -84
  59. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +0 -96
  60. package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +0 -105
  61. package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +0 -208
  62. package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +0 -163
  63. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +0 -90
  64. package/lib/DboBuilder/ViewHandler/size.ts +0 -37
  65. package/lib/DboBuilder/ViewHandler/subscribe.ts +0 -118
  66. package/lib/DboBuilder/ViewHandler/validateViewRules.ts +0 -70
  67. package/lib/DboBuilder/dboBuilderUtils.ts +0 -222
  68. package/lib/DboBuilder/getColumns.ts +0 -114
  69. package/lib/DboBuilder/getCondition.ts +0 -201
  70. package/lib/DboBuilder/getSubscribeRelatedTables.ts +0 -190
  71. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +0 -426
  72. package/lib/DboBuilder/insertNestedRecords.ts +0 -355
  73. package/lib/DboBuilder/parseUpdateRules.ts +0 -187
  74. package/lib/DboBuilder/prepareShortestJoinPaths.ts +0 -186
  75. package/lib/DboBuilder/runSQL.ts +0 -182
  76. package/lib/DboBuilder/runTransaction.ts +0 -50
  77. package/lib/DboBuilder/sqlErrCodeToMsg.ts +0 -254
  78. package/lib/DboBuilder/uploadFile.ts +0 -69
  79. package/lib/Event_Trigger_Tags.ts +0 -118
  80. package/lib/FileManager/FileManager.ts +0 -358
  81. package/lib/FileManager/getValidatedFileType.ts +0 -69
  82. package/lib/FileManager/initFileManager.ts +0 -187
  83. package/lib/FileManager/upload.ts +0 -62
  84. package/lib/FileManager/uploadStream.ts +0 -79
  85. package/lib/Filtering.ts +0 -463
  86. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +0 -502
  87. package/lib/JSONBValidation/validation.ts +0 -143
  88. package/lib/Logging.ts +0 -127
  89. package/lib/PostgresNotifListenManager.ts +0 -143
  90. package/lib/Prostgles.ts +0 -479
  91. package/lib/ProstglesTypes.ts +0 -196
  92. package/lib/PubSubManager/PubSubManager.ts +0 -609
  93. package/lib/PubSubManager/addSub.ts +0 -138
  94. package/lib/PubSubManager/addSync.ts +0 -141
  95. package/lib/PubSubManager/getCreatePubSubManagerError.ts +0 -72
  96. package/lib/PubSubManager/getPubSubManagerInitQuery.ts +0 -662
  97. package/lib/PubSubManager/initPubSubManager.ts +0 -79
  98. package/lib/PubSubManager/notifListener.ts +0 -173
  99. package/lib/PubSubManager/orphanTriggerCheck.ts +0 -70
  100. package/lib/PubSubManager/pushSubData.ts +0 -55
  101. package/lib/PublishParser/PublishParser.ts +0 -162
  102. package/lib/PublishParser/getFileTableRules.ts +0 -124
  103. package/lib/PublishParser/getSchemaFromPublish.ts +0 -141
  104. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +0 -177
  105. package/lib/PublishParser/publishTypesAndUtils.ts +0 -399
  106. package/lib/RestApi.ts +0 -127
  107. package/lib/SchemaWatch/SchemaWatch.ts +0 -90
  108. package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +0 -3
  109. package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +0 -45
  110. package/lib/SchemaWatch/getWatchSchemaTagList.ts +0 -27
  111. package/lib/SyncReplication.ts +0 -557
  112. package/lib/TableConfig/TableConfig.ts +0 -468
  113. package/lib/TableConfig/getColumnDefinitionQuery.ts +0 -111
  114. package/lib/TableConfig/getConstraintDefinitionQueries.ts +0 -95
  115. package/lib/TableConfig/getFutureTableSchema.ts +0 -64
  116. package/lib/TableConfig/getPGIndexes.ts +0 -53
  117. package/lib/TableConfig/getTableColumnQueries.ts +0 -129
  118. package/lib/TableConfig/initTableConfig.ts +0 -326
  119. package/lib/index.ts +0 -13
  120. package/lib/initProstgles.ts +0 -322
  121. package/lib/onSocketConnected.ts +0 -102
  122. package/lib/runClientRequest.ts +0 -129
  123. package/lib/shortestPath.ts +0 -122
  124. package/lib/typeTests/DBoGenerated.d.ts +0 -320
  125. package/lib/typeTests/dboTypeCheck.ts +0 -81
  126. package/lib/utils.ts +0 -15
  127. package/tests/client/hooks.spec.ts +0 -205
  128. package/tests/client/index.ts +0 -139
  129. package/tests/client/package-lock.json +0 -637
  130. package/tests/client/package.json +0 -26
  131. package/tests/client/renderReactHook.ts +0 -177
  132. package/tests/client/tsconfig.json +0 -15
  133. package/tests/client/useProstgles.spec.ts +0 -120
  134. package/tests/clientFileTests.spec.ts +0 -102
  135. package/tests/clientOnlyQueries.spec.ts +0 -667
  136. package/tests/clientRestApi.spec.ts +0 -82
  137. package/tests/config_test/DBoGenerated.d.ts +0 -407
  138. package/tests/config_test/index.html +0 -109
  139. package/tests/config_test/index.js +0 -86
  140. package/tests/config_test/index.js.map +0 -1
  141. package/tests/config_test/index.ts +0 -91
  142. package/tests/config_test/init.sql +0 -48
  143. package/tests/config_test/package.json +0 -29
  144. package/tests/config_test/tsconfig.json +0 -23
  145. package/tests/config_testDBoGenerated.d.ts +0 -407
  146. package/tests/isomorphicQueries.spec.ts +0 -1493
  147. package/tests/server/DBoGenerated.d.ts +0 -537
  148. package/tests/server/index.html +0 -73
  149. package/tests/server/index.ts +0 -289
  150. package/tests/server/init.sql +0 -224
  151. package/tests/server/package-lock.json +0 -2164
  152. package/tests/server/package.json +0 -25
  153. package/tests/server/publishTypeCheck.ts +0 -136
  154. package/tests/server/server.ts +0 -35
  155. package/tests/server/testPublish.ts +0 -147
  156. package/tests/server/testTableConfig.ts +0 -156
  157. package/tests/server/tsconfig.json +0 -22
  158. package/tests/serverOnlyQueries.spec.ts +0 -32
  159. package/tests/test.sh +0 -20
@@ -1,222 +0,0 @@
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
- }
@@ -1,114 +0,0 @@
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
- }
@@ -1,201 +0,0 @@
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
- }