@rebasepro/server-postgres 0.28.2 → 0.29.0-canary.g0e3a0e7

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 (40) hide show
  1. package/dist/PostgresBackendDriver.d.ts +69 -1
  2. package/dist/PostgresBootstrapper.d.ts +34 -1
  3. package/dist/{cli-console-C0FYkICX.js → cli-console-CJLtH58M.js} +3 -3
  4. package/dist/{cli-console-C0FYkICX.js.map → cli-console-CJLtH58M.js.map} +1 -1
  5. package/dist/cli.js +12 -12
  6. package/dist/{connection-czvI7TZL.js → connection-CcYqncW5.js} +113 -36
  7. package/dist/connection-CcYqncW5.js.map +1 -0
  8. package/dist/connection.d.ts +57 -0
  9. package/dist/database-health.d.ts +23 -0
  10. package/dist/{databasePoolManager-BjoVvuAq.js → databasePoolManager-XmhMczz0.js} +2 -2
  11. package/dist/{databasePoolManager-BjoVvuAq.js.map → databasePoolManager-XmhMczz0.js.map} +1 -1
  12. package/dist/{deferred-index-build-BcJ_oulu.js → deferred-index-build-BwH6k1Og.js} +30 -1
  13. package/dist/{deferred-index-build-BcJ_oulu.js.map → deferred-index-build-BwH6k1Og.js.map} +1 -1
  14. package/dist/{ensure-collection-policies-BNwSQfVx.js → ensure-collection-policies-f0LIwiwp.js} +3 -3
  15. package/dist/{ensure-collection-policies-BNwSQfVx.js.map → ensure-collection-policies-f0LIwiwp.js.map} +1 -1
  16. package/dist/{ensure-collection-tables-CSbgkTBx.js → ensure-collection-tables-DvaCEy6X.js} +4 -4
  17. package/dist/{ensure-collection-tables-CSbgkTBx.js.map → ensure-collection-tables-DvaCEy6X.js.map} +1 -1
  18. package/dist/{enum-labels-kept-BCgFGAbJ.js → enum-labels-kept-DAbJ_IIl.js} +2 -2
  19. package/dist/{enum-labels-kept-BCgFGAbJ.js.map → enum-labels-kept-DAbJ_IIl.js.map} +1 -1
  20. package/dist/index.d.ts +5 -2
  21. package/dist/index.es.js +4 -4
  22. package/dist/{migrate-policy-stamps-B-8vTSIm.js → migrate-policy-stamps-CdljD_y1.js} +4 -4
  23. package/dist/{migrate-policy-stamps-B-8vTSIm.js.map → migrate-policy-stamps-CdljD_y1.js.map} +1 -1
  24. package/dist/{open-rebase-D9n8idex.js → open-rebase-DvmKIu7q.js} +591 -37
  25. package/dist/open-rebase-DvmKIu7q.js.map +1 -0
  26. package/dist/pooled-database.d.ts +38 -0
  27. package/dist/{push-index-prebuild-DR3P4yOw.js → push-index-prebuild-C6wKdjYV.js} +3 -3
  28. package/dist/{push-index-prebuild-DR3P4yOw.js.map → push-index-prebuild-C6wKdjYV.js.map} +1 -1
  29. package/dist/{push-legacy-renames-BIxBmVLl.js → push-legacy-renames-BFF72tHG.js} +3 -3
  30. package/dist/{push-legacy-renames-BIxBmVLl.js.map → push-legacy-renames-BFF72tHG.js.map} +1 -1
  31. package/dist/{push-policy-plan-BHsasXa7.js → push-policy-plan-lOTPeQ1u.js} +2 -2
  32. package/dist/{push-policy-plan-BHsasXa7.js.map → push-policy-plan-lOTPeQ1u.js.map} +1 -1
  33. package/dist/read-routing.d.ts +139 -0
  34. package/dist/schema/deferred-index-build.d.ts +9 -0
  35. package/dist/schema/introspect-db.js +1 -1
  36. package/dist/{websocket-D4wrzF3b.js → websocket-CCJnghvG.js} +2 -2
  37. package/dist/{websocket-D4wrzF3b.js.map → websocket-CCJnghvG.js.map} +1 -1
  38. package/package.json +7 -7
  39. package/dist/connection-czvI7TZL.js.map +0 -1
  40. package/dist/open-rebase-D9n8idex.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { i as createPostgresDatabaseConnection } from "./connection-czvI7TZL.js";
3
+ import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, l as isPooledPool, m as transactionSettingsStatements, n as closeWithPool, p as searchPathList } from "./connection-CcYqncW5.js";
4
4
  import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
5
5
  import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-DYets7cp.js";
6
6
  import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BIHfsGZL.js";
@@ -11,11 +11,11 @@ import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
11
11
  import { n as planSchema } from "./plan-schema-DMVh77yb.js";
12
12
  import { t as generateSchema } from "./generate-drizzle-schema-logic-CVRmZjP3.js";
13
13
  import { i as renderPgType } from "./render-ddl-NpPPDACz.js";
14
- import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-BcJ_oulu.js";
14
+ import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-BwH6k1Og.js";
15
15
  import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CIGoIGcC.js";
16
- import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-CSbgkTBx.js";
16
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DvaCEy6X.js";
17
17
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
18
- import { t as DatabasePoolManager } from "./databasePoolManager-BjoVvuAq.js";
18
+ import { t as DatabasePoolManager } from "./databasePoolManager-XmhMczz0.js";
19
19
  import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CF-8zgYA.js";
20
20
  import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-ChFg6UxI.js";
21
21
  import { Client, DatabaseError, Pool } from "pg";
@@ -8296,7 +8296,10 @@ async function generateSchemaCommit(input) {
8296
8296
  * This plans both, for a person to read. It relaxes every column the
8297
8297
  * collections declare optional and the database still requires — the
8298
8298
  * `drop-not-null` actions the live editor's `converge` policy already plans —
8299
- * and it lists every column no collection declares. It drops only the columns
8299
+ * and it lists every column no collection declares. An undeclared column that
8300
+ * blocks inserts (NOT NULL, no default) is relaxed too, unless it is being
8301
+ * dropped: that keeps its data and makes the table writable again, which is
8302
+ * the one thing a removed property must not prevent. It drops only the columns
8300
8303
  * the caller names, one by one: removing a property is not consent to destroy
8301
8304
  * the column's data, so the drop is a separate, explicit act.
8302
8305
  *
@@ -8371,6 +8374,16 @@ function planSchemaReconcile(collections, existing, options = {}) {
8371
8374
  }
8372
8375
  problems.push(table.columns.some((c) => c.column === column) ? `"${request}": the "${slug}" collection still declares "${column}". Remove the property, deploy, then drop it.` : `"${request}": "${table.qualified}" has no column "${column}".`);
8373
8376
  }
8377
+ for (const column of undeclared) {
8378
+ if (!column.blocksInserts || dropped.includes(column)) continue;
8379
+ relaxed.push({
8380
+ collection: column.collection,
8381
+ table: column.table,
8382
+ column: column.column,
8383
+ undeclared: true
8384
+ });
8385
+ relaxStatements.push(`ALTER TABLE ${relation(column.tablePlan)} ALTER COLUMN "${column.column}" DROP NOT NULL;`);
8386
+ }
8374
8387
  const statements = [...relaxStatements, ...dropped.map((d) => `ALTER TABLE ${relation(d.tablePlan)} DROP COLUMN "${d.column}";`)];
8375
8388
  const strip = ({ tablePlan: _table, ...column }) => column;
8376
8389
  return {
@@ -9387,6 +9400,291 @@ var PgNotifyListener = class {
9387
9400
  }
9388
9401
  };
9389
9402
  //#endregion
9403
+ //#region src/read-routing.ts
9404
+ var DEFAULT_READ_STICKY_MS = 5e3;
9405
+ var DEFAULT_READ_MAX_LAG_MS = 1e3;
9406
+ var DEFAULT_SAMPLE_INTERVAL_MS = 1e3;
9407
+ var DEFAULT_FAILURE_COOLDOWN_MS = 1e4;
9408
+ var DEFAULT_MAX_PINNED = 1e4;
9409
+ /** A sample older than this many intervals is no evidence about the standby now. */
9410
+ var STALE_SAMPLE_INTERVALS = 3;
9411
+ var FAILURE_WARNING_INTERVAL_MS = 6e4;
9412
+ /**
9413
+ * Parse one of the routing variables: a whole number of milliseconds, zero
9414
+ * allowed. A value that is set and malformed throws, naming the variable — a
9415
+ * mistyped guard must not quietly become another number.
9416
+ */
9417
+ function parseReadRoutingMs(raw, variable) {
9418
+ const trimmed = raw.trim();
9419
+ if (!/^[0-9]+$/.test(trimmed)) throw new Error(`${variable} must be a whole number of milliseconds, got "${raw}".`);
9420
+ return Number(trimmed);
9421
+ }
9422
+ /** The routing options from the environment, defaults filled in. */
9423
+ function readRoutingOptionsFromEnv(env) {
9424
+ const sticky = env.REBASE_READ_STICKY_MS?.trim();
9425
+ const lag = env.REBASE_READ_MAX_LAG_MS?.trim();
9426
+ return {
9427
+ stickyMs: sticky ? parseReadRoutingMs(sticky, "REBASE_READ_STICKY_MS") : DEFAULT_READ_STICKY_MS,
9428
+ maxLagMs: lag ? parseReadRoutingMs(lag, "REBASE_READ_MAX_LAG_MS") : DEFAULT_READ_MAX_LAG_MS
9429
+ };
9430
+ }
9431
+ /**
9432
+ * Whether two connection strings name the same database on the same server as
9433
+ * the same role — ignoring the query string, where the boot pins
9434
+ * `options=-c search_path=…` onto the primary's URL. Comparing the strings
9435
+ * themselves is how the read pool came to be opened for a `DATABASE_READ_URL`
9436
+ * that named the primary: the pinned primary URL never equalled the bare one.
9437
+ *
9438
+ * Unparseable strings are compared as given.
9439
+ */
9440
+ function sameDatabaseTarget(a, b) {
9441
+ let left;
9442
+ let right;
9443
+ try {
9444
+ left = new URL(a);
9445
+ right = new URL(b);
9446
+ } catch {
9447
+ return a === b;
9448
+ }
9449
+ const port = (url) => url.port || "5432";
9450
+ return left.hostname.toLowerCase() === right.hostname.toLowerCase() && port(left) === port(right) && decodeURIComponent(left.pathname) === decodeURIComponent(right.pathname) && decodeURIComponent(left.username) === decodeURIComponent(right.username);
9451
+ }
9452
+ /**
9453
+ * SQLSTATEs after which a read is retried on the primary: the standby could
9454
+ * not serve it, not a judgement of the statement. Class 08 (connection), class
9455
+ * 53 (out of connections or resources), `57P0x` (shutting down, restarting,
9456
+ * starting), `57014` (statement cancelled — a standby cancels queries that
9457
+ * conflict with replay), and `40001` (the same conflict, reported as a
9458
+ * serialization failure).
9459
+ */
9460
+ function isReplicaSqlState(code) {
9461
+ return code.startsWith("08") || code.startsWith("53") || code.startsWith("57P") || code === "57014" || code === "40001";
9462
+ }
9463
+ var REPLICA_NETWORK_CODES = /* @__PURE__ */ new Set([
9464
+ "ECONNREFUSED",
9465
+ "ECONNRESET",
9466
+ "ENOTFOUND",
9467
+ "EAI_AGAIN",
9468
+ "EHOSTUNREACH",
9469
+ "ENETUNREACH",
9470
+ "ETIMEDOUT",
9471
+ "EPIPE"
9472
+ ]);
9473
+ var REPLICA_POOL_MESSAGES = [
9474
+ "timeout exceeded when trying to connect",
9475
+ "Connection terminated due to connection timeout",
9476
+ "Connection terminated unexpectedly",
9477
+ "Client has encountered a connection error and is not queryable",
9478
+ "Query read timeout"
9479
+ ];
9480
+ /**
9481
+ * Whether a read that failed on the standby should be run again on the
9482
+ * primary: the standby (or the way to it) failed, anywhere down the cause
9483
+ * chain. A policy denial, a bad filter or an error a hook threw is the read's
9484
+ * own answer, and the primary would give it too — those are not retried, so a
9485
+ * hook with side effects does not run twice for them.
9486
+ */
9487
+ function isReplicaFallbackError(error, depth = 0) {
9488
+ if (!error || typeof error !== "object" || depth > 8) return false;
9489
+ const code = Reflect.get(error, "code");
9490
+ if (typeof code === "string" && (REPLICA_NETWORK_CODES.has(code) || /^[0-9A-Z]{5}$/.test(code) && isReplicaSqlState(code))) return true;
9491
+ const message = Reflect.get(error, "message");
9492
+ if (typeof message === "string" && REPLICA_POOL_MESSAGES.some((m) => message.startsWith(m))) return true;
9493
+ if (error instanceof AggregateError && error.errors.some((e) => isReplicaFallbackError(e, depth + 1))) return true;
9494
+ return isReplicaFallbackError(Reflect.get(error, "cause"), depth + 1);
9495
+ }
9496
+ /**
9497
+ * Replay lag in milliseconds, as the standby sees it: zero when it has
9498
+ * replayed everything it received (an idle primary sends nothing, and the
9499
+ * last replayed transaction's age would otherwise grow without bound), else
9500
+ * the age of the last transaction it replayed. Zero on a server that is not
9501
+ * in recovery — a read URL that names a primary has no lag. `null` when the
9502
+ * standby cannot say.
9503
+ */
9504
+ var REPLICA_LAG_SQL = `SELECT CASE
9505
+ WHEN NOT pg_is_in_recovery() THEN 0
9506
+ WHEN pg_last_wal_receive_lsn() IS NOT NULL AND pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
9507
+ ELSE EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) * 1000
9508
+ END AS lag_ms`;
9509
+ /** Run {@link REPLICA_LAG_SQL} on `pool`, in milliseconds. */
9510
+ async function readReplicaLagMs(pool) {
9511
+ const raw = (await pool.query(REPLICA_LAG_SQL)).rows[0]?.lag_ms;
9512
+ if (raw === null || raw === void 0) return null;
9513
+ const lag = Number(raw);
9514
+ return Number.isFinite(lag) ? Math.max(0, lag) : null;
9515
+ }
9516
+ /**
9517
+ * The standby's routing state for one data source: recent writers, the last
9518
+ * lag sample, and whether the standby failed a read recently. One per source,
9519
+ * held by the base driver, so every request's authenticated driver shares it.
9520
+ */
9521
+ var ReadRouter = class {
9522
+ db;
9523
+ sampleLag;
9524
+ stickyMs;
9525
+ maxLagMs;
9526
+ sampleIntervalMs;
9527
+ failureCooldownMs;
9528
+ maxPinned;
9529
+ now;
9530
+ /** Principal → when its read-your-writes window ends. Insertion order is age. */
9531
+ pinnedUntil = /* @__PURE__ */ new Map();
9532
+ lagMs = null;
9533
+ sampledAt = Number.NEGATIVE_INFINITY;
9534
+ unavailableUntil = 0;
9535
+ lastFailureWarningAt = Number.NEGATIVE_INFINITY;
9536
+ timer;
9537
+ sampling;
9538
+ constructor(db, sampleLag, options) {
9539
+ this.db = db;
9540
+ this.sampleLag = sampleLag;
9541
+ this.stickyMs = options.stickyMs;
9542
+ this.maxLagMs = options.maxLagMs;
9543
+ this.sampleIntervalMs = options.sampleIntervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS;
9544
+ this.failureCooldownMs = options.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
9545
+ this.maxPinned = options.maxPinnedPrincipals ?? DEFAULT_MAX_PINNED;
9546
+ this.now = options.now ?? Date.now;
9547
+ }
9548
+ /** Take the first sample and keep sampling. Unref'd: it never holds the process open. */
9549
+ start() {
9550
+ if (this.timer) return;
9551
+ this.sample();
9552
+ this.timer = setInterval(() => void this.sample(), this.sampleIntervalMs);
9553
+ this.timer.unref?.();
9554
+ }
9555
+ stop() {
9556
+ if (this.timer) clearInterval(this.timer);
9557
+ this.timer = void 0;
9558
+ }
9559
+ /** One lag sample. A failed sample leaves no sample, so reads go to the primary. */
9560
+ sample() {
9561
+ this.sampling ??= (async () => {
9562
+ try {
9563
+ const lag = await this.sampleLag();
9564
+ this.lagMs = lag;
9565
+ this.sampledAt = lag === null ? Number.NEGATIVE_INFINITY : this.now();
9566
+ } catch (error) {
9567
+ this.lagMs = null;
9568
+ this.sampledAt = Number.NEGATIVE_INFINITY;
9569
+ this.noteReplicaFailure(error);
9570
+ } finally {
9571
+ this.sampling = void 0;
9572
+ }
9573
+ })();
9574
+ return this.sampling;
9575
+ }
9576
+ /** The last sampled lag in seconds, or `undefined` with no current sample. */
9577
+ get lagSeconds() {
9578
+ return this.hasFreshSample() && this.lagMs !== null ? this.lagMs / 1e3 : void 0;
9579
+ }
9580
+ /**
9581
+ * Where `principal`'s read goes. A read with no principal is routed on the
9582
+ * standby's health alone: there is no write of its own to see.
9583
+ */
9584
+ route(principal) {
9585
+ const now = this.now();
9586
+ if (now < this.unavailableUntil) return {
9587
+ target: "primary",
9588
+ reason: "unavailable"
9589
+ };
9590
+ if (principal !== void 0) {
9591
+ const until = this.pinnedUntil.get(principal);
9592
+ if (until !== void 0) {
9593
+ if (now < until) return {
9594
+ target: "primary",
9595
+ reason: "sticky"
9596
+ };
9597
+ this.pinnedUntil.delete(principal);
9598
+ }
9599
+ }
9600
+ if (!this.hasFreshSample() || this.lagMs === null) return {
9601
+ target: "primary",
9602
+ reason: "no-sample"
9603
+ };
9604
+ if (this.lagMs > this.maxLagMs) return {
9605
+ target: "primary",
9606
+ reason: "lag"
9607
+ };
9608
+ return { target: "replica" };
9609
+ }
9610
+ /**
9611
+ * `principal` is writing: its reads go to the primary until
9612
+ * {@link stickyMs} after this. Called when the write starts AND when it
9613
+ * ends, so a read during a long write is pinned too and the window runs
9614
+ * from the commit.
9615
+ */
9616
+ notePrimaryWrite(principal) {
9617
+ if (this.stickyMs <= 0) return;
9618
+ this.pinnedUntil.delete(principal);
9619
+ this.pinnedUntil.set(principal, this.now() + this.stickyMs);
9620
+ while (this.pinnedUntil.size > this.maxPinned) {
9621
+ const oldest = this.pinnedUntil.keys().next().value;
9622
+ if (oldest === void 0) break;
9623
+ this.pinnedUntil.delete(oldest);
9624
+ }
9625
+ }
9626
+ /** The standby failed: leave it alone for the cooldown, and say so once a minute. */
9627
+ noteReplicaFailure(error) {
9628
+ const now = this.now();
9629
+ this.unavailableUntil = now + this.failureCooldownMs;
9630
+ if (now - this.lastFailureWarningAt >= FAILURE_WARNING_INTERVAL_MS) {
9631
+ this.lastFailureWarningAt = now;
9632
+ logger.warn("⚠️ The read replica (DATABASE_READ_URL) failed, so reads are served by the primary for now. Not repeated for a minute.", { error: error instanceof Error ? error.message : String(error) });
9633
+ }
9634
+ }
9635
+ hasFreshSample() {
9636
+ return this.now() - this.sampledAt <= this.sampleIntervalMs * STALE_SAMPLE_INTERVALS;
9637
+ }
9638
+ };
9639
+ //#endregion
9640
+ //#region src/database-health.ts
9641
+ /** The three counts `pg.Pool` keeps, as a stats row for `pool`. */
9642
+ function poolStatsOf(pool, name) {
9643
+ return {
9644
+ pool: name,
9645
+ total: pool.totalCount,
9646
+ idle: pool.idleCount,
9647
+ waiting: pool.waitingCount
9648
+ };
9649
+ }
9650
+ /**
9651
+ * Connections by state, across the server — `max_connections` is a server
9652
+ * limit, so a count of one database's would understate how close it is.
9653
+ * Client backends only: the server's own workers do not count against it.
9654
+ * A role without `pg_read_all_stats` sees other roles' sessions with a null
9655
+ * state, which is counted as `unknown` rather than dropped.
9656
+ */
9657
+ var CONNECTIONS_SQL = `SELECT COALESCE(state, 'unknown') AS state, count(*)::int AS count
9658
+ FROM pg_stat_activity
9659
+ WHERE backend_type = 'client backend'
9660
+ GROUP BY 1`;
9661
+ /**
9662
+ * Sample the server behind `primary`, and the standby behind `replica` when
9663
+ * there is one. Each part is read on its own: a role that may not read one
9664
+ * answer still reports the others, and the part it could not read is left
9665
+ * out rather than reported as zero.
9666
+ */
9667
+ async function sampleDatabaseHealth(primary, replica) {
9668
+ const sample = {};
9669
+ const [connections, max, size, lag] = await Promise.allSettled([
9670
+ primary.query(CONNECTIONS_SQL),
9671
+ primary.query("SELECT current_setting('max_connections') AS max"),
9672
+ primary.query("SELECT pg_database_size(current_database())::text AS bytes"),
9673
+ replica ? readReplicaLagMs(replica) : Promise.resolve(null)
9674
+ ]);
9675
+ if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [row.state, Number(row.count)]));
9676
+ if (max.status === "fulfilled") {
9677
+ const value = Number(max.value.rows[0]?.max);
9678
+ if (Number.isFinite(value)) sample.maxConnections = value;
9679
+ }
9680
+ if (size.status === "fulfilled") {
9681
+ const value = Number(size.value.rows[0]?.bytes);
9682
+ if (Number.isFinite(value)) sample.sizeBytes = value;
9683
+ }
9684
+ if (lag.status === "fulfilled" && lag.value !== null) sample.replicaLagSeconds = lag.value / 1e3;
9685
+ return sample;
9686
+ }
9687
+ //#endregion
9390
9688
  //#region src/PostgresBackendDriver.ts
9391
9689
  /**
9392
9690
  * Has an operator opted out of database role switching entirely?
@@ -9701,6 +9999,24 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9701
9999
  */
9702
10000
  listenConnectionString;
9703
10001
  /**
10002
+ * A handle on this source's direct URL for the work that needs a session
10003
+ * of its own — the Studio SQL console's runs, cursors and cancels — set by
10004
+ * the bootstrapper when the pool reaches the database through a
10005
+ * transaction-mode pooler (`DATABASE_POOLED=true`). There, `SET ROLE` for a
10006
+ * session, a cursor held across reads and `pg_cancel_backend` of "this
10007
+ * run's backend" mean nothing: each transaction may land on another server
10008
+ * connection. Unset, the pool itself is direct and serves them.
10009
+ */
10010
+ sessionDb;
10011
+ /**
10012
+ * Where authenticated reads may go instead of the primary: this source's
10013
+ * read replica, with its lag guard and read-your-writes pins. Set by the
10014
+ * bootstrapper when `DATABASE_READ_URL` names another server. Read by
10015
+ * {@link AuthenticatedPostgresBackendDriver}; this driver's own reads stay
10016
+ * on the primary.
10017
+ */
10018
+ readRouter;
10019
+ /**
9704
10020
  * When true, realtime notifications are deferred until after the
9705
10021
  * wrapping transaction commits. Set by `withAuth` → `withTransaction`.
9706
10022
  */
@@ -9749,6 +10065,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9749
10065
  }),
9750
10066
  planSchemaReconcile: async (collections, options) => readReconcileFacts(this.schemaFactsQueryable(), collections, options),
9751
10067
  listen: (...args) => this.listen(...args),
10068
+ poolStats: () => this.poolStats(),
10069
+ sampleHealth: () => this.sampleHealth(),
9752
10070
  ...this.branchService ? {
9753
10071
  createBranch: this.branchService.createBranch.bind(this.branchService),
9754
10072
  deleteBranch: this.branchService.deleteBranch.bind(this.branchService),
@@ -9789,7 +10107,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9789
10107
  */
9790
10108
  async listen(channel, onNotify, options) {
9791
10109
  const pool = "$client" in this.db ? this.db.$client : void 0;
9792
- const connectionString = this.listenConnectionString || (pool instanceof Pool ? pool.options.connectionString : void 0);
10110
+ const connectionString = this.listenConnectionString || (pool instanceof Pool && !isPooledPool(pool) ? pool.options.connectionString : void 0);
9793
10111
  if (!connectionString) throw new Error("no database URL to hold a LISTEN connection on (set DATABASE_DIRECT_URL)");
9794
10112
  const listener = new PgNotifyListener({
9795
10113
  connectionString,
@@ -9835,6 +10153,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9835
10153
  return masked;
9836
10154
  },
9837
10155
  aggregate: async (collectionPath, options) => {
10156
+ this.assertAggregateUnmasked(collectionPath, options);
9838
10157
  return raw.aggregate(collectionPath, options);
9839
10158
  },
9840
10159
  cursorFor: (collectionPath, row, orderBy) => raw.cursorFor(collectionPath, row, orderBy)
@@ -9936,6 +10255,23 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9936
10255
  return !!(resolved.globalCallbacks?.afterRead || resolved.callbacks?.afterRead || resolved.propertyCallbacks?.afterRead);
9937
10256
  }
9938
10257
  /**
10258
+ * Refuse an aggregate that would read what `afterRead` hides.
10259
+ *
10260
+ * An aggregate reads the stored columns and never passes through the
10261
+ * callbacks, so on a collection whose rows one rewrites, `max(email)` or
10262
+ * `groupBy=salary` hands back the value the mask exists to withhold, one
10263
+ * bucket at a time. What a callback does to a row cannot be known from
10264
+ * here, so the rule is closed: on such a collection only `count()` with no
10265
+ * `groupBy` is served — the number `GET /count` already gives — and any
10266
+ * other aggregate is refused, whichever tier (global, collection or
10267
+ * property) the callback sits on.
10268
+ */
10269
+ assertAggregateUnmasked(path, options) {
10270
+ if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => aggregate.fn === "count" && !aggregate.field)) return;
10271
+ if (!PostgresBackendDriver.hasAfterRead(this.resolveCollectionCallbacks(void 0, path))) return;
10272
+ throw ApiError.badRequest(`Aggregates other than count are refused on a collection whose rows an afterRead callback rewrites ("${path}"): a sum, average, minimum, maximum, field count or group would read the stored values the callback hides. Use \`count()\` without \`groupBy\`, or read the rows.`, "AGGREGATE_MASKED_BY_AFTER_READ", { collection: path });
10273
+ }
10274
+ /**
9939
10275
  * Apply afterRead to REST/SDK read results.
9940
10276
  *
9941
10277
  * The REST / `include` path fetches rows through the raw fetch service, which
@@ -10997,6 +11333,35 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10997
11333
  return this.poolManager.getDrizzle(databaseName);
10998
11334
  }
10999
11335
  /**
11336
+ * {@link getTargetDb} for work that needs one session from start to end:
11337
+ * the app database is reached through {@link sessionDb} when there is one.
11338
+ * Other databases come from the pool manager, whose URL is already the
11339
+ * direct one (`DATABASE_DIRECT_URL` before `DATABASE_URL`).
11340
+ */
11341
+ async getSessionTargetDb(databaseName) {
11342
+ if (this.sessionDb && (!databaseName || databaseName === await this.appDatabaseName())) return this.sessionDb;
11343
+ return this.getTargetDb(databaseName);
11344
+ }
11345
+ /** `SQLAdmin.poolStats`: the pools this driver opened beside the server's. */
11346
+ poolStats() {
11347
+ const stats = [];
11348
+ const replica = this.readRouter && "$client" in this.readRouter.db ? this.readRouter.db.$client : void 0;
11349
+ if (replica instanceof Pool) stats.push(poolStatsOf(replica, "read"));
11350
+ const session = this.sessionDb && "$client" in this.sessionDb ? this.sessionDb.$client : void 0;
11351
+ if (session instanceof Pool) stats.push(poolStatsOf(session, "session"));
11352
+ return stats;
11353
+ }
11354
+ /**
11355
+ * `SQLAdmin.sampleHealth`: the server behind the pool, and the replica's
11356
+ * lag. Without a pg pool (PGlite) there is no server to sample.
11357
+ */
11358
+ async sampleHealth() {
11359
+ const pool = "$client" in this.db ? this.db.$client : void 0;
11360
+ if (!(pool instanceof Pool)) return {};
11361
+ const replica = this.readRouter && "$client" in this.readRouter.db ? this.readRouter.db.$client : void 0;
11362
+ return sampleDatabaseHealth(pool, replica instanceof Pool ? replica : void 0);
11363
+ }
11364
+ /**
11000
11365
  * Build one statement, binding `$n` placeholders as real parameters.
11001
11366
  *
11002
11367
  * Shared by the role-switched path (inside a transaction) and the
@@ -11013,7 +11378,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11013
11378
  return sql.join(chunks, sql.raw(""));
11014
11379
  }
11015
11380
  async executeSql(sqlText, options) {
11016
- if (options?.isolateSession) return this.onIsolatedSession(await this.getTargetDb(options.database), options.role, (db, role) => this.executeSqlOn(db, sqlText, {
11381
+ if (options?.isolateSession) return this.onIsolatedSession(await this.getSessionTargetDb(options.database), options.role, (db, role) => this.executeSqlOn(db, sqlText, {
11017
11382
  ...options,
11018
11383
  role
11019
11384
  }), options.maxResultBytes);
@@ -11036,7 +11401,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11036
11401
  ...pool.options,
11037
11402
  connectionTimeoutMillis: timeoutMs,
11038
11403
  query_timeout: timeoutMs,
11039
- statement_timeout: timeoutMs
11404
+ ...isPooledPool(pool) ? {} : { statement_timeout: timeoutMs }
11040
11405
  });
11041
11406
  client.on("error", () => {});
11042
11407
  try {
@@ -11051,7 +11416,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11051
11416
  * result. See `SQLAdmin.runSqlScript` and `services/sql-script.ts`.
11052
11417
  */
11053
11418
  async runSqlScript(sqlText, options) {
11054
- const targetDb = await this.getTargetDb(options?.database);
11419
+ const targetDb = await this.getSessionTargetDb(options?.database);
11055
11420
  const pool = "$client" in targetDb ? targetDb.$client : void 0;
11056
11421
  if (!(pool instanceof Pool)) return sqlScriptResultFromRows(await this.executeSql(sqlText, {
11057
11422
  database: options?.database,
@@ -11071,7 +11436,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11071
11436
  * role it may not take) is the caller's to read, as on the socket.
11072
11437
  */
11073
11438
  async openSqlCursor(sqlText, options) {
11074
- const targetDb = await this.getTargetDb(options?.database);
11439
+ const targetDb = await this.getSessionTargetDb(options?.database);
11075
11440
  const pool = "$client" in targetDb ? targetDb.$client : void 0;
11076
11441
  if (!(pool instanceof Pool)) throw new ApiError(501, "SQL_EXPORT_UNSUPPORTED", "Downloading a whole result reads it through a cursor on a connection of its own, and the in-process development database has one connection. Point DATABASE_URL at a Postgres of your own (`rebase dev --docker` starts one), or add a LIMIT and export the rows on screen.");
11077
11442
  const role = options?.role;
@@ -11353,6 +11718,11 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11353
11718
  return new AuthenticatedPostgresBackendDriver(this, user);
11354
11719
  }
11355
11720
  };
11721
+ /**
11722
+ * The uid `dataAsAdmin`, crons and jobs act as (`SERVICE_IDENTITY` in
11723
+ * `@rebasepro/server`). Its reads stay on the primary.
11724
+ */
11725
+ var SERVICE_PRINCIPAL = "service";
11356
11726
  var AuthenticatedPostgresBackendDriver = class {
11357
11727
  delegate;
11358
11728
  key = "postgres";
@@ -11410,7 +11780,62 @@ var AuthenticatedPostgresBackendDriver = class {
11410
11780
  isolationLevel: "repeatable read"
11411
11781
  });
11412
11782
  }
11783
+ /**
11784
+ * Run `operation` in a transaction as this caller — on the read replica
11785
+ * when this is a read the replica may serve (see {@link replicaFor}), else
11786
+ * on the primary.
11787
+ *
11788
+ * A read the replica fails for the replica's own reasons (it is down,
11789
+ * full, or cancelled the read to replay WAL — see
11790
+ * `isReplicaFallbackError`) runs again on the primary; anything else it
11791
+ * answered is the answer. A write pins this caller to the primary for
11792
+ * `REBASE_READ_STICKY_MS`, from when it starts until that long after it
11793
+ * ends, so the caller's next list shows what it just saved.
11794
+ */
11413
11795
  async withTransaction(operation, options) {
11796
+ const router = this.delegate.readRouter;
11797
+ const principal = this.user?.uid;
11798
+ if (options?.accessMode !== "read only") {
11799
+ if (!router || !principal) return this.runTransaction(this.delegate.db, operation, options);
11800
+ router.notePrimaryWrite(principal);
11801
+ try {
11802
+ return await this.runTransaction(this.delegate.db, operation, options);
11803
+ } finally {
11804
+ router.notePrimaryWrite(principal);
11805
+ }
11806
+ }
11807
+ const replica = this.replicaFor();
11808
+ if (replica) try {
11809
+ return await this.runTransaction(replica, operation, options);
11810
+ } catch (error) {
11811
+ if (!isReplicaFallbackError(error)) throw error;
11812
+ router?.noteReplicaFailure(error);
11813
+ }
11814
+ return this.runTransaction(this.delegate.db, operation, options);
11815
+ }
11816
+ /**
11817
+ * The replica's handle for a read by this caller, or `undefined` for the
11818
+ * primary: there is no replica, the read is inside a write's transaction
11819
+ * (it must see what that write has not committed), the caller is the
11820
+ * service identity (crons, jobs, `dataAsAdmin` — server work that reads
11821
+ * what it acts on), or the router says the replica is behind, failing, or
11822
+ * this caller just wrote.
11823
+ */
11824
+ replicaFor() {
11825
+ const router = this.delegate.readRouter;
11826
+ if (!router) return void 0;
11827
+ if (currentWriteScope()) return void 0;
11828
+ const principal = this.user?.uid;
11829
+ if (principal === SERVICE_PRINCIPAL) return void 0;
11830
+ const route = router.route(principal);
11831
+ if (route.target === "primary") {
11832
+ logger.debug(`[DataDriver] read served by the primary (${route.reason})`);
11833
+ return;
11834
+ }
11835
+ return router.db;
11836
+ }
11837
+ async runTransaction(db, operation, options) {
11838
+ const transactionSettings = transactionSettingsStatements(pooledTransactionSettings("$client" in db ? db.$client : void 0));
11414
11839
  const pendingNotifications = [];
11415
11840
  const writeScope = options?.accessMode === "read only" ? void 0 : new WriteTransactionScope();
11416
11841
  const client = this.delegate.client;
@@ -11424,7 +11849,8 @@ var AuthenticatedPostgresBackendDriver = class {
11424
11849
  },
11425
11850
  storageSource: client?.storage
11426
11851
  });
11427
- const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => this.delegate.db.transaction(async (tx) => {
11852
+ const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => db.transaction(async (tx) => {
11853
+ if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
11428
11854
  if (!this.user?.uid) logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
11429
11855
  if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
11430
11856
  await applyAuthContext(tx, authContextOf(this.user), this.delegate.rlsUserRole);
@@ -12049,7 +12475,7 @@ var MAX_NOTIFY_BYTES = 7900;
12049
12475
  * notification.
12050
12476
  */
12051
12477
  var CHUNK_SLACK_BYTES = 64;
12052
- var quoteIdent$1 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
12478
+ var quoteIdent$2 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
12053
12479
  var quoteLiteral$1 = (value) => `'${value.replace(/'/g, "''")}'`;
12054
12480
  /**
12055
12481
  * The row-level function: `{ schema, table, op, row }`, one per changed row.
@@ -12319,8 +12745,8 @@ $rebase_cdc$;
12319
12745
  * function serves every table. Empty means "the primary key".
12320
12746
  */
12321
12747
  function buildCdcTriggerSql(schema, table, identityColumns = [], level = "statement") {
12322
- const qualified = `${quoteIdent$1(schema)}.${quoteIdent$1(table)}`;
12323
- return ALL_TRIGGER_NAMES.map((name) => `DROP TRIGGER IF EXISTS ${quoteIdent$1(name)} ON ${qualified};\n`).join("") + buildCdcTriggerCreateSql(schema, table, identityColumns, level);
12748
+ const qualified = `${quoteIdent$2(schema)}.${quoteIdent$2(table)}`;
12749
+ return ALL_TRIGGER_NAMES.map((name) => `DROP TRIGGER IF EXISTS ${quoteIdent$2(name)} ON ${qualified};\n`).join("") + buildCdcTriggerCreateSql(schema, table, identityColumns, level);
12324
12750
  }
12325
12751
  /**
12326
12752
  * `CREATE TRIGGER` alone, for a table that has no capture trigger yet.
@@ -12330,9 +12756,9 @@ function buildCdcTriggerSql(schema, table, identityColumns = [], level = "statem
12330
12756
  * `CREATE TRIGGER` takes SHARE ROW EXCLUSIVE, which readers never wait for.
12331
12757
  */
12332
12758
  var buildCdcTriggerCreateSql = (schema, table, identityColumns, level) => {
12333
- const qualified = `${quoteIdent$1(schema)}.${quoteIdent$1(table)}`;
12759
+ const qualified = `${quoteIdent$2(schema)}.${quoteIdent$2(table)}`;
12334
12760
  const args = [...new Set(identityColumns)].map(quoteLiteral$1).join(", ");
12335
- return triggersFor(level).map((spec) => `CREATE TRIGGER ${quoteIdent$1(spec.name)} ${spec.timing} ON ${qualified} ${spec.forEach} EXECUTE FUNCTION ${spec.fn === "statement" ? CDC_STATEMENT_FUNCTION : CDC_TRIGGER_FUNCTION}(${args});`).join("\n");
12761
+ return triggersFor(level).map((spec) => `CREATE TRIGGER ${quoteIdent$2(spec.name)} ${spec.timing} ON ${qualified} ${spec.forEach} EXECUTE FUNCTION ${spec.fn === "statement" ? CDC_STATEMENT_FUNCTION : CDC_TRIGGER_FUNCTION}(${args});`).join("\n");
12336
12762
  };
12337
12763
  /** `to_regprocedure` of each function, as a SQL expression. */
12338
12764
  var ROW_FUNCTION_OID = `to_regprocedure(${quoteLiteral$1(`${CDC_TRIGGER_FUNCTION}()`)})`;
@@ -12454,7 +12880,7 @@ async function settleInstalledCapture(run, options) {
12454
12880
  */
12455
12881
  async function resolveIdentityColumns(run, ref) {
12456
12882
  const requested = ref.identityColumns ?? [];
12457
- const qualified = `${quoteIdent$1(ref.schema)}.${quoteIdent$1(ref.table)}`;
12883
+ const qualified = `${quoteIdent$2(ref.schema)}.${quoteIdent$2(ref.table)}`;
12458
12884
  let columns;
12459
12885
  let relkind = null;
12460
12886
  try {
@@ -12498,7 +12924,7 @@ var decodeTriggerArgs = (hex) => {
12498
12924
  * 4.4 s while a report read the table.
12499
12925
  */
12500
12926
  async function readCaptureState(run, refs) {
12501
- const rows = await run(`WITH target(key, rel) AS (VALUES ${refs.map((ref) => `(${quoteLiteral$1(`${ref.schema}.${ref.table}`)}, to_regclass(${quoteLiteral$1(`${quoteIdent$1(ref.schema)}.${quoteIdent$1(ref.table)}`)}))`).join(", ")})
12927
+ const rows = await run(`WITH target(key, rel) AS (VALUES ${refs.map((ref) => `(${quoteLiteral$1(`${ref.schema}.${ref.table}`)}, to_regclass(${quoteLiteral$1(`${quoteIdent$2(ref.schema)}.${quoteIdent$2(ref.table)}`)}))`).join(", ")})
12502
12928
  SELECT t.key,
12503
12929
  (SELECT c.relkind::text FROM pg_class c WHERE c.oid = t.rel) AS relkind,
12504
12930
  (SELECT coalesce(json_agg(json_build_object('name', a.attname,
@@ -13546,7 +13972,7 @@ var WalCdcListener = class {
13546
13972
  */
13547
13973
  /** The publication WAL capture streams. A plain identifier: it is interpolated into replication commands. */
13548
13974
  var CDC_PUBLICATION = "rebase_cdc";
13549
- var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
13975
+ var quoteIdent$1 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
13550
13976
  var quoteLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
13551
13977
  /** SQLSTATE 42710: the publication, or the table's membership of it, already exists — another instance got there first. */
13552
13978
  function isDuplicateObject(err) {
@@ -13570,7 +13996,7 @@ async function walCaptureBlocker(run) {
13570
13996
  async function readTableStates(run, tables) {
13571
13997
  const states = /* @__PURE__ */ new Map();
13572
13998
  if (tables.length === 0) return states;
13573
- const names = tables.map((t) => quoteLiteral(`${quoteIdent(t.schema)}.${quoteIdent(t.table)}`)).join(", ");
13999
+ const names = tables.map((t) => quoteLiteral(`${quoteIdent$1(t.schema)}.${quoteIdent$1(t.table)}`)).join(", ");
13574
14000
  const rows = await run(`SELECT n.name, c.oid IS NOT NULL AS exists, c.relkind::text AS relkind, c.relreplident::text AS replica_identity, EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary) AS has_pk, EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisreplident) AS has_identity_index, EXISTS (SELECT 1 FROM pg_publication_rel r JOIN pg_publication p ON p.oid = r.prpubid WHERE r.prrelid = c.oid AND p.pubname = ${quoteLiteral(CDC_PUBLICATION)}) AS published FROM unnest(ARRAY[${names}]::text[]) AS n(name) LEFT JOIN pg_class c ON c.oid = to_regclass(n.name)`);
13575
14001
  for (const row of rows) states.set(String(row.name), {
13576
14002
  exists: row.exists === true,
@@ -13612,13 +14038,13 @@ async function provisionWalPublication(run, tables) {
13612
14038
  if ((await run(`SELECT 1 FROM pg_publication WHERE pubname = ${quoteLiteral("rebase_cdc")}`)).length === 0) {
13613
14039
  const options = "publish = 'insert, update, delete, truncate'" + (version >= 13e4 ? ", publish_via_partition_root = true" : "");
13614
14040
  try {
13615
- await run(`CREATE PUBLICATION ${quoteIdent(CDC_PUBLICATION)} WITH (${options})`);
14041
+ await run(`CREATE PUBLICATION ${quoteIdent$1(CDC_PUBLICATION)} WITH (${options})`);
13616
14042
  } catch (err) {
13617
14043
  if (!isDuplicateObject(err)) throw err;
13618
14044
  }
13619
14045
  }
13620
14046
  const byTable = /* @__PURE__ */ new Map();
13621
- for (const ref of tables) byTable.set(`${quoteIdent(ref.schema)}.${quoteIdent(ref.table)}`, ref);
14047
+ for (const ref of tables) byTable.set(`${quoteIdent$1(ref.schema)}.${quoteIdent$1(ref.table)}`, ref);
13622
14048
  const states = await readTableStates(run, [...byTable.values()]);
13623
14049
  const published = [];
13624
14050
  const skipped = [];
@@ -13637,7 +14063,7 @@ async function provisionWalPublication(run, tables) {
13637
14063
  continue;
13638
14064
  }
13639
14065
  try {
13640
- await withLockBudget(run, `ALTER PUBLICATION ${quoteIdent(CDC_PUBLICATION)} ADD TABLE ${qualified}`);
14066
+ await withLockBudget(run, `ALTER PUBLICATION ${quoteIdent$1(CDC_PUBLICATION)} ADD TABLE ${qualified}`);
13641
14067
  published.push(ref);
13642
14068
  } catch (err) {
13643
14069
  if (isDuplicateObject(err)) published.push(ref);
@@ -20433,6 +20859,79 @@ function patchPgNumericToNumber(tables) {
20433
20859
  if (patchedCount > 0) logger.debug(`[PgNumeric] ${patchedCount} numeric column(s) will be served as numbers`);
20434
20860
  }
20435
20861
  //#endregion
20862
+ //#region src/pooled-database.ts
20863
+ /**
20864
+ * Running behind a transaction-mode pooler (PgBouncer, `DATABASE_POOLED=true`).
20865
+ *
20866
+ * The pool sends no session settings at connect behind one — the pooler would
20867
+ * refuse or drop them — and a transaction sets its own (`SET LOCAL`, see
20868
+ * `pooledTransactionSettings`). What that leaves is a statement outside any
20869
+ * transaction: it runs with the role's defaults, and the default
20870
+ * `search_path` is `"$user", public`. This framework's role is usually called
20871
+ * `rebase`, and so is its schema, so an unqualified table resolves to
20872
+ * `rebase.<name>` before `public.<name>` — the hazard `pinSearchPath` exists
20873
+ * for, which a pooled pool cannot pin.
20874
+ *
20875
+ * So the boot gives the role a default `search_path` of `public` in this
20876
+ * database, the same value every direct connection of this framework already
20877
+ * pins, over the direct URL. It applies to server connections the pooler opens
20878
+ * from then on.
20879
+ *
20880
+ * @module
20881
+ */
20882
+ function quoteIdent(name) {
20883
+ return `"${name.replace(/"/g, "\"\"")}"`;
20884
+ }
20885
+ /** The statement that gives `role` a default `search_path` in `database`. */
20886
+ function roleSearchPathStatement(role, database, searchPath) {
20887
+ return `ALTER ROLE ${quoteIdent(role)} IN DATABASE ${quoteIdent(database)} SET search_path TO ${searchPathList(searchPath)}`;
20888
+ }
20889
+ /** Whether a reported `search_path` already is `wanted`, spelling aside. */
20890
+ function searchPathMatches(reported, wanted) {
20891
+ const normalise = (value) => value.split(",").map((part) => part.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean).join(",");
20892
+ return normalise(reported) === normalise(wanted);
20893
+ }
20894
+ /**
20895
+ * Make the role the pooled pool connects as default to `searchPath` in its
20896
+ * database, when it does not already. Asked through the pool (what the pooler
20897
+ * hands out is what matters), changed through `directUrl`.
20898
+ *
20899
+ * With `provision: false` — a boot that runs no DDL — nothing is changed and
20900
+ * the statement to run is logged. A role that may not change its own
20901
+ * defaults is logged the same way; neither stops the boot, because every
20902
+ * transaction still sets the path for itself.
20903
+ */
20904
+ async function ensurePooledRoleDefaults(pool, directUrl, options) {
20905
+ const wanted = options.searchPath ?? "public";
20906
+ let facts;
20907
+ try {
20908
+ facts = (await pool.query("SELECT current_setting('search_path') AS search_path, current_user AS role, current_database() AS database")).rows[0];
20909
+ } catch (error) {
20910
+ logger.warn("[pooler] Could not read the search_path the pooler hands out", { error: error instanceof Error ? error.message : String(error) });
20911
+ return;
20912
+ }
20913
+ if (!facts || searchPathMatches(facts.search_path, wanted)) return;
20914
+ const statement = roleSearchPathStatement(facts.role, facts.database, wanted);
20915
+ if (!options.provision) {
20916
+ logger.warn(`⚠️ [pooler] Statements outside a transaction resolve unqualified tables with search_path "${facts.search_path}", not "${wanted}", and this process runs no DDL at boot. Run once:\n ${statement};`);
20917
+ return;
20918
+ }
20919
+ const client = new Client({
20920
+ connectionString: directUrl,
20921
+ connectionTimeoutMillis: 1e4
20922
+ });
20923
+ client.on("error", () => void 0);
20924
+ try {
20925
+ await client.connect();
20926
+ await client.query(statement);
20927
+ logger.info(`[pooler] Set the default search_path of role "${facts.role}" in "${facts.database}" to ${wanted} (was ` + JSON.stringify(facts.search_path) + "), for statements outside a transaction.");
20928
+ } catch (error) {
20929
+ logger.warn(`⚠️ [pooler] Could not set the default search_path of role "${facts.role}": ${error instanceof Error ? error.message : String(error)}. Run once as a role that may:\n ${statement};`);
20930
+ } finally {
20931
+ await client.end().catch(() => void 0);
20932
+ }
20933
+ }
20934
+ //#endregion
20436
20935
  //#region src/PostgresBootstrapper.ts
20437
20936
  /**
20438
20937
  * PostgresBootstrapper
@@ -20528,10 +21027,18 @@ function resolveSourceUrls(pgConfig, sourceKey, env = process.env) {
20528
21027
  const isDefault = sourceKey === DEFAULT_DATA_SOURCE_KEY;
20529
21028
  return {
20530
21029
  readUrl: pgConfig.readConnectionString || (isDefault ? env.DATABASE_READ_URL : void 0) || void 0,
20531
- directUrl: pgConfig.directConnectionString || (isDefault ? env.DATABASE_DIRECT_URL : void 0) || pgConfig.connectionString || void 0
21030
+ directUrl: pgConfig.directConnectionString || (isDefault ? env.DATABASE_DIRECT_URL : void 0) || (pgConfig.pooled ? void 0 : pgConfig.connectionString) || void 0
20532
21031
  };
20533
21032
  }
20534
21033
  /**
21034
+ * The refusal for a pooled source with no direct URL — named so the
21035
+ * control plane's log line and the self-hoster's both say what to set.
21036
+ */
21037
+ function pooledWithoutDirectUrlError(sourceKey) {
21038
+ const suffix = resourceEnvSuffix(sourceKey);
21039
+ return /* @__PURE__ */ new Error(`DATABASE_POOLED${suffix}=true says DATABASE_URL${suffix} goes through a transaction-mode pooler, but DATABASE_DIRECT_URL${suffix} is not set. Realtime, the job queue's wake-up, index builds and the SQL console need a connection that keeps its session, which a transaction-mode pooler does not give. Set DATABASE_DIRECT_URL${suffix} to the database itself (not the pooler), or unset DATABASE_POOLED${suffix}.`);
21040
+ }
21041
+ /**
20535
21042
  * Is this the local database `rebase init` scaffolds — i.e. the one case where
20536
21043
  * "you are connected as a superuser" is not news?
20537
21044
  *
@@ -20726,10 +21233,14 @@ function postgresDriverConfigFromEnv(config, env = process.env, sourceKey = DEFA
20726
21233
  const isDefaultSource = sourceKey === DEFAULT_DATA_SOURCE_KEY;
20727
21234
  const readConnectionString = config.readConnectionString || (isDefaultSource ? read("DATABASE_READ_URL") : void 0);
20728
21235
  const directConnectionString = config.directConnectionString || (isDefaultSource ? read("DATABASE_DIRECT_URL") : void 0);
21236
+ const pooled = config.pooled ?? (isDefaultSource ? read("DATABASE_POOLED")?.toLowerCase() === "true" : void 0);
21237
+ const readRouting = config.readRouting ?? (read("REBASE_READ_STICKY_MS") || read("REBASE_READ_MAX_LAG_MS") ? readRoutingOptionsFromEnv(env) : void 0);
20729
21238
  return {
20730
21239
  ...config,
20731
21240
  ...readConnectionString ? { readConnectionString } : {},
20732
21241
  ...directConnectionString ? { directConnectionString } : {},
21242
+ ...pooled ? { pooled } : {},
21243
+ ...readRouting ? { readRouting } : {},
20733
21244
  realtime
20734
21245
  };
20735
21246
  }
@@ -20856,18 +21367,56 @@ async function openPostgresDriver(pgConfig, config) {
20856
21367
  realtimeService.recountIntervalMs = tuning(pgConfig.realtime?.recountIntervalMs, "realtime.recountIntervalMs", "milliseconds");
20857
21368
  const recountMinRows = tuning(pgConfig.realtime?.recountMinRows, "realtime.recountMinRows", "rows");
20858
21369
  if (recountMinRows !== void 0) realtimeService.recountMinRows = recountMinRows;
20859
- const { readUrl, directUrl } = resolveSourceUrls(pgConfig, sourceKey, {});
21370
+ const pooled = pgConfig.pooled === true || isPooledPool(rawClient);
21371
+ const { readUrl, directUrl } = resolveSourceUrls({
21372
+ ...pgConfig,
21373
+ pooled
21374
+ }, sourceKey, {});
21375
+ if (pooled && !directUrl) throw pooledWithoutDirectUrlError(sourceKey);
21376
+ const primaryUrl = pgConfig.connectionString || (rawClient && typeof rawClient === "object" && "options" in rawClient ? rawClient.options.connectionString : void 0);
20860
21377
  let readDb;
20861
- if (readUrl && readUrl !== pgConfig.connectionString) try {
20862
- const { createReadReplicaConnection } = await import("./connection-czvI7TZL.js").then((n) => n.n);
20863
- readDb = createReadReplicaConnection(readUrl, mergedSchema).db;
20864
- logger.info("📖 [PostgresBootstrapper] Read replica connection established");
21378
+ let readRouter;
21379
+ let readPool;
21380
+ if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
21381
+ const { createReadReplicaConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
21382
+ const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
21383
+ ...pgConfig.poolConfig,
21384
+ pooled
21385
+ });
21386
+ readDb = readResources.db;
21387
+ readPool = readResources.pool;
21388
+ readRouter = new ReadRouter(readDb, () => readReplicaLagMs(readResources.pool), pgConfig.readRouting ?? readRoutingOptionsFromEnv({}));
21389
+ readRouter.start();
21390
+ logger.info(`📖 [PostgresBootstrapper] Authenticated reads may use the read replica (read-your-writes ${readRouter.stickyMs} ms, lag limit ${readRouter.maxLagMs} ms)`);
20865
21391
  } catch (err) {
20866
21392
  logger.warn("⚠️ Could not connect to read replica, falling back to primary for all queries", { error: err });
20867
21393
  }
20868
- const poolManager = pgConfig.adminConnectionString ? new DatabasePoolManager(pgConfig.adminConnectionString) : void 0;
21394
+ let sessionDb;
21395
+ let sessionPool;
21396
+ if (pooled && directUrl) {
21397
+ const { createDirectDatabaseConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
21398
+ const session = createDirectDatabaseConnection(directUrl, void 0, {
21399
+ max: 3,
21400
+ idleTimeoutMillis: 1e4
21401
+ });
21402
+ sessionDb = session.db;
21403
+ sessionPool = session.pool;
21404
+ }
21405
+ const adminUrl = pooled && directUrl && pgConfig.adminConnectionString && primaryUrl && sameDatabaseTarget(pgConfig.adminConnectionString, primaryUrl) ? directUrl : pgConfig.adminConnectionString;
21406
+ const poolManager = adminUrl ? new DatabasePoolManager(adminUrl) : void 0;
21407
+ closeWithPool(rawClient, async () => {
21408
+ readRouter?.stop();
21409
+ await Promise.allSettled([
21410
+ readPool?.end(),
21411
+ sessionPool?.end(),
21412
+ poolManager?.shutdown()
21413
+ ]);
21414
+ });
20869
21415
  const driver = new PostgresBackendDriver(schemaAwareDb, realtimeService, registry, void 0, poolManager);
20870
21416
  driver.listenConnectionString = directUrl;
21417
+ driver.sessionDb = sessionDb;
21418
+ driver.readRouter = readRouter;
21419
+ if (pooled && directUrl) await ensurePooledRoleDefaults(rawClient, directUrl, { provision });
20871
21420
  realtimeService.setDataDriver(driver);
20872
21421
  let rlsEnforcement;
20873
21422
  let exposedInternalTables;
@@ -21172,7 +21721,12 @@ function createPostgresBootstrapper(pgConfig) {
21172
21721
  const openIndexBuildSession = (driverResult) => async () => {
21173
21722
  const db = requireProvisioningDb(driverResult);
21174
21723
  const pool = "$client" in db ? db.$client : void 0;
21175
- const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BcJ_oulu.js").then((n) => n.r);
21724
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
21725
+ const config = effectiveConfig();
21726
+ if (isPooledPool(pool) || config.pooled) {
21727
+ if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
21728
+ return clientIndexBuildSession(config.directConnectionString)();
21729
+ }
21176
21730
  if (isPgPool(pool)) return poolIndexBuildSession(pool)();
21177
21731
  const queryable = provisioningQueryable(driverResult);
21178
21732
  return {
@@ -21315,7 +21869,7 @@ function createPostgresBootstrapper(pgConfig) {
21315
21869
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21316
21870
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21317
21871
  if (historyIndexes.length > 0) {
21318
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BcJ_oulu.js").then((n) => n.r);
21872
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
21319
21873
  const indexOptions = {
21320
21874
  log: (message) => logger.info(`[history] ${message}`),
21321
21875
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -21371,7 +21925,7 @@ function createPostgresBootstrapper(pgConfig) {
21371
21925
  * proved it can bootstrap with.
21372
21926
  */
21373
21927
  async ensureCollectionSchema(collections, driverResult, log) {
21374
- const { ensureCollectionTables } = await import("./ensure-collection-tables-CSbgkTBx.js").then((n) => n.n);
21928
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-DvaCEy6X.js").then((n) => n.n);
21375
21929
  const queryable = provisioningQueryable(driverResult);
21376
21930
  const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CIGoIGcC.js").then((n) => n.i);
21377
21931
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
@@ -21385,7 +21939,7 @@ function createPostgresBootstrapper(pgConfig) {
21385
21939
  pendingIndexBuild?.cancel();
21386
21940
  pendingIndexBuild = void 0;
21387
21941
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
21388
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BcJ_oulu.js").then((n) => n.r);
21942
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
21389
21943
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
21390
21944
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
21391
21945
  log: (message) => logger.info(`[schema] ${message}`),
@@ -21425,7 +21979,7 @@ function createPostgresBootstrapper(pgConfig) {
21425
21979
  await provisionRlsRuntime(driverResult);
21426
21980
  },
21427
21981
  async ensureCollectionPolicies(collections, driverResult, log) {
21428
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-BNwSQfVx.js");
21982
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-f0LIwiwp.js");
21429
21983
  const queryable = provisioningQueryable(driverResult);
21430
21984
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
21431
21985
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -21541,7 +22095,7 @@ function createPostgresBootstrapper(pgConfig) {
21541
22095
  return driverResult.internals.driver.admin;
21542
22096
  },
21543
22097
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
21544
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-D4wrzF3b.js").then((n) => n.c);
22098
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-CCJnghvG.js").then((n) => n.c);
21545
22099
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
21546
22100
  const realtimeConfig = effectiveConfig().realtime;
21547
22101
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -21686,4 +22240,4 @@ async function openRebase(options) {
21686
22240
  //#endregion
21687
22241
  export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
21688
22242
 
21689
- //# sourceMappingURL=open-rebase-D9n8idex.js.map
22243
+ //# sourceMappingURL=open-rebase-DvmKIu7q.js.map