@rebasepro/server-postgres 0.9.1-canary.fd3754b → 0.10.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.
Files changed (67) hide show
  1. package/README.md +21 -0
  2. package/dist/PostgresBackendDriver.d.ts +43 -2
  3. package/dist/PostgresBootstrapper.d.ts +17 -1
  4. package/dist/auth/services.d.ts +68 -52
  5. package/dist/collections/buildRegistry.d.ts +27 -0
  6. package/dist/connection.d.ts +21 -0
  7. package/dist/data-transformer.d.ts +9 -2
  8. package/dist/index.es.js +2711 -2772
  9. package/dist/index.es.js.map +1 -1
  10. package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
  11. package/dist/schema/auth-schema.d.ts +24 -24
  12. package/dist/schema/doctor.d.ts +1 -1
  13. package/dist/schema/introspect-db-logic.d.ts +0 -5
  14. package/dist/schema/introspect-db-naming.d.ts +10 -0
  15. package/dist/security/policy-drift.d.ts +70 -5
  16. package/dist/security/rls-enforcement.d.ts +29 -4
  17. package/dist/services/FetchService.d.ts +4 -24
  18. package/dist/services/PersistService.d.ts +27 -1
  19. package/dist/services/RelationService.d.ts +34 -1
  20. package/dist/services/channel-history.d.ts +118 -0
  21. package/dist/services/collection-helpers.d.ts +79 -14
  22. package/dist/services/dataService.d.ts +3 -1
  23. package/dist/services/index.d.ts +1 -1
  24. package/dist/services/realtimeService.d.ts +76 -2
  25. package/dist/services/row-pipeline.d.ts +63 -0
  26. package/package.json +15 -40
  27. package/src/PostgresBackendDriver.ts +183 -18
  28. package/src/PostgresBootstrapper.ts +86 -27
  29. package/src/auth/ensure-tables.ts +170 -28
  30. package/src/auth/services.ts +181 -150
  31. package/src/cli-helpers.ts +2 -20
  32. package/src/cli.ts +60 -0
  33. package/src/collections/buildRegistry.ts +59 -0
  34. package/src/connection.ts +61 -1
  35. package/src/data-transformer.ts +11 -9
  36. package/src/databasePoolManager.ts +2 -0
  37. package/src/schema/auth-bootstrap-sql.ts +7 -1
  38. package/src/schema/auth-schema.ts +13 -13
  39. package/src/schema/doctor-cli.ts +5 -1
  40. package/src/schema/doctor.ts +45 -20
  41. package/src/schema/generate-drizzle-schema-logic.ts +24 -29
  42. package/src/schema/generate-postgres-ddl-logic.ts +76 -28
  43. package/src/schema/introspect-db-inference.ts +1 -1
  44. package/src/schema/introspect-db-logic.ts +1 -10
  45. package/src/schema/introspect-db-naming.ts +15 -0
  46. package/src/schema/introspect-db.ts +19 -2
  47. package/src/schema/introspect-runtime.ts +1 -1
  48. package/src/security/policy-drift.test.ts +199 -14
  49. package/src/security/policy-drift.ts +197 -13
  50. package/src/security/rls-enforcement.ts +74 -7
  51. package/src/services/BranchService.ts +42 -10
  52. package/src/services/FetchService.ts +65 -270
  53. package/src/services/PersistService.ts +130 -14
  54. package/src/services/RelationService.ts +153 -94
  55. package/src/services/channel-history.ts +343 -0
  56. package/src/services/collection-helpers.ts +164 -47
  57. package/src/services/dataService.ts +3 -2
  58. package/src/services/index.ts +1 -0
  59. package/src/services/realtimeService.ts +238 -29
  60. package/src/services/row-pipeline.ts +239 -0
  61. package/src/utils/drizzle-conditions.ts +13 -0
  62. package/src/websocket.ts +34 -12
  63. package/dist/chunk-DSJWtz9O.js +0 -40
  64. package/dist/schema/auth-default-policies.d.ts +0 -10
  65. package/dist/src-Eh-CZosp.js +0 -595
  66. package/dist/src-Eh-CZosp.js.map +0 -1
  67. package/src/schema/auth-default-policies.ts +0 -125
@@ -17,6 +17,7 @@ import {
17
17
  RebaseData,
18
18
  RebaseSdkData,
19
19
  RestFetchService,
20
+ SaveManyProps,
20
21
  SaveProps,
21
22
  TableColumnInfo,
22
23
  TableForeignKeyInfo,
@@ -28,6 +29,7 @@ import {
28
29
  import { sql as drizzleSql } from "drizzle-orm";
29
30
  import { buildPropertyCallbacks, buildSdkData, resolveCollectionRelations, updateDateAutoValues } from "@rebasepro/common";
30
31
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
32
+ import { deriveRowAddress } from "./services/collection-helpers";
31
33
  import { HistoryService } from "./history/HistoryService";
32
34
  import { mergeDeep } from "@rebasepro/utils";
33
35
  import { logger } from "@rebasepro/server";
@@ -109,6 +111,7 @@ export class PostgresBackendDriver implements DataDriver {
109
111
  executeSql: (...args: Parameters<NonNullable<DatabaseAdmin["executeSql"]>>) => this.executeSql(...args),
110
112
  fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
111
113
  fetchAvailableRoles: () => this.fetchAvailableRoles(),
114
+ fetchApplicationRoles: () => this.fetchApplicationRoles(),
112
115
  fetchCurrentDatabase: () => this.fetchCurrentDatabase(),
113
116
  fetchUnmappedTables: (...args: Parameters<NonNullable<DatabaseAdmin["fetchUnmappedTables"]>>) => this.fetchUnmappedTables(...args),
114
117
  fetchTableMetadata: (...args: Parameters<NonNullable<DatabaseAdmin["fetchTableMetadata"]>>) => this.fetchTableMetadata(...args),
@@ -532,7 +535,8 @@ export class PostgresBackendDriver implements DataDriver {
532
535
  id,
533
536
  values,
534
537
  collection,
535
- status
538
+ status,
539
+ upsert
536
540
  }: SaveProps<M>): Promise<Record<string, unknown>> {
537
541
 
538
542
  const {
@@ -545,13 +549,26 @@ export class PostgresBackendDriver implements DataDriver {
545
549
  let updatedValues = values;
546
550
  const contextForCallback = this.buildCallContext();
547
551
 
548
- // Fetch previous values for callbacks AND history recording
552
+ // Fetch previous values for callbacks AND history recording. Same walk
553
+ // as the saved row the callbacks receive (`fetchOneForRest`), so
554
+ // `values` and `previousValues` compare like with like — a Date on one
555
+ // side and its ISO string on the other reads as a change that never
556
+ // happened.
549
557
  let previousValuesForHistory: Partial<M> | undefined;
550
558
  if (status === "existing" && id) {
551
- const existing = await this.dataService.fetchOne<M>(path, id, resolvedCollection?.databaseId);
552
- if (existing) {
553
- const { id: _existingId, ...existingValues } = existing;
554
- previousValuesForHistory = existingValues as Partial<M>;
559
+ try {
560
+ const existing = await this.dataService.getFetchService()
561
+ .fetchOneForRest(path, id, undefined, resolvedCollection?.databaseId);
562
+ if (existing) {
563
+ const { id: _existingId, ...existingValues } = existing;
564
+ previousValuesForHistory = existingValues as Partial<M>;
565
+ }
566
+ } catch (err) {
567
+ // Best-effort enrichment: callbacks and history run without
568
+ // previous values rather than the save failing on a read the
569
+ // write itself does not need (e.g. a collection whose key the
570
+ // registry cannot resolve).
571
+ logger.debug(`[save] Could not fetch previous values for "${path}"`, { detail: err instanceof Error ? err.message : String(err) });
555
572
  }
556
573
  }
557
574
 
@@ -616,7 +633,8 @@ export class PostgresBackendDriver implements DataDriver {
616
633
  path,
617
634
  updatedValues,
618
635
  id,
619
- resolvedCollection?.databaseId
636
+ resolvedCollection?.databaseId,
637
+ { upsert }
620
638
  );
621
639
 
622
640
  if (savedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
@@ -649,8 +667,19 @@ export class PostgresBackendDriver implements DataDriver {
649
667
  }
650
668
  }
651
669
 
652
- const savedId = savedRow.id as string | number;
653
- const { id: _savedId, ...savedValues } = savedRow;
670
+ // The row is exactly its columns, so its address is derived, not read
671
+ // off it: `savedRow.id` is undefined for every table whose key is not
672
+ // literally named `id`, and is ordinary data for a table that has such
673
+ // a column without it being the key.
674
+ const savedId = deriveRowAddress(
675
+ savedRow,
676
+ (resolvedCollection ?? collection) as CollectionConfig,
677
+ this.registry
678
+ );
679
+ // `values` are the row's columns — all of them. For an `id`-keyed table
680
+ // that includes `id`, which used to be stripped here because it was the
681
+ // synthesized address rather than the column it now is.
682
+ const savedValues = savedRow;
654
683
 
655
684
  if (globalCallbacks?.afterSave || callbacks?.afterSave || propertyCallbacks?.afterSave) {
656
685
  // 1. Global callbacks first
@@ -695,7 +724,7 @@ export class PostgresBackendDriver implements DataDriver {
695
724
  if (this.historyService && resolvedCollection?.history) {
696
725
  this.historyService.recordHistory({
697
726
  tableName: path,
698
- id: savedId.toString(),
727
+ id: savedId,
699
728
  action: status === "new" ? "create" : "update",
700
729
  values: savedValues as Record<string, unknown>,
701
730
  previousValues: previousValuesForHistory as Record<string, unknown> | undefined,
@@ -707,14 +736,14 @@ export class PostgresBackendDriver implements DataDriver {
707
736
  if (this._deferNotifications) {
708
737
  this._pendingNotifications.push({
709
738
  path,
710
- id: savedId.toString(),
739
+ id: savedId,
711
740
  row: savedRow,
712
741
  databaseId: resolvedCollection?.databaseId
713
742
  });
714
743
  } else {
715
744
  await this.realtimeService.notifyUpdate(
716
745
  path,
717
- savedId.toString(),
746
+ savedId,
718
747
  savedRow,
719
748
  resolvedCollection?.databaseId
720
749
  );
@@ -764,13 +793,86 @@ export class PostgresBackendDriver implements DataDriver {
764
793
  }
765
794
  }
766
795
 
796
+ /**
797
+ * Write many rows through the same pipeline as {@link save}.
798
+ *
799
+ * The batch runs in one transaction of its own, so a failure part-way leaves
800
+ * nothing behind — the point of a batch is that a re-run starts from a known
801
+ * state. When this driver is already inside a transaction (the authenticated
802
+ * path, via `withTransaction`) the nested call becomes a savepoint, which is
803
+ * still atomic and still commits once.
804
+ *
805
+ * Rows are applied in order, so a batch that touches the same key twice ends
806
+ * with the last write winning, exactly as separate calls would.
807
+ */
808
+ async saveMany<M extends Record<string, unknown>>({
809
+ path,
810
+ rows,
811
+ collection,
812
+ upsert
813
+ }: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
814
+ return this.db.transaction(async (tx) => {
815
+ // Bind the whole batch to the transaction handle. Without this the
816
+ // rows would be written through `this.db` and survive a rollback.
817
+ const txDriver = new PostgresBackendDriver(
818
+ tx, this.realtimeService, this.registry, this.user, this.poolManager, this.historyService
819
+ );
820
+ txDriver.dataService = new DataService(tx, this.registry);
821
+ txDriver.client = this.client;
822
+ // Carry the caller's notification batching through, so a bulk write
823
+ // nested in an outer transaction still holds its events until commit.
824
+ txDriver._deferNotifications = this._deferNotifications;
825
+ txDriver._pendingNotifications = this._pendingNotifications;
826
+
827
+ const saved: Record<string, unknown>[] = [];
828
+
829
+ for (let i = 0; i < rows.length; i++) {
830
+ const values = rows[i];
831
+ const id = (values as Record<string, unknown>)?.id as string | number | undefined;
832
+ try {
833
+ saved.push(await txDriver.save<M>({
834
+ path,
835
+ values,
836
+ // No `id` argument, deliberately: passing one selects the
837
+ // UPDATE path, and an import's rows usually carry a natural
838
+ // key for a row that does not exist yet — which would 404 on
839
+ // every one. Leaving the key inside `values` is what
840
+ // single-row `create(data, id)` does, and it inserts.
841
+ // Callers who want existing rows overwritten pass `upsert`.
842
+ collection,
843
+ status: "new",
844
+ upsert
845
+ }));
846
+ } catch (error) {
847
+ // One bad row in ten thousand is impossible to find from a
848
+ // message that only says the batch failed. Say which row, and
849
+ // keep the original error as the cause so its status survives.
850
+ const label = id !== undefined ? `id ${JSON.stringify(id)}` : "no id";
851
+ throw Object.assign(
852
+ new Error(`Row ${i} of ${rows.length} (${label}) failed: ${(error as Error)?.message ?? error}`, { cause: error }),
853
+ {
854
+ statusCode: (error as { statusCode?: number })?.statusCode,
855
+ code: (error as { code?: string })?.code,
856
+ name: (error as Error)?.name
857
+ }
858
+ );
859
+ }
860
+ }
861
+
862
+ return saved;
863
+ });
864
+ }
865
+
767
866
  async delete<M extends Record<string, unknown>>({
768
867
  row,
769
868
  collection
770
869
  }: DeleteProps<M>): Promise<void> {
771
870
 
772
871
  const targetPath = row.path;
773
- const targetRow: Record<string, unknown> = { id: row.id, ...(row.values ?? {}) };
872
+ // The callbacks' `row` is the row: its columns, nothing else. The address
873
+ // travels beside it as `id`, so merging it in here only ever invented an
874
+ // `id` field for tables that have no such column.
875
+ const targetRow: Record<string, unknown> = { ...(row.values ?? {}) };
774
876
 
775
877
  // Resolve from backend registry to restore callbacks lost during WebSocket serialization
776
878
  const {
@@ -1070,6 +1172,56 @@ export class PostgresBackendDriver implements DataDriver {
1070
1172
  return result.map((r: Record<string, unknown>) => r.rolname as string);
1071
1173
  }
1072
1174
 
1175
+ /**
1176
+ * Application-level roles actually in use in this project.
1177
+ *
1178
+ * Distinct from {@link fetchAvailableRoles}, which returns native
1179
+ * PostgreSQL roles from `pg_roles` (`postgres`, `rebase_user`, …). Those
1180
+ * are the roles the SQL editor can `SET ROLE` to. *These* are the strings
1181
+ * held in the users table's `roles` column, injected per-transaction as
1182
+ * `auth.roles()` and matched by `SecurityRule.roles`. Feeding the pg roles
1183
+ * into a `SecurityRule.roles` field produces a condition no user can ever
1184
+ * satisfy, so the two must not be conflated.
1185
+ *
1186
+ * Roles have no registry table — they were migrated out of
1187
+ * `rebase.user_roles` onto an inline `roles TEXT[]` column — so the live
1188
+ * set is derived from what is assigned. A role that is declared in a policy
1189
+ * but held by nobody yet cannot be discovered here; callers that need it
1190
+ * should union in the roles they already know about.
1191
+ */
1192
+ async fetchApplicationRoles(): Promise<string[]> {
1193
+ // The users table lives in `rebase` for a default (public) setup, but
1194
+ // follows the configured schema otherwise — locate it rather than
1195
+ // assuming. The `roles` ARRAY column is what makes it the auth table.
1196
+ const located = await this.executeSql(`
1197
+ SELECT table_schema, table_name
1198
+ FROM information_schema.columns
1199
+ WHERE column_name = 'roles'
1200
+ AND data_type = 'ARRAY'
1201
+ AND table_name = 'users'
1202
+ AND table_schema NOT IN ('information_schema', 'pg_catalog')
1203
+ ORDER BY (table_schema = 'rebase') DESC, table_schema
1204
+ LIMIT 1;
1205
+ `);
1206
+ if (located.length === 0) return [];
1207
+
1208
+ const schema = located[0].table_schema as string;
1209
+ const table = located[0].table_name as string;
1210
+ // Identifiers come from information_schema, not user input, but they
1211
+ // are still interpolated — quote them so odd-but-legal names survive.
1212
+ const qualified = `"${schema.replace(/"/g, "\"\"")}"."${table.replace(/"/g, "\"\"")}"`;
1213
+
1214
+ const rows = await this.executeSql(`
1215
+ SELECT DISTINCT unnest(roles) AS role
1216
+ FROM ${qualified}
1217
+ WHERE roles IS NOT NULL
1218
+ ORDER BY role;
1219
+ `);
1220
+ return rows
1221
+ .map((r) => r.role as string)
1222
+ .filter((r): r is string => typeof r === "string" && r.length > 0);
1223
+ }
1224
+
1073
1225
  async fetchCurrentDatabase(): Promise<string | undefined> {
1074
1226
  return this.poolManager?.defaultDatabaseName;
1075
1227
  }
@@ -1273,10 +1425,10 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
1273
1425
  const pendingNotifications: PostgresBackendDriver["_pendingNotifications"] = [];
1274
1426
 
1275
1427
  const result = await this.delegate.db.transaction(async (tx) => {
1276
- let userId = this.user?.uid;
1277
- if (!userId) {
1428
+ let uid = this.user?.uid;
1429
+ if (!uid) {
1278
1430
  logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
1279
- userId = "anonymous";
1431
+ uid = "anonymous";
1280
1432
  }
1281
1433
 
1282
1434
  const userRoles = this.user?.roles ?? [];
@@ -1295,7 +1447,7 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
1295
1447
  //
1296
1448
  // Fails closed: if the switch cannot be performed, the transaction
1297
1449
  // aborts rather than falling back to an RLS-bypassing connection.
1298
- await applyAuthContext(tx, { userId, roles: userRoles }, this.delegate.rlsUserRole);
1450
+ await applyAuthContext(tx, { uid, roles: userRoles }, this.delegate.rlsUserRole);
1299
1451
 
1300
1452
  const txEntityService = new DataService(tx, this.delegate.registry);
1301
1453
  const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
@@ -1334,7 +1486,7 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
1334
1486
  */
1335
1487
  private injectAuthContext(unsubscribe: () => void): () => void {
1336
1488
  const authContext = {
1337
- userId: this.user?.uid || "anonymous",
1489
+ uid: this.user?.uid || "anonymous",
1338
1490
  roles: this.user?.roles ?? []
1339
1491
  };
1340
1492
  const entries = Array.from(this.delegate.realtimeService.subscriptions.entries());
@@ -1362,6 +1514,19 @@ export class AuthenticatedPostgresBackendDriver implements DataDriver {
1362
1514
  return this.withTransaction((delegate) => delegate.save(props));
1363
1515
  }
1364
1516
 
1517
+ /**
1518
+ * One transaction for the whole batch, rather than one per row.
1519
+ *
1520
+ * This is the point of the method: `save` opens a transaction per call, so
1521
+ * importing 10k rows through it means 10k transactions (and, over HTTP, 10k
1522
+ * round trips). Here the RLS context is established once and every row lands
1523
+ * or none does. Realtime notifications are already deferred to commit by
1524
+ * `withTransaction`, so a batch does not flood subscribers mid-flight.
1525
+ */
1526
+ async saveMany<M extends Record<string, unknown>>(props: SaveManyProps<M>): Promise<Record<string, unknown>[]> {
1527
+ return this.withTransaction((delegate) => delegate.saveMany(props));
1528
+ }
1529
+
1365
1530
  async delete<M extends Record<string, unknown>>(props: DeleteProps<M>): Promise<void> {
1366
1531
  return this.withTransaction((delegate) => delegate.delete(props));
1367
1532
  }
@@ -4,7 +4,7 @@
4
4
  * Implements the `BackendBootstrapper` interface for PostgreSQL.
5
5
  */
6
6
 
7
- import { getTableName, isTable, Relations, sql } from "drizzle-orm";
7
+ import { 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";
@@ -17,10 +17,12 @@ import {
17
17
  CollectionConfig,
18
18
  type HistoryConfig,
19
19
  InitializedDriver,
20
- RealtimeProvider
20
+ RealtimeProvider,
21
+ type RealtimeChannelsConfig
21
22
  } from "@rebasepro/types";
22
23
  import { PostgresBackendDriver } from "./PostgresBackendDriver";
23
24
  import { RealtimeService } from "./services/realtimeService";
25
+ import { buildCollectionRegistry } from "./collections/buildRegistry";
24
26
  import { DatabasePoolManager } from "./databasePoolManager";
25
27
  import { PostgresCollectionRegistry } from "./collections/PostgresCollectionRegistry";
26
28
  import { createEmailService, type EmailConfig, type EmailService, logger } from "@rebasepro/server";
@@ -33,7 +35,7 @@ import { ensureHistoryTableExists } from "./history/ensure-history-table";
33
35
  import { patchPgArrayNullSafety } from "./utils/pg-array-null-patch";
34
36
  import { buildCollectionsFromSchema, introspectSchema, readRlsStatus } from "./schema/introspect-runtime";
35
37
  import { buildDrizzleTablesFromSchema, buildDrizzleRelationsFromSchema } from "./schema/dynamic-tables";
36
- import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
38
+ import { detectConnectionPosture, ensureAppRole, validatePolicyPgRoles, warnOnAnonymousGrants, REBASE_USER_ROLE, type RawSqlRunner } from "./security/rls-enforcement";
37
39
  import { provisionTriggerCdc, type CdcTableRef } from "./services/cdc/trigger-cdc";
38
40
 
39
41
  export interface PostgresDriverConfig {
@@ -51,6 +53,12 @@ export interface PostgresDriverConfig {
51
53
  * (BaaS mode). Defaults to `public`.
52
54
  */
53
55
  introspectionSchema?: string;
56
+ /**
57
+ * Realtime options. Currently only channel retention, which is opt-in:
58
+ * without rules here no channel keeps any history and broadcast stays
59
+ * fire-and-forget. See {@link ChannelRetentionRule}.
60
+ */
61
+ realtime?: RealtimeChannelsConfig;
54
62
  }
55
63
 
56
64
  /**
@@ -64,6 +72,15 @@ export interface PostgresDriverInternals {
64
72
  realtimeService: RealtimeService;
65
73
  driver: PostgresBackendDriver;
66
74
  poolManager?: DatabasePoolManager;
75
+ /**
76
+ * Attach CDC triggers to tables that did not exist when the driver
77
+ * bootstrapped. Only set when database-level capture is actually active.
78
+ *
79
+ * Auth owns its own tables and creates them later in boot, so at driver
80
+ * bootstrap they are legitimately missing and get skipped; without this
81
+ * they would stay uninstrumented until the next restart.
82
+ */
83
+ provisionCdcForTables?: (tables: CdcTableRef[]) => Promise<void>;
67
84
  }
68
85
 
69
86
  // Re-export from shared CLI error utilities
@@ -161,30 +178,17 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
161
178
  }
162
179
 
163
180
  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
-
172
181
  const schemaTables = introspectedTables ?? pgConfig.schema?.tables;
173
-
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
182
  const schemaRelations = introspectedRelations ?? (pgConfig.schema?.relations as Record<string, Relations> | undefined);
187
- if (schemaRelations) registry.registerRelations(schemaRelations);
183
+
184
+ // Create a fresh registry for this driver. Registration order is
185
+ // load-bearing, so it lives in one place — see `buildCollectionRegistry`.
186
+ const registry = buildCollectionRegistry({
187
+ collections: activeCollections,
188
+ tables: schemaTables,
189
+ enums: pgConfig.schema?.enums as Record<string, PgEnum<[string, ...string[]]>> | undefined,
190
+ relations: schemaRelations
191
+ });
188
192
 
189
193
  // Patch Drizzle's PgArray columns to handle NULL values safely.
190
194
  // Drizzle's mapFromDriverValue crashes with "value.map is not a function"
@@ -303,6 +307,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
303
307
  registry.getCollections() as never,
304
308
  driver.rlsUserRole ?? posture.role
305
309
  );
310
+
311
+ // The same habit one surface over, and the dangerous direction:
312
+ // a rule that reads as "signed in only" but is true for every
313
+ // caller grants the data away rather than hiding it.
314
+ warnOnAnonymousGrants(registry.getCollections() as never);
306
315
  }
307
316
 
308
317
  // Ensure branch metadata table exists when branching is available
@@ -314,6 +323,16 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
314
323
  }
315
324
  }
316
325
 
326
+ // ── Channel history ──────────────────────────────────────────────
327
+ // Opt-in per channel pattern. With no rules this creates no tables
328
+ // and leaves broadcast on its original fire-and-forget path, so
329
+ // presence-only apps pay nothing for it.
330
+ try {
331
+ await realtimeService.configureChannelHistory(pgConfig.realtime?.channels);
332
+ } catch (err) {
333
+ logger.warn("⚠️ Could not initialize channel history tables — retained channels will not replay", { error: err });
334
+ }
335
+
317
336
  // ── Realtime change source ───────────────────────────────────────
318
337
  // Prefer DATABASE_DIRECT_URL to bypass PgBouncer for LISTEN/NOTIFY.
319
338
  const directUrl = process.env.DATABASE_DIRECT_URL || pgConfig.connectionString;
@@ -341,6 +360,7 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
341
360
  const wantsCdc = cdcMode !== "off";
342
361
  const explicitCdc = cdcMode === "trigger" || cdcMode === "wal";
343
362
  let cdcEnabled = false;
363
+ let provisionCdcForTables: PostgresDriverInternals["provisionCdcForTables"];
344
364
 
345
365
  if (wantsCdc && !directUrl) {
346
366
  const reason = "no direct database connection is available for the realtime LISTEN client (set DATABASE_DIRECT_URL)";
@@ -374,6 +394,11 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
374
394
  await provisionTriggerCdc(cdcRunSql, cdcTables);
375
395
  await realtimeService.enableCdc(directUrl);
376
396
  cdcEnabled = true;
397
+ // Boot steps that create their own tables (auth) run after
398
+ // this one and use it to instrument what they just created.
399
+ provisionCdcForTables = async (tables) => {
400
+ await provisionTriggerCdc(cdcRunSql, tables);
401
+ };
377
402
  logger.info(
378
403
  `📡 [CDC] Realtime source = database-level change capture (mode: ${cdcMode === "wal" ? "wal→trigger" : "trigger"}). ` +
379
404
  `All writes now emit realtime events regardless of origin.`
@@ -424,6 +449,14 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
424
449
  );
425
450
  const missing: Array<{ slug: string; table: string }> = [];
426
451
  for (const col of registeredCollections) {
452
+ // Auth owns its table and creates it later in this same
453
+ // boot (initializeAuth → ensureAuthTablesExist), so it is
454
+ // legitimately absent right now. Reporting it as drift
455
+ // tells the user to `db:push` a table that is about to
456
+ // exist — and on an introspected database, one that the
457
+ // database was never supposed to hold.
458
+ if ((col as { auth?: { enabled?: boolean } }).auth?.enabled) continue;
459
+
427
460
  const schemaName = "schema" in col && col.schema ? col.schema : "public";
428
461
  const tableName = registry.hasTableForCollection(
429
462
  col.table ?? col.slug
@@ -438,8 +471,10 @@ export function createPostgresBootstrapper(pgConfig: PostgresDriverConfig): Back
438
471
  const checkName = resolvedTable ?? tableName;
439
472
  const fullCheckName = schemaName === "public" ? checkName : `${schemaName}.${checkName}`;
440
473
  if (!dbTables.has(fullCheckName)) {
474
+ // Report what was actually looked up: an unqualified
475
+ // "users" sends people hunting for public.users.
441
476
  missing.push({ slug: col.slug,
442
- table: checkName });
477
+ table: fullCheckName });
443
478
  }
444
479
  }
445
480
  if (missing.length > 0) {
@@ -473,7 +508,8 @@ table: checkName });
473
508
  registry,
474
509
  realtimeService,
475
510
  driver,
476
- poolManager
511
+ poolManager,
512
+ provisionCdcForTables
477
513
  };
478
514
 
479
515
  return {
@@ -502,6 +538,29 @@ table: checkName });
502
538
  // ensureAuthTablesExist works with the collection abstraction — no Drizzle leakage.
503
539
  await ensureAuthTablesExist(db, authCollection);
504
540
 
541
+ // The driver bootstrapped before these tables existed, so CDC skipped
542
+ // them. Instrument them now, or writes to the user table emit no
543
+ // realtime events until the next restart.
544
+ if (authCollection && internals.provisionCdcForTables) {
545
+ const authSchema = "schema" in authCollection && typeof authCollection.schema === "string"
546
+ ? authCollection.schema
547
+ : "rebase";
548
+ const authTable = "table" in authCollection && typeof authCollection.table === "string"
549
+ ? authCollection.table
550
+ : authCollection.slug;
551
+ if (authTable) {
552
+ try {
553
+ await internals.provisionCdcForTables([{ schema: authSchema, table: authTable }]);
554
+ } catch (err) {
555
+ logger.warn(
556
+ `⚠️ [CDC] Could not attach change-capture to the auth table "${authSchema}.${authTable}" — ` +
557
+ "writes to it won't emit database-level events.",
558
+ { detail: err instanceof Error ? err.message : String(err) }
559
+ );
560
+ }
561
+ }
562
+ }
563
+
505
564
  let emailService: EmailService | undefined;
506
565
  if (authConfig.email) {
507
566
  emailService = createEmailService(authConfig.email as EmailConfig);