@rebasepro/server-postgres 0.28.1 → 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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-CcYqncW5.js","names":[],"sources":["../src/pool-disconnects.ts","../src/connection.ts"],"sourcesContent":["/**\n * What a pool says when the server ends its idle connections.\n *\n * `pg_terminate_backend` ends every connection to a database at once, and an\n * idle pool client hears it as an `error` event: one per connection, from\n * every pool the process holds. `rebase db branch create --force` does exactly\n * that to the database it copies, so fifteen forced creates beside a running\n * `rebase dev` printed 220 `❌ [ERROR] [pg-pool] Unexpected pool error\n * {\"detail\":\"terminating connection due to administrator command\"}` lines. It\n * read as an outage, and nothing was wrong: the pool opens new connections on\n * the next query. A database restart looks the same.\n */\nimport { logger } from \"@rebasepro/server\";\n\n/** SQLSTATEs of a connection the server ended: admin_shutdown, crash_shutdown, cannot_connect_now. */\nconst SERVER_ENDED_CODES = new Set([\"57P01\", \"57P02\", \"57P03\"]);\n\n/** Did the server end this connection, rather than something go wrong with it? */\nexport function serverEndedConnection(err: Error): boolean {\n const code = \"code\" in err ? err.code : undefined;\n return (typeof code === \"string\" && SERVER_ENDED_CODES.has(code))\n || /terminating connection due to administrator command/i.test(err.message);\n}\n\n/** How long one line stands for every server-ended connection after it, across all pools. */\nexport const DISCONNECT_BURST_MS = 10_000;\n\n/** When the current burst's line stops covering further disconnects. */\nlet burstUntil = 0;\n\n/** The logger methods a pool's error listener writes through. */\nexport type PoolErrorLog = Pick<typeof logger, \"warn\" | \"error\" | \"debug\">;\n\n/**\n * Say a pool's `error` event: a connection the server ended is one WARN line\n * per burst for the whole process, and the rest of the burst is at debug;\n * anything else is the ERROR it always was.\n *\n * The window is fixed from the first disconnect, not extended by each, so a\n * second burst ten seconds later is said again.\n */\nexport function reportPoolError(label: string, err: Error, log: PoolErrorLog = logger, now: () => number = Date.now): void {\n if (!serverEndedConnection(err)) {\n log.error(`[${label}] Unexpected pool error`, { detail: err.message });\n return;\n }\n const at = now();\n if (at < burstUntil) {\n log.debug(`[${label}] The database ended another idle connection`, { detail: err.message });\n return;\n }\n burstUntil = at + DISCONNECT_BURST_MS;\n const code = \"code\" in err && typeof err.code === \"string\" ? `, ${err.code}` : \"\";\n log.warn(\n `[${label}] The database ended this server's idle connections (${err.message}${code}). ` +\n \"New ones open on the next query. A database restart does this, and so does \" +\n \"`rebase db branch create --force`, which closes the database it copies.\"\n );\n}\n","import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\nimport { reportPoolError } from \"./pool-disconnects\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n /**\n * `search_path` pinned on every connection (default: `\"public\"`).\n *\n * Pass `false` to send no `search_path` at all and inherit whatever the\n * server/role defaults to. See {@link pinSearchPath} for why the default\n * is not \"inherit\".\n */\n searchPath?: string | false;\n /**\n * The URL reaches the database through a transaction-mode pooler such as\n * PgBouncer (`DATABASE_POOLED=true`).\n *\n * A transaction-mode pooler hands each transaction whatever server\n * connection is free, so nothing set for a *session* survives to the next\n * statement — and the startup packet's parameters are either refused by\n * the pooler or dropped by it (`ignore_startup_parameters`). So a pooled\n * pool sends neither `statement_timeout` nor `options=-c search_path` at\n * connect; {@link pooledTransactionSettings} says what to `SET LOCAL` at\n * the start of each transaction instead, and the boot sets the role's\n * default `search_path` (see `ensurePooledRoleDefaults`).\n *\n * Explicit rather than sniffed from the URL: a pooler's address looks like\n * any other database's.\n */\n pooled?: boolean;\n}\n\n/**\n * Ceiling on pool size, from the environment.\n *\n * Exists for the managed development database. PGlite is a single session\n * behind a multiplexing socket server, and two pooled clients holding\n * overlapping transactions deadlock there — which a request-per-transaction\n * server produces the moment two requests overlap. One connection turns that\n * deadlock into ordinary queueing.\n *\n * A ceiling rather than a value, so it constrains every pool in the process\n * without any of them having to know why. Ignored when unset or unparseable,\n * because a malformed limit must not silently serialize a production server.\n */\nexport function poolMaxCeiling(env: NodeJS.ProcessEnv = process.env): number | null {\n const raw = env.REBASE_DB_POOL_MAX;\n if (typeof raw !== \"string\") return null;\n\n // Plain decimal digits only. `Number` would also accept `1e3`, `0x10` and\n // ` 4 ` — none of which anyone writes on purpose in a config value, and all\n // of which would mean this silently did something other than it appears to.\n if (!/^[0-9]+$/.test(raw.trim())) return null;\n\n const parsed = Number(raw.trim());\n\n return parsed >= 1 ? parsed : null;\n}\n\n/** Apply {@link poolMaxCeiling} to a requested pool size. */\nexport function cappedPoolMax(requested: number, env: NodeJS.ProcessEnv = process.env): number {\n const ceiling = poolMaxCeiling(env);\n\n return ceiling === null ? requested : Math.min(requested, ceiling);\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n searchPath: \"public\",\n pooled: false,\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/**\n * The time limits every pool to this server shares: how long to wait for a\n * connection (then 503), the server-side statement timeout, the client-side\n * read backstop above it, and TCP keep-alive. Exported for the per-database\n * pools (`DatabasePoolManager`), which had none of them — pg's default\n * `connectionTimeoutMillis` is 0, wait forever.\n */\nexport function defaultPoolTimeouts(): Pick<PoolConfig,\n \"connectionTimeoutMillis\" | \"query_timeout\" | \"statement_timeout\" | \"keepAlive\" | \"keepAliveInitialDelayMillis\"> {\n return {\n connectionTimeoutMillis: DEFAULT_POOL.connectionTimeoutMillis,\n query_timeout: DEFAULT_POOL.queryTimeout,\n statement_timeout: DEFAULT_POOL.statementTimeout,\n keepAlive: DEFAULT_POOL.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * What a pool behind a transaction-mode pooler would have sent at connect, and\n * must instead set inside each transaction. See {@link PostgresPoolConfig.pooled}.\n */\nexport interface PooledTransactionSettings {\n /** `false` when the pool was told to inherit the server's `search_path`. */\n searchPath: string | false;\n statementTimeoutMs: number;\n}\n\nconst pooledPools = new WeakMap<object, PooledTransactionSettings>();\n\n/**\n * The settings a transaction on `pool` must `SET LOCAL` for itself, or\n * `undefined` when the pool talks to the database directly and sent them at\n * connect.\n */\nexport function pooledTransactionSettings(pool: unknown): PooledTransactionSettings | undefined {\n return pool !== null && typeof pool === \"object\" ? pooledPools.get(pool) : undefined;\n}\n\n/** Whether `pool` reaches its database through a transaction-mode pooler. */\nexport function isPooledPool(pool: unknown): boolean {\n return pooledTransactionSettings(pool) !== undefined;\n}\n\n/**\n * The `SET LOCAL` statements that give a transaction on a pooled connection\n * what a direct connection got from its startup packet. Empty for a direct\n * pool. `SET LOCAL` ends with the transaction, so nothing reaches the next\n * client the pooler hands that server connection to.\n */\nexport function transactionSettingsStatements(settings: PooledTransactionSettings | undefined): string[] {\n if (!settings) return [];\n const statements: string[] = [];\n if (settings.searchPath !== false) {\n statements.push(`SET LOCAL search_path TO ${searchPathList(settings.searchPath)}`);\n }\n if (settings.statementTimeoutMs > 0) {\n statements.push(`SET LOCAL statement_timeout = ${Math.floor(settings.statementTimeoutMs)}`);\n }\n return statements;\n}\n\n/**\n * A `search_path` value as a list of quoted identifiers, so a schema name can\n * never be read as SQL. `\"$user\"` keeps its meaning quoted.\n */\nexport function searchPathList(searchPath: string): string {\n return searchPath\n .split(\",\")\n .map(part => part.trim().replace(/^\"(.*)\"$/, \"$1\"))\n .filter(part => part.length > 0)\n .map(part => `\"${part.replace(/\"/g, \"\\\"\\\"\")}\"`)\n .join(\", \");\n}\n\n/**\n * The `pg.Pool` settings shared by every pool this module opens, with the\n * startup parameters a transaction-mode pooler cannot carry left out when\n * `pooled`. The pool is registered so {@link pooledTransactionSettings} can\n * answer for it.\n */\nfunction poolOptions(\n connectionString: string,\n opts: Required<PostgresPoolConfig>,\n max: number\n): PoolConfig {\n return {\n connectionString: opts.pooled ? connectionString : pinSearchPath(connectionString, opts.searchPath),\n max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n ...(opts.pooled ? {} : { statement_timeout: opts.statementTimeout }),\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n}\n\nfunction registerPooled(pool: Pool, opts: Required<PostgresPoolConfig>): void {\n if (!opts.pooled) return;\n pooledPools.set(pool, { searchPath: opts.searchPath, statementTimeoutMs: opts.statementTimeout });\n}\n\n/**\n * Pin `search_path` into a connection string, so unqualified SQL resolves to a\n * schema this framework chose rather than to one Postgres inferred.\n *\n * Postgres defaults `search_path` to `\"$user\", public`: the *first* candidate\n * is a schema named after the connecting role. Rebase creates a schema called\n * `rebase` (auth, history, api keys), and every template, compose file and\n * deployment doc names the database role `rebase` too — so `$user` resolves to\n * a schema that exists, and every unqualified statement lands there instead of\n * in `public`. The generated Drizzle schema emits bare `pgTable(\"posts\", …)`\n * for any collection without an explicit `schema`, which makes the *runtime's*\n * own reads and writes unqualified; a developer's raw `rebase.sql(...)`, the\n * Studio SQL editor and any hand-written migration are unqualified too. The\n * result is collection tables created in, and served from, `rebase`.\n *\n * Drizzle cannot express the fix on its side: `pgSchema(\"public\")` throws by\n * design (\"just use pgTable() instead\"), so there is no way to emit a\n * public-qualified table from the generator. The pin has to live on the\n * connection.\n *\n * Precedence is deliberate and verified against node-postgres: `options` in\n * the connection string wins over the `options` field passed to `Pool`, so\n * rewriting the URL — rather than setting the field — is what makes this\n * authoritative. Two escape hatches survive it:\n *\n * - an `options` that already mentions `search_path` is left untouched, so a\n * deployment that deliberately pins something else keeps it;\n * - `searchPath: false` (or an unparseable, non-URL connection string) sends\n * nothing and inherits the server default.\n *\n * Anything else in `options` (a `statement_timeout`, say) is preserved and the\n * `search_path` flag is appended to it.\n */\nexport function pinSearchPath(connectionString: string, searchPath: string | false = \"public\"): string {\n if (searchPath === false) return connectionString;\n\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n // Key/value DSNs and anything else we cannot parse are returned as\n // given: a connection that works unpinned beats one we corrupted.\n return connectionString;\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return connectionString;\n\n const existing = url.searchParams.get(\"options\");\n if (existing && /(^|\\s)-c\\s*search_path\\s*=/.test(existing)) return connectionString;\n\n const flag = `-c search_path=${searchPath}`;\n url.searchParams.set(\"options\", existing ? `${existing} ${flag}` : flag);\n // Re-serialize by hand. `URLSearchParams` writes a space as `+`, which\n // node-postgres happens to decode but libpq does not — and this same string\n // is handed to `pg_dump`/`psql` for backups. Percent-encoding is the form\n // both agree on, and is what the scaffolded `.env` already ships.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n return url.toString();\n}\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;\n if (expired && typeof expired.add === \"function\" && typeof expired.has === \"function\" && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n * @param env Where the pool-size ceiling `REBASE_DB_POOL_MAX`\n * is read from (see {@link poolMaxCeiling}); pass\n * `{}` to read none.\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig,\n env: NodeJS.ProcessEnv = process.env\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max, env));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n reportPoolError(\"pg-pool\", err);\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-direct-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n const pgPoolConfig = poolOptions(connectionString, opts, cappedPoolMax(opts.max));\n connectionString = pgPoolConfig.connectionString ?? connectionString;\n\n const pool = new Pool(pgPoolConfig);\n registerPooled(pool, opts);\n\n pool.on(\"error\", (err) => reportPoolError(\"pg-replica-pool\", err));\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Close `companions` whenever `pool` is closed, before it.\n *\n * The pools a driver opens for itself — a read replica's, a direct session\n * pool, the per-database pools — are invisible to whoever opened the main\n * pool, and closing the main pool is the one shutdown signal every server\n * version sends a driver. So the main pool's `end` is wrapped: companions\n * first, then the pool, once however many times it is called (`pg.Pool`\n * throws on a second `end`). A pool without `end`, or no pool, is left alone.\n */\nexport function closeWithPool(pool: unknown, companions: () => Promise<void>): void {\n if (pool === null || typeof pool !== \"object\" || !(\"end\" in pool) || typeof pool.end !== \"function\") return;\n const end: (...args: unknown[]) => unknown = pool.end.bind(pool);\n let closing: Promise<void> | undefined;\n const wrapped = (callback?: (err?: Error) => void): Promise<void> | void => {\n closing ??= (async () => {\n try {\n await companions();\n } finally {\n await end();\n }\n })();\n if (typeof callback === \"function\") {\n closing.then(() => callback(), (err: unknown) => callback(err instanceof Error ? err : new Error(String(err))));\n return;\n }\n return closing;\n };\n Object.defineProperty(pool, \"end\", { value: wrapped, configurable: true, writable: true });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAS;CAAS;AAAO,CAAC;;AAG9D,SAAgB,sBAAsB,KAAqB;CACvD,MAAM,OAAO,UAAU,MAAM,IAAI,OAAO,KAAA;CACxC,OAAQ,OAAO,SAAS,YAAY,mBAAmB,IAAI,IAAI,KACxD,uDAAuD,KAAK,IAAI,OAAO;AAClF;;AAGA,IAAa,sBAAsB;;AAGnC,IAAI,aAAa;;;;;;;;;AAajB,SAAgB,gBAAgB,OAAe,KAAY,MAAoB,QAAQ,MAAoB,KAAK,KAAW;CACvH,IAAI,CAAC,sBAAsB,GAAG,GAAG;EAC7B,IAAI,MAAM,IAAI,MAAM,0BAA0B,EAAE,QAAQ,IAAI,QAAQ,CAAC;EACrE;CACJ;CACA,MAAM,KAAK,IA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,WAAW,aAA2D;EACxE,aAAa,YAAY;GACrB,IAAI;IACA,MAAM,WAAW;GACrB,UAAU;IACN,MAAM,IAAI;GACd;EACJ,EAAA,CAAG;EACH,IAAI,OAAO,aAAa,YAAY;GAChC,QAAQ,WAAW,SAAS,IAAI,QAAiB,SAAS,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC,CAAC;GAC9G;EACJ;EACA,OAAO;CACX;CACA,OAAO,eAAe,MAAM,OAAO;EAAE,OAAO;EAAS,cAAc;EAAM,UAAU;CAAK,CAAC;AAC7F"}
@@ -26,6 +26,23 @@ export interface PostgresPoolConfig {
26
26
  * is not "inherit".
27
27
  */
28
28
  searchPath?: string | false;
29
+ /**
30
+ * The URL reaches the database through a transaction-mode pooler such as
31
+ * PgBouncer (`DATABASE_POOLED=true`).
32
+ *
33
+ * A transaction-mode pooler hands each transaction whatever server
34
+ * connection is free, so nothing set for a *session* survives to the next
35
+ * statement — and the startup packet's parameters are either refused by
36
+ * the pooler or dropped by it (`ignore_startup_parameters`). So a pooled
37
+ * pool sends neither `statement_timeout` nor `options=-c search_path` at
38
+ * connect; {@link pooledTransactionSettings} says what to `SET LOCAL` at
39
+ * the start of each transaction instead, and the boot sets the role's
40
+ * default `search_path` (see `ensurePooledRoleDefaults`).
41
+ *
42
+ * Explicit rather than sniffed from the URL: a pooler's address looks like
43
+ * any other database's.
44
+ */
45
+ pooled?: boolean;
29
46
  }
30
47
  /**
31
48
  * Ceiling on pool size, from the environment.
@@ -51,6 +68,35 @@ export declare function cappedPoolMax(requested: number, env?: NodeJS.ProcessEnv
51
68
  * `connectionTimeoutMillis` is 0, wait forever.
52
69
  */
53
70
  export declare function defaultPoolTimeouts(): Pick<PoolConfig, "connectionTimeoutMillis" | "query_timeout" | "statement_timeout" | "keepAlive" | "keepAliveInitialDelayMillis">;
71
+ /**
72
+ * What a pool behind a transaction-mode pooler would have sent at connect, and
73
+ * must instead set inside each transaction. See {@link PostgresPoolConfig.pooled}.
74
+ */
75
+ export interface PooledTransactionSettings {
76
+ /** `false` when the pool was told to inherit the server's `search_path`. */
77
+ searchPath: string | false;
78
+ statementTimeoutMs: number;
79
+ }
80
+ /**
81
+ * The settings a transaction on `pool` must `SET LOCAL` for itself, or
82
+ * `undefined` when the pool talks to the database directly and sent them at
83
+ * connect.
84
+ */
85
+ export declare function pooledTransactionSettings(pool: unknown): PooledTransactionSettings | undefined;
86
+ /** Whether `pool` reaches its database through a transaction-mode pooler. */
87
+ export declare function isPooledPool(pool: unknown): boolean;
88
+ /**
89
+ * The `SET LOCAL` statements that give a transaction on a pooled connection
90
+ * what a direct connection got from its startup packet. Empty for a direct
91
+ * pool. `SET LOCAL` ends with the transaction, so nothing reaches the next
92
+ * client the pooler hands that server connection to.
93
+ */
94
+ export declare function transactionSettingsStatements(settings: PooledTransactionSettings | undefined): string[];
95
+ /**
96
+ * A `search_path` value as a list of quoted identifiers, so a schema name can
97
+ * never be read as SQL. `"$user"` keeps its meaning quoted.
98
+ */
99
+ export declare function searchPathList(searchPath: string): string;
54
100
  /**
55
101
  * Pin `search_path` into a connection string, so unqualified SQL resolves to a
56
102
  * schema this framework chose rather than to one Postgres inferred.
@@ -153,3 +199,14 @@ export declare function createReadReplicaConnection(connectionString: string, sc
153
199
  pool: Pool;
154
200
  connectionString: string;
155
201
  };
202
+ /**
203
+ * Close `companions` whenever `pool` is closed, before it.
204
+ *
205
+ * The pools a driver opens for itself — a read replica's, a direct session
206
+ * pool, the per-database pools — are invisible to whoever opened the main
207
+ * pool, and closing the main pool is the one shutdown signal every server
208
+ * version sends a driver. So the main pool's `end` is wrapped: companions
209
+ * first, then the pool, once however many times it is called (`pg.Pool`
210
+ * throws on a second `end`). A pool without `end`, or no pool, is left alone.
211
+ */
212
+ export declare function closeWithPool(pool: unknown, companions: () => Promise<void>): void;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * What a Postgres source reports about itself for `/metrics`: its pools, and a
3
+ * sample of the server behind them.
4
+ *
5
+ * The control plane scrapes the runtime on every substrate, including ones
6
+ * where it cannot reach the database directly. So the numbers a database
7
+ * needs watched by — connections against `max_connections`, its size, how far
8
+ * a standby is behind — are read here, by the process that is connected
9
+ * anyway, and published with the rest of its metrics.
10
+ *
11
+ * @module
12
+ */
13
+ import type { Pool } from "pg";
14
+ import type { DatabaseHealthSample, DatabasePoolStats } from "@rebasepro/types";
15
+ /** The three counts `pg.Pool` keeps, as a stats row for `pool`. */
16
+ export declare function poolStatsOf(pool: Pick<Pool, "totalCount" | "idleCount" | "waitingCount">, name: string): DatabasePoolStats;
17
+ /**
18
+ * Sample the server behind `primary`, and the standby behind `replica` when
19
+ * there is one. Each part is read on its own: a role that may not read one
20
+ * answer still reports the others, and the part it could not read is left
21
+ * out rather than reported as zero.
22
+ */
23
+ export declare function sampleDatabaseHealth(primary: Pick<Pool, "query">, replica?: Pick<Pool, "query">): Promise<DatabaseHealthSample>;
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
- import { c as pinSearchPath, o as defaultPoolTimeouts, s as guardPoolAgainstDirtyRelease, t as cappedPoolMax, u as reportPoolError } from "./connection-czvI7TZL.js";
4
+ import { c as guardPoolAgainstDirtyRelease, h as reportPoolError, s as defaultPoolTimeouts, t as cappedPoolMax, u as pinSearchPath } from "./connection-CcYqncW5.js";
5
5
  import { Pool } from "pg";
6
6
  import { drizzle } from "drizzle-orm/node-postgres";
7
7
  import { logger } from "@rebasepro/server";
@@ -114,4 +114,4 @@ var DatabasePoolManager = class {
114
114
  //#endregion
115
115
  export { databasePoolManager_exports as n, DatabasePoolManager as t };
116
116
 
117
- //# sourceMappingURL=databasePoolManager-BjoVvuAq.js.map
117
+ //# sourceMappingURL=databasePoolManager-XmhMczz0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"databasePoolManager-BjoVvuAq.js","names":[],"sources":["../src/databasePoolManager.ts"],"sourcesContent":["import { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { guardPoolAgainstDirtyRelease, pinSearchPath, cappedPoolMax, defaultPoolTimeouts } from \"./connection\";\nimport { reportPoolError } from \"./pool-disconnects\";\n\nexport class DatabasePoolManager {\n private pools: Map<string, Pool> = new Map();\n private drizzleInstances: Map<string, NodePgDatabase> = new Map();\n public readonly defaultDatabaseName: string;\n private readonly rootConnectionString: string;\n\n constructor(adminConnectionString: string) {\n this.rootConnectionString = adminConnectionString;\n try {\n const url = new URL(adminConnectionString);\n // Decoded as pg decodes it to connect (`decodeURI`): the URL holds\n // `caf%C3%A9` for the database `café`, and this name is used as an\n // SQL identifier and as the key of the pool `getPool` builds back\n // from it.\n this.defaultDatabaseName = decodeURI(url.pathname.slice(1));\n } catch (e) {\n throw new Error(`Invalid adminConnectionString provided: ${e}`);\n }\n }\n\n public getDrizzle(databaseName: string): NodePgDatabase<Record<string, never>> {\n const existing = this.drizzleInstances.get(databaseName);\n if (existing) {\n return existing;\n }\n\n const pool = this.getPool(databaseName);\n const db = drizzle(pool);\n this.drizzleInstances.set(databaseName, db);\n return db;\n }\n\n public getPool(databaseName: string): Pool {\n if (this.pools.has(databaseName)) {\n return this.pools.get(databaseName)!;\n }\n\n const url = new URL(this.rootConnectionString);\n url.pathname = `/${databaseName}`;\n\n const pool = new Pool({\n // Same pin as the primary pool: these are branch/multi-database\n // connections to the *same* server, so they inherit the same\n // `\"$user\"` hazard. See `pinSearchPath`.\n connectionString: pinSearchPath(url.toString()),\n // Capped by REBASE_DB_POOL_MAX, which the managed development\n // database sets to 1: PGlite multiplexes onto a single session and\n // overlapping transactions deadlock there.\n max: cappedPoolMax(10),\n idleTimeoutMillis: 10000, // Reduced from 30000 for aggressive cleanup\n allowExitOnIdle: true, // Prevent idle clients from hanging the Node.js process\n // The main pool's limits: a full pool answers 503 after 10 s rather\n // than queueing forever, and a statement stops at 30 s server-side.\n ...defaultPoolTimeouts()\n });\n\n // Prevent idle client errors from crashing the Node.js process\n pool.on(\"error\", (err) => reportPoolError(`DatabasePoolManager:${databaseName}`, err));\n guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);\n\n this.pools.set(databaseName, pool);\n return pool;\n }\n\n /**\n * Disconnect and remove the pool for a specific database.\n * Required before `CREATE DATABASE ... TEMPLATE` or `DROP DATABASE`,\n * which need exclusive access to the target database.\n */\n public async disconnectDatabase(databaseName: string): Promise<void> {\n const pool = this.pools.get(databaseName);\n if (pool) {\n await pool.end();\n this.pools.delete(databaseName);\n this.drizzleInstances.delete(databaseName);\n }\n }\n\n /** Check if a pool exists for a given database name. */\n public hasPool(databaseName: string): boolean {\n return this.pools.has(databaseName);\n }\n\n /**\n * Does this server serve exactly one database?\n *\n * The managed development database is PGlite, and PGlite serves exactly\n * one. `CREATE DATABASE \"rb_feature\" TEMPLATE \"postgres\"` there writes a\n * `pg_database` catalogue row and nothing else: nothing errors, the row is\n * listable, `pg_database_size` answers — and connecting to the \"branch\"\n * lands you in the parent. Every write made in the belief that it is\n * sandboxed goes to the developer's real development database.\n *\n * The CLI already refuses `rebase db branch` on this ground, but it does it\n * by parsing argv, so Studio — which reaches `BranchService` over the\n * websocket — walked straight past it. The connection is the only thing\n * both callers share, so the answer belongs here.\n *\n * Measured, not assumed: `select version()` over the PGlite socket returns\n * `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`, which is how a wasm build\n * announces itself and what `dev-db/constraints.ts` documents. A real\n * Postgres never carries `(PGlite `.\n *\n * Cached, because a live connection cannot change engine underneath us, and\n * a `PostgresBackendDriver` — which builds a `BranchService` — is\n * constructed per transaction.\n */\n public servesOneDatabase(): Promise<boolean> {\n this.oneDatabaseProbe ??= this.probeOneDatabase();\n return this.oneDatabaseProbe;\n }\n\n private oneDatabaseProbe?: Promise<boolean>;\n\n private async probeOneDatabase(): Promise<boolean> {\n try {\n const result = await this.getPool(this.defaultDatabaseName)\n .query<{ version: string }>(\"SELECT version() AS version\");\n return /\\(PGlite\\b/i.test(result.rows[0]?.version ?? \"\");\n } catch (err) {\n // Fail open, and do not cache the failure. The cost of a wrong\n // \"yes\" is refusing branching on a real Postgres that momentarily\n // could not answer; the cost of a wrong \"no\" is one fake branch,\n // which is what this exists to prevent — but a server that cannot\n // run `select version()` is not one we can conclude anything about.\n this.oneDatabaseProbe = undefined;\n logger.warn(\"[DatabasePoolManager] Could not read the server version\", { error: err });\n return false;\n }\n }\n\n public async shutdown(): Promise<void> {\n const promises = [];\n for (const [dbName, pool] of this.pools.entries()) {\n // Debug: every CLI command that reaches a database ends here, and\n // the reader of `rebase db branch create` did not ask about pools.\n logger.debug(`[DatabasePoolManager] Shutting down pool for ${dbName}`);\n promises.push(pool.end());\n }\n await Promise.all(promises);\n this.pools.clear();\n this.drizzleInstances.clear();\n }\n}\n"],"mappings":";;;;;;;;;AAOA,IAAa,sBAAb,MAAiC;CAC7B,wBAAmC,IAAI,IAAI;CAC3C,mCAAwD,IAAI,IAAI;CAChE;CACA;CAEA,YAAY,uBAA+B;EACvC,KAAK,uBAAuB;EAC5B,IAAI;GACA,MAAM,MAAM,IAAI,IAAI,qBAAqB;GAKzC,KAAK,sBAAsB,UAAU,IAAI,SAAS,MAAM,CAAC,CAAC;EAC9D,SAAS,GAAG;GACR,MAAM,IAAI,MAAM,2CAA2C,GAAG;EAClE;CACJ;CAEA,WAAkB,cAA6D;EAC3E,MAAM,WAAW,KAAK,iBAAiB,IAAI,YAAY;EACvD,IAAI,UACA,OAAO;EAIX,MAAM,KAAK,QADE,KAAK,QAAQ,YACP,CAAI;EACvB,KAAK,iBAAiB,IAAI,cAAc,EAAE;EAC1C,OAAO;CACX;CAEA,QAAe,cAA4B;EACvC,IAAI,KAAK,MAAM,IAAI,YAAY,GAC3B,OAAO,KAAK,MAAM,IAAI,YAAY;EAGtC,MAAM,MAAM,IAAI,IAAI,KAAK,oBAA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AAM,MAAM;EACjB,KAAK,iBAAiB,MAAM;CAChC;AACJ"}
1
+ {"version":3,"file":"databasePoolManager-XmhMczz0.js","names":[],"sources":["../src/databasePoolManager.ts"],"sourcesContent":["import { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { guardPoolAgainstDirtyRelease, pinSearchPath, cappedPoolMax, defaultPoolTimeouts } from \"./connection\";\nimport { reportPoolError } from \"./pool-disconnects\";\n\nexport class DatabasePoolManager {\n private pools: Map<string, Pool> = new Map();\n private drizzleInstances: Map<string, NodePgDatabase> = new Map();\n public readonly defaultDatabaseName: string;\n private readonly rootConnectionString: string;\n\n constructor(adminConnectionString: string) {\n this.rootConnectionString = adminConnectionString;\n try {\n const url = new URL(adminConnectionString);\n // Decoded as pg decodes it to connect (`decodeURI`): the URL holds\n // `caf%C3%A9` for the database `café`, and this name is used as an\n // SQL identifier and as the key of the pool `getPool` builds back\n // from it.\n this.defaultDatabaseName = decodeURI(url.pathname.slice(1));\n } catch (e) {\n throw new Error(`Invalid adminConnectionString provided: ${e}`);\n }\n }\n\n public getDrizzle(databaseName: string): NodePgDatabase<Record<string, never>> {\n const existing = this.drizzleInstances.get(databaseName);\n if (existing) {\n return existing;\n }\n\n const pool = this.getPool(databaseName);\n const db = drizzle(pool);\n this.drizzleInstances.set(databaseName, db);\n return db;\n }\n\n public getPool(databaseName: string): Pool {\n if (this.pools.has(databaseName)) {\n return this.pools.get(databaseName)!;\n }\n\n const url = new URL(this.rootConnectionString);\n url.pathname = `/${databaseName}`;\n\n const pool = new Pool({\n // Same pin as the primary pool: these are branch/multi-database\n // connections to the *same* server, so they inherit the same\n // `\"$user\"` hazard. See `pinSearchPath`.\n connectionString: pinSearchPath(url.toString()),\n // Capped by REBASE_DB_POOL_MAX, which the managed development\n // database sets to 1: PGlite multiplexes onto a single session and\n // overlapping transactions deadlock there.\n max: cappedPoolMax(10),\n idleTimeoutMillis: 10000, // Reduced from 30000 for aggressive cleanup\n allowExitOnIdle: true, // Prevent idle clients from hanging the Node.js process\n // The main pool's limits: a full pool answers 503 after 10 s rather\n // than queueing forever, and a statement stops at 30 s server-side.\n ...defaultPoolTimeouts()\n });\n\n // Prevent idle client errors from crashing the Node.js process\n pool.on(\"error\", (err) => reportPoolError(`DatabasePoolManager:${databaseName}`, err));\n guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);\n\n this.pools.set(databaseName, pool);\n return pool;\n }\n\n /**\n * Disconnect and remove the pool for a specific database.\n * Required before `CREATE DATABASE ... TEMPLATE` or `DROP DATABASE`,\n * which need exclusive access to the target database.\n */\n public async disconnectDatabase(databaseName: string): Promise<void> {\n const pool = this.pools.get(databaseName);\n if (pool) {\n await pool.end();\n this.pools.delete(databaseName);\n this.drizzleInstances.delete(databaseName);\n }\n }\n\n /** Check if a pool exists for a given database name. */\n public hasPool(databaseName: string): boolean {\n return this.pools.has(databaseName);\n }\n\n /**\n * Does this server serve exactly one database?\n *\n * The managed development database is PGlite, and PGlite serves exactly\n * one. `CREATE DATABASE \"rb_feature\" TEMPLATE \"postgres\"` there writes a\n * `pg_database` catalogue row and nothing else: nothing errors, the row is\n * listable, `pg_database_size` answers — and connecting to the \"branch\"\n * lands you in the parent. Every write made in the belief that it is\n * sandboxed goes to the developer's real development database.\n *\n * The CLI already refuses `rebase db branch` on this ground, but it does it\n * by parsing argv, so Studio — which reaches `BranchService` over the\n * websocket — walked straight past it. The connection is the only thing\n * both callers share, so the answer belongs here.\n *\n * Measured, not assumed: `select version()` over the PGlite socket returns\n * `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`, which is how a wasm build\n * announces itself and what `dev-db/constraints.ts` documents. A real\n * Postgres never carries `(PGlite `.\n *\n * Cached, because a live connection cannot change engine underneath us, and\n * a `PostgresBackendDriver` — which builds a `BranchService` — is\n * constructed per transaction.\n */\n public servesOneDatabase(): Promise<boolean> {\n this.oneDatabaseProbe ??= this.probeOneDatabase();\n return this.oneDatabaseProbe;\n }\n\n private oneDatabaseProbe?: Promise<boolean>;\n\n private async probeOneDatabase(): Promise<boolean> {\n try {\n const result = await this.getPool(this.defaultDatabaseName)\n .query<{ version: string }>(\"SELECT version() AS version\");\n return /\\(PGlite\\b/i.test(result.rows[0]?.version ?? \"\");\n } catch (err) {\n // Fail open, and do not cache the failure. The cost of a wrong\n // \"yes\" is refusing branching on a real Postgres that momentarily\n // could not answer; the cost of a wrong \"no\" is one fake branch,\n // which is what this exists to prevent — but a server that cannot\n // run `select version()` is not one we can conclude anything about.\n this.oneDatabaseProbe = undefined;\n logger.warn(\"[DatabasePoolManager] Could not read the server version\", { error: err });\n return false;\n }\n }\n\n public async shutdown(): Promise<void> {\n const promises = [];\n for (const [dbName, pool] of this.pools.entries()) {\n // Debug: every CLI command that reaches a database ends here, and\n // the reader of `rebase db branch create` did not ask about pools.\n logger.debug(`[DatabasePoolManager] Shutting down pool for ${dbName}`);\n promises.push(pool.end());\n }\n await Promise.all(promises);\n this.pools.clear();\n this.drizzleInstances.clear();\n }\n}\n"],"mappings":";;;;;;;;;AAOA,IAAa,sBAAb,MAAiC;CAC7B,wBAAmC,IAAI,IAAI;CAC3C,mCAAwD,IAAI,IAAI;CAChE;CACA;CAEA,YAAY,uBAA+B;EACvC,KAAK,uBAAuB;EAC5B,IAAI;GACA,MAAM,MAAM,IAAI,IAAI,qBAAqB;GAKzC,KAAK,sBAAsB,UAAU,IAAI,SAAS,MAAM,CAAC,CAAC;EAC9D,SAAS,GAAG;GACR,MAAM,IAAI,MAAM,2CAA2C,GAAG;EAClE;CACJ;CAEA,WAAkB,cAA6D;EAC3E,MAAM,WAAW,KAAK,iBAAiB,IAAI,YAAY;EACvD,IAAI,UACA,OAAO;EAIX,MAAM,KAAK,QADE,KAAK,QAAQ,YACP,CAAI;EACvB,KAAK,iBAAiB,IAAI,cAAc,EAAE;EAC1C,OAAO;CACX;CAEA,QAAe,cAA4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,OAAO,MAAM,gDAAgD,QAAQ;GACrE,SAAS,KAAK,KAAK,IAAI,CAAC;EAC5B;EACA,MAAM,QAAQ,IAAI,QAAQ;EAC1B,KAAK,MAAM,MAAM;EACjB,KAAK,iBAAiB,MAAM;CAChC;AACJ"}
@@ -706,6 +706,7 @@ var functionTarget = (statement) => {
706
706
  var deferred_index_build_exports = /* @__PURE__ */ __exportAll({
707
707
  TABLE_BUSY_REASON: () => TABLE_BUSY_REASON,
708
708
  buildDeferredIndexes: () => buildDeferredIndexes,
709
+ clientIndexBuildSession: () => clientIndexBuildSession,
709
710
  isPgPool: () => isPgPool,
710
711
  poolIndexBuildSession: () => poolIndexBuildSession,
711
712
  scheduleDeferredIndexBuild: () => scheduleDeferredIndexBuild
@@ -738,6 +739,34 @@ var poolIndexBuildSession = (pool) => async () => {
738
739
  release: () => client.release()
739
740
  };
740
741
  };
742
+ /**
743
+ * A session on a connection opened for it, from a URL — for a pool behind a
744
+ * transaction-mode pooler, where "the pool's next connection" is not one
745
+ * backend: the pooler hands each statement whatever server connection is
746
+ * free, so a session advisory lock and `SET statement_timeout = 0` would land
747
+ * on one and the `CREATE INDEX` run on another. The URL must name the
748
+ * database itself (`DATABASE_DIRECT_URL`). Ended, not released, when done.
749
+ */
750
+ var clientIndexBuildSession = (connectionString) => async () => {
751
+ const { Client } = await import("pg");
752
+ const client = new Client({
753
+ connectionString,
754
+ connectionTimeoutMillis: 1e4
755
+ });
756
+ client.on("error", () => void 0);
757
+ await client.connect();
758
+ return {
759
+ dedicated: true,
760
+ async query(text) {
761
+ const config = {
762
+ text,
763
+ query_timeout: INDEX_BUILD_READ_TIMEOUT_MS
764
+ };
765
+ return { rows: (await client.query(config)).rows };
766
+ },
767
+ release: () => client.end().catch(() => void 0)
768
+ };
769
+ };
741
770
  /** `42P01 undefined_table` — `pg_stat_progress_create_index` before Postgres 12. */
742
771
  var isUndefinedTable = (err) => extractPgError(err)?.code === "42P01";
743
772
  /** `25001 active_sql_transaction` — `CONCURRENTLY` on a connection inside a transaction block. */
@@ -1048,4 +1077,4 @@ function scheduleDeferredIndexBuild(openSession, indexes, options = {}) {
1048
1077
  //#endregion
1049
1078
  export { assertSafeIdentifier as a, helperFunctionKey as c, HELPER_FUNCTIONS as i, columnTypeDriftMessage as l, buildDeferredIndexes as n, describeHelperFunction as o, deferred_index_build_exports as r, diffPlanAgainstCatalogue as s, TABLE_BUSY_REASON as t, typesAgree as u };
1050
1079
 
1051
- //# sourceMappingURL=deferred-index-build-BcJ_oulu.js.map
1080
+ //# sourceMappingURL=deferred-index-build-BwH6k1Og.js.map