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.
Files changed (107) hide show
  1. package/dist/Auth/setEmailProvider.js +2 -2
  2. package/dist/Auth/setEmailProvider.js.map +1 -1
  3. package/lib/Auth/AuthHandler.ts +436 -0
  4. package/lib/Auth/AuthTypes.ts +280 -0
  5. package/lib/Auth/getSafeReturnURL.ts +35 -0
  6. package/lib/Auth/sendEmail.ts +83 -0
  7. package/lib/Auth/setAuthProviders.ts +128 -0
  8. package/lib/Auth/setEmailProvider.ts +85 -0
  9. package/lib/Auth/setupAuthRoutes.ts +161 -0
  10. package/lib/DBEventsManager.ts +178 -0
  11. package/lib/DBSchemaBuilder.ts +225 -0
  12. package/lib/DboBuilder/DboBuilder.ts +319 -0
  13. package/lib/DboBuilder/DboBuilderTypes.ts +361 -0
  14. package/lib/DboBuilder/QueryBuilder/Functions.ts +1153 -0
  15. package/lib/DboBuilder/QueryBuilder/QueryBuilder.ts +288 -0
  16. package/lib/DboBuilder/QueryBuilder/getJoinQuery.ts +263 -0
  17. package/lib/DboBuilder/QueryBuilder/getNewQuery.ts +271 -0
  18. package/lib/DboBuilder/QueryBuilder/getSelectQuery.ts +136 -0
  19. package/lib/DboBuilder/QueryBuilder/prepareHaving.ts +22 -0
  20. package/lib/DboBuilder/QueryStreamer.ts +250 -0
  21. package/lib/DboBuilder/TableHandler/DataValidator.ts +428 -0
  22. package/lib/DboBuilder/TableHandler/TableHandler.ts +205 -0
  23. package/lib/DboBuilder/TableHandler/delete.ts +115 -0
  24. package/lib/DboBuilder/TableHandler/insert.ts +183 -0
  25. package/lib/DboBuilder/TableHandler/insertTest.ts +78 -0
  26. package/lib/DboBuilder/TableHandler/onDeleteFromFileTable.ts +62 -0
  27. package/lib/DboBuilder/TableHandler/runInsertUpdateQuery.ts +134 -0
  28. package/lib/DboBuilder/TableHandler/update.ts +126 -0
  29. package/lib/DboBuilder/TableHandler/updateBatch.ts +49 -0
  30. package/lib/DboBuilder/TableHandler/updateFile.ts +48 -0
  31. package/lib/DboBuilder/TableHandler/upsert.ts +34 -0
  32. package/lib/DboBuilder/ViewHandler/ViewHandler.ts +393 -0
  33. package/lib/DboBuilder/ViewHandler/count.ts +38 -0
  34. package/lib/DboBuilder/ViewHandler/find.ts +153 -0
  35. package/lib/DboBuilder/ViewHandler/getExistsCondition.ts +73 -0
  36. package/lib/DboBuilder/ViewHandler/getExistsFilters.ts +74 -0
  37. package/lib/DboBuilder/ViewHandler/getInfo.ts +32 -0
  38. package/lib/DboBuilder/ViewHandler/getTableJoinQuery.ts +84 -0
  39. package/lib/DboBuilder/ViewHandler/parseComplexFilter.ts +96 -0
  40. package/lib/DboBuilder/ViewHandler/parseFieldFilter.ts +105 -0
  41. package/lib/DboBuilder/ViewHandler/parseJoinPath.ts +208 -0
  42. package/lib/DboBuilder/ViewHandler/prepareSortItems.ts +163 -0
  43. package/lib/DboBuilder/ViewHandler/prepareWhere.ts +90 -0
  44. package/lib/DboBuilder/ViewHandler/size.ts +37 -0
  45. package/lib/DboBuilder/ViewHandler/subscribe.ts +118 -0
  46. package/lib/DboBuilder/ViewHandler/validateViewRules.ts +70 -0
  47. package/lib/DboBuilder/dboBuilderUtils.ts +222 -0
  48. package/lib/DboBuilder/getColumns.ts +114 -0
  49. package/lib/DboBuilder/getCondition.ts +201 -0
  50. package/lib/DboBuilder/getSubscribeRelatedTables.ts +190 -0
  51. package/lib/DboBuilder/getTablesForSchemaPostgresSQL.ts +426 -0
  52. package/lib/DboBuilder/insertNestedRecords.ts +355 -0
  53. package/lib/DboBuilder/parseUpdateRules.ts +187 -0
  54. package/lib/DboBuilder/prepareShortestJoinPaths.ts +186 -0
  55. package/lib/DboBuilder/runSQL.ts +182 -0
  56. package/lib/DboBuilder/runTransaction.ts +50 -0
  57. package/lib/DboBuilder/sqlErrCodeToMsg.ts +254 -0
  58. package/lib/DboBuilder/uploadFile.ts +69 -0
  59. package/lib/Event_Trigger_Tags.ts +118 -0
  60. package/lib/FileManager/FileManager.ts +358 -0
  61. package/lib/FileManager/getValidatedFileType.ts +69 -0
  62. package/lib/FileManager/initFileManager.ts +187 -0
  63. package/lib/FileManager/upload.ts +62 -0
  64. package/lib/FileManager/uploadStream.ts +79 -0
  65. package/lib/Filtering.ts +463 -0
  66. package/lib/JSONBValidation/validate_jsonb_schema_sql.ts +502 -0
  67. package/lib/JSONBValidation/validation.ts +143 -0
  68. package/lib/Logging.ts +127 -0
  69. package/lib/PostgresNotifListenManager.ts +143 -0
  70. package/lib/Prostgles.ts +485 -0
  71. package/lib/ProstglesTypes.ts +196 -0
  72. package/lib/PubSubManager/PubSubManager.ts +609 -0
  73. package/lib/PubSubManager/addSub.ts +138 -0
  74. package/lib/PubSubManager/addSync.ts +141 -0
  75. package/lib/PubSubManager/getCreatePubSubManagerError.ts +72 -0
  76. package/lib/PubSubManager/getPubSubManagerInitQuery.ts +662 -0
  77. package/lib/PubSubManager/initPubSubManager.ts +79 -0
  78. package/lib/PubSubManager/notifListener.ts +173 -0
  79. package/lib/PubSubManager/orphanTriggerCheck.ts +70 -0
  80. package/lib/PubSubManager/pushSubData.ts +55 -0
  81. package/lib/PublishParser/PublishParser.ts +162 -0
  82. package/lib/PublishParser/getFileTableRules.ts +124 -0
  83. package/lib/PublishParser/getSchemaFromPublish.ts +141 -0
  84. package/lib/PublishParser/getTableRulesWithoutFileTable.ts +177 -0
  85. package/lib/PublishParser/publishTypesAndUtils.ts +399 -0
  86. package/lib/RestApi.ts +127 -0
  87. package/lib/SchemaWatch/SchemaWatch.ts +90 -0
  88. package/lib/SchemaWatch/createSchemaWatchEventTrigger.ts +3 -0
  89. package/lib/SchemaWatch/getValidatedWatchSchemaType.ts +45 -0
  90. package/lib/SchemaWatch/getWatchSchemaTagList.ts +27 -0
  91. package/lib/SyncReplication.ts +557 -0
  92. package/lib/TableConfig/TableConfig.ts +468 -0
  93. package/lib/TableConfig/getColumnDefinitionQuery.ts +111 -0
  94. package/lib/TableConfig/getConstraintDefinitionQueries.ts +95 -0
  95. package/lib/TableConfig/getFutureTableSchema.ts +64 -0
  96. package/lib/TableConfig/getPGIndexes.ts +53 -0
  97. package/lib/TableConfig/getTableColumnQueries.ts +129 -0
  98. package/lib/TableConfig/initTableConfig.ts +326 -0
  99. package/lib/index.ts +13 -0
  100. package/lib/initProstgles.ts +319 -0
  101. package/lib/onSocketConnected.ts +102 -0
  102. package/lib/runClientRequest.ts +129 -0
  103. package/lib/shortestPath.ts +122 -0
  104. package/lib/typeTests/DBoGenerated.d.ts +320 -0
  105. package/lib/typeTests/dboTypeCheck.ts +81 -0
  106. package/lib/utils.ts +15 -0
  107. package/package.json +1 -1
@@ -0,0 +1,186 @@
1
+ import { DboBuilder } from "../DboBuilder/DboBuilder";
2
+ import { JOIN_TYPES, Join } from "../ProstglesTypes";
3
+ import { Graph, findShortestPath } from "../shortestPath";
4
+ import { TableSchema } from "./DboBuilderTypes";
5
+ import { JoinPaths } from "./ViewHandler/ViewHandler";
6
+
7
+ type Result = {
8
+ joinGraph?: Graph | undefined;
9
+ joins: Join[];
10
+ shortestJoinPaths: JoinPaths;
11
+ }
12
+ export async function prepareShortestJoinPaths(dboBuilder: DboBuilder): Promise<Result> {
13
+
14
+ if (dboBuilder.prostgles.opts.joins) {
15
+
16
+ let joinConfig = await dboBuilder.prostgles.opts.joins;
17
+ if (!dboBuilder.tablesOrViews) {
18
+ throw new Error("Could not create join config. this.tablesOrViews missing");
19
+ }
20
+
21
+ const inferredJoins = await getInferredJoins2(dboBuilder.tablesOrViews);
22
+ if (joinConfig === "inferred") {
23
+ joinConfig = inferredJoins
24
+ /* If joins are specified then include inferred joins except the explicit tables */
25
+ } else if (Array.isArray(joinConfig)) {
26
+ const joinTables = joinConfig.map(j => j.tables).flat();
27
+ joinConfig = joinConfig.concat(inferredJoins.filter(j => !j.tables.find(t => joinTables.includes(t))))
28
+ } else if (joinConfig) {
29
+ throw new Error("Unexpected joins init param. Expecting 'inferred' OR joinConfig but got: " + JSON.stringify(joinConfig))
30
+ }
31
+ const joins = JSON.parse(JSON.stringify(joinConfig)) as Join[];
32
+
33
+ // Validate joins
34
+ try {
35
+ const tovNames = dboBuilder.tablesOrViews!.map(t => t.name);
36
+
37
+ // 2 find incorrect tables
38
+ const missing = joins.flatMap(j => j.tables).find(t => !tovNames.includes(t));
39
+ if (missing) {
40
+ throw "Table not found: " + missing;
41
+ }
42
+
43
+ // 3 find incorrect fields
44
+ joins.map(({ tables, on }) => {
45
+ const t1 = tables[0],
46
+ t2 = tables[1];
47
+ on.map(cond => {
48
+
49
+ const f1s = Object.keys(cond),
50
+ f2s = Object.values(cond);
51
+ [[t1, f1s], [t2, f2s]].map(v => {
52
+ const t = <string>v[0],
53
+ f = <string[]>v[1];
54
+
55
+ const tov = dboBuilder.tablesOrViews!.find(_t => _t.name === t);
56
+ if (!tov) throw "Table not found: " + t;
57
+ const m1 = f.filter(k => !tov!.columns.map(c => c.name).includes(k))
58
+ if (m1 && m1.length) {
59
+ throw `Table ${t}(${tov.columns.map(c => c.name).join()}) has no fields named: ${m1.join()}`;
60
+ }
61
+ });
62
+ })
63
+ });
64
+
65
+ // 4 find incorrect/missing join types
66
+ const expected_types = " \n\n-> Expecting: " + JOIN_TYPES.map(t => JSON.stringify(t)).join(` | `)
67
+ const mt = joins.find(j => !j.type);
68
+ if (mt) throw "Join type missing for: " + JSON.stringify(mt, null, 2) + expected_types;
69
+
70
+ const it = joins.find(j => !JOIN_TYPES.includes(j.type));
71
+ if (it) throw "Incorrect join type for: " + JSON.stringify(it, null, 2) + expected_types;
72
+
73
+ } catch (e) {
74
+ const errMsg = ((joinConfig as any) === "inferred"? "INFERRED " : "") + "JOINS VALIDATION ERROR \n-> " + e;
75
+ throw errMsg;
76
+ }
77
+
78
+ // Make joins graph
79
+ const joinGraph: Graph = {};
80
+ joins.forEach(({ tables }) => {
81
+ const _t = tables.slice().sort(),
82
+ t1 = _t[0]!,
83
+ t2 = _t[1]!;
84
+
85
+ if (t1 === t2) return;
86
+
87
+ joinGraph![t1] ??= {};
88
+ joinGraph![t1]![t2] = 1;
89
+
90
+ joinGraph![t2] ??= {};
91
+ joinGraph![t2]![t1] = 1;
92
+ });
93
+ const tables = Array.from(new Set(joins.flatMap(t => t.tables)));
94
+ const shortestJoinPaths: JoinPaths = [];
95
+ tables.forEach((t1, i1) => {
96
+ tables.forEach((t2, i2) => {
97
+
98
+ /** Prevent recursion */
99
+ if (
100
+ t1 === t2 ||
101
+ shortestJoinPaths.some(jp => {
102
+ if (arrayValuesMatch([jp.t1, jp.t2], [t1, t2])) {
103
+ const spath = findShortestPath(joinGraph, t1, t2);
104
+ if (spath && arrayValuesMatch(spath.path, jp.path)) {
105
+ return true;
106
+ }
107
+ }
108
+ })
109
+ ) {
110
+ return;
111
+ }
112
+
113
+ const spath = findShortestPath(joinGraph, t1, t2);
114
+ if (!(spath && spath.distance < Infinity)) return;
115
+
116
+ const existing1 = shortestJoinPaths.find(j => j.t1 === t1 && j.t2 === t2)
117
+ if (!existing1) {
118
+ shortestJoinPaths.push({ t1, t2, path: spath.path.slice() });
119
+ }
120
+
121
+ const existing2 = shortestJoinPaths.find(j => j.t2 === t1 && j.t1 === t2);
122
+ if (!existing2) {
123
+ shortestJoinPaths.push({ t1: t2, t2: t1, path: spath.path.slice().reverse() });
124
+ }
125
+ });
126
+ });
127
+ return {
128
+ joins, shortestJoinPaths, joinGraph
129
+ }
130
+ }
131
+
132
+ return {
133
+ joins: [],
134
+ shortestJoinPaths: [],
135
+ };
136
+ }
137
+
138
+
139
+ const arrayValuesMatch = <T>(arr1: T[], arr2: T[]): boolean => {
140
+ return arr1.slice().sort().join() === arr2.slice().sort().join()
141
+ }
142
+
143
+ async function getInferredJoins2(schema: TableSchema[]): Promise<Join[]> {
144
+ const joins: Join[] = [];
145
+ const upsertJoin = (t1: string, t2: string, cols: { col1: string; col2: string }[], type: Join["type"]) => {
146
+ const existingIdx = joins.findIndex(j => arrayValuesMatch(j.tables.slice(0), [t1, t2]));
147
+ const existing = joins[existingIdx];
148
+ const normalCond = cols.reduce((a, v) => ({ ...a, [v.col1]: v.col2 }), {});
149
+ const revertedCond = cols.reduce((a, v) => ({ ...a, [v.col2]: v.col1 }), {});
150
+ if (existing) {
151
+ const isLTR = existing.tables[0] === t1
152
+ const cond = isLTR ? normalCond : revertedCond;
153
+
154
+ /** At some point we should add relationship type to EACH JOIN CONDITION GROUP */
155
+ // const fixedType = isLTR? type : type.split("").reverse().join("") as Join["type"];
156
+
157
+ /** Avoid duplicates */
158
+ if (!existing.on.some(_cond => JSON.stringify(_cond) === JSON.stringify(cond))) {
159
+ existing.on.push(cond);
160
+ joins[existingIdx] = existing;
161
+ }
162
+ } else {
163
+ joins.push({
164
+ tables: [t1, t2],
165
+ on: [normalCond],
166
+ type
167
+ })
168
+ }
169
+ }
170
+ schema.map(tov => {
171
+ tov.columns.map(col => {
172
+ if (col.references) {
173
+ col.references.forEach(r => {
174
+ const joinCols = r.cols.map((c, i) => ({ col1: c, col2: r.fcols[i]! }));
175
+ let type: Join["type"] = "one-many";
176
+ const ftablePkeys = schema.find(_tov => _tov.name === r.ftable)?.columns.filter(fcol => fcol.is_pkey);
177
+ if (ftablePkeys?.length && ftablePkeys.every(fkey => r.fcols.includes(fkey.name))) {
178
+ type = "one-one";
179
+ }
180
+ upsertJoin(tov.name, r.ftable, joinCols, type)
181
+ })
182
+ }
183
+ })
184
+ })
185
+ return joins;
186
+ }
@@ -0,0 +1,182 @@
1
+ import pgPromise, { ParameterizedQuery as PQ, ParameterizedQuery } from 'pg-promise';
2
+ import pg from "pg-promise/typescript/pg-subset";
3
+ import { AnyObject, SQLOptions, SQLResult, SQLResultInfo } from "prostgles-types";
4
+ import { DB, Prostgles } from "../Prostgles";
5
+ import { DboBuilder, LocalParams, pgp, postgresToTsType } from "./DboBuilder";
6
+
7
+
8
+ export async function runSQL(this: DboBuilder, queryWithoutRLS: string, args: undefined | AnyObject | any[], options: SQLOptions | undefined, localParams?: LocalParams) {
9
+ const queryWithRLS = queryWithoutRLS;
10
+ if(queryWithRLS?.replace(/\s\s+/g, ' ').toLowerCase().includes("create extension pg_stat_statements")){
11
+ const { shared_preload_libraries } = await this.db.oneOrNone('SHOW shared_preload_libraries');
12
+ if(!(shared_preload_libraries || "").includes("pg_stat_statements")){
13
+ throw "This query will crash the server (pg_stat_statements must be loaded via shared_preload_libraries). Need to: \n ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements' \n" +
14
+ " AND restart server: \n (linux) sudo service postgresql restart\n (mac) brew services restart postgres\n "
15
+ }
16
+ }
17
+
18
+ await this.cacheDBTypes();
19
+
20
+ if (!(await canRunSQL(this.prostgles, localParams))) {
21
+ throw "Not allowed to run SQL";
22
+ }
23
+
24
+ const { returnType, allowListen, hasParams = true }: SQLOptions = options || ({} as SQLOptions);
25
+ const { socket } = localParams || {};
26
+
27
+
28
+ const db = localParams?.tx?.t || this.db;
29
+ if (returnType === "stream") {
30
+ if(localParams?.tx) throw "Cannot use stream with localParams transaction";
31
+ if (!socket) throw "Only allowed with client socket";
32
+ const streamInfo = await this.queryStreamer.create({ socket, query: pgp.as.format(queryWithRLS, args), options });
33
+ return streamInfo;
34
+
35
+ } else if (returnType === "noticeSubscription") {
36
+ if (!socket) throw "Only allowed with client socket"
37
+ return await this.prostgles.dbEventsManager?.addNotice(socket);
38
+
39
+ } else if (returnType === "statement") {
40
+ try {
41
+ return pgp.as.format(queryWithoutRLS, args);
42
+ } catch (err) {
43
+ throw (err as any).toString();
44
+ }
45
+
46
+ }
47
+
48
+ if (!db) {
49
+ throw "db is missing"
50
+ }
51
+
52
+ let finalQuery: string | ParameterizedQuery = queryWithRLS + "";
53
+ const isNotListenOrNotify = (returnType === "arrayMode") && !["listen ", "notify "].find(c => queryWithoutRLS.toLowerCase().trim().startsWith(c))
54
+ if (isNotListenOrNotify) {
55
+ finalQuery = new PQ({
56
+ rowMode: "array",
57
+ text: hasParams ? pgp.as.format(queryWithRLS, args) : queryWithRLS,
58
+ });
59
+ }
60
+
61
+ const params = hasParams ? args : undefined;
62
+ let queryResult: pgPromise.IResultExt<AnyObject> | undefined;
63
+
64
+ if(returnType === "default-with-rollback"){
65
+ const ROLLBACK = "Rollback";
66
+ await db.tx(async t => {
67
+ queryResult = await t.result<AnyObject>(finalQuery, params);
68
+ /** Rollback */
69
+ return Promise.reject(new Error(ROLLBACK));
70
+ }).catch(e => {
71
+ if(!(e instanceof Error && e.message === ROLLBACK)) throw e;
72
+ });
73
+ } else {
74
+ queryResult = await db.result<AnyObject>(finalQuery, params);
75
+ }
76
+ if(!queryResult) throw "No query result";
77
+ const { fields, rows } = queryResult;
78
+
79
+ const listenHandlers = await onSQLResult.bind(this)(queryWithoutRLS, queryResult, allowListen, localParams);
80
+ if(listenHandlers) {
81
+ return listenHandlers;
82
+ }
83
+
84
+ if (returnType === "rows") {
85
+ return rows;
86
+
87
+ } else if (returnType === "row") {
88
+ return rows[0];
89
+
90
+ } else if (returnType === "value") {
91
+ return Object.values(rows?.[0] ?? {})?.[0];
92
+
93
+ } else if (returnType === "values") {
94
+ return rows.map(r => Object.values(r ?? {})[0]);
95
+
96
+ } else {
97
+
98
+ const qres: SQLResult<typeof returnType> = {
99
+ duration: 0,
100
+ ...queryResult,
101
+ fields: getDetailedFieldInfo.bind(this)(fields),
102
+ };
103
+ return qres;
104
+ }
105
+ }
106
+
107
+ const onSQLResult = async function(this: DboBuilder, queryWithoutRLS: string, { command }: Omit<SQLResultInfo, "duration">, allowListen: boolean | undefined, localParams?: LocalParams) {
108
+
109
+ this.prostgles.schemaWatch?.onSchemaChangeFallback?.({ command, query: queryWithoutRLS });
110
+
111
+ if (command === "LISTEN") {
112
+ const { socket } = localParams || {};
113
+ if (!allowListen) throw new Error(`Your query contains a LISTEN command. Set { allowListen: true } to get subscription hooks. Or ignore this message`)
114
+ if (!socket) throw "Only allowed with client socket"
115
+ return await this.prostgles.dbEventsManager?.addNotify(queryWithoutRLS, socket);
116
+ }
117
+ }
118
+
119
+ export async function cacheDBTypes(this: DboBuilder, force = false) {
120
+ if(force){
121
+ this.DATA_TYPES = undefined;
122
+ this.USER_TABLES = undefined;
123
+ this.USER_TABLE_COLUMNS = undefined;
124
+ }
125
+ this.DATA_TYPES ??= await this.db.any("SELECT oid, typname FROM pg_type") ?? [];
126
+ this.USER_TABLES ??= await this.db.any(`
127
+ SELECT
128
+ relid,
129
+ relname,
130
+ schemaname,
131
+ array_to_json(array_agg(c.column_name) FILTER (WHERE c.column_name IS NOT NULL)) as pkey_columns
132
+ FROM pg_catalog.pg_statio_user_tables t
133
+ LEFT JOIN (
134
+ SELECT a.attname as column_name, i.indrelid as table_oid
135
+ FROM pg_index i
136
+ JOIN pg_attribute a ON a.attrelid = i.indrelid
137
+ AND a.attnum = ANY(i.indkey)
138
+ WHERE i.indisprimary
139
+ ) c
140
+ ON t.relid = c.table_oid
141
+ GROUP BY relid, relname, schemaname
142
+ `) ?? [];
143
+ this.USER_TABLE_COLUMNS ??= await this.db.any(`
144
+ SELECT t.relid, t.schemaname,t.relname, c.column_name, c.udt_name, c.ordinal_position
145
+ FROM information_schema.columns c
146
+ INNER JOIN pg_catalog.pg_statio_user_tables t
147
+ ON c.table_schema = t.schemaname AND c.table_name = t.relname
148
+ `);
149
+ }
150
+
151
+ export function getDetailedFieldInfo(this: DboBuilder, fields: pg.IColumn[]) {
152
+ return fields?.map(f => {
153
+ const dataType = this.DATA_TYPES!.find(dt => +dt.oid === +f.dataTypeID)?.typname ?? "text",
154
+ table = this.USER_TABLES!.find(t => +t.relid === +f.tableID),
155
+ column = this.USER_TABLE_COLUMNS!.find(c => +c.relid === +f.tableID && c.ordinal_position === f.columnID),
156
+ tsDataType = postgresToTsType(dataType);
157
+
158
+ return {
159
+ ...f,
160
+ tsDataType,
161
+ dataType,
162
+ udt_name: dataType,
163
+ tableName: table?.relname,
164
+ tableSchema: table?.schemaname,
165
+ columnName: column?.column_name
166
+ }
167
+ }) ?? [];
168
+ }
169
+
170
+ export const canRunSQL = async (prostgles: Prostgles, localParams?: LocalParams): Promise<boolean> => {
171
+ if (!localParams?.socket || !localParams?.httpReq) return true;
172
+
173
+ const { socket } = localParams;
174
+ const publishParams = await prostgles.publishParser!.getPublishParams({ socket });
175
+ //@ts-ignore
176
+ const res = await prostgles.opts.publishRawSQL?.(publishParams);
177
+ return Boolean(res && typeof res === "boolean" || res === "*");
178
+ }
179
+
180
+ export const canCreateTables = async (db: DB): Promise<boolean> => {
181
+ return db.any(`SELECT has_database_privilege(current_database(), 'create') as yes`).then(rows => rows?.[0].yes === true)
182
+ }
@@ -0,0 +1,50 @@
1
+ import * as pg from "pg";
2
+ const { Client } = pg;
3
+
4
+ export type PGTX = ((query: pg.Client["query"]) => Promise<void>);
5
+ export type RunTransactionOpts = {
6
+ begin?: boolean;
7
+ onSuccess: "COMMIT" | "ROLLBACK" | undefined;
8
+ }
9
+ export const runClientTransaction = async (handler: PGTX, { onSuccess, begin = true }: RunTransactionOpts, dbConn: pg.ClientConfig) => {
10
+ const client = new Client(dbConn)
11
+ try {
12
+ if(begin){
13
+ await client.query('BEGIN')
14
+ }
15
+ await handler(client.query);
16
+ if(onSuccess){
17
+ await client.query(onSuccess);
18
+ }
19
+ } catch (e) {
20
+ await client.query('ROLLBACK');
21
+ throw e
22
+ } finally {
23
+ client.end();
24
+ }
25
+ }
26
+
27
+ export const runClientTransactionStatement = async (statement: string, dbConn: pg.ClientConfig) => {
28
+ return runClientTransaction(async (query) => {
29
+ await query(statement);
30
+ }, { onSuccess: undefined, begin: false }, dbConn);
31
+ }
32
+
33
+ // let pool: pg.Pool | undefined;
34
+ // export const runPoolTransaction = async (handler: PGTX, { onSuccess, begin = true }: RunTransactionOpts, dbConn: pg.ClientConfig) => {
35
+ // pool ??= new Pool(dbConn);
36
+ // const client = await pool.connect()
37
+
38
+ // try {
39
+ // await client.query('BEGIN')
40
+ // await handler(client.query);
41
+ // if(onSuccess){
42
+ // await client.query(onSuccess);
43
+ // }
44
+ // } catch (e) {
45
+ // await client.query('ROLLBACK');
46
+ // throw e
47
+ // } finally {
48
+ // client.release();
49
+ // }
50
+ // }