@rebasepro/server-postgres 0.9.1-canary.682a9cf → 0.9.1-canary.73476f2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/PostgresBackendDriver.d.ts +2 -25
- package/dist/PostgresBootstrapper.d.ts +0 -10
- package/dist/auth/services.d.ts +0 -16
- package/dist/connection.d.ts +0 -21
- package/dist/data-transformer.d.ts +2 -9
- package/dist/index.es.js +561 -1454
- package/dist/index.es.js.map +1 -1
- package/dist/schema/auth-default-policies.d.ts +10 -0
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/services/FetchService.d.ts +24 -4
- package/dist/services/PersistService.d.ts +1 -27
- package/dist/services/RelationService.d.ts +1 -34
- package/dist/services/collection-helpers.d.ts +14 -79
- package/dist/services/dataService.d.ts +1 -3
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +0 -7
- package/package.json +9 -11
- package/src/PostgresBackendDriver.ts +13 -127
- package/src/PostgresBootstrapper.ts +25 -62
- package/src/auth/ensure-tables.ts +11 -73
- package/src/auth/services.ts +19 -49
- package/src/connection.ts +1 -61
- package/src/data-transformer.ts +9 -11
- package/src/databasePoolManager.ts +0 -2
- package/src/schema/auth-default-policies.ts +132 -0
- package/src/schema/doctor.ts +20 -45
- package/src/schema/generate-drizzle-schema-logic.ts +29 -24
- package/src/schema/generate-postgres-ddl-logic.ts +28 -76
- package/src/schema/introspect-db.ts +2 -19
- package/src/services/BranchService.ts +10 -42
- package/src/services/FetchService.ts +270 -65
- package/src/services/PersistService.ts +14 -130
- package/src/services/RelationService.ts +94 -153
- package/src/services/collection-helpers.ts +47 -164
- package/src/services/dataService.ts +2 -3
- package/src/services/index.ts +0 -1
- package/src/services/realtimeService.ts +19 -40
- package/src/utils/drizzle-conditions.ts +0 -13
- package/src/websocket.ts +1 -4
- package/dist/collections/buildRegistry.d.ts +0 -27
- package/dist/services/row-pipeline.d.ts +0 -63
- package/src/collections/buildRegistry.ts +0 -59
- package/src/services/row-pipeline.ts +0 -239
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* Implements the `BackendBootstrapper` interface for PostgreSQL.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
import { Relations, sql } from "drizzle-orm";
|
|
7
|
+
import { getTableName, isTable, Relations, sql } from "drizzle-orm";
|
|
8
8
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
9
9
|
import { PgEnum, PgTable } from "drizzle-orm/pg-core";
|
|
10
10
|
import type { RebasePgTable } from "./types";
|
|
@@ -21,7 +21,6 @@ import {
|
|
|
21
21
|
} from "@rebasepro/types";
|
|
22
22
|
import { PostgresBackendDriver } from "./PostgresBackendDriver";
|
|
23
23
|
import { RealtimeService } from "./services/realtimeService";
|
|
24
|
-
import { buildCollectionRegistry } from "./collections/buildRegistry";
|
|
25
24
|
import { DatabasePoolManager } from "./databasePoolManager";
|
|
26
25
|
import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
|
|
27
26
|
import { createEmailService, type EmailConfig, type EmailService, logger } from "@rebasepro/server";
|
|
@@ -65,15 +64,6 @@ export interface PostgresDriverInternals {
|
|
|
65
64
|
realtimeService: RealtimeService;
|
|
66
65
|
driver: PostgresBackendDriver;
|
|
67
66
|
poolManager?: DatabasePoolManager;
|
|
68
|
-
/**
|
|
69
|
-
* Attach CDC triggers to tables that did not exist when the driver
|
|
70
|
-
* bootstrapped. Only set when database-level capture is actually active.
|
|
71
|
-
*
|
|
72
|
-
* Auth owns its own tables and creates them later in boot, so at driver
|
|
73
|
-
* bootstrap they are legitimately missing and get skipped; without this
|
|
74
|
-
* they would stay uninstrumented until the next restart.
|
|
75
|
-
*/
|
|
76
|
-
provisionCdcForTables?: (tables: CdcTableRef[]) => Promise<void>;
|
|
77
67
|
}
|
|
78
68
|
|
|
79
69
|
// Re-export from shared CLI error utilities
|
|
@@ -171,17 +161,30 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
171
161
|
}
|
|
172
162
|
|
|
173
163
|
const activeCollections = introspectedCollections ?? collections;
|
|
164
|
+
|
|
165
|
+
// Create a fresh registry for this driver
|
|
166
|
+
const registry = new PostgresCollectionRegistry();
|
|
167
|
+
if (activeCollections) {
|
|
168
|
+
registry.registerMultiple(activeCollections);
|
|
169
|
+
logger.info(`📋 [PostgresRegistry] Registered ${registry.getCollections().length} collections: [${registry.getCollections().map(c => c.slug).join(", ")}]`);
|
|
170
|
+
}
|
|
171
|
+
|
|
174
172
|
const schemaTables = introspectedTables ?? pgConfig.schema?.tables;
|
|
175
|
-
const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
|
|
176
173
|
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
174
|
+
// Register tables
|
|
175
|
+
if (schemaTables) {
|
|
176
|
+
Object.values(schemaTables).forEach((table) => {
|
|
177
|
+
if (isTable(table)) {
|
|
178
|
+
const tableName = getTableName(table);
|
|
179
|
+
registry.registerTable(table as PgTable, tableName);
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (pgConfig.schema?.enums) registry.registerEnums(pgConfig.schema.enums as Record<string, PgEnum<[string, ...string[]]>>);
|
|
185
|
+
|
|
186
|
+
const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
|
|
187
|
+
if (schemaRelations) registry.registerRelations(schemaRelations);
|
|
185
188
|
|
|
186
189
|
// Patch Drizzle's PgArray columns to handle NULL values safely.
|
|
187
190
|
// Drizzle's mapFromDriverValue crashes with "value.map is not a function"
|
|
@@ -343,7 +346,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
343
346
|
const wantsCdc = cdcMode !== "off";
|
|
344
347
|
const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
|
|
345
348
|
let cdcEnabled = false;
|
|
346
|
-
let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
|
|
347
349
|
|
|
348
350
|
if (wantsCdc && !directUrl) {
|
|
349
351
|
const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
|
|
@@ -377,11 +379,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
377
379
|
await provisionTriggerCdc(cdcRunSql, cdcTables);
|
|
378
380
|
await realtimeService.enableCdc(directUrl);
|
|
379
381
|
cdcEnabled = true;
|
|
380
|
-
// Boot steps that create their own tables (auth) run after
|
|
381
|
-
// this one and use it to instrument what they just created.
|
|
382
|
-
provisionCdcForTables = async (tables) => {
|
|
383
|
-
await provisionTriggerCdc(cdcRunSql, tables);
|
|
384
|
-
};
|
|
385
382
|
logger.info(
|
|
386
383
|
`📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
|
|
387
384
|
`All writes now emit realtime events regardless of origin.`
|
|
@@ -432,14 +429,6 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
432
429
|
);
|
|
433
430
|
const missing: Array<{ slug: string; table: string }> = [];
|
|
434
431
|
for (const col of registeredCollections) {
|
|
435
|
-
// Auth owns its table and creates it later in this same
|
|
436
|
-
// boot (initializeAuth → ensureAuthTablesExist), so it is
|
|
437
|
-
// legitimately absent right now. Reporting it as drift
|
|
438
|
-
// tells the user to `db:push` a table that is about to
|
|
439
|
-
// exist — and on an introspected database, one that the
|
|
440
|
-
// database was never supposed to hold.
|
|
441
|
-
if ((col as { auth?: { enabled?: boolean } }).auth?.enabled) continue;
|
|
442
|
-
|
|
443
432
|
const schemaName = "schema" in col && col.schema ? col.schema : "public";
|
|
444
433
|
const tableName = registry.hasTableForCollection(
|
|
445
434
|
col.table ?? col.slug
|
|
@@ -454,10 +443,8 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
|
|
|
454
443
|
const checkName = resolvedTable ?? tableName;
|
|
455
444
|
const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
|
|
456
445
|
if (!dbTables.has(fullCheckName)) {
|
|
457
|
-
// Report what was actually looked up: an unqualified
|
|
458
|
-
// "users" sends people hunting for public.users.
|
|
459
446
|
missing.push({ slug: col.slug,
|
|
460
|
-
table:
|
|
447
|
+
table: checkName });
|
|
461
448
|
}
|
|
462
449
|
}
|
|
463
450
|
if (missing.length > 0) {
|
|
@@ -491,8 +478,7 @@ table: fullCheckName });
|
|
|
491
478
|
registry,
|
|
492
479
|
realtimeService,
|
|
493
480
|
driver,
|
|
494
|
-
poolManager
|
|
495
|
-
provisionCdcForTables
|
|
481
|
+
poolManager
|
|
496
482
|
};
|
|
497
483
|
|
|
498
484
|
return {
|
|
@@ -521,29 +507,6 @@ table: fullCheckName });
|
|
|
521
507
|
// ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
|
|
522
508
|
await ensureAuthTablesExist(db, authCollection);
|
|
523
509
|
|
|
524
|
-
// The driver bootstrapped before these tables existed, so CDC skipped
|
|
525
|
-
// them. Instrument them now, or writes to the user table emit no
|
|
526
|
-
// realtime events until the next restart.
|
|
527
|
-
if (authCollection && internals.provisionCdcForTables) {
|
|
528
|
-
const authSchema = "schema" in authCollection && typeof authCollection.schema === "string"
|
|
529
|
-
? authCollection.schema
|
|
530
|
-
: "rebase";
|
|
531
|
-
const authTable = "table" in authCollection && typeof authCollection.table === "string"
|
|
532
|
-
? authCollection.table
|
|
533
|
-
: authCollection.slug;
|
|
534
|
-
if (authTable) {
|
|
535
|
-
try {
|
|
536
|
-
await internals.provisionCdcForTables([{ schema: authSchema, table: authTable }]);
|
|
537
|
-
} catch (err) {
|
|
538
|
-
logger.warn(
|
|
539
|
-
`⚠️ [CDC] Could not attach change-capture to the auth table "${authSchema}.${authTable}" — ` +
|
|
540
|
-
"writes to it won't emit database-level events.",
|
|
541
|
-
{ detail: err instanceof Error ? err.message : String(err) }
|
|
542
|
-
);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
510
|
let emailService: EmailService | undefined;
|
|
548
511
|
if (authConfig.email) {
|
|
549
512
|
emailService = createEmailService(authConfig.email as EmailConfig);
|
|
@@ -251,32 +251,17 @@ export async function ensureAuthTablesExist(db: NodePgDatabase, collection?: Col
|
|
|
251
251
|
// Seed default roles if none exist
|
|
252
252
|
// (no-op: roles are now stored inline on the users table)
|
|
253
253
|
|
|
254
|
-
// ── Migration:
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
"password_hash VARCHAR(255)",
|
|
266
|
-
"email_verified BOOLEAN DEFAULT FALSE NOT NULL",
|
|
267
|
-
"email_verification_token VARCHAR(255)",
|
|
268
|
-
"email_verification_sent_at TIMESTAMP WITH TIME ZONE",
|
|
269
|
-
"is_anonymous BOOLEAN DEFAULT FALSE NOT NULL",
|
|
270
|
-
"metadata JSONB DEFAULT '{}' NOT NULL",
|
|
271
|
-
"created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL",
|
|
272
|
-
"updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL"
|
|
273
|
-
];
|
|
274
|
-
for (const columnDef of userColumnBackfills) {
|
|
275
|
-
await db.execute(sql`
|
|
276
|
-
ALTER TABLE ${sql.raw(usersTableName)}
|
|
277
|
-
ADD COLUMN IF NOT EXISTS ${sql.raw(columnDef)}
|
|
278
|
-
`);
|
|
279
|
-
}
|
|
254
|
+
// ── Migration: Add is_anonymous column (safe for existing tables) ────
|
|
255
|
+
await db.execute(sql`
|
|
256
|
+
ALTER TABLE ${sql.raw(usersTableName)}
|
|
257
|
+
ADD COLUMN IF NOT EXISTS is_anonymous BOOLEAN DEFAULT FALSE
|
|
258
|
+
`);
|
|
259
|
+
|
|
260
|
+
// ── Migration: Add inline roles column (safe for existing tables) ────
|
|
261
|
+
await db.execute(sql`
|
|
262
|
+
ALTER TABLE ${sql.raw(usersTableName)}
|
|
263
|
+
ADD COLUMN IF NOT EXISTS roles TEXT[] DEFAULT '{}' NOT NULL
|
|
264
|
+
`);
|
|
280
265
|
|
|
281
266
|
// ── Migration: Copy roles from legacy junction table to inline column ──
|
|
282
267
|
// If the old rebase.user_roles and rebase.roles tables exist, migrate
|
|
@@ -373,53 +358,6 @@ export async function ensureAuthTablesExist(db: NodePgDatabase, collection?: Col
|
|
|
373
358
|
ON ${sql.raw(recoveryCodesTableName)}(user_id)
|
|
374
359
|
`);
|
|
375
360
|
|
|
376
|
-
// ── Migration: clear stale FORCE ROW LEVEL SECURITY (older RLS model) ──
|
|
377
|
-
// The current model never emits FORCE: privileged auth writes run as
|
|
378
|
-
// the table owner and rely on the owner bypassing plain ENABLE RLS
|
|
379
|
-
// (see generate-postgres-ddl-logic). A table still carrying FORCE from
|
|
380
|
-
// an older framework era binds the owner too, so the first user
|
|
381
|
-
// registration after an upgrade fails with SQLSTATE 42501. Reconcile
|
|
382
|
-
// on boot; only tables actually flagged get the ALTER (and its lock).
|
|
383
|
-
try {
|
|
384
|
-
const authTablePairs: [string, string][] = [
|
|
385
|
-
[usersSchema, resolvedTable],
|
|
386
|
-
[authSchema, "user_identities"],
|
|
387
|
-
[authSchema, "refresh_tokens"],
|
|
388
|
-
[authSchema, "password_reset_tokens"],
|
|
389
|
-
[authSchema, "app_config"],
|
|
390
|
-
[authSchema, "mfa_factors"],
|
|
391
|
-
[authSchema, "mfa_challenges"],
|
|
392
|
-
[authSchema, "recovery_codes"]
|
|
393
|
-
];
|
|
394
|
-
for (const [schemaName, tableName] of authTablePairs) {
|
|
395
|
-
const forced = await db.execute(sql`
|
|
396
|
-
SELECT 1
|
|
397
|
-
FROM pg_class c
|
|
398
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
399
|
-
WHERE n.nspname = ${schemaName}
|
|
400
|
-
AND c.relname = ${tableName}
|
|
401
|
-
AND c.relforcerowsecurity
|
|
402
|
-
`);
|
|
403
|
-
if (forced.rows.length > 0) {
|
|
404
|
-
await db.execute(sql`
|
|
405
|
-
ALTER TABLE ${sql.raw(`"${schemaName}"."${tableName}"`)}
|
|
406
|
-
NO FORCE ROW LEVEL SECURITY
|
|
407
|
-
`);
|
|
408
|
-
logger.warn(
|
|
409
|
-
`🔧 Cleared stale FORCE ROW LEVEL SECURITY on "${schemaName}"."${tableName}" ` +
|
|
410
|
-
"(legacy RLS model — it binds the owner connection and breaks privileged auth writes)"
|
|
411
|
-
);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
} catch (rlsReconcileError: unknown) {
|
|
415
|
-
// Non-fatal: the connection may lack ownership on a pre-provisioned
|
|
416
|
-
// table; registration will still fail loudly (42501) if FORCE remains.
|
|
417
|
-
logger.warn(
|
|
418
|
-
`⚠️ Could not reconcile FORCE ROW LEVEL SECURITY on auth tables: ` +
|
|
419
|
-
`${rlsReconcileError instanceof Error ? rlsReconcileError.message : String(rlsReconcileError)}`
|
|
420
|
-
);
|
|
421
|
-
}
|
|
422
|
-
|
|
423
361
|
logger.info("✅ Auth tables ready");
|
|
424
362
|
} catch (error) {
|
|
425
363
|
logger.error("❌ Failed to create auth tables", { error });
|
package/src/auth/services.ts
CHANGED
|
@@ -82,32 +82,6 @@ export class UserService implements UserRepository {
|
|
|
82
82
|
return `"${schema}"."${name}"`;
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
/**
|
|
86
|
-
* Run a privileged auth write with an explicitly cleared RLS context.
|
|
87
|
-
*
|
|
88
|
-
* The auth services run on the base/owner connection, which by design
|
|
89
|
-
* carries a NULL `app.user_id` so the `auth.uid() IS NULL` server-escape
|
|
90
|
-
* in the default policies applies. That NULL is normally guaranteed by
|
|
91
|
-
* `set_config(..., is_local = true)` resetting at transaction end — but a
|
|
92
|
-
* GUC that survives on a pooled connection (or a connection role that
|
|
93
|
-
* doesn't bypass RLS: FORCE ROW LEVEL SECURITY, or a non-owner role)
|
|
94
|
-
* turns the trusted write into an RLS-scoped one and denies it with
|
|
95
|
-
* SQLSTATE 42501. Clearing the GUCs here, transaction-locally at the
|
|
96
|
-
* single chokepoint, makes the server context deterministic instead of
|
|
97
|
-
* trusting whatever state the pool hands us. `auth.uid()` reads '' as
|
|
98
|
-
* NULL via NULLIF, so '' is the server context.
|
|
99
|
-
*/
|
|
100
|
-
private async withServerContext<T>(fn: (db: NodePgDatabase) => Promise<T>): Promise<T> {
|
|
101
|
-
return await this.db.transaction(async (tx) => {
|
|
102
|
-
await tx.execute(sql`
|
|
103
|
-
SELECT set_config('app.user_id', '', true),
|
|
104
|
-
set_config('app.user_roles', '', true),
|
|
105
|
-
set_config('app.jwt', '', true)
|
|
106
|
-
`);
|
|
107
|
-
return await fn(tx as unknown as NodePgDatabase);
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
|
|
111
85
|
private mapRowToUser(row: Record<string, unknown>): UserData {
|
|
112
86
|
if (!row) return row as UserData;
|
|
113
87
|
|
|
@@ -226,9 +200,7 @@ export class UserService implements UserRepository {
|
|
|
226
200
|
|
|
227
201
|
async createUser(data: CreateUserData): Promise<UserData> {
|
|
228
202
|
const payload = this.mapPayload(data);
|
|
229
|
-
const [row] = await this.
|
|
230
|
-
(await db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[]
|
|
231
|
-
);
|
|
203
|
+
const [row] = (await this.db.insert(this.usersTable).values(payload).returning()) as Record<string, unknown>[];
|
|
232
204
|
return this.mapRowToUser(row);
|
|
233
205
|
}
|
|
234
206
|
|
|
@@ -283,12 +255,12 @@ export class UserService implements UserRepository {
|
|
|
283
255
|
}
|
|
284
256
|
|
|
285
257
|
async linkUserIdentity(userId: string, provider: string, providerId: string, profileData?: Record<string, unknown>): Promise<void> {
|
|
286
|
-
await this.
|
|
258
|
+
await this.db.insert(this.userIdentitiesTable).values({
|
|
287
259
|
userId,
|
|
288
260
|
provider,
|
|
289
261
|
providerId,
|
|
290
262
|
profileData: profileData || null
|
|
291
|
-
}).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] })
|
|
263
|
+
}).onConflictDoNothing({ target: [this.userIdentitiesTable.provider, this.userIdentitiesTable.providerId] });
|
|
292
264
|
}
|
|
293
265
|
|
|
294
266
|
async updateUser(id: string, data: Partial<Omit<CreateUserData, "id">>): Promise<UserData | null> {
|
|
@@ -298,20 +270,18 @@ export class UserService implements UserRepository {
|
|
|
298
270
|
const updatedAtKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
299
271
|
payload[updatedAtKey] = new Date();
|
|
300
272
|
|
|
301
|
-
const [row] = await this.
|
|
302
|
-
(
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
.returning()) as Record<string, unknown>[]
|
|
307
|
-
);
|
|
273
|
+
const [row] = (await this.db
|
|
274
|
+
.update(this.usersTable)
|
|
275
|
+
.set(payload)
|
|
276
|
+
.where(eq(idCol, id))
|
|
277
|
+
.returning()) as Record<string, unknown>[];
|
|
308
278
|
return row ? this.mapRowToUser(row) : null;
|
|
309
279
|
}
|
|
310
280
|
|
|
311
281
|
async deleteUser(id: string): Promise<void> {
|
|
312
282
|
const idCol = getColumn(this.usersTable, "id");
|
|
313
283
|
if (!idCol) return;
|
|
314
|
-
await this.
|
|
284
|
+
await this.db.delete(this.usersTable).where(eq(idCol, id));
|
|
315
285
|
}
|
|
316
286
|
|
|
317
287
|
async listUsers(): Promise<UserData[]> {
|
|
@@ -387,13 +357,13 @@ export class UserService implements UserRepository {
|
|
|
387
357
|
const passwordHashColKey = getColumnKey(this.usersTable, "passwordHash", "password_hash") || "passwordHash";
|
|
388
358
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
389
359
|
|
|
390
|
-
await this.
|
|
360
|
+
await this.db
|
|
391
361
|
.update(this.usersTable)
|
|
392
362
|
.set({
|
|
393
363
|
[passwordHashColKey]: passwordHash,
|
|
394
364
|
[updatedAtColKey]: new Date()
|
|
395
365
|
})
|
|
396
|
-
.where(eq(idCol, id))
|
|
366
|
+
.where(eq(idCol, id));
|
|
397
367
|
}
|
|
398
368
|
|
|
399
369
|
/**
|
|
@@ -406,14 +376,14 @@ export class UserService implements UserRepository {
|
|
|
406
376
|
const emailVerificationTokenColKey = getColumnKey(this.usersTable, "emailVerificationToken", "email_verification_token") || "emailVerificationToken";
|
|
407
377
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
408
378
|
|
|
409
|
-
await this.
|
|
379
|
+
await this.db
|
|
410
380
|
.update(this.usersTable)
|
|
411
381
|
.set({
|
|
412
382
|
[emailVerifiedColKey]: verified,
|
|
413
383
|
[emailVerificationTokenColKey]: null,
|
|
414
384
|
[updatedAtColKey]: new Date()
|
|
415
385
|
})
|
|
416
|
-
.where(eq(idCol, id))
|
|
386
|
+
.where(eq(idCol, id));
|
|
417
387
|
}
|
|
418
388
|
|
|
419
389
|
/**
|
|
@@ -426,14 +396,14 @@ export class UserService implements UserRepository {
|
|
|
426
396
|
const emailVerificationSentAtColKey = getColumnKey(this.usersTable, "emailVerificationSentAt", "email_verification_sent_at") || "emailVerificationSentAt";
|
|
427
397
|
const updatedAtColKey = getColumnKey(this.usersTable, "updatedAt", "updated_at") || "updatedAt";
|
|
428
398
|
|
|
429
|
-
await this.
|
|
399
|
+
await this.db
|
|
430
400
|
.update(this.usersTable)
|
|
431
401
|
.set({
|
|
432
402
|
[emailVerificationTokenColKey]: token,
|
|
433
403
|
[emailVerificationSentAtColKey]: token ? new Date() : null,
|
|
434
404
|
[updatedAtColKey]: new Date()
|
|
435
405
|
})
|
|
436
|
-
.where(eq(idCol, id))
|
|
406
|
+
.where(eq(idCol, id));
|
|
437
407
|
}
|
|
438
408
|
|
|
439
409
|
/**
|
|
@@ -493,11 +463,11 @@ export class UserService implements UserRepository {
|
|
|
493
463
|
async setUserRoles(userId: string, roleIds: string[]): Promise<void> {
|
|
494
464
|
const usersTableName = this.getQualifiedUsersTableName();
|
|
495
465
|
const rolesArray = `{${roleIds.join(",")}}`;
|
|
496
|
-
await this.
|
|
466
|
+
await this.db.execute(sql`
|
|
497
467
|
UPDATE ${sql.raw(usersTableName)}
|
|
498
468
|
SET roles = ${rolesArray}::text[], updated_at = NOW()
|
|
499
469
|
WHERE id = ${userId}
|
|
500
|
-
`)
|
|
470
|
+
`);
|
|
501
471
|
}
|
|
502
472
|
|
|
503
473
|
/**
|
|
@@ -505,11 +475,11 @@ export class UserService implements UserRepository {
|
|
|
505
475
|
*/
|
|
506
476
|
async assignDefaultRole(userId: string, roleId: string): Promise<void> {
|
|
507
477
|
const usersTableName = this.getQualifiedUsersTableName();
|
|
508
|
-
await this.
|
|
478
|
+
await this.db.execute(sql`
|
|
509
479
|
UPDATE ${sql.raw(usersTableName)}
|
|
510
480
|
SET roles = array_append(roles, ${roleId}), updated_at = NOW()
|
|
511
481
|
WHERE id = ${userId} AND NOT (${roleId} = ANY(roles))
|
|
512
|
-
`)
|
|
482
|
+
`);
|
|
513
483
|
}
|
|
514
484
|
|
|
515
485
|
/**
|
package/src/connection.ts
CHANGED
|
@@ -27,68 +27,11 @@ const DEFAULT_POOL: Required<PostgresPoolConfig> = {
|
|
|
27
27
|
max: 20,
|
|
28
28
|
idleTimeoutMillis: 30_000,
|
|
29
29
|
connectionTimeoutMillis: 10_000,
|
|
30
|
-
|
|
31
|
-
// statement_timeout. When the client timer fires first, node-postgres
|
|
32
|
-
// abandons the in-flight statement but keeps the connection — inside a
|
|
33
|
-
// transaction that leaves the tx open (and any pending ROLLBACK is
|
|
34
|
-
// spliced out of the client queue before it ever reaches the wire), so
|
|
35
|
-
// the pooled connection is returned still in-transaction with its RLS
|
|
36
|
-
// GUCs set. The server abort (SQLSTATE 57014) is the clean path; the
|
|
37
|
-
// client timeout is only a backstop for a dead network.
|
|
38
|
-
queryTimeout: 60_000,
|
|
30
|
+
queryTimeout: 30_000,
|
|
39
31
|
statementTimeout: 30_000,
|
|
40
32
|
keepAlive: true
|
|
41
33
|
};
|
|
42
34
|
|
|
43
|
-
/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
|
|
44
|
-
const TX_IDLE = "I";
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Destroy pool clients that are released while still inside a transaction.
|
|
48
|
-
*
|
|
49
|
-
* pg-pool returns a client to the idle list whenever `release()` is called
|
|
50
|
-
* without an error — even if the connection is still mid-transaction (status
|
|
51
|
-
* `T`/`E`). That happens in practice: drizzle's pool transaction releases in
|
|
52
|
-
* a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails
|
|
53
|
-
* (e.g. it was queued behind a statement that hit the client-side
|
|
54
|
-
* query_timeout), the client goes back dirty. The next checkout then runs
|
|
55
|
-
* its statements inside the zombie transaction — with the previous request's
|
|
56
|
-
* `app.*` RLS GUCs still applied, which turns unrelated queries into
|
|
57
|
-
* RLS-scoped ones (observed in production as registration failing with
|
|
58
|
-
* SQLSTATE 42501 under a leaked anonymous context).
|
|
59
|
-
*
|
|
60
|
-
* pg-pool emits `release` before it consults its private `_expired` set, so
|
|
61
|
-
* marking the client expired here makes `_release()` destroy it instead of
|
|
62
|
-
* pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are
|
|
63
|
-
* private APIs — feature-detect and fall back to loud logging so an upstream
|
|
64
|
-
* change degrades to observability, never to silent corruption.
|
|
65
|
-
*/
|
|
66
|
-
export function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {
|
|
67
|
-
pool.on("release", (err: Error | undefined, client: unknown) => {
|
|
68
|
-
if (err) return; // errored clients are already destroyed by pg-pool
|
|
69
|
-
const txStatus = (client as { _txStatus?: string | null })?._txStatus;
|
|
70
|
-
if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
|
|
71
|
-
|
|
72
|
-
// pg-pool keeps expired clients in a WeakSet (a plain object works too
|
|
73
|
-
// if upstream ever changes it — duck-type on add/has).
|
|
74
|
-
const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;
|
|
75
|
-
if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
|
|
76
|
-
expired.add(client);
|
|
77
|
-
logger.error(
|
|
78
|
-
`[${label}] Client released back to the pool while still in a transaction ` +
|
|
79
|
-
`(status '${txStatus}') — destroying it so the open transaction and its ` +
|
|
80
|
-
`session state (RLS GUCs) cannot leak into the next request.`
|
|
81
|
-
);
|
|
82
|
-
} else {
|
|
83
|
-
logger.error(
|
|
84
|
-
`[${label}] Client released mid-transaction (status '${txStatus}') but the ` +
|
|
85
|
-
`pool's internal expiry set is unavailable (pg-pool internals changed?). ` +
|
|
86
|
-
`The connection may leak its open transaction into subsequent requests.`
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
|
|
92
35
|
/**
|
|
93
36
|
* Create a Drizzle-backed Postgres connection with a production-grade
|
|
94
37
|
* connection pool.
|
|
@@ -132,7 +75,6 @@ export function createPostgresDatabaseConnection(
|
|
|
132
75
|
logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
|
|
133
76
|
}
|
|
134
77
|
});
|
|
135
|
-
guardPoolAgainstDirtyRelease(pool, "pg-pool");
|
|
136
78
|
|
|
137
79
|
// Create drizzle instance — pass schema when available to enable db.query relational API
|
|
138
80
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
@@ -176,7 +118,6 @@ export function createDirectDatabaseConnection(
|
|
|
176
118
|
pool.on("error", (err) => {
|
|
177
119
|
logger.error("[pg-direct-pool] Unexpected pool error", { detail: err.message });
|
|
178
120
|
});
|
|
179
|
-
guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
|
|
180
121
|
|
|
181
122
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
182
123
|
|
|
@@ -216,7 +157,6 @@ export function createReadReplicaConnection(
|
|
|
216
157
|
pool.on("error", (err) => {
|
|
217
158
|
logger.error("[pg-replica-pool] Unexpected pool error", { detail: err.message });
|
|
218
159
|
});
|
|
219
|
-
guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
|
|
220
160
|
|
|
221
161
|
const db = schema ? drizzle(pool, { schema }) : drizzle(pool);
|
|
222
162
|
|
package/src/data-transformer.ts
CHANGED
|
@@ -20,19 +20,12 @@ import { logger } from "@rebasepro/server";
|
|
|
20
20
|
export interface SerializedEntityData {
|
|
21
21
|
/** Scalar column values ready for INSERT/UPDATE. */
|
|
22
22
|
scalarData: Record<string, unknown>;
|
|
23
|
-
/**
|
|
24
|
-
* Inverse relation updates that must be applied to target tables.
|
|
25
|
-
*
|
|
26
|
-
* No address here: the row being written does not know its own. These are
|
|
27
|
-
* applied by `PersistService`, which addresses them with the id it holds —
|
|
28
|
-
* the one it was given for an update, or the one the INSERT returned — and
|
|
29
|
-
* that is the authority. This item used to carry a `currentId` derived from
|
|
30
|
-
* the *input* values, which nothing ever read.
|
|
31
|
-
*/
|
|
23
|
+
/** Inverse relation updates that must be applied to target tables. */
|
|
32
24
|
inverseRelationUpdates: Array<{
|
|
33
25
|
relationKey: string;
|
|
34
26
|
relation: Relation;
|
|
35
27
|
newValue: unknown;
|
|
28
|
+
currentId?: string | number;
|
|
36
29
|
}>;
|
|
37
30
|
/** JoinPath relation updates that require multi-hop writes. */
|
|
38
31
|
joinPathRelationUpdates: Array<{
|
|
@@ -112,6 +105,7 @@ joinPathRelationUpdates: [] };
|
|
|
112
105
|
relationKey: string;
|
|
113
106
|
relation: Relation;
|
|
114
107
|
newValue: unknown;
|
|
108
|
+
currentId?: string | number;
|
|
115
109
|
}> = [];
|
|
116
110
|
const joinPathRelationUpdates: Array<{
|
|
117
111
|
relationKey: string;
|
|
@@ -152,10 +146,12 @@ joinPathRelationUpdates: [] };
|
|
|
152
146
|
} else if (relation.direction === "inverse" && relation.foreignKeyOnTarget) {
|
|
153
147
|
// Inverse relation: Need to update the target table's FK
|
|
154
148
|
const serializedValue = serializePropertyToServer(effectiveValue, property);
|
|
149
|
+
const pks = getPrimaryKeys(collection, registry!);
|
|
155
150
|
inverseRelationUpdates.push({
|
|
156
151
|
relationKey: key,
|
|
157
152
|
relation,
|
|
158
|
-
newValue: serializedValue
|
|
153
|
+
newValue: serializedValue,
|
|
154
|
+
currentId: (row.id as string | number | undefined) || buildCompositeId(row, pks)
|
|
159
155
|
});
|
|
160
156
|
// Don't add the original relation property to the result
|
|
161
157
|
continue;
|
|
@@ -174,10 +170,12 @@ joinPathRelationUpdates: [] };
|
|
|
174
170
|
});
|
|
175
171
|
} else {
|
|
176
172
|
// Many inverse joinPath: capture as inverse relation update
|
|
173
|
+
const pks = getPrimaryKeys(collection, registry!);
|
|
177
174
|
inverseRelationUpdates.push({
|
|
178
175
|
relationKey: key,
|
|
179
176
|
relation,
|
|
180
|
-
newValue: serializedValue
|
|
177
|
+
newValue: serializedValue,
|
|
178
|
+
currentId: (row.id as string | number | undefined) || buildCompositeId(row, pks)
|
|
181
179
|
});
|
|
182
180
|
}
|
|
183
181
|
// Don't add the original relation property to the result
|
|
@@ -2,7 +2,6 @@ import { Pool } from "pg";
|
|
|
2
2
|
import { drizzle } from "drizzle-orm/node-postgres";
|
|
3
3
|
import { NodePgDatabase } from "drizzle-orm/node-postgres";
|
|
4
4
|
import { logger } from "@rebasepro/server";
|
|
5
|
-
import { guardPoolAgainstDirtyRelease } from "./connection";
|
|
6
5
|
|
|
7
6
|
export class DatabasePoolManager {
|
|
8
7
|
private pools: Map<string, Pool> = new Map();
|
|
@@ -51,7 +50,6 @@ export class DatabasePoolManager {
|
|
|
51
50
|
pool.on("error", (err) => {
|
|
52
51
|
logger.error(`[DatabasePoolManager] Unexpected error on idle client for db ${databaseName}`, { error: err });
|
|
53
52
|
});
|
|
54
|
-
guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);
|
|
55
53
|
|
|
56
54
|
this.pools.set(databaseName, pool);
|
|
57
55
|
return pool;
|