prostgles-server 4.2.159 → 4.2.161
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/setEmailProvider.js +2 -2
- package/dist/Auth/setEmailProvider.js.map +1 -1
- package/lib/Auth/AuthHandler.ts +436 -0
- package/lib/Auth/AuthTypes.ts +280 -0
- package/lib/Auth/getSafeReturnURL.ts +35 -0
- package/lib/Auth/sendEmail.ts +83 -0
- package/lib/Auth/setAuthProviders.ts +128 -0
- package/lib/Auth/setEmailProvider.ts +85 -0
- package/lib/Auth/setupAuthRoutes.ts +161 -0
- package/lib/DBEventsManager.ts +178 -0
- package/lib/DBSchemaBuilder.ts +225 -0
- package/lib/DboBuilder/DboBuilder.ts +319 -0
- package/lib/DboBuilder/DboBuilderTypes.ts +361 -0
- package/lib/DboBuilder/QueryBuilder/Functions.ts +1153 -0
- package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +288 -0
- package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +263 -0
- package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +271 -0
- package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +136 -0
- package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +22 -0
- package/lib/DboBuilder/QueryStreamer.ts +250 -0
- package/lib/DboBuilder/TableHandler/DataValidator.ts +428 -0
- package/lib/DboBuilder/TableHandler/TableHandler.ts +205 -0
- package/lib/DboBuilder/TableHandler/delete.ts +115 -0
- package/lib/DboBuilder/TableHandler/insert.ts +183 -0
- package/lib/DboBuilder/TableHandler/insertTest.ts +78 -0
- package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +62 -0
- package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +134 -0
- package/lib/DboBuilder/TableHandler/update.ts +126 -0
- package/lib/DboBuilder/TableHandler/updateBatch.ts +49 -0
- package/lib/DboBuilder/TableHandler/updateFile.ts +48 -0
- package/lib/DboBuilder/TableHandler/upsert.ts +34 -0
- package/lib/DboBuilder/ViewHandler/ViewHandler.ts +393 -0
- package/lib/DboBuilder/ViewHandler/count.ts +38 -0
- package/lib/DboBuilder/ViewHandler/find.ts +153 -0
- package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +73 -0
- package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +74 -0
- package/lib/DboBuilder/ViewHandler/getInfo.ts +32 -0
- package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +84 -0
- package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +96 -0
- package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +105 -0
- package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +208 -0
- package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +163 -0
- package/lib/DboBuilder/ViewHandler/prepareWhere.ts +90 -0
- package/lib/DboBuilder/ViewHandler/size.ts +37 -0
- package/lib/DboBuilder/ViewHandler/subscribe.ts +118 -0
- package/lib/DboBuilder/ViewHandler/validateViewRules.ts +70 -0
- package/lib/DboBuilder/dboBuilderUtils.ts +222 -0
- package/lib/DboBuilder/getColumns.ts +114 -0
- package/lib/DboBuilder/getCondition.ts +201 -0
- package/lib/DboBuilder/getSubscribeRelatedTables.ts +190 -0
- package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +426 -0
- package/lib/DboBuilder/insertNestedRecords.ts +355 -0
- package/lib/DboBuilder/parseUpdateRules.ts +187 -0
- package/lib/DboBuilder/prepareShortestJoinPaths.ts +186 -0
- package/lib/DboBuilder/runSQL.ts +182 -0
- package/lib/DboBuilder/runTransaction.ts +50 -0
- package/lib/DboBuilder/sqlErrCodeToMsg.ts +254 -0
- package/lib/DboBuilder/uploadFile.ts +69 -0
- package/lib/Event_Trigger_Tags.ts +118 -0
- package/lib/FileManager/FileManager.ts +358 -0
- package/lib/FileManager/getValidatedFileType.ts +69 -0
- package/lib/FileManager/initFileManager.ts +187 -0
- package/lib/FileManager/upload.ts +62 -0
- package/lib/FileManager/uploadStream.ts +79 -0
- package/lib/Filtering.ts +463 -0
- package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +502 -0
- package/lib/JSONBValidation/validation.ts +143 -0
- package/lib/Logging.ts +127 -0
- package/lib/PostgresNotifListenManager.ts +143 -0
- package/lib/Prostgles.ts +485 -0
- package/lib/ProstglesTypes.ts +196 -0
- package/lib/PubSubManager/PubSubManager.ts +609 -0
- package/lib/PubSubManager/addSub.ts +138 -0
- package/lib/PubSubManager/addSync.ts +141 -0
- package/lib/PubSubManager/getCreatePubSubManagerError.ts +72 -0
- package/lib/PubSubManager/getPubSubManagerInitQuery.ts +662 -0
- package/lib/PubSubManager/initPubSubManager.ts +79 -0
- package/lib/PubSubManager/notifListener.ts +173 -0
- package/lib/PubSubManager/orphanTriggerCheck.ts +70 -0
- package/lib/PubSubManager/pushSubData.ts +55 -0
- package/lib/PublishParser/PublishParser.ts +162 -0
- package/lib/PublishParser/getFileTableRules.ts +124 -0
- package/lib/PublishParser/getSchemaFromPublish.ts +141 -0
- package/lib/PublishParser/getTableRulesWithoutFileTable.ts +177 -0
- package/lib/PublishParser/publishTypesAndUtils.ts +399 -0
- package/lib/RestApi.ts +127 -0
- package/lib/SchemaWatch/SchemaWatch.ts +90 -0
- package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +3 -0
- package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +45 -0
- package/lib/SchemaWatch/getWatchSchemaTagList.ts +27 -0
- package/lib/SyncReplication.ts +557 -0
- package/lib/TableConfig/TableConfig.ts +468 -0
- package/lib/TableConfig/getColumnDefinitionQuery.ts +111 -0
- package/lib/TableConfig/getConstraintDefinitionQueries.ts +95 -0
- package/lib/TableConfig/getFutureTableSchema.ts +64 -0
- package/lib/TableConfig/getPGIndexes.ts +53 -0
- package/lib/TableConfig/getTableColumnQueries.ts +129 -0
- package/lib/TableConfig/initTableConfig.ts +326 -0
- package/lib/index.ts +13 -0
- package/lib/initProstgles.ts +319 -0
- package/lib/onSocketConnected.ts +102 -0
- package/lib/runClientRequest.ts +129 -0
- package/lib/shortestPath.ts +122 -0
- package/lib/typeTests/DBoGenerated.d.ts +320 -0
- package/lib/typeTests/dboTypeCheck.ts +81 -0
- package/lib/utils.ts +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
|
|
@@ -0,0 +1,183 @@
|
|
|
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
|
+
// }
|
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
}
|