prostgles-server 4.2.485 → 4.2.487

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 (25) hide show
  1. package/dist/DboBuilder/TableHandler/insert/getInsertTableRules.d.ts +5 -0
  2. package/dist/DboBuilder/TableHandler/insert/getInsertTableRules.d.ts.map +1 -0
  3. package/dist/DboBuilder/TableHandler/insert/getInsertTableRules.js +16 -0
  4. package/dist/DboBuilder/TableHandler/insert/getInsertTableRules.js.map +1 -0
  5. package/dist/DboBuilder/TableHandler/insert/getReferenceColumnInserts.d.ts +18 -0
  6. package/dist/DboBuilder/TableHandler/insert/getReferenceColumnInserts.d.ts.map +1 -0
  7. package/dist/DboBuilder/TableHandler/insert/getReferenceColumnInserts.js +45 -0
  8. package/dist/DboBuilder/TableHandler/insert/getReferenceColumnInserts.js.map +1 -0
  9. package/dist/DboBuilder/TableHandler/insert/insertNestedRecords.d.ts +0 -18
  10. package/dist/DboBuilder/TableHandler/insert/insertNestedRecords.d.ts.map +1 -1
  11. package/dist/DboBuilder/TableHandler/insert/insertNestedRecords.js +33 -251
  12. package/dist/DboBuilder/TableHandler/insert/insertNestedRecords.js.map +1 -1
  13. package/dist/DboBuilder/TableHandler/insert/insertRowWithNestedRecords.d.ts +23 -0
  14. package/dist/DboBuilder/TableHandler/insert/insertRowWithNestedRecords.d.ts.map +1 -0
  15. package/dist/DboBuilder/TableHandler/insert/insertRowWithNestedRecords.js +195 -0
  16. package/dist/DboBuilder/TableHandler/insert/insertRowWithNestedRecords.js.map +1 -0
  17. package/dist/DboBuilder/TableHandler/update.d.ts.map +1 -1
  18. package/dist/DboBuilder/TableHandler/update.js +4 -3
  19. package/dist/DboBuilder/TableHandler/update.js.map +1 -1
  20. package/lib/DboBuilder/TableHandler/insert/getInsertTableRules.ts +23 -0
  21. package/lib/DboBuilder/TableHandler/insert/getReferenceColumnInserts.ts +64 -0
  22. package/lib/DboBuilder/TableHandler/insert/insertNestedRecords.ts +39 -396
  23. package/lib/DboBuilder/TableHandler/insert/insertRowWithNestedRecords.ts +310 -0
  24. package/lib/DboBuilder/TableHandler/update.ts +2 -1
  25. package/package.json +9 -9
@@ -0,0 +1,310 @@
1
+ import type { AnyObject, InsertParams } from "prostgles-types";
2
+ import { isObject, omitKeys } from "prostgles-types";
3
+ import type { ParsedTableRule } from "../../../PublishParser/PublishParser";
4
+ import type { LocalParams, TableHandlers } from "../../DboBuilder";
5
+ import type { TableHandler } from "../TableHandler";
6
+ import type { ReferenceColumnInsert } from "./getReferenceColumnInserts";
7
+ import { getInsertTableRules } from "./getInsertTableRules";
8
+
9
+ type InsertNestedRecordsArgs = {
10
+ data: AnyObject | AnyObject[];
11
+ insertParams?: InsertParams;
12
+ tableRules: ParsedTableRule | undefined;
13
+ localParams: LocalParams | undefined;
14
+ };
15
+
16
+ /**
17
+ * Referenced inserts within a single transaction
18
+ */
19
+ export async function insertRowWithNestedRecords(
20
+ this: TableHandler,
21
+ {
22
+ row,
23
+ extraKeys,
24
+ colInserts,
25
+ dbTX,
26
+ rootOnConflict,
27
+ }: {
28
+ row: AnyObject;
29
+ extraKeys: string[];
30
+ colInserts: ReferenceColumnInsert<boolean>[];
31
+ dbTX: TableHandlers;
32
+ rootOnConflict: "DoNothing" | "DoUpdate" | undefined;
33
+ },
34
+ { insertParams, tableRules, localParams }: Omit<InsertNestedRecordsArgs, "data">,
35
+ ) {
36
+ /* Ensure we're using the same transaction */
37
+ const tableHandler = this.tx ? this : (dbTX[this.name] as TableHandler);
38
+
39
+ const omitedKeys = extraKeys.concat(colInserts.map((c) => c.insertedFieldName));
40
+
41
+ const rootData: AnyObject = omitKeys(row, omitedKeys);
42
+
43
+ let insertedChildren: AnyObject[];
44
+ let targetTableRules: ParsedTableRule;
45
+
46
+ const colInsertsResult = colInserts.map((ci) => ({
47
+ ...ci,
48
+ inserted: undefined as AnyObject[] | undefined,
49
+ }));
50
+
51
+ /** Insert referenced first and then populate root data with referenced keys */
52
+ for (const colInsert of colInsertsResult) {
53
+ const newLocalParams: LocalParams = {
54
+ ...localParams,
55
+ nestedInsert: {
56
+ depth: (localParams?.nestedInsert?.depth ?? 0) + 1,
57
+ previousData: rootData,
58
+ previousTable: this.name,
59
+ referencingColumn: colInsert.insertedFieldName,
60
+ },
61
+ };
62
+ const colRows = await referencedInsert(
63
+ tableHandler,
64
+ dbTX,
65
+ newLocalParams,
66
+ colInsert.tableName,
67
+ row[colInsert.insertedFieldName] as AnyObject | AnyObject[],
68
+ rootOnConflict,
69
+ );
70
+ const [colRow, ...otherColRows] = colRows;
71
+ if (!Array.isArray(colRows) || !colRow || otherColRows.length) {
72
+ const someFcolsAreNullOrUndefined =
73
+ colRow && colInsert.insertedFieldRef.fcols.some((fcol) => colRow[fcol] === undefined);
74
+ throw new Error(
75
+ [
76
+ "Could not do nested column insert: ",
77
+ someFcolsAreNullOrUndefined ?
78
+ "Some fcols values are undefined"
79
+ : "Unexpected return " + JSON.stringify(colRows),
80
+ ].join("\n"),
81
+ );
82
+ }
83
+ colInsert.inserted = colRows;
84
+
85
+ colInsert.insertedFieldRef.fcols.map((fcol, idx) => {
86
+ const col = colInsert.insertedFieldRef.cols[idx];
87
+ if (!col) throw "Invalid column name for colInsert.insertedFieldRef.cols";
88
+ const foreignKey = colRow[fcol] as string | number;
89
+ rootData[col] = foreignKey;
90
+ });
91
+ }
92
+
93
+ const fullRootResult = (await tableHandler.insert(
94
+ rootData,
95
+ { returning: "*", onConflict: insertParams?.onConflict },
96
+ undefined,
97
+ /** Remove requiredNestedInserts check before doing the actual insert */
98
+ tableRules?.insert?.requiredNestedInserts ?
99
+ {
100
+ ...tableRules,
101
+ insert: {
102
+ ...tableRules.insert,
103
+ requiredNestedInserts: tableRules.insert.requiredNestedInserts.filter(
104
+ ({ ftable }) => !extraKeys.includes(ftable),
105
+ ),
106
+ },
107
+ }
108
+ : tableRules,
109
+ localParams,
110
+ )) as AnyObject;
111
+ let returnData: AnyObject | undefined;
112
+ const returning = insertParams?.returning;
113
+ if (returning) {
114
+ returnData = {};
115
+ const returningItems = await this.prepareReturning(
116
+ returning,
117
+ this.parseFieldFilter(tableRules?.insert?.returningFields),
118
+ );
119
+ returningItems
120
+ .filter((s) => s.selected)
121
+ .map((rs) => {
122
+ const colInsertResult = colInsertsResult.find(
123
+ ({ insertedFieldName }) => insertedFieldName === rs.columnName,
124
+ );
125
+ const inserted =
126
+ colInsertResult?.singleInsert ? colInsertResult.inserted?.[0] : colInsertResult?.inserted;
127
+ returnData![rs.alias] = inserted ?? fullRootResult[rs.alias];
128
+ });
129
+ }
130
+
131
+ for (const targetTable of extraKeys) {
132
+ const childDataItems = (
133
+ Array.isArray(row[targetTable]) ?
134
+ row[targetTable]
135
+ : [row[targetTable]]) as AnyObject[];
136
+
137
+ /** check */
138
+ if (childDataItems.some((d) => !isObject(d))) {
139
+ throw "Expected array of objects";
140
+ }
141
+
142
+ const childInsert = async (cdata: AnyObject | AnyObject[], tableName: string) => {
143
+ return referencedInsert(this, dbTX, localParams, tableName, cdata, rootOnConflict);
144
+ };
145
+
146
+ const joinPath = getJoinPath(this, targetTable);
147
+
148
+ const { path } = joinPath;
149
+ const [tbl1, tbl2, tbl3] = path;
150
+ targetTableRules = await getInsertTableRules(
151
+ this,
152
+ targetTable,
153
+ localParams?.clientReq,
154
+ localParams?.scope,
155
+ );
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) =>
160
+ c.references?.some((rc) => rc.cols.length === 1 && rc.ftable === tbl1),
161
+ );
162
+
163
+ if (!path.length) {
164
+ throw "Nested inserts join path not found for " + [this.name, targetTable].join(", ");
165
+ } else if (path.length === 2) {
166
+ if (targetTable !== tbl2) throw "Did not expect this";
167
+
168
+ if (!colsRefT1.length) {
169
+ throw `Target table ${tbl2} does not reference any columns from the root table ${this.name}. Cannot insert nested data`;
170
+ }
171
+
172
+ insertedChildren = await childInsert(
173
+ childDataItems.map((d) => {
174
+ const result = { ...d };
175
+ colsRefT1.map((col) => {
176
+ result[col.references![0]!.cols[0]!] = fullRootResult[col.references![0]!.fcols[0]!];
177
+ });
178
+ return result;
179
+ }),
180
+ targetTable,
181
+ );
182
+ } else if (path.length === 3) {
183
+ if (targetTable !== tbl3) throw "Did not expect this";
184
+ const colsRefT3 = cols2.filter((c) =>
185
+ c.references?.some((rc) => rc.cols.length === 1 && rc.ftable === tbl3),
186
+ );
187
+ if (!colsRefT1.length || !colsRefT3.length)
188
+ throw "Incorrectly referenced or missing columns for nested insert";
189
+
190
+ const fileTable = this.dboBuilder.prostgles.fileManager?.tableName;
191
+ if (targetTable !== fileTable) {
192
+ throw "Only media allowed to have nested inserts more than 2 tables apart";
193
+ }
194
+
195
+ /* We expect tbl2 to have only 2 columns (media_id and foreign_id) */
196
+ if (
197
+ !(
198
+ cols2.filter((c) => c.references?.[0]?.ftable === fileTable).length === 1 &&
199
+ cols2.filter((c) => c.references?.[0]?.ftable === tableHandler.name).length === 1
200
+ )
201
+ ) {
202
+ console.log({
203
+ tbl1,
204
+ tbl2,
205
+ tbl3,
206
+ name: tableHandler.name,
207
+ tthisName: this.name,
208
+ });
209
+ throw (
210
+ "Second joining table (" +
211
+ tbl2 +
212
+ ") not of expected format. Must contain exactly one reference column for each table (file table and target table) "
213
+ );
214
+ }
215
+
216
+ insertedChildren = await childInsert(childDataItems, targetTable);
217
+
218
+ /* Insert in key_lookup table */
219
+ for (const t3Child of insertedChildren) {
220
+ const tbl2Row: AnyObject = {};
221
+
222
+ colsRefT3.map((col) => {
223
+ tbl2Row[col.name] = t3Child[col.references![0]!.fcols[0]!];
224
+ });
225
+ colsRefT1.map((col) => {
226
+ tbl2Row[col.name] = fullRootResult[col.references![0]!.fcols[0]!];
227
+ });
228
+
229
+ await childInsert(tbl2Row, tbl2!);
230
+ }
231
+ } else {
232
+ console.error(JSON.stringify({ path, thisTable: this.name, targetTable }, null, 2));
233
+ throw "Unexpected path for Nested inserts";
234
+ }
235
+
236
+ /* Return also the nested inserted data */
237
+ if (insertedChildren.length && returning) {
238
+ const targetTableHandler = dbTX[targetTable] as TableHandler;
239
+ const targetReturning = await targetTableHandler.prepareReturning(
240
+ "*",
241
+ targetTableHandler.parseFieldFilter(targetTableRules.insert?.returningFields),
242
+ );
243
+ const clientTargetInserts = insertedChildren.map((d) => {
244
+ const _d = { ...d };
245
+ const res: AnyObject = {};
246
+ targetReturning.map((r) => {
247
+ res[r.alias] = _d[r.alias];
248
+ });
249
+ return res;
250
+ });
251
+
252
+ returnData![targetTable] =
253
+ clientTargetInserts.length === 1 ? clientTargetInserts[0] : clientTargetInserts;
254
+ }
255
+ }
256
+
257
+ return returnData;
258
+ }
259
+
260
+ const getJoinPath = (
261
+ tableHandler: TableHandler,
262
+ targetTable: string,
263
+ ): {
264
+ t1: string;
265
+ t2: string;
266
+ path: string[];
267
+ } => {
268
+ const jp = tableHandler.dboBuilder.getShortestJoinPath(tableHandler, targetTable);
269
+ if (!jp) {
270
+ const pref =
271
+ tableHandler.dboBuilder.prostgles.opts.joins !== "inferred" ? "Joins are not inferred! " : "";
272
+ throw new Error(
273
+ `${pref}Could not find a single join path for the nested data ( sourceTable: ${tableHandler.name} targetTable: ${targetTable} ) `,
274
+ );
275
+ }
276
+ return jp;
277
+ };
278
+
279
+ const referencedInsert = async (
280
+ tableHandler: TableHandler,
281
+ dbTX: TableHandlers | undefined,
282
+ localParams: LocalParams | undefined,
283
+ targetTable: string,
284
+ targetData: AnyObject | AnyObject[],
285
+ onConflict: Extract<InsertParams["onConflict"], string> | undefined,
286
+ ): Promise<AnyObject[]> => {
287
+ getJoinPath(tableHandler, targetTable);
288
+
289
+ if (!dbTX?.[targetTable] || !("insert" in dbTX[targetTable])) {
290
+ throw new Error("childInsertErr: Table handler missing for referenced table: " + targetTable);
291
+ }
292
+
293
+ const childRules = await getInsertTableRules(
294
+ tableHandler,
295
+ targetTable,
296
+ localParams?.clientReq,
297
+ localParams?.scope,
298
+ );
299
+
300
+ const results: AnyObject[] = [];
301
+ for (const dataItem of (Array.isArray(targetData) ? targetData : [targetData]) as AnyObject[]) {
302
+ const result: AnyObject = await (dbTX[targetTable] as TableHandler)
303
+ .insert(dataItem, { returning: "*", onConflict }, undefined, childRules, localParams)
304
+ .catch((e) => {
305
+ return Promise.reject(e);
306
+ });
307
+ results.push(result);
308
+ }
309
+ return results;
310
+ };
@@ -3,10 +3,11 @@ import type { ParsedTableRule } from "../../PublishParser/PublishParser";
3
3
  import type { Filter, LocalParams } from "../DboBuilder";
4
4
  import { getErrorAsObject, getSerializedClientErrorFromPGError, withUserRLS } from "../DboBuilder";
5
5
  import { prepareNewData } from "./DataValidator";
6
- import { getInsertTableRules, getReferenceColumnInserts } from "./insert/insertNestedRecords";
6
+ import { getReferenceColumnInserts } from "./insert/getReferenceColumnInserts";
7
7
  import { runInsertUpdateQuery } from "./runInsertUpdateQuery";
8
8
  import type { TableHandler } from "./TableHandler";
9
9
  import { updateFile } from "./updateFile";
10
+ import { getInsertTableRules } from "./insert/getInsertTableRules";
10
11
 
11
12
  export async function update(
12
13
  this: TableHandler,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prostgles-server",
3
- "version": "4.2.485",
3
+ "version": "4.2.487",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -38,8 +38,8 @@
38
38
  ],
39
39
  "homepage": "https://prostgles.com",
40
40
  "dependencies": {
41
- "@aws-sdk/client-ses": "^3.1000.0",
42
- "@aws-sdk/credential-provider-node": "^3.972.14",
41
+ "@aws-sdk/client-ses": "^3.1011.0",
42
+ "@aws-sdk/credential-provider-node": "^3.972.21",
43
43
  "@types/passport": "^1.0.17",
44
44
  "@types/passport-facebook": "^3.0.4",
45
45
  "@types/passport-github2": "^1.2.9",
@@ -55,24 +55,24 @@
55
55
  "passport-microsoft": "^2.1.0",
56
56
  "passport-oauth2": "^1.8.0",
57
57
  "pg": "^8.19.0",
58
- "pg-cursor": "^2.18.0",
59
- "pg-promise": "^12.6.1",
60
- "prostgles-types": "^4.0.212"
58
+ "pg-cursor": "^2.19.0",
59
+ "pg-promise": "^12.6.2",
60
+ "prostgles-types": "^4.0.213"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@eslint/js": "^9.22.0",
64
64
  "@types/express": "^4.17.25",
65
65
  "@types/json-schema": "^7.0.15",
66
- "@types/node": "^22.19.13",
66
+ "@types/node": "^22.19.15",
67
67
  "@types/nodemailer": "^6.4.23",
68
68
  "@types/pg": "^8.18.0",
69
69
  "@types/pg-cursor": "^2.7.2",
70
70
  "@types/sharp": "^0.30.5",
71
- "eslint": "^9.39.3",
71
+ "eslint": "^9.39.4",
72
72
  "eslint-plugin-security": "^3.0.1",
73
73
  "prettier": "^3.8.1",
74
74
  "socket.io": "^4.8.3",
75
75
  "typescript": "^5.9.3",
76
- "typescript-eslint": "^8.56.1"
76
+ "typescript-eslint": "^8.57.1"
77
77
  }
78
78
  }