prostgles-server 4.2.158 → 4.2.160

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 +3 -3
  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,115 +0,0 @@
1
- import pgPromise from "pg-promise";
2
- import { AnyObject, DeleteParams, FieldFilter } from "prostgles-types";
3
- import { DeleteRule, TableRule } from "../../PublishParser/PublishParser";
4
- import { Filter, LocalParams, getErrorAsObject, getSerializedClientErrorFromPGError, withUserRLS } from "../DboBuilder";
5
- import { runQueryReturnType } from "../ViewHandler/find";
6
- import { TableHandler } from "./TableHandler";
7
- import { onDeleteFromFileTable } from "./onDeleteFromFileTable";
8
-
9
- export async function _delete(this: TableHandler, filter?: Filter, params?: DeleteParams, param3_unused?: undefined, tableRules?: TableRule, localParams?: LocalParams): Promise<any> {
10
- const start = Date.now();
11
- try {
12
- const { returning } = params || {};
13
- filter = filter || {};
14
- this.checkFilter(filter);
15
-
16
- let forcedFilter: AnyObject | undefined = {},
17
- filterFields: FieldFilter | undefined = "*",
18
- returningFields: FieldFilter | undefined = "*",
19
- validate: DeleteRule["validate"];
20
-
21
- const { testRule = false, returnQuery = false } = localParams || {};
22
- if (tableRules) {
23
- if (!tableRules.delete) throw "delete rules missing";
24
- forcedFilter = tableRules.delete.forcedFilter;
25
- filterFields = tableRules.delete.filterFields;
26
- returningFields = tableRules.delete.returningFields;
27
- validate = tableRules.delete.validate;
28
-
29
- if (!returningFields) returningFields = tableRules?.select?.fields;
30
- if (!returningFields) returningFields = tableRules?.delete?.filterFields;
31
-
32
- if (!filterFields) throw ` Invalid delete rule for ${this.name}. filterFields missing `;
33
-
34
- /* Safely test publish rules */
35
- if (testRule) {
36
- await this.validateViewRules({ filterFields, returningFields, forcedFilter, rule: "delete" });
37
- return true;
38
- }
39
- }
40
-
41
- if (params) {
42
- const good_paramsObj: Record<keyof DeleteParams, 1> = { returning: 1, returnType: 1 };
43
- const good_params = Object.keys(good_paramsObj);
44
- const bad_params = Object.keys(params).filter(k => !good_params.includes(k));
45
- if (bad_params && bad_params.length) throw "Invalid params: " + bad_params.join(", ") + " \n Expecting: " + good_params.join(", ");
46
- }
47
-
48
- let queryType: keyof pgPromise.ITask<{}> = 'none';
49
- let queryWithoutRLS = `DELETE FROM ${this.escapedName} `;
50
- const filterOpts = (await this.prepareWhere({
51
- select: undefined,
52
- filter,
53
- forcedFilter,
54
- filterFields,
55
- localParams,
56
- tableRule: tableRules
57
- }))
58
- queryWithoutRLS += filterOpts.where;
59
- if (validate) {
60
- const _filter = filterOpts.filter;
61
- await validate(_filter);
62
- }
63
-
64
- let returningQuery = "";
65
- if (returning) {
66
- queryType = "any";
67
- if (!returningFields) {
68
- throw "Returning dissallowed";
69
- }
70
- returningQuery = this.makeReturnQuery(await this.prepareReturning(returning, this.parseFieldFilter(returningFields)));
71
- queryWithoutRLS += returningQuery
72
- }
73
-
74
- // TODO - delete orphaned files
75
- // if(this.dboBuilder.prostgles.opts.fileTable?.referencedTables?.[this.name]?.referenceColumns){
76
- // if(!this.getFinalDBtx(localParams)){
77
- // const ACTION = "delete";
78
- // return this.dboBuilder.getTX(_dbtx => _dbtx[this.name]?.[ACTION]?.(filter, params, param3_unused, tableRules, localParams))
79
- // }
80
- // }
81
-
82
- const queryWithRLS = withUserRLS(localParams, queryWithoutRLS);
83
- if (returnQuery) return queryWithRLS;
84
-
85
- /**
86
- * Delete file
87
- */
88
- if (this.is_media) {
89
- const result = await onDeleteFromFileTable.bind(this)({
90
- localParams,
91
- queryType,
92
- returningQuery: returnQuery? returnQuery : undefined,
93
- filterOpts,
94
- });
95
- await this._log({ command: "delete", localParams, data: { filter, params }, duration: Date.now() - start });
96
- return result;
97
- }
98
-
99
- const result = await runQueryReturnType({
100
- queryWithoutRLS,
101
- queryWithRLS,
102
- newQuery: undefined,
103
- returnType: params?.returnType,
104
- handler: this,
105
- localParams
106
- });
107
- await this._log({ command: "delete", localParams, data: { filter, params }, duration: Date.now() - start });
108
- return result;
109
-
110
- } catch (e) {
111
- await this._log({ command: "delete", localParams, data: { filter, params }, duration: Date.now() - start, error: getErrorAsObject(e) });
112
- throw getSerializedClientErrorFromPGError(e, { type: "tableMethod", localParams, view: this });
113
- }
114
- }
115
-
@@ -1,183 +0,0 @@
1
- import { AnyObject, InsertParams, asName, isObject } from "prostgles-types";
2
- import { TableRule, ValidateRowBasic } from "../../PublishParser/PublishParser";
3
- import { LocalParams, getErrorAsObject, getSerializedClientErrorFromPGError, withUserRLS } from "../DboBuilder";
4
- import { insertNestedRecords } from "../insertNestedRecords";
5
- import { prepareNewData } from "./DataValidator";
6
- import { TableHandler } from "./TableHandler";
7
- import { insertTest } from "./insertTest";
8
- import { runInsertUpdateQuery } from "./runInsertUpdateQuery";
9
-
10
- export async function insert(this: TableHandler, rowOrRows: AnyObject | AnyObject[] = {}, insertParams?: InsertParams, param3_unused?: undefined, tableRules?: TableRule, localParams?: LocalParams): Promise<any | any[] | boolean> {
11
-
12
- const ACTION = "insert";
13
- const start = Date.now();
14
- try {
15
-
16
- const { fixIssues = false } = insertParams || {};
17
- const { returnQuery = false, nestedInsert } = localParams || {};
18
-
19
- const finalDBtx = this.getFinalDBtx(localParams);
20
- const rule = tableRules?.[ACTION];
21
- const { postValidate, checkFilter, validate, allowedNestedInserts } = rule ?? {};
22
-
23
- /** Post validate and checkFilter require a transaction dbo handler because they happen after the insert */
24
- if(postValidate || checkFilter){
25
- if(!finalDBtx){
26
- return this.dboBuilder.getTX(_dbtx => _dbtx[this.name]?.[ACTION]?.(rowOrRows, insertParams, param3_unused, tableRules, localParams))
27
- }
28
- }
29
-
30
- const { testOnly, fields, forcedData, returningFields } = await insertTest.bind(this)({ tableRules, localParams });
31
- if(testOnly){
32
- return true;
33
- }
34
-
35
- if(allowedNestedInserts){
36
- if(!nestedInsert || !allowedNestedInserts.some(ai => ai.table === nestedInsert?.previousTable && ai.column === nestedInsert.referencingColumn)){
37
- throw `Direct inserts not allowed. Only nested inserts from these tables: ${JSON.stringify(allowedNestedInserts)} `
38
- }
39
- }
40
- validateInsertParams(insertParams);
41
-
42
- const isMultiInsert = Array.isArray(rowOrRows);
43
- const preValidatedRows = await Promise.all((isMultiInsert? rowOrRows : [rowOrRows]).map(async nonValidated => {
44
- const { preValidate, validate } = tableRules?.insert ?? {};
45
- const { tableConfigurator } = this.dboBuilder.prostgles;
46
- if(!tableConfigurator) throw "tableConfigurator missing";
47
- let row = await tableConfigurator.getPreInsertRow(this, { dbx: this.getFinalDbo(localParams), validate, localParams, row: nonValidated })
48
- if (preValidate) {
49
- if(!localParams) throw "localParams missing for insert preValidate";
50
- row = await preValidate({ row, dbx: (this.tx?.dbTX || this.dboBuilder.dbo) as any, localParams });
51
- }
52
-
53
- return row;
54
- }));
55
- const preValidatedrowOrRows = isMultiInsert? preValidatedRows : preValidatedRows[0]!;
56
-
57
- /**
58
- * If media it will: upload file and continue insert
59
- * If nested insert it will: make separate inserts and not continue main insert
60
- */
61
- const mediaOrNestedInsert = await insertNestedRecords.bind(this)({ data: preValidatedrowOrRows, param2: insertParams, tableRules, localParams });
62
- const { data, insertResult } = mediaOrNestedInsert;
63
- if ("insertResult" in mediaOrNestedInsert) {
64
- return insertResult;
65
- }
66
-
67
- const pkeyNames = this.columns.filter(c => c.is_pkey).map(c => c.name);
68
- const getInsertQuery = async (_rows: AnyObject[]) => {
69
- const validatedData = await Promise.all(_rows.map(async _row => {
70
-
71
- const row = { ..._row };
72
-
73
- if (!isObject(row)) {
74
- throw "\nInvalid insert data provided. Expected an object but received: " + JSON.stringify(row);
75
- }
76
-
77
- const { data: validatedRow, allowedCols } = await prepareNewData({
78
- row,
79
- forcedData,
80
- allowedFields: fields,
81
- tableRules,
82
- fixIssues,
83
- tableConfigurator: this.dboBuilder.prostgles.tableConfigurator,
84
- tableHandler: this,
85
- });
86
- return { validatedRow, allowedCols };
87
- }));
88
- const validatedRows = validatedData.map(d => d.validatedRow);
89
- const allowedCols = Array.from(new Set(validatedData.flatMap(d => d.allowedCols)));
90
- const dbTx = finalDBtx || this.dboBuilder.dbo;
91
- const validationOptions = { validate: validate as ValidateRowBasic, localParams };
92
- // const query = await this.colSet.getInsertQuery(validatedRows, allowedCols, dbTx, validate, localParams);
93
- const query = (await this.dataValidator.parse({ command: "insert", rows: validatedRows, allowedCols, dbTx, validationOptions })).getQuery();
94
- const { onConflict } = insertParams ?? {};
95
- let conflict_query = "";
96
- if (onConflict === "DoNothing") {
97
- conflict_query = " ON CONFLICT DO NOTHING ";
98
- } else if(onConflict === "DoUpdate"){
99
- if(!pkeyNames.length) {
100
- throw "Cannot do DoUpdate on a table without a primary key";
101
- }
102
- const nonPkeyCols = allowedCols.filter(c => !pkeyNames.includes(c)).map(v => asName(v));
103
- if(!nonPkeyCols.length){
104
- throw "Cannot on conflict DoUpdate on a table with only primary key columns";
105
- }
106
- conflict_query = ` ON CONFLICT (${pkeyNames.join(", ")}) DO UPDATE SET ${nonPkeyCols.map(k => `${k} = EXCLUDED.${k}`).join(", ")}`;
107
- }
108
- return query + conflict_query;
109
- };
110
-
111
- let query = "";
112
- if (Array.isArray(data)) {
113
-
114
- if(!data.length){
115
- throw "Empty insert. Provide data";
116
- }
117
-
118
- query = await getInsertQuery(data);
119
- } else {
120
- query = await getInsertQuery([data ?? {}]);
121
- }
122
-
123
- const queryWithoutUserRLS = query;
124
- const queryWithRLS = withUserRLS(localParams, query);
125
- if (returnQuery) return queryWithRLS;
126
-
127
- if (this.dboBuilder.prostgles.opts.DEBUG_MODE) {
128
- console.log(this.tx?.t.ctx?.start, "insert in " + this.name, data);
129
- }
130
-
131
- const result = await runInsertUpdateQuery({
132
- rule,
133
- localParams,
134
- queryWithoutUserRLS,
135
- tableHandler: this,
136
- returningFields,
137
- data: preValidatedrowOrRows,
138
- fields,
139
- params: insertParams,
140
- type: "insert",
141
- isMultiInsert,
142
- });
143
- await this._log({ command: "insert", localParams, data: { rowOrRows, param2: insertParams }, duration: Date.now() - start });
144
- return result;
145
- } catch (e) {
146
- await this._log({ command: "insert", localParams, data: { rowOrRows, param2: insertParams }, duration: Date.now() - start, error: getErrorAsObject(e) });
147
- throw getSerializedClientErrorFromPGError(e, { type: "tableMethod", localParams, view: this });
148
- }
149
- }
150
-
151
- const validateInsertParams = (params: InsertParams | undefined) => {
152
-
153
- const { onConflict, returnType, returning } = params ?? {};
154
- if(![undefined, "DoNothing", "DoUpdate"].includes(onConflict)){
155
- throw `Invalid onConflict: ${onConflict}. Expecting one of: DoNothing, DoUpdate`;
156
- }
157
-
158
- const allowedReturnTypes: InsertParams["returnType"][] = ["row", "value", "values", "statement", undefined]
159
- if(!allowedReturnTypes.includes(returnType)){
160
- throw `Invalid return type ${returnType}. Expecting one of: ${allowedReturnTypes}`
161
- }
162
-
163
- if(returnType && returnType !== "statement" && !returning){
164
- throw `Must specify returning when using a non statement returnType: ${returnType}`;
165
- }
166
-
167
- if (params) {
168
- const good_paramsObj: Record<keyof InsertParams, 1> = { returning: 1, returnType: 1, fixIssues: 1, onConflict: 1 };
169
- const good_params = Object.keys(good_paramsObj);
170
- const bad_params = Object.keys(params).filter(k => !good_params.includes(k));
171
- if (bad_params && bad_params.length) throw "Invalid params: " + bad_params.join(", ") + " \n Expecting: " + good_params.join(", ");
172
- }
173
- }
174
-
175
- // const removeBuffers = (o: any) => {
176
- // if(isPlainObject(o)){
177
- // return JSON.stringify(getKeys(o).reduce((a, k) => {
178
- // const value = o[k]
179
- // return { ...a, [k]: Buffer.isBuffer(value)? `Buffer[${value.byteLength}][...REMOVED]` : value
180
- // }
181
- // }, {}));
182
- // }
183
- // }
@@ -1,78 +0,0 @@
1
- import { AnyObject, asName, FieldFilter, FullFilter } from "prostgles-types";
2
- import { LocalParams, pgp } from "../DboBuilder";
3
- import { TableRule } from "../../PublishParser/PublishParser";
4
- import { asValue } from "../../PubSubManager/PubSubManager";
5
- import { TableHandler } from "./TableHandler";
6
-
7
- type InsertTestArgs = {
8
- tableRules: TableRule | undefined;
9
- localParams: LocalParams | undefined;
10
- }
11
- export async function insertTest(this: TableHandler, { localParams, tableRules }: InsertTestArgs) {
12
- const { testRule } = localParams || {};
13
-
14
- const ACTION = "insert";
15
-
16
- let returningFields: FieldFilter | undefined;
17
- let forcedData: AnyObject | undefined;
18
- let fields: FieldFilter | undefined;
19
- let checkFilter: FullFilter<AnyObject, void> | undefined;
20
- let testOnly = false;
21
-
22
- if (tableRules) {
23
- if (!tableRules[ACTION]) throw `${ACTION} rules missing for ${this.name}`;
24
- returningFields = tableRules[ACTION].returningFields;
25
- forcedData = tableRules[ACTION].forcedData;
26
- checkFilter = tableRules[ACTION].checkFilter;
27
- fields = tableRules[ACTION].fields;
28
-
29
- /* If no returning fields specified then take select fields as returning or the allowed insert fields */
30
- if (!returningFields) returningFields = tableRules?.select?.fields || tableRules?.insert.fields;
31
-
32
- if (!fields) throw ` invalid insert rule for ${this.name} -> fields missing `;
33
-
34
- /* Safely test publish rules */
35
- if (testRule) {
36
- await this.validateViewRules({ fields, returningFields, forcedFilter: forcedData, rule: "insert" });
37
- if(checkFilter){
38
- try {
39
- await this.find(checkFilter, { limit: 0 });
40
- } catch (e){
41
- throw `Invalid checkFilter provided for ${this.name}. Error: ${JSON.stringify(e)}`
42
- }
43
- }
44
- if (forcedData) {
45
- const keys = Object.keys(forcedData);
46
- if (keys.length) {
47
- const dataCols = keys.filter(k => this.column_names.includes(k));
48
- const nestedInsertCols = keys.filter(k => !this.column_names.includes(k) && this.dboBuilder.dbo[k]?.insert);
49
- if(nestedInsertCols.length){
50
- throw `Nested insert not supported for forcedData rule: ${nestedInsertCols}`;
51
- }
52
- const badCols = keys.filter(k => !dataCols.includes(k) && !nestedInsertCols.includes(k));
53
- if(badCols.length){
54
- throw `Invalid columns found in forced filter: ${badCols.join(", ")}`;
55
- }
56
- try {
57
- const values = "(" + dataCols.map(k => asValue(forcedData![k]) + "::" + this.columns.find(c => c.name === k)!.udt_name).join(", ") + ")",
58
- colNames = dataCols.map(k => asName(k)).join(",");
59
- const query = pgp.as.format("EXPLAIN INSERT INTO " + this.escapedName + " (${colNames:raw}) SELECT * FROM ( VALUES ${values:raw} ) t WHERE FALSE;", { colNames, values })
60
- await this.db.any(query);
61
- } catch (e) {
62
- throw "\nissue with forcedData: \nVALUE: " + JSON.stringify(forcedData, null, 2) + "\nERROR: " + e;
63
- }
64
- }
65
- }
66
-
67
- testOnly = true;
68
- }
69
- }
70
-
71
- return {
72
- returningFields,
73
- fields,
74
- forcedData,
75
- checkFilter,
76
- testOnly
77
- }
78
- }
@@ -1,62 +0,0 @@
1
- import { AnyObject, asName } from "prostgles-types";
2
- import { LocalParams } from "../DboBuilder";
3
- import { pickKeys } from "../../PubSubManager/PubSubManager";
4
- import { TableHandler } from "./TableHandler";
5
-
6
- type OnDeleteFromFileTableArgs = {
7
- localParams: LocalParams | undefined;
8
- queryType: "one" | "none" | "many" | "any";
9
- returningQuery: undefined | string;
10
- filterOpts: {
11
- where: string;
12
- filter: AnyObject;
13
- }
14
- }
15
- export async function onDeleteFromFileTable(this: TableHandler, { localParams, queryType, returningQuery, filterOpts }: OnDeleteFromFileTableArgs){
16
-
17
- if (!this.dboBuilder.prostgles.fileManager) throw new Error("fileManager missing")
18
- if (this.dboBuilder.prostgles.opts.fileTable?.delayedDelete) {
19
- return this.dbHandler[queryType](`UPDATE ${asName(this.name)} SET deleted = now() ${filterOpts.where} ${returningQuery ?? ""};`)
20
- } else {
21
-
22
- const txDelete = async (tbl: TableHandler) => {
23
- if (!tbl.tx) throw new Error("Missing transaction object tx");
24
- let files: { id: string; name: string }[] = [];
25
- const totalFiles = await tbl.count(filterOpts.filter);
26
- do {
27
- const batch = await tbl.find(filterOpts.filter, { limit: 100, offset: files.length });
28
- files = files.concat(batch);
29
- } while(files.length < totalFiles)
30
-
31
- const fileManager = tbl.dboBuilder.prostgles.fileManager
32
- if (!fileManager) throw new Error("fileManager missing");
33
-
34
- for await (const file of files) {
35
- await tbl.tx.t.any(`DELETE FROM ${asName(this.name)} WHERE id = \${id}`, file);
36
- }
37
- /** If any table delete fails then do not delete files */
38
- for await (const file of files) {
39
- await fileManager.deleteFile(file.name);
40
- /** TODO: Keep track of deleted files in case of failure */
41
- // await tbl.t?.any(`UPDATE ${asName(this.name)} SET deleted = NOW(), deleted_from_storage = NOW() WHERE id = ` + "${id}", file);
42
- }
43
-
44
- if (returningQuery) {
45
- return files.map(f => pickKeys(f, ["id", "name"]));
46
- }
47
-
48
- return undefined;
49
- }
50
-
51
- if (localParams?.tx?.dbTX) {
52
- return txDelete(localParams.tx.dbTX[this.name] as TableHandler)
53
- } else if (this.tx) {
54
- return txDelete(this)
55
- } else {
56
-
57
- return this.dboBuilder.getTX(tx => {
58
- return txDelete(tx[this.name] as TableHandler)
59
- })
60
- }
61
- }
62
- }
@@ -1,134 +0,0 @@
1
- import { AnyObject, asName, FieldFilter, InsertParams, UpdateParams } from "prostgles-types";
2
- import { InsertRule, UpdateRule } from "../../PublishParser/PublishParser";
3
- import { getClientErrorFromPGError, LocalParams, withUserRLS } from "../DboBuilder";
4
- import { getSelectItemQuery, TableHandler } from "./TableHandler";
5
-
6
- type RunInsertUpdateQueryArgs = {
7
- tableHandler: TableHandler;
8
- queryWithoutUserRLS: string;
9
- localParams: LocalParams | undefined;
10
- fields: FieldFilter | undefined;
11
- returningFields: FieldFilter | undefined;
12
- } & ({
13
- type: "insert";
14
- params: InsertParams | undefined
15
- rule: InsertRule | undefined;
16
- data: AnyObject | AnyObject[];
17
- isMultiInsert: boolean;
18
- nestedInsertsResultsObj?: undefined;
19
- } | {
20
- type: "update";
21
- nestedInsertsResultsObj: Record<string, any>;
22
- params: UpdateParams | undefined
23
- rule: UpdateRule | undefined;
24
- data: undefined;
25
- });
26
-
27
- export const runInsertUpdateQuery = async (args: RunInsertUpdateQueryArgs) => {
28
- const { tableHandler, queryWithoutUserRLS, rule, localParams, fields, returningFields, params, nestedInsertsResultsObj } = args;
29
- const { name } = tableHandler;
30
-
31
- const returningSelectItems = await tableHandler.prepareReturning(params?.returning, tableHandler.parseFieldFilter(returningFields))
32
- const { checkFilter, postValidate } = rule ?? {};
33
- let checkCondition = "WHERE FALSE";
34
- if(checkFilter){
35
- const checkCond = await tableHandler.prepareWhere({
36
- select: undefined,
37
- localParams: undefined,
38
- tableRule: undefined,
39
- filter: checkFilter,
40
- addWhere: false,
41
- });
42
- checkCondition = `WHERE NOT (${checkCond.where})`;
43
- }
44
- const hasReturning = !!returningSelectItems.length;
45
- const userRLS = withUserRLS(localParams, "");
46
- const escapedTableName = asName(name)
47
- const query = `
48
- ${userRLS}
49
- WITH ${escapedTableName} AS (
50
- ${queryWithoutUserRLS}
51
- RETURNING *
52
- )
53
- SELECT
54
- count(*) as row_count,
55
- (
56
- SELECT json_agg(item)
57
- FROM (
58
- SELECT *
59
- FROM ${escapedTableName}
60
- ) item
61
- ) as modified,
62
- (
63
- SELECT json_agg(item)
64
- FROM (
65
- SELECT ${!hasReturning? "1" : getSelectItemQuery(returningSelectItems)}
66
- FROM ${escapedTableName}
67
- WHERE ${hasReturning? "TRUE" : "FALSE"}
68
- ) item
69
- ) as modified_returning,
70
- (
71
- SELECT json_agg(item)
72
- FROM (
73
- SELECT *
74
- FROM ${escapedTableName}
75
- ${checkCondition}
76
- LIMIT 5
77
- ) item
78
- ) AS failed_check
79
- FROM ${escapedTableName}
80
- `;
81
-
82
- const allowedFieldKeys = tableHandler.parseFieldFilter(fields);
83
- let result: {
84
- row_count: number | null;
85
- modified: AnyObject[] | null;
86
- failed_check: AnyObject[] | null;
87
- modified_returning: AnyObject[] | null;
88
- };
89
-
90
- const queryType = "one";
91
-
92
- const tx = localParams?.tx?.t || tableHandler.tx?.t;
93
- if (tx) {
94
- result = await tx[queryType](query).catch((err: any) => getClientErrorFromPGError(err, { type: "tableMethod", localParams, view: tableHandler, allowedKeys: allowedFieldKeys }));
95
- } else {
96
- result = await tableHandler.db.tx(t => (t as any)[queryType](query)).catch(err => getClientErrorFromPGError(err, { type: "tableMethod", localParams, view: tableHandler, allowedKeys: allowedFieldKeys }));
97
- }
98
-
99
- if(checkFilter && result.failed_check?.length){
100
- throw new Error(`Insert ${name} records failed the check condition: ${JSON.stringify(checkFilter, null, 2)}`);
101
- }
102
-
103
- const finalDBtx = tableHandler.getFinalDBtx(localParams);
104
- if(postValidate){
105
- if(!finalDBtx) throw new Error("Unexpected: no dbTX for postValidate");
106
- if(!localParams) throw new Error("Unexpected: no localParams for postValidate");
107
-
108
- const rows = result.modified ?? [];
109
- for await (const row of rows){
110
- await postValidate({ row: row ?? {}, dbx: finalDBtx as any, localParams })
111
- }
112
- }
113
-
114
- let returnMany = false;
115
- if(args.type === "update"){
116
- const { multi = true } = args.params || {};
117
- if(!multi && result.row_count && +result.row_count > 1){
118
- throw `More than 1 row modified: ${result.row_count} rows affected`;
119
- }
120
-
121
- if(hasReturning){
122
- returnMany = multi;
123
- }
124
-
125
- } else {
126
- returnMany = args.isMultiInsert
127
- }
128
-
129
- if(!hasReturning) return undefined;
130
-
131
- const modified_returning = result.modified_returning?.map(d => ({ ...d, ...nestedInsertsResultsObj }))
132
-
133
- return returnMany? modified_returning : modified_returning?.[0];
134
- }