@zaaxch/grasp-postgres 0.0.0-stage → 0.2.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/README.md +9 -2
- package/dist/connection.d.ts +15 -0
- package/dist/connection.d.ts.map +1 -0
- package/dist/connection.js +105 -0
- package/dist/connection.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/store.d.ts +23 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +813 -0
- package/dist/store.js.map +1 -0
- package/dist/table.d.ts +49 -0
- package/dist/table.d.ts.map +1 -0
- package/dist/table.js +154 -0
- package/dist/table.js.map +1 -0
- package/package.json +47 -3
package/dist/store.js
ADDED
|
@@ -0,0 +1,813 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { GraspError, asUserId, } from '@zaaxch/grasp-core';
|
|
3
|
+
import { connectPostgres, createPgReadinessProbe, queryPg, resolvePgClient, runPgTransaction, } from './connection.js';
|
|
4
|
+
const SCHEMA_ADVISORY_LOCK_KEY = 72910451;
|
|
5
|
+
const SHELL_MIGRATIONS = [
|
|
6
|
+
{
|
|
7
|
+
key: '_grasp:001_init',
|
|
8
|
+
sql: `
|
|
9
|
+
CREATE TABLE IF NOT EXISTS _grasp_users (
|
|
10
|
+
id TEXT PRIMARY KEY,
|
|
11
|
+
email TEXT,
|
|
12
|
+
email_lower TEXT,
|
|
13
|
+
display_name TEXT,
|
|
14
|
+
avatar_url TEXT,
|
|
15
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
16
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
17
|
+
);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_users_email_lower
|
|
19
|
+
ON _grasp_users (email_lower)
|
|
20
|
+
WHERE email_lower IS NOT NULL;
|
|
21
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_users_created_desc
|
|
22
|
+
ON _grasp_users (created_at DESC, id DESC);
|
|
23
|
+
|
|
24
|
+
CREATE TABLE IF NOT EXISTS _grasp_entitlements (
|
|
25
|
+
user_id TEXT PRIMARY KEY,
|
|
26
|
+
plan_id TEXT NOT NULL,
|
|
27
|
+
status TEXT NOT NULL,
|
|
28
|
+
source TEXT NOT NULL,
|
|
29
|
+
stripe_customer_id TEXT,
|
|
30
|
+
stripe_subscription_id TEXT,
|
|
31
|
+
cancel_at_period_end BOOLEAN,
|
|
32
|
+
current_period_end TIMESTAMPTZ,
|
|
33
|
+
entitled_through TIMESTAMPTZ,
|
|
34
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
35
|
+
);
|
|
36
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_entitlements_stripe_customer
|
|
37
|
+
ON _grasp_entitlements (stripe_customer_id)
|
|
38
|
+
WHERE stripe_customer_id IS NOT NULL;
|
|
39
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_entitlements_stripe_sub
|
|
40
|
+
ON _grasp_entitlements (stripe_subscription_id)
|
|
41
|
+
WHERE stripe_subscription_id IS NOT NULL;
|
|
42
|
+
|
|
43
|
+
CREATE TABLE IF NOT EXISTS _grasp_webhook_events (
|
|
44
|
+
event_id TEXT PRIMARY KEY,
|
|
45
|
+
event_type TEXT NOT NULL,
|
|
46
|
+
status TEXT NOT NULL,
|
|
47
|
+
reason TEXT,
|
|
48
|
+
payload_json TEXT,
|
|
49
|
+
processed_at TIMESTAMPTZ NOT NULL
|
|
50
|
+
);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_webhook_events_status
|
|
52
|
+
ON _grasp_webhook_events (status, processed_at DESC);
|
|
53
|
+
|
|
54
|
+
CREATE TABLE IF NOT EXISTS _grasp_credit_balances (
|
|
55
|
+
user_id TEXT PRIMARY KEY,
|
|
56
|
+
balance BIGINT NOT NULL CHECK (balance >= 0),
|
|
57
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS _grasp_credits_ledger (
|
|
61
|
+
id TEXT PRIMARY KEY,
|
|
62
|
+
user_id TEXT NOT NULL,
|
|
63
|
+
delta BIGINT NOT NULL,
|
|
64
|
+
balance_after BIGINT NOT NULL,
|
|
65
|
+
reason TEXT NOT NULL,
|
|
66
|
+
idempotency_key TEXT UNIQUE,
|
|
67
|
+
created_at TIMESTAMPTZ NOT NULL
|
|
68
|
+
);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_credits_ledger_user_created
|
|
70
|
+
ON _grasp_credits_ledger (user_id, created_at DESC, id DESC);
|
|
71
|
+
|
|
72
|
+
CREATE TABLE IF NOT EXISTS _grasp_quota_scopes (
|
|
73
|
+
user_id TEXT NOT NULL,
|
|
74
|
+
resource TEXT NOT NULL,
|
|
75
|
+
seq BIGINT NOT NULL DEFAULT 1,
|
|
76
|
+
updated_at TIMESTAMPTZ NOT NULL,
|
|
77
|
+
PRIMARY KEY (user_id, resource)
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
CREATE TABLE IF NOT EXISTS _grasp_outbox_jobs (
|
|
81
|
+
id TEXT PRIMARY KEY,
|
|
82
|
+
job_name TEXT NOT NULL,
|
|
83
|
+
payload_json TEXT NOT NULL,
|
|
84
|
+
status TEXT NOT NULL,
|
|
85
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
86
|
+
max_attempts INTEGER NOT NULL,
|
|
87
|
+
run_after TIMESTAMPTZ NOT NULL,
|
|
88
|
+
lease_owner TEXT,
|
|
89
|
+
lease_until TIMESTAMPTZ,
|
|
90
|
+
last_error TEXT,
|
|
91
|
+
created_at TIMESTAMPTZ NOT NULL,
|
|
92
|
+
updated_at TIMESTAMPTZ NOT NULL
|
|
93
|
+
);
|
|
94
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_outbox_status_run_after
|
|
95
|
+
ON _grasp_outbox_jobs (status, run_after ASC, created_at ASC);
|
|
96
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_outbox_status_lease
|
|
97
|
+
ON _grasp_outbox_jobs (status, lease_until ASC);
|
|
98
|
+
|
|
99
|
+
CREATE TABLE IF NOT EXISTS _grasp_deleted_accounts (
|
|
100
|
+
id TEXT PRIMARY KEY,
|
|
101
|
+
user_id TEXT NOT NULL,
|
|
102
|
+
deleted_at TIMESTAMPTZ NOT NULL,
|
|
103
|
+
deleted_collections TEXT[] NOT NULL
|
|
104
|
+
);
|
|
105
|
+
CREATE INDEX IF NOT EXISTS idx_grasp_deleted_accounts_user
|
|
106
|
+
ON _grasp_deleted_accounts (user_id, deleted_at DESC);
|
|
107
|
+
`,
|
|
108
|
+
},
|
|
109
|
+
];
|
|
110
|
+
const PG_ROLE_REGEX = /^[a-zA-Z_][a-zA-Z0-9_-]{0,62}$/;
|
|
111
|
+
function mapPgUser(row) {
|
|
112
|
+
return {
|
|
113
|
+
id: asUserId(row.id),
|
|
114
|
+
email: row.email,
|
|
115
|
+
displayName: row.display_name,
|
|
116
|
+
avatarUrl: row.avatar_url,
|
|
117
|
+
createdAt: row.created_at.toISOString(),
|
|
118
|
+
updatedAt: row.updated_at.toISOString(),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function mapPgEntitlement(row) {
|
|
122
|
+
return {
|
|
123
|
+
userId: asUserId(row.user_id),
|
|
124
|
+
planId: row.plan_id,
|
|
125
|
+
status: row.status,
|
|
126
|
+
source: row.source,
|
|
127
|
+
...(row.stripe_customer_id !== null ? { stripeCustomerId: row.stripe_customer_id } : {}),
|
|
128
|
+
...(row.stripe_subscription_id !== null
|
|
129
|
+
? { stripeSubscriptionId: row.stripe_subscription_id }
|
|
130
|
+
: {}),
|
|
131
|
+
...(row.cancel_at_period_end !== null ? { cancelAtPeriodEnd: row.cancel_at_period_end } : {}),
|
|
132
|
+
...(row.current_period_end !== null ? { currentPeriodEnd: row.current_period_end } : {}),
|
|
133
|
+
...(row.entitled_through !== null ? { entitledThrough: row.entitled_through } : {}),
|
|
134
|
+
updatedAt: row.updated_at,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function mapPgWebhook(row) {
|
|
138
|
+
return {
|
|
139
|
+
eventId: row.event_id,
|
|
140
|
+
eventType: row.event_type,
|
|
141
|
+
status: row.status,
|
|
142
|
+
...(row.reason !== null ? { reason: row.reason } : {}),
|
|
143
|
+
...(row.payload_json !== null ? { payloadJson: row.payload_json } : {}),
|
|
144
|
+
processedAt: row.processed_at,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
function mapPgOutbox(row) {
|
|
148
|
+
return {
|
|
149
|
+
id: row.id,
|
|
150
|
+
jobName: row.job_name,
|
|
151
|
+
payloadJson: row.payload_json,
|
|
152
|
+
status: row.status,
|
|
153
|
+
attempts: Number(row.attempts),
|
|
154
|
+
maxAttempts: Number(row.max_attempts),
|
|
155
|
+
runAfter: row.run_after,
|
|
156
|
+
...(row.lease_owner !== null ? { leaseOwner: row.lease_owner } : {}),
|
|
157
|
+
...(row.lease_until !== null ? { leaseUntil: row.lease_until } : {}),
|
|
158
|
+
...(row.last_error !== null ? { lastError: row.last_error } : {}),
|
|
159
|
+
createdAt: row.created_at,
|
|
160
|
+
updatedAt: row.updated_at,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function encodeCursor(createdAt, id) {
|
|
164
|
+
return Buffer.from(JSON.stringify({ c: createdAt.toISOString(), id }), 'utf8').toString('base64url');
|
|
165
|
+
}
|
|
166
|
+
function decodeCursor(cursor) {
|
|
167
|
+
try {
|
|
168
|
+
const raw = Buffer.from(cursor, 'base64url').toString('utf8');
|
|
169
|
+
const parsed = JSON.parse(raw);
|
|
170
|
+
if (typeof parsed.c !== 'string' || typeof parsed.id !== 'string' || parsed.id.length === 0) {
|
|
171
|
+
throw new Error('Malformed cursor fields');
|
|
172
|
+
}
|
|
173
|
+
const createdAt = new Date(parsed.c);
|
|
174
|
+
if (Number.isNaN(createdAt.getTime())) {
|
|
175
|
+
throw new Error('Invalid cursor date');
|
|
176
|
+
}
|
|
177
|
+
return { createdAt, id: parsed.id };
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
throw GraspError.badRequest('Invalid pagination cursor');
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function assertPositiveInt(value, fieldName) {
|
|
184
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
185
|
+
throw GraspError.badRequest(`${fieldName} must be a positive integer`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function validatePgAppUser(appUser) {
|
|
189
|
+
if (appUser === undefined)
|
|
190
|
+
return undefined;
|
|
191
|
+
const trimmed = appUser.trim();
|
|
192
|
+
if (trimmed.length === 0)
|
|
193
|
+
return undefined;
|
|
194
|
+
if (!PG_ROLE_REGEX.test(trimmed)) {
|
|
195
|
+
throw GraspError.validation('Invalid PostgreSQL appUser role name', [
|
|
196
|
+
{ path: ['appUser'], message: `Role "${trimmed}" must match ${PG_ROLE_REGEX.source}` },
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
return trimmed;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Connects to PostgreSQL and constructs the complete `GraspShellStore` + SQL query & migration engine.
|
|
203
|
+
*/
|
|
204
|
+
export async function createPostgresStore(options) {
|
|
205
|
+
const appUser = validatePgAppUser(options.appUser);
|
|
206
|
+
const pool = connectPostgres(options);
|
|
207
|
+
return createPostgresStoreFromPool({
|
|
208
|
+
pool,
|
|
209
|
+
...(options.tables !== undefined ? { tables: options.tables } : {}),
|
|
210
|
+
...(appUser !== undefined ? { appUser } : {}),
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
export function createPostgresStoreFromPool(input) {
|
|
214
|
+
const { pool } = input;
|
|
215
|
+
const registeredTables = [...(input.tables ?? [])];
|
|
216
|
+
const appUser = validatePgAppUser(input.appUser);
|
|
217
|
+
const exec = (text, values, tx) => {
|
|
218
|
+
const client = resolvePgClient(pool, tx);
|
|
219
|
+
const mutableValues = [...values];
|
|
220
|
+
if (client !== undefined) {
|
|
221
|
+
return client.query(text, mutableValues);
|
|
222
|
+
}
|
|
223
|
+
return pool.query(text, mutableValues);
|
|
224
|
+
};
|
|
225
|
+
const withTransaction = (fn) => runPgTransaction(pool, fn);
|
|
226
|
+
const users = {
|
|
227
|
+
async upsertBySubject(params, tx) {
|
|
228
|
+
const now = params.now ?? new Date();
|
|
229
|
+
const emailLower = params.email !== null ? params.email.trim().toLowerCase() : null;
|
|
230
|
+
const res = await exec(`
|
|
231
|
+
INSERT INTO _grasp_users (id, email, email_lower, display_name, avatar_url, created_at, updated_at)
|
|
232
|
+
VALUES ($1, $2, $3, $4, $5, $6, $6)
|
|
233
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
234
|
+
email = EXCLUDED.email,
|
|
235
|
+
email_lower = EXCLUDED.email_lower,
|
|
236
|
+
display_name = EXCLUDED.display_name,
|
|
237
|
+
avatar_url = EXCLUDED.avatar_url,
|
|
238
|
+
updated_at = EXCLUDED.updated_at
|
|
239
|
+
RETURNING id, email, display_name, avatar_url, created_at, updated_at
|
|
240
|
+
`, [params.id, params.email, emailLower, params.displayName, params.avatarUrl, now], tx);
|
|
241
|
+
const row = res.rows[0];
|
|
242
|
+
if (row === undefined) {
|
|
243
|
+
throw GraspError.internal('Failed to upsert user record');
|
|
244
|
+
}
|
|
245
|
+
return mapPgUser(row);
|
|
246
|
+
},
|
|
247
|
+
async findById(userId, tx) {
|
|
248
|
+
const res = await exec(`SELECT id, email, display_name, avatar_url, created_at, updated_at FROM _grasp_users WHERE id = $1`, [userId], tx);
|
|
249
|
+
return res.rows[0] !== undefined ? mapPgUser(res.rows[0]) : null;
|
|
250
|
+
},
|
|
251
|
+
async findByEmail(email, tx) {
|
|
252
|
+
const normalized = email.trim().toLowerCase();
|
|
253
|
+
const res = await exec(`SELECT id, email, display_name, avatar_url, created_at, updated_at FROM _grasp_users WHERE email_lower = $1 LIMIT 1`, [normalized], tx);
|
|
254
|
+
return res.rows[0] !== undefined ? mapPgUser(res.rows[0]) : null;
|
|
255
|
+
},
|
|
256
|
+
async listUsers(opts = {}) {
|
|
257
|
+
const rawLimit = opts.limit ?? 50;
|
|
258
|
+
if (!Number.isSafeInteger(rawLimit) || rawLimit < 1 || rawLimit > 200) {
|
|
259
|
+
throw GraspError.badRequest('listUsers limit must be between 1 and 200');
|
|
260
|
+
}
|
|
261
|
+
const res = opts.cursor !== undefined
|
|
262
|
+
? (() => {
|
|
263
|
+
const decoded = decodeCursor(opts.cursor);
|
|
264
|
+
return exec(`
|
|
265
|
+
SELECT id, email, display_name, avatar_url, created_at, updated_at
|
|
266
|
+
FROM _grasp_users
|
|
267
|
+
WHERE (created_at < $1) OR (created_at = $1 AND id < $2)
|
|
268
|
+
ORDER BY created_at DESC, id DESC
|
|
269
|
+
LIMIT $3
|
|
270
|
+
`, [decoded.createdAt, decoded.id, rawLimit + 1]);
|
|
271
|
+
})()
|
|
272
|
+
: exec(`
|
|
273
|
+
SELECT id, email, display_name, avatar_url, created_at, updated_at
|
|
274
|
+
FROM _grasp_users
|
|
275
|
+
ORDER BY created_at DESC, id DESC
|
|
276
|
+
LIMIT $1
|
|
277
|
+
`, [rawLimit + 1]);
|
|
278
|
+
const rows = (await res).rows;
|
|
279
|
+
const hasMore = rows.length > rawLimit;
|
|
280
|
+
const page = hasMore ? rows.slice(0, rawLimit) : rows;
|
|
281
|
+
const last = page.at(-1);
|
|
282
|
+
return {
|
|
283
|
+
users: page.map(mapPgUser),
|
|
284
|
+
nextCursor: hasMore && last !== undefined ? encodeCursor(last.created_at, last.id) : null,
|
|
285
|
+
};
|
|
286
|
+
},
|
|
287
|
+
async deleteUserAndRecordAudit(params, tx) {
|
|
288
|
+
const client = resolvePgClient(pool, tx);
|
|
289
|
+
if (client === undefined) {
|
|
290
|
+
throw GraspError.internal('deleteUserAndRecordAudit requires an active transaction');
|
|
291
|
+
}
|
|
292
|
+
const deletedAt = params.now ?? new Date();
|
|
293
|
+
const deletedCollections = [...params.deletedCollections];
|
|
294
|
+
await exec(`DELETE FROM _grasp_users WHERE id = $1`, [params.userId], tx);
|
|
295
|
+
await exec(`DELETE FROM _grasp_entitlements WHERE user_id = $1`, [params.userId], tx);
|
|
296
|
+
await exec(`DELETE FROM _grasp_credit_balances WHERE user_id = $1`, [params.userId], tx);
|
|
297
|
+
await exec(`DELETE FROM _grasp_credits_ledger WHERE user_id = $1`, [params.userId], tx);
|
|
298
|
+
await exec(`DELETE FROM _grasp_quota_scopes WHERE user_id = $1`, [params.userId], tx);
|
|
299
|
+
await exec(`
|
|
300
|
+
INSERT INTO _grasp_deleted_accounts (id, user_id, deleted_at, deleted_collections)
|
|
301
|
+
VALUES ($1, $2, $3, $4)
|
|
302
|
+
`, [
|
|
303
|
+
`${params.userId}:${deletedAt.getTime()}:${randomUUID()}`,
|
|
304
|
+
params.userId,
|
|
305
|
+
deletedAt,
|
|
306
|
+
deletedCollections,
|
|
307
|
+
], tx);
|
|
308
|
+
return {
|
|
309
|
+
userId: params.userId,
|
|
310
|
+
deletedAt,
|
|
311
|
+
deletedCollections,
|
|
312
|
+
};
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
const entitlements = {
|
|
316
|
+
async findByUserId(userId, tx) {
|
|
317
|
+
const res = await exec(`SELECT * FROM _grasp_entitlements WHERE user_id = $1`, [userId], tx);
|
|
318
|
+
return res.rows[0] !== undefined ? mapPgEntitlement(res.rows[0]) : null;
|
|
319
|
+
},
|
|
320
|
+
async findByStripeCustomerId(stripeCustomerId, tx) {
|
|
321
|
+
const res = await exec(`SELECT * FROM _grasp_entitlements WHERE stripe_customer_id = $1 LIMIT 1`, [stripeCustomerId], tx);
|
|
322
|
+
return res.rows[0] !== undefined ? mapPgEntitlement(res.rows[0]) : null;
|
|
323
|
+
},
|
|
324
|
+
async upsertEntitlement(params, tx) {
|
|
325
|
+
const now = params.now ?? new Date();
|
|
326
|
+
const res = await exec(`
|
|
327
|
+
INSERT INTO _grasp_entitlements (
|
|
328
|
+
user_id, plan_id, status, source, stripe_customer_id, stripe_subscription_id,
|
|
329
|
+
cancel_at_period_end, current_period_end, entitled_through, updated_at
|
|
330
|
+
)
|
|
331
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
332
|
+
ON CONFLICT (user_id) DO UPDATE SET
|
|
333
|
+
plan_id = EXCLUDED.plan_id,
|
|
334
|
+
status = EXCLUDED.status,
|
|
335
|
+
source = EXCLUDED.source,
|
|
336
|
+
stripe_customer_id = EXCLUDED.stripe_customer_id,
|
|
337
|
+
stripe_subscription_id = EXCLUDED.stripe_subscription_id,
|
|
338
|
+
cancel_at_period_end = EXCLUDED.cancel_at_period_end,
|
|
339
|
+
current_period_end = EXCLUDED.current_period_end,
|
|
340
|
+
entitled_through = EXCLUDED.entitled_through,
|
|
341
|
+
updated_at = EXCLUDED.updated_at
|
|
342
|
+
RETURNING *
|
|
343
|
+
`, [
|
|
344
|
+
params.userId,
|
|
345
|
+
params.planId,
|
|
346
|
+
params.status,
|
|
347
|
+
params.source,
|
|
348
|
+
params.stripeCustomerId ?? null,
|
|
349
|
+
params.stripeSubscriptionId ?? null,
|
|
350
|
+
params.cancelAtPeriodEnd ?? null,
|
|
351
|
+
params.currentPeriodEnd ?? null,
|
|
352
|
+
params.entitledThrough ?? null,
|
|
353
|
+
now,
|
|
354
|
+
], tx);
|
|
355
|
+
const row = res.rows[0];
|
|
356
|
+
if (row === undefined) {
|
|
357
|
+
throw GraspError.internal('Failed to upsert entitlement record');
|
|
358
|
+
}
|
|
359
|
+
return mapPgEntitlement(row);
|
|
360
|
+
},
|
|
361
|
+
async ensureTrialOnce(params) {
|
|
362
|
+
const insertRes = await exec(`
|
|
363
|
+
INSERT INTO _grasp_entitlements (
|
|
364
|
+
user_id, plan_id, status, source, entitled_through, updated_at
|
|
365
|
+
)
|
|
366
|
+
VALUES ($1, $2, 'trial', 'trial', $3, $4)
|
|
367
|
+
ON CONFLICT (user_id) DO NOTHING
|
|
368
|
+
RETURNING *
|
|
369
|
+
`, [params.userId, params.planId, params.endsAt, params.startsAt]);
|
|
370
|
+
const inserted = insertRes.rows[0];
|
|
371
|
+
if (inserted !== undefined) {
|
|
372
|
+
return {
|
|
373
|
+
created: true,
|
|
374
|
+
entitlement: mapPgEntitlement(inserted),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
const existing = await exec(`SELECT * FROM _grasp_entitlements WHERE user_id = $1`, [params.userId]);
|
|
378
|
+
const row = existing.rows[0];
|
|
379
|
+
if (row === undefined) {
|
|
380
|
+
throw GraspError.internal('Entitlement record vanished during concurrent trial check');
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
created: false,
|
|
384
|
+
entitlement: mapPgEntitlement(row),
|
|
385
|
+
};
|
|
386
|
+
},
|
|
387
|
+
async processWebhookIdempotently(params) {
|
|
388
|
+
const processedAt = params.now ?? new Date();
|
|
389
|
+
const duplicateSentinel = Symbol('duplicateWebhook');
|
|
390
|
+
try {
|
|
391
|
+
return await withTransaction(async (tx) => {
|
|
392
|
+
const existing = await exec(`SELECT * FROM _grasp_webhook_events WHERE event_id = $1`, [params.eventId], tx);
|
|
393
|
+
const existingRow = existing.rows[0];
|
|
394
|
+
if (existingRow !== undefined) {
|
|
395
|
+
return {
|
|
396
|
+
duplicate: true,
|
|
397
|
+
status: existingRow.status,
|
|
398
|
+
...(existingRow.reason !== null ? { reason: existingRow.reason } : {}),
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
const outcome = await params.apply(tx);
|
|
402
|
+
const insertRes = await exec(`
|
|
403
|
+
INSERT INTO _grasp_webhook_events (
|
|
404
|
+
event_id, event_type, status, reason, payload_json, processed_at
|
|
405
|
+
)
|
|
406
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
407
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
408
|
+
RETURNING event_id
|
|
409
|
+
`, [
|
|
410
|
+
params.eventId,
|
|
411
|
+
params.eventType,
|
|
412
|
+
outcome.status,
|
|
413
|
+
outcome.reason ?? null,
|
|
414
|
+
params.payloadJson ?? null,
|
|
415
|
+
processedAt,
|
|
416
|
+
], tx);
|
|
417
|
+
if (insertRes.rowCount === 0) {
|
|
418
|
+
throw duplicateSentinel;
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
duplicate: false,
|
|
422
|
+
status: outcome.status,
|
|
423
|
+
...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),
|
|
424
|
+
};
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
catch (err) {
|
|
428
|
+
if (err === duplicateSentinel) {
|
|
429
|
+
const existing = await exec(`SELECT * FROM _grasp_webhook_events WHERE event_id = $1`, [params.eventId]);
|
|
430
|
+
const row = existing.rows[0];
|
|
431
|
+
if (row !== undefined) {
|
|
432
|
+
return {
|
|
433
|
+
duplicate: true,
|
|
434
|
+
status: row.status,
|
|
435
|
+
...(row.reason !== null ? { reason: row.reason } : {}),
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
throw err;
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
async listQuarantinedWebhooks(limit = 50) {
|
|
443
|
+
const safeLimit = Math.max(1, Math.min(200, Math.trunc(limit)));
|
|
444
|
+
const res = await exec(`
|
|
445
|
+
SELECT * FROM _grasp_webhook_events
|
|
446
|
+
WHERE status = 'quarantined'
|
|
447
|
+
ORDER BY processed_at DESC
|
|
448
|
+
LIMIT $1
|
|
449
|
+
`, [safeLimit]);
|
|
450
|
+
return res.rows.map(mapPgWebhook);
|
|
451
|
+
},
|
|
452
|
+
async getWebhookEvent(eventId) {
|
|
453
|
+
const res = await exec(`SELECT * FROM _grasp_webhook_events WHERE event_id = $1`, [eventId]);
|
|
454
|
+
return res.rows[0] !== undefined ? mapPgWebhook(res.rows[0]) : null;
|
|
455
|
+
},
|
|
456
|
+
async markWebhookReplayed(eventId, result, tx) {
|
|
457
|
+
const processedAt = result.now ?? new Date();
|
|
458
|
+
const res = await exec(`
|
|
459
|
+
UPDATE _grasp_webhook_events
|
|
460
|
+
SET status = $2, reason = $3, processed_at = $4
|
|
461
|
+
WHERE event_id = $1
|
|
462
|
+
`, [eventId, result.status, result.reason ?? null, processedAt], tx);
|
|
463
|
+
if ((res.rowCount ?? 0) === 0) {
|
|
464
|
+
throw GraspError.notFound(`Webhook event "${eventId}" not found`);
|
|
465
|
+
}
|
|
466
|
+
},
|
|
467
|
+
};
|
|
468
|
+
const runGrantCreditsTx = async (params, tx) => {
|
|
469
|
+
const now = params.now ?? new Date();
|
|
470
|
+
if (params.idempotencyKey !== undefined) {
|
|
471
|
+
const existingLedger = await exec(`SELECT balance_after FROM _grasp_credits_ledger WHERE idempotency_key = $1`, [params.idempotencyKey], tx);
|
|
472
|
+
const existingRow = existingLedger.rows[0];
|
|
473
|
+
if (existingRow !== undefined) {
|
|
474
|
+
const current = await exec(`SELECT balance FROM _grasp_credit_balances WHERE user_id = $1`, [params.userId], tx);
|
|
475
|
+
return {
|
|
476
|
+
balance: current.rows[0] !== undefined
|
|
477
|
+
? Number(current.rows[0].balance)
|
|
478
|
+
: Number(existingRow.balance_after),
|
|
479
|
+
duplicate: true,
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
await exec(`SAVEPOINT grasp_grant_credits`, [], tx);
|
|
484
|
+
const balanceRes = await exec(`
|
|
485
|
+
INSERT INTO _grasp_credit_balances (user_id, balance, updated_at)
|
|
486
|
+
VALUES ($1, $2, $3)
|
|
487
|
+
ON CONFLICT (user_id) DO UPDATE SET
|
|
488
|
+
balance = _grasp_credit_balances.balance + EXCLUDED.balance,
|
|
489
|
+
updated_at = EXCLUDED.updated_at
|
|
490
|
+
RETURNING balance
|
|
491
|
+
`, [params.userId, params.amount, now], tx);
|
|
492
|
+
const balanceRow = balanceRes.rows[0];
|
|
493
|
+
if (balanceRow === undefined) {
|
|
494
|
+
throw GraspError.internal('Failed to update credit balance');
|
|
495
|
+
}
|
|
496
|
+
const newBalance = Number(balanceRow.balance);
|
|
497
|
+
const ledgerRes = await exec(`
|
|
498
|
+
INSERT INTO _grasp_credits_ledger (
|
|
499
|
+
id, user_id, delta, balance_after, reason, idempotency_key, created_at
|
|
500
|
+
)
|
|
501
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
|
502
|
+
ON CONFLICT (idempotency_key) DO NOTHING
|
|
503
|
+
RETURNING id
|
|
504
|
+
`, [
|
|
505
|
+
randomUUID(),
|
|
506
|
+
params.userId,
|
|
507
|
+
params.amount,
|
|
508
|
+
newBalance,
|
|
509
|
+
params.reason,
|
|
510
|
+
params.idempotencyKey ?? null,
|
|
511
|
+
now,
|
|
512
|
+
], tx);
|
|
513
|
+
if ((ledgerRes.rowCount ?? 0) === 0 && params.idempotencyKey !== undefined) {
|
|
514
|
+
await exec(`ROLLBACK TO SAVEPOINT grasp_grant_credits`, [], tx);
|
|
515
|
+
await exec(`RELEASE SAVEPOINT grasp_grant_credits`, [], tx);
|
|
516
|
+
const current = await exec(`SELECT balance FROM _grasp_credit_balances WHERE user_id = $1`, [params.userId], tx);
|
|
517
|
+
return {
|
|
518
|
+
balance: current.rows[0] !== undefined ? Number(current.rows[0].balance) : 0,
|
|
519
|
+
duplicate: true,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
await exec(`RELEASE SAVEPOINT grasp_grant_credits`, [], tx);
|
|
523
|
+
return { balance: newBalance, duplicate: false };
|
|
524
|
+
};
|
|
525
|
+
const runSpendCreditsTx = async (params, tx) => {
|
|
526
|
+
const now = params.now ?? new Date();
|
|
527
|
+
const updateRes = await exec(`
|
|
528
|
+
UPDATE _grasp_credit_balances
|
|
529
|
+
SET balance = balance - $2, updated_at = $3
|
|
530
|
+
WHERE user_id = $1 AND balance >= $2
|
|
531
|
+
RETURNING balance
|
|
532
|
+
`, [params.userId, params.amount, now], tx);
|
|
533
|
+
const updatedRow = updateRes.rows[0];
|
|
534
|
+
if (updatedRow === undefined) {
|
|
535
|
+
const current = await exec(`SELECT balance FROM _grasp_credit_balances WHERE user_id = $1`, [params.userId], tx);
|
|
536
|
+
const availableCredits = current.rows[0] !== undefined ? Number(current.rows[0].balance) : 0;
|
|
537
|
+
throw GraspError.paymentRequired('Insufficient credits', {
|
|
538
|
+
metadata: {
|
|
539
|
+
requiredCredits: params.amount,
|
|
540
|
+
availableCredits,
|
|
541
|
+
},
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
const newBalance = Number(updatedRow.balance);
|
|
545
|
+
await exec(`
|
|
546
|
+
INSERT INTO _grasp_credits_ledger (id, user_id, delta, balance_after, reason, created_at)
|
|
547
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
548
|
+
`, [randomUUID(), params.userId, -params.amount, newBalance, params.reason, now], tx);
|
|
549
|
+
return { balance: newBalance };
|
|
550
|
+
};
|
|
551
|
+
const credits = {
|
|
552
|
+
async getBalance(userId, tx) {
|
|
553
|
+
const res = await exec(`SELECT balance FROM _grasp_credit_balances WHERE user_id = $1`, [userId], tx);
|
|
554
|
+
return res.rows[0] !== undefined ? Number(res.rows[0].balance) : 0;
|
|
555
|
+
},
|
|
556
|
+
async grantCredits(params, tx) {
|
|
557
|
+
assertPositiveInt(params.amount, 'amount');
|
|
558
|
+
if (params.reason.trim().length === 0) {
|
|
559
|
+
throw GraspError.badRequest('Credit grant reason must not be empty');
|
|
560
|
+
}
|
|
561
|
+
if (tx !== undefined) {
|
|
562
|
+
return runGrantCreditsTx(params, tx);
|
|
563
|
+
}
|
|
564
|
+
return withTransaction((innerTx) => runGrantCreditsTx(params, innerTx));
|
|
565
|
+
},
|
|
566
|
+
async spendCredits(params, tx) {
|
|
567
|
+
assertPositiveInt(params.amount, 'amount');
|
|
568
|
+
if (params.reason.trim().length === 0) {
|
|
569
|
+
throw GraspError.badRequest('Credit spend reason must not be empty');
|
|
570
|
+
}
|
|
571
|
+
if (tx !== undefined) {
|
|
572
|
+
return runSpendCreditsTx(params, tx);
|
|
573
|
+
}
|
|
574
|
+
return withTransaction((innerTx) => runSpendCreditsTx(params, innerTx));
|
|
575
|
+
},
|
|
576
|
+
async listLedger(userId, limit = 50) {
|
|
577
|
+
const safeLimit = Math.max(1, Math.min(200, Math.trunc(limit)));
|
|
578
|
+
const res = await exec(`
|
|
579
|
+
SELECT id, user_id, delta, balance_after, reason, idempotency_key, created_at
|
|
580
|
+
FROM _grasp_credits_ledger
|
|
581
|
+
WHERE user_id = $1
|
|
582
|
+
ORDER BY created_at DESC, id DESC
|
|
583
|
+
LIMIT $2
|
|
584
|
+
`, [userId, safeLimit]);
|
|
585
|
+
return res.rows.map((row) => ({
|
|
586
|
+
id: row.id,
|
|
587
|
+
userId: asUserId(row.user_id),
|
|
588
|
+
delta: Number(row.delta),
|
|
589
|
+
balanceAfter: Number(row.balance_after),
|
|
590
|
+
reason: row.reason,
|
|
591
|
+
...(row.idempotency_key !== null ? { idempotencyKey: row.idempotency_key } : {}),
|
|
592
|
+
createdAt: row.created_at,
|
|
593
|
+
}));
|
|
594
|
+
},
|
|
595
|
+
};
|
|
596
|
+
const quota = {
|
|
597
|
+
async consumeWithQuota(params) {
|
|
598
|
+
assertPositiveInt(params.amount, 'amount');
|
|
599
|
+
if (!Number.isSafeInteger(params.limit) || params.limit < 0) {
|
|
600
|
+
throw GraspError.badRequest('limit must be a non-negative integer');
|
|
601
|
+
}
|
|
602
|
+
if (params.resource.trim().length === 0) {
|
|
603
|
+
throw GraspError.badRequest('resource must not be empty');
|
|
604
|
+
}
|
|
605
|
+
return withTransaction(async (tx) => {
|
|
606
|
+
await exec(`
|
|
607
|
+
INSERT INTO _grasp_quota_scopes (user_id, resource, seq, updated_at)
|
|
608
|
+
VALUES ($1, $2, 1, $3)
|
|
609
|
+
ON CONFLICT (user_id, resource) DO UPDATE SET
|
|
610
|
+
seq = _grasp_quota_scopes.seq + 1,
|
|
611
|
+
updated_at = EXCLUDED.updated_at
|
|
612
|
+
`, [params.userId, params.resource, new Date()], tx);
|
|
613
|
+
const used = await params.countUsage(tx);
|
|
614
|
+
if (!Number.isSafeInteger(used) || used < 0) {
|
|
615
|
+
throw GraspError.internal('countUsage must return a non-negative integer');
|
|
616
|
+
}
|
|
617
|
+
if (used + params.amount > params.limit) {
|
|
618
|
+
throw GraspError.quotaExceeded(`Quota exceeded for "${params.resource}"`, {
|
|
619
|
+
metadata: {
|
|
620
|
+
resource: params.resource,
|
|
621
|
+
limit: params.limit,
|
|
622
|
+
used,
|
|
623
|
+
requested: params.amount,
|
|
624
|
+
},
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
return params.write(tx);
|
|
628
|
+
});
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
const outbox = {
|
|
632
|
+
async enqueue(params, tx) {
|
|
633
|
+
const now = params.now ?? new Date();
|
|
634
|
+
const runAfter = params.runAfter ?? now;
|
|
635
|
+
const maxAttempts = params.maxAttempts ?? 5;
|
|
636
|
+
assertPositiveInt(maxAttempts, 'maxAttempts');
|
|
637
|
+
if (params.jobName.trim().length === 0) {
|
|
638
|
+
throw GraspError.badRequest('jobName must not be empty');
|
|
639
|
+
}
|
|
640
|
+
let payloadJson;
|
|
641
|
+
try {
|
|
642
|
+
payloadJson = params.payload === undefined ? 'null' : JSON.stringify(params.payload);
|
|
643
|
+
}
|
|
644
|
+
catch (err) {
|
|
645
|
+
throw GraspError.badRequest('Outbox job payload must be JSON serializable', { cause: err });
|
|
646
|
+
}
|
|
647
|
+
const id = randomUUID();
|
|
648
|
+
const res = await exec(`
|
|
649
|
+
INSERT INTO _grasp_outbox_jobs (
|
|
650
|
+
id, job_name, payload_json, status, attempts, max_attempts, run_after, created_at, updated_at
|
|
651
|
+
)
|
|
652
|
+
VALUES ($1, $2, $3, 'pending', 0, $4, $5, $6, $6)
|
|
653
|
+
RETURNING *
|
|
654
|
+
`, [id, params.jobName, payloadJson, maxAttempts, runAfter, now], tx);
|
|
655
|
+
const row = res.rows[0];
|
|
656
|
+
if (row === undefined) {
|
|
657
|
+
throw GraspError.internal('Failed to enqueue outbox job');
|
|
658
|
+
}
|
|
659
|
+
return mapPgOutbox(row);
|
|
660
|
+
},
|
|
661
|
+
async claimBatch(params) {
|
|
662
|
+
assertPositiveInt(params.limit, 'limit');
|
|
663
|
+
assertPositiveInt(params.leaseMs, 'leaseMs');
|
|
664
|
+
const now = params.now ?? new Date();
|
|
665
|
+
const leaseUntil = new Date(now.getTime() + params.leaseMs);
|
|
666
|
+
const res = await exec(`
|
|
667
|
+
WITH candidate AS (
|
|
668
|
+
SELECT id
|
|
669
|
+
FROM _grasp_outbox_jobs
|
|
670
|
+
WHERE (status = 'pending' AND run_after <= $1)
|
|
671
|
+
OR (status = 'processing' AND lease_until <= $1)
|
|
672
|
+
ORDER BY run_after ASC, created_at ASC
|
|
673
|
+
LIMIT $2
|
|
674
|
+
FOR UPDATE SKIP LOCKED
|
|
675
|
+
)
|
|
676
|
+
UPDATE _grasp_outbox_jobs AS j
|
|
677
|
+
SET status = 'processing',
|
|
678
|
+
attempts = j.attempts + 1,
|
|
679
|
+
lease_owner = $3,
|
|
680
|
+
lease_until = $4,
|
|
681
|
+
updated_at = $1
|
|
682
|
+
FROM candidate
|
|
683
|
+
WHERE j.id = candidate.id
|
|
684
|
+
RETURNING j.*
|
|
685
|
+
`, [now, params.limit, params.workerId, leaseUntil]);
|
|
686
|
+
return res.rows
|
|
687
|
+
.map(mapPgOutbox)
|
|
688
|
+
.sort((a, b) => a.runAfter.getTime() - b.runAfter.getTime() ||
|
|
689
|
+
a.createdAt.getTime() - b.createdAt.getTime());
|
|
690
|
+
},
|
|
691
|
+
async complete(params) {
|
|
692
|
+
const now = params.now ?? new Date();
|
|
693
|
+
const res = await exec(`
|
|
694
|
+
UPDATE _grasp_outbox_jobs
|
|
695
|
+
SET status = 'completed', lease_owner = NULL, lease_until = NULL, updated_at = $3
|
|
696
|
+
WHERE id = $1 AND status = 'processing' AND lease_owner = $2
|
|
697
|
+
`, [params.id, params.workerId, now]);
|
|
698
|
+
return (res.rowCount ?? 0) === 1;
|
|
699
|
+
},
|
|
700
|
+
async failOrRetry(params) {
|
|
701
|
+
const now = params.now ?? new Date();
|
|
702
|
+
const retryDelayMs = Math.max(0, params.retryDelayMs ?? 5000);
|
|
703
|
+
const nextRunAfter = new Date(now.getTime() + retryDelayMs);
|
|
704
|
+
const res = await exec(`
|
|
705
|
+
UPDATE _grasp_outbox_jobs
|
|
706
|
+
SET status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'pending' END,
|
|
707
|
+
last_error = $3,
|
|
708
|
+
run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE $4 END,
|
|
709
|
+
lease_owner = NULL,
|
|
710
|
+
lease_until = NULL,
|
|
711
|
+
updated_at = $5
|
|
712
|
+
WHERE id = $1 AND status = 'processing' AND lease_owner = $2
|
|
713
|
+
RETURNING status
|
|
714
|
+
`, [params.id, params.workerId, params.error, nextRunAfter, now]);
|
|
715
|
+
return res.rows[0]?.status ?? null;
|
|
716
|
+
},
|
|
717
|
+
async getStats() {
|
|
718
|
+
const res = await exec(`SELECT status, COUNT(*)::text AS count FROM _grasp_outbox_jobs GROUP BY status`, []);
|
|
719
|
+
const stats = {
|
|
720
|
+
pending: 0,
|
|
721
|
+
processing: 0,
|
|
722
|
+
completed: 0,
|
|
723
|
+
failed: 0,
|
|
724
|
+
};
|
|
725
|
+
for (const row of res.rows) {
|
|
726
|
+
if (row.status in stats) {
|
|
727
|
+
stats[row.status] = Number(row.count);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
return stats;
|
|
731
|
+
},
|
|
732
|
+
async retryFailed(limit = 100, now = new Date()) {
|
|
733
|
+
assertPositiveInt(limit, 'limit');
|
|
734
|
+
const res = await exec(`
|
|
735
|
+
WITH targets AS (
|
|
736
|
+
SELECT id FROM _grasp_outbox_jobs
|
|
737
|
+
WHERE status = 'failed'
|
|
738
|
+
ORDER BY updated_at ASC
|
|
739
|
+
LIMIT $1
|
|
740
|
+
FOR UPDATE SKIP LOCKED
|
|
741
|
+
)
|
|
742
|
+
UPDATE _grasp_outbox_jobs AS j
|
|
743
|
+
SET status = 'pending',
|
|
744
|
+
attempts = 0,
|
|
745
|
+
run_after = $2,
|
|
746
|
+
lease_owner = NULL,
|
|
747
|
+
lease_until = NULL,
|
|
748
|
+
last_error = NULL,
|
|
749
|
+
updated_at = $2
|
|
750
|
+
FROM targets
|
|
751
|
+
WHERE j.id = targets.id
|
|
752
|
+
`, [limit, now]);
|
|
753
|
+
return res.rowCount ?? 0;
|
|
754
|
+
},
|
|
755
|
+
};
|
|
756
|
+
return {
|
|
757
|
+
kind: 'postgres',
|
|
758
|
+
pool,
|
|
759
|
+
readiness: createPgReadinessProbe(pool),
|
|
760
|
+
withTransaction,
|
|
761
|
+
query: (fragment, tx) => queryPg(pool, fragment, tx),
|
|
762
|
+
users,
|
|
763
|
+
entitlements,
|
|
764
|
+
credits,
|
|
765
|
+
quota,
|
|
766
|
+
outbox,
|
|
767
|
+
async applySchema() {
|
|
768
|
+
return withTransaction(async (tx) => {
|
|
769
|
+
await exec(`SELECT pg_advisory_xact_lock($1)`, [SCHEMA_ADVISORY_LOCK_KEY], tx);
|
|
770
|
+
await exec(`
|
|
771
|
+
CREATE TABLE IF NOT EXISTS _grasp_schema_migrations (
|
|
772
|
+
id TEXT PRIMARY KEY,
|
|
773
|
+
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
774
|
+
)
|
|
775
|
+
`, [], tx);
|
|
776
|
+
const appliedRows = await exec(`SELECT id FROM _grasp_schema_migrations`, [], tx);
|
|
777
|
+
const alreadyApplied = new Set(appliedRows.rows.map((row) => row.id));
|
|
778
|
+
const newlyApplied = [];
|
|
779
|
+
const pending = [...SHELL_MIGRATIONS];
|
|
780
|
+
for (const table of registeredTables) {
|
|
781
|
+
for (const migration of table.migrations) {
|
|
782
|
+
pending.push({
|
|
783
|
+
key: `${table.name}:${migration.id}`,
|
|
784
|
+
sql: migration.sql,
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
for (const item of pending) {
|
|
789
|
+
if (alreadyApplied.has(item.key)) {
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
await exec(item.sql, [], tx);
|
|
793
|
+
await exec(`INSERT INTO _grasp_schema_migrations (id) VALUES ($1)`, [item.key], tx);
|
|
794
|
+
newlyApplied.push(item.key);
|
|
795
|
+
}
|
|
796
|
+
if (appUser !== undefined) {
|
|
797
|
+
const roleCheck = await exec(`SELECT 1 AS exists FROM pg_roles WHERE rolname = $1`, [appUser], tx);
|
|
798
|
+
if (roleCheck.rows.length > 0) {
|
|
799
|
+
const quotedRole = `"${appUser.replace(/"/g, '""')}"`;
|
|
800
|
+
await exec(`GRANT USAGE ON SCHEMA public TO ${quotedRole}`, [], tx);
|
|
801
|
+
await exec(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO ${quotedRole}`, [], tx);
|
|
802
|
+
await exec(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ${quotedRole}`, [], tx);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return { applied: newlyApplied };
|
|
806
|
+
});
|
|
807
|
+
},
|
|
808
|
+
async close() {
|
|
809
|
+
await pool.end();
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
//# sourceMappingURL=store.js.map
|