prostgles-server 4.2.158 → 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 (145) hide show
  1. package/dist/Auth/AuthTypes.d.ts +4 -8
  2. package/dist/Auth/AuthTypes.d.ts.map +1 -1
  3. package/dist/Auth/setAuthProviders.d.ts.map +1 -1
  4. package/dist/Auth/setAuthProviders.js +4 -5
  5. package/dist/Auth/setAuthProviders.js.map +1 -1
  6. package/dist/Auth/setEmailProvider.js +1 -1
  7. package/dist/Auth/setEmailProvider.js.map +1 -1
  8. package/package.json +1 -1
  9. package/lib/Auth/AuthHandler.ts +0 -436
  10. package/lib/Auth/AuthTypes.ts +0 -285
  11. package/lib/Auth/getSafeReturnURL.ts +0 -35
  12. package/lib/Auth/sendEmail.ts +0 -83
  13. package/lib/Auth/setAuthProviders.ts +0 -129
  14. package/lib/Auth/setEmailProvider.ts +0 -85
  15. package/lib/Auth/setupAuthRoutes.ts +0 -161
  16. package/lib/DBEventsManager.ts +0 -178
  17. package/lib/DBSchemaBuilder.ts +0 -225
  18. package/lib/DboBuilder/DboBuilder.ts +0 -319
  19. package/lib/DboBuilder/DboBuilderTypes.ts +0 -361
  20. package/lib/DboBuilder/QueryBuilder/Functions.ts +0 -1153
  21. package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +0 -288
  22. package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +0 -263
  23. package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +0 -271
  24. package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +0 -136
  25. package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +0 -22
  26. package/lib/DboBuilder/QueryStreamer.ts +0 -250
  27. package/lib/DboBuilder/TableHandler/DataValidator.ts +0 -428
  28. package/lib/DboBuilder/TableHandler/TableHandler.ts +0 -205
  29. package/lib/DboBuilder/TableHandler/delete.ts +0 -115
  30. package/lib/DboBuilder/TableHandler/insert.ts +0 -183
  31. package/lib/DboBuilder/TableHandler/insertTest.ts +0 -78
  32. package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +0 -62
  33. package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +0 -134
  34. package/lib/DboBuilder/TableHandler/update.ts +0 -126
  35. package/lib/DboBuilder/TableHandler/updateBatch.ts +0 -49
  36. package/lib/DboBuilder/TableHandler/updateFile.ts +0 -48
  37. package/lib/DboBuilder/TableHandler/upsert.ts +0 -34
  38. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +0 -393
  39. package/lib/DboBuilder/ViewHandler/count.ts +0 -38
  40. package/lib/DboBuilder/ViewHandler/find.ts +0 -153
  41. package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +0 -73
  42. package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +0 -74
  43. package/lib/DboBuilder/ViewHandler/getInfo.ts +0 -32
  44. package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +0 -84
  45. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +0 -96
  46. package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +0 -105
  47. package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +0 -208
  48. package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +0 -163
  49. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +0 -90
  50. package/lib/DboBuilder/ViewHandler/size.ts +0 -37
  51. package/lib/DboBuilder/ViewHandler/subscribe.ts +0 -118
  52. package/lib/DboBuilder/ViewHandler/validateViewRules.ts +0 -70
  53. package/lib/DboBuilder/dboBuilderUtils.ts +0 -222
  54. package/lib/DboBuilder/getColumns.ts +0 -114
  55. package/lib/DboBuilder/getCondition.ts +0 -201
  56. package/lib/DboBuilder/getSubscribeRelatedTables.ts +0 -190
  57. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +0 -426
  58. package/lib/DboBuilder/insertNestedRecords.ts +0 -355
  59. package/lib/DboBuilder/parseUpdateRules.ts +0 -187
  60. package/lib/DboBuilder/prepareShortestJoinPaths.ts +0 -186
  61. package/lib/DboBuilder/runSQL.ts +0 -182
  62. package/lib/DboBuilder/runTransaction.ts +0 -50
  63. package/lib/DboBuilder/sqlErrCodeToMsg.ts +0 -254
  64. package/lib/DboBuilder/uploadFile.ts +0 -69
  65. package/lib/Event_Trigger_Tags.ts +0 -118
  66. package/lib/FileManager/FileManager.ts +0 -358
  67. package/lib/FileManager/getValidatedFileType.ts +0 -69
  68. package/lib/FileManager/initFileManager.ts +0 -187
  69. package/lib/FileManager/upload.ts +0 -62
  70. package/lib/FileManager/uploadStream.ts +0 -79
  71. package/lib/Filtering.ts +0 -463
  72. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +0 -502
  73. package/lib/JSONBValidation/validation.ts +0 -143
  74. package/lib/Logging.ts +0 -127
  75. package/lib/PostgresNotifListenManager.ts +0 -143
  76. package/lib/Prostgles.ts +0 -485
  77. package/lib/ProstglesTypes.ts +0 -196
  78. package/lib/PubSubManager/PubSubManager.ts +0 -609
  79. package/lib/PubSubManager/addSub.ts +0 -138
  80. package/lib/PubSubManager/addSync.ts +0 -141
  81. package/lib/PubSubManager/getCreatePubSubManagerError.ts +0 -72
  82. package/lib/PubSubManager/getPubSubManagerInitQuery.ts +0 -662
  83. package/lib/PubSubManager/initPubSubManager.ts +0 -79
  84. package/lib/PubSubManager/notifListener.ts +0 -173
  85. package/lib/PubSubManager/orphanTriggerCheck.ts +0 -70
  86. package/lib/PubSubManager/pushSubData.ts +0 -55
  87. package/lib/PublishParser/PublishParser.ts +0 -162
  88. package/lib/PublishParser/getFileTableRules.ts +0 -124
  89. package/lib/PublishParser/getSchemaFromPublish.ts +0 -141
  90. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +0 -177
  91. package/lib/PublishParser/publishTypesAndUtils.ts +0 -399
  92. package/lib/RestApi.ts +0 -127
  93. package/lib/SchemaWatch/SchemaWatch.ts +0 -90
  94. package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +0 -3
  95. package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +0 -45
  96. package/lib/SchemaWatch/getWatchSchemaTagList.ts +0 -27
  97. package/lib/SyncReplication.ts +0 -557
  98. package/lib/TableConfig/TableConfig.ts +0 -468
  99. package/lib/TableConfig/getColumnDefinitionQuery.ts +0 -111
  100. package/lib/TableConfig/getConstraintDefinitionQueries.ts +0 -95
  101. package/lib/TableConfig/getFutureTableSchema.ts +0 -64
  102. package/lib/TableConfig/getPGIndexes.ts +0 -53
  103. package/lib/TableConfig/getTableColumnQueries.ts +0 -129
  104. package/lib/TableConfig/initTableConfig.ts +0 -326
  105. package/lib/index.ts +0 -13
  106. package/lib/initProstgles.ts +0 -319
  107. package/lib/onSocketConnected.ts +0 -102
  108. package/lib/runClientRequest.ts +0 -129
  109. package/lib/shortestPath.ts +0 -122
  110. package/lib/typeTests/DBoGenerated.d.ts +0 -320
  111. package/lib/typeTests/dboTypeCheck.ts +0 -81
  112. package/lib/utils.ts +0 -15
  113. package/tests/client/hooks.spec.ts +0 -205
  114. package/tests/client/index.ts +0 -139
  115. package/tests/client/package-lock.json +0 -637
  116. package/tests/client/package.json +0 -26
  117. package/tests/client/renderReactHook.ts +0 -177
  118. package/tests/client/tsconfig.json +0 -15
  119. package/tests/client/useProstgles.spec.ts +0 -120
  120. package/tests/clientFileTests.spec.ts +0 -102
  121. package/tests/clientOnlyQueries.spec.ts +0 -667
  122. package/tests/clientRestApi.spec.ts +0 -82
  123. package/tests/config_test/DBoGenerated.d.ts +0 -407
  124. package/tests/config_test/index.html +0 -109
  125. package/tests/config_test/index.js +0 -86
  126. package/tests/config_test/index.js.map +0 -1
  127. package/tests/config_test/index.ts +0 -91
  128. package/tests/config_test/init.sql +0 -48
  129. package/tests/config_test/package.json +0 -29
  130. package/tests/config_test/tsconfig.json +0 -23
  131. package/tests/config_testDBoGenerated.d.ts +0 -407
  132. package/tests/isomorphicQueries.spec.ts +0 -1493
  133. package/tests/server/DBoGenerated.d.ts +0 -537
  134. package/tests/server/index.html +0 -73
  135. package/tests/server/index.ts +0 -289
  136. package/tests/server/init.sql +0 -224
  137. package/tests/server/package-lock.json +0 -2164
  138. package/tests/server/package.json +0 -25
  139. package/tests/server/publishTypeCheck.ts +0 -136
  140. package/tests/server/server.ts +0 -35
  141. package/tests/server/testPublish.ts +0 -147
  142. package/tests/server/testTableConfig.ts +0 -156
  143. package/tests/server/tsconfig.json +0 -22
  144. package/tests/serverOnlyQueries.spec.ts +0 -32
  145. package/tests/test.sh +0 -20
@@ -1,355 +0,0 @@
1
- import { AnyObject, getKeys, InsertParams, isDefined, isObject } from "prostgles-types";
2
- import { LocalParams, TableHandlers } from "./DboBuilder";
3
- import { TableRule } from "../PublishParser/PublishParser";
4
- import { omitKeys } from "../PubSubManager/PubSubManager";
5
- import { TableHandler } from "./TableHandler/TableHandler";
6
-
7
- type InsertNestedRecordsArgs = {
8
- data: (AnyObject | AnyObject[]);
9
- param2?: InsertParams;
10
- tableRules?: TableRule;
11
- localParams?: LocalParams;
12
- };
13
-
14
- /**
15
- * Referenced inserts within a single transaction
16
- */
17
- export async function insertNestedRecords(
18
- this: TableHandler,
19
- {
20
- data,
21
- param2,
22
- tableRules,
23
- localParams = {},
24
- }: InsertNestedRecordsArgs
25
- ): Promise<{
26
- data?: AnyObject | AnyObject[];
27
- insertResult?: AnyObject | AnyObject[];
28
- }> {
29
- const MEDIA_COL_NAMES = ["data", "name"];
30
-
31
- const getExtraKeys = (row: AnyObject) => getKeys(row).filter(fieldName => {
32
- /* If media then use file insert columns */
33
- if (this.is_media) {
34
- return !this.column_names.concat(MEDIA_COL_NAMES).includes(fieldName)
35
- } else if (!this.columns.find(c => c.name === fieldName)) {
36
- if (!isObject(row[fieldName]) && !Array.isArray(row[fieldName])) {
37
- throw new Error("Invalid/Dissalowed field in data: " + fieldName)
38
- } else if (!this.dboBuilder.dbo[fieldName]) {
39
- return false;
40
- // throw new Error("Invalid/Dissalowed nested insert table name in data: " + fieldName)
41
- }
42
- return true;
43
- }
44
- return false;
45
- });
46
-
47
-
48
- /**
49
- * True when: nested table data is provided within
50
- * [nestedTable] property key
51
- * OR
52
- * [referencing_column] property key
53
- * If true then will do the full insert within this function
54
- * Nested insert is not allowed for the file table
55
- * */
56
- const isMultiInsert = Array.isArray(data);
57
- const hasNestedInserts = this.is_media ? false : (isMultiInsert ? data : [data]).some(d => getExtraKeys(d).length || getReferenceColumnInserts(this, d).length);
58
-
59
- /**
60
- * Make sure nested insert uses a transaction
61
- */
62
- const dbTX = this.getFinalDBtx(localParams);
63
- const t = localParams?.tx?.t || this.tx?.t;
64
- if (hasNestedInserts && (!dbTX || !t)) {
65
- return {
66
- insertResult: await this.dboBuilder.getTX((dbTX, _t) =>
67
- (dbTX[this.name] as TableHandler).insert(
68
- data,
69
- param2,
70
- undefined,
71
- tableRules,
72
- { tx: { dbTX, t: _t }, ...localParams }
73
- )
74
- )
75
- }
76
- }
77
-
78
-
79
- const _data = await Promise.all((isMultiInsert ? data : [data]).map(async row => {
80
- // const { preValidate, validate } = tableRules?.insert ?? {};
81
- // const { tableConfigurator } = this.dboBuilder.prostgles;
82
- // if(!tableConfigurator) throw "tableConfigurator missing";
83
- // let row = await tableConfigurator.getPreInsertRow(this, { dbx: this.getFinalDbo(localParams), validate, localParams, row: _row })
84
- // if (preValidate) {
85
- // row = await preValidate({ row, dbx: this.tx?.dbTX || this.dboBuilder.dbo, localParams });
86
- // }
87
-
88
- /* Potentially a nested join */
89
- if (hasNestedInserts) {
90
- const extraKeys = getExtraKeys(row);
91
- const colInserts = getReferenceColumnInserts(this, row);
92
-
93
- /* Ensure we're using the same transaction */
94
- const _this = this.tx ? this : dbTX![this.name] as TableHandler;
95
-
96
- const omitedKeys = extraKeys.concat(colInserts.map(c => c.col));
97
-
98
- const rootData: AnyObject = omitKeys(row, omitedKeys);
99
-
100
- let insertedChildren: AnyObject[];
101
- let targetTableRules: TableRule;
102
-
103
- const colInsertsResult = colInserts.map(ci => ({
104
- ...ci,
105
- inserted: undefined as AnyObject[] | undefined
106
- }));
107
- /** Insert referenced first and then populate root data with referenced keys */
108
- if (colInserts.length) {
109
- for await (const colInsert of colInsertsResult) {
110
- const newLocalParams: LocalParams = {
111
- ...(localParams ?? {}),
112
- nestedInsert: {
113
- depth: (localParams.nestedInsert?.depth ?? 0) + 1,
114
- previousData: rootData,
115
- previousTable: this.name,
116
- referencingColumn: colInsert.col
117
- }
118
- }
119
- const colRows = await referencedInsert(_this, dbTX, newLocalParams, colInsert.tableName, row[colInsert.col]);
120
- if (!Array.isArray(colRows) || colRows.length !== 1 || [null, undefined].includes(colRows[0]![colInsert.fcol])) {
121
- throw new Error("Could not do nested column insert: Unexpected return " + JSON.stringify(colRows))
122
- }
123
- colInsert.inserted = colRows;
124
-
125
- const foreignKey = colRows[0]![colInsert.fcol];
126
- rootData[colInsert.col] = foreignKey;
127
- }
128
- }
129
-
130
- const fullRootResult = await _this.insert(rootData, { returning: "*" }, undefined, tableRules, localParams);
131
- let returnData: AnyObject | undefined;
132
- const returning = param2?.returning;
133
- if (returning) {
134
- returnData = {}
135
- const returningItems = await this.prepareReturning(returning, this.parseFieldFilter(tableRules?.insert?.returningFields));
136
- returningItems.filter(s => s.selected).map(rs => {
137
- const colInsertResult = colInsertsResult.find(({ col }) => col === rs.columnName);
138
- const inserted = colInsertResult?.singleInsert? colInsertResult.inserted?.[0] : colInsertResult?.inserted;
139
- returnData![rs.alias] = inserted ?? fullRootResult[rs.alias];
140
- })
141
- }
142
-
143
- await Promise.all(extraKeys.map(async targetTable => {
144
- const childDataItems = Array.isArray(row[targetTable]) ? row[targetTable] : [row[targetTable]];
145
-
146
- const childInsert = async (cdata: AnyObject | AnyObject[], tableName: string) => {
147
-
148
- return referencedInsert(this, dbTX, localParams, tableName, cdata);
149
- }
150
-
151
- const joinPath = await getJoinPath(this, targetTable);
152
-
153
- const { path } = joinPath;
154
- const [tbl1, tbl2, tbl3] = path;
155
- targetTableRules = await getInsertTableRules(this, targetTable, localParams); // tbl3
156
-
157
- const cols2 = this.dboBuilder.dbo[tbl2!]!.columns || [];
158
- if (!this.dboBuilder.dbo[tbl2!]) throw "Invalid/disallowed table: " + tbl2;
159
- const colsRefT1 = cols2?.filter(c => c.references?.some(rc => rc.cols.length === 1 && rc.ftable === tbl1));
160
-
161
-
162
- if (!path.length) {
163
- throw "Nested inserts join path not found for " + [this.name, targetTable];
164
- } else if (path.length === 2) {
165
- if (targetTable !== tbl2) throw "Did not expect this";
166
-
167
- if (!colsRefT1.length) {
168
- throw `Target table ${tbl2} does not reference any columns from the root table ${this.name}. Cannot insert nested data`;
169
- }
170
-
171
- insertedChildren = await childInsert(
172
- childDataItems.map((d: AnyObject) => {
173
- const result = { ...d };
174
- colsRefT1.map(col => {
175
- result[col.references![0]!.cols[0]!] = fullRootResult[col.references![0]!.fcols[0]!]
176
- })
177
- return result;
178
- }),
179
- targetTable
180
- );
181
-
182
- } else if (path.length === 3) {
183
- if (targetTable !== tbl3) throw "Did not expect this";
184
- const colsRefT3 = cols2?.filter(c => c.references?.some(rc => rc.cols.length === 1 && rc.ftable === tbl3));
185
- if (!colsRefT1.length || !colsRefT3.length) throw "Incorrectly referenced or missing columns for nested insert";
186
-
187
- const fileTable = this.dboBuilder.prostgles.fileManager?.tableName;
188
- if (targetTable !== fileTable) {
189
- throw "Only media allowed to have nested inserts more than 2 tables apart"
190
- }
191
-
192
- /* We expect tbl2 to have only 2 columns (media_id and foreign_id) */
193
- if (!cols2 || !(
194
- cols2.filter(c => c.references?.[0]?.ftable === fileTable).length === 1 &&
195
- cols2.filter(c => c.references?.[0]?.ftable === _this.name).length === 1
196
- )) {
197
- console.log({ tbl1, tbl2, tbl3, name: _this.name, tthisName: this.name })
198
- throw "Second joining table (" + tbl2 + ") not of expected format. Must contain exactly one reference column for each table (file table and target table) ";
199
- }
200
-
201
- insertedChildren = await childInsert(childDataItems, targetTable);
202
-
203
- /* Insert in key_lookup table */
204
- await Promise.all(insertedChildren.map(async t3Child => {
205
- const tbl2Row: AnyObject = {};
206
-
207
- colsRefT3.map(col => {
208
- tbl2Row[col.name] = t3Child[col.references![0]!.fcols[0]!];
209
- })
210
- colsRefT1.map(col => {
211
- tbl2Row[col.name] = fullRootResult[col.references![0]!.fcols[0]!];
212
- })
213
-
214
- await childInsert(tbl2Row, tbl2!);//.then(() => {});
215
- }));
216
-
217
- } else {
218
- console.error(JSON.stringify({ path, thisTable: this.name, targetTable }, null, 2));
219
- throw "Unexpected path for Nested inserts";
220
- }
221
-
222
- /* Return also the nested inserted data */
223
- if (targetTableRules && insertedChildren?.length && returning) {
224
- const targetTableHandler = dbTX![targetTable] as TableHandler;
225
- const targetReturning = await targetTableHandler.prepareReturning("*", targetTableHandler.parseFieldFilter(targetTableRules?.insert?.returningFields));
226
- const clientTargetInserts = insertedChildren.map(d => {
227
- const _d = { ...d };
228
- const res: AnyObject = {};
229
- targetReturning.map(r => {
230
- res[r.alias] = _d[r.alias]
231
- });
232
- return res;
233
- });
234
-
235
- returnData![targetTable] = clientTargetInserts.length === 1 ? clientTargetInserts[0] : clientTargetInserts;
236
- }
237
- }));
238
-
239
- return returnData
240
- }
241
-
242
- return row;
243
- }));
244
-
245
- const result = isMultiInsert ? _data : _data[0];
246
- const res = hasNestedInserts ?
247
- { insertResult: result } :
248
- { data: result };
249
-
250
- return res;
251
- }
252
-
253
- /* Must be allowed to insert into referenced table */
254
- export const getInsertTableRules = async (tableHandler: TableHandler, targetTable: string, localParams: LocalParams) => {
255
- const childRules = await tableHandler.dboBuilder.publishParser?.getValidatedRequestRuleWusr({ tableName: targetTable, command: "insert", localParams });
256
- if (!childRules || !childRules.insert) throw "Dissallowed nested insert into table " + childRules;
257
- return childRules;
258
- }
259
-
260
- const getJoinPath = async (tableHandler: TableHandler, targetTable: string): Promise<{
261
- t1: string;
262
- t2: string;
263
- path: string[];
264
- }> => {
265
-
266
- const jp = tableHandler.dboBuilder.getShortestJoinPath(tableHandler, targetTable);
267
- if (!jp) {
268
- const pref = tableHandler.dboBuilder.prostgles.opts.joins !== "inferred" ? "Joins are not inferred! " : ""
269
- throw new Error(`${pref}Could not find a single join path for the nested data ( sourceTable: ${tableHandler.name} targetTable: ${targetTable} ) `);
270
- }
271
- return jp;
272
- }
273
-
274
- const referencedInsert = async (tableHandler: TableHandler, dbTX: TableHandlers | undefined, localParams: LocalParams, targetTable: string, targetData: AnyObject | AnyObject[]): Promise<AnyObject[]> => {
275
-
276
-
277
- // const thisInfo = await tableHandler.getInfo();
278
- await getJoinPath(tableHandler, targetTable);
279
-
280
- if (!targetData || !dbTX?.[targetTable] || !("insert" in dbTX[targetTable]!)) {
281
- throw new Error("childInsertErr: Table handler missing for referenced table: " + targetTable);
282
- }
283
-
284
- const childRules = await getInsertTableRules(tableHandler, targetTable, localParams);
285
-
286
- // if (thisInfo.has_media === "one" && thisInfo.media_table_name === targetTable && Array.isArray(targetData) && targetData.length > 1) {
287
- // throw "Constraint check fail: Cannot insert more than one record into " + JSON.stringify(targetTable);
288
- // }
289
- return Promise.all(
290
- (Array.isArray(targetData) ? targetData : [targetData])
291
- .map(m => (dbTX![targetTable] as TableHandler)
292
- .insert(m, { returning: "*" }, undefined, childRules, localParams)
293
- .catch(e => {
294
- return Promise.reject(e);
295
- })
296
- )
297
- );
298
-
299
- }
300
-
301
- type ReferenceColumnInsert<ExpectSingleInsert> = {
302
- tableName: string;
303
- col: string;
304
- fcol: string;
305
- singleInsert: boolean;
306
- data: ExpectSingleInsert extends true? AnyObject : (AnyObject | AnyObject[]);
307
- }
308
-
309
- /**
310
- * Insert through the reference column. e.g.:
311
- * {
312
- * root_field: "data",
313
- * fkey_column: { ...referenced_table_data }
314
- * }
315
- */
316
- export const getReferenceColumnInserts = <ExpectSingleInsert extends boolean>(tableHandler: TableHandler, parentRow: AnyObject, expectSingleInsert?: ExpectSingleInsert): ReferenceColumnInsert<ExpectSingleInsert>[] => {
317
- return Object.entries(parentRow)
318
- .map(([insertedFieldName, insertedFieldValue]) => {
319
- if(insertedFieldValue && isObject(insertedFieldValue)){
320
- const insertedRefCol = tableHandler.columns.find(c => c.name === insertedFieldName && c.references?.length);
321
- if(!insertedRefCol) return undefined;
322
- return {
323
- insertedRefCol,
324
- insertedRefColRef: insertedRefCol.references!
325
- }
326
- }
327
-
328
- return undefined;
329
- })
330
- .filter(isDefined)
331
- .map(({ insertedRefCol, insertedRefColRef }) => {
332
-
333
- if(insertedRefColRef.length !== 1){
334
- throw "Cannot do a nested insert on column that references multiple tables"
335
- }
336
-
337
- const referencesMultipleColumns = insertedRefColRef?.some(refs => refs.fcols.length !== 1);
338
- if(referencesMultipleColumns){
339
- throw "Cannot do a nested insert on multi-column foreign key reference"
340
- }
341
-
342
- const singleInsert = !Array.isArray(parentRow[insertedRefCol.name]);
343
- if(expectSingleInsert && !singleInsert){
344
- throw "Expected singleInsert";
345
- }
346
- const res = {
347
- tableName: insertedRefCol.references![0]!.ftable!,
348
- col: insertedRefCol.name,
349
- fcol: insertedRefCol.references![0]!.fcols[0]!,
350
- singleInsert,
351
- data: parentRow[insertedRefCol.name],
352
- }
353
- return res;
354
- }).filter(isDefined);
355
- }
@@ -1,187 +0,0 @@
1
- import { AnyObject, FieldFilter, isDefined, UpdateParams } from "prostgles-types";
2
- import { Filter, LocalParams } from "./DboBuilder";
3
- import { TableRule, UpdateRule, ValidateRowBasic, ValidateUpdateRowBasic } from "../PublishParser/PublishParser";
4
- import { TableHandler } from "./TableHandler/TableHandler";
5
- import { prepareNewData } from "./TableHandler/DataValidator";
6
-
7
- /**
8
- * 1) Check if publish is valid
9
- * 2) Retrieve allowed update cols for a specific request
10
- */
11
- export async function parseUpdateRules(
12
- this: TableHandler,
13
- filter: Filter,
14
- params?: UpdateParams,
15
- tableRules?: TableRule,
16
- localParams?: LocalParams
17
- ): Promise<{
18
- fields: string[];
19
- validateRow?: ValidateRowBasic;
20
- finalUpdateFilter: AnyObject;
21
- forcedData?: AnyObject;
22
- forcedFilter?: AnyObject;
23
- returningFields: FieldFilter;
24
- filterFields?: FieldFilter;
25
- }> {
26
- const { testRule = false } = localParams ?? {};
27
- if (!testRule) {
28
- this.checkFilter(filter);
29
- }
30
-
31
- let forcedFilter: AnyObject | undefined = {},
32
- forcedData: AnyObject | undefined = {},
33
- validate: ValidateUpdateRowBasic | undefined,
34
- returningFields: FieldFilter = "*",
35
- filterFields: FieldFilter | undefined = "*",
36
- fields: FieldFilter = "*";
37
-
38
- let finalUpdateFilter = { ...filter };
39
-
40
- if (tableRules) {
41
- if (!tableRules.update) throw "update rules missing for " + this.name;
42
- ({ forcedFilter, forcedData, fields, filterFields, validate } = tableRules.update);
43
-
44
- returningFields = tableRules.update.returningFields ?? tableRules?.select?.fields ?? "";
45
-
46
- if (!returningFields && params?.returning) {
47
- throw "You are not allowed to return any fields from the update"
48
- }
49
-
50
- if (!fields) {
51
- throw ` Invalid update rule fo r ${this.name}. fields missing `;
52
- }
53
- finalUpdateFilter = (await this.prepareWhere({
54
- select: undefined,
55
- filter,
56
- forcedFilter,
57
- filterFields,
58
- localParams,
59
- tableRule: tableRules
60
- })).filter;
61
- if (tableRules.update.dynamicFields?.length) {
62
- /**
63
- * dynamicFields.fields used to allow a custom list of fields for specific records
64
- * dynamicFields.filter cannot overlap each other
65
- * updates must target records from a specific dynamicFields.filter or not match any dynamicFields.filter
66
- */
67
- if (testRule) {
68
- for await (const [dfIndex, dfRule] of tableRules.update.dynamicFields.entries()) {
69
-
70
- /**
71
- * Validated filter and fields
72
- */
73
- const condition = await this.prepareWhere({
74
- select: undefined,
75
- filterFields: this.column_names,
76
- filter: dfRule.filter,
77
- localParams,
78
- tableRule: tableRules
79
- });
80
- if (!condition.where) {
81
- throw "dynamicFields.filter cannot be empty: " + JSON.stringify(dfRule);
82
- }
83
- await this.validateViewRules({
84
- fields: dfRule.fields,
85
- filterFields,
86
- returningFields,
87
- forcedFilter,
88
- dynamicFields: tableRules.update.dynamicFields,
89
- rule: "update"
90
- });
91
-
92
-
93
- await this.find(dfRule.filter, { limit: 0 });
94
-
95
- /** Ensure dynamicFields filters do not overlap */
96
- for await (const [_dfIndex, _dfRule] of tableRules.update.dynamicFields.entries()) {
97
- if (dfIndex !== _dfIndex) {
98
- if (await this.findOne({ $and: [dfRule.filter, _dfRule.filter] }, { select: "" })) {
99
- throw `dynamicFields.filter cannot overlap each other. \n
100
- Overlapping dynamicFields rules:
101
- ${JSON.stringify(dfRule)}
102
- AND
103
- ${JSON.stringify(_dfRule)}
104
- `;
105
- }
106
- }
107
- }
108
- }
109
- }
110
-
111
- /** Pick dynamicFields.fields if matching filter */
112
- let matchedRule: Required<UpdateRule>["dynamicFields"][number] | undefined;
113
- for await (const dfRule of tableRules.update.dynamicFields) {
114
- const match = await this.findOne({ $and: ([finalUpdateFilter, dfRule.filter] as AnyObject[]).filter(isDefined) });
115
-
116
- if (match) {
117
-
118
- /** Ensure it doesn't overlap with other dynamicFields.filter */
119
- if (matchedRule && !testRule) {
120
- throw "Your update is targeting multiple tableRules.update.dynamicFields. Restrict update filter to only target one rule";
121
- }
122
-
123
- matchedRule = dfRule;
124
- fields = dfRule.fields;
125
- }
126
- }
127
- }
128
-
129
- /* Safely test publish rules */
130
- if (testRule) {
131
- await this.validateViewRules({ fields, filterFields, returningFields, forcedFilter, dynamicFields: tableRules.update.dynamicFields, rule: "update" });
132
- if (forcedData) {
133
- try {
134
- const { data, allowedCols } = await prepareNewData({
135
- row: forcedData,
136
- forcedData: undefined,
137
- allowedFields: "*",
138
- tableRules,
139
- fixIssues: false,
140
- tableConfigurator: this.dboBuilder.prostgles.tableConfigurator,
141
- tableHandler: this,
142
- });
143
- let updateValidate: ValidateRowBasic | undefined;
144
- if(validate){
145
- if(!localParams) throw "localParams missing";
146
- updateValidate = (args) => validate!({ update: args.row, filter: {}, dbx: this.getFinalDbo(localParams), localParams })
147
- }
148
- const updateQ = (await this.dataValidator.parse({
149
- command: "update",
150
- rows: [data],
151
- allowedCols,
152
- dbTx: this.tx?.dbTX || this.dboBuilder.dbo,
153
- validationOptions: {
154
- validate: updateValidate,
155
- localParams,
156
- }
157
- })).getQuery();
158
- const query = updateQ + " WHERE FALSE ";
159
- await this.db.any("EXPLAIN " + query);
160
- } catch (e) {
161
- throw " issue with forcedData: \nVALUE: " + JSON.stringify(forcedData, null, 2) + "\nERROR: " + e;
162
- }
163
- }
164
-
165
- return true as unknown as any;
166
- }
167
- }
168
-
169
- /* Update all allowed fields (fields) except the forcedFilter (so that the user cannot change the forced filter values) */
170
- const _fields = this.parseFieldFilter(fields);
171
-
172
- let validateRow: ValidateRowBasic | undefined;
173
- if(validate){
174
- if(!localParams) throw "localParams missing";
175
- validateRow = ({ row }) => validate!({ update: row, filter: finalUpdateFilter, localParams, dbx: this.getFinalDbo(localParams) });
176
- }
177
-
178
- return {
179
- fields: _fields,
180
- validateRow,
181
- finalUpdateFilter,
182
- forcedData,
183
- forcedFilter,
184
- returningFields,
185
- filterFields,
186
- }
187
- }