@rebasepro/server-postgres 0.29.0 → 0.29.2

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 (161) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-X9R505mP.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-X9R505mP.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +90 -12
  4. package/dist/PostgresBootstrapper.d.ts +34 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-CwiJEp_J.js} +3 -3
  9. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-CwiJEp_J.js.map} +1 -1
  10. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-CbZj9ovZ.js} +2 -2
  11. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-CbZj9ovZ.js.map} +1 -1
  12. package/dist/{cli-console-DPdZCWTi.js → cli-console-DDkNetCz.js} +6 -6
  13. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DDkNetCz.js.map} +1 -1
  14. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-C73Qy7WJ.js} +49 -6
  15. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-C73Qy7WJ.js.map} +1 -1
  16. package/dist/cli.js +209 -53
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/database-preflight-DIauc8i5.js +184 -0
  23. package/dist/database-preflight-DIauc8i5.js.map +1 -0
  24. package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
  25. package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
  26. package/dist/db-subcommands.d.ts +1 -1
  27. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-DDdnjaOW.js} +25 -9
  28. package/dist/deferred-index-build-DDdnjaOW.js.map +1 -0
  29. package/dist/{doctor-_g2tHRtG.js → doctor-DwMXljiq.js} +11 -11
  30. package/dist/doctor-DwMXljiq.js.map +1 -0
  31. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-DJsOMpaI.js} +23 -13
  32. package/dist/ensure-collection-policies-DJsOMpaI.js.map +1 -0
  33. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-h1mUO7Uu.js} +18 -10
  34. package/dist/ensure-collection-tables-h1mUO7Uu.js.map +1 -0
  35. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-CUqYgMvo.js} +4 -4
  36. package/dist/ensure-tables-CUqYgMvo.js.map +1 -0
  37. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-z7ustOl_.js} +3 -3
  38. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-z7ustOl_.js.map} +1 -1
  39. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-BIUqhSzh.js} +2 -2
  40. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-BIUqhSzh.js.map} +1 -1
  41. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-BBXjxm5z.js} +3 -3
  42. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-BBXjxm5z.js.map} +1 -1
  43. package/dist/{generate-files-DbwU8Btx.js → generate-files-BkiRFoV1.js} +3 -3
  44. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-BkiRFoV1.js.map} +1 -1
  45. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-G9PvjHrr.js} +10 -5
  46. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-G9PvjHrr.js.map} +1 -1
  47. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-D2soazQU.js} +18 -7
  48. package/dist/generated-schema-diff-D2soazQU.js.map +1 -0
  49. package/dist/history/HistoryService.d.ts +2 -3
  50. package/dist/history/ensure-history-table.d.ts +8 -3
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.es.js +22 -14
  53. package/dist/index.es.js.map +1 -1
  54. package/dist/interfaces.d.ts +24 -2
  55. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  56. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  57. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-CveNQli3.js} +166 -460
  58. package/dist/migrate-baseline-CveNQli3.js.map +1 -0
  59. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-C4qbQ0jK.js} +42 -13
  60. package/dist/migrate-policy-stamps-C4qbQ0jK.js.map +1 -0
  61. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-Cvid3iwR.js} +1813 -689
  62. package/dist/open-rebase-Cvid3iwR.js.map +1 -0
  63. package/dist/open-rebase.d.ts +7 -2
  64. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-80uTIHQs.js} +2 -2
  65. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-80uTIHQs.js.map} +1 -1
  66. package/dist/pipelined-transaction.d.ts +24 -37
  67. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-CMhNYEYF.js} +109 -14
  68. package/dist/plan-schema-CMhNYEYF.js.map +1 -0
  69. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-Bx6663KD.js} +29 -6
  70. package/dist/policy-drift-Bx6663KD.js.map +1 -0
  71. package/dist/push-index-adoption-C-TpM445.js +22 -0
  72. package/dist/push-index-adoption-C-TpM445.js.map +1 -0
  73. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-xbpgZEJK.js} +4 -4
  74. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-xbpgZEJK.js.map} +1 -1
  75. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-D-JEv0Gn.js} +2 -2
  76. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-D-JEv0Gn.js.map} +1 -1
  77. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-7UKspspl.js} +4 -4
  78. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-7UKspspl.js.map} +1 -1
  79. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-BOw5PtU8.js} +14 -8
  80. package/dist/push-policy-plan-BOw5PtU8.js.map +1 -0
  81. package/dist/read-routing.d.ts +10 -30
  82. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-Di-fTGti.js} +40 -10
  83. package/dist/render-ddl-Di-fTGti.js.map +1 -0
  84. package/dist/request-role-cli-Bxxskru9.js +260 -0
  85. package/dist/request-role-cli-Bxxskru9.js.map +1 -0
  86. package/dist/request-role-cli.d.ts +86 -0
  87. package/dist/request-role-migration-BCW4v0rq.js +150 -0
  88. package/dist/request-role-migration-BCW4v0rq.js.map +1 -0
  89. package/dist/rls-bootstrap-sql-CxszeSc7.js +534 -0
  90. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +1 -0
  91. package/dist/rls-enforcement-CyUCPDH8.js +1195 -0
  92. package/dist/rls-enforcement-CyUCPDH8.js.map +1 -0
  93. package/dist/rls-settings-BCGMIig3.js +231 -0
  94. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  95. package/dist/schema/doctor-cli.js +145 -7
  96. package/dist/schema/doctor-cli.js.map +1 -1
  97. package/dist/schema/doctor-database.d.ts +27 -0
  98. package/dist/schema/drizzle-ddl.d.ts +2 -2
  99. package/dist/schema/ensure-collection-policies.d.ts +15 -3
  100. package/dist/schema/generate-drizzle-schema.js +1 -1
  101. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -1
  102. package/dist/schema/generate-postgres-ddl.js +1 -1
  103. package/dist/schema/index-adoption.d.ts +99 -0
  104. package/dist/schema/introspect-db-logic.d.ts +2 -1
  105. package/dist/schema/introspect-db.js +3 -3
  106. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  107. package/dist/schema/plan/diff-plan.d.ts +14 -2
  108. package/dist/schema/plan/render-ddl.d.ts +17 -3
  109. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  110. package/dist/schema/plan/types.d.ts +17 -0
  111. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  112. package/dist/schema/plan/view-names.d.ts +6 -0
  113. package/dist/schema/push-index-adoption.d.ts +10 -0
  114. package/dist/schema/push-policy-plan.d.ts +5 -1
  115. package/dist/schema/rls-bootstrap-sql.d.ts +34 -0
  116. package/dist/schema/search-column.d.ts +2 -2
  117. package/dist/search-column-BM-GV6vH.js.map +1 -1
  118. package/dist/security/caller-sql-columns.d.ts +60 -0
  119. package/dist/security/caller-sql.d.ts +8 -0
  120. package/dist/security/database-preflight.d.ts +24 -0
  121. package/dist/security/policy-drift.d.ts +19 -1
  122. package/dist/security/request-role-migration.d.ts +36 -0
  123. package/dist/security/rls-enforcement.d.ts +277 -21
  124. package/dist/security/rls-settings.d.ts +210 -0
  125. package/dist/services/FetchService.d.ts +33 -8
  126. package/dist/services/PersistService.d.ts +75 -4
  127. package/dist/services/RelationService.d.ts +1 -1
  128. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  129. package/dist/services/channel-bus/index.d.ts +2 -2
  130. package/dist/services/channel-history.d.ts +2 -2
  131. package/dist/services/channel-presence.d.ts +3 -3
  132. package/dist/services/dataService.d.ts +8 -2
  133. package/dist/services/realtimeService.d.ts +21 -5
  134. package/dist/services/socket-liveness.d.ts +6 -1
  135. package/dist/services/view-access.d.ts +2 -2
  136. package/dist/types.d.ts +1 -1
  137. package/dist/utils/drizzle-conditions.d.ts +12 -0
  138. package/dist/utils/positional-params.d.ts +40 -0
  139. package/dist/view-names-Dscp6--B.js +24 -0
  140. package/dist/view-names-Dscp6--B.js.map +1 -0
  141. package/dist/{websocket-D2y88dOa.js → websocket-BSYV_KSw.js} +3 -3
  142. package/dist/websocket-BSYV_KSw.js.map +1 -0
  143. package/dist/websocket.d.ts +14 -3
  144. package/package.json +7 -7
  145. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  146. package/dist/doctor-_g2tHRtG.js.map +0 -1
  147. package/dist/ensure-collection-policies-DUpWJb5D.js.map +0 -1
  148. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  149. package/dist/ensure-tables-Bx1DYarz.js.map +0 -1
  150. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  151. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  152. package/dist/migrate-baseline-BeepEphh.js.map +0 -1
  153. package/dist/migrate-policy-stamps-cYMJ_9Ha.js.map +0 -1
  154. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  155. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  156. package/dist/policy-drift-IjD2AUD-.js.map +0 -1
  157. package/dist/push-policy-plan--oRXOj4X.js.map +0 -1
  158. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  159. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  160. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
  161. package/dist/websocket-D2y88dOa.js.map +0 -1
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import type { NodePgDatabase } from "drizzle-orm/node-postgres";
12
12
  import type { Pool } from "pg";
13
- import { type CollectionCallbacks, type CollectionConfig, type RebaseSdkData, type RebaseServerClient, type RegisteredDatabase } from "@rebasepro/types";
13
+ import { type CallerSqlOptions, type CollectionCallbacks, type CollectionConfig, type RebaseSdkData, type RebaseServerClient, type RegisteredDatabase } from "@rebasepro/types";
14
14
  import { type PostgresPoolConfig } from "./connection.js";
15
15
  /** Who a request runs as: what row-level security policies read. */
16
16
  export interface RebaseIdentity {
@@ -62,14 +62,19 @@ export interface OpenRebaseOptions {
62
62
  * the type a function's `rebase.dataAsAdmin` has — and is untyped when it
63
63
  * registered none.
64
64
  */
65
- export interface OpenedRebase<DB = RegisteredDatabase> extends Pick<RebaseServerClient<DB>, "dataAsAdmin" | "sql"> {
65
+ export interface OpenedRebase<DB = RegisteredDatabase> extends Pick<RebaseServerClient<DB>, "dataAsAdmin" | "sql" | "sqlAsAdmin"> {
66
66
  /**
67
67
  * The data as `user` sees it: every read and write runs as them, filtered
68
68
  * by the collections' row-level security policies — the scoping an HTTP
69
69
  * request from that user gets. Named after the driver method it uses.
70
+ *
71
+ * `sql` runs one statement as them, under the same policies — see
72
+ * `DataDriver.sql`. Unlike the owner-level {@link sql} beside it, it sees
73
+ * only their rows: the query text is yours, their values go in `params`.
70
74
  */
71
75
  withAuth(user: RebaseIdentity): Promise<{
72
76
  data: RebaseSdkData<DB>;
77
+ sql(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;
73
78
  }>;
74
79
  /** The collections this was opened with, or the ones the database described. */
75
80
  readonly collections: CollectionConfig[];
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { at as extractCauseMessage } from "./cli-errors-D8s4z_3g.js";
3
+ import { ot as extractCauseMessage } from "./cli-errors-C73Qy7WJ.js";
4
4
  import { DATABASE_UNAVAILABLE_MESSAGE, declaredErrorAnswer, isDatabaseUnreachable, logger } from "@rebasepro/server";
5
5
  import { fieldKeyForColumn, getTableName } from "@rebasepro/common";
6
6
  //#region src/utils/pg-error-utils.ts
@@ -399,4 +399,4 @@ function sanitizeErrorForClient(error, context, options = {}) {
399
399
  //#endregion
400
400
  export { pgErrorToFriendlyMessage as a, isRowLevelSecurityDenial as i, extractPgError as n, reachedDatabase as o, isRoleSwitchingPermissionError as r, sanitizeErrorForClient as s, classifyConnectFailure as t };
401
401
 
402
- //# sourceMappingURL=pg-error-utils-BLOVXK67.js.map
402
+ //# sourceMappingURL=pg-error-utils-80uTIHQs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pg-error-utils-BLOVXK67.js","names":[],"sources":["../src/utils/pg-error-utils.ts"],"sourcesContent":["/**\n * Shared PostgreSQL error extraction and user-friendly message formatting.\n *\n * Drizzle wraps native PG errors in a `.cause` chain. These utilities\n * unwrap that chain to get the real PostgreSQL error (identified by a\n * 5-character alphanumeric `code` such as `42P01`) and translate it into\n * a message that is safe and helpful to show to end-users.\n */\n\nimport { DATABASE_UNAVAILABLE_MESSAGE, declaredErrorAnswer, isDatabaseUnreachable, logger } from \"@rebasepro/server\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { extractCauseMessage } from \"./error-cause\";\n\n/**\n * Shape of a deliberate client-facing error — `ApiError` from\n * `@rebasepro/server`, `RebaseApiError` from `@rebasepro/types`, or anything\n * else carrying a 4xx `statusCode`.\n *\n * Matched structurally rather than with `instanceof`: `@rebasepro/server` can\n * be loaded twice (published dist vs. workspace source), which breaks class\n * identity — `PersistService` hedges against the same thing by also accepting\n * `name === \"ApiError\"`.\n */\ninterface ClientFacingError extends Error {\n statusCode?: number;\n code?: string;\n /** See `ApiError.expected` — routine outcomes log at debug, not warn. */\n expected?: boolean;\n}\n\n/**\n * Return the error when it is a deliberate 4xx, otherwise null.\n *\n * A thrown `ApiError` is a decision the server made about the request, not a\n * database failure: its message and code are already written for the client.\n *\n * So is a `RebaseApiError` — what a collection callback throws, since a\n * collection file cannot import the server package. It spells its status\n * `status`, and reading only `statusCode` here turned an `afterRead` that\n * refused with a 403 into \"Could not load data … Check server logs\" on a\n * subscription, where REST and the socket's own requests answer the 403.\n * Recognised by the predicate those doors use, `declaredErrorAnswer`.\n */\nfunction asClientFacingError(error: unknown): Pick<ClientFacingError, \"statusCode\" | \"code\" | \"message\" | \"expected\"> | null {\n const answer = declaredErrorAnswer(error);\n if (answer) {\n if (answer.status < 400 || answer.status >= 500) return null;\n return { statusCode: answer.status, code: answer.code, message: answer.message, expected: answer.expected };\n }\n if (!(error instanceof Error)) return null;\n const e = error as ClientFacingError;\n if (typeof e.statusCode !== \"number\" || e.statusCode < 400 || e.statusCode >= 500) return null;\n return e;\n}\n\n/** Shape of PostgreSQL errors with diagnostic metadata. */\nexport interface PostgresError extends Error {\n code?: string;\n detail?: string;\n hint?: string;\n constraint?: string;\n column?: string;\n table?: string;\n dataType?: string;\n cause?: unknown;\n}\n\n/**\n * Extract the underlying PostgreSQL error from a Drizzle wrapper.\n * Drizzle wraps PG errors in a `cause` property — this function\n * recursively walks the chain until it finds an object with a PG\n * error code (5-char alphanumeric, e.g. `42P01`).\n */\nexport function extractPgError(error: unknown): PostgresError | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) {\n // Check non-Error objects for a cause chain (Drizzle sometimes wraps oddly)\n if (\"cause\" in error && (error as Record<string, unknown>).cause && typeof (error as Record<string, unknown>).cause === \"object\") {\n return extractPgError((error as Record<string, unknown>).cause);\n }\n return null;\n }\n\n // Check if the error itself has a PG error code\n if (\"code\" in error && typeof (error as PostgresError).code === \"string\" && /^[0-9A-Z]{5}$/.test((error as PostgresError).code!)) {\n return error as PostgresError;\n }\n\n // Check the cause chain (Drizzle wraps PG errors)\n if (error.cause && typeof error.cause === \"object\") {\n return extractPgError(error.cause);\n }\n\n return null;\n}\n\n/**\n * Whether the failure came back from Postgres rather than from building the\n * query — which decides whether a fallback query is worth issuing.\n *\n * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds\n * RLS). Once a statement raises, that transaction is aborted, and every later\n * statement on it returns `25P02` — \"current transaction is aborted, commands\n * ignored until end of transaction block\". So a retry after a database error\n * cannot succeed, and it replaces a precise diagnosis (\"invalid input syntax\n * for type uuid\") with a generic one. Rethrow instead.\n *\n * A query the driver could not even build — a missing reciprocal relation, say\n * — never reached Postgres, leaves the transaction usable, and is exactly what\n * the fallback paths exist for.\n */\nexport function reachedDatabase(error: unknown): boolean {\n return extractPgError(error) !== null;\n}\n\n// In its own module so the driver CLI can use it without loading the server\n// (this file imports `@rebasepro/server`).\nexport { extractCauseMessage };\n\n/**\n * Codes that mean \"this connection will never work as configured\".\n *\n * A wrong password or a database that does not exist is a settled fact about\n * the connection string, not a transient fault — retrying produces the same\n * answer forever.\n */\nconst UNRECOVERABLE_CONNECT_CODES = new Set([\n \"28P01\", // invalid_password\n \"28000\", // invalid_authorization_specification\n \"3D000\", // invalid_catalog_name — the database does not exist\n \"42501\" // insufficient_privilege\n]);\n\nexport interface ConnectFailure {\n /** True when retrying cannot help: the connection string itself is wrong. */\n fatal: boolean;\n /** The deepest message available — the Postgres one where there is one. */\n reason: string;\n /** The `SQLSTATE`, when the failure came from Postgres rather than the socket. */\n code?: string;\n}\n\n/**\n * Describe a failed connection attempt in terms a developer can act on.\n *\n * The error a caller catches is Drizzle's wrapper: its message is\n * `Failed query: SELECT 1` and its stack runs through drizzle internals, while\n * the sentence that says what is actually wrong — \"password authentication\n * failed for user …\", \"database … does not exist\" — sits in `.cause`. Logging\n * the wrapper, as the bootstrapper used to, tells a developer with a typo in\n * their `DATABASE_URL` nothing at all.\n */\nexport function classifyConnectFailure(error: unknown): ConnectFailure {\n const pgError = extractPgError(error);\n const reason =\n pgError?.message ??\n extractCauseMessage(error) ??\n (error instanceof Error ? error.message : String(error));\n return {\n fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),\n reason,\n code: pgError?.code\n };\n}\n\n/**\n * Detect whether an error is specifically a role-switching permission failure\n * (e.g. \"permission denied to set role\" or \"must be member of role\"),\n * as opposed to a table-level permission denial.\n *\n * This is used by the backend driver to auto-disable role switching when the\n * connection user lacks SET ROLE privileges, rather than surfacing a confusing\n * error to the Studio SQL Editor user.\n */\nexport function isRoleSwitchingPermissionError(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n const msg = pgError.message.toLowerCase();\n return msg.includes(\"set role\") || msg.includes(\"member of role\");\n}\n\n/**\n * Was this `42501` the *caller* being refused by a policy, rather than the\n * server lacking a privilege?\n *\n * Both arrive as `insufficient_privilege`, and they are opposite kinds of\n * problem. A row-level-security refusal is a working access-control system\n * doing its job: the caller asked for something their policies do not permit,\n * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being\n * wrong — the connection role cannot touch the table at all, no policy is\n * involved, and nothing the caller changes about the request will help.\n *\n * Postgres distinguishes them in the message, so this does too:\n *\n * new row violates row-level security policy for table \"notes\" → the caller\n * permission denied for table notes → the server\n *\n * Only writes reach this. A read that RLS excludes is not an error — the rows\n * are filtered and the caller gets an empty page — so the erroring case is\n * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.\n *\n * Matched on the message because that is the only thing carrying the\n * distinction; the SQLSTATE is identical either way. Narrow by design: anything\n * not naming row-level security stays the server's problem, since reporting a\n * genuine privilege misconfiguration as \"forbidden\" would send an operator\n * hunting for a policy bug that does not exist.\n */\nexport function isRowLevelSecurityDenial(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n return pgError.message.toLowerCase().includes(\"row-level security policy\");\n}\n\n/**\n * One constraint the database refused, named in the caller's vocabulary.\n *\n * `field` is the **wire** name, derived from the physical column: `author_id`\n * on the table is `authorId` on the row and in the request body, and telling a\n * caller their `author_id` is missing sends them looking for a key their client\n * has never seen. `code` is the SQLSTATE, which is stable, documented by\n * Postgres and the same in every environment — unlike the message, which is\n * deliberately thinner in production.\n *\n * Deliberately no `value`. The column name is safe to publish: it is already in\n * the OpenAPI, the generated SDK and the caller's own request. The *value* is\n * not — `23505`'s detail reads `Key (email)=(a@b.c) already exists.`, which\n * answers \"is this person registered?\" for any address on a table whose rows\n * RLS is otherwise hiding completely.\n */\nexport interface PgFieldViolation {\n field: string;\n code: string;\n}\n\n/**\n * The physical column names a Postgres error is about.\n *\n * Postgres puts one in `column` for `23502` and nowhere else, so the rest are\n * read out of the two places that do carry them:\n *\n * - `detail` — `Key (author_id)=(9) is not present in table \"authors\".` and\n * `Key (email, tenant_id)=(…) already exists.` Only the parenthesised column\n * list is read; the values after `=` are never touched.\n * - `constraint` — `users_email_key`, `posts_author_id_fkey`. The table prefix\n * and the constraint suffix are stripped, leaving the columns joined by `_`,\n * which is ambiguous for multi-column constraints and is therefore only used\n * when `detail` gave nothing.\n *\n * `22P02` carries neither, because an invalid literal fails during parse rather\n * than against a constraint. Its message names the *type*, and an enum type is\n * generated as `<table>_<column>` — which is the one case worth decoding,\n * because a value outside an enum's labels is the most common 22P02 anyone\n * hits and the least legible one.\n */\nfunction offendingColumns(pgError: PostgresError, collection?: CollectionConfig): string[] {\n if (pgError.column) return [pgError.column];\n\n const detail = pgError.detail;\n if (detail) {\n const keyed = /Key \\(([^)]+)\\)=/.exec(detail);\n if (keyed) {\n return keyed[1].split(\",\").map(part => part.trim().replace(/^\"|\"$/g, \"\")).filter(Boolean);\n }\n }\n\n if (pgError.code === \"22P02\") {\n // `invalid input value for enum posts_status: \"archived\"`\n const enumType = /invalid input value for enum ([^:\\s]+)/i.exec(pgError.message ?? \"\");\n if (enumType && collection) {\n const typeName = enumType[1].replace(/^.*\\./, \"\").replace(/\"/g, \"\");\n const table = getTableName(collection);\n if (typeName.startsWith(`${table}_`)) return [typeName.slice(table.length + 1)];\n }\n return [];\n }\n\n const constraint = pgError.constraint;\n if (constraint && collection) {\n const table = getTableName(collection);\n const stripped = constraint\n .replace(new RegExp(`^${table}_`), \"\")\n .replace(/_(pkey|key|fkey|unique|check|excl|idx)$/, \"\");\n // Only when it names something the collection actually has: a\n // hand-written constraint name is not a column list, and guessing at one\n // would put a field in the response that does not exist.\n if (stripped && stripped !== constraint) {\n const columns = new Set<string>();\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n columns.add((prop as { columnName?: string })?.columnName ?? key);\n }\n if (columns.has(stripped)) return [stripped];\n const wire = fieldKeyForColumn(collection, stripped);\n if (collection.properties && wire in collection.properties) return [stripped];\n }\n }\n\n return [];\n}\n\n/**\n * The fields a Postgres error is about, for `details.violations`.\n *\n * Only the four SQLSTATEs that describe *the caller's data*: a missing value, a\n * duplicate, a bad literal, a foreign key pointing at nothing. Everything else\n * — a dropped connection, a missing table, a privilege problem — is the\n * deployment's, and naming a field for it would send the reader to the wrong\n * place.\n *\n * Empty when the collection is unknown or the column cannot be recovered. An\n * empty list is the honest answer; inventing a field is worse than saying\n * nothing, because a form will mark the wrong input red.\n */\nexport function pgFieldViolations(\n pgError: PostgresError,\n collection?: CollectionConfig\n): PgFieldViolation[] {\n const code = pgError.code;\n if (code !== \"23502\" && code !== \"23505\" && code !== \"22P02\" && code !== \"23503\") return [];\n // Without the collection there is no mapping, only a guess. `toWireKey`\n // would get the default case right and silently invent a field for any\n // property carrying an explicit `columnName` — and a form pointed at an\n // input that does not exist is worse off than one shown the raw column.\n if (!collection) return [];\n const columns = offendingColumns(pgError, collection);\n if (columns.length === 0) return [];\n return columns.map(column => ({\n field: fieldKeyForColumn(collection, column),\n code\n }));\n}\n\n/**\n * What a missing table or column most often means: the database is behind the\n * collections. Both ways of catching it up, because \"run migrations\" alone\n * sent a project on the managed development database — which nobody\n * migrates — the wrong way.\n */\nconst SCHEMA_BEHIND =\n \"Check that the database is up to date with the collections: `rebase db push` in development, \" +\n \"or `rebase db migrate` where migrations are used.\";\n\n/**\n * Translate a raw PostgreSQL error into a user-friendly message.\n *\n * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})\n * @param context - A human-readable context string (e.g. collection slug or path)\n * @returns An object with a `message` safe for the client and the PG `code`.\n */\nexport function pgErrorToFriendlyMessage(\n pgError: PostgresError,\n context: string,\n options: { verbose?: boolean; collection?: CollectionConfig } = {}\n): { message: string; code: string; violations: PgFieldViolation[] } {\n // Postgres's own `DETAIL` and `HINT`, and the raw driver message, are what\n // make these errors useful while you are building — and what makes them an\n // oracle once the server is answering strangers.\n //\n // The sharp one is `23505`: its detail reads `Key (email)=(a@b.c) already\n // exists.`, which answers \"is this person registered?\" for any address, on\n // a table whose rows RLS is otherwise hiding completely. The rest leak\n // physical column and constraint names, which are the map for the next\n // question. So in production the shape of the failure is served — what\n // rule was broken, and where — and the values are not.\n //\n // The full text is not lost: the caller logs the original error. This\n // decides what crosses the wire, not what is recorded.\n const verbose = options.verbose ?? process.env.NODE_ENV !== \"production\";\n\n const detail = verbose ? (pgError.detail as string | undefined) : undefined;\n const hint = verbose ? (pgError.hint as string | undefined) : undefined;\n const constraint = pgError.constraint as string | undefined;\n const column = pgError.column as string | undefined;\n const table = pgError.table as string | undefined;\n const dataType = verbose ? (pgError.dataType as string | undefined) : undefined;\n const rawMessage = pgError.message || \"Unknown database error\";\n const pgMessage = verbose ? rawMessage : \"\";\n const code = pgError.code || \"UNKNOWN\";\n\n // Which *field* the caller has to fix, derived from the column. Safe in\n // production — a column name is already published in the OpenAPI and the\n // generated SDK — where the value that broke the rule is not, and is never\n // included. See `pgFieldViolations`.\n const violations = pgFieldViolations(pgError, options.collection);\n\n const suffix = hint ? ` Hint: ${hint}` : \"\";\n const tableRef = table ?? context;\n\n /** `\": <postgres said>\"`, or nothing when the details are withheld. */\n const said = pgMessage ? `: ${pgMessage}` : \"\";\n\n switch (pgError.code) {\n case \"23503\": // foreign_key_violation\n return {\n message: detail\n ? `Foreign key constraint violated: ${detail}${suffix}`\n : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23001\": // restrict_violation\n // A row other rows still point at, under `ON DELETE RESTRICT` — the\n // default for a required link. `table` is the *referencing* table,\n // which is the one the caller has to clear or reassign first.\n return {\n message: `Cannot complete operation: rows in \"${table ?? \"another table\"}\" still reference this row in ` +\n `\"${context}\", and their foreign key${constraint ? ` (${constraint})` : \"\"} does not allow it to be ` +\n `deleted or its key changed. Delete or reassign those rows first.${detail ? ` ${detail}` : \"\"}${suffix}`,\n code,\n violations\n };\n case \"23505\": // unique_violation\n return {\n message: detail\n ? `Duplicate value: ${detail}${suffix}`\n : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23502\": {\n // not_null_violation. The message names the *field* when the\n // collection is known, because that is the key the caller sent and\n // the only one they can act on: told `author_id` is missing, they go\n // looking for a key their generated client has never mentioned.\n const named = violations[0]?.field ?? column ?? \"unknown\";\n return {\n message: `Missing required field: \"${named}\" in \"${tableRef}\" cannot be empty.${suffix}`,\n code,\n violations\n };\n }\n case \"23514\": // check_violation\n return {\n message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"22P02\": // invalid_text_representation (e.g. invalid UUID, wrong enum value)\n return {\n message: `Invalid data format in \"${context}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22001\": // string_data_right_truncation (value too long)\n return {\n message: `Value too long for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22003\": // numeric_value_out_of_range\n return {\n message: `Numeric value out of range for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"42703\": // undefined_column\n return {\n message: `Unknown column in \"${tableRef}\"${said}. ${SCHEMA_BEHIND}${suffix}`,\n code,\n violations\n };\n case \"42P01\": // undefined_table\n return {\n message: `Table not found for \"${context}\"${said}. ${SCHEMA_BEHIND}${suffix}`,\n code,\n violations\n };\n case \"42501\": // insufficient_privilege\n // Two unrelated failures share this SQLSTATE, and the old message\n // named both causes because it could not tell them apart — which\n // meant it was half wrong whichever one had happened, and sent the\n // reader to check the other. Postgres says which in its own message.\n return rawMessage.toLowerCase().includes(\"row-level security policy\")\n ? {\n // The caller. Their policies do not permit this row; the\n // deployment is working exactly as configured.\n message: `Not permitted to write this row in \"${tableRef}\": it does not satisfy the row-level security policy.${suffix}`,\n code,\n violations\n }\n : {\n // The deployment. No policy is involved — the connecting\n // role cannot touch the table at all.\n message: `Permission denied on \"${tableRef}\": the database role this server connects as lacks privileges on it.${suffix}`,\n code,\n violations\n };\n case \"28000\": // invalid_authorization_specification\n return {\n message: `Authorization failed for \"${context}\". Check your database credentials.${suffix}`,\n code,\n violations\n };\n default: {\n // Unhandled PG code — still surface the actual database message\n const parts = [`Database error in \"${context}\" [${code}]${said}`];\n if (detail) parts.push(`Detail: ${detail}`);\n if (column) parts.push(`Column: ${column}`);\n if (dataType) parts.push(`Data type: ${dataType}`);\n if (constraint) parts.push(`Constraint: ${constraint}`);\n if (hint) parts.push(`Hint: ${hint}`);\n return { message: parts.join(\". \"), code, violations };\n }\n }\n}\n\n/**\n * Sanitize any error into a message safe and helpful for the client.\n *\n * A deliberate 4xx (`ApiError`) passes through untouched — the server already\n * decided what the client should read. Otherwise the PG error is extracted\n * from the Drizzle cause chain, falling back to a generic message that\n * doesn't leak SQL.\n *\n * @param error - The raw caught error\n * @param context - A human-readable context string (e.g. collection path)\n * @returns An object with `message` (user-friendly) and optional `code`\n * (the `ApiError` code, or the PG SQLSTATE).\n */\nexport function sanitizeErrorForClient(\n error: unknown,\n context: string,\n options: { collection?: CollectionConfig } = {}\n): { message: string; code?: string; violations?: PgFieldViolation[] } {\n // ── A deliberate 4xx is not a database failure ──────────────────\n // Its message and code are written for the client; replacing them with\n // \"Check server logs\" would discard the only diagnosis the caller gets\n // (e.g. the offending filter field and the collection's valid ones).\n // Log level follows the same convention as the HTTP error handler in\n // @rebasepro/server: routine outcomes at debug, everything else at warn.\n const clientError = asClientFacingError(error);\n if (clientError) {\n const line = `[API ${clientError.statusCode} ${clientError.code ?? \"BAD_REQUEST\"}] in \"${context}\": ${clientError.message}`;\n if (clientError.expected) {\n logger.debug(line);\n } else {\n logger.warn(`⚠️ ${line}`);\n }\n return { message: clientError.message, ...(clientError.code && { code: clientError.code }) };\n }\n\n // ── The database unreachable: the answer every door gives then ──\n // Ahead of the SQLSTATE arm, because `57P01` is a SQLSTATE that says the\n // connection is gone rather than that the statement was wrong.\n if (isDatabaseUnreachable(error)) {\n logger.warn(`[DB] The database is unreachable; \"${context}\" could not be read`);\n return { message: DATABASE_UNAVAILABLE_MESSAGE, code: \"DATABASE_UNAVAILABLE\" };\n }\n\n // ── Always log the full, unsanitized error server-side ──────────\n const pgError = extractPgError(error);\n\n if (pgError) {\n logger.error(`[PG ${pgError.code}] Error in \"${context}\"`, {\n code: pgError.code,\n message: pgError.message,\n detail: pgError.detail,\n hint: pgError.hint,\n column: pgError.column,\n table: pgError.table,\n constraint: pgError.constraint,\n dataType: pgError.dataType\n // The outer Drizzle wrapper message used to be logged here \"for\n // full context\": it is `Failed query: <sql>\\nparams: <values>`, so\n // it published the statement and every bound value (an email, a\n // password hash) on every realtime data failure. The SQLSTATE,\n // detail, table, column and constraint above are the diagnostic\n // value; the wrapper added only the leak. `logger` strips the\n // wrapper as well, but the field itself carried nothing else.\n });\n const { message, code, violations } = pgErrorToFriendlyMessage(pgError, context, { collection: options.collection });\n return { message, code, ...(violations.length > 0 && { violations }) };\n }\n\n // No PG error found — log the raw error as-is\n logger.error(`Database error in \"${context}\" (no PG error extracted)`, {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n cause: error instanceof Error && error.cause\n ? (error.cause instanceof Error ? error.cause.message : String(error.cause))\n : undefined\n });\n\n // Try to get the deepest cause message\n const causeMessage = extractCauseMessage(error);\n if (causeMessage) {\n return { message: `Database error in \"${context}\": ${causeMessage}` };\n }\n\n // Last resort — generic message, never leak raw SQL\n return { message: `Could not load data for \"${context}\". Check server logs for details.` };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,oBAAoB,OAAgG;CACzH,MAAM,SAAS,oBAAoB,KAAK;CACxC,IAAI,QAAQ;EACR,IAAI,OAAO,SAAS,OAAO,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;GACd,SAAS,QAAQ;GACjB,QAAQ,QAAQ;GAChB,MAAM,QAAQ;GACd,QAAQ,QAAQ;GAChB,OAAO,QAAQ;GACf,YAAY,QAAQ;GACpB,UAAU,QAAQ;EAQtB,CAAC;EACD,MAAM,EAAE,SAAS,MAAM,eAAe,yBAAyB,SAAS,SAAS,EAAE,YAAY,QAAQ,WAAW,CAAC;EACnH,OAAO;GAAE;GAAS;GAAM,GAAI,WAAW,SAAS,KAAK,EAAE,WAAW;EAAG;CACzE;CAGA,OAAO,MAAM,sBAAsB,QAAQ,4BAA4B;EACnE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC5D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ,KAAA;EAC9C,OAAO,iBAAiB,SAAS,MAAM,QAChC,MAAM,iBAAiB,QAAQ,MAAM,MAAM,UAAU,OAAO,MAAM,KAAK,IACxE,KAAA;CACV,CAAC;CAGD,MAAM,eAAe,oBAAoB,KAAK;CAC9C,IAAI,cACA,OAAO,EAAE,SAAS,sBAAsB,QAAQ,KAAK,eAAe;CAIxE,OAAO,EAAE,SAAS,4BAA4B,QAAQ,mCAAmC;AAC7F"}
1
+ {"version":3,"file":"pg-error-utils-80uTIHQs.js","names":[],"sources":["../src/utils/pg-error-utils.ts"],"sourcesContent":["/**\n * Shared PostgreSQL error extraction and user-friendly message formatting.\n *\n * Drizzle wraps native PG errors in a `.cause` chain. These utilities\n * unwrap that chain to get the real PostgreSQL error (identified by a\n * 5-character alphanumeric `code` such as `42P01`) and translate it into\n * a message that is safe and helpful to show to end-users.\n */\n\nimport { DATABASE_UNAVAILABLE_MESSAGE, declaredErrorAnswer, isDatabaseUnreachable, logger } from \"@rebasepro/server\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { extractCauseMessage } from \"./error-cause\";\n\n/**\n * Shape of a deliberate client-facing error — `ApiError` from\n * `@rebasepro/server`, `RebaseApiError` from `@rebasepro/types`, or anything\n * else carrying a 4xx `statusCode`.\n *\n * Matched structurally rather than with `instanceof`: `@rebasepro/server` can\n * be loaded twice (published dist vs. workspace source), which breaks class\n * identity — `PersistService` hedges against the same thing by also accepting\n * `name === \"ApiError\"`.\n */\ninterface ClientFacingError extends Error {\n statusCode?: number;\n code?: string;\n /** See `ApiError.expected` — routine outcomes log at debug, not warn. */\n expected?: boolean;\n}\n\n/**\n * Return the error when it is a deliberate 4xx, otherwise null.\n *\n * A thrown `ApiError` is a decision the server made about the request, not a\n * database failure: its message and code are already written for the client.\n *\n * So is a `RebaseApiError` — what a collection callback throws, since a\n * collection file cannot import the server package. It spells its status\n * `status`, and reading only `statusCode` here turned an `afterRead` that\n * refused with a 403 into \"Could not load data … Check server logs\" on a\n * subscription, where REST and the socket's own requests answer the 403.\n * Recognised by the predicate those doors use, `declaredErrorAnswer`.\n */\nfunction asClientFacingError(error: unknown): Pick<ClientFacingError, \"statusCode\" | \"code\" | \"message\" | \"expected\"> | null {\n const answer = declaredErrorAnswer(error);\n if (answer) {\n if (answer.status < 400 || answer.status >= 500) return null;\n return { statusCode: answer.status, code: answer.code, message: answer.message, expected: answer.expected };\n }\n if (!(error instanceof Error)) return null;\n const e = error as ClientFacingError;\n if (typeof e.statusCode !== \"number\" || e.statusCode < 400 || e.statusCode >= 500) return null;\n return e;\n}\n\n/** Shape of PostgreSQL errors with diagnostic metadata. */\nexport interface PostgresError extends Error {\n code?: string;\n detail?: string;\n hint?: string;\n constraint?: string;\n column?: string;\n table?: string;\n dataType?: string;\n cause?: unknown;\n}\n\n/**\n * Extract the underlying PostgreSQL error from a Drizzle wrapper.\n * Drizzle wraps PG errors in a `cause` property — this function\n * recursively walks the chain until it finds an object with a PG\n * error code (5-char alphanumeric, e.g. `42P01`).\n */\nexport function extractPgError(error: unknown): PostgresError | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) {\n // Check non-Error objects for a cause chain (Drizzle sometimes wraps oddly)\n if (\"cause\" in error && (error as Record<string, unknown>).cause && typeof (error as Record<string, unknown>).cause === \"object\") {\n return extractPgError((error as Record<string, unknown>).cause);\n }\n return null;\n }\n\n // Check if the error itself has a PG error code\n if (\"code\" in error && typeof (error as PostgresError).code === \"string\" && /^[0-9A-Z]{5}$/.test((error as PostgresError).code!)) {\n return error as PostgresError;\n }\n\n // Check the cause chain (Drizzle wraps PG errors)\n if (error.cause && typeof error.cause === \"object\") {\n return extractPgError(error.cause);\n }\n\n return null;\n}\n\n/**\n * Whether the failure came back from Postgres rather than from building the\n * query — which decides whether a fallback query is worth issuing.\n *\n * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds\n * RLS). Once a statement raises, that transaction is aborted, and every later\n * statement on it returns `25P02` — \"current transaction is aborted, commands\n * ignored until end of transaction block\". So a retry after a database error\n * cannot succeed, and it replaces a precise diagnosis (\"invalid input syntax\n * for type uuid\") with a generic one. Rethrow instead.\n *\n * A query the driver could not even build — a missing reciprocal relation, say\n * — never reached Postgres, leaves the transaction usable, and is exactly what\n * the fallback paths exist for.\n */\nexport function reachedDatabase(error: unknown): boolean {\n return extractPgError(error) !== null;\n}\n\n// In its own module so the driver CLI can use it without loading the server\n// (this file imports `@rebasepro/server`).\nexport { extractCauseMessage };\n\n/**\n * Codes that mean \"this connection will never work as configured\".\n *\n * A wrong password or a database that does not exist is a settled fact about\n * the connection string, not a transient fault — retrying produces the same\n * answer forever.\n */\nconst UNRECOVERABLE_CONNECT_CODES = new Set([\n \"28P01\", // invalid_password\n \"28000\", // invalid_authorization_specification\n \"3D000\", // invalid_catalog_name — the database does not exist\n \"42501\" // insufficient_privilege\n]);\n\nexport interface ConnectFailure {\n /** True when retrying cannot help: the connection string itself is wrong. */\n fatal: boolean;\n /** The deepest message available — the Postgres one where there is one. */\n reason: string;\n /** The `SQLSTATE`, when the failure came from Postgres rather than the socket. */\n code?: string;\n}\n\n/**\n * Describe a failed connection attempt in terms a developer can act on.\n *\n * The error a caller catches is Drizzle's wrapper: its message is\n * `Failed query: SELECT 1` and its stack runs through drizzle internals, while\n * the sentence that says what is actually wrong — \"password authentication\n * failed for user …\", \"database … does not exist\" — sits in `.cause`. Logging\n * the wrapper, as the bootstrapper used to, tells a developer with a typo in\n * their `DATABASE_URL` nothing at all.\n */\nexport function classifyConnectFailure(error: unknown): ConnectFailure {\n const pgError = extractPgError(error);\n const reason =\n pgError?.message ??\n extractCauseMessage(error) ??\n (error instanceof Error ? error.message : String(error));\n return {\n fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),\n reason,\n code: pgError?.code\n };\n}\n\n/**\n * Detect whether an error is specifically a role-switching permission failure\n * (e.g. \"permission denied to set role\" or \"must be member of role\"),\n * as opposed to a table-level permission denial.\n *\n * This is used by the backend driver to auto-disable role switching when the\n * connection user lacks SET ROLE privileges, rather than surfacing a confusing\n * error to the Studio SQL Editor user.\n */\nexport function isRoleSwitchingPermissionError(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n const msg = pgError.message.toLowerCase();\n return msg.includes(\"set role\") || msg.includes(\"member of role\");\n}\n\n/**\n * Was this `42501` the *caller* being refused by a policy, rather than the\n * server lacking a privilege?\n *\n * Both arrive as `insufficient_privilege`, and they are opposite kinds of\n * problem. A row-level-security refusal is a working access-control system\n * doing its job: the caller asked for something their policies do not permit,\n * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being\n * wrong — the connection role cannot touch the table at all, no policy is\n * involved, and nothing the caller changes about the request will help.\n *\n * Postgres distinguishes them in the message, so this does too:\n *\n * new row violates row-level security policy for table \"notes\" → the caller\n * permission denied for table notes → the server\n *\n * Only writes reach this. A read that RLS excludes is not an error — the rows\n * are filtered and the caller gets an empty page — so the erroring case is\n * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.\n *\n * Matched on the message because that is the only thing carrying the\n * distinction; the SQLSTATE is identical either way. Narrow by design: anything\n * not naming row-level security stays the server's problem, since reporting a\n * genuine privilege misconfiguration as \"forbidden\" would send an operator\n * hunting for a policy bug that does not exist.\n */\nexport function isRowLevelSecurityDenial(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n return pgError.message.toLowerCase().includes(\"row-level security policy\");\n}\n\n/**\n * One constraint the database refused, named in the caller's vocabulary.\n *\n * `field` is the **wire** name, derived from the physical column: `author_id`\n * on the table is `authorId` on the row and in the request body, and telling a\n * caller their `author_id` is missing sends them looking for a key their client\n * has never seen. `code` is the SQLSTATE, which is stable, documented by\n * Postgres and the same in every environment — unlike the message, which is\n * deliberately thinner in production.\n *\n * Deliberately no `value`. The column name is safe to publish: it is already in\n * the OpenAPI, the generated SDK and the caller's own request. The *value* is\n * not — `23505`'s detail reads `Key (email)=(a@b.c) already exists.`, which\n * answers \"is this person registered?\" for any address on a table whose rows\n * RLS is otherwise hiding completely.\n */\nexport interface PgFieldViolation {\n field: string;\n code: string;\n}\n\n/**\n * The physical column names a Postgres error is about.\n *\n * Postgres puts one in `column` for `23502` and nowhere else, so the rest are\n * read out of the two places that do carry them:\n *\n * - `detail` — `Key (author_id)=(9) is not present in table \"authors\".` and\n * `Key (email, tenant_id)=(…) already exists.` Only the parenthesised column\n * list is read; the values after `=` are never touched.\n * - `constraint` — `users_email_key`, `posts_author_id_fkey`. The table prefix\n * and the constraint suffix are stripped, leaving the columns joined by `_`,\n * which is ambiguous for multi-column constraints and is therefore only used\n * when `detail` gave nothing.\n *\n * `22P02` carries neither, because an invalid literal fails during parse rather\n * than against a constraint. Its message names the *type*, and an enum type is\n * generated as `<table>_<column>` — which is the one case worth decoding,\n * because a value outside an enum's labels is the most common 22P02 anyone\n * hits and the least legible one.\n */\nfunction offendingColumns(pgError: PostgresError, collection?: CollectionConfig): string[] {\n if (pgError.column) return [pgError.column];\n\n const detail = pgError.detail;\n if (detail) {\n const keyed = /Key \\(([^)]+)\\)=/.exec(detail);\n if (keyed) {\n return keyed[1].split(\",\").map(part => part.trim().replace(/^\"|\"$/g, \"\")).filter(Boolean);\n }\n }\n\n if (pgError.code === \"22P02\") {\n // `invalid input value for enum posts_status: \"archived\"`\n const enumType = /invalid input value for enum ([^:\\s]+)/i.exec(pgError.message ?? \"\");\n if (enumType && collection) {\n const typeName = enumType[1].replace(/^.*\\./, \"\").replace(/\"/g, \"\");\n const table = getTableName(collection);\n if (typeName.startsWith(`${table}_`)) return [typeName.slice(table.length + 1)];\n }\n return [];\n }\n\n const constraint = pgError.constraint;\n if (constraint && collection) {\n const table = getTableName(collection);\n const stripped = constraint\n .replace(new RegExp(`^${table}_`), \"\")\n .replace(/_(pkey|key|fkey|unique|check|excl|idx)$/, \"\");\n // Only when it names something the collection actually has: a\n // hand-written constraint name is not a column list, and guessing at one\n // would put a field in the response that does not exist.\n if (stripped && stripped !== constraint) {\n const columns = new Set<string>();\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n columns.add((prop as { columnName?: string })?.columnName ?? key);\n }\n if (columns.has(stripped)) return [stripped];\n const wire = fieldKeyForColumn(collection, stripped);\n if (collection.properties && wire in collection.properties) return [stripped];\n }\n }\n\n return [];\n}\n\n/**\n * The fields a Postgres error is about, for `details.violations`.\n *\n * Only the four SQLSTATEs that describe *the caller's data*: a missing value, a\n * duplicate, a bad literal, a foreign key pointing at nothing. Everything else\n * — a dropped connection, a missing table, a privilege problem — is the\n * deployment's, and naming a field for it would send the reader to the wrong\n * place.\n *\n * Empty when the collection is unknown or the column cannot be recovered. An\n * empty list is the honest answer; inventing a field is worse than saying\n * nothing, because a form will mark the wrong input red.\n */\nexport function pgFieldViolations(\n pgError: PostgresError,\n collection?: CollectionConfig\n): PgFieldViolation[] {\n const code = pgError.code;\n if (code !== \"23502\" && code !== \"23505\" && code !== \"22P02\" && code !== \"23503\") return [];\n // Without the collection there is no mapping, only a guess. `toWireKey`\n // would get the default case right and silently invent a field for any\n // property carrying an explicit `columnName` — and a form pointed at an\n // input that does not exist is worse off than one shown the raw column.\n if (!collection) return [];\n const columns = offendingColumns(pgError, collection);\n if (columns.length === 0) return [];\n return columns.map(column => ({\n field: fieldKeyForColumn(collection, column),\n code\n }));\n}\n\n/**\n * What a missing table or column most often means: the database is behind the\n * collections. Both ways of catching it up, because \"run migrations\" alone\n * sent a project on the managed development database — which nobody\n * migrates — the wrong way.\n */\nconst SCHEMA_BEHIND =\n \"Check that the database is up to date with the collections: `rebase db push` in development, \" +\n \"or `rebase db migrate` where migrations are used.\";\n\n/**\n * Translate a raw PostgreSQL error into a user-friendly message.\n *\n * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})\n * @param context - A human-readable context string (e.g. collection slug or path)\n * @returns An object with a `message` safe for the client and the PG `code`.\n */\nexport function pgErrorToFriendlyMessage(\n pgError: PostgresError,\n context: string,\n options: { verbose?: boolean; collection?: CollectionConfig } = {}\n): { message: string; code: string; violations: PgFieldViolation[] } {\n // Postgres's own `DETAIL` and `HINT`, and the raw driver message, are what\n // make these errors useful while you are building — and what makes them an\n // oracle once the server is answering strangers.\n //\n // The sharp one is `23505`: its detail reads `Key (email)=(a@b.c) already\n // exists.`, which answers \"is this person registered?\" for any address, on\n // a table whose rows RLS is otherwise hiding completely. The rest leak\n // physical column and constraint names, which are the map for the next\n // question. So in production the shape of the failure is served — what\n // rule was broken, and where — and the values are not.\n //\n // The full text is not lost: the caller logs the original error. This\n // decides what crosses the wire, not what is recorded.\n const verbose = options.verbose ?? process.env.NODE_ENV !== \"production\";\n\n const detail = verbose ? (pgError.detail as string | undefined) : undefined;\n const hint = verbose ? (pgError.hint as string | undefined) : undefined;\n const constraint = pgError.constraint as string | undefined;\n const column = pgError.column as string | undefined;\n const table = pgError.table as string | undefined;\n const dataType = verbose ? (pgError.dataType as string | undefined) : undefined;\n const rawMessage = pgError.message || \"Unknown database error\";\n const pgMessage = verbose ? rawMessage : \"\";\n const code = pgError.code || \"UNKNOWN\";\n\n // Which *field* the caller has to fix, derived from the column. Safe in\n // production — a column name is already published in the OpenAPI and the\n // generated SDK — where the value that broke the rule is not, and is never\n // included. See `pgFieldViolations`.\n const violations = pgFieldViolations(pgError, options.collection);\n\n const suffix = hint ? ` Hint: ${hint}` : \"\";\n const tableRef = table ?? context;\n\n /** `\": <postgres said>\"`, or nothing when the details are withheld. */\n const said = pgMessage ? `: ${pgMessage}` : \"\";\n\n switch (pgError.code) {\n case \"23503\": // foreign_key_violation\n return {\n message: detail\n ? `Foreign key constraint violated: ${detail}${suffix}`\n : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23001\": // restrict_violation\n // A row other rows still point at, under `ON DELETE RESTRICT` — the\n // default for a required link. `table` is the *referencing* table,\n // which is the one the caller has to clear or reassign first.\n return {\n message: `Cannot complete operation: rows in \"${table ?? \"another table\"}\" still reference this row in ` +\n `\"${context}\", and their foreign key${constraint ? ` (${constraint})` : \"\"} does not allow it to be ` +\n `deleted or its key changed. Delete or reassign those rows first.${detail ? ` ${detail}` : \"\"}${suffix}`,\n code,\n violations\n };\n case \"23505\": // unique_violation\n return {\n message: detail\n ? `Duplicate value: ${detail}${suffix}`\n : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23502\": {\n // not_null_violation. The message names the *field* when the\n // collection is known, because that is the key the caller sent and\n // the only one they can act on: told `author_id` is missing, they go\n // looking for a key their generated client has never mentioned.\n const named = violations[0]?.field ?? column ?? \"unknown\";\n return {\n message: `Missing required field: \"${named}\" in \"${tableRef}\" cannot be empty.${suffix}`,\n code,\n violations\n };\n }\n case \"23514\": // check_violation\n return {\n message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"22P02\": // invalid_text_representation (e.g. invalid UUID, wrong enum value)\n return {\n message: `Invalid data format in \"${context}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22001\": // string_data_right_truncation (value too long)\n return {\n message: `Value too long for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22003\": // numeric_value_out_of_range\n return {\n message: `Numeric value out of range for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"42703\": // undefined_column\n return {\n message: `Unknown column in \"${tableRef}\"${said}. ${SCHEMA_BEHIND}${suffix}`,\n code,\n violations\n };\n case \"42P01\": // undefined_table\n return {\n message: `Table not found for \"${context}\"${said}. ${SCHEMA_BEHIND}${suffix}`,\n code,\n violations\n };\n case \"42501\": // insufficient_privilege\n // Two unrelated failures share this SQLSTATE, and the old message\n // named both causes because it could not tell them apart — which\n // meant it was half wrong whichever one had happened, and sent the\n // reader to check the other. Postgres says which in its own message.\n return rawMessage.toLowerCase().includes(\"row-level security policy\")\n ? {\n // The caller. Their policies do not permit this row; the\n // deployment is working exactly as configured.\n message: `Not permitted to write this row in \"${tableRef}\": it does not satisfy the row-level security policy.${suffix}`,\n code,\n violations\n }\n : {\n // The deployment. No policy is involved — the connecting\n // role cannot touch the table at all.\n message: `Permission denied on \"${tableRef}\": the database role this server connects as lacks privileges on it.${suffix}`,\n code,\n violations\n };\n case \"28000\": // invalid_authorization_specification\n return {\n message: `Authorization failed for \"${context}\". Check your database credentials.${suffix}`,\n code,\n violations\n };\n default: {\n // Unhandled PG code — still surface the actual database message\n const parts = [`Database error in \"${context}\" [${code}]${said}`];\n if (detail) parts.push(`Detail: ${detail}`);\n if (column) parts.push(`Column: ${column}`);\n if (dataType) parts.push(`Data type: ${dataType}`);\n if (constraint) parts.push(`Constraint: ${constraint}`);\n if (hint) parts.push(`Hint: ${hint}`);\n return { message: parts.join(\". \"), code, violations };\n }\n }\n}\n\n/**\n * Sanitize any error into a message safe and helpful for the client.\n *\n * A deliberate 4xx (`ApiError`) passes through untouched — the server already\n * decided what the client should read. Otherwise the PG error is extracted\n * from the Drizzle cause chain, falling back to a generic message that\n * doesn't leak SQL.\n *\n * @param error - The raw caught error\n * @param context - A human-readable context string (e.g. collection path)\n * @returns An object with `message` (user-friendly) and optional `code`\n * (the `ApiError` code, or the PG SQLSTATE).\n */\nexport function sanitizeErrorForClient(\n error: unknown,\n context: string,\n options: { collection?: CollectionConfig } = {}\n): { message: string; code?: string; violations?: PgFieldViolation[] } {\n // ── A deliberate 4xx is not a database failure ──────────────────\n // Its message and code are written for the client; replacing them with\n // \"Check server logs\" would discard the only diagnosis the caller gets\n // (e.g. the offending filter field and the collection's valid ones).\n // Log level follows the same convention as the HTTP error handler in\n // @rebasepro/server: routine outcomes at debug, everything else at warn.\n const clientError = asClientFacingError(error);\n if (clientError) {\n const line = `[API ${clientError.statusCode} ${clientError.code ?? \"BAD_REQUEST\"}] in \"${context}\": ${clientError.message}`;\n if (clientError.expected) {\n logger.debug(line);\n } else {\n logger.warn(`⚠️ ${line}`);\n }\n return { message: clientError.message, ...(clientError.code && { code: clientError.code }) };\n }\n\n // ── The database unreachable: the answer every door gives then ──\n // Ahead of the SQLSTATE arm, because `57P01` is a SQLSTATE that says the\n // connection is gone rather than that the statement was wrong.\n if (isDatabaseUnreachable(error)) {\n logger.warn(`[DB] The database is unreachable; \"${context}\" could not be read`);\n return { message: DATABASE_UNAVAILABLE_MESSAGE, code: \"DATABASE_UNAVAILABLE\" };\n }\n\n // ── Always log the full, unsanitized error server-side ──────────\n const pgError = extractPgError(error);\n\n if (pgError) {\n logger.error(`[PG ${pgError.code}] Error in \"${context}\"`, {\n code: pgError.code,\n message: pgError.message,\n detail: pgError.detail,\n hint: pgError.hint,\n column: pgError.column,\n table: pgError.table,\n constraint: pgError.constraint,\n dataType: pgError.dataType\n // The outer Drizzle wrapper message used to be logged here \"for\n // full context\": it is `Failed query: <sql>\\nparams: <values>`, so\n // it published the statement and every bound value (an email, a\n // password hash) on every realtime data failure. The SQLSTATE,\n // detail, table, column and constraint above are the diagnostic\n // value; the wrapper added only the leak. `logger` strips the\n // wrapper as well, but the field itself carried nothing else.\n });\n const { message, code, violations } = pgErrorToFriendlyMessage(pgError, context, { collection: options.collection });\n return { message, code, ...(violations.length > 0 && { violations }) };\n }\n\n // No PG error found — log the raw error as-is\n logger.error(`Database error in \"${context}\" (no PG error extracted)`, {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n cause: error instanceof Error && error.cause\n ? (error.cause instanceof Error ? error.cause.message : String(error.cause))\n : undefined\n });\n\n // Try to get the deepest cause message\n const causeMessage = extractCauseMessage(error);\n if (causeMessage) {\n return { message: `Database error in \"${context}\": ${causeMessage}` };\n }\n\n // Last resort — generic message, never leak raw SQL\n return { message: `Could not load data for \"${context}\". Check server logs for details.` };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,oBAAoB,OAAgG;CACzH,MAAM,SAAS,oBAAoB,KAAK;CACxC,IAAI,QAAQ;EACR,IAAI,OAAO,SAAS,OAAO,OAAO,UAAU,KAAK,OAAO;EACxD,OAAO;GAAE,YAAY,OAAO;GAAQ,MAAM,OAAO;GAAM,SAAS,OAAO;GAAS,UAAU,OAAO;EAAS;CAC9G;CACA,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CACtC,MAAM,IAAI;CACV,IAAI,OAAO,EAAE,eAAe,YAAY,EAAE,aAAa,OAAO,EAAE,cAAc,KAAK,OAAO;CAC1F,OAAO;AACX;;;;;;;AAoBA,SAAgB,eAAe,OAAsC;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,IAAI,EAAE,iBAAiB,QAAQ;EAE3B,IAAI,WAAW,SAAU,MAAkC,SAAS,OAAQ,MAAkC,UAAU,UACpH,OAAO,eAAgB,MAAkC,KAAK;EAElE,OAAO;CACX;CAGA,IAAI,UAAU,SAAS,OAAQ,MAAwB,SAAS,YAAY,gBAAgB,KAAM,MAAwB,IAAK,GAC3H,OAAO;CAIX,IAAI,MAAM,SAAS,OAAO,MAAM,UAAU,UACtC,OAAO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,sBAAsB,QAAQ,KAAK,eAAe;CAIxE,OAAO,EAAE,SAAS,4BAA4B,QAAQ,mCAAmC;AAC7F"}
@@ -1,34 +1,3 @@
1
- /**
2
- * A request's transaction, opened in the same round trip as its first query.
3
- *
4
- * Every request runs in a transaction that starts with two statements of its
5
- * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
6
- * and drops to the restricted role (`authContextStatement`). Sent one after
7
- * the other, each waits for the last, and a lone read paid four round trips —
8
- * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
9
- * one. Against a database a few milliseconds away that is most of the request.
10
- *
11
- * Postgres accepts several statements in one batch: the extended protocol's
12
- * Parse/Bind/Execute for each, then one Sync. The server runs them in order
13
- * and answers them together, so this sends nothing when the transaction is
14
- * opened and puts its opening statements in front of the first query instead.
15
- * Should one of them fail, the server skips the rest up to the Sync: a refused
16
- * role switch fails the batch before the query runs, with the same error a
17
- * statement of its own would have raised.
18
- *
19
- * A read-only transaction at READ COMMITTED goes one step further. Each of its
20
- * statements reads its own snapshot, so running each statement in a batch of
21
- * its own with the context in front — a transaction that ends at the Sync —
22
- * is the same transaction as far as anything inside it can tell, minus the
23
- * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
24
- * statement that only means something inside a transaction block (a
25
- * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
26
- * one, from that statement on.
27
- *
28
- * Statement values are serialized by pg's own `prepareValue`, so a value means
29
- * the same here as in any other query; rows are parsed with the query's own
30
- * type parsers, as pg's `Query` parses them.
31
- */
32
1
  import pg, { type Connection, type FieldDef, type Pool, type PoolClient, type QueryResult, type Submittable } from "pg";
33
2
  import { NodePgDatabase, NodePgTransaction } from "drizzle-orm/node-postgres";
34
3
  import { type PgTransactionConfig } from "drizzle-orm/pg-core";
@@ -52,8 +21,9 @@ interface ClientQueryConfig {
52
21
  type ResultCallback = (error: Error | null, result?: QueryResult) => void;
53
22
  /**
54
23
  * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
55
- * Sync, one round trip. The last statement's result is the batch's; the
56
- * others are run for their effect and their rows are dropped unparsed.
24
+ * Sync, one round trip. The result is the one statement's the caller asked
25
+ * for (`last`); the statements around it are run for their effect and their
26
+ * rows are dropped unparsed.
57
27
  *
58
28
  * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
59
29
  * nothing for it but what `submit` writes, and hands it each message the
@@ -71,8 +41,10 @@ export declare class PipelinedQuery implements Submittable {
71
41
  }[];
72
42
  private readonly rowMode;
73
43
  private readonly types;
74
- /** Statements ahead of the last whose completion has not arrived yet. */
44
+ /** Statements ahead of the result's whose completion has not arrived yet. */
75
45
  private ahead;
46
+ /** Whether the result's statement has completed: what follows it is not the result. */
47
+ private answered;
76
48
  private fields;
77
49
  private parsers;
78
50
  private readonly rows;
@@ -81,7 +53,7 @@ export declare class PipelinedQuery implements Submittable {
81
53
  private oid;
82
54
  private rowError;
83
55
  private settled;
84
- constructor(lead: readonly PipelineStatement[], last: ClientQueryConfig, callback: ResultCallback);
56
+ constructor(lead: readonly PipelineStatement[], last: ClientQueryConfig, callback: ResultCallback, trail?: readonly PipelineStatement[]);
85
57
  submit(connection: Connection): void;
86
58
  handleRowDescription(message: {
87
59
  fields: FieldDef[];
@@ -98,14 +70,29 @@ export declare class PipelinedQuery implements Submittable {
98
70
  handleError(error: Error): void;
99
71
  handleReadyForQuery(): void;
100
72
  }
101
- /** Send `lead` and then `last` in one round trip; the result is `last`'s. */
102
- export declare function runPipelined(client: PoolClient, lead: readonly PipelineStatement[], last: ClientQueryConfig): Promise<QueryResult>;
73
+ /** Send `lead`, `last` and `trail` in one round trip; the result is `last`'s. */
74
+ export declare function runPipelined(client: PoolClient, lead: readonly PipelineStatement[], last: ClientQueryConfig, trail?: readonly PipelineStatement[]): Promise<QueryResult>;
103
75
  /**
104
76
  * Whether a transaction with these settings can run each statement in a batch
105
77
  * of its own. Read-only, at READ COMMITTED: every statement takes its own
106
78
  * snapshot there anyway, and none of them can write.
107
79
  */
108
80
  export declare function runsStatementByStatement(config: PgTransactionConfig | undefined): boolean;
81
+ /**
82
+ * Send the current transaction's `COMMIT` in the same batch as its next
83
+ * statement: for a write whose next statement is its last, so it is one round
84
+ * trip rather than two. Call it right before that statement, with nothing in
85
+ * between that could send another.
86
+ *
87
+ * `false`, with nothing changed, outside a pipelined write transaction (a
88
+ * PGlite handle, a read, no transaction at all): the caller's statement runs
89
+ * as it would have, and the transaction commits when it ends.
90
+ *
91
+ * Nothing sent after that statement belongs to its transaction: it opens a
92
+ * new one, with the same opening. So only the reads that explain why a write
93
+ * changed nothing may follow it — the write committed nothing to undo.
94
+ */
95
+ export declare function commitWithNextStatement(): boolean;
109
96
  /**
110
97
  * The drizzle handle and pg pool to run a pipelined transaction on, or
111
98
  * `undefined` for a handle that is not a drizzle database over a pg pool of
@@ -1,12 +1,13 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { a as buildSearchColumnSpec, d as searchColumnTypeSql, f as searchExtensionStatements, i as assertSearchIsPostgresOnly, p as searchHelperFunctions } from "./search-column-BM-GV6vH.js";
4
+ import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
4
5
  import { a as getPrimaryKeyName, c as isIdProperty, d as sqlExpressionText, i as getPrimaryKeyColumn, l as primaryKeyPropertyNames, n as declaresEnumType, o as getPrimaryKeyProp, r as enumLabelsOf, s as idColumnDefault, u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
5
6
  import { i as isAuthCollection, n as authUsersColumnDefinition, r as authUsersColumnSql, t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
6
7
  import { c as vectorExtensionStatement, n as buildVectorColumnSpecs, o as vectorExtensionDeclared, r as buildVectorIndexPlan } from "./vector-index-DsQ3V2d2.js";
7
- import { c as buildCollectionIndexSpecs, f as deriveIndexName, h as leadsWithColumn, p as foreignKeyIndexSpec } from "./source-fZb92pN8.js";
8
+ import { c as buildCollectionIndexSpecs, f as deriveIndexName, h as leadsWithColumn, l as collectionIndexStatement, p as foreignKeyIndexSpec } from "./source-fZb92pN8.js";
8
9
  import { REBASE_SCHEMA, hasForeignKeyOnTarget, isManyToMany, isPostgresCollectionConfig } from "@rebasepro/types";
9
- import { TENANT_INDEX_REASON, assertBeforeQueryIsPostgresOnly, compileRulePolicies, fieldKeyForColumn, findRelation, getEffectiveSecurityRules, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getTableName, getTableVarName, getTenantConfig, relationalCollections, resolveCollectionRelations, resolveJunctionSpecs, resolveStringColumnLength } from "@rebasepro/common";
10
+ import { TENANT_INDEX_REASON, assertBeforeQueryIsPostgresOnly, compileRulePolicies, fieldKeyForColumn, findRelation, getEffectiveSecurityRules, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getTableName, getTableVarName, getTenantConfig, relationalCollections, resolveCollectionRelations, resolveJunctionSpecs, resolveStringColumnLength, tenantBypassRoles } from "@rebasepro/common";
10
11
  import { generateForeignKeyName, getPolicySupersededNames, legacyForeignKeyName, toPostgresIdentifier, toSnakeCase } from "@rebasepro/utils";
11
12
  import { createHash } from "node:crypto";
12
13
  //#region src/schema/relation-names.ts
@@ -55,6 +56,53 @@ function sharedRelationName(relation, sourceCollection) {
55
56
  return fallback();
56
57
  }
57
58
  //#endregion
59
+ //#region src/schema/plan/tenant-keep-trigger.ts
60
+ /**
61
+ * `tenant`'s immutability, as a database trigger.
62
+ *
63
+ * The driver refuses an update that moves a row to another tenant
64
+ * (`TENANT_IMMUTABLE`, see `resolveTenantWrite` in `@rebasepro/common`), and
65
+ * the restrictive tenant policy cannot: a policy sees the new row or the old
66
+ * one, never both, so a caller who belongs to two tenants passes it while
67
+ * moving a row from one to the other. Every writer that is not the driver —
68
+ * SQL run as the caller (`DataDriver.sql`) above all — met only the policy.
69
+ *
70
+ * So a `BEFORE UPDATE` trigger compares the two. It applies to whoever the
71
+ * table's policies bind (`row_security_active`), which is every request role
72
+ * whatever `rls.requestRole` names it: the owner connection (migrations, the
73
+ * auth flows, a person in `psql`) keeps moving rows when it means to, as it
74
+ * always could, and so does a caller holding one of the collection's
75
+ * `bypassRoles` — the same exemption the driver makes.
76
+ *
77
+ * One function for every table, the column and the bypass roles arriving as
78
+ * trigger arguments, like `set_updated_at`. The arguments are compared with
79
+ * the catalogue's on boot (see `diffPlanAgainstCatalogue`), so a changed
80
+ * `bypassRoles` re-creates the binding rather than leaving the old list in
81
+ * force.
82
+ */
83
+ /** The one trigger function, qualified. A frozen derived name. */
84
+ var KEEP_TENANT_FN = `${REBASE_SCHEMA}.keep_tenant`;
85
+ /** The trigger's name on `table`. A frozen derived name. */
86
+ var keepTenantTriggerName = (table) => `${table}_keep_tenant`;
87
+ var keepTenantFunction = () => `CREATE OR REPLACE FUNCTION ${KEEP_TENANT_FN}() RETURNS trigger\nLANGUAGE plpgsql AS \$\$
88
+ BEGIN
89
+ IF row_security_active(TG_RELID) THEN
90
+ IF to_jsonb(OLD) -> TG_ARGV[0] IS DISTINCT FROM to_jsonb(NEW) -> TG_ARGV[0] THEN
91
+ IF NOT (string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && TG_ARGV[1:TG_NARGS - 1]) THEN
92
+ RAISE EXCEPTION 'TENANT_IMMUTABLE: an update cannot move a row of "%" to another tenant (column "%")', TG_TABLE_NAME, TG_ARGV[0]
93
+ USING ERRCODE = '42501',
94
+ HINT = 'Move it as a role listed in the collection''s tenant.bypassRoles.';
95
+ END IF;
96
+ END IF;
97
+ END IF;
98
+ RETURN NEW;
99
+ END;
100
+ \$\$;`;
101
+ /** The arguments the binding passes: the column, then each bypass role. */
102
+ var keepTenantArguments = (plan) => [plan.column, ...plan.bypassRoles ?? []];
103
+ var literal = (value) => `'${value.replace(/'/g, "''")}'`;
104
+ var createKeepTenantStatement = (plan) => `CREATE TRIGGER "${plan.name}" BEFORE UPDATE ON "${plan.schema}"."${plan.table}" FOR EACH ROW EXECUTE FUNCTION ${KEEP_TENANT_FN}(${keepTenantArguments(plan).map(literal).join(", ")});`;
105
+ //#endregion
58
106
  //#region src/schema/plan/updated-at-trigger.ts
59
107
  /**
60
108
  * `autoValue: "on_update"`, as a database trigger.
@@ -121,8 +169,8 @@ END;
121
169
  */
122
170
  var dropTriggerStatement = (plan) => `DROP TRIGGER IF EXISTS "${plan.name}" ON "${plan.schema}"."${plan.table}";`;
123
171
  var createTriggerStatement = (plan) => `CREATE TRIGGER "${plan.name}" BEFORE UPDATE ON "${plan.schema}"."${plan.table}" FOR EACH ROW EXECUTE FUNCTION ${SET_UPDATED_AT_FN}('${plan.column.replace(/'/g, "''")}');`;
124
- /** Both statements, in the order they must run. */
125
- var triggerStatements = (plan) => [dropTriggerStatement(plan), createTriggerStatement(plan)];
172
+ /** Both statements, in the order they must run — for either kind of trigger. */
173
+ var triggerStatements = (plan) => [dropTriggerStatement(plan), plan.kind === "keep-tenant" ? createKeepTenantStatement(plan) : createTriggerStatement(plan)];
126
174
  //#endregion
127
175
  //#region src/schema/plan/plan-schema.ts
128
176
  /**
@@ -493,7 +541,10 @@ var columnDefault = (propName, prop, collection, type) => {
493
541
  */
494
542
  var compileSecurityRule = (collection, rule, resolveCollection, injected, ruleKey = rule.name ?? "(unnamed)") => {
495
543
  const supersedes = getPolicySupersededNames(rule, getTableName(collection));
496
- return compileRulePolicies(collection, rule, { resolveCollection }).map((policy, index) => ({
544
+ return compileRulePolicies(collection, rule, {
545
+ resolveCollection,
546
+ adminRole: true
547
+ }).map((policy, index) => ({
497
548
  ...policy,
498
549
  ruleKey,
499
550
  injected,
@@ -549,11 +600,21 @@ var withoutLiveSupersededNames = (policies) => {
549
600
  return kept;
550
601
  });
551
602
  };
603
+ /**
604
+ * Whether a collection serves a SQL view rather than a table.
605
+ *
606
+ * A link into one is read-side only. Postgres refuses a foreign key that
607
+ * references a view ("referenced relation is not a table"), and the generated
608
+ * drizzle file declares no variable for a view, so a link into one plans no
609
+ * constraint and no generated relation. The runtime still reads it: its
610
+ * relations are built from the catalogue, which holds views.
611
+ */
612
+ var servesView = (collection) => isPostgresCollectionConfig(collection) && Boolean(collection.view);
552
613
  function planSchema(allCollections, options = {}) {
553
614
  assertSearchIsPostgresOnly(allCollections);
554
615
  assertBeforeQueryIsPostgresOnly(allCollections);
555
616
  const relational = relationalCollections(allCollections);
556
- const collections = relational.filter((c) => !(isPostgresCollectionConfig(c) && c.view));
617
+ const collections = relational.filter((c) => !servesView(c));
557
618
  const firstBySlugOrTable = /* @__PURE__ */ new Map();
558
619
  for (const c of relational) for (const key of [c.slug, getTableName(c)]) if (!firstBySlugOrTable.has(key)) firstBySlugOrTable.set(key, c);
559
620
  const resolveCollection = (slug) => firstBySlugOrTable.get(slug);
@@ -653,6 +714,7 @@ function planSchema(allCollections, options = {}) {
653
714
  for (const statement of searchHelperFunctions(table.search)) add(functions, statement);
654
715
  }
655
716
  if (triggerFunctionNeeded.value) add(functions, setUpdatedAtFunction());
717
+ if (tables.some((t) => t.triggers.some((trigger) => trigger.kind === "keep-tenant"))) add(functions, keepTenantFunction());
656
718
  return {
657
719
  schemas,
658
720
  declaredSchemas,
@@ -679,13 +741,19 @@ function planViews(collections) {
679
741
  const schema = schemaOf(collection);
680
742
  const name = getTableName(collection);
681
743
  const idColumns = Object.entries(collection.properties ?? {}).filter(([, property]) => Boolean(property.isId)).map(([key, property]) => resolveColumnName(key, property));
744
+ const materialized = collection.view.materialized === true;
682
745
  return [{
683
746
  schema,
684
747
  name,
685
748
  qualified: `${schema}.${name}`,
686
749
  query: collection.view.query.trim().replace(/;\s*$/, ""),
687
- materialized: collection.view.materialized === true,
688
- idColumns
750
+ materialized,
751
+ roles: materialized ? [...collection.view.roles ?? DEFAULT_VIEW_ROLES] : [],
752
+ idColumns,
753
+ indexes: materialized ? buildCollectionIndexSpecs(collection, resolveColumnName).map((spec) => collectionIndexStatement({
754
+ ...spec,
755
+ table: viewRowsName(name)
756
+ }).replace(/;$/, "")) : []
689
757
  }];
690
758
  });
691
759
  const named = (query, view) => new RegExp(`(^|[^A-Za-z0-9_$"])"?${escapeRegExp(view.name)}"?([^A-Za-z0-9_$"]|$)`).test(query);
@@ -715,7 +783,12 @@ function planViews(collections) {
715
783
  view.qualified,
716
784
  view.query,
717
785
  view.materialized,
718
- view.idColumns
786
+ view.idColumns,
787
+ ...view.materialized ? [
788
+ "gated",
789
+ view.roles,
790
+ view.indexes
791
+ ] : []
719
792
  ])).digest("hex").slice(0, 16)
720
793
  }));
721
794
  }
@@ -867,6 +940,8 @@ function planCollectionTable(collection, resolveCollection, triggerFunctionNeede
867
940
  const injected = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));
868
941
  const policies = withoutLiveSupersededNames(getEffectiveSecurityRules(collection).flatMap((rule, index) => compileSecurityRule(collection, rule, resolveCollection, Boolean(rule.name && injected.has(rule.name)), rule.name ?? `#${index}`)));
869
942
  const tenantIndexes = applyTenantColumnEffects(collection, columns, primaryKey, schema, table);
943
+ const keepTenant = planKeepTenantTrigger(collection, columns, schema, table);
944
+ if (keepTenant) triggers.push(keepTenant);
870
945
  settleDefaultOnDelete(collection, columns, relations);
871
946
  const indexes = [...buildCollectionIndexSpecs(collection, resolveColumnName), ...tenantIndexes];
872
947
  indexes.push(...planForeignKeyIndexes(schema, table, columns, primaryKey, indexes, (column) => {
@@ -1048,6 +1123,24 @@ function applyTenantColumnEffects(collection, columns, primaryKey, schema, table
1048
1123
  }];
1049
1124
  }
1050
1125
  /**
1126
+ * The trigger that keeps a row in its tenant, or nothing when the collection
1127
+ * declares no `tenant`. See `tenant-keep-trigger.ts` for why a policy cannot.
1128
+ */
1129
+ function planKeepTenantTrigger(collection, columns, schema, table) {
1130
+ const tenant = getTenantConfig(collection);
1131
+ if (!tenant) return void 0;
1132
+ const column = findTenantColumn(collection, columns, tenant.field);
1133
+ if (!column) return void 0;
1134
+ return {
1135
+ schema,
1136
+ table,
1137
+ column: column.column,
1138
+ name: toPostgresIdentifier(keepTenantTriggerName(table)),
1139
+ kind: "keep-tenant",
1140
+ bypassRoles: [...tenantBypassRoles(tenant)]
1141
+ };
1142
+ }
1143
+ /**
1051
1144
  * A btree on each foreign-key column of one table, where nothing already
1052
1145
  * serves the lookup — see `foreignKeyIndexSpec` for why the column needs one.
1053
1146
  *
@@ -1174,7 +1267,7 @@ function planRelationColumn(propName, prop, collection, relations, schema, table
1174
1267
  unique: prop.validation?.unique === true,
1175
1268
  columnOwnedByProperty: columnOwnedByProperty || void 0,
1176
1269
  legacyColumn: derived && legacyKey !== relation.localKey ? legacyKey : void 0,
1177
- foreignKey: foreignKeyPlan({
1270
+ foreignKey: servesView(target) ? void 0 : foreignKeyPlan({
1178
1271
  schema,
1179
1272
  table,
1180
1273
  column: relation.localKey,
@@ -1204,7 +1297,7 @@ function planReferenceColumn(propName, prop, collection, resolveCollection, sche
1204
1297
  nullable: !required,
1205
1298
  primaryKey: false,
1206
1299
  unique: prop.validation?.unique === true,
1207
- foreignKey: target ? foreignKeyPlan({
1300
+ foreignKey: target && !servesView(target) ? foreignKeyPlan({
1208
1301
  schema,
1209
1302
  table,
1210
1303
  column,
@@ -1303,7 +1396,7 @@ function planJunctionTable(tableName, reachedRelation, reachedSource, junctionSp
1303
1396
  primaryKey: false,
1304
1397
  unique: false,
1305
1398
  legacyColumn: legacyFor(collection, column),
1306
- foreignKey: foreignKeyPlan({
1399
+ foreignKey: servesView(collection) ? void 0 : foreignKeyPlan({
1307
1400
  schema,
1308
1401
  table,
1309
1402
  column,
@@ -1397,6 +1490,7 @@ function planRelations(collections, tableEntries) {
1397
1490
  references: [getPrimaryKeyName(source, via)]
1398
1491
  });
1399
1492
  if (inverseRelationName === owningRelationName) continue;
1493
+ if (servesView(target)) continue;
1400
1494
  plans.push({
1401
1495
  tableVar,
1402
1496
  key: relation.through.targetColumn,
@@ -1417,6 +1511,7 @@ function planRelations(collections, tableEntries) {
1417
1511
  } catch {
1418
1512
  continue;
1419
1513
  }
1514
+ if (servesView(target)) continue;
1420
1515
  const targetVar = getTableVarName(getTableName(target));
1421
1516
  const relationName = sharedRelationName(relation, collection);
1422
1517
  const dedupe = `${relationName}::${relation.kind}`;
@@ -1489,6 +1584,6 @@ function planRelations(collections, tableEntries) {
1489
1584
  return plans;
1490
1585
  }
1491
1586
  //#endregion
1492
- export { triggerStatements as a, SET_UPDATED_AT_FN as i, planSchema as n, sharedRelationName as o, quoteSqlLiteral as r, columnPgType as t };
1587
+ export { triggerStatements as a, sharedRelationName as c, SET_UPDATED_AT_FN as i, planSchema as n, KEEP_TENANT_FN as o, quoteSqlLiteral as r, keepTenantArguments as s, columnPgType as t };
1493
1588
 
1494
- //# sourceMappingURL=plan-schema-CMNWvqIa.js.map
1589
+ //# sourceMappingURL=plan-schema-CMhNYEYF.js.map