@restura/core 2.0.3 → 2.1.0
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/index.d.ts +166 -57
- package/dist/index.js +1209 -921
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -83,16 +83,20 @@ var EventManager = class {
|
|
|
83
83
|
filter
|
|
84
84
|
});
|
|
85
85
|
}
|
|
86
|
-
async fireActionFromDbTrigger(sqlMutationData, result) {
|
|
86
|
+
async fireActionFromDbTrigger(sqlMutationData, result, options) {
|
|
87
|
+
const handlerErrors = [];
|
|
87
88
|
if (sqlMutationData.mutationType === "INSERT") {
|
|
88
|
-
await this.fireInsertActions(sqlMutationData, result);
|
|
89
|
+
await this.fireInsertActions(sqlMutationData, result, handlerErrors);
|
|
89
90
|
} else if (sqlMutationData.mutationType === "UPDATE") {
|
|
90
|
-
await this.fireUpdateActions(sqlMutationData, result);
|
|
91
|
+
await this.fireUpdateActions(sqlMutationData, result, handlerErrors);
|
|
91
92
|
} else if (sqlMutationData.mutationType === "DELETE") {
|
|
92
|
-
await this.fireDeleteActions(sqlMutationData, result);
|
|
93
|
+
await this.fireDeleteActions(sqlMutationData, result, handlerErrors);
|
|
94
|
+
}
|
|
95
|
+
if (options?.rethrowHandlerErrors && handlerErrors.length) {
|
|
96
|
+
throw handlerErrors[0];
|
|
93
97
|
}
|
|
94
98
|
}
|
|
95
|
-
async fireInsertActions(data, triggerResult) {
|
|
99
|
+
async fireInsertActions(data, triggerResult, handlerErrors) {
|
|
96
100
|
await Bluebird.map(
|
|
97
101
|
this.actionHandlers.DATABASE_ROW_INSERT,
|
|
98
102
|
async ({ callback, filter }) => {
|
|
@@ -107,12 +111,13 @@ var EventManager = class {
|
|
|
107
111
|
await callback(insertData, data.queryMetadata);
|
|
108
112
|
} catch (error) {
|
|
109
113
|
logger.error(`Error firing insert action for table ${triggerResult.table}`, error);
|
|
114
|
+
handlerErrors.push(error);
|
|
110
115
|
}
|
|
111
116
|
},
|
|
112
117
|
{ concurrency: 10 }
|
|
113
118
|
);
|
|
114
119
|
}
|
|
115
|
-
async fireDeleteActions(data, triggerResult) {
|
|
120
|
+
async fireDeleteActions(data, triggerResult, handlerErrors) {
|
|
116
121
|
await Bluebird.map(
|
|
117
122
|
this.actionHandlers.DATABASE_ROW_DELETE,
|
|
118
123
|
async ({ callback, filter }) => {
|
|
@@ -127,12 +132,13 @@ var EventManager = class {
|
|
|
127
132
|
await callback(deleteData, data.queryMetadata);
|
|
128
133
|
} catch (error) {
|
|
129
134
|
logger.error(`Error firing delete action for table ${triggerResult.table}`, error);
|
|
135
|
+
handlerErrors.push(error);
|
|
130
136
|
}
|
|
131
137
|
},
|
|
132
138
|
{ concurrency: 10 }
|
|
133
139
|
);
|
|
134
140
|
}
|
|
135
|
-
async fireUpdateActions(data, triggerResult) {
|
|
141
|
+
async fireUpdateActions(data, triggerResult, handlerErrors) {
|
|
136
142
|
await Bluebird.map(
|
|
137
143
|
this.actionHandlers.DATABASE_COLUMN_UPDATE,
|
|
138
144
|
async ({ callback, filter }) => {
|
|
@@ -148,11 +154,53 @@ var EventManager = class {
|
|
|
148
154
|
await callback(columnChangeData, data.queryMetadata);
|
|
149
155
|
} catch (error) {
|
|
150
156
|
logger.error(`Error firing update action for table ${triggerResult.table}`, error);
|
|
157
|
+
handlerErrors.push(error);
|
|
151
158
|
}
|
|
152
159
|
},
|
|
153
160
|
{ concurrency: 10 }
|
|
154
161
|
);
|
|
155
162
|
}
|
|
163
|
+
// A handler whose filter doesn't match the schema's notify config silently never fires — surface it at startup
|
|
164
|
+
validateHandlersAgainstSchema(schema, mode) {
|
|
165
|
+
if (mode === "off") return;
|
|
166
|
+
const problems = [];
|
|
167
|
+
const checkTable = (tableName, handlerKind) => {
|
|
168
|
+
if (!tableName) return void 0;
|
|
169
|
+
const table = schema.database.find((item) => item.name === tableName);
|
|
170
|
+
if (!table) {
|
|
171
|
+
problems.push(`${handlerKind} handler registered for unknown table "${tableName}"`);
|
|
172
|
+
return void 0;
|
|
173
|
+
}
|
|
174
|
+
if (!table.notify) {
|
|
175
|
+
problems.push(
|
|
176
|
+
`${handlerKind} handler registered for table "${tableName}" which has no notify config \u2014 it will never fire`
|
|
177
|
+
);
|
|
178
|
+
return void 0;
|
|
179
|
+
}
|
|
180
|
+
return table;
|
|
181
|
+
};
|
|
182
|
+
this.actionHandlers.DATABASE_ROW_INSERT.forEach(({ filter }) => checkTable(filter?.tableName, "Row-insert"));
|
|
183
|
+
this.actionHandlers.DATABASE_ROW_DELETE.forEach(({ filter }) => checkTable(filter?.tableName, "Row-delete"));
|
|
184
|
+
this.actionHandlers.DATABASE_COLUMN_UPDATE.forEach(({ filter }) => {
|
|
185
|
+
const table = checkTable(filter?.tableName, "Column-change");
|
|
186
|
+
if (!table || !filter || table.notify === "ALL") return;
|
|
187
|
+
const notifyColumns = table.notify.map((entry) => entry.replace(/^!/, ""));
|
|
188
|
+
for (const column of filter.columns) {
|
|
189
|
+
if (column === "*") continue;
|
|
190
|
+
if (!notifyColumns.includes(column)) {
|
|
191
|
+
problems.push(
|
|
192
|
+
`Column-change handler on "${filter.tableName}" filters column "${column}" which is not in the table's notify list \u2014 it will never fire`
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
if (!problems.length) return;
|
|
198
|
+
if (mode === "strict") {
|
|
199
|
+
throw new Error(`Notify handler validation failed:
|
|
200
|
+
- ${problems.join("\n- ")}`);
|
|
201
|
+
}
|
|
202
|
+
problems.forEach((problem) => logger.warn(`Notify handler validation: ${problem}`));
|
|
203
|
+
}
|
|
156
204
|
hasHandlersForEventType(eventType, filter, triggerResult) {
|
|
157
205
|
if (filter) {
|
|
158
206
|
switch (eventType) {
|
|
@@ -1812,12 +1860,23 @@ var resturaConfigSchema = z3.object({
|
|
|
1812
1860
|
customApiFolderPath: z3.string().default(process.cwd() + customApiFolderPath),
|
|
1813
1861
|
generatedTypesPath: z3.string().default(process.cwd() + "/src/@types"),
|
|
1814
1862
|
fileTempCachePath: z3.string().optional(),
|
|
1815
|
-
scratchDatabaseSuffix: z3.string().optional()
|
|
1863
|
+
scratchDatabaseSuffix: z3.string().optional(),
|
|
1864
|
+
eventDelivery: z3.enum(["direct", "outbox"]).default("direct"),
|
|
1865
|
+
eventOutbox: z3.object({
|
|
1866
|
+
channel: z3.string().default("restura_outbox"),
|
|
1867
|
+
pollIntervalMs: z3.number().default(15e3),
|
|
1868
|
+
batchSize: z3.number().default(50),
|
|
1869
|
+
maxAttempts: z3.number().default(5),
|
|
1870
|
+
pruneAfterDays: z3.number().default(7)
|
|
1871
|
+
}).prefault({}),
|
|
1872
|
+
notifyValidation: z3.enum(["off", "warn", "strict"]).default("warn"),
|
|
1873
|
+
queryMetadataKeys: z3.union([z3.literal("ALL"), z3.array(z3.string())]).optional()
|
|
1816
1874
|
});
|
|
1817
1875
|
|
|
1818
|
-
// src/restura/sql/
|
|
1819
|
-
import
|
|
1820
|
-
import
|
|
1876
|
+
// src/restura/sql/PsqlConnection.ts
|
|
1877
|
+
import crypto from "crypto";
|
|
1878
|
+
import { format as sqlFormat } from "sql-formatter";
|
|
1879
|
+
import { z as z4 } from "zod";
|
|
1821
1880
|
|
|
1822
1881
|
// src/restura/sql/PsqlUtils.ts
|
|
1823
1882
|
import format from "pg-format";
|
|
@@ -1908,6 +1967,140 @@ function toSqlLiteral(value) {
|
|
|
1908
1967
|
return format.literal(value);
|
|
1909
1968
|
}
|
|
1910
1969
|
|
|
1970
|
+
// src/restura/sql/PsqlConnection.ts
|
|
1971
|
+
var DEFAULT_QUERY_METADATA_KEYS = [
|
|
1972
|
+
"userId",
|
|
1973
|
+
"adminUserId",
|
|
1974
|
+
"isSystemUser",
|
|
1975
|
+
"role",
|
|
1976
|
+
"host",
|
|
1977
|
+
"ipAddress",
|
|
1978
|
+
"storeId",
|
|
1979
|
+
"storeCustomerId",
|
|
1980
|
+
"appTokenId",
|
|
1981
|
+
"requestId"
|
|
1982
|
+
];
|
|
1983
|
+
var PsqlConnection = class _PsqlConnection {
|
|
1984
|
+
static queryMetadataKeys = DEFAULT_QUERY_METADATA_KEYS;
|
|
1985
|
+
static setQueryMetadataKeys(keys) {
|
|
1986
|
+
_PsqlConnection.queryMetadataKeys = keys;
|
|
1987
|
+
}
|
|
1988
|
+
instanceId;
|
|
1989
|
+
constructor(instanceId) {
|
|
1990
|
+
this.instanceId = instanceId || crypto.randomUUID();
|
|
1991
|
+
}
|
|
1992
|
+
buildQueryMetadata(requesterDetails) {
|
|
1993
|
+
if (_PsqlConnection.queryMetadataKeys === "ALL") {
|
|
1994
|
+
return { connectionInstanceId: this.instanceId, ...requesterDetails };
|
|
1995
|
+
}
|
|
1996
|
+
const meta = { connectionInstanceId: this.instanceId };
|
|
1997
|
+
const details = requesterDetails ?? {};
|
|
1998
|
+
for (const key of _PsqlConnection.queryMetadataKeys) {
|
|
1999
|
+
if (details[key] !== void 0) meta[key] = details[key];
|
|
2000
|
+
}
|
|
2001
|
+
return meta;
|
|
2002
|
+
}
|
|
2003
|
+
async queryOne(query, options, requesterDetails) {
|
|
2004
|
+
const formattedQuery = questionMarksToOrderedParams(query);
|
|
2005
|
+
const meta = this.buildQueryMetadata(requesterDetails);
|
|
2006
|
+
const queryMetadata = `--QUERY_METADATA(${JSON.stringify(meta)})
|
|
2007
|
+
`;
|
|
2008
|
+
const startTime = process.hrtime();
|
|
2009
|
+
try {
|
|
2010
|
+
const response = await this.query(queryMetadata + formattedQuery, options);
|
|
2011
|
+
if (response.rows.length === 0) throw new RsError("NOT_FOUND", "No results found");
|
|
2012
|
+
else if (response.rows.length > 1) throw new RsError("DUPLICATE", "More than one result found");
|
|
2013
|
+
this.logSqlStatement(formattedQuery, options, meta, startTime);
|
|
2014
|
+
return response.rows[0];
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
this.logSqlStatement(formattedQuery, options, meta, startTime);
|
|
2017
|
+
if (RsError.isRsError(error)) throw error;
|
|
2018
|
+
if (error?.routine === "_bt_check_unique") {
|
|
2019
|
+
throw new RsError("DUPLICATE", error.message);
|
|
2020
|
+
}
|
|
2021
|
+
throw new RsError("DATABASE_ERROR", `${error.message}`);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
async queryOneSchema(query, params, requesterDetails, zodSchema) {
|
|
2025
|
+
const result = await this.queryOne(query, params, requesterDetails);
|
|
2026
|
+
try {
|
|
2027
|
+
return zodSchema.parse(result);
|
|
2028
|
+
} catch (error) {
|
|
2029
|
+
if (error instanceof z4.ZodError) {
|
|
2030
|
+
logger.error("Invalid data returned from database:");
|
|
2031
|
+
logger.trace("\n" + JSON.stringify(result, null, 2));
|
|
2032
|
+
logger.error("\n" + z4.prettifyError(error));
|
|
2033
|
+
} else {
|
|
2034
|
+
logger.error(error);
|
|
2035
|
+
}
|
|
2036
|
+
throw new RsError("DATABASE_ERROR", `Invalid data returned from database`);
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
async runQuery(query, options, requesterDetails) {
|
|
2040
|
+
const formattedQuery = questionMarksToOrderedParams(query);
|
|
2041
|
+
const meta = this.buildQueryMetadata(requesterDetails);
|
|
2042
|
+
const queryMetadata = `--QUERY_METADATA(${JSON.stringify(meta)})
|
|
2043
|
+
`;
|
|
2044
|
+
const startTime = process.hrtime();
|
|
2045
|
+
try {
|
|
2046
|
+
const response = await this.query(queryMetadata + formattedQuery, options);
|
|
2047
|
+
this.logSqlStatement(formattedQuery, options, meta, startTime);
|
|
2048
|
+
return response.rows;
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
this.logSqlStatement(formattedQuery, options, meta, startTime);
|
|
2051
|
+
if (error?.routine === "_bt_check_unique") {
|
|
2052
|
+
throw new RsError("DUPLICATE", error.message);
|
|
2053
|
+
}
|
|
2054
|
+
throw new RsError("DATABASE_ERROR", `${error.message}`);
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
async runQuerySchema(query, params, requesterDetails, zodSchema) {
|
|
2058
|
+
const result = await this.runQuery(query, params, requesterDetails);
|
|
2059
|
+
try {
|
|
2060
|
+
return z4.array(zodSchema).parse(result);
|
|
2061
|
+
} catch (error) {
|
|
2062
|
+
if (error instanceof z4.ZodError) {
|
|
2063
|
+
logger.error("Invalid data returned from database:");
|
|
2064
|
+
logger.trace("\n" + JSON.stringify(result, null, 2));
|
|
2065
|
+
logger.error("\n" + z4.prettifyError(error));
|
|
2066
|
+
} else {
|
|
2067
|
+
logger.error(error);
|
|
2068
|
+
}
|
|
2069
|
+
throw new RsError("DATABASE_ERROR", `Invalid data returned from database`);
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
logSqlStatement(query, options, queryMetadata, startTime, prefix = "") {
|
|
2073
|
+
if (logger.level !== "trace") return;
|
|
2074
|
+
const sqlStatement = query.replace(/\$(\d+)/g, (_, num) => {
|
|
2075
|
+
const paramIndex = parseInt(num) - 1;
|
|
2076
|
+
if (paramIndex >= options.length) return "INVALID_PARAM_INDEX";
|
|
2077
|
+
return toSqlLiteral(options[paramIndex]);
|
|
2078
|
+
});
|
|
2079
|
+
const formattedSql = sqlFormat(sqlStatement, {
|
|
2080
|
+
language: "postgresql",
|
|
2081
|
+
linesBetweenQueries: 2,
|
|
2082
|
+
indentStyle: "standard",
|
|
2083
|
+
keywordCase: "upper",
|
|
2084
|
+
useTabs: true,
|
|
2085
|
+
tabWidth: 4
|
|
2086
|
+
});
|
|
2087
|
+
const [seconds, nanoseconds] = process.hrtime(startTime);
|
|
2088
|
+
const durationMs = seconds * 1e3 + nanoseconds / 1e6;
|
|
2089
|
+
let initiator = "Anonymous";
|
|
2090
|
+
const initiatorId = queryMetadata.userId ?? queryMetadata.adminUserId;
|
|
2091
|
+
if (initiatorId) initiator = `User Id (${initiatorId.toString()})`;
|
|
2092
|
+
if ("isSystemUser" in queryMetadata && queryMetadata.isSystemUser) initiator = "SYSTEM";
|
|
2093
|
+
logger.trace(`${prefix}query by ${initiator}, Query ->
|
|
2094
|
+
${formattedSql}`, {
|
|
2095
|
+
durationMs
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
|
|
2100
|
+
// src/restura/sql/PsqlEngine.ts
|
|
2101
|
+
import { ObjectUtils as ObjectUtils3 } from "@redskytech/core-utils";
|
|
2102
|
+
import pg4 from "pg";
|
|
2103
|
+
|
|
1911
2104
|
// src/restura/sql/SqlEngine.ts
|
|
1912
2105
|
import { ObjectUtils as ObjectUtils2 } from "@redskytech/core-utils";
|
|
1913
2106
|
var SqlEngine = class {
|
|
@@ -2037,893 +2230,931 @@ var SqlEngine = class {
|
|
|
2037
2230
|
}
|
|
2038
2231
|
};
|
|
2039
2232
|
|
|
2040
|
-
// src/restura/sql/
|
|
2041
|
-
import
|
|
2042
|
-
var
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
} else {
|
|
2058
|
-
result += str[i];
|
|
2059
|
-
}
|
|
2060
|
-
} else {
|
|
2061
|
-
result += str[i];
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2064
|
-
return result;
|
|
2233
|
+
// src/restura/sql/PsqlTransaction.ts
|
|
2234
|
+
import pg from "pg";
|
|
2235
|
+
var { Client } = pg;
|
|
2236
|
+
var PsqlTransaction = class extends PsqlConnection {
|
|
2237
|
+
constructor(clientConfig, instanceId) {
|
|
2238
|
+
super(instanceId);
|
|
2239
|
+
this.clientConfig = clientConfig;
|
|
2240
|
+
this.client = new Client(clientConfig);
|
|
2241
|
+
this.connectPromise = this.client.connect();
|
|
2242
|
+
this.beginTransactionPromise = this.beginTransaction();
|
|
2243
|
+
}
|
|
2244
|
+
client;
|
|
2245
|
+
beginTransactionPromise;
|
|
2246
|
+
connectPromise;
|
|
2247
|
+
async close() {
|
|
2248
|
+
if (this.client) {
|
|
2249
|
+
await this.client.end();
|
|
2065
2250
|
}
|
|
2251
|
+
}
|
|
2252
|
+
async beginTransaction() {
|
|
2253
|
+
await this.connectPromise;
|
|
2254
|
+
return this.client.query("BEGIN");
|
|
2255
|
+
}
|
|
2256
|
+
async rollback() {
|
|
2257
|
+
return this.query("ROLLBACK");
|
|
2258
|
+
}
|
|
2259
|
+
async commit() {
|
|
2260
|
+
return this.query("COMMIT");
|
|
2261
|
+
}
|
|
2262
|
+
async release() {
|
|
2263
|
+
return this.client.end();
|
|
2264
|
+
}
|
|
2265
|
+
async query(query, values) {
|
|
2266
|
+
await this.connectPromise;
|
|
2267
|
+
await this.beginTransactionPromise;
|
|
2268
|
+
return this.client.query(query, values);
|
|
2269
|
+
}
|
|
2270
|
+
};
|
|
2066
2271
|
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
for (var i = 0; i < str.length; i++) {
|
|
2072
|
-
if (str[i] === '\\\\' && i + 1 < str.length && str[i + 1] === '|') {
|
|
2073
|
-
current += '|';
|
|
2074
|
-
i++;
|
|
2075
|
-
} else if (str[i] === '|') {
|
|
2076
|
-
values.push(unescapeValue(current));
|
|
2077
|
-
current = '';
|
|
2078
|
-
} else {
|
|
2079
|
-
current += str[i];
|
|
2080
|
-
}
|
|
2081
|
-
}
|
|
2082
|
-
if (current.length > 0) {
|
|
2083
|
-
values.push(unescapeValue(current));
|
|
2084
|
-
}
|
|
2085
|
-
return values;
|
|
2086
|
-
}
|
|
2272
|
+
// src/restura/sql/psqlSchemaUtils.ts
|
|
2273
|
+
import getDiff from "@wmfs/pg-diff-sync";
|
|
2274
|
+
import pgInfo from "@wmfs/pg-info";
|
|
2275
|
+
import pg3 from "pg";
|
|
2087
2276
|
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2277
|
+
// src/restura/sql/PsqlPool.ts
|
|
2278
|
+
import pg2 from "pg";
|
|
2279
|
+
var { Pool } = pg2;
|
|
2280
|
+
var PsqlPool = class extends PsqlConnection {
|
|
2281
|
+
constructor(poolConfig) {
|
|
2282
|
+
super();
|
|
2283
|
+
this.poolConfig = poolConfig;
|
|
2284
|
+
if (poolConfig.connectionString) {
|
|
2285
|
+
let url;
|
|
2286
|
+
try {
|
|
2287
|
+
url = new URL(poolConfig.connectionString);
|
|
2288
|
+
} catch {
|
|
2289
|
+
throw new Error(`Invalid connectionString: ${poolConfig.connectionString}`);
|
|
2290
|
+
}
|
|
2291
|
+
poolConfig.host = url.hostname;
|
|
2292
|
+
poolConfig.port = url.port ? parseInt(url.port) : 5432;
|
|
2293
|
+
poolConfig.user = url.username;
|
|
2294
|
+
poolConfig.password = url.password;
|
|
2295
|
+
poolConfig.database = url.pathname.replace(/^\//, "");
|
|
2093
2296
|
}
|
|
2297
|
+
this.pool = new Pool(poolConfig);
|
|
2298
|
+
this.queryOne("SELECT NOW();", [], {
|
|
2299
|
+
isSystemUser: true,
|
|
2300
|
+
role: "",
|
|
2301
|
+
host: "localhost",
|
|
2302
|
+
ipAddress: "",
|
|
2303
|
+
scopes: []
|
|
2304
|
+
}).then(() => {
|
|
2305
|
+
logger.info("Connected to PostgreSQL database");
|
|
2306
|
+
}).catch((error) => {
|
|
2307
|
+
logger.error("Error connecting to database", error);
|
|
2308
|
+
process.exit(1);
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
pool;
|
|
2312
|
+
async query(query, values) {
|
|
2313
|
+
return this.pool.query(query, values);
|
|
2314
|
+
}
|
|
2315
|
+
};
|
|
2094
2316
|
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2317
|
+
// src/restura/sql/psqlSchemaUtils.ts
|
|
2318
|
+
var { Client: Client2 } = pg3;
|
|
2319
|
+
var systemUser = {
|
|
2320
|
+
role: "",
|
|
2321
|
+
scopes: [],
|
|
2322
|
+
host: "",
|
|
2323
|
+
ipAddress: "",
|
|
2324
|
+
isSystemUser: true
|
|
2325
|
+
};
|
|
2326
|
+
function schemaToPsqlType(column) {
|
|
2327
|
+
if (column.hasAutoIncrement) return "BIGSERIAL";
|
|
2328
|
+
if (column.type === "ENUM") return "TEXT";
|
|
2329
|
+
if (column.type === "DATETIME") return "TIMESTAMPTZ";
|
|
2330
|
+
if (column.type === "MEDIUMINT") return "INT";
|
|
2331
|
+
return column.type;
|
|
2332
|
+
}
|
|
2333
|
+
var OUTBOX_TABLE_NAME = "dbEventOutbox";
|
|
2334
|
+
var DEFAULT_OUTBOX_CHANNEL = "restura_outbox";
|
|
2335
|
+
var SENSITIVE_COLUMN_PATTERN = /password|token|secret|credential|guid|key$/i;
|
|
2336
|
+
function isSensitiveColumnName(columnName) {
|
|
2337
|
+
return SENSITIVE_COLUMN_PATTERN.test(columnName);
|
|
2338
|
+
}
|
|
2339
|
+
function createOutboxTableSql() {
|
|
2340
|
+
return `
|
|
2341
|
+
CREATE TABLE IF NOT EXISTS "${OUTBOX_TABLE_NAME}"
|
|
2342
|
+
(
|
|
2343
|
+
"id" BIGSERIAL PRIMARY KEY,
|
|
2344
|
+
"createdOn" TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
2345
|
+
"tableName" TEXT NOT NULL,
|
|
2346
|
+
"operation" TEXT NOT NULL,
|
|
2347
|
+
"recordId" BIGINT NULL,
|
|
2348
|
+
"record" JSONB NULL,
|
|
2349
|
+
"previousRecord" JSONB NULL,
|
|
2350
|
+
"queryMetadata" JSONB NULL,
|
|
2351
|
+
"processedOn" TIMESTAMPTZ NULL,
|
|
2352
|
+
"attempts" INT NOT NULL DEFAULT 0,
|
|
2353
|
+
"nextAttemptOn" TIMESTAMPTZ NULL,
|
|
2354
|
+
"isDeadLetter" BOOLEAN NOT NULL DEFAULT FALSE
|
|
2355
|
+
);
|
|
2356
|
+
CREATE INDEX IF NOT EXISTS "${OUTBOX_TABLE_NAME}_unprocessed_index" ON "${OUTBOX_TABLE_NAME}" ("id") WHERE "processedOn" IS NULL AND "isDeadLetter" = FALSE;
|
|
2357
|
+
CREATE INDEX IF NOT EXISTS "${OUTBOX_TABLE_NAME}_processedOn_index" ON "${OUTBOX_TABLE_NAME}" ("processedOn") WHERE "processedOn" IS NOT NULL;
|
|
2358
|
+
`;
|
|
2359
|
+
}
|
|
2360
|
+
function resolveNotifyColumns(tableName, notify, tableColumns) {
|
|
2361
|
+
if (!notify) return [];
|
|
2362
|
+
if (notify === "ALL") {
|
|
2363
|
+
if (!tableColumns) {
|
|
2364
|
+
throw new Error(
|
|
2365
|
+
`notify: "ALL" on table "${tableName}" requires tableColumns so the sensitive-column denylist can be applied. Pass options.tableColumns or list columns explicitly.`
|
|
2366
|
+
);
|
|
2118
2367
|
}
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
if (col.isJsonField) {
|
|
2128
|
-
return '(' + col.sql + ')::' + col.cast;
|
|
2129
|
-
}
|
|
2130
|
-
return col.sql + '::' + col.cast;
|
|
2368
|
+
return tableColumns.filter((column) => !isSensitiveColumnName(column));
|
|
2369
|
+
}
|
|
2370
|
+
return notify.map((entry) => {
|
|
2371
|
+
if (entry.startsWith("!")) return entry.slice(1);
|
|
2372
|
+
if (isSensitiveColumnName(entry)) {
|
|
2373
|
+
throw new Error(
|
|
2374
|
+
`Refusing to include sensitive column "${tableName}"."${entry}" in notify trigger payloads. Remove it from the notify list or prefix it with '!' to force-include it.`
|
|
2375
|
+
);
|
|
2131
2376
|
}
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
{
|
|
2135
|
-
${initializers}
|
|
2377
|
+
return entry;
|
|
2378
|
+
});
|
|
2136
2379
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2380
|
+
function sqlStringLiteral(value) {
|
|
2381
|
+
return value.replace(/'/g, "''");
|
|
2382
|
+
}
|
|
2383
|
+
function buildRowJson(rowVariable, columns) {
|
|
2384
|
+
return `jsonb_build_object(
|
|
2385
|
+
${columns.map((column) => `'${sqlStringLiteral(column)}', ${rowVariable}."${column}"`).join(",\n ")}
|
|
2386
|
+
)`;
|
|
2387
|
+
}
|
|
2388
|
+
var QUERY_METADATA_DECLARE_BLOCK = `
|
|
2389
|
+
SELECT INTO query_metadata
|
|
2390
|
+
(regexp_match(
|
|
2391
|
+
current_query(),
|
|
2392
|
+
'^--QUERY_METADATA\\(({.*})', 'n'
|
|
2393
|
+
))[1]::json;
|
|
2141
2394
|
`;
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
=
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
OldNegate
|
|
2160
|
-
= "!"
|
|
2161
|
-
|
|
2162
|
-
OldOperator
|
|
2163
|
-
= "and"i / "or"i
|
|
2164
|
-
|
|
2165
|
-
OldColumn
|
|
2166
|
-
= first:OldColumnPart rest:("." OldColumnPart)* {
|
|
2167
|
-
const partsArray = [first];
|
|
2168
|
-
if (rest && rest.length > 0) {
|
|
2169
|
-
partsArray.push(...rest.map(item => item[1]));
|
|
2170
|
-
}
|
|
2171
|
-
|
|
2172
|
-
if (partsArray.length > 3) {
|
|
2173
|
-
throw new SyntaxError('Column path cannot have more than 3 parts (table.column.jsonField)');
|
|
2174
|
-
}
|
|
2175
|
-
|
|
2176
|
-
if (partsArray.length === 1) {
|
|
2177
|
-
return quoteSqlIdentity(partsArray[0]);
|
|
2178
|
-
}
|
|
2179
|
-
const tableName = quoteSqlIdentity(partsArray[0]);
|
|
2180
|
-
|
|
2181
|
-
// If we only have two parts (table.column), use regular dot notation
|
|
2182
|
-
if (partsArray.length === 2) {
|
|
2183
|
-
return tableName + "." + quoteSqlIdentity(partsArray[1]);
|
|
2184
|
-
}
|
|
2185
|
-
|
|
2186
|
-
// For JSON paths (more than 2 parts), first part is a column, last part uses ->>
|
|
2187
|
-
const jsonColumn = quoteSqlIdentity(partsArray[1]);
|
|
2188
|
-
const lastPart = partsArray[partsArray.length - 1];
|
|
2189
|
-
const escapedLast = lastPart.replace(/'/g, "''");
|
|
2190
|
-
const result = tableName + "." + jsonColumn + "->>'" + escapedLast + "'";
|
|
2191
|
-
return result;
|
|
2192
|
-
}
|
|
2395
|
+
function buildTriggerFunctionSql(tableName, operation, notify, options) {
|
|
2396
|
+
if (!notify) return "";
|
|
2397
|
+
const columns = resolveNotifyColumns(tableName, notify, options?.tableColumns);
|
|
2398
|
+
const delivery = options?.delivery || "direct";
|
|
2399
|
+
const channel = options?.channel || DEFAULT_OUTBOX_CHANNEL;
|
|
2400
|
+
const tableNameLiteral = sqlStringLiteral(tableName);
|
|
2401
|
+
const channelLiteral = sqlStringLiteral(channel);
|
|
2402
|
+
const functionName = `notify_${tableName}_${operation}`;
|
|
2403
|
+
const rowVariable = operation === "delete" ? "OLD" : "NEW";
|
|
2404
|
+
let body;
|
|
2405
|
+
if (delivery === "outbox") {
|
|
2406
|
+
const recordJson = operation === "delete" ? "NULL" : buildRowJson("NEW", columns);
|
|
2407
|
+
const previousRecordJson = operation === "insert" ? "NULL" : buildRowJson("OLD", columns);
|
|
2408
|
+
body = ` INSERT INTO "${OUTBOX_TABLE_NAME}" ("tableName", "operation", "recordId", "record", "previousRecord", "queryMetadata")
|
|
2409
|
+
VALUES ('${tableNameLiteral}', '${operation.toUpperCase()}', ${rowVariable}.id, ${recordJson}, ${previousRecordJson}, query_metadata::jsonb)
|
|
2410
|
+
RETURNING "id" INTO outbox_id;
|
|
2193
2411
|
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
}
|
|
2412
|
+
PERFORM pg_notify('${channelLiteral}', outbox_id::text);`;
|
|
2413
|
+
} else {
|
|
2414
|
+
const idField = operation === "insert" ? `'insertedId', NEW.id` : operation === "update" ? `'changedId', NEW.id` : `'deletedId', OLD.id`;
|
|
2415
|
+
const payloadFields = [`'table', '${tableNameLiteral}'`, `'queryMetadata', query_metadata`, idField];
|
|
2416
|
+
if (operation !== "delete") payloadFields.push(`'record', ${buildRowJson("NEW", columns)}`);
|
|
2417
|
+
if (operation !== "insert") payloadFields.push(`'previousRecord', ${buildRowJson("OLD", columns)}`);
|
|
2418
|
+
body = ` PERFORM pg_notify(
|
|
2419
|
+
'${operation}',
|
|
2420
|
+
json_build_object(
|
|
2421
|
+
${payloadFields.join(",\n ")}
|
|
2422
|
+
)::text
|
|
2423
|
+
);`;
|
|
2424
|
+
}
|
|
2425
|
+
const outboxDeclare = delivery === "outbox" ? "\n outbox_id BIGINT;" : "";
|
|
2426
|
+
const legacyDrop = operation === "update" && tableName !== tableName.toLowerCase() ? `DROP TRIGGER IF EXISTS ${tableName}_update ON "${tableName}";
|
|
2427
|
+
` : "";
|
|
2428
|
+
const updateGuard = operation === "update" ? "\n WHEN (OLD.* IS DISTINCT FROM NEW.*)" : "";
|
|
2429
|
+
return `
|
|
2430
|
+
CREATE OR REPLACE FUNCTION ${functionName}()
|
|
2431
|
+
RETURNS TRIGGER AS $$
|
|
2432
|
+
DECLARE
|
|
2433
|
+
query_metadata JSON;${outboxDeclare}
|
|
2434
|
+
BEGIN
|
|
2435
|
+
${QUERY_METADATA_DECLARE_BLOCK}
|
|
2436
|
+
${body}
|
|
2198
2437
|
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
}
|
|
2438
|
+
RETURN ${rowVariable};
|
|
2439
|
+
END;
|
|
2440
|
+
$$ LANGUAGE plpgsql;
|
|
2203
2441
|
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2442
|
+
${legacyDrop}CREATE OR REPLACE TRIGGER "${tableName}_${operation}"
|
|
2443
|
+
AFTER ${operation.toUpperCase()} ON "${tableName}"
|
|
2444
|
+
FOR EACH ROW${updateGuard}
|
|
2445
|
+
EXECUTE FUNCTION ${functionName}();
|
|
2446
|
+
`;
|
|
2447
|
+
}
|
|
2448
|
+
function createInsertTriggerSql(tableName, notify, options) {
|
|
2449
|
+
return buildTriggerFunctionSql(tableName, "insert", notify, options);
|
|
2450
|
+
}
|
|
2451
|
+
function createUpdateTriggerSql(tableName, notify, options) {
|
|
2452
|
+
return buildTriggerFunctionSql(tableName, "update", notify, options);
|
|
2453
|
+
}
|
|
2454
|
+
function createDeleteTriggerSql(tableName, notify, options) {
|
|
2455
|
+
return buildTriggerFunctionSql(tableName, "delete", notify, options);
|
|
2456
|
+
}
|
|
2457
|
+
function generateNotifyTriggersSql(schema, options) {
|
|
2458
|
+
const statements = [];
|
|
2459
|
+
const hasNotifyTables = schema.database.some((table) => table.notify);
|
|
2460
|
+
if (options?.eventDelivery === "outbox" && hasNotifyTables) {
|
|
2461
|
+
statements.push(createOutboxTableSql());
|
|
2462
|
+
}
|
|
2463
|
+
for (const table of schema.database) {
|
|
2464
|
+
if (!table.notify) continue;
|
|
2465
|
+
const triggerOptions = {
|
|
2466
|
+
delivery: options?.eventDelivery,
|
|
2467
|
+
channel: options?.outboxChannel,
|
|
2468
|
+
tableColumns: table.columns.map((column) => column.name)
|
|
2469
|
+
};
|
|
2470
|
+
statements.push(createInsertTriggerSql(table.name, table.notify, triggerOptions));
|
|
2471
|
+
statements.push(createUpdateTriggerSql(table.name, table.notify, triggerOptions));
|
|
2472
|
+
statements.push(createDeleteTriggerSql(table.name, table.notify, triggerOptions));
|
|
2473
|
+
}
|
|
2474
|
+
return statements;
|
|
2475
|
+
}
|
|
2476
|
+
function generateDatabaseSchemaFromSchema(schema, options) {
|
|
2477
|
+
const sqlStatements = [];
|
|
2478
|
+
const indexes = [];
|
|
2479
|
+
const triggers = generateNotifyTriggersSql(schema, options);
|
|
2480
|
+
for (const table of schema.database) {
|
|
2481
|
+
let sql = `CREATE TABLE "${table.name}"
|
|
2482
|
+
( `;
|
|
2483
|
+
const tableColumns = [];
|
|
2484
|
+
for (const column of table.columns) {
|
|
2485
|
+
let columnSql = "";
|
|
2486
|
+
columnSql += ` "${column.name}" ${schemaToPsqlType(column)}`;
|
|
2487
|
+
let value = column.value;
|
|
2488
|
+
if (column.type === "JSON") value = "";
|
|
2489
|
+
if (column.type === "JSONB") value = "";
|
|
2490
|
+
if (column.type === "DECIMAL" && value) {
|
|
2491
|
+
value = value.replace("-", ",").replace(/['"]/g, "");
|
|
2492
|
+
}
|
|
2493
|
+
if (value && column.type !== "ENUM") {
|
|
2494
|
+
columnSql += `(${value})`;
|
|
2495
|
+
} else if (column.length) columnSql += `(${column.length})`;
|
|
2496
|
+
if (column.isPrimary) {
|
|
2497
|
+
columnSql += " PRIMARY KEY ";
|
|
2498
|
+
}
|
|
2499
|
+
if (column.isUnique) {
|
|
2500
|
+
columnSql += ` CONSTRAINT "${table.name}_${column.name}_unique_index" UNIQUE `;
|
|
2501
|
+
}
|
|
2502
|
+
if (column.isNullable) columnSql += " NULL";
|
|
2503
|
+
else columnSql += " NOT NULL";
|
|
2504
|
+
if (column.default) columnSql += ` DEFAULT ${column.default}`;
|
|
2505
|
+
if (value && column.type === "ENUM") {
|
|
2506
|
+
columnSql += ` CHECK ("${column.name}" IN (${value}))`;
|
|
2507
|
+
}
|
|
2508
|
+
tableColumns.push(columnSql);
|
|
2207
2509
|
}
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
OldValue
|
|
2221
|
-
= "value" _ ":" value:OldText {
|
|
2222
|
-
return value;
|
|
2510
|
+
sql += tableColumns.join(", \n");
|
|
2511
|
+
for (const index of table.indexes) {
|
|
2512
|
+
if (!index.isPrimaryKey) {
|
|
2513
|
+
let unique = " ";
|
|
2514
|
+
if (index.isUnique) unique = "UNIQUE ";
|
|
2515
|
+
let indexSQL = ` CREATE ${unique}INDEX "${index.name}" ON "${table.name}"`;
|
|
2516
|
+
indexSQL += ` (${index.columns.map((item) => `"${item}" ${index.order}`).join(", ")})`;
|
|
2517
|
+
indexSQL += index.where ? ` WHERE ${index.where}` : "";
|
|
2518
|
+
indexSQL += ";";
|
|
2519
|
+
indexes.push(indexSQL);
|
|
2520
|
+
}
|
|
2223
2521
|
}
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
/ SimpleExpr
|
|
2238
|
-
|
|
2239
|
-
SimpleExprList
|
|
2240
|
-
= left:SimpleExpr _ op:("and"i / "or"i) _ right:SimpleExprList
|
|
2241
|
-
{ return left + ' ' + op.toUpperCase() + ' ' + right; }
|
|
2242
|
-
/ SimpleExpr
|
|
2243
|
-
|
|
2244
|
-
SimpleExpr
|
|
2245
|
-
= negate:"!"? _ "(" _ col:Column _ "," _ op:OperatorWithValue _ ")" _
|
|
2246
|
-
{ return (negate ? 'NOT ' : '') + '(' + op(col) + ')'; }
|
|
2247
|
-
/ negate:"!"? _ "(" _ col:Column _ "," _ op:NullOperator _ ")" _
|
|
2248
|
-
{ return (negate ? 'NOT ' : '') + '(' + op(col) + ')'; }
|
|
2249
|
-
/ negate:"!"? _ "(" _ col:Column _ "," _ val:CastedValue _ ")" _
|
|
2250
|
-
{ return (negate ? 'NOT ' : '') + '(' + formatColumn(col) + ' = ' + formatValueWithCast(val.value, val.cast) + ')'; }
|
|
2251
|
-
|
|
2252
|
-
Column
|
|
2253
|
-
= first:ColPart rest:("." ColPart)* cast:TypeCast? {
|
|
2254
|
-
const partsArray = [first];
|
|
2255
|
-
if (rest && rest.length > 0) {
|
|
2256
|
-
partsArray.push(...rest.map(item => item[1]));
|
|
2257
|
-
}
|
|
2258
|
-
|
|
2259
|
-
if (partsArray.length > 3) {
|
|
2260
|
-
throw new SyntaxError('Column path cannot have more than 3 parts (table.column.jsonField)');
|
|
2261
|
-
}
|
|
2262
|
-
|
|
2263
|
-
var sql;
|
|
2264
|
-
var isJsonField = false;
|
|
2265
|
-
if (partsArray.length === 1) {
|
|
2266
|
-
sql = quoteSqlIdentity(partsArray[0]);
|
|
2267
|
-
} else {
|
|
2268
|
-
const tableName = quoteSqlIdentity(partsArray[0]);
|
|
2269
|
-
|
|
2270
|
-
if (partsArray.length === 2) {
|
|
2271
|
-
sql = tableName + '.' + quoteSqlIdentity(partsArray[1]);
|
|
2272
|
-
} else {
|
|
2273
|
-
const jsonColumn = quoteSqlIdentity(partsArray[1]);
|
|
2274
|
-
const lastPart = partsArray[partsArray.length - 1];
|
|
2275
|
-
const escapedLast = lastPart.replace(/'/g, "''");
|
|
2276
|
-
sql = tableName + '.' + jsonColumn + "->>'" + escapedLast + "'";
|
|
2277
|
-
isJsonField = true;
|
|
2278
|
-
}
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
return { sql: sql, cast: cast, isJsonField: isJsonField };
|
|
2522
|
+
sql += "\n);";
|
|
2523
|
+
sqlStatements.push(sql);
|
|
2524
|
+
}
|
|
2525
|
+
for (const table of schema.database) {
|
|
2526
|
+
if (!table.foreignKeys.length) continue;
|
|
2527
|
+
const sql = `ALTER TABLE "${table.name}" `;
|
|
2528
|
+
const constraints = [];
|
|
2529
|
+
for (const foreignKey of table.foreignKeys) {
|
|
2530
|
+
let constraint = ` ADD CONSTRAINT "${foreignKey.name}"
|
|
2531
|
+
FOREIGN KEY ("${foreignKey.column}") REFERENCES "${foreignKey.refTable}" ("${foreignKey.refColumn}")`;
|
|
2532
|
+
constraint += ` ON DELETE ${foreignKey.onDelete}`;
|
|
2533
|
+
constraint += ` ON UPDATE ${foreignKey.onUpdate}`;
|
|
2534
|
+
constraints.push(constraint);
|
|
2282
2535
|
}
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
= "in"i _ "," _ vals:InValueList cast:TypeCast? { return function(col) {
|
|
2293
|
-
var formattedCol = formatColumn(col);
|
|
2294
|
-
var literals = vals.map(function(v) {
|
|
2295
|
-
var unescaped = unescapeValue(v);
|
|
2296
|
-
var formatted = formatValue(unescaped);
|
|
2297
|
-
return cast ? formatted + '::' + cast : formatted;
|
|
2298
|
-
});
|
|
2299
|
-
return formattedCol + ' IN (' + literals.join(', ') + ')';
|
|
2300
|
-
}; }
|
|
2301
|
-
/ "ne"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' <> ' + formatValueWithCast(val.value, val.cast); }; }
|
|
2302
|
-
/ "gte"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' >= ' + formatValueWithCast(val.value, val.cast); }; }
|
|
2303
|
-
/ "gt"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' > ' + formatValueWithCast(val.value, val.cast); }; }
|
|
2304
|
-
/ "lte"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' <= ' + formatValueWithCast(val.value, val.cast); }; }
|
|
2305
|
-
/ "lt"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' < ' + formatValueWithCast(val.value, val.cast); }; }
|
|
2306
|
-
/ "has"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal('%' + unescapeValue(val.value) + '%'); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
2307
|
-
/ "sw"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal(unescapeValue(val.value) + '%'); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
2308
|
-
/ "ew"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal('%' + unescapeValue(val.value)); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
2309
|
-
|
|
2310
|
-
InValueList
|
|
2311
|
-
= first:InValue rest:("|" InValue)* {
|
|
2312
|
-
var values = [first];
|
|
2313
|
-
for (var i = 0; i < rest.length; i++) {
|
|
2314
|
-
values.push(rest[i][1]);
|
|
2315
|
-
}
|
|
2316
|
-
return values;
|
|
2536
|
+
sqlStatements.push(sql + constraints.join(",\n") + ";");
|
|
2537
|
+
}
|
|
2538
|
+
for (const table of schema.database) {
|
|
2539
|
+
if (!table.checkConstraints.length) continue;
|
|
2540
|
+
const sql = `ALTER TABLE "${table.name}" `;
|
|
2541
|
+
const constraints = [];
|
|
2542
|
+
for (const check of table.checkConstraints) {
|
|
2543
|
+
const constraint = `ADD CONSTRAINT "${check.name}" CHECK (${check.check})`;
|
|
2544
|
+
constraints.push(constraint);
|
|
2317
2545
|
}
|
|
2546
|
+
sqlStatements.push(sql + constraints.join(",\n") + ";");
|
|
2547
|
+
}
|
|
2548
|
+
sqlStatements.push(indexes.join("\n"));
|
|
2549
|
+
sqlStatements.push(triggers.join("\n"));
|
|
2550
|
+
return sqlStatements.join("\n\n");
|
|
2551
|
+
}
|
|
2552
|
+
async function getNewPublicSchemaAndScratchPool(targetPool, scratchDbName) {
|
|
2553
|
+
const scratchDbExists = await targetPool.runQuery(
|
|
2554
|
+
`SELECT * FROM pg_database WHERE datname = ?;`,
|
|
2555
|
+
[scratchDbName],
|
|
2556
|
+
systemUser
|
|
2557
|
+
);
|
|
2558
|
+
if (scratchDbExists.length === 0) {
|
|
2559
|
+
await targetPool.runQuery(`CREATE DATABASE ${escapeColumnName(scratchDbName)};`, [], systemUser);
|
|
2560
|
+
}
|
|
2561
|
+
const scratchPool = new PsqlPool({
|
|
2562
|
+
host: targetPool.poolConfig.host,
|
|
2563
|
+
port: targetPool.poolConfig.port,
|
|
2564
|
+
user: targetPool.poolConfig.user,
|
|
2565
|
+
database: scratchDbName,
|
|
2566
|
+
password: targetPool.poolConfig.password,
|
|
2567
|
+
max: targetPool.poolConfig.max,
|
|
2568
|
+
idleTimeoutMillis: targetPool.poolConfig.idleTimeoutMillis,
|
|
2569
|
+
connectionTimeoutMillis: targetPool.poolConfig.connectionTimeoutMillis
|
|
2570
|
+
});
|
|
2571
|
+
await scratchPool.runQuery(`DROP SCHEMA public CASCADE;`, [], systemUser);
|
|
2572
|
+
await scratchPool.runQuery(
|
|
2573
|
+
`CREATE SCHEMA public AUTHORIZATION ${escapeColumnName(targetPool.poolConfig.user)};`,
|
|
2574
|
+
[],
|
|
2575
|
+
systemUser
|
|
2576
|
+
);
|
|
2577
|
+
const schemaComment = await targetPool.runQuery(
|
|
2578
|
+
`
|
|
2579
|
+
SELECT pg_description.description
|
|
2580
|
+
FROM pg_description
|
|
2581
|
+
JOIN pg_namespace ON pg_namespace.oid = pg_description.objoid
|
|
2582
|
+
WHERE pg_namespace.nspname = 'public';`,
|
|
2583
|
+
[],
|
|
2584
|
+
systemUser
|
|
2585
|
+
);
|
|
2586
|
+
if (schemaComment[0]?.description) {
|
|
2587
|
+
const escaped = schemaComment[0].description.replace(/'/g, "''");
|
|
2588
|
+
await scratchPool.runQuery(`COMMENT ON SCHEMA public IS '${escaped}';`, [], systemUser);
|
|
2589
|
+
}
|
|
2590
|
+
return scratchPool;
|
|
2591
|
+
}
|
|
2592
|
+
async function diffDatabaseToSchema(schema, targetPool, scratchDbName, options) {
|
|
2593
|
+
let scratchPool;
|
|
2594
|
+
let originalClient;
|
|
2595
|
+
let scratchClient;
|
|
2596
|
+
try {
|
|
2597
|
+
scratchPool = await getNewPublicSchemaAndScratchPool(targetPool, scratchDbName);
|
|
2598
|
+
const sqlFullStatement = generateDatabaseSchemaFromSchema(schema, options);
|
|
2599
|
+
await scratchPool.runQuery(sqlFullStatement, [], systemUser);
|
|
2600
|
+
const connectionConfig = {
|
|
2601
|
+
host: targetPool.poolConfig.host,
|
|
2602
|
+
port: targetPool.poolConfig.port,
|
|
2603
|
+
user: targetPool.poolConfig.user,
|
|
2604
|
+
password: targetPool.poolConfig.password,
|
|
2605
|
+
ssl: targetPool.poolConfig.ssl
|
|
2606
|
+
};
|
|
2607
|
+
originalClient = new Client2({ ...connectionConfig, database: targetPool.poolConfig.database });
|
|
2608
|
+
scratchClient = new Client2({ ...connectionConfig, database: scratchDbName });
|
|
2609
|
+
await Promise.all([originalClient.connect(), scratchClient.connect()]);
|
|
2610
|
+
const [info1, info2] = await Promise.all([
|
|
2611
|
+
pgInfo({ client: originalClient }),
|
|
2612
|
+
pgInfo({ client: scratchClient })
|
|
2613
|
+
]);
|
|
2614
|
+
const diff = getDiff(info1, info2);
|
|
2615
|
+
return diff.join("\n");
|
|
2616
|
+
} finally {
|
|
2617
|
+
const cleanups = [];
|
|
2618
|
+
if (originalClient) cleanups.push(originalClient.end());
|
|
2619
|
+
if (scratchClient) cleanups.push(scratchClient.end());
|
|
2620
|
+
if (scratchPool) cleanups.push(scratchPool.pool.end());
|
|
2621
|
+
await Promise.allSettled(cleanups);
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2318
2624
|
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
=
|
|
2332
|
-
|
|
2333
|
-
CastedValueWithPipes
|
|
2334
|
-
= val:ValueWithPipes cast:TypeCast? { return { value: val, cast: cast }; }
|
|
2335
|
-
|
|
2336
|
-
TypeCast
|
|
2337
|
-
= "::" type:("timestamptz"i / "timestamp"i / "boolean"i / "numeric"i / "bigint"i / "text"i / "date"i / "int"i)
|
|
2338
|
-
{ return type.toLowerCase(); }
|
|
2339
|
-
|
|
2340
|
-
QuotedString
|
|
2341
|
-
= '"' chars:DoubleQuotedChar* '"' { return chars.join(''); }
|
|
2342
|
-
/ "'" chars:SingleQuotedChar* "'" { return chars.join(''); }
|
|
2343
|
-
|
|
2344
|
-
DoubleQuotedChar
|
|
2345
|
-
= '\\\\"' { return '"'; }
|
|
2346
|
-
/ '\\\\\\\\' { return '\\\\'; }
|
|
2347
|
-
/ [^"\\\\]
|
|
2348
|
-
|
|
2349
|
-
SingleQuotedChar
|
|
2350
|
-
= "\\\\'" { return "'"; }
|
|
2351
|
-
/ '\\\\\\\\' { return '\\\\'; }
|
|
2352
|
-
/ [^'\\\\]
|
|
2353
|
-
|
|
2354
|
-
Value
|
|
2355
|
-
= QuotedString
|
|
2356
|
-
/ chars:ValueChar+ { return chars.join(''); }
|
|
2357
|
-
|
|
2358
|
-
ValueChar
|
|
2359
|
-
= "\\\\\\\\" { return '\\\\\\\\'; }
|
|
2360
|
-
/ "\\\\," { return '\\\\,'; }
|
|
2361
|
-
/ "\\\\|" { return '\\\\|'; }
|
|
2362
|
-
/ [a-zA-Z0-9_\\-!#/@$%^&*+=<>?~.;'" ]
|
|
2363
|
-
/ c:":" !":" { return c; }
|
|
2364
|
-
|
|
2365
|
-
ValueWithPipes
|
|
2366
|
-
= QuotedString
|
|
2367
|
-
/ chars:ValueWithPipesChar+ { return chars.join(''); }
|
|
2368
|
-
|
|
2369
|
-
ValueWithPipesChar
|
|
2370
|
-
= "\\\\\\\\" { return '\\\\\\\\'; }
|
|
2371
|
-
/ "\\\\," { return '\\\\,'; }
|
|
2372
|
-
/ "\\\\|" { return '\\\\|'; }
|
|
2373
|
-
/ [a-zA-Z0-9_\\-!#/@$%^&*+=<>?~.;'" |]
|
|
2374
|
-
/ c:":" !":" { return c; }
|
|
2375
|
-
`;
|
|
2376
|
-
var fullGrammar = entryGrammar + oldGrammar + newGrammar;
|
|
2377
|
-
var filterPsqlParser = peg.generate(fullGrammar, {
|
|
2378
|
-
format: "commonjs",
|
|
2379
|
-
dependencies: { format: "pg-format" }
|
|
2380
|
-
});
|
|
2381
|
-
var filterPsqlParser_default = filterPsqlParser;
|
|
2382
|
-
|
|
2383
|
-
// src/restura/sql/psqlSchemaUtils.ts
|
|
2384
|
-
import getDiff from "@wmfs/pg-diff-sync";
|
|
2385
|
-
import pgInfo from "@wmfs/pg-info";
|
|
2386
|
-
import pg2 from "pg";
|
|
2387
|
-
|
|
2388
|
-
// src/restura/sql/PsqlPool.ts
|
|
2389
|
-
import pg from "pg";
|
|
2390
|
-
|
|
2391
|
-
// src/restura/sql/PsqlConnection.ts
|
|
2392
|
-
import crypto from "crypto";
|
|
2393
|
-
import { format as sqlFormat } from "sql-formatter";
|
|
2394
|
-
import { z as z4 } from "zod";
|
|
2395
|
-
var PsqlConnection = class {
|
|
2396
|
-
instanceId;
|
|
2397
|
-
constructor(instanceId) {
|
|
2398
|
-
this.instanceId = instanceId || crypto.randomUUID();
|
|
2625
|
+
// src/restura/sql/eventOutbox.ts
|
|
2626
|
+
var defaultEventOutboxOptions = {
|
|
2627
|
+
channel: DEFAULT_OUTBOX_CHANNEL,
|
|
2628
|
+
pollIntervalMs: 15e3,
|
|
2629
|
+
batchSize: 50,
|
|
2630
|
+
maxAttempts: 5,
|
|
2631
|
+
pruneAfterDays: 7
|
|
2632
|
+
};
|
|
2633
|
+
var PRUNE_INTERVAL_MS = 60 * 60 * 1e3;
|
|
2634
|
+
var EventOutboxConsumer = class {
|
|
2635
|
+
constructor(psqlConnectionPool, options) {
|
|
2636
|
+
this.psqlConnectionPool = psqlConnectionPool;
|
|
2637
|
+
this.options = { ...defaultEventOutboxOptions, ...options };
|
|
2399
2638
|
}
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2639
|
+
options;
|
|
2640
|
+
isDraining = false;
|
|
2641
|
+
drainRequested = false;
|
|
2642
|
+
isStopped = false;
|
|
2643
|
+
pollTimer;
|
|
2644
|
+
pruneTimer;
|
|
2645
|
+
activeDrain = Promise.resolve();
|
|
2646
|
+
lastDrainOn = null;
|
|
2647
|
+
get channel() {
|
|
2648
|
+
return this.options.channel;
|
|
2649
|
+
}
|
|
2650
|
+
start() {
|
|
2651
|
+
this.isStopped = false;
|
|
2652
|
+
this.pollTimer = setInterval(() => void this.drain(), this.options.pollIntervalMs);
|
|
2653
|
+
this.pruneTimer = setInterval(() => void this.prune(), PRUNE_INTERVAL_MS);
|
|
2654
|
+
void this.drain();
|
|
2655
|
+
void this.prune();
|
|
2656
|
+
}
|
|
2657
|
+
async stop() {
|
|
2658
|
+
this.isStopped = true;
|
|
2659
|
+
if (this.pollTimer) clearInterval(this.pollTimer);
|
|
2660
|
+
if (this.pruneTimer) clearInterval(this.pruneTimer);
|
|
2661
|
+
await this.activeDrain;
|
|
2662
|
+
}
|
|
2663
|
+
/** Safe to call at any frequency; overlapping calls coalesce into one extra pass. */
|
|
2664
|
+
async drain() {
|
|
2665
|
+
if (this.isDraining) {
|
|
2666
|
+
this.drainRequested = true;
|
|
2667
|
+
return;
|
|
2419
2668
|
}
|
|
2669
|
+
this.isDraining = true;
|
|
2670
|
+
this.activeDrain = (async () => {
|
|
2671
|
+
try {
|
|
2672
|
+
do {
|
|
2673
|
+
this.drainRequested = false;
|
|
2674
|
+
let processedCount = 0;
|
|
2675
|
+
do {
|
|
2676
|
+
processedCount = await this.processBatch();
|
|
2677
|
+
} while (processedCount > 0 && !this.isStopped);
|
|
2678
|
+
} while (this.drainRequested && !this.isStopped);
|
|
2679
|
+
this.lastDrainOn = (/* @__PURE__ */ new Date()).toISOString();
|
|
2680
|
+
} catch (error) {
|
|
2681
|
+
logger.error(`Event outbox drain failed: ${error}`);
|
|
2682
|
+
} finally {
|
|
2683
|
+
this.isDraining = false;
|
|
2684
|
+
}
|
|
2685
|
+
})();
|
|
2686
|
+
await this.activeDrain;
|
|
2420
2687
|
}
|
|
2421
|
-
async
|
|
2422
|
-
const result = await this.
|
|
2688
|
+
async getStats() {
|
|
2689
|
+
const result = await this.psqlConnectionPool.runQuery(
|
|
2690
|
+
`SELECT
|
|
2691
|
+
COUNT(*) FILTER (WHERE "processedOn" IS NULL AND "isDeadLetter" = FALSE) AS "pendingCount",
|
|
2692
|
+
COUNT(*) FILTER (WHERE "isDeadLetter" = TRUE) AS "deadLetterCount"
|
|
2693
|
+
FROM "${OUTBOX_TABLE_NAME}";`,
|
|
2694
|
+
[],
|
|
2695
|
+
systemUser
|
|
2696
|
+
);
|
|
2697
|
+
return {
|
|
2698
|
+
pendingCount: Number(result[0]?.pendingCount || 0),
|
|
2699
|
+
deadLetterCount: Number(result[0]?.deadLetterCount || 0),
|
|
2700
|
+
lastDrainOn: this.lastDrainOn
|
|
2701
|
+
};
|
|
2702
|
+
}
|
|
2703
|
+
async processBatch() {
|
|
2704
|
+
const transaction = new PsqlTransaction({
|
|
2705
|
+
host: this.psqlConnectionPool.poolConfig.host,
|
|
2706
|
+
port: this.psqlConnectionPool.poolConfig.port,
|
|
2707
|
+
user: this.psqlConnectionPool.poolConfig.user,
|
|
2708
|
+
password: this.psqlConnectionPool.poolConfig.password,
|
|
2709
|
+
database: this.psqlConnectionPool.poolConfig.database,
|
|
2710
|
+
connectionTimeoutMillis: this.psqlConnectionPool.poolConfig.connectionTimeoutMillis
|
|
2711
|
+
});
|
|
2423
2712
|
try {
|
|
2424
|
-
|
|
2713
|
+
const rows = await transaction.runQuery(
|
|
2714
|
+
`SELECT * FROM "${OUTBOX_TABLE_NAME}"
|
|
2715
|
+
WHERE "processedOn" IS NULL AND "isDeadLetter" = FALSE
|
|
2716
|
+
AND ("nextAttemptOn" IS NULL OR "nextAttemptOn" <= now())
|
|
2717
|
+
ORDER BY "id"
|
|
2718
|
+
LIMIT ?
|
|
2719
|
+
FOR UPDATE SKIP LOCKED;`,
|
|
2720
|
+
[this.options.batchSize],
|
|
2721
|
+
systemUser
|
|
2722
|
+
);
|
|
2723
|
+
for (const row of rows) {
|
|
2724
|
+
await this.processRow(transaction, row);
|
|
2725
|
+
}
|
|
2726
|
+
await transaction.commit();
|
|
2727
|
+
return rows.length;
|
|
2425
2728
|
} catch (error) {
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
logger.error("\n" + z4.prettifyError(error));
|
|
2430
|
-
} else {
|
|
2431
|
-
logger.error(error);
|
|
2729
|
+
try {
|
|
2730
|
+
await transaction.rollback();
|
|
2731
|
+
} catch {
|
|
2432
2732
|
}
|
|
2433
|
-
throw
|
|
2733
|
+
throw error;
|
|
2734
|
+
} finally {
|
|
2735
|
+
await transaction.release();
|
|
2434
2736
|
}
|
|
2435
2737
|
}
|
|
2436
|
-
async
|
|
2437
|
-
const formattedQuery = questionMarksToOrderedParams(query);
|
|
2438
|
-
const meta = { connectionInstanceId: this.instanceId, ...requesterDetails };
|
|
2439
|
-
const queryMetadata = `--QUERY_METADATA(${JSON.stringify(meta)})
|
|
2440
|
-
`;
|
|
2441
|
-
const startTime = process.hrtime();
|
|
2738
|
+
async processRow(transaction, row) {
|
|
2442
2739
|
try {
|
|
2443
|
-
const
|
|
2444
|
-
|
|
2445
|
-
|
|
2740
|
+
const triggerResult = {
|
|
2741
|
+
table: row.tableName,
|
|
2742
|
+
insertedId: row.operation === "INSERT" ? row.recordId ?? void 0 : void 0,
|
|
2743
|
+
changedId: row.operation === "UPDATE" ? row.recordId ?? void 0 : void 0,
|
|
2744
|
+
deletedId: row.operation === "DELETE" ? row.recordId ?? void 0 : void 0,
|
|
2745
|
+
queryMetadata: row.queryMetadata ?? {},
|
|
2746
|
+
record: row.record ?? {},
|
|
2747
|
+
previousRecord: row.previousRecord ?? {},
|
|
2748
|
+
requesterId: 0
|
|
2749
|
+
};
|
|
2750
|
+
await eventManager_default.fireActionFromDbTrigger(
|
|
2751
|
+
{ mutationType: row.operation, queryMetadata: triggerResult.queryMetadata },
|
|
2752
|
+
triggerResult,
|
|
2753
|
+
{ rethrowHandlerErrors: true }
|
|
2754
|
+
);
|
|
2755
|
+
await transaction.runQuery(
|
|
2756
|
+
`UPDATE "${OUTBOX_TABLE_NAME}" SET "processedOn" = now() WHERE "id" = ?;`,
|
|
2757
|
+
[row.id],
|
|
2758
|
+
systemUser
|
|
2759
|
+
);
|
|
2446
2760
|
} catch (error) {
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2761
|
+
const attempts = row.attempts + 1;
|
|
2762
|
+
const isDeadLetter = attempts >= this.options.maxAttempts;
|
|
2763
|
+
if (isDeadLetter) {
|
|
2764
|
+
logger.error(
|
|
2765
|
+
`Event outbox row ${row.id} (${row.tableName} ${row.operation}) moved to dead letter after ${attempts} attempts: ${error}`
|
|
2766
|
+
);
|
|
2767
|
+
} else {
|
|
2768
|
+
logger.warn(
|
|
2769
|
+
`Event outbox row ${row.id} (${row.tableName} ${row.operation}) attempt ${attempts} failed: ${error}`
|
|
2770
|
+
);
|
|
2450
2771
|
}
|
|
2451
|
-
|
|
2772
|
+
const backoffSeconds = 30 * Math.pow(2, row.attempts);
|
|
2773
|
+
await transaction.runQuery(
|
|
2774
|
+
`UPDATE "${OUTBOX_TABLE_NAME}"
|
|
2775
|
+
SET "attempts" = ?, "isDeadLetter" = ?, "nextAttemptOn" = now() + (? || ' seconds')::interval
|
|
2776
|
+
WHERE "id" = ?;`,
|
|
2777
|
+
[attempts, isDeadLetter, backoffSeconds, row.id],
|
|
2778
|
+
systemUser
|
|
2779
|
+
);
|
|
2452
2780
|
}
|
|
2453
2781
|
}
|
|
2454
|
-
async
|
|
2455
|
-
const result = await this.runQuery(query, params, requesterDetails);
|
|
2782
|
+
async prune() {
|
|
2456
2783
|
try {
|
|
2457
|
-
|
|
2784
|
+
await this.psqlConnectionPool.runQuery(
|
|
2785
|
+
`DELETE FROM "${OUTBOX_TABLE_NAME}"
|
|
2786
|
+
WHERE "processedOn" IS NOT NULL
|
|
2787
|
+
AND "isDeadLetter" = FALSE
|
|
2788
|
+
AND "processedOn" < now() - (? || ' days')::interval;`,
|
|
2789
|
+
[this.options.pruneAfterDays],
|
|
2790
|
+
systemUser
|
|
2791
|
+
);
|
|
2458
2792
|
} catch (error) {
|
|
2459
|
-
|
|
2460
|
-
logger.error("Invalid data returned from database:");
|
|
2461
|
-
logger.trace("\n" + JSON.stringify(result, null, 2));
|
|
2462
|
-
logger.error("\n" + z4.prettifyError(error));
|
|
2463
|
-
} else {
|
|
2464
|
-
logger.error(error);
|
|
2465
|
-
}
|
|
2466
|
-
throw new RsError("DATABASE_ERROR", `Invalid data returned from database`);
|
|
2793
|
+
logger.error(`Event outbox prune failed: ${error}`);
|
|
2467
2794
|
}
|
|
2468
2795
|
}
|
|
2469
|
-
logSqlStatement(query, options, queryMetadata, startTime, prefix = "") {
|
|
2470
|
-
if (logger.level !== "trace") return;
|
|
2471
|
-
const sqlStatement = query.replace(/\$(\d+)/g, (_, num) => {
|
|
2472
|
-
const paramIndex = parseInt(num) - 1;
|
|
2473
|
-
if (paramIndex >= options.length) return "INVALID_PARAM_INDEX";
|
|
2474
|
-
return toSqlLiteral(options[paramIndex]);
|
|
2475
|
-
});
|
|
2476
|
-
const formattedSql = sqlFormat(sqlStatement, {
|
|
2477
|
-
language: "postgresql",
|
|
2478
|
-
linesBetweenQueries: 2,
|
|
2479
|
-
indentStyle: "standard",
|
|
2480
|
-
keywordCase: "upper",
|
|
2481
|
-
useTabs: true,
|
|
2482
|
-
tabWidth: 4
|
|
2483
|
-
});
|
|
2484
|
-
const [seconds, nanoseconds] = process.hrtime(startTime);
|
|
2485
|
-
const durationMs = seconds * 1e3 + nanoseconds / 1e6;
|
|
2486
|
-
let initiator = "Anonymous";
|
|
2487
|
-
if ("userId" in queryMetadata && queryMetadata.userId)
|
|
2488
|
-
initiator = `User Id (${queryMetadata.userId.toString()})`;
|
|
2489
|
-
if ("isSystemUser" in queryMetadata && queryMetadata.isSystemUser) initiator = "SYSTEM";
|
|
2490
|
-
logger.trace(`${prefix}query by ${initiator}, Query ->
|
|
2491
|
-
${formattedSql}`, {
|
|
2492
|
-
durationMs
|
|
2493
|
-
});
|
|
2494
|
-
}
|
|
2495
2796
|
};
|
|
2496
2797
|
|
|
2497
|
-
// src/restura/sql/
|
|
2498
|
-
|
|
2499
|
-
var
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2798
|
+
// src/restura/sql/filterPsqlParser.ts
|
|
2799
|
+
import peg from "pegjs";
|
|
2800
|
+
var initializers = `
|
|
2801
|
+
// Quotes a SQL identifier (column/table name) with double quotes, escaping any embedded quotes
|
|
2802
|
+
function quoteSqlIdentity(value) {
|
|
2803
|
+
return '"' + value.replace(/"/g, '""') + '"';
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
// Unescape special characters in values: \\, -> , | \\| -> | | \\\\ -> \\
|
|
2807
|
+
function unescapeValue(str) {
|
|
2808
|
+
var result = '';
|
|
2809
|
+
for (var i = 0; i < str.length; i++) {
|
|
2810
|
+
if (str[i] === '\\\\' && i + 1 < str.length) {
|
|
2811
|
+
var next = str[i + 1];
|
|
2812
|
+
if (next === ',' || next === '|' || next === '\\\\') {
|
|
2813
|
+
result += next;
|
|
2814
|
+
i++;
|
|
2815
|
+
} else {
|
|
2816
|
+
result += str[i];
|
|
2817
|
+
}
|
|
2818
|
+
} else {
|
|
2819
|
+
result += str[i];
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
return result;
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
// Split pipe-separated values respecting escaped pipes
|
|
2826
|
+
function splitPipeValues(str) {
|
|
2827
|
+
var values = [];
|
|
2828
|
+
var current = '';
|
|
2829
|
+
for (var i = 0; i < str.length; i++) {
|
|
2830
|
+
if (str[i] === '\\\\' && i + 1 < str.length && str[i + 1] === '|') {
|
|
2831
|
+
current += '|';
|
|
2832
|
+
i++;
|
|
2833
|
+
} else if (str[i] === '|') {
|
|
2834
|
+
values.push(unescapeValue(current));
|
|
2835
|
+
current = '';
|
|
2836
|
+
} else {
|
|
2837
|
+
current += str[i];
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
if (current.length > 0) {
|
|
2841
|
+
values.push(unescapeValue(current));
|
|
2842
|
+
}
|
|
2843
|
+
return values;
|
|
2844
|
+
}
|
|
2845
|
+
|
|
2846
|
+
// Build SQL IN clause from pipe-separated values
|
|
2847
|
+
function buildInClause(column, rawValue) {
|
|
2848
|
+
var values = splitPipeValues(rawValue);
|
|
2849
|
+
var literals = values.map(function(v) { return formatValue(v); });
|
|
2850
|
+
return column + ' IN (' + literals.join(', ') + ')';
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
// Check if a value is numeric and format appropriately
|
|
2854
|
+
function formatValue(value) {
|
|
2855
|
+
// Check if the value is a valid number (integer or decimal)
|
|
2856
|
+
if (/^-?\\d+(\\.\\d+)?$/.test(value)) {
|
|
2857
|
+
return value; // Return as-is without quotes
|
|
2858
|
+
}
|
|
2859
|
+
return format.literal(value);
|
|
2860
|
+
}
|
|
2861
|
+
|
|
2862
|
+
// Format a value with optional type cast
|
|
2863
|
+
function formatValueWithCast(rawValue, cast) {
|
|
2864
|
+
var formatted = formatValue(unescapeValue(rawValue));
|
|
2865
|
+
return cast ? formatted + '::' + cast : formatted;
|
|
2866
|
+
}
|
|
2867
|
+
|
|
2868
|
+
// Build SQL IN clause from pipe-separated values with optional cast
|
|
2869
|
+
function buildInClauseWithCast(column, rawValue, cast) {
|
|
2870
|
+
var values = splitPipeValues(rawValue);
|
|
2871
|
+
var literals = values.map(function(v) {
|
|
2872
|
+
var formatted = formatValue(v);
|
|
2873
|
+
return cast ? formatted + '::' + cast : formatted;
|
|
2874
|
+
});
|
|
2875
|
+
return column + ' IN (' + literals.join(', ') + ')';
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2878
|
+
// Format column with optional cast
|
|
2879
|
+
function formatColumn(col) {
|
|
2880
|
+
if (!col.cast) {
|
|
2881
|
+
return col.sql;
|
|
2882
|
+
}
|
|
2883
|
+
// Wrap JSON field extractions in parentheses when casting
|
|
2884
|
+
// because :: has higher precedence than ->>
|
|
2885
|
+
if (col.isJsonField) {
|
|
2886
|
+
return '(' + col.sql + ')::' + col.cast;
|
|
2887
|
+
}
|
|
2888
|
+
return col.sql + '::' + col.cast;
|
|
2889
|
+
}
|
|
2890
|
+
`;
|
|
2891
|
+
var entryGrammar = `
|
|
2892
|
+
{
|
|
2893
|
+
${initializers}
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
Start
|
|
2897
|
+
= sql:StartOld { return { sql: sql, usedOldSyntax: true }; }
|
|
2898
|
+
/ sql:StartNew { return { sql: sql, usedOldSyntax: false }; }
|
|
2899
|
+
`;
|
|
2900
|
+
var oldGrammar = `
|
|
2901
|
+
StartOld
|
|
2902
|
+
= OldExpressionList
|
|
2903
|
+
_
|
|
2904
|
+
= [ \\t\\r\\n]* // Matches spaces, tabs, and line breaks
|
|
2905
|
+
|
|
2906
|
+
OldExpressionList
|
|
2907
|
+
= leftExpression:OldExpression _ operator:OldOperator _ rightExpression:OldExpressionList
|
|
2908
|
+
{ return \`\${leftExpression} \${operator} \${rightExpression}\`;}
|
|
2909
|
+
/ OldExpression
|
|
2910
|
+
|
|
2911
|
+
OldExpression
|
|
2912
|
+
= negate:OldNegate? _ "(" _ "column" _ ":" column:OldColumn _ ","? _ value:OldValue? ","? _ type:OldType? _ ")"_
|
|
2913
|
+
{return \`\${negate? " NOT " : ""}(\${type ? type(column, value) : (value == null ? \`\${column} IS NULL\` : \`\${column} = \${formatValue(value)}\`)})\`;}
|
|
2914
|
+
/
|
|
2915
|
+
negate:OldNegate?"("expression:OldExpressionList")" { return \`\${negate? " NOT " : ""}(\${expression})\`; }
|
|
2916
|
+
|
|
2917
|
+
OldNegate
|
|
2918
|
+
= "!"
|
|
2919
|
+
|
|
2920
|
+
OldOperator
|
|
2921
|
+
= "and"i / "or"i
|
|
2922
|
+
|
|
2923
|
+
OldColumn
|
|
2924
|
+
= first:OldColumnPart rest:("." OldColumnPart)* {
|
|
2925
|
+
const partsArray = [first];
|
|
2926
|
+
if (rest && rest.length > 0) {
|
|
2927
|
+
partsArray.push(...rest.map(item => item[1]));
|
|
2928
|
+
}
|
|
2929
|
+
|
|
2930
|
+
if (partsArray.length > 3) {
|
|
2931
|
+
throw new SyntaxError('Column path cannot have more than 3 parts (table.column.jsonField)');
|
|
2932
|
+
}
|
|
2933
|
+
|
|
2934
|
+
if (partsArray.length === 1) {
|
|
2935
|
+
return quoteSqlIdentity(partsArray[0]);
|
|
2936
|
+
}
|
|
2937
|
+
const tableName = quoteSqlIdentity(partsArray[0]);
|
|
2938
|
+
|
|
2939
|
+
// If we only have two parts (table.column), use regular dot notation
|
|
2940
|
+
if (partsArray.length === 2) {
|
|
2941
|
+
return tableName + "." + quoteSqlIdentity(partsArray[1]);
|
|
2942
|
+
}
|
|
2943
|
+
|
|
2944
|
+
// For JSON paths (more than 2 parts), first part is a column, last part uses ->>
|
|
2945
|
+
const jsonColumn = quoteSqlIdentity(partsArray[1]);
|
|
2946
|
+
const lastPart = partsArray[partsArray.length - 1];
|
|
2947
|
+
const escapedLast = lastPart.replace(/'/g, "''");
|
|
2948
|
+
const result = tableName + "." + jsonColumn + "->>'" + escapedLast + "'";
|
|
2949
|
+
return result;
|
|
2950
|
+
}
|
|
2951
|
+
|
|
2952
|
+
OldColumnPart
|
|
2953
|
+
= text:[a-z0-9 \\t\\r\\n\\-_:@']i+ {
|
|
2954
|
+
return text.join("");
|
|
2515
2955
|
}
|
|
2516
|
-
this.pool = new Pool(poolConfig);
|
|
2517
|
-
this.queryOne("SELECT NOW();", [], {
|
|
2518
|
-
isSystemUser: true,
|
|
2519
|
-
role: "",
|
|
2520
|
-
host: "localhost",
|
|
2521
|
-
ipAddress: "",
|
|
2522
|
-
scopes: []
|
|
2523
|
-
}).then(() => {
|
|
2524
|
-
logger.info("Connected to PostgreSQL database");
|
|
2525
|
-
}).catch((error) => {
|
|
2526
|
-
logger.error("Error connecting to database", error);
|
|
2527
|
-
process.exit(1);
|
|
2528
|
-
});
|
|
2529
|
-
}
|
|
2530
|
-
pool;
|
|
2531
|
-
async query(query, values) {
|
|
2532
|
-
return this.pool.query(query, values);
|
|
2533
|
-
}
|
|
2534
|
-
};
|
|
2535
2956
|
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
scopes: [],
|
|
2541
|
-
host: "",
|
|
2542
|
-
ipAddress: "",
|
|
2543
|
-
isSystemUser: true
|
|
2544
|
-
};
|
|
2545
|
-
function schemaToPsqlType(column) {
|
|
2546
|
-
if (column.hasAutoIncrement) return "BIGSERIAL";
|
|
2547
|
-
if (column.type === "ENUM") return "TEXT";
|
|
2548
|
-
if (column.type === "DATETIME") return "TIMESTAMPTZ";
|
|
2549
|
-
if (column.type === "MEDIUMINT") return "INT";
|
|
2550
|
-
return column.type;
|
|
2551
|
-
}
|
|
2552
|
-
function createInsertTriggerSql(tableName, notify) {
|
|
2553
|
-
if (!notify) return "";
|
|
2554
|
-
if (notify === "ALL") {
|
|
2555
|
-
return `
|
|
2556
|
-
CREATE OR REPLACE FUNCTION notify_${tableName}_insert()
|
|
2557
|
-
RETURNS TRIGGER AS $$
|
|
2558
|
-
DECLARE
|
|
2559
|
-
query_metadata JSON;
|
|
2560
|
-
BEGIN
|
|
2561
|
-
SELECT INTO query_metadata
|
|
2562
|
-
(regexp_match(
|
|
2563
|
-
current_query(),
|
|
2564
|
-
'^--QUERY_METADATA\\(({.*})', 'n'
|
|
2565
|
-
))[1]::json;
|
|
2957
|
+
OldText
|
|
2958
|
+
= text:[a-z0-9 \\t\\r\\n\\-_:@'.]i+ {
|
|
2959
|
+
return text.join("");
|
|
2960
|
+
}
|
|
2566
2961
|
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
'queryMetadata', query_metadata,
|
|
2572
|
-
'insertedId', NEW.id,
|
|
2573
|
-
'record', NEW
|
|
2574
|
-
)::text
|
|
2575
|
-
);
|
|
2962
|
+
OldType
|
|
2963
|
+
= "type" _ ":" _ type:OldTypeString {
|
|
2964
|
+
return type;
|
|
2965
|
+
}
|
|
2576
2966
|
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2967
|
+
OldTypeString
|
|
2968
|
+
= text:"startsWith" { return function(column, value) { return \`\${column} ILIKE '\${format.literal(value).slice(1,-1)}%'\`; } }
|
|
2969
|
+
/ text:"endsWith" { return function(column, value) { return \`\${column} ILIKE '%\${format.literal(value).slice(1,-1)}'\`; } }
|
|
2970
|
+
/ text:"contains" { return function(column, value) { return \`\${column} ILIKE '%\${format.literal(value).slice(1,-1)}%'\`; } }
|
|
2971
|
+
/ text:"exact" { return function(column, value) { return \`\${column} = \${formatValue(value)}\`; } }
|
|
2972
|
+
/ text:"greaterThanEqual" { return function(column, value) { return \`\${column} >= \${formatValue(value)}\`; } }
|
|
2973
|
+
/ text:"greaterThan" { return function(column, value) { return \`\${column} > \${formatValue(value)}\`; } }
|
|
2974
|
+
/ text:"lessThanEqual" { return function(column, value) { return \`\${column} <= \${formatValue(value)}\`; } }
|
|
2975
|
+
/ text:"lessThan" { return function(column, value) { return \`\${column} < \${formatValue(value)}\`; } }
|
|
2976
|
+
/ text:"isNull" { return function(column, value) { return \`\${column} IS NULL\`; } }
|
|
2580
2977
|
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2978
|
+
OldValue
|
|
2979
|
+
= "value" _ ":" value:OldText {
|
|
2980
|
+
return value;
|
|
2981
|
+
}
|
|
2585
2982
|
`;
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
CREATE OR REPLACE FUNCTION notify_${tableName}_insert()
|
|
2590
|
-
RETURNS TRIGGER AS $$
|
|
2591
|
-
DECLARE
|
|
2592
|
-
query_metadata JSON;
|
|
2593
|
-
BEGIN
|
|
2594
|
-
SELECT INTO query_metadata
|
|
2595
|
-
(regexp_match(
|
|
2596
|
-
current_query(),
|
|
2597
|
-
'^--QUERY_METADATA\\(({.*})', 'n'
|
|
2598
|
-
))[1]::json;
|
|
2983
|
+
var newGrammar = `
|
|
2984
|
+
StartNew
|
|
2985
|
+
= ExpressionList
|
|
2599
2986
|
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
'queryMetadata', query_metadata,
|
|
2605
|
-
'insertedId', NEW.id,
|
|
2606
|
-
'record', json_build_object(
|
|
2607
|
-
${notifyColumnNewBuildString}
|
|
2608
|
-
)
|
|
2609
|
-
)::text
|
|
2610
|
-
);
|
|
2987
|
+
ExpressionList
|
|
2988
|
+
= left:Expression _ op:("and"i / "or"i) _ right:ExpressionList
|
|
2989
|
+
{ return left + ' ' + op.toUpperCase() + ' ' + right; }
|
|
2990
|
+
/ Expression
|
|
2611
2991
|
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2992
|
+
Expression
|
|
2993
|
+
= negate:"!"? _ "(" _ inner:SimpleExprList _ ")" _
|
|
2994
|
+
{ return (negate ? 'NOT ' : '') + '(' + inner + ')'; }
|
|
2995
|
+
/ SimpleExpr
|
|
2615
2996
|
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
`;
|
|
2621
|
-
}
|
|
2622
|
-
function createUpdateTriggerSql(tableName, notify) {
|
|
2623
|
-
if (!notify) return "";
|
|
2624
|
-
if (notify === "ALL") {
|
|
2625
|
-
return `
|
|
2626
|
-
CREATE OR REPLACE FUNCTION notify_${tableName}_update()
|
|
2627
|
-
RETURNS TRIGGER AS $$
|
|
2628
|
-
DECLARE
|
|
2629
|
-
query_metadata JSON;
|
|
2630
|
-
BEGIN
|
|
2631
|
-
SELECT INTO query_metadata
|
|
2632
|
-
(regexp_match(
|
|
2633
|
-
current_query(),
|
|
2634
|
-
'^--QUERY_METADATA\\(({.*})', 'n'
|
|
2635
|
-
))[1]::json;
|
|
2997
|
+
SimpleExprList
|
|
2998
|
+
= left:SimpleExpr _ op:("and"i / "or"i) _ right:SimpleExprList
|
|
2999
|
+
{ return left + ' ' + op.toUpperCase() + ' ' + right; }
|
|
3000
|
+
/ SimpleExpr
|
|
2636
3001
|
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
'previousRecord', OLD
|
|
2645
|
-
)::text
|
|
2646
|
-
);
|
|
2647
|
-
RETURN NEW;
|
|
2648
|
-
END;
|
|
2649
|
-
$$ LANGUAGE plpgsql;
|
|
3002
|
+
SimpleExpr
|
|
3003
|
+
= negate:"!"? _ "(" _ col:Column _ "," _ op:OperatorWithValue _ ")" _
|
|
3004
|
+
{ return (negate ? 'NOT ' : '') + '(' + op(col) + ')'; }
|
|
3005
|
+
/ negate:"!"? _ "(" _ col:Column _ "," _ op:NullOperator _ ")" _
|
|
3006
|
+
{ return (negate ? 'NOT ' : '') + '(' + op(col) + ')'; }
|
|
3007
|
+
/ negate:"!"? _ "(" _ col:Column _ "," _ val:CastedValue _ ")" _
|
|
3008
|
+
{ return (negate ? 'NOT ' : '') + '(' + formatColumn(col) + ' = ' + formatValueWithCast(val.value, val.cast) + ')'; }
|
|
2650
3009
|
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
3010
|
+
Column
|
|
3011
|
+
= first:ColPart rest:("." ColPart)* cast:TypeCast? {
|
|
3012
|
+
const partsArray = [first];
|
|
3013
|
+
if (rest && rest.length > 0) {
|
|
3014
|
+
partsArray.push(...rest.map(item => item[1]));
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
if (partsArray.length > 3) {
|
|
3018
|
+
throw new SyntaxError('Column path cannot have more than 3 parts (table.column.jsonField)');
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
var sql;
|
|
3022
|
+
var isJsonField = false;
|
|
3023
|
+
if (partsArray.length === 1) {
|
|
3024
|
+
sql = quoteSqlIdentity(partsArray[0]);
|
|
3025
|
+
} else {
|
|
3026
|
+
const tableName = quoteSqlIdentity(partsArray[0]);
|
|
3027
|
+
|
|
3028
|
+
if (partsArray.length === 2) {
|
|
3029
|
+
sql = tableName + '.' + quoteSqlIdentity(partsArray[1]);
|
|
3030
|
+
} else {
|
|
3031
|
+
const jsonColumn = quoteSqlIdentity(partsArray[1]);
|
|
3032
|
+
const lastPart = partsArray[partsArray.length - 1];
|
|
3033
|
+
const escapedLast = lastPart.replace(/'/g, "''");
|
|
3034
|
+
sql = tableName + '.' + jsonColumn + "->>'" + escapedLast + "'";
|
|
3035
|
+
isJsonField = true;
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
return { sql: sql, cast: cast, isJsonField: isJsonField };
|
|
3040
|
+
}
|
|
2670
3041
|
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
json_build_object(
|
|
2674
|
-
'table', '${tableName}',
|
|
2675
|
-
'queryMetadata', query_metadata,
|
|
2676
|
-
'changedId', NEW.id,
|
|
2677
|
-
'record', json_build_object(
|
|
2678
|
-
${notifyColumnNewBuildString}
|
|
2679
|
-
),
|
|
2680
|
-
'previousRecord', json_build_object(
|
|
2681
|
-
${notifyColumnOldBuildString}
|
|
2682
|
-
)
|
|
2683
|
-
)::text
|
|
2684
|
-
);
|
|
2685
|
-
RETURN NEW;
|
|
2686
|
-
END;
|
|
2687
|
-
$$ LANGUAGE plpgsql;
|
|
3042
|
+
ColPart
|
|
3043
|
+
= chars:[a-zA-Z0-9_]+ { return chars.join(''); }
|
|
2688
3044
|
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
3045
|
+
NullOperator
|
|
3046
|
+
= "notnull"i { return function(col) { return formatColumn(col) + ' IS NOT NULL'; }; }
|
|
3047
|
+
/ "null"i { return function(col) { return formatColumn(col) + ' IS NULL'; }; }
|
|
3048
|
+
|
|
3049
|
+
OperatorWithValue
|
|
3050
|
+
= "in"i _ "," _ vals:InValueList cast:TypeCast? { return function(col) {
|
|
3051
|
+
var formattedCol = formatColumn(col);
|
|
3052
|
+
var literals = vals.map(function(v) {
|
|
3053
|
+
var unescaped = unescapeValue(v);
|
|
3054
|
+
var formatted = formatValue(unescaped);
|
|
3055
|
+
return cast ? formatted + '::' + cast : formatted;
|
|
3056
|
+
});
|
|
3057
|
+
return formattedCol + ' IN (' + literals.join(', ') + ')';
|
|
3058
|
+
}; }
|
|
3059
|
+
/ "ne"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' <> ' + formatValueWithCast(val.value, val.cast); }; }
|
|
3060
|
+
/ "gte"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' >= ' + formatValueWithCast(val.value, val.cast); }; }
|
|
3061
|
+
/ "gt"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' > ' + formatValueWithCast(val.value, val.cast); }; }
|
|
3062
|
+
/ "lte"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' <= ' + formatValueWithCast(val.value, val.cast); }; }
|
|
3063
|
+
/ "lt"i _ "," _ val:CastedValue { return function(col) { return formatColumn(col) + ' < ' + formatValueWithCast(val.value, val.cast); }; }
|
|
3064
|
+
/ "has"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal('%' + unescapeValue(val.value) + '%'); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
3065
|
+
/ "sw"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal(unescapeValue(val.value) + '%'); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
3066
|
+
/ "ew"i _ "," _ val:CastedValue { return function(col) { var formatted = format.literal('%' + unescapeValue(val.value)); return formatColumn(col) + ' ILIKE ' + (val.cast ? formatted + '::' + val.cast : formatted); }; }
|
|
3067
|
+
|
|
3068
|
+
InValueList
|
|
3069
|
+
= first:InValue rest:("|" InValue)* {
|
|
3070
|
+
var values = [first];
|
|
3071
|
+
for (var i = 0; i < rest.length; i++) {
|
|
3072
|
+
values.push(rest[i][1]);
|
|
3073
|
+
}
|
|
3074
|
+
return values;
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
InValue
|
|
3078
|
+
= QuotedString
|
|
3079
|
+
/ chars:InValueChar+ { return chars.join(''); }
|
|
3080
|
+
|
|
3081
|
+
InValueChar
|
|
3082
|
+
= "\\\\\\\\" { return '\\\\\\\\'; }
|
|
3083
|
+
/ "\\\\," { return '\\\\,'; }
|
|
3084
|
+
/ "\\\\|" { return '\\\\|'; }
|
|
3085
|
+
/ [a-zA-Z0-9_\\-!#/@$%^&*+=<>?~.;'" ]
|
|
3086
|
+
/ c:":" !":" { return c; }
|
|
3087
|
+
|
|
3088
|
+
CastedValue
|
|
3089
|
+
= val:Value cast:TypeCast? { return { value: val, cast: cast }; }
|
|
3090
|
+
|
|
3091
|
+
CastedValueWithPipes
|
|
3092
|
+
= val:ValueWithPipes cast:TypeCast? { return { value: val, cast: cast }; }
|
|
3093
|
+
|
|
3094
|
+
TypeCast
|
|
3095
|
+
= "::" type:("timestamptz"i / "timestamp"i / "boolean"i / "numeric"i / "bigint"i / "text"i / "date"i / "int"i)
|
|
3096
|
+
{ return type.toLowerCase(); }
|
|
3097
|
+
|
|
3098
|
+
QuotedString
|
|
3099
|
+
= '"' chars:DoubleQuotedChar* '"' { return chars.join(''); }
|
|
3100
|
+
/ "'" chars:SingleQuotedChar* "'" { return chars.join(''); }
|
|
3101
|
+
|
|
3102
|
+
DoubleQuotedChar
|
|
3103
|
+
= '\\\\"' { return '"'; }
|
|
3104
|
+
/ '\\\\\\\\' { return '\\\\'; }
|
|
3105
|
+
/ [^"\\\\]
|
|
3106
|
+
|
|
3107
|
+
SingleQuotedChar
|
|
3108
|
+
= "\\\\'" { return "'"; }
|
|
3109
|
+
/ '\\\\\\\\' { return '\\\\'; }
|
|
3110
|
+
/ [^'\\\\]
|
|
3111
|
+
|
|
3112
|
+
Value
|
|
3113
|
+
= QuotedString
|
|
3114
|
+
/ chars:ValueChar+ { return chars.join(''); }
|
|
3115
|
+
|
|
3116
|
+
ValueChar
|
|
3117
|
+
= "\\\\\\\\" { return '\\\\\\\\'; }
|
|
3118
|
+
/ "\\\\," { return '\\\\,'; }
|
|
3119
|
+
/ "\\\\|" { return '\\\\|'; }
|
|
3120
|
+
/ [a-zA-Z0-9_\\-!#/@$%^&*+=<>?~.;'" ]
|
|
3121
|
+
/ c:":" !":" { return c; }
|
|
2709
3122
|
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
'table', '${tableName}',
|
|
2714
|
-
'queryMetadata', query_metadata,
|
|
2715
|
-
'deletedId', OLD.id,
|
|
2716
|
-
'previousRecord', OLD
|
|
2717
|
-
)::text
|
|
2718
|
-
);
|
|
2719
|
-
RETURN OLD;
|
|
2720
|
-
END;
|
|
2721
|
-
$$ LANGUAGE plpgsql;
|
|
3123
|
+
ValueWithPipes
|
|
3124
|
+
= QuotedString
|
|
3125
|
+
/ chars:ValueWithPipesChar+ { return chars.join(''); }
|
|
2722
3126
|
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
3127
|
+
ValueWithPipesChar
|
|
3128
|
+
= "\\\\\\\\" { return '\\\\\\\\'; }
|
|
3129
|
+
/ "\\\\," { return '\\\\,'; }
|
|
3130
|
+
/ "\\\\|" { return '\\\\|'; }
|
|
3131
|
+
/ [a-zA-Z0-9_\\-!#/@$%^&*+=<>?~.;'" |]
|
|
3132
|
+
/ c:":" !":" { return c; }
|
|
2727
3133
|
`;
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
query_metadata JSON;
|
|
2735
|
-
BEGIN
|
|
2736
|
-
SELECT INTO query_metadata
|
|
2737
|
-
(regexp_match(
|
|
2738
|
-
current_query(),
|
|
2739
|
-
'^--QUERY_METADATA\\(({.*})', 'n'
|
|
2740
|
-
))[1]::json;
|
|
2741
|
-
|
|
2742
|
-
PERFORM pg_notify(
|
|
2743
|
-
'delete',
|
|
2744
|
-
json_build_object(
|
|
2745
|
-
'table', '${tableName}',
|
|
2746
|
-
'queryMetadata', query_metadata,
|
|
2747
|
-
'deletedId', OLD.id,
|
|
2748
|
-
'previousRecord', json_build_object(
|
|
2749
|
-
${notifyColumnOldBuildString}
|
|
2750
|
-
)
|
|
2751
|
-
)::text
|
|
2752
|
-
);
|
|
2753
|
-
RETURN OLD;
|
|
2754
|
-
END;
|
|
2755
|
-
$$ LANGUAGE plpgsql;
|
|
2756
|
-
|
|
2757
|
-
CREATE OR REPLACE TRIGGER "${tableName}_delete"
|
|
2758
|
-
AFTER DELETE ON "${tableName}"
|
|
2759
|
-
FOR EACH ROW
|
|
2760
|
-
EXECUTE FUNCTION notify_${tableName}_delete();
|
|
2761
|
-
`;
|
|
2762
|
-
}
|
|
2763
|
-
function generateDatabaseSchemaFromSchema(schema) {
|
|
2764
|
-
const sqlStatements = [];
|
|
2765
|
-
const indexes = [];
|
|
2766
|
-
const triggers = [];
|
|
2767
|
-
for (const table of schema.database) {
|
|
2768
|
-
if (table.notify) {
|
|
2769
|
-
triggers.push(createInsertTriggerSql(table.name, table.notify));
|
|
2770
|
-
triggers.push(createUpdateTriggerSql(table.name, table.notify));
|
|
2771
|
-
triggers.push(createDeleteTriggerSql(table.name, table.notify));
|
|
2772
|
-
}
|
|
2773
|
-
let sql = `CREATE TABLE "${table.name}"
|
|
2774
|
-
( `;
|
|
2775
|
-
const tableColumns = [];
|
|
2776
|
-
for (const column of table.columns) {
|
|
2777
|
-
let columnSql = "";
|
|
2778
|
-
columnSql += ` "${column.name}" ${schemaToPsqlType(column)}`;
|
|
2779
|
-
let value = column.value;
|
|
2780
|
-
if (column.type === "JSON") value = "";
|
|
2781
|
-
if (column.type === "JSONB") value = "";
|
|
2782
|
-
if (column.type === "DECIMAL" && value) {
|
|
2783
|
-
value = value.replace("-", ",").replace(/['"]/g, "");
|
|
2784
|
-
}
|
|
2785
|
-
if (value && column.type !== "ENUM") {
|
|
2786
|
-
columnSql += `(${value})`;
|
|
2787
|
-
} else if (column.length) columnSql += `(${column.length})`;
|
|
2788
|
-
if (column.isPrimary) {
|
|
2789
|
-
columnSql += " PRIMARY KEY ";
|
|
2790
|
-
}
|
|
2791
|
-
if (column.isUnique) {
|
|
2792
|
-
columnSql += ` CONSTRAINT "${table.name}_${column.name}_unique_index" UNIQUE `;
|
|
2793
|
-
}
|
|
2794
|
-
if (column.isNullable) columnSql += " NULL";
|
|
2795
|
-
else columnSql += " NOT NULL";
|
|
2796
|
-
if (column.default) columnSql += ` DEFAULT ${column.default}`;
|
|
2797
|
-
if (value && column.type === "ENUM") {
|
|
2798
|
-
columnSql += ` CHECK ("${column.name}" IN (${value}))`;
|
|
2799
|
-
}
|
|
2800
|
-
tableColumns.push(columnSql);
|
|
2801
|
-
}
|
|
2802
|
-
sql += tableColumns.join(", \n");
|
|
2803
|
-
for (const index of table.indexes) {
|
|
2804
|
-
if (!index.isPrimaryKey) {
|
|
2805
|
-
let unique = " ";
|
|
2806
|
-
if (index.isUnique) unique = "UNIQUE ";
|
|
2807
|
-
let indexSQL = ` CREATE ${unique}INDEX "${index.name}" ON "${table.name}"`;
|
|
2808
|
-
indexSQL += ` (${index.columns.map((item) => `"${item}" ${index.order}`).join(", ")})`;
|
|
2809
|
-
indexSQL += index.where ? ` WHERE ${index.where}` : "";
|
|
2810
|
-
indexSQL += ";";
|
|
2811
|
-
indexes.push(indexSQL);
|
|
2812
|
-
}
|
|
2813
|
-
}
|
|
2814
|
-
sql += "\n);";
|
|
2815
|
-
sqlStatements.push(sql);
|
|
2816
|
-
}
|
|
2817
|
-
for (const table of schema.database) {
|
|
2818
|
-
if (!table.foreignKeys.length) continue;
|
|
2819
|
-
const sql = `ALTER TABLE "${table.name}" `;
|
|
2820
|
-
const constraints = [];
|
|
2821
|
-
for (const foreignKey of table.foreignKeys) {
|
|
2822
|
-
let constraint = ` ADD CONSTRAINT "${foreignKey.name}"
|
|
2823
|
-
FOREIGN KEY ("${foreignKey.column}") REFERENCES "${foreignKey.refTable}" ("${foreignKey.refColumn}")`;
|
|
2824
|
-
constraint += ` ON DELETE ${foreignKey.onDelete}`;
|
|
2825
|
-
constraint += ` ON UPDATE ${foreignKey.onUpdate}`;
|
|
2826
|
-
constraints.push(constraint);
|
|
2827
|
-
}
|
|
2828
|
-
sqlStatements.push(sql + constraints.join(",\n") + ";");
|
|
2829
|
-
}
|
|
2830
|
-
for (const table of schema.database) {
|
|
2831
|
-
if (!table.checkConstraints.length) continue;
|
|
2832
|
-
const sql = `ALTER TABLE "${table.name}" `;
|
|
2833
|
-
const constraints = [];
|
|
2834
|
-
for (const check of table.checkConstraints) {
|
|
2835
|
-
const constraint = `ADD CONSTRAINT "${check.name}" CHECK (${check.check})`;
|
|
2836
|
-
constraints.push(constraint);
|
|
2837
|
-
}
|
|
2838
|
-
sqlStatements.push(sql + constraints.join(",\n") + ";");
|
|
2839
|
-
}
|
|
2840
|
-
sqlStatements.push(indexes.join("\n"));
|
|
2841
|
-
sqlStatements.push(triggers.join("\n"));
|
|
2842
|
-
return sqlStatements.join("\n\n");
|
|
2843
|
-
}
|
|
2844
|
-
async function getNewPublicSchemaAndScratchPool(targetPool, scratchDbName) {
|
|
2845
|
-
const scratchDbExists = await targetPool.runQuery(
|
|
2846
|
-
`SELECT * FROM pg_database WHERE datname = ?;`,
|
|
2847
|
-
[scratchDbName],
|
|
2848
|
-
systemUser
|
|
2849
|
-
);
|
|
2850
|
-
if (scratchDbExists.length === 0) {
|
|
2851
|
-
await targetPool.runQuery(`CREATE DATABASE ${escapeColumnName(scratchDbName)};`, [], systemUser);
|
|
2852
|
-
}
|
|
2853
|
-
const scratchPool = new PsqlPool({
|
|
2854
|
-
host: targetPool.poolConfig.host,
|
|
2855
|
-
port: targetPool.poolConfig.port,
|
|
2856
|
-
user: targetPool.poolConfig.user,
|
|
2857
|
-
database: scratchDbName,
|
|
2858
|
-
password: targetPool.poolConfig.password,
|
|
2859
|
-
max: targetPool.poolConfig.max,
|
|
2860
|
-
idleTimeoutMillis: targetPool.poolConfig.idleTimeoutMillis,
|
|
2861
|
-
connectionTimeoutMillis: targetPool.poolConfig.connectionTimeoutMillis
|
|
2862
|
-
});
|
|
2863
|
-
await scratchPool.runQuery(`DROP SCHEMA public CASCADE;`, [], systemUser);
|
|
2864
|
-
await scratchPool.runQuery(
|
|
2865
|
-
`CREATE SCHEMA public AUTHORIZATION ${escapeColumnName(targetPool.poolConfig.user)};`,
|
|
2866
|
-
[],
|
|
2867
|
-
systemUser
|
|
2868
|
-
);
|
|
2869
|
-
const schemaComment = await targetPool.runQuery(
|
|
2870
|
-
`
|
|
2871
|
-
SELECT pg_description.description
|
|
2872
|
-
FROM pg_description
|
|
2873
|
-
JOIN pg_namespace ON pg_namespace.oid = pg_description.objoid
|
|
2874
|
-
WHERE pg_namespace.nspname = 'public';`,
|
|
2875
|
-
[],
|
|
2876
|
-
systemUser
|
|
2877
|
-
);
|
|
2878
|
-
if (schemaComment[0]?.description) {
|
|
2879
|
-
const escaped = schemaComment[0].description.replace(/'/g, "''");
|
|
2880
|
-
await scratchPool.runQuery(`COMMENT ON SCHEMA public IS '${escaped}';`, [], systemUser);
|
|
2881
|
-
}
|
|
2882
|
-
return scratchPool;
|
|
2883
|
-
}
|
|
2884
|
-
async function diffDatabaseToSchema(schema, targetPool, scratchDbName) {
|
|
2885
|
-
let scratchPool;
|
|
2886
|
-
let originalClient;
|
|
2887
|
-
let scratchClient;
|
|
2888
|
-
try {
|
|
2889
|
-
scratchPool = await getNewPublicSchemaAndScratchPool(targetPool, scratchDbName);
|
|
2890
|
-
const sqlFullStatement = generateDatabaseSchemaFromSchema(schema);
|
|
2891
|
-
await scratchPool.runQuery(sqlFullStatement, [], systemUser);
|
|
2892
|
-
const connectionConfig = {
|
|
2893
|
-
host: targetPool.poolConfig.host,
|
|
2894
|
-
port: targetPool.poolConfig.port,
|
|
2895
|
-
user: targetPool.poolConfig.user,
|
|
2896
|
-
password: targetPool.poolConfig.password,
|
|
2897
|
-
ssl: targetPool.poolConfig.ssl
|
|
2898
|
-
};
|
|
2899
|
-
originalClient = new Client({ ...connectionConfig, database: targetPool.poolConfig.database });
|
|
2900
|
-
scratchClient = new Client({ ...connectionConfig, database: scratchDbName });
|
|
2901
|
-
await Promise.all([originalClient.connect(), scratchClient.connect()]);
|
|
2902
|
-
const [info1, info2] = await Promise.all([
|
|
2903
|
-
pgInfo({ client: originalClient }),
|
|
2904
|
-
pgInfo({ client: scratchClient })
|
|
2905
|
-
]);
|
|
2906
|
-
const diff = getDiff(info1, info2);
|
|
2907
|
-
return diff.join("\n");
|
|
2908
|
-
} finally {
|
|
2909
|
-
const cleanups = [];
|
|
2910
|
-
if (originalClient) cleanups.push(originalClient.end());
|
|
2911
|
-
if (scratchClient) cleanups.push(scratchClient.end());
|
|
2912
|
-
if (scratchPool) cleanups.push(scratchPool.pool.end());
|
|
2913
|
-
await Promise.allSettled(cleanups);
|
|
2914
|
-
}
|
|
2915
|
-
}
|
|
3134
|
+
var fullGrammar = entryGrammar + oldGrammar + newGrammar;
|
|
3135
|
+
var filterPsqlParser = peg.generate(fullGrammar, {
|
|
3136
|
+
format: "commonjs",
|
|
3137
|
+
dependencies: { format: "pg-format" }
|
|
3138
|
+
});
|
|
3139
|
+
var filterPsqlParser_default = filterPsqlParser;
|
|
2916
3140
|
|
|
2917
3141
|
// src/restura/sql/PsqlEngine.ts
|
|
2918
|
-
var { Client:
|
|
3142
|
+
var { Client: Client3, types } = pg4;
|
|
2919
3143
|
var PsqlEngine = class extends SqlEngine {
|
|
2920
|
-
|
|
2921
|
-
constructor(psqlConnectionPool, shouldListenForDbTriggers = false, scratchDatabaseSuffix = "") {
|
|
3144
|
+
constructor(psqlConnectionPool, shouldListenForDbTriggers = false, scratchDatabaseSuffix = "", eventDelivery) {
|
|
2922
3145
|
super();
|
|
2923
3146
|
this.psqlConnectionPool = psqlConnectionPool;
|
|
3147
|
+
this.eventDelivery = eventDelivery || { mode: "direct" };
|
|
2924
3148
|
this.setupPgReturnTypes();
|
|
3149
|
+
if (this.eventDelivery.mode === "outbox") {
|
|
3150
|
+
this.outboxConsumer = new EventOutboxConsumer(psqlConnectionPool, this.eventDelivery.outbox);
|
|
3151
|
+
}
|
|
2925
3152
|
if (shouldListenForDbTriggers) {
|
|
2926
|
-
this.setupTriggerListeners = this.listenForDbTriggers()
|
|
3153
|
+
this.setupTriggerListeners = this.listenForDbTriggers().catch((error) => {
|
|
3154
|
+
logger.error(`Failed to setup trigger listeners: ${error}`);
|
|
3155
|
+
void this.reconnectTriggerClient();
|
|
3156
|
+
});
|
|
3157
|
+
this.outboxConsumer?.start();
|
|
2927
3158
|
}
|
|
2928
3159
|
this.scratchDbName = `${psqlConnectionPool.poolConfig.database}_scratch${scratchDatabaseSuffix ? `_${scratchDatabaseSuffix}` : ""}`;
|
|
2929
3160
|
}
|
|
@@ -2931,12 +3162,34 @@ var PsqlEngine = class extends SqlEngine {
|
|
|
2931
3162
|
triggerClient;
|
|
2932
3163
|
scratchDbName = "";
|
|
2933
3164
|
reconnectAttempts = 0;
|
|
2934
|
-
MAX_RECONNECT_ATTEMPTS = 5;
|
|
2935
3165
|
INITIAL_RECONNECT_DELAY = 5e3;
|
|
3166
|
+
MAX_RECONNECT_DELAY = 6e4;
|
|
3167
|
+
HEARTBEAT_INTERVAL_MS = 3e4;
|
|
3168
|
+
eventDelivery;
|
|
3169
|
+
outboxConsumer;
|
|
3170
|
+
heartbeatTimer;
|
|
3171
|
+
isListenerConnected = false;
|
|
3172
|
+
isReconnecting = false;
|
|
3173
|
+
isClosed = false;
|
|
3174
|
+
lastHeartbeatOn = null;
|
|
2936
3175
|
async close() {
|
|
3176
|
+
this.isClosed = true;
|
|
3177
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
3178
|
+
if (this.outboxConsumer) await this.outboxConsumer.stop();
|
|
2937
3179
|
if (this.triggerClient) {
|
|
2938
3180
|
await this.triggerClient.end();
|
|
2939
3181
|
}
|
|
3182
|
+
this.isListenerConnected = false;
|
|
3183
|
+
}
|
|
3184
|
+
getEventListenerHealth() {
|
|
3185
|
+
return {
|
|
3186
|
+
connected: this.isListenerConnected,
|
|
3187
|
+
lastHeartbeatOn: this.lastHeartbeatOn,
|
|
3188
|
+
reconnectAttempts: this.reconnectAttempts
|
|
3189
|
+
};
|
|
3190
|
+
}
|
|
3191
|
+
getOutboxConsumer() {
|
|
3192
|
+
return this.outboxConsumer;
|
|
2940
3193
|
}
|
|
2941
3194
|
/**
|
|
2942
3195
|
* Setup the return types for the PostgreSQL connection.
|
|
@@ -2959,35 +3212,55 @@ var PsqlEngine = class extends SqlEngine {
|
|
|
2959
3212
|
types.setTypeParser(PG_TYPE_OID.TIMESTAMPTZ, (val) => val === null ? null : new Date(val).toISOString());
|
|
2960
3213
|
}
|
|
2961
3214
|
async reconnectTriggerClient() {
|
|
2962
|
-
if (this.
|
|
2963
|
-
|
|
2964
|
-
|
|
3215
|
+
if (this.isReconnecting || this.isClosed) return;
|
|
3216
|
+
this.isReconnecting = true;
|
|
3217
|
+
this.isListenerConnected = false;
|
|
3218
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
3219
|
+
try {
|
|
3220
|
+
while (!this.isClosed) {
|
|
3221
|
+
if (this.triggerClient) {
|
|
3222
|
+
try {
|
|
3223
|
+
await this.triggerClient.end();
|
|
3224
|
+
} catch (error) {
|
|
3225
|
+
logger.error(`Error closing trigger client: ${error}`);
|
|
3226
|
+
}
|
|
3227
|
+
this.triggerClient = void 0;
|
|
3228
|
+
}
|
|
3229
|
+
const exponentialDelay = this.INITIAL_RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts);
|
|
3230
|
+
const delay = Math.min(exponentialDelay, this.MAX_RECONNECT_DELAY) + Math.floor(Math.random() * 1e3);
|
|
3231
|
+
logger.info(
|
|
3232
|
+
`Attempting to reconnect trigger client in ${Math.round(delay / 1e3)} seconds... (attempt ${this.reconnectAttempts + 1})`
|
|
3233
|
+
);
|
|
3234
|
+
await new Promise((resolve2) => setTimeout(resolve2, delay));
|
|
3235
|
+
if (this.isClosed) return;
|
|
3236
|
+
this.reconnectAttempts++;
|
|
3237
|
+
try {
|
|
3238
|
+
await this.listenForDbTriggers();
|
|
3239
|
+
this.reconnectAttempts = 0;
|
|
3240
|
+
return;
|
|
3241
|
+
} catch (error) {
|
|
3242
|
+
logger.error(`Reconnection attempt ${this.reconnectAttempts} failed: ${error}`);
|
|
3243
|
+
}
|
|
3244
|
+
}
|
|
3245
|
+
} finally {
|
|
3246
|
+
this.isReconnecting = false;
|
|
2965
3247
|
}
|
|
2966
|
-
|
|
3248
|
+
}
|
|
3249
|
+
startHeartbeat() {
|
|
3250
|
+
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
3251
|
+
this.heartbeatTimer = setInterval(async () => {
|
|
3252
|
+
if (!this.triggerClient || this.isClosed) return;
|
|
2967
3253
|
try {
|
|
2968
|
-
await this.triggerClient.
|
|
3254
|
+
await this.triggerClient.query("SELECT 1");
|
|
3255
|
+
this.lastHeartbeatOn = (/* @__PURE__ */ new Date()).toISOString();
|
|
2969
3256
|
} catch (error) {
|
|
2970
|
-
logger.error(`
|
|
2971
|
-
|
|
2972
|
-
}
|
|
2973
|
-
const delay = this.INITIAL_RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts);
|
|
2974
|
-
logger.info(
|
|
2975
|
-
`Attempting to reconnect trigger client in ${delay / 1e3} seconds... (Attempt ${this.reconnectAttempts + 1}/${this.MAX_RECONNECT_ATTEMPTS})`
|
|
2976
|
-
);
|
|
2977
|
-
await new Promise((resolve2) => setTimeout(resolve2, delay));
|
|
2978
|
-
this.reconnectAttempts++;
|
|
2979
|
-
try {
|
|
2980
|
-
await this.listenForDbTriggers();
|
|
2981
|
-
this.reconnectAttempts = 0;
|
|
2982
|
-
} catch (error) {
|
|
2983
|
-
logger.error(`Reconnection attempt ${this.reconnectAttempts} failed: ${error}`);
|
|
2984
|
-
if (this.reconnectAttempts < this.MAX_RECONNECT_ATTEMPTS) {
|
|
2985
|
-
await this.reconnectTriggerClient();
|
|
3257
|
+
logger.error(`Trigger client heartbeat failed, reconnecting: ${error}`);
|
|
3258
|
+
void this.reconnectTriggerClient();
|
|
2986
3259
|
}
|
|
2987
|
-
}
|
|
3260
|
+
}, this.HEARTBEAT_INTERVAL_MS);
|
|
2988
3261
|
}
|
|
2989
3262
|
async listenForDbTriggers() {
|
|
2990
|
-
|
|
3263
|
+
const client = new Client3({
|
|
2991
3264
|
user: this.psqlConnectionPool.poolConfig.user,
|
|
2992
3265
|
host: this.psqlConnectionPool.poolConfig.host,
|
|
2993
3266
|
database: this.psqlConnectionPool.poolConfig.database,
|
|
@@ -2995,25 +3268,52 @@ var PsqlEngine = class extends SqlEngine {
|
|
|
2995
3268
|
port: this.psqlConnectionPool.poolConfig.port,
|
|
2996
3269
|
connectionTimeoutMillis: this.psqlConnectionPool.poolConfig.connectionTimeoutMillis
|
|
2997
3270
|
});
|
|
3271
|
+
this.triggerClient = client;
|
|
3272
|
+
client.on("error", (error) => {
|
|
3273
|
+
logger.error(`Trigger client error: ${error}`);
|
|
3274
|
+
void this.reconnectTriggerClient();
|
|
3275
|
+
});
|
|
3276
|
+
client.on("notification", async (msg) => {
|
|
3277
|
+
if (this.outboxConsumer && msg.channel === this.outboxConsumer.channel) {
|
|
3278
|
+
await this.outboxConsumer.drain();
|
|
3279
|
+
} else if (msg.channel === "insert" || msg.channel === "update" || msg.channel === "delete") {
|
|
3280
|
+
const payload = ObjectUtils3.safeParse(msg.payload);
|
|
3281
|
+
await this.handleTrigger(payload, msg.channel.toUpperCase());
|
|
3282
|
+
}
|
|
3283
|
+
});
|
|
3284
|
+
await client.connect();
|
|
3285
|
+
const channels = ["insert", "update", "delete"];
|
|
3286
|
+
if (this.outboxConsumer) channels.push(this.outboxConsumer.channel);
|
|
3287
|
+
for (const channel of channels) {
|
|
3288
|
+
await client.query(`LISTEN ${escapeColumnName(channel)}`);
|
|
3289
|
+
}
|
|
3290
|
+
this.isListenerConnected = true;
|
|
3291
|
+
this.lastHeartbeatOn = (/* @__PURE__ */ new Date()).toISOString();
|
|
3292
|
+
this.startHeartbeat();
|
|
3293
|
+
logger.info("Successfully connected to database triggers");
|
|
3294
|
+
void this.warnIfOutboxBacklogInDirectMode();
|
|
3295
|
+
}
|
|
3296
|
+
async warnIfOutboxBacklogInDirectMode() {
|
|
3297
|
+
if (this.eventDelivery.mode !== "direct") return;
|
|
2998
3298
|
try {
|
|
2999
|
-
await this.
|
|
3000
|
-
|
|
3001
|
-
|
|
3299
|
+
const tableExists = await this.psqlConnectionPool.runQuery(
|
|
3300
|
+
`SELECT to_regclass('public."dbEventOutbox"') AS exists;`,
|
|
3301
|
+
[],
|
|
3302
|
+
systemUser
|
|
3303
|
+
);
|
|
3304
|
+
if (!tableExists[0]?.exists) return;
|
|
3305
|
+
const pending = await this.psqlConnectionPool.runQuery(
|
|
3306
|
+
`SELECT COUNT(*)::int AS count FROM "dbEventOutbox" WHERE "processedOn" IS NULL;`,
|
|
3307
|
+
[],
|
|
3308
|
+
systemUser
|
|
3309
|
+
);
|
|
3310
|
+
if (Number(pending[0]?.count) > 0) {
|
|
3311
|
+
logger.warn(
|
|
3312
|
+
`eventDelivery is 'direct' but "dbEventOutbox" exists with ${pending[0].count} unprocessed rows \u2014 the database appears to have outbox-mode triggers installed. Switch eventDelivery to 'outbox' or regenerate direct-mode triggers.`
|
|
3313
|
+
);
|
|
3002
3314
|
}
|
|
3003
|
-
this.triggerClient.on("error", async (error) => {
|
|
3004
|
-
logger.error(`Trigger client error: ${error}`);
|
|
3005
|
-
await this.reconnectTriggerClient();
|
|
3006
|
-
});
|
|
3007
|
-
this.triggerClient.on("notification", async (msg) => {
|
|
3008
|
-
if (msg.channel === "insert" || msg.channel === "update" || msg.channel === "delete") {
|
|
3009
|
-
const payload = ObjectUtils3.safeParse(msg.payload);
|
|
3010
|
-
await this.handleTrigger(payload, msg.channel.toUpperCase());
|
|
3011
|
-
}
|
|
3012
|
-
});
|
|
3013
|
-
logger.info("Successfully connected to database triggers");
|
|
3014
3315
|
} catch (error) {
|
|
3015
|
-
logger.
|
|
3016
|
-
await this.reconnectTriggerClient();
|
|
3316
|
+
logger.warn(`Could not check dbEventOutbox backlog: ${error}`);
|
|
3017
3317
|
}
|
|
3018
3318
|
}
|
|
3019
3319
|
async handleTrigger(payload, mutationType) {
|
|
@@ -3027,10 +3327,21 @@ var PsqlEngine = class extends SqlEngine {
|
|
|
3027
3327
|
return sqlFullStatement;
|
|
3028
3328
|
}
|
|
3029
3329
|
generateDatabaseSchemaFromSchema(schema) {
|
|
3030
|
-
return generateDatabaseSchemaFromSchema(schema);
|
|
3330
|
+
return generateDatabaseSchemaFromSchema(schema, this.schemaGenerationOptions());
|
|
3031
3331
|
}
|
|
3032
3332
|
async diffDatabaseToSchema(schema) {
|
|
3033
|
-
return diffDatabaseToSchema(
|
|
3333
|
+
return diffDatabaseToSchema(
|
|
3334
|
+
schema,
|
|
3335
|
+
this.psqlConnectionPool,
|
|
3336
|
+
this.scratchDbName,
|
|
3337
|
+
this.schemaGenerationOptions()
|
|
3338
|
+
);
|
|
3339
|
+
}
|
|
3340
|
+
schemaGenerationOptions() {
|
|
3341
|
+
return {
|
|
3342
|
+
eventDelivery: this.eventDelivery.mode,
|
|
3343
|
+
outboxChannel: this.eventDelivery.outbox?.channel
|
|
3344
|
+
};
|
|
3034
3345
|
}
|
|
3035
3346
|
createNestedSelect(req, schema, item, routeData, sqlParams) {
|
|
3036
3347
|
if (!item.subquery) return "";
|
|
@@ -3468,7 +3779,13 @@ var ResturaEngine = class {
|
|
|
3468
3779
|
this.multerCommonUpload = getMulterUpload(this.resturaConfig.fileTempCachePath);
|
|
3469
3780
|
new TempCache(this.resturaConfig.fileTempCachePath);
|
|
3470
3781
|
this.psqlConnectionPool = psqlConnectionPool;
|
|
3471
|
-
|
|
3782
|
+
if (this.resturaConfig.queryMetadataKeys) {
|
|
3783
|
+
PsqlConnection.setQueryMetadataKeys(this.resturaConfig.queryMetadataKeys);
|
|
3784
|
+
}
|
|
3785
|
+
this.psqlEngine = new PsqlEngine(this.psqlConnectionPool, true, this.resturaConfig.scratchDatabaseSuffix, {
|
|
3786
|
+
mode: this.resturaConfig.eventDelivery,
|
|
3787
|
+
outbox: this.resturaConfig.eventOutbox
|
|
3788
|
+
});
|
|
3472
3789
|
await customApiFactory_default.loadApiFiles(this.resturaConfig.customApiFolderPath);
|
|
3473
3790
|
this.authenticationHandler = authenticationHandler;
|
|
3474
3791
|
app.use(compression());
|
|
@@ -3494,6 +3811,7 @@ var ResturaEngine = class {
|
|
|
3494
3811
|
this.expressApp = app;
|
|
3495
3812
|
await this.reloadEndpoints();
|
|
3496
3813
|
await this.initializeGeneratedTypesFolder();
|
|
3814
|
+
eventManager_default.validateHandlersAgainstSchema(this.schema, this.resturaConfig.notifyValidation);
|
|
3497
3815
|
logger.info("Restura Engine Initialized");
|
|
3498
3816
|
}
|
|
3499
3817
|
/**
|
|
@@ -3623,6 +3941,7 @@ var ResturaEngine = class {
|
|
|
3623
3941
|
}
|
|
3624
3942
|
async updateSchema(req, res) {
|
|
3625
3943
|
try {
|
|
3944
|
+
eventManager_default.validateHandlersAgainstSchema(req.data, this.resturaConfig.notifyValidation);
|
|
3626
3945
|
this.schema = sortObjectKeysAlphabetically(req.data);
|
|
3627
3946
|
await this.storeFileSystemSchema();
|
|
3628
3947
|
await this.reloadEndpoints();
|
|
@@ -4431,47 +4750,12 @@ function defaultsMatch(desired, live, column) {
|
|
|
4431
4750
|
const normalizedLive = live.replace(/::[a-z][a-z0-9_ ]*(\[\])?$/gi, "").trim();
|
|
4432
4751
|
return lowercaseOutsideStrings(desired.trim()) === lowercaseOutsideStrings(normalizedLive);
|
|
4433
4752
|
}
|
|
4434
|
-
|
|
4435
|
-
// src/restura/sql/PsqlTransaction.ts
|
|
4436
|
-
import pg4 from "pg";
|
|
4437
|
-
var { Client: Client3 } = pg4;
|
|
4438
|
-
var PsqlTransaction = class extends PsqlConnection {
|
|
4439
|
-
constructor(clientConfig, instanceId) {
|
|
4440
|
-
super(instanceId);
|
|
4441
|
-
this.clientConfig = clientConfig;
|
|
4442
|
-
this.client = new Client3(clientConfig);
|
|
4443
|
-
this.connectPromise = this.client.connect();
|
|
4444
|
-
this.beginTransactionPromise = this.beginTransaction();
|
|
4445
|
-
}
|
|
4446
|
-
client;
|
|
4447
|
-
beginTransactionPromise;
|
|
4448
|
-
connectPromise;
|
|
4449
|
-
async close() {
|
|
4450
|
-
if (this.client) {
|
|
4451
|
-
await this.client.end();
|
|
4452
|
-
}
|
|
4453
|
-
}
|
|
4454
|
-
async beginTransaction() {
|
|
4455
|
-
await this.connectPromise;
|
|
4456
|
-
return this.client.query("BEGIN");
|
|
4457
|
-
}
|
|
4458
|
-
async rollback() {
|
|
4459
|
-
return this.query("ROLLBACK");
|
|
4460
|
-
}
|
|
4461
|
-
async commit() {
|
|
4462
|
-
return this.query("COMMIT");
|
|
4463
|
-
}
|
|
4464
|
-
async release() {
|
|
4465
|
-
return this.client.end();
|
|
4466
|
-
}
|
|
4467
|
-
async query(query, values) {
|
|
4468
|
-
await this.connectPromise;
|
|
4469
|
-
await this.beginTransactionPromise;
|
|
4470
|
-
return this.client.query(query, values);
|
|
4471
|
-
}
|
|
4472
|
-
};
|
|
4473
4753
|
export {
|
|
4754
|
+
DEFAULT_OUTBOX_CHANNEL,
|
|
4755
|
+
EventManager,
|
|
4756
|
+
EventOutboxConsumer,
|
|
4474
4757
|
HtmlStatusCodes,
|
|
4758
|
+
OUTBOX_TABLE_NAME,
|
|
4475
4759
|
PsqlConnection,
|
|
4476
4760
|
PsqlEngine,
|
|
4477
4761
|
PsqlPool,
|
|
@@ -4481,17 +4765,21 @@ export {
|
|
|
4481
4765
|
apiGenerator,
|
|
4482
4766
|
createDeleteTriggerSql,
|
|
4483
4767
|
createInsertTriggerSql,
|
|
4768
|
+
createOutboxTableSql,
|
|
4484
4769
|
createUpdateTriggerSql,
|
|
4770
|
+
defaultEventOutboxOptions,
|
|
4485
4771
|
diffDatabaseToSchema,
|
|
4486
4772
|
diffSchemaToDatabase,
|
|
4487
4773
|
escapeColumnName,
|
|
4488
4774
|
eventManager_default as eventManager,
|
|
4489
4775
|
filterPsqlParser_default as filterPsqlParser,
|
|
4490
4776
|
generateDatabaseSchemaFromSchema,
|
|
4777
|
+
generateNotifyTriggersSql,
|
|
4491
4778
|
getNewPublicSchemaAndScratchPool,
|
|
4492
4779
|
insertObjectQuery,
|
|
4493
4780
|
introspectDatabase,
|
|
4494
4781
|
isSchemaValid,
|
|
4782
|
+
isSensitiveColumnName,
|
|
4495
4783
|
isValueNumber,
|
|
4496
4784
|
logger,
|
|
4497
4785
|
modelGenerator,
|