@vrplatform/kysely 1.3.41 → 1.3.45-10
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/build/.data.tar +0 -0
- package/build/main/camel-case/index.js +1 -1
- package/build/main/camel-case/index.js.map +1 -1
- package/build/main/control-plane/index.d.ts +368 -0
- package/build/main/control-plane/index.js +64 -0
- package/build/main/control-plane/index.js.map +1 -0
- package/build/main/domain.d.ts +4 -0
- package/build/main/domain.js +3 -0
- package/build/main/domain.js.map +1 -0
- package/build/main/error.d.ts +2 -1
- package/build/main/error.js +2 -1
- package/build/main/error.js.map +1 -1
- package/build/main/index.d.ts +13 -16
- package/build/main/index.js +145 -65
- package/build/main/index.js.map +1 -1
- package/build/main/isomorphic.d.ts +5 -5
- package/build/main/isomorphic.js +4 -10
- package/build/main/isomorphic.js.map +1 -1
- package/build/main/local/digest.d.ts +3 -3
- package/build/main/local/digest.js.map +1 -1
- package/build/main/local/generate.js +10 -10
- package/build/main/local/generate.js.map +1 -1
- package/build/main/local/index.d.ts +5 -1
- package/build/main/local/index.js +215 -6
- package/build/main/local/index.js.map +1 -1
- package/build/main/local/prune-pulled-schema.js +4 -1
- package/build/main/local/prune-pulled-schema.js.map +1 -1
- package/build/main/migration.d.ts +7 -0
- package/build/main/migration.js +11 -0
- package/build/main/migration.js.map +1 -0
- package/build/main/pganalyze-comment-plugin/comment-transformer.js +0 -1
- package/build/main/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
- package/build/main/pganalyze-comment-plugin/index.js +16 -3
- package/build/main/pganalyze-comment-plugin/index.js.map +1 -1
- package/build/main/plugins.d.ts +2 -2
- package/build/main/plugins.js.map +1 -1
- package/build/main/postgres-error.d.ts +8 -0
- package/build/main/postgres-error.js +21 -0
- package/build/main/postgres-error.js.map +1 -0
- package/build/main/query/index.d.ts +1 -0
- package/build/main/query/index.js +1 -0
- package/build/main/query/index.js.map +1 -1
- package/build/main/query/listing/status.d.ts +2 -12
- package/build/main/query/listing/status.js +31 -19
- package/build/main/query/listing/status.js.map +1 -1
- package/build/main/query/tenant/billing-partner.d.ts +4 -0
- package/build/main/query/tenant/billing-partner.js +8 -0
- package/build/main/query/tenant/billing-partner.js.map +1 -0
- package/build/main/query/tenant/index.d.ts +2 -0
- package/build/main/query/tenant/index.js +19 -0
- package/build/main/query/tenant/index.js.map +1 -0
- package/build/main/query/tenant/status.d.ts +14 -0
- package/build/main/query/tenant/status.js +40 -0
- package/build/main/query/tenant/status.js.map +1 -0
- package/build/main/regional.d.ts +60 -0
- package/build/main/regional.js +205 -0
- package/build/main/regional.js.map +1 -0
- package/build/main/test/index.d.ts +3 -14
- package/build/main/test/index.js +0 -23
- package/build/main/test/index.js.map +1 -1
- package/build/main/transaction.d.ts +3 -3
- package/build/main/transaction.js.map +1 -1
- package/build/main/v1.generated.d.ts +593 -23
- package/build/main/v1.generated.js.map +1 -1
- package/build/migrations-v2/0000000000000-baseline.ts +5 -0
- package/build/migrations-v2/0000000000001-public-audit-events-v2.ts +137 -0
- package/build/migrations-v2/0000000000002-audit-recovery-watermarks.ts +30 -0
- package/build/migrations-v2/0000000000003-audit-effect-recovery-watermark.ts +13 -0
- package/build/migrations-v2/0000000000004-audit-event-projected-at.ts +15 -0
- package/build/migrations-v2/0000000000005-audit-recovery-indexes.ts +63 -0
- package/build/migrations-v2/0000000000006-audit-action-public-event-projected-at.ts +22 -0
- package/build/migrations-v2/0000000000007-audit-action-public-event-projected-at-backfill.ts +35 -0
- package/build/migrations-v2/0000000000008-global-user-attribution.ts +33 -0
- package/build/migrations-v2/0000000000008-team-issue-rule-state.ts +52 -0
- package/build/migrations-v2/0000000000009-reservation-issue-projections.ts +45 -0
- package/build/migrations-v2/0000000000010-bank-rule-application-bank-record-delete-cascade.ts +26 -0
- package/build/migrations-v2/0000000000011-guest-balance-journal-entry-lookup-index.ts +25 -0
- package/build/migrations-v2/0000000000012-trial-free-analytics-billing-status.ts +72 -0
- package/build/migrations-v2/0000000000013-ui-permission-bundles.ts +45 -0
- package/build/migrations-v2/0000000000014-ui-permission-bundle-top-up.ts +32 -0
- package/build/migrations-v2/0000000000016-managed-team-access.ts +34 -0
- package/build/migrations-v2/0000000000017-drop-trial-until.ts +42 -0
- package/build/migrations-v2/0000000000018-accounting-integrity-monitoring.ts +276 -0
- package/build/migrations-v2/0000000000019-accounting-integrity-run-shards.ts +26 -0
- package/build/migrations-v2/0000000000020-accounting-integrity-case-classification.ts +52 -0
- package/build/migrations-v2/0000000000021-payment-line-classification-monitor-indexes.ts +31 -0
- package/build/migrations-v2/0000000000022-accounting-integrity-controlled-repairs.ts +281 -0
- package/build/migrations-v2/0000000000023-line-classification-usage.ts +325 -0
- package/build/migrations-v2/0000000000024-tenant-region-migration.ts +108 -0
- package/build/migrations-v2/0000000000025-partner-ach-denial-default.ts +30 -0
- package/build/migrations-v2/0000000000026-line-classification-usage-capture.ts +399 -0
- package/build/migrations-v2/0000000000027-payout-replacement-chain.ts +27 -0
- package/build/migrations-v2/0000000000028-accounting-integrity-operator-workflow.ts +108 -0
- package/build/migrations-v2/0000000000029-accounting-integrity-definition-artifacts.ts +40 -0
- package/build/migrations-v2/0000000000030-accounting-integrity-review-metadata-compatibility.ts +49 -0
- package/build/module/camel-case/index.js +1 -1
- package/build/module/camel-case/index.js.map +1 -1
- package/build/module/control-plane/index.d.ts +368 -0
- package/build/module/control-plane/index.js +50 -0
- package/build/module/control-plane/index.js.map +1 -0
- package/build/module/domain.d.ts +4 -0
- package/build/module/domain.js +2 -0
- package/build/module/domain.js.map +1 -0
- package/build/module/error.d.ts +2 -1
- package/build/module/error.js +3 -1
- package/build/module/error.js.map +1 -1
- package/build/module/index.d.ts +13 -16
- package/build/module/index.js +146 -63
- package/build/module/index.js.map +1 -1
- package/build/module/isomorphic.d.ts +5 -5
- package/build/module/isomorphic.js +1 -6
- package/build/module/isomorphic.js.map +1 -1
- package/build/module/local/digest.d.ts +3 -3
- package/build/module/local/digest.js.map +1 -1
- package/build/module/local/generate.js +10 -10
- package/build/module/local/generate.js.map +1 -1
- package/build/module/local/index.d.ts +5 -1
- package/build/module/local/index.js +216 -7
- package/build/module/local/index.js.map +1 -1
- package/build/module/local/prune-pulled-schema.js +4 -1
- package/build/module/local/prune-pulled-schema.js.map +1 -1
- package/build/module/migration.d.ts +7 -0
- package/build/module/migration.js +8 -0
- package/build/module/migration.js.map +1 -0
- package/build/module/pganalyze-comment-plugin/comment-transformer.js.map +1 -1
- package/build/module/pganalyze-comment-plugin/index.js.map +1 -1
- package/build/module/plugins.d.ts +2 -2
- package/build/module/plugins.js.map +1 -1
- package/build/module/postgres-error.d.ts +8 -0
- package/build/module/postgres-error.js +18 -0
- package/build/module/postgres-error.js.map +1 -0
- package/build/module/query/index.d.ts +1 -0
- package/build/module/query/index.js +1 -0
- package/build/module/query/index.js.map +1 -1
- package/build/module/query/listing/status.d.ts +2 -12
- package/build/module/query/listing/status.js +31 -17
- package/build/module/query/listing/status.js.map +1 -1
- package/build/module/query/tenant/billing-partner.d.ts +4 -0
- package/build/module/query/tenant/billing-partner.js +5 -0
- package/build/module/query/tenant/billing-partner.js.map +1 -0
- package/build/module/query/tenant/index.d.ts +2 -0
- package/build/module/query/tenant/index.js +3 -0
- package/build/module/query/tenant/index.js.map +1 -0
- package/build/module/query/tenant/status.d.ts +14 -0
- package/build/module/query/tenant/status.js +35 -0
- package/build/module/query/tenant/status.js.map +1 -0
- package/build/module/regional.d.ts +60 -0
- package/build/module/regional.js +162 -0
- package/build/module/regional.js.map +1 -0
- package/build/module/test/index.d.ts +3 -14
- package/build/module/test/index.js +1 -23
- package/build/module/test/index.js.map +1 -1
- package/build/module/transaction.d.ts +3 -3
- package/build/module/transaction.js.map +1 -1
- package/build/module/v1.generated.d.ts +593 -23
- package/build/module/v1.generated.js.map +1 -1
- package/package.json +18 -9
- package/build/main/tsconfig.main.tsbuildinfo +0 -1
- package/build/module/tsconfig.esm.tsbuildinfo +0 -1
package/build/module/index.js
CHANGED
|
@@ -1,46 +1,141 @@
|
|
|
1
1
|
import { backOff } from 'exponential-backoff';
|
|
2
|
-
import { PostgresJSDialect } from 'kysely-postgres-js';
|
|
2
|
+
import { PostgresJSDialect, PostgresJSDriver, } from 'kysely-postgres-js';
|
|
3
3
|
import postgres from 'postgres';
|
|
4
|
+
import { withControlPlaneSchema } from './control-plane';
|
|
4
5
|
import { KyselyError } from './error';
|
|
5
6
|
import { getKysely } from './plugins';
|
|
6
7
|
export * from './error';
|
|
7
8
|
export * from './isomorphic';
|
|
9
|
+
export * from './postgres-error';
|
|
8
10
|
export * from './query';
|
|
11
|
+
export * from './regional';
|
|
9
12
|
export * from './transaction';
|
|
10
13
|
import { parseDuration } from '@vrplatform/utils';
|
|
11
|
-
const retryableMessages = [
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const retryableMessages = [
|
|
15
|
+
'CONNECTION_CLOSED',
|
|
16
|
+
'CONNECT_TIMEOUT',
|
|
17
|
+
'Idle connection closed by Hyperdrive.',
|
|
18
|
+
'server_login_retry',
|
|
19
|
+
];
|
|
20
|
+
const postgresRetryAttempts = 3;
|
|
21
|
+
function isRetryableConnectionError(error) {
|
|
22
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
23
|
+
return retryableMessages.some((retryable) => message.includes(retryable));
|
|
24
|
+
}
|
|
25
|
+
function retryPostgres(operation, retry) {
|
|
26
|
+
return backOff(operation, {
|
|
27
|
+
numOfAttempts: postgresRetryAttempts,
|
|
28
|
+
startingDelay: parseDuration('1s'),
|
|
29
|
+
maxDelay: parseDuration('5s'),
|
|
30
|
+
retry: (error, attemptNumber) => attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
class RetryingPostgresJSDialect extends PostgresJSDialect {
|
|
34
|
+
config;
|
|
35
|
+
constructor(config) {
|
|
36
|
+
super(config);
|
|
37
|
+
this.config = config;
|
|
38
|
+
}
|
|
39
|
+
createDriver() {
|
|
40
|
+
const driver = new PostgresJSDriver(this.config);
|
|
41
|
+
const connections = new WeakMap();
|
|
42
|
+
const getConnection = (connection) => {
|
|
43
|
+
const state = connections.get(connection);
|
|
44
|
+
if (!state)
|
|
45
|
+
throw new Error('Postgres connection state is unavailable');
|
|
46
|
+
return state;
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
init: () => driver.init(),
|
|
50
|
+
acquireConnection: async () => {
|
|
51
|
+
const state = {
|
|
52
|
+
connection: await driver.acquireConnection(),
|
|
53
|
+
inTransaction: false,
|
|
54
|
+
};
|
|
55
|
+
const connection = {
|
|
56
|
+
executeQuery: (compiledQuery) => retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
|
|
57
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
58
|
+
if (state.inTransaction ||
|
|
59
|
+
(!isRetryableConnectionError(error) &&
|
|
60
|
+
(compiledQuery.query.kind !== 'SelectQueryNode' ||
|
|
61
|
+
(message !==
|
|
62
|
+
'Egress connection severed outside of Hyperdrive' &&
|
|
63
|
+
message !== 'Network connection lost.')))) {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// Postgres.js already ejects a severed reserved connection.
|
|
67
|
+
// Acquire a new reservation before replaying the safe read.
|
|
68
|
+
state.connection = await driver.acquireConnection();
|
|
69
|
+
return true;
|
|
70
|
+
}),
|
|
71
|
+
streamQuery: (compiledQuery, chunkSize) => {
|
|
72
|
+
if (chunkSize === undefined) {
|
|
73
|
+
throw new Error('Postgres stream chunk size is required');
|
|
74
|
+
}
|
|
75
|
+
return state.connection.streamQuery(compiledQuery, chunkSize);
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
connections.set(connection, state);
|
|
79
|
+
return connection;
|
|
80
|
+
},
|
|
81
|
+
beginTransaction: async (connection, settings) => {
|
|
82
|
+
const state = getConnection(connection);
|
|
83
|
+
state.inTransaction = true;
|
|
84
|
+
try {
|
|
85
|
+
await driver.beginTransaction(state.connection, settings);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
state.inTransaction = false;
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
commitTransaction: async (connection) => {
|
|
93
|
+
const state = getConnection(connection);
|
|
94
|
+
try {
|
|
95
|
+
await driver.commitTransaction(state.connection);
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
state.inTransaction = false;
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
rollbackTransaction: async (connection) => {
|
|
102
|
+
const state = getConnection(connection);
|
|
103
|
+
try {
|
|
104
|
+
await driver.rollbackTransaction(state.connection);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
state.inTransaction = false;
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
111
|
+
rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
112
|
+
releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
113
|
+
releaseConnection: async (connection) => {
|
|
114
|
+
await driver.releaseConnection(getConnection(connection).connection);
|
|
115
|
+
connections.delete(connection);
|
|
116
|
+
},
|
|
117
|
+
destroy: () => driver.destroy(),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
15
121
|
export function useKysely(postgres, options) {
|
|
16
122
|
console.debug('Creating Kysely instance');
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
if (retryableMessages.some((m) => message?.includes(m))) {
|
|
28
|
-
return true;
|
|
29
|
-
}
|
|
30
|
-
return false;
|
|
31
|
-
},
|
|
32
|
-
});
|
|
33
|
-
},
|
|
34
|
-
}), {
|
|
123
|
+
const reserveConnection = postgres.reserve.bind(postgres);
|
|
124
|
+
postgres.reserve = async () => {
|
|
125
|
+
const connection = await retryPostgres(reserveConnection, isRetryableConnectionError);
|
|
126
|
+
if (options?.hyperdrive) {
|
|
127
|
+
const unsafe = connection.unsafe;
|
|
128
|
+
connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
|
|
129
|
+
}
|
|
130
|
+
return connection;
|
|
131
|
+
};
|
|
132
|
+
const kysely = getKysely(new RetryingPostgresJSDialect({ postgres }), {
|
|
35
133
|
repositoryName: options?.repositoryName,
|
|
36
134
|
log: options?.log,
|
|
37
135
|
});
|
|
38
136
|
kysely.destroy = async () => {
|
|
39
137
|
console.debug('Closing Kysely connection');
|
|
40
|
-
await
|
|
41
|
-
postgres.end({ timeout: 5000 }).catch(() => undefined),
|
|
42
|
-
new Promise((res) => setTimeout(res, 6000)),
|
|
43
|
-
]);
|
|
138
|
+
await postgres.end({ timeout: 5 }).catch(() => undefined);
|
|
44
139
|
const index = _connections.indexOf(postgres);
|
|
45
140
|
if (index !== -1)
|
|
46
141
|
_connections.splice(index, 1);
|
|
@@ -50,32 +145,37 @@ export function useKysely(postgres, options) {
|
|
|
50
145
|
let _connections = [];
|
|
51
146
|
export async function useAsyncPostgres(connectionString, opt) {
|
|
52
147
|
const delayMs = 2500;
|
|
53
|
-
const
|
|
54
|
-
const
|
|
148
|
+
const probe = opt?.probe === true;
|
|
149
|
+
const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;
|
|
150
|
+
const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;
|
|
55
151
|
const url = new URL(connectionString);
|
|
56
|
-
console.debug(`Creating Postgres connection with ${retries}
|
|
152
|
+
console.debug(`Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`);
|
|
57
153
|
if (_connections.length > 0)
|
|
58
154
|
console.warn(`We already have ${_connections.length} Postgres connections`);
|
|
59
155
|
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
60
156
|
try {
|
|
61
157
|
const sql = postgres(connectionString, {
|
|
62
158
|
ssl: ssl ? 'require' : false,
|
|
63
|
-
|
|
64
|
-
// idle_timeout: 10
|
|
159
|
+
target_session_attrs: 'read-write',
|
|
65
160
|
// enable prepare statements, pgbouncer on crunchy allows for prepared statements
|
|
66
161
|
prepare: true,
|
|
67
|
-
|
|
68
|
-
|
|
162
|
+
...(opt?.hyperdrive
|
|
163
|
+
? {
|
|
164
|
+
max: 5,
|
|
165
|
+
// Retire idle clients before Hyperdrive can close them asynchronously.
|
|
166
|
+
idle_timeout: 10,
|
|
167
|
+
}
|
|
168
|
+
: {
|
|
169
|
+
connect_timeout: 10,
|
|
170
|
+
idle_timeout: 60,
|
|
171
|
+
}),
|
|
69
172
|
});
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
// connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off
|
|
73
|
-
await sql `set statement_timeout to '30s';`;
|
|
74
|
-
await sql `set lock_timeout to '10s';`;
|
|
75
|
-
}
|
|
76
|
-
catch (e) {
|
|
77
|
-
console.warn('Failed to set statement timeout, continuing', e);
|
|
173
|
+
if (probe) {
|
|
174
|
+
await sql `select 1`;
|
|
78
175
|
}
|
|
176
|
+
// statement_timeout/lock_timeout are role-level settings on the cluster
|
|
177
|
+
// (ALTER ROLE application SET ...) so they cover every pooled
|
|
178
|
+
// connection; per-session SETs here only ever applied to one of them
|
|
79
179
|
_connections.push(sql);
|
|
80
180
|
return sql;
|
|
81
181
|
}
|
|
@@ -93,32 +193,15 @@ export async function useAsyncKysely(connectionString, opt) {
|
|
|
93
193
|
const sql = await useAsyncPostgres(connectionString, opt);
|
|
94
194
|
return useKysely(sql, opt);
|
|
95
195
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
export function usePostgres(connectionString, opt) {
|
|
100
|
-
if (!connectionString)
|
|
101
|
-
throw new KyselyError('No connection string');
|
|
102
|
-
const ssl = opt?.forceDisableSSL !== true;
|
|
103
|
-
const url = new URL(connectionString);
|
|
104
|
-
console.debug(`Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`);
|
|
105
|
-
const pg = postgres(connectionString, {
|
|
106
|
-
ssl: ssl ? 'require' : false,
|
|
107
|
-
});
|
|
108
|
-
_connections.push(pg);
|
|
109
|
-
return pg;
|
|
196
|
+
export async function useAsyncControlPlaneKysely(connectionString, opt) {
|
|
197
|
+
const sql = await useAsyncPostgres(connectionString, opt);
|
|
198
|
+
return withControlPlaneSchema(useKysely(sql, opt), 'public');
|
|
110
199
|
}
|
|
111
200
|
export async function forceCloseAllPostgres(timeoutMs = 5000) {
|
|
112
201
|
await Promise.race([
|
|
113
|
-
Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs }).catch(() => undefined))),
|
|
202
|
+
Promise.all(_connections.map((pg) => pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined))),
|
|
114
203
|
new Promise((res) => setTimeout(res, timeoutMs + 1000)),
|
|
115
204
|
]);
|
|
116
205
|
_connections = [];
|
|
117
206
|
}
|
|
118
|
-
export class DatabaseError extends Error {
|
|
119
|
-
constructor(message, cause) {
|
|
120
|
-
super(message);
|
|
121
|
-
this.cause = cause;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
207
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,S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KAAU,EAAE;QACvC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAAA,CACpB;CACF","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './query';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n retries?: false | number;\n};\n\nconst retryableMessages = ['CONNECTION_CLOSED'];\n\nexport type Kysely = K<DB>;\nexport type Postgres = Sql;\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function useKysely(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely(\n new PostgresJSDialect({\n postgres,\n onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (retryableMessages.some((m) => message?.includes(m))) {\n return true;\n }\n return false;\n },\n });\n },\n }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await Promise.race([\n postgres.end({ timeout: 5000 }).catch(() => undefined),\n new Promise((res) => setTimeout(res, 6000)),\n ]);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const retries = opt?.retries === false ? 0 : opt?.retries || 3;\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with ${retries} retries and ssl=${ssl} and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n // connect_timeout: 10\n // idle_timeout: 10\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n connect_timeout: 10,\n idle_timeout: 60,\n });\n\n await sql`select 1`;\n try {\n // connect 30s, idle 60s, max lifetime 45min, statement 60s, lock 10s, log_min_duration 20s, log_lock_waits off\n await sql`set statement_timeout to '30s';`;\n await sql`set lock_timeout to '10s';`;\n } catch (e) {\n console.warn('Failed to set statement timeout, continuing', e);\n }\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\n/**\n * @deprecated This method is deprecated in favor of the useAsyncKysely method.\n */\nexport function usePostgres(\n connectionString?: string,\n opt?: Pick<PgOpt, 'forceDisableSSL'>\n) {\n if (!connectionString) throw new KyselyError('No connection string');\n const ssl = opt?.forceDisableSSL !== true;\n const url = new URL(connectionString);\n console.debug(\n `Creating sync Postgres connection with ssl=${ssl} and port=${url.port}`\n );\n const pg = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n });\n _connections.push(pg);\n return pg;\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n\nexport class DatabaseError extends Error {\n constructor(message: string, cause: any) {\n super(message);\n this.cause = cause;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AAQ9C,OAAO,EACL,iBAAiB,EAEjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,QAAsB,MAAM,UAAU,CAAC;AAC9C,OAAO,EAAuB,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAE9B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAelD,MAAM,iBAAiB,GAAG;IACxB,mBAAmB;IACnB,iBAAiB;IACjB,uCAAuC;IACvC,oBAAoB;CACrB,CAAC;AACF,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,SAAS,0BAA0B,CAAC,KAAc;IAChD,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,aAAa,CACpB,SAA2B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C,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,sBAAsB,CAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type {\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n Transaction as T,\n} from 'kysely';\nimport {\n PostgresJSDialect,\n type PostgresJSDialectConfig,\n PostgresJSDriver,\n} from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n hyperdrive?: true;\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: true;\n retries?: false | number;\n} & Pick<KyselyOpts, 'hyperdrive'>;\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n 'server_login_retry',\n];\nconst postgresRetryAttempts = 3;\n\nfunction isRetryableConnectionError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return retryableMessages.some((retryable) => message.includes(retryable));\n}\n\nfunction retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>\n) {\n return backOff(operation, {\n numOfAttempts: postgresRetryAttempts,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error, attemptNumber) =>\n attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),\n });\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(private readonly config: PostgresJSDialectConfig) {\n super(config);\n }\n\n override createDriver(): Driver {\n const driver = new PostgresJSDriver(this.config);\n const connections = new WeakMap<\n DatabaseConnection,\n { connection: DatabaseConnection; inTransaction: boolean }\n >();\n const getConnection = (connection: DatabaseConnection) => {\n const state = connections.get(connection);\n if (!state) throw new Error('Postgres connection state is unavailable');\n return state;\n };\n\n return {\n init: () => driver.init(),\n acquireConnection: async () => {\n const state = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: (compiledQuery) =>\n retryPostgres(\n () => state.connection.executeQuery(compiledQuery),\n async (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n state.inTransaction ||\n (!isRetryableConnectionError(error) &&\n (compiledQuery.query.kind !== 'SelectQueryNode' ||\n (message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.')))\n ) {\n return false;\n }\n\n // Postgres.js already ejects a severed reserved connection.\n // Acquire a new reservation before replaying the safe read.\n state.connection = await driver.acquireConnection();\n return true;\n }\n ),\n streamQuery: (compiledQuery, chunkSize) => {\n if (chunkSize === undefined) {\n throw new Error('Postgres stream chunk size is required');\n }\n return state.connection.streamQuery(compiledQuery, chunkSize);\n },\n };\n connections.set(connection, state);\n return connection;\n },\n beginTransaction: async (connection, settings) => {\n const state = getConnection(connection);\n state.inTransaction = true;\n try {\n await driver.beginTransaction(state.connection, settings);\n } catch (error) {\n state.inTransaction = false;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.commitTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n rollbackTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.rollbackTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n savepoint: (connection, savepointName, compileQuery) =>\n driver.savepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n driver.rollbackToSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n driver.releaseSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseConnection: async (connection) => {\n await driver.releaseConnection(getConnection(connection).connection);\n connections.delete(connection);\n },\n destroy: () => driver.destroy(),\n };\n }\n}\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const reserveConnection = postgres.reserve.bind(postgres);\n postgres.reserve = async () => {\n const connection = await retryPostgres(\n reserveConnection,\n isRetryableConnectionError\n );\n if (options?.hyperdrive) {\n const unsafe = connection.unsafe;\n connection.unsafe = (query, parameters, queryOptions) =>\n unsafe(query, parameters, { ...queryOptions, prepare: true });\n }\n return connection;\n };\n const kysely = getKysely<Database>(\n new RetryingPostgresJSDialect({ postgres }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n }),\n });\n\n if (probe) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return withControlPlaneSchema(useKysely<ControlPlaneDB>(sql, opt), 'public');\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { ControlledTransaction as CT, Kysely as K, Transaction as T } from 'kysely';
|
|
2
2
|
export type { ColumnType, Expression, ExpressionBuilder, ExpressionOrFactory, Generated, Insertable, JSONColumnType, KyselyPlugin, Nullable, OperandExpression, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, RootOperationNode, Selectable, SelectQueryBuilder, SqlBool, UnknownRow, Updateable, } from 'kysely';
|
|
3
3
|
export { jsonArrayFrom } from 'kysely/helpers/postgres';
|
|
4
|
+
export * from './domain';
|
|
4
5
|
export * from './v1.generated';
|
|
5
6
|
import type { DB } from './v1.generated';
|
|
6
|
-
export type
|
|
7
|
+
export type DatabaseKysely<Database> = K<Database>;
|
|
8
|
+
export type DatabaseTransaction<Database> = T<Database>;
|
|
9
|
+
export type Transaction = DatabaseTransaction<DB>;
|
|
7
10
|
export type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;
|
|
8
11
|
export { sql } from 'kysely';
|
|
9
|
-
export type Kysely =
|
|
10
|
-
export declare class DatabaseError extends Error {
|
|
11
|
-
constructor(message: string, cause: any);
|
|
12
|
-
}
|
|
12
|
+
export type Kysely = DatabaseKysely<DB>;
|
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
export { jsonArrayFrom } from 'kysely/helpers/postgres';
|
|
2
|
+
export * from './domain';
|
|
2
3
|
export * from './v1.generated';
|
|
3
4
|
export { sql } from 'kysely';
|
|
4
|
-
export class DatabaseError extends Error {
|
|
5
|
-
constructor(message, cause) {
|
|
6
|
-
super(message);
|
|
7
|
-
this.cause = cause;
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
5
|
//# sourceMappingURL=isomorphic.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"isomorphic.js","sourceRoot":"src/","sources":["isomorphic.ts"],"names":[],"mappings":"AA2BA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,cAAc,UAAU,CAAC;AACzB,cAAc,gBAAgB,CAAC;AAQ/B,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["import type {\n ControlledTransaction as CT,\n Kysely as K,\n Transaction as T,\n} from 'kysely';\n\nexport type {\n ColumnType,\n Expression,\n ExpressionBuilder,\n ExpressionOrFactory,\n Generated,\n Insertable,\n JSONColumnType,\n KyselyPlugin,\n Nullable,\n OperandExpression,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n Selectable,\n SelectQueryBuilder,\n SqlBool,\n UnknownRow,\n Updateable,\n} from 'kysely';\nexport { jsonArrayFrom } from 'kysely/helpers/postgres';\nexport * from './domain';\nexport * from './v1.generated';\n\nimport type { DB } from './v1.generated';\n\nexport type DatabaseKysely<Database> = K<Database>;\nexport type DatabaseTransaction<Database> = T<Database>;\nexport type Transaction = DatabaseTransaction<DB>;\nexport type ControlledTransaction<S extends string[] = string[]> = CT<DB, S>;\nexport { sql } from 'kysely';\n\nexport type Kysely = DatabaseKysely<DB>;\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
export declare function ensureDigestFunction(kysely:
|
|
3
|
-
export declare function ensureGenRandomBytesFunction(kysely:
|
|
1
|
+
import { type DatabaseKysely } from '../isomorphic';
|
|
2
|
+
export declare function ensureDigestFunction<Database>(kysely: DatabaseKysely<Database>): Promise<void>;
|
|
3
|
+
export declare function ensureGenRandomBytesFunction<Database>(kysely: DatabaseKysely<Database>): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"digest.js","sourceRoot":"src/","sources":["local/digest.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,GAAG,EAAE,MAAM,eAAe,CAAC;AAEzD,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,MAAgC;IAEhC,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,6BAA6B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;KASR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAgC;IAEhC,IAAI,CAAC;QACH,MAAM,GAAG,CAAA,4BAA4B,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACxD,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,GAAG,CAAA;;;;;;;;;;;;;;;;;;KAkBR,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;AACH,CAAC","sourcesContent":["import { type DatabaseKysely, sql } from '../isomorphic';\n\nexport async function ensureDigestFunction<Database>(\n kysely: DatabaseKysely<Database>\n) {\n try {\n await sql`select digest('', 'sha256')`.execute(kysely);\n } catch {\n await sql`\n create or replace function digest(input text, algo text)\n returns bytea\n language sql\n immutable\n strict\n as $$\n select '\\\\x0000000000000000000000000000000000000000000000000000000000000000'::bytea;\n $$;\n `.execute(kysely);\n }\n}\n\nexport async function ensureGenRandomBytesFunction<Database>(\n kysely: DatabaseKysely<Database>\n) {\n try {\n await sql`select gen_random_bytes(1)`.execute(kysely);\n } catch {\n await sql`\n create or replace function gen_random_bytes(p_len integer)\n returns bytea\n language sql\n stable\n strict\n as $$\n select substring(\n decode(\n repeat(\n md5(random()::text || now()::text),\n ((p_len + 15) / 16)\n ),\n 'hex'\n )\n from 1 for p_len\n );\n $$;\n `.execute(kysely);\n }\n}\n"]}
|
|
@@ -6,11 +6,15 @@ import { PGlite } from '@electric-sql/pglite';
|
|
|
6
6
|
import { FileMigrationProvider, Migrator } from 'kysely';
|
|
7
7
|
import codegen from 'kysely-codegen';
|
|
8
8
|
import { PGliteDialect } from 'kysely-pglite-dialect';
|
|
9
|
+
import { appMigrationEpoch } from '../migration';
|
|
9
10
|
import { getKysely } from '../plugins';
|
|
10
11
|
async function normalizeGeneratedTypes(root) {
|
|
11
12
|
const outFile = path.join(root, 'src/v1.generated.ts');
|
|
12
13
|
const current = await Bun.file(outFile).text();
|
|
13
|
-
const next = current
|
|
14
|
+
const next = current
|
|
15
|
+
.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;')
|
|
16
|
+
.replace(' managedTeamAccess: Generated<string>;\n', ' managedTeamAccess: Generated<"all" | "assigned">;\n')
|
|
17
|
+
.replace(' slug: string;\n', ' slug: Generated<string>;\n');
|
|
14
18
|
if (next !== current) {
|
|
15
19
|
await Bun.write(outFile, next);
|
|
16
20
|
}
|
|
@@ -30,14 +34,14 @@ async function migrateKysely(root, kysely) {
|
|
|
30
34
|
console.log('init migrating kysely ....');
|
|
31
35
|
const migrator = new Migrator({
|
|
32
36
|
db: kysely,
|
|
33
|
-
migrationTableSchema:
|
|
34
|
-
migrationTableName:
|
|
35
|
-
migrationLockTableName:
|
|
37
|
+
migrationTableSchema: appMigrationEpoch.tableSchema,
|
|
38
|
+
migrationTableName: appMigrationEpoch.tableName,
|
|
39
|
+
migrationLockTableName: appMigrationEpoch.lockTableName,
|
|
36
40
|
provider: new FileMigrationProvider({
|
|
37
41
|
fs,
|
|
38
42
|
path,
|
|
39
43
|
// This needs to be an absolute path.
|
|
40
|
-
migrationFolder: path.join(root,
|
|
44
|
+
migrationFolder: path.join(root, appMigrationEpoch.folder),
|
|
41
45
|
}),
|
|
42
46
|
});
|
|
43
47
|
console.log('migrating kysely ....');
|
|
@@ -84,9 +88,6 @@ async function generateDump(root, dumpPath) {
|
|
|
84
88
|
outFile: path.join(root, 'src/v1.generated.ts'),
|
|
85
89
|
defaultSchemas: ['xxx'],
|
|
86
90
|
camelCase: true,
|
|
87
|
-
typeMapping: {
|
|
88
|
-
date: 'string',
|
|
89
|
-
},
|
|
90
91
|
dialect: codegen.getDialect('postgres'),
|
|
91
92
|
})
|
|
92
93
|
.catch(() => {
|
|
@@ -124,8 +125,7 @@ export async function createLocalKysely(root, dumpPath) {
|
|
|
124
125
|
return;
|
|
125
126
|
isDestroyed = true;
|
|
126
127
|
// const destroyTime = performance.now();
|
|
127
|
-
await originalDestroy()
|
|
128
|
-
await pglite.close().catch(() => undefined);
|
|
128
|
+
await originalDestroy();
|
|
129
129
|
//console.log(
|
|
130
130
|
// `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`
|
|
131
131
|
//);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACtE,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,KAAK,UAAU,uBAAuB,C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IACpD,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE,CAAC;QAC3B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,yCAAyC;QACzC,MAAM,eAAe,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/C,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC5C,cAAc;QACd,0EAA0E;QAC1E,IAAI;IAHwC,CAI7C,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAAA,CACf","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current.replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n );\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: 'core',\n migrationTableName: 'kysely_migration',\n migrationLockTableName: 'kysely_migration_lock',\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, 'migrations'),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n typeMapping: {\n date: 'string',\n },\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy().catch(() => undefined);\n await pglite.close().catch(() => undefined);\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EAAe,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACtE,OAAO,OAAO,MAAM,gBAAgB,CAAC;AACrC,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,KAAK,UAAU,uBAAuB,CAAC,IAAY;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,MAAM,IAAI,GAAG,OAAO;SACjB,OAAO,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CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { appMigrationEpoch } from '../migration';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current\n .replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n )\n .replace(\n ' managedTeamAccess: Generated<string>;\\n',\n ' managedTeamAccess: Generated<\"all\" | \"assigned\">;\\n'\n )\n .replace(' slug: string;\\n', ' slug: Generated<string>;\\n');\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: appMigrationEpoch.tableSchema,\n migrationTableName: appMigrationEpoch.tableName,\n migrationLockTableName: appMigrationEpoch.lockTableName,\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, appMigrationEpoch.folder),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy();\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type LogConfig } from 'kysely';
|
|
2
|
+
import type { ControlPlaneKysely } from '../index';
|
|
2
3
|
import type { DB } from '../v1.generated';
|
|
3
4
|
export declare const root: string;
|
|
4
5
|
export declare const dumpPath: string;
|
|
@@ -6,4 +7,7 @@ export type UseLocalKyselyOptions = {
|
|
|
6
7
|
repositoryName?: string;
|
|
7
8
|
log?: true | LogConfig;
|
|
8
9
|
};
|
|
9
|
-
export
|
|
10
|
+
export type LocalKysely = import('kysely').Kysely<DB> & {
|
|
11
|
+
controlPlaneKysely: ControlPlaneKysely;
|
|
12
|
+
};
|
|
13
|
+
export declare function useLocalKysely(args?: UseLocalKyselyOptions): Promise<LocalKysely>;
|