@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
@@ -1,30 +1,32 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-COuS5Fm-.js";
3
+ import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-C1zXTPJq.js";
4
4
  import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
5
- import { a as diagnoseDbError, at as extractCauseMessage, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-D8s4z_3g.js";
6
- import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BLOVXK67.js";
7
- import { t as BranchService } from "./BranchService-JiYJ_n9E.js";
8
- import { a as ensureAppRole, d as validatePolicyPgRoles, f as warnOnAnonymousGrants, i as detectConnectionPosture, l as revokeUserRoleSql, m as warnOnRoleSchemaCollision, n as applyAuthContext, o as ensureAppRoleGrants, p as warnOnLegacyRlsFunctions, r as authContextStatement, s as findExposedInternalTables, t as REBASE_USER_ROLE$1 } from "./rls-enforcement-jZTv1yci.js";
5
+ import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
6
+ import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, ot as extractCauseMessage, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-C73Qy7WJ.js";
7
+ import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-80uTIHQs.js";
8
+ import { t as BranchService } from "./BranchService-X9R505mP.js";
9
+ import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-BCGMIig3.js";
10
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-CyUCPDH8.js";
9
11
  import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
10
12
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
11
- import { n as planSchema } from "./plan-schema-CMNWvqIa.js";
12
- import { t as generateSchema } from "./generate-drizzle-schema-logic-DpFA1UVd.js";
13
- import { i as renderPgType } from "./render-ddl-CzVcbbR1.js";
14
- import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-F2GWu009.js";
15
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-D4W9o9xE.js";
16
- import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-BK--gDo6.js";
13
+ import { n as planSchema } from "./plan-schema-CMhNYEYF.js";
14
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-BBXjxm5z.js";
15
+ import { i as renderPgType } from "./render-ddl-Di-fTGti.js";
16
+ import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-DDdnjaOW.js";
17
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CbZj9ovZ.js";
18
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-h1mUO7Uu.js";
17
19
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
18
- import { t as DatabasePoolManager } from "./databasePoolManager-7hXVurmG.js";
19
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-Bx1DYarz.js";
20
- import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-4lOC0g1_.js";
20
+ import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
21
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CUqYgMvo.js";
22
+ import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-D2soazQU.js";
21
23
  import pg, { Client, DatabaseError, Pool } from "pg";
22
24
  import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
23
25
  import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
24
- import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, not, notInArray, or, relations, sql } from "drizzle-orm";
26
+ import { SQL, and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
25
27
  import { PgArray, PgDialect, PgNumeric, PgTable, PgTimestamp, PgTimestampString, PgTransaction, bigint, boolean, getTableConfig, index, integer, jsonb, pgSchema, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
26
- import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, joinConditions, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
27
- import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, REBASE_USER_ROLE, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, effectiveAccess, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, warnOnTableDdl, withRelationReferencesOnly } from "@rebasepro/common";
28
+ import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, declaredDatabaseRls, declaredRlsPolicyShape, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPercentileFraction, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, isTimeZoneName, joinConditions, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
29
+ import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, effectiveAccess, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, grantExecuteToRequestRolesSql, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, restrictedFieldNames, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, warnOnTableDdl, withRelationReferencesOnly } from "@rebasepro/common";
28
30
  import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
29
31
  import { AsyncLocalStorage } from "node:async_hooks";
30
32
  import { createHash } from "node:crypto";
@@ -821,6 +823,28 @@ function toMembershipList(value) {
821
823
  return Array.isArray(value) ? value : [value];
822
824
  }
823
825
  /**
826
+ * A list as a native array operand: one untyped parameter holding a Postgres
827
+ * array literal (`'{"1","2"}'`).
828
+ *
829
+ * Not `ARRAY[$1, $2]`: untyped parameters in an array constructor resolve to
830
+ * `text`, so against an `integer[]`, `uuid[]`, `boolean[]` or enum array there
831
+ * was no operator ("operator does not exist: integer[] @> text[]") and the
832
+ * filter was a 500. An untyped literal on one side of `@>`, `<@` or `&&` takes
833
+ * the type of the other side, so Postgres types it as the column's own array
834
+ * type. A cast to the drizzle column's type would not do: the runtime
835
+ * catalogue reads an enum array as `text[]`.
836
+ *
837
+ * Every element is quoted and escaped, so a comma, a brace or a quote in a
838
+ * value stays inside its element; a quoted element still parses as a number,
839
+ * a boolean or a uuid.
840
+ */
841
+ function nativeArrayOperand(values) {
842
+ return sql`${`{${values.map((value) => {
843
+ if (value === null || value === void 0) return "NULL";
844
+ return `"${(typeof value === "string" ? value : value instanceof Date ? value.toISOString() : typeof value === "object" ? JSON.stringify(value) : String(value)).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
845
+ }).join(",")}}`}`;
846
+ }
847
+ /**
824
848
  * `array-contains-all` (`@>`: every listed element is in the column) and
825
849
  * `array-contained-by` (`<@`: every element of the column is listed), on a
826
850
  * native array or a JSONB array. Both are containment, so a GIN index on the
@@ -838,7 +862,7 @@ function arraySetCondition(target, op, value, isNativeArray) {
838
862
  return isNativeArray ? sql`cardinality(${target}) = 0` : sql`${target} = '[]'::jsonb`;
839
863
  }
840
864
  const operator = op === "array-contains-all" ? sql`@>` : sql`<@`;
841
- return isNativeArray ? sql`${target} ${operator} ARRAY[${sql.join(values.map((v) => sql`${v}`), sql`, `)}]` : sql`${target} ${operator} ${JSON.stringify(values)}::jsonb`;
865
+ return isNativeArray ? sql`${target} ${operator} ${nativeArrayOperand(values)}` : sql`${target} ${operator} ${JSON.stringify(values)}::jsonb`;
842
866
  }
843
867
  /**
844
868
  * "The jsonb array holds at least one of `values`", as one containment test per
@@ -1010,6 +1034,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1010
1034
  };
1011
1035
  }
1012
1036
  }
1037
+ const folded = parseCaseFoldedFieldPath(field);
1038
+ if (folded) {
1039
+ const base = columnAt(folded.field);
1040
+ if (!base) throw ApiError.badRequest(`Cannot filter on "${field}": '${folded.field}' is not a column of "${collectionPath}".`, "INVALID_FILTER_FIELD");
1041
+ const text = /^(text|varchar|character|citext)/.test(base.getSQLType?.() ?? "") ? sql`${base}` : sql`${base}::text`;
1042
+ return {
1043
+ kind: "text",
1044
+ expression: folded.fn === "lower" ? sql`lower(${text})` : sql`upper(${text})`
1045
+ };
1046
+ }
1013
1047
  if (collection) {
1014
1048
  const relation = resolveCollectionRelations(collection)[field];
1015
1049
  if (relation?.kind === "belongsTo") {
@@ -1151,6 +1185,7 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1151
1185
  static compileFilterTarget(target, op, value, field, collectionPath) {
1152
1186
  if (target.kind === "column") return this.buildSingleFilterCondition(target.column, op, value);
1153
1187
  if (target.kind === "json") return this.buildJsonPathCondition(target.column, target.path, op, value);
1188
+ if (target.kind === "text") return this.buildTextCondition(target.expression, op, value, field);
1154
1189
  if (target.kind === "relation-field") return this.buildRelationFieldCondition(target, op, value, field, collectionPath);
1155
1190
  return this.buildRelationFilterCondition(target.relation, op, value, target.sourceIdColumn, target.registry, field, collectionPath);
1156
1191
  }
@@ -1191,7 +1226,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1191
1226
  case "<=": return sql`${numeric} <= ${value}`;
1192
1227
  }
1193
1228
  }
1194
- const asText = (v) => typeof v === "boolean" ? String(v) : String(v);
1229
+ return this.buildTextCondition(leaf, op, value, "a JSON path");
1230
+ }
1231
+ /**
1232
+ * A comparison against a text expression: a JSON path's leaf, or a column
1233
+ * folded to one case. Values compare as text — booleans as `->>` renders
1234
+ * them — and the membership operators compile to `= ANY` / `<> ALL` over
1235
+ * one array parameter, so a list of any length is one bound value.
1236
+ */
1237
+ static buildTextCondition(leaf, op, value, what) {
1238
+ const asText = (v) => String(v);
1195
1239
  switch (op) {
1196
1240
  case "==": return value === null || value === void 0 ? sql`${leaf} IS NULL` : sql`${leaf} = ${asText(value)}`;
1197
1241
  case "!=": return value === null || value === void 0 ? sql`${leaf} IS NOT NULL` : sql`${leaf} != ${asText(value)}`;
@@ -1210,10 +1254,10 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1210
1254
  if (value === null || value === void 0) return op === "in" ? sql`${leaf} IS NULL` : sql`${leaf} IS NOT NULL`;
1211
1255
  const values = toMembershipList(value).map(asText);
1212
1256
  if (values.length === 0) return op === "in" ? sql`FALSE` : sql`TRUE`;
1213
- const list = sql.join(values.map((v) => sql`${v}`), sql`, `);
1214
- return op === "in" ? sql`${leaf} IN (${list})` : sql`${leaf} NOT IN (${list})`;
1257
+ const list = sql.param(values);
1258
+ return op === "in" ? sql`${leaf} = ANY(${list}::text[])` : sql`${leaf} <> ALL(${list}::text[])`;
1215
1259
  }
1216
- default: throw ApiError.badRequest(`Operator "${op}" is not supported on a JSON path. Use it on the column itself.`, "INVALID_FILTER_OPERATOR");
1260
+ default: throw ApiError.badRequest(`Operator "${op}" is not supported on ${what}. Use it on the column itself.`, "INVALID_FILTER_OPERATOR");
1217
1261
  }
1218
1262
  }
1219
1263
  /**
@@ -1482,9 +1526,9 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1482
1526
  const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1483
1527
  if (op === "array-contains-any") {
1484
1528
  if (Array.isArray(value) && value.length === 0) return sql`FALSE`;
1485
- if (Array.isArray(value) && value.length > 0) return isNativeArray ? sql`${ref} && ARRAY[${sql.join(value.map((v) => sql`${v}`), sql`, `)}]` : jsonArrayContainsAny(ref, value);
1529
+ if (Array.isArray(value) && value.length > 0) return isNativeArray ? sql`${ref} && ${nativeArrayOperand(value)}` : jsonArrayContainsAny(ref, value);
1486
1530
  }
1487
- return isNativeArray ? sql`${ref} @> ARRAY[${value}]` : sql`${ref} @> ${JSON.stringify([value])}`;
1531
+ return isNativeArray ? sql`${ref} @> ${nativeArrayOperand([value])}` : sql`${ref} @> ${JSON.stringify([value])}`;
1488
1532
  };
1489
1533
  switch (op) {
1490
1534
  case "==": return {
@@ -1674,7 +1718,7 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1674
1718
  return eq(column, value);
1675
1719
  case "!=":
1676
1720
  if (value === null || value === void 0) return sql`${column} IS NOT NULL`;
1677
- return sql`${column} != ${value}`;
1721
+ return ne(column, value);
1678
1722
  case ">": return sql`${column} > ${value}`;
1679
1723
  case ">=": return sql`${column} >= ${value}`;
1680
1724
  case "<": return sql`${column} < ${value}`;
@@ -1686,16 +1730,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1686
1730
  }
1687
1731
  case "array-contains": {
1688
1732
  const meta = getColumnMeta(column);
1689
- if (meta.dataType === "array" || meta.columnType === "PgArray") return sql`${column} @> ARRAY[${value}]`;
1733
+ if (meta.dataType === "array" || meta.columnType === "PgArray") return sql`${column} @> ${nativeArrayOperand([value])}`;
1690
1734
  return sql`${column} @> ${JSON.stringify([value])}`;
1691
1735
  }
1692
1736
  case "array-contains-any": {
1693
1737
  const meta = getColumnMeta(column);
1694
1738
  const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1695
1739
  if (Array.isArray(value) && value.length === 0) return sql`FALSE`;
1696
- if (Array.isArray(value) && value.length > 0) if (isNativeArray) return sql`${column} && ARRAY[${sql.join(value.map((v) => sql`${v}`), sql`, `)}]`;
1740
+ if (Array.isArray(value) && value.length > 0) if (isNativeArray) return sql`${column} && ${nativeArrayOperand(value)}`;
1697
1741
  else return jsonArrayContainsAny(column, value);
1698
- if (isNativeArray) return sql`${column} @> ARRAY[${value}]`;
1742
+ if (isNativeArray) return sql`${column} @> ${nativeArrayOperand([value])}`;
1699
1743
  return sql`${column} @> ${JSON.stringify([value])}`;
1700
1744
  }
1701
1745
  case "array-contains-all":
@@ -2143,8 +2187,9 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
2143
2187
  if (!table[spec.column]) return void 0;
2144
2188
  const query = DrizzleConditionBuilder.normalizedTsQuery(searchString, spec);
2145
2189
  const config = sql`${spec.language}`;
2146
- const rows = spec.fields.map((f, i) => sql`(${i}, ${f.path}, ${sql.raw(f.textSql)}, ${sql.raw(f.foldedTextSql)})`);
2147
- const matchedField = spec.mode === "hybrid" ? sql`(to_tsvector(${config}::regconfig, f.txt) @@ ${query} OR ${DrizzleConditionBuilder.foldedSubstringOf(searchString, sql`f.folded`)})` : sql`to_tsvector(${config}::regconfig, f.txt) @@ ${query}`;
2190
+ const hybrid = spec.mode === "hybrid";
2191
+ const rows = spec.fields.map((f, i) => sql`(${i}, ${f.path}, ${sql.raw(f.textSql)}, ${sql.raw(hybrid ? f.foldedTextSql : f.textSql)})`);
2192
+ const matchedField = hybrid ? sql`(to_tsvector(${config}::regconfig, f.txt) @@ ${query} OR ${DrizzleConditionBuilder.foldedSubstringOf(searchString, sql`f.folded`)})` : sql`to_tsvector(${config}::regconfig, f.txt) @@ ${query}`;
2148
2193
  return sql`(
2149
2194
  SELECT coalesce(jsonb_agg(s.m ORDER BY f.ord), '[]'::jsonb)
2150
2195
  FROM (VALUES ${sql.join(rows, sql`, `)}) AS f(ord, path, txt, folded)
@@ -3078,8 +3123,6 @@ function rowInTrashError(path, key, softDelete) {
3078
3123
  * `beforeQueryConditions`) — and not of the server's own work, which reads
3079
3124
  * with no viewer at all.
3080
3125
  */
3081
- /** The roles a materialized view is served to when it names none. */
3082
- var DEFAULT_VIEW_ROLES = ["admin"];
3083
3126
  /** Whether a collection serves a view rather than a table. */
3084
3127
  function isViewCollection(collection) {
3085
3128
  return Boolean(collection && isPostgresCollectionConfig(collection) && collection.view);
@@ -3230,7 +3273,7 @@ async function beforeQueryCondition(env, collection, path, table, description, f
3230
3273
  * the gap with a single confined cast.
3231
3274
  *
3232
3275
  * Exported so `data-transformer` uses this one rather than restating the same
3233
- * fact — it wrote `query.innerJoin(...) as unknown as typeof query`, which is
3276
+ * fact — it double-cast `query.innerJoin(...)` to `typeof query`, which is
3234
3277
  * the same claim about the same drizzle behaviour in a second spelling.
3235
3278
  */
3236
3279
  function applyDynamicJoin(query, joinTable, condition) {
@@ -4686,6 +4729,43 @@ function assertRelationReadable(collection, key, relation, use) {
4686
4729
  }]
4687
4730
  });
4688
4731
  }
4732
+ /**
4733
+ * What `fingerprint()` computes over a table's row versions, from their tuple
4734
+ * headers alone: no column is read, decoded or turned into text.
4735
+ *
4736
+ * Every row version has the xmin of the transaction that wrote it: an insert
4737
+ * or an update adds a new one, a delete takes one away. The count and the xmin
4738
+ * sum alone are linear, and cancel: a transaction that deletes one row,
4739
+ * updates another and inserts a third keeps both whenever the two xmins it
4740
+ * removed add up to twice its own, which two concurrent sessions reach. So
4741
+ * each version also adds a hash of its xmin, which no such arithmetic
4742
+ * cancels: a write only ever adds versions under its own new xid, so the
4743
+ * multiset of xmins after it can never equal the one before. The xmin alone,
4744
+ * and not the ctid beside it, because a materialized view's collection is a
4745
+ * view over its stored rows that passes their `xmin` through and no `ctid`.
4746
+ */
4747
+ function rowVersionsFingerprint(xmin) {
4748
+ return sql`md5(count(*)::text || ':' || coalesce(sum(${xmin}::text::bigint), 0)::text || ':' || coalesce(sum(hashtext(${xmin}::text)::bigint), 0)::text)`;
4749
+ }
4750
+ /**
4751
+ * The column types `percentile_cont` orders by: anything that casts to
4752
+ * `double precision`, and `interval`. A text or a timestamp column is a
4753
+ * Postgres error at execution time, so it is refused before the statement.
4754
+ */
4755
+ var PERCENTILE_TYPES = /^(smallint|integer|int[248]?|bigint|smallserial|serial[248]?|bigserial|real|float[48]?|double precision|numeric|decimal|interval)\b/i;
4756
+ /**
4757
+ * Refuse a `percentile` the statement could not compute, as the 400 the REST
4758
+ * parser answers: a `p` that is not a fraction of at most three decimals (the
4759
+ * key names three, so a fourth made two percentiles share one key), or a column
4760
+ * that is not a number. Here, not only in the parser, because the in-process
4761
+ * SDK hands its aggregates straight to the driver.
4762
+ */
4763
+ function assertPercentileComputable(aggregate, column) {
4764
+ if (!isPercentileFraction(aggregate.p)) throw ApiError.badRequest(`\`percentile\` needs a fraction from 0 to 1 with at most three decimals, e.g. \`percentile(${aggregate.field ?? "field"},0.95)\`; got ${String(aggregate.p)}.`, "INVALID_AGGREGATE_SELECT");
4765
+ if (is(column, SQL)) return;
4766
+ const type = column.getSQLType();
4767
+ if (!PERCENTILE_TYPES.test(type)) throw ApiError.badRequest(`\`percentile\` is defined on a number or interval column, and '${aggregate.field}' is ${type}.`, "INVALID_AGGREGATE_SELECT");
4768
+ }
4689
4769
  var FetchService = class FetchService {
4690
4770
  db;
4691
4771
  registry;
@@ -4806,6 +4886,19 @@ var FetchService = class FetchService {
4806
4886
  return DrizzleConditionBuilder.buildFilterConditions(filter, table, collectionPath, this.filterContext(collectionPath, table));
4807
4887
  }
4808
4888
  /**
4889
+ * A filter and a logical group as conditions, compiled as a read compiles
4890
+ * them: for a write whose rows the filter chooses (`updateWhere`,
4891
+ * `deleteWhere`).
4892
+ */
4893
+ buildWriteConditions(filter, logical, table, collectionPath) {
4894
+ const conditions = filter ? this.buildFilterConditions(filter, table, collectionPath) : [];
4895
+ if (logical) {
4896
+ const condition = DrizzleConditionBuilder.buildLogicalConditions(logical, table, collectionPath, this.filterContext(collectionPath, table));
4897
+ if (condition) conditions.push(condition);
4898
+ }
4899
+ return conditions;
4900
+ }
4901
+ /**
4809
4902
  * Resolves the correct Drizzle column for sorting.
4810
4903
  * Automatically maps owning relation property keys to their underlying foreign key column.
4811
4904
  *
@@ -4824,7 +4917,7 @@ var FetchService = class FetchService {
4824
4917
  * `_score` is only meaningful for a collection that declared a `search`
4825
4918
  * block *and* for a request that carried a search string — ranking rows
4826
4919
  * against no query ranks them all at zero. Outside those two conditions it
4827
- * is an unknown field and gets the same 400 as any other typo, which is the
4920
+ * is an unknown field and gets the same 400 as every other typo, which is the
4828
4921
  * behaviour that matters: a sort that is silently dropped returns 200 with
4829
4922
  * rows in arbitrary order, and paging over that repeats and skips rows.
4830
4923
  */
@@ -5506,7 +5599,7 @@ var FetchService = class FetchService {
5506
5599
  return stripUnreadable(flatRow, collection);
5507
5600
  }
5508
5601
  }
5509
- const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
5602
+ const visibleOne = visibleColumnProjection(getTableColumns(table), collection) ?? getTableColumns(table);
5510
5603
  const result = await this.db.select(visibleOne).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
5511
5604
  if (result.length === 0) return void 0;
5512
5605
  const raw = result[0];
@@ -5667,45 +5760,75 @@ var FetchService = class FetchService {
5667
5760
  }
5668
5761
  return column;
5669
5762
  };
5763
+ const jsonLeafFor = (field, numeric) => {
5764
+ const path = field.includes("->") ? field.split(/->>?/).map((segment) => segment.trim()).filter(Boolean) : [];
5765
+ if (path.length < 2) return void 0;
5766
+ const [columnKey, ...keys] = path;
5767
+ const column = columnFor(columnKey, field);
5768
+ const sqlType = column.getSQLType?.() ?? "";
5769
+ if (sqlType !== "jsonb" && sqlType !== "json") throw ApiError.badRequest(`'${field}' reads inside '${columnKey}', which is ${sqlType || "not a JSON column"} on "${collectionPath}".`, "UNKNOWN_AGGREGATE_FIELD");
5770
+ const literal = (key) => sql.raw(`'${key.replace(/'/g, "''")}'`);
5771
+ let expression = sql`${column}`;
5772
+ for (const key of keys.slice(0, -1)) expression = sql`${expression} -> ${literal(key)}`;
5773
+ const leaf = sql`(${expression} ->> ${literal(keys[keys.length - 1])})`;
5774
+ return numeric ? sql`CASE WHEN ${leaf} ~ '^-?[0-9]+(\.[0-9]+)?$' THEN ${leaf}::numeric END` : leaf;
5775
+ };
5776
+ const NUMERIC_FUNCTIONS = /* @__PURE__ */ new Set([
5777
+ "sum",
5778
+ "avg",
5779
+ "percentile"
5780
+ ]);
5670
5781
  const selection = {};
5782
+ const groupKeys = new Set((options.groupBy ?? []).map((group) => typeof group === "string" ? group : group.key));
5783
+ const aliases = /* @__PURE__ */ new Set();
5671
5784
  for (const aggregate of options.aggregates) {
5785
+ if (aliases.has(aggregate.alias) || groupKeys.has(aggregate.alias)) throw ApiError.badRequest(`Two values of this aggregate would come back as '${aggregate.alias}'. Name one with \`as\`.`, "INVALID_AGGREGATE_SELECT", { alias: aggregate.alias });
5786
+ aliases.add(aggregate.alias);
5787
+ const filtered = aggregate.filter ? this.buildFilterConditions(aggregate.filter, table, collectionPath) : [];
5788
+ if (aggregate.filter && aggregate.fn === "fingerprint") throw ApiError.badRequest("`fingerprint()` covers the rows the query matches; narrow it with the query's own `where`.", "INVALID_AGGREGATE_SELECT");
5789
+ const filterClause = (extra) => {
5790
+ const conditions = [...extra ? [extra] : [], ...filtered];
5791
+ return conditions.length > 0 ? sql` FILTER (WHERE ${and(...conditions)})` : sql``;
5792
+ };
5672
5793
  if (aggregate.fn === "count" && !aggregate.field) {
5673
- selection[aggregate.alias] = sql`count(*)`;
5794
+ selection[aggregate.alias] = sql`count(*)${filterClause()}`;
5674
5795
  continue;
5675
5796
  }
5676
5797
  if (aggregate.fn === "fingerprint") {
5677
5798
  if (isPostgresCollectionConfig(collection) && collection.view && !collection.view.materialized) throw ApiError.badRequest(`\`fingerprint()\` reads the versions of stored rows, and "${collection.slug}" is a view that stores none. Fingerprint the tables it reads, or make it a materialized view.`, "INVALID_AGGREGATE_SELECT");
5678
- selection[aggregate.alias] = sql`md5(count(*)::text || ':' || coalesce(sum(${table}.xmin::text::bigint), 0)::text)`;
5799
+ selection[aggregate.alias] = rowVersionsFingerprint(sql`${table}.xmin`);
5679
5800
  continue;
5680
5801
  }
5681
- const column = columnFor(aggregate.field, `${aggregate.fn}()`);
5802
+ const column = jsonLeafFor(aggregate.field, NUMERIC_FUNCTIONS.has(aggregate.fn)) ?? columnFor(aggregate.field, `${aggregate.fn}()`);
5803
+ const where = filterClause();
5682
5804
  switch (aggregate.fn) {
5683
5805
  case "count":
5684
- selection[aggregate.alias] = sql`count(${column})`;
5806
+ selection[aggregate.alias] = sql`count(${column})${where}`;
5685
5807
  break;
5686
5808
  case "sum":
5687
- selection[aggregate.alias] = sql`sum(${column})::numeric`;
5809
+ selection[aggregate.alias] = sql`(sum(${column})${where})::numeric`;
5688
5810
  break;
5689
5811
  case "avg":
5690
- selection[aggregate.alias] = sql`avg(${column})::numeric`;
5812
+ selection[aggregate.alias] = sql`(avg(${column})${where})::numeric`;
5691
5813
  break;
5692
5814
  case "min":
5693
- selection[aggregate.alias] = sql`min(${column})`;
5815
+ selection[aggregate.alias] = sql`min(${column})${where}`;
5694
5816
  break;
5695
5817
  case "max":
5696
- selection[aggregate.alias] = sql`max(${column})`;
5818
+ selection[aggregate.alias] = sql`max(${column})${where}`;
5697
5819
  break;
5698
5820
  case "countDistinct":
5699
- selection[aggregate.alias] = sql`count(DISTINCT ${column})`;
5821
+ selection[aggregate.alias] = sql`count(DISTINCT ${column})${where}`;
5700
5822
  break;
5701
5823
  case "mode":
5702
- selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})`;
5824
+ selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})${where}`;
5703
5825
  break;
5704
5826
  case "percentile":
5705
- selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column}))::numeric`;
5827
+ assertPercentileComputable(aggregate, column);
5828
+ selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column})${where})::numeric`;
5706
5829
  break;
5707
5830
  case "distinct":
5708
- selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column}) FILTER (WHERE ${column} IS NOT NULL), '[]'::jsonb)`;
5831
+ selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column})${filterClause(sql`${column} IS NOT NULL`)}, '[]'::jsonb)`;
5709
5832
  break;
5710
5833
  }
5711
5834
  }
@@ -5713,7 +5836,7 @@ var FetchService = class FetchService {
5713
5836
  const groupColumns = (options.groupBy ?? []).map((group) => {
5714
5837
  if (typeof group === "string") return {
5715
5838
  field: group,
5716
- column: columnFor(group, "groupBy")
5839
+ column: jsonLeafFor(group, false) ?? columnFor(group, "groupBy")
5717
5840
  };
5718
5841
  const column = columnFor(group.field, `${group.transform}()`);
5719
5842
  return {
@@ -5778,7 +5901,13 @@ var FetchService = class FetchService {
5778
5901
  transform: group.transform
5779
5902
  });
5780
5903
  const format = group.transform === "year" ? "YYYY" : group.transform === "month" ? "YYYY-MM" : "YYYY-MM-DD";
5781
- return sql`to_char(${sqlType.includes("with time zone") ? sql`(${column} AT TIME ZONE 'UTC')` : sql`${column}`}, ${sql.raw(`'${format}'`)})`;
5904
+ if (group.timeZone !== void 0 && !isTimeZoneName(group.timeZone)) throw ApiError.badRequest(`\`${group.transform}(${group.field})\` was asked for in "${group.timeZone}", which is not a time zone. Use an IANA name such as "Europe/Madrid".`, "INVALID_AGGREGATE_GROUP", {
5905
+ field: group.field,
5906
+ transform: group.transform,
5907
+ timeZone: group.timeZone
5908
+ });
5909
+ const zone = sql.raw(`'${group.timeZone ?? "UTC"}'`);
5910
+ return sql`to_char(${sqlType.startsWith("date") ? sql`${column}` : sqlType.includes("with time zone") ? sql`(${column} AT TIME ZONE ${zone})` : group.timeZone ? sql`((${column} AT TIME ZONE 'UTC') AT TIME ZONE ${zone})` : sql`${column}`}, ${sql.raw(`'${format}'`)})`;
5782
5911
  }
5783
5912
  case "unnest": {
5784
5913
  const meta = getColumnMeta(column);
@@ -5924,7 +6053,7 @@ var FetchService = class FetchService {
5924
6053
  const projection = this.columnProjection(table, collection, options?.fields, idInfoArray);
5925
6054
  const narrowing = await this.narrowReadCondition(collectionPath, collection, table, "get", FetchService.describeRead({ fields: options?.fields }));
5926
6055
  const identity = narrowing ? and(addressed, narrowing) : addressed;
5927
- const result = await this.db.select(projection).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
6056
+ const result = await this.db.select(projection ?? getTableColumns(table)).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
5928
6057
  if (result.length === 0) return null;
5929
6058
  const row = toRestRow(result[0], collection, this.registry);
5930
6059
  if (normalizedInclude) await this.loadIncludes([row], collection, collectionPath, normalizedInclude);
@@ -5940,13 +6069,16 @@ var FetchService = class FetchService {
5940
6069
  * `toRestRow`. For a row the statement itself wrote, with nothing written
5941
6070
  * after it, `RETURNING` those same columns is that row — the same values
5942
6071
  * through the same column decoders, in the same order, rendered the same
5943
- * way. Two things narrow the read and not the statement, and either one
5944
- * keeps the read:
6072
+ * way. One thing narrows the read and not the statement, and keeps the
6073
+ * read: a `beforeQuery` adds conditions to it (and runs application code),
6074
+ * so a row outside them is no answer today, and would be one from
6075
+ * `RETURNING`.
5945
6076
  *
5946
- * - a `beforeQuery` adds conditions to the read (and runs application
5947
- * code): a row outside them is no answer today, and would be one from
5948
- * `RETURNING`;
5949
- * - per-field read access, which projects the read for the viewer.
6077
+ * Per-field read access does not: the read selects the same columns and
6078
+ * withholds what the caller may not read when it renders the row
6079
+ * (`toRestRow` → `stripUnreadable`), which is the render here too — so an
6080
+ * `excludeFromApi` column is written, and not answered, without a read
6081
+ * back per row.
5950
6082
  *
5951
6083
  * Row-level security is the same either way. `INSERT … RETURNING` holds
5952
6084
  * the new row to the table's SELECT policies and refuses one they hide
@@ -5955,7 +6087,7 @@ var FetchService = class FetchService {
5955
6087
  */
5956
6088
  insertReturning(collectionPath) {
5957
6089
  const collection = getCollectionByPath(collectionPath, this.registry);
5958
- if (hasBeforeQuery(this.registry, collection) || hasFieldAccessRules(collection)) return void 0;
6090
+ if (hasBeforeQuery(this.registry, collection)) return void 0;
5959
6091
  const table = getTableForCollection(collection, this.registry);
5960
6092
  const tableColumns = getTableColumns(table);
5961
6093
  if (!tableColumns) return void 0;
@@ -6914,60 +7046,493 @@ function runInWriteScope(scope, fn) {
6914
7046
  */
6915
7047
  globalThis[Symbol.for("rebase.server.ambientTransactionResolver")] = currentWriteScope;
6916
7048
  //#endregion
6917
- //#region src/services/PersistService.ts
7049
+ //#region src/pipelined-transaction.ts
6918
7050
  /**
6919
- * The top-level properties whose value is stamped once, when the row is
6920
- * created: `on_create` dates and `user_on_create` identities.
7051
+ * A request's transaction, opened in the same round trip as its first query.
6921
7052
  *
6922
- * What they hold is a fact about the row's creation, so a write to a row that
6923
- * already exists has nothing to say about them — an update, and the
6924
- * conflict-update of an upsert that met a stored row. Top level only: a stamp
6925
- * nested inside a `map` is part of that map's value, not a column a write can
6926
- * leave out.
7053
+ * Every request runs in a transaction that starts with two statements of its
7054
+ * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
7055
+ * and drops to the restricted role (`authContextStatement`). Sent one after
7056
+ * the other, each waits for the last, and a lone read paid four round trips —
7057
+ * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
7058
+ * one. Against a database a few milliseconds away that is most of the request.
7059
+ *
7060
+ * Postgres accepts several statements in one batch: the extended protocol's
7061
+ * Parse/Bind/Execute for each, then one Sync. The server runs them in order
7062
+ * and answers them together, so this sends nothing when the transaction is
7063
+ * opened and puts its opening statements in front of the first query instead.
7064
+ * Should one of them fail, the server skips the rest up to the Sync: a refused
7065
+ * role switch fails the batch before the query runs, with the same error a
7066
+ * statement of its own would have raised.
7067
+ *
7068
+ * A read-only transaction at READ COMMITTED goes one step further. Each of its
7069
+ * statements reads its own snapshot, so running each statement in a batch of
7070
+ * its own with the context in front — a transaction that ends at the Sync —
7071
+ * is the same transaction as far as anything inside it can tell, minus the
7072
+ * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
7073
+ * statement that only means something inside a transaction block (a
7074
+ * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
7075
+ * one, from that statement on.
7076
+ *
7077
+ * A write that knows its last statement (`commitWithNextStatement`) sends its
7078
+ * `COMMIT` in the same batch, behind it: a lone write is then `BEGIN`, the
7079
+ * context, the statement and `COMMIT` in one round trip, where it was two.
7080
+ * Should the statement fail, the server skips the `COMMIT` and the
7081
+ * transaction is rolled back like every failed one. A statement sent after it
7082
+ * opens a new transaction, with the same opening.
7083
+ *
7084
+ * Statement values are serialized by pg's own `prepareValue`, so a value means
7085
+ * the same here as in any other query; rows are parsed with the query's own
7086
+ * type parsers, as pg's `Query` parses them.
6927
7087
  */
6928
- function createStampKeys(properties) {
6929
- const keys = [];
6930
- for (const [key, property] of Object.entries(properties ?? {})) if (property?.type === "date" && property.autoValue === "on_create" || property?.type === "string" && property.autoValue === "user_on_create") keys.push(key);
6931
- return keys;
7088
+ var COMMAND_TAG = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
7089
+ /**
7090
+ * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
7091
+ * Sync, one round trip. The result is the one statement's the caller asked
7092
+ * for (`last`); the statements around it are run for their effect and their
7093
+ * rows are dropped unparsed.
7094
+ *
7095
+ * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
7096
+ * nothing for it but what `submit` writes, and hands it each message the
7097
+ * server sends back until ReadyForQuery.
7098
+ */
7099
+ var PipelinedQuery = class {
7100
+ /** How many statements this batch sends. */
7101
+ statementCount;
7102
+ /** Set by `client.query`, which wraps it for its read timeout. */
7103
+ callback;
7104
+ /** The statements, in the order they are sent, with their serialized values. */
7105
+ statements;
7106
+ rowMode;
7107
+ types;
7108
+ /** Statements ahead of the result's whose completion has not arrived yet. */
7109
+ ahead;
7110
+ /** Whether the result's statement has completed: what follows it is not the result. */
7111
+ answered = false;
7112
+ fields = [];
7113
+ parsers = [];
7114
+ rows = [];
7115
+ command = "";
7116
+ rowCount = null;
7117
+ oid = 0;
7118
+ rowError;
7119
+ settled = false;
7120
+ constructor(lead, last, callback, trail = []) {
7121
+ this.statements = [
7122
+ ...lead,
7123
+ last,
7124
+ ...trail
7125
+ ].map((statement) => ({
7126
+ text: statement.text,
7127
+ values: (statement.values ?? []).map((value) => prepareValue(value))
7128
+ }));
7129
+ this.statementCount = this.statements.length;
7130
+ this.ahead = lead.length;
7131
+ this.rowMode = last.rowMode;
7132
+ this.types = last.types ?? pg.types;
7133
+ this.callback = callback;
7134
+ }
7135
+ submit(connection) {
7136
+ connection.stream.cork();
7137
+ try {
7138
+ for (const statement of this.statements) {
7139
+ connection.parse({
7140
+ text: statement.text,
7141
+ name: "",
7142
+ types: []
7143
+ }, true);
7144
+ connection.bind({
7145
+ portal: "",
7146
+ statement: "",
7147
+ values: statement.values
7148
+ }, true);
7149
+ connection.describe({
7150
+ type: "P",
7151
+ name: ""
7152
+ }, true);
7153
+ connection.execute({ portal: "" }, true);
7154
+ }
7155
+ connection.sync();
7156
+ } finally {
7157
+ connection.stream.uncork();
7158
+ }
7159
+ }
7160
+ handleRowDescription(message) {
7161
+ if (this.ahead > 0 || this.answered) return;
7162
+ this.fields = message.fields;
7163
+ this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, "text"));
7164
+ }
7165
+ handleDataRow(message) {
7166
+ if (this.ahead > 0 || this.answered || this.rowError) return;
7167
+ const values = message.fields;
7168
+ try {
7169
+ if (this.rowMode === "array") {
7170
+ const row = new Array(values.length);
7171
+ for (let i = 0; i < values.length; i++) {
7172
+ const raw = values[i];
7173
+ row[i] = raw === null ? null : this.parsers[i](raw);
7174
+ }
7175
+ this.rows.push(row);
7176
+ } else {
7177
+ const row = {};
7178
+ for (let i = 0; i < values.length; i++) {
7179
+ const raw = values[i];
7180
+ row[this.fields[i].name] = raw === null ? null : this.parsers[i](raw);
7181
+ }
7182
+ this.rows.push(row);
7183
+ }
7184
+ } catch (error) {
7185
+ this.rowError = error instanceof Error ? error : new Error(String(error));
7186
+ }
7187
+ }
7188
+ handleCommandComplete(message) {
7189
+ if (this.ahead > 0) {
7190
+ this.ahead -= 1;
7191
+ return;
7192
+ }
7193
+ if (this.answered) return;
7194
+ this.answered = true;
7195
+ const match = COMMAND_TAG.exec(message.text);
7196
+ if (!match) return;
7197
+ this.command = match[1];
7198
+ if (match[3]) {
7199
+ this.oid = Number.parseInt(match[2], 10);
7200
+ this.rowCount = Number.parseInt(match[3], 10);
7201
+ } else if (match[2]) this.rowCount = Number.parseInt(match[2], 10);
7202
+ }
7203
+ /** An empty statement completes with EmptyQueryResponse rather than CommandComplete. */
7204
+ handleEmptyQuery() {
7205
+ if (this.ahead > 0) this.ahead -= 1;
7206
+ else this.answered = true;
7207
+ }
7208
+ handlePortalSuspended() {}
7209
+ handleError(error) {
7210
+ if (this.settled) return;
7211
+ this.settled = true;
7212
+ this.callback?.(error);
7213
+ }
7214
+ handleReadyForQuery() {
7215
+ if (this.settled) return;
7216
+ this.settled = true;
7217
+ if (this.rowError) {
7218
+ this.callback?.(this.rowError);
7219
+ return;
7220
+ }
7221
+ const result = {
7222
+ command: this.command,
7223
+ rowCount: this.rowCount,
7224
+ oid: this.oid,
7225
+ fields: this.fields,
7226
+ rows: this.rows
7227
+ };
7228
+ this.callback?.(null, result);
7229
+ }
7230
+ };
7231
+ /** Send `lead`, `last` and `trail` in one round trip; the result is `last`'s. */
7232
+ function runPipelined(client, lead, last, trail = []) {
7233
+ return new Promise((resolve, reject) => {
7234
+ client.query(new PipelinedQuery(lead, last, (error, result) => {
7235
+ if (error) reject(error);
7236
+ else if (result) resolve(result);
7237
+ }, trail));
7238
+ });
6932
7239
  }
6933
7240
  /**
6934
- * The most rows one INSERT of a batch carries, and the most values: Postgres
6935
- * takes at most 65,535 parameters in a statement.
7241
+ * A statement that means something only inside a transaction block, so a
7242
+ * read cannot run it in a batch of its own: savepoints, transaction-local
7243
+ * settings, cursors and transaction-scoped locks.
6936
7244
  */
6937
- var BATCH_MAX_ROWS = 1e3;
6938
- var BATCH_MAX_PARAMS = 3e4;
7245
+ var NEEDS_TRANSACTION_BLOCK = /^\s*(?:savepoint|release|rollback|set\s+local|set\s+transaction|declare|lock|prepare\s+transaction)\b|\bset_config\s*\(|\bpg_advisory_xact_lock|\bpg_try_advisory_xact_lock/i;
6939
7246
  /**
6940
- * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
6941
- * when nothing could catch its failure and carry on, straight on `db`.
6942
- *
6943
- * The savepoint exists for a write a hook started (`context.data`): a hook may
6944
- * catch the database refusing it, and the write it runs inside must stay
6945
- * usable. A write a caller started directly inside a request's transaction
6946
- * (frame depth 1, an open write scope) has no such catcher — the REST route,
6947
- * the socket handler and the bulk and batch loops all rethrow, and the
6948
- * request's transaction rolls back whole — so its savepoint only cost two
6949
- * round trips per row: 2,000 of a 1,000-row bulk's statements. Outside a
6950
- * request's transaction (`db` is the pool) a real transaction is still opened,
6951
- * so the row and its relation writes land together.
7247
+ * A statement pg runs with a protocol of its own: COPY streams, a named
7248
+ * statement pg keeps track of, a portal read page by page. Sent as pg sends
7249
+ * it, after the transaction's opening has gone ahead in a batch of its own.
6952
7250
  */
6953
- function inOwnTransactionUnlessTopLevel(db, write) {
6954
- if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
6955
- return db.transaction((tx) => write(tx));
7251
+ function cannotPipeline(config) {
7252
+ return Boolean(config.name) || Boolean(config.rows) || /^\s*copy\b/i.test(config.text);
6956
7253
  }
6957
- /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
6958
- function castableType(sqlType) {
7254
+ function toQueryConfig(statement) {
6959
7255
  return {
6960
- smallserial: "smallint",
6961
- serial: "integer",
6962
- bigserial: "bigint"
6963
- }[sqlType.toLowerCase()] ?? sqlType;
7256
+ text: statement.text,
7257
+ values: statement.values ? [...statement.values] : void 0
7258
+ };
7259
+ }
7260
+ function beginStatement(config) {
7261
+ const parts = ["begin"];
7262
+ if (config?.isolationLevel) parts.push(`isolation level ${config.isolationLevel}`);
7263
+ if (config?.accessMode) parts.push(config.accessMode);
7264
+ if (typeof config?.deferrable === "boolean") parts.push(config.deferrable ? "deferrable" : "not deferrable");
7265
+ return parts.join(" ");
6964
7266
  }
6965
7267
  /**
6966
- * Service for handling all row write operations.
6967
- * Handles saving, deleting, and updating rows.
7268
+ * Whether a transaction with these settings can run each statement in a batch
7269
+ * of its own. Read-only, at READ COMMITTED: every statement takes its own
7270
+ * snapshot there anyway, and none of them can write.
6968
7271
  */
6969
- var PersistService = class {
6970
- db;
7272
+ function runsStatementByStatement(config) {
7273
+ return config?.accessMode === "read only" && (config.isolationLevel === void 0 || config.isolationLevel === "read committed") && config.deferrable !== true;
7274
+ }
7275
+ /**
7276
+ * A savepoint being set or released: a statement with no result to wait for,
7277
+ * which can go out with whatever is sent next.
7278
+ */
7279
+ var DEFERRABLE = /^\s*(?:savepoint|release(?:\s+savepoint)?)\s+[A-Za-z_][A-Za-z0-9_]*\s*;?\s*$/i;
7280
+ var ROLLBACK_TO = /^\s*rollback\s+to\s+(?:savepoint\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*;?\s*$/i;
7281
+ function settledWithoutSending(text) {
7282
+ const command = text.trim().split(/\s+/)[0].toUpperCase();
7283
+ return Promise.resolve({
7284
+ command,
7285
+ rowCount: null,
7286
+ oid: 0,
7287
+ fields: [],
7288
+ rows: []
7289
+ });
7290
+ }
7291
+ var COMMIT = { text: "commit" };
7292
+ /**
7293
+ * The client side of one transaction: sends its opening with the first query,
7294
+ * holds savepoints back until a statement goes out after them, and sends
7295
+ * `COMMIT` or `ROLLBACK` only when something was sent — or sends the `COMMIT`
7296
+ * behind the statement it was told is the last.
7297
+ */
7298
+ var TransactionOpening = class {
7299
+ client;
7300
+ begin;
7301
+ opening;
7302
+ statementByStatement;
7303
+ /**
7304
+ * `fresh`: nothing sent, or what was sent has committed (the next
7305
+ * statement opens a new transaction). `implicit`: each statement ran in a
7306
+ * batch of its own. `open`: in a transaction block.
7307
+ */
7308
+ state = "fresh";
7309
+ /** In a block: statements accepted and not yet sent, which go out ahead of the next one. */
7310
+ pending = [];
7311
+ /** In a block: whether its `BEGIN` has reached the server. */
7312
+ begun = false;
7313
+ /** Whether the next statement sent carries the `COMMIT` behind it. See {@link commitWithNext}. */
7314
+ commitsWithNext = false;
7315
+ constructor(client, begin, opening, statementByStatement) {
7316
+ this.client = client;
7317
+ this.begin = begin;
7318
+ this.opening = opening;
7319
+ this.statementByStatement = statementByStatement;
7320
+ }
7321
+ /** The `query` the transaction's drizzle session calls. Decides synchronously, so concurrent calls queue in order. */
7322
+ query(config, values) {
7323
+ const statement = typeof config === "string" ? {
7324
+ text: config,
7325
+ values
7326
+ } : values !== void 0 ? {
7327
+ ...config,
7328
+ values
7329
+ } : config;
7330
+ const pipelinable = !cannotPipeline(statement);
7331
+ if (this.state !== "open") {
7332
+ if (this.statementByStatement && pipelinable && !NEEDS_TRANSACTION_BLOCK.test(statement.text)) {
7333
+ this.state = "implicit";
7334
+ return runPipelined(this.client, [READ_ONLY_STATEMENT, ...this.opening], statement);
7335
+ }
7336
+ this.state = "open";
7337
+ this.pending = [{ text: this.begin }, ...this.opening];
7338
+ }
7339
+ const rollbackTo = ROLLBACK_TO.exec(statement.text);
7340
+ if (rollbackTo) {
7341
+ const at = this.pending.findLastIndex((pending) => pending.text.trim().toLowerCase() === `savepoint ${rollbackTo[1].toLowerCase()}`);
7342
+ if (at >= 0) {
7343
+ this.pending = this.pending.slice(0, at);
7344
+ return settledWithoutSending(statement.text);
7345
+ }
7346
+ }
7347
+ if (DEFERRABLE.test(statement.text) && !statement.values?.length) {
7348
+ this.pending.push({ text: statement.text });
7349
+ return settledWithoutSending(statement.text);
7350
+ }
7351
+ return this.send(statement, pipelinable);
7352
+ }
7353
+ /**
7354
+ * Send the `COMMIT` behind the next statement, in its batch. `false`, and
7355
+ * nothing changes, for a transaction that runs each statement in a batch
7356
+ * of its own (a read has no `COMMIT` to send).
7357
+ */
7358
+ commitWithNext() {
7359
+ if (this.statementByStatement) return false;
7360
+ this.commitsWithNext = true;
7361
+ return true;
7362
+ }
7363
+ /** `statement`, with everything pending in front of it. */
7364
+ send(statement, pipelinable = true) {
7365
+ const lead = this.pending;
7366
+ this.pending = [];
7367
+ if (lead.length > 0) this.begun = true;
7368
+ if (this.commitsWithNext && pipelinable) {
7369
+ this.commitsWithNext = false;
7370
+ return runPipelined(this.client, lead, statement, [COMMIT]).then((result) => {
7371
+ this.state = "fresh";
7372
+ this.begun = false;
7373
+ return result;
7374
+ });
7375
+ }
7376
+ if (lead.length === 0) return this.client.query(statement);
7377
+ if (pipelinable) return runPipelined(this.client, lead, statement);
7378
+ return runPipelined(this.client, lead.slice(0, -1), toQueryConfig(lead[lead.length - 1])).then(() => this.client.query(statement));
7379
+ }
7380
+ async commit() {
7381
+ this.commitsWithNext = false;
7382
+ if (this.state === "open" && this.begun) await this.send({ text: "commit" });
7383
+ this.pending = [];
7384
+ }
7385
+ async rollback() {
7386
+ this.commitsWithNext = false;
7387
+ this.pending = [];
7388
+ if (this.state === "open" && this.begun) await this.client.query("rollback");
7389
+ }
7390
+ };
7391
+ /**
7392
+ * What `SET TRANSACTION READ ONLY` sets, as a statement that can run in a batch
7393
+ * outside a transaction block — where `SET TRANSACTION` warns and does nothing.
7394
+ */
7395
+ var READ_ONLY_STATEMENT = { text: "SELECT set_config('transaction_read_only', 'on', true)" };
7396
+ /** The relational schema a drizzle handle was built with, for a session over another client. */
7397
+ function schemaConfigOf(db) {
7398
+ const { schema, fullSchema, tableNamesMap } = db._;
7399
+ return schema && fullSchema ? {
7400
+ schema,
7401
+ fullSchema,
7402
+ tableNamesMap
7403
+ } : void 0;
7404
+ }
7405
+ var dialect = new PgDialect();
7406
+ /** The pipelined transaction the current async context runs in. */
7407
+ var currentTransaction = new AsyncLocalStorage();
7408
+ /**
7409
+ * Send the current transaction's `COMMIT` in the same batch as its next
7410
+ * statement: for a write whose next statement is its last, so it is one round
7411
+ * trip rather than two. Call it right before that statement, with nothing in
7412
+ * between that could send another.
7413
+ *
7414
+ * `false`, with nothing changed, outside a pipelined write transaction (a
7415
+ * PGlite handle, a read, no transaction at all): the caller's statement runs
7416
+ * as it would have, and the transaction commits when it ends.
7417
+ *
7418
+ * Nothing sent after that statement belongs to its transaction: it opens a
7419
+ * new one, with the same opening. So only the reads that explain why a write
7420
+ * changed nothing may follow it — the write committed nothing to undo.
7421
+ */
7422
+ function commitWithNextStatement() {
7423
+ return currentTransaction.getStore()?.commitWithNext() ?? false;
7424
+ }
7425
+ /**
7426
+ * The drizzle handle and pg pool to run a pipelined transaction on, or
7427
+ * `undefined` for a handle that is not a drizzle database over a pg pool of
7428
+ * this process's pg (PGlite, a transaction, a caller's own copy of either
7429
+ * library), which opens its transactions statement by statement.
7430
+ */
7431
+ function pipelineTarget(db) {
7432
+ if (!(db instanceof NodePgDatabase) || !("$client" in db)) return void 0;
7433
+ const client = db.$client;
7434
+ return client instanceof pg.Pool ? {
7435
+ db,
7436
+ pool: client
7437
+ } : void 0;
7438
+ }
7439
+ /**
7440
+ * Run `work` in a transaction on a client of `pool`, its opening sent with the
7441
+ * first query.
7442
+ *
7443
+ * `opening` runs at the start of the transaction, after the `BEGIN` that
7444
+ * `config` describes — and, for a read-only transaction at READ COMMITTED,
7445
+ * ahead of every statement, each in a transaction of its own (see the module
7446
+ * comment). `work` gets a drizzle transaction like the one
7447
+ * `db.transaction()` hands out: savepoints nest inside it, and it commits
7448
+ * when `work` resolves and rolls back when it throws.
7449
+ */
7450
+ async function runPipelinedTransaction(db, pool, opening, config, work) {
7451
+ const client = await pool.connect();
7452
+ const transaction = new TransactionOpening(client, beginStatement(config), opening, runsStatementByStatement(config));
7453
+ const sessionClient = new Proxy(client, { get(target, property) {
7454
+ if (property === "query") return transaction.query.bind(transaction);
7455
+ const value = Reflect.get(target, property, target);
7456
+ return typeof value === "function" ? value.bind(target) : value;
7457
+ } });
7458
+ const schema = schemaConfigOf(db);
7459
+ const tx = new NodePgTransaction(dialect, new NodePgSession(sessionClient, dialect, schema), schema);
7460
+ try {
7461
+ let result;
7462
+ try {
7463
+ result = await currentTransaction.run(transaction, () => work(tx));
7464
+ } catch (error) {
7465
+ await transaction.rollback();
7466
+ throw error;
7467
+ }
7468
+ await transaction.commit();
7469
+ return result;
7470
+ } finally {
7471
+ client.release();
7472
+ }
7473
+ }
7474
+ //#endregion
7475
+ //#region src/services/PersistService.ts
7476
+ /**
7477
+ * The top-level properties whose value is stamped once, when the row is
7478
+ * created: `on_create` dates and `user_on_create` identities.
7479
+ *
7480
+ * What they hold is a fact about the row's creation, so a write to a row that
7481
+ * already exists has nothing to say about them — an update, and the
7482
+ * conflict-update of an upsert that met a stored row. Top level only: a stamp
7483
+ * nested inside a `map` is part of that map's value, not a column a write can
7484
+ * leave out.
7485
+ */
7486
+ function createStampKeys(properties) {
7487
+ const keys = [];
7488
+ for (const [key, property] of Object.entries(properties ?? {})) if (property?.type === "date" && property.autoValue === "on_create" || property?.type === "string" && property.autoValue === "user_on_create") keys.push(key);
7489
+ return keys;
7490
+ }
7491
+ /**
7492
+ * The most rows one INSERT of a batch carries, and the most values: Postgres
7493
+ * takes at most 65,535 parameters in a statement.
7494
+ */
7495
+ var BATCH_MAX_ROWS = 1e3;
7496
+ var BATCH_MAX_PARAMS = 3e4;
7497
+ /**
7498
+ * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
7499
+ * when nothing could catch its failure and carry on, straight on `db`.
7500
+ *
7501
+ * The savepoint exists for a write a hook started (`context.data`): a hook may
7502
+ * catch the database refusing it, and the write it runs inside must stay
7503
+ * usable. A write a caller started directly inside a request's transaction
7504
+ * (frame depth 1, an open write scope) has no such catcher — the REST route,
7505
+ * the socket handler and the bulk and batch loops all rethrow, and the
7506
+ * request's transaction rolls back whole — so its savepoint only cost two
7507
+ * round trips per row: 2,000 of a 1,000-row bulk's statements. Outside a
7508
+ * request's transaction (`db` is the pool) a real transaction is still opened,
7509
+ * so the row and its relation writes land together.
7510
+ */
7511
+ function inOwnTransactionUnlessTopLevel(db, write) {
7512
+ if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
7513
+ return db.transaction((tx) => write(tx));
7514
+ }
7515
+ /**
7516
+ * A filtered write whose filter compiled to no condition: it would address
7517
+ * every row, and is refused rather than run.
7518
+ */
7519
+ function filterRequired(collectionPath) {
7520
+ return ApiError.badRequest(`A filtered write to "${collectionPath}" needs at least one condition: without one it would address every row.`, "FILTER_REQUIRED");
7521
+ }
7522
+ /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
7523
+ function castableType(sqlType) {
7524
+ return {
7525
+ smallserial: "smallint",
7526
+ serial: "integer",
7527
+ bigserial: "bigint"
7528
+ }[sqlType.toLowerCase()] ?? sqlType;
7529
+ }
7530
+ /**
7531
+ * Service for handling all row write operations.
7532
+ * Handles saving, deleting, and updating rows.
7533
+ */
7534
+ var PersistService = class {
7535
+ db;
6971
7536
  registry;
6972
7537
  callContext;
6973
7538
  /** Reads: whether a row is under a parent, the key a link joins on. */
@@ -7031,9 +7596,10 @@ var PersistService = class {
7031
7596
  await this.db.select({ locked: sql`1` }).from(table).where(condition).for("no key update");
7032
7597
  }
7033
7598
  /**
7034
- * Delete an row by ID
7599
+ * Delete a row by ID. `options.commitsTransaction`: see
7600
+ * {@link PersistSaveOptions.commitsTransaction}.
7035
7601
  */
7036
- async delete(collectionPath, id, _databaseId) {
7602
+ async delete(collectionPath, id, _databaseId, options) {
7037
7603
  const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : void 0;
7038
7604
  if (hop) {
7039
7605
  assertWritableThrough(hop, collectionPath);
@@ -7049,7 +7615,11 @@ var PersistService = class {
7049
7615
  const condition = rowIdentityCondition(table, requirePrimaryKeys(collection, this.registry), id, collectionPath);
7050
7616
  let result;
7051
7617
  try {
7052
- result = await inOwnTransactionUnlessTopLevel(this.db, (tx) => tx.delete(table).where(condition));
7618
+ result = await inOwnTransactionUnlessTopLevel(this.db, (tx) => {
7619
+ const statement = tx.delete(table).where(condition);
7620
+ if (options?.commitsTransaction) commitWithNextStatement();
7621
+ return statement;
7622
+ });
7053
7623
  } catch (error) {
7054
7624
  throw this.toUserFriendlyError(error, collection.slug, collection, "delete");
7055
7625
  }
@@ -7109,6 +7679,15 @@ var PersistService = class {
7109
7679
  * not have. What they compile to is `field-op-sql.ts`.
7110
7680
  */
7111
7681
  async save(collectionPath, values, id, databaseId, options) {
7682
+ const saved = await this.saveUnlessKept(collectionPath, values, id, databaseId, options);
7683
+ if (!saved) throw new Error(`Saving a row in "${collectionPath}" answered no row.`);
7684
+ return saved;
7685
+ }
7686
+ /**
7687
+ * {@link save}, for an upsert with a {@link ConflictRule}: `undefined`
7688
+ * when the rule left the stored row on the conflict target as it was.
7689
+ */
7690
+ async saveUnlessKept(collectionPath, values, id, databaseId, options) {
7112
7691
  let effectiveCollectionPath = collectionPath;
7113
7692
  const effectiveValues = { ...values };
7114
7693
  let junctionTableInfo;
@@ -7179,7 +7758,11 @@ var PersistService = class {
7179
7758
  const entityData = sanitizeAndConvertDates(serializedResult.scalarData);
7180
7759
  assertWritableColumns(entityData, table, effectiveCollectionPath);
7181
7760
  if (fieldOpKeys.length > 0) assertWritableColumns(Object.fromEntries(fieldOpKeys.map((key) => [key, null])), table, effectiveCollectionPath);
7182
- savedId = await inOwnTransactionUnlessTopLevel(this.db, async (tx) => {
7761
+ const lastStatement = () => {
7762
+ if (options?.commitsTransaction && rowIsWrittenLast) commitWithNextStatement();
7763
+ };
7764
+ const conditional = Boolean(options?.ignoreDuplicates || options?.conflictWhere);
7765
+ const kept = await inOwnTransactionUnlessTopLevel(this.db, async (tx) => {
7183
7766
  let currentId;
7184
7767
  if (id && !options?.upsert) {
7185
7768
  currentId = id;
@@ -7194,7 +7777,9 @@ var PersistService = class {
7194
7777
  ...compiledOps ?? {}
7195
7778
  });
7196
7779
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7197
- const updated = await updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds))).returning(returning?.columns ?? returningKeys);
7780
+ const statement = updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds))).returning(returning?.columns ?? returningKeys);
7781
+ lastStatement();
7782
+ const updated = await statement;
7198
7783
  if (returning && updated[0]) returnedRow = returning.render(updated[0]);
7199
7784
  if (updated.length === 0) {
7200
7785
  const broken = await brokenFieldOpBounds(tx, table, [condition], bounds);
@@ -7228,14 +7813,19 @@ var PersistService = class {
7228
7813
  const softDelete = resolveSoftDelete(collection);
7229
7814
  const trashColumn = softDelete ? softDeleteColumn(collection, table) : void 0;
7230
7815
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7231
- const updating = Object.keys(set).length > 0;
7816
+ const updating = Object.keys(set).length > 0 && !options.ignoreDuplicates;
7817
+ const condition = options.conflictWhere ? this.fetchService.buildFilterConditions(options.conflictWhere, table, effectiveCollectionPath) : [];
7818
+ const setWhere = condition.length > 0 ? and(...writable ? [writable] : [], ...condition) : writable;
7232
7819
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7233
- result = updating ? await insertQuery.onConflictDoUpdate({
7820
+ const statement = updating ? insertQuery.onConflictDoUpdate({
7234
7821
  target,
7235
7822
  set,
7236
- setWhere: writable
7237
- }).returning(returning?.columns ?? returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7823
+ setWhere
7824
+ }).returning(returning?.columns ?? returningKeys) : insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7825
+ lastStatement();
7826
+ result = await statement;
7238
7827
  if (returning && result[0]) returnedRow = returning.render(result[0]);
7828
+ if (result.length === 0 && conditional && (options.ignoreDuplicates || !await this.storedRowRefusesWrite(tx, table, target.map((column, i) => eq(column, dataForInsert[targetFields[i]])), scope, trashColumn))) return;
7239
7829
  if (result.length === 0) {
7240
7830
  const keyConditions = target.map((column, i) => eq(column, dataForInsert[targetFields[i]]));
7241
7831
  if (scope) keyConditions.push(scope);
@@ -7251,7 +7841,9 @@ var PersistService = class {
7251
7841
  }
7252
7842
  } else {
7253
7843
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7254
- result = await insertQuery.returning(returning?.columns ?? returningKeys);
7844
+ const statement = insertQuery.returning(returning?.columns ?? returningKeys);
7845
+ lastStatement();
7846
+ result = await statement;
7255
7847
  if (returning && result[0]) returnedRow = returning.render(result[0]);
7256
7848
  }
7257
7849
  const resultRow = result[0];
@@ -7265,6 +7857,8 @@ var PersistService = class {
7265
7857
  if (junctionTableInfo) await this.relationWrites.handleJunctionTableCreation(tx, currentId, junctionTableInfo);
7266
7858
  return currentId;
7267
7859
  });
7860
+ if (kept === void 0) return void 0;
7861
+ savedId = kept;
7268
7862
  } catch (error) {
7269
7863
  throw this.toUserFriendlyError(error, collection.slug, collection);
7270
7864
  }
@@ -7348,6 +7942,10 @@ var PersistService = class {
7348
7942
  const scope = upsert ? await this.writeScope(collection, collectionPath, table) : void 0;
7349
7943
  const trashColumn = (upsert ? resolveSoftDelete(collection) : void 0) ? softDeleteColumn(collection, table) : void 0;
7350
7944
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7945
+ const conditional = Boolean(options?.ignoreDuplicates || options?.conflictWhere);
7946
+ const condition = upsert && options?.conflictWhere ? this.fetchService.buildFilterConditions(options.conflictWhere, table, collectionPath) : [];
7947
+ const setWhere = condition.length > 0 ? and(...writable ? [writable] : [], ...condition) : writable;
7948
+ const lastCommits = options?.commitsTransaction === true && (!upsert || options.ignoreDuplicates === true || !scope && !trashColumn);
7351
7949
  const runs = [];
7352
7950
  let start = 0;
7353
7951
  let params = 0;
@@ -7375,8 +7973,11 @@ var PersistService = class {
7375
7973
  for (const run of runs) {
7376
7974
  const slice = prepared.slice(run.start, run.end);
7377
7975
  const insertQuery = this.db.insert(table).values(slice.map((row) => row.data));
7976
+ const last = run === runs[runs.length - 1];
7378
7977
  if (!upsert) {
7379
- const result = await insertQuery.returning(returning.columns);
7978
+ const statement = insertQuery.returning(returning.columns);
7979
+ if (last && lastCommits) commitWithNextStatement();
7980
+ const result = await statement;
7380
7981
  if (result.length !== slice.length) throw new Error(`Inserted ${slice.length} rows into "${collectionPath}" and got ${result.length} back.`);
7381
7982
  result.forEach((row, i) => {
7382
7983
  written[run.start + i] = returning.render(row);
@@ -7389,11 +7990,13 @@ var PersistService = class {
7389
7990
  const column = table[field];
7390
7991
  set[field] = sql`excluded.${sql.identifier(column.name)}`;
7391
7992
  }
7392
- const result = setColumns.length > 0 ? await insertQuery.onConflictDoUpdate({
7993
+ const statement = setColumns.length > 0 && !options?.ignoreDuplicates ? insertQuery.onConflictDoUpdate({
7393
7994
  target,
7394
7995
  set,
7395
- setWhere: writable
7396
- }).returning(returning.columns) : await insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7996
+ setWhere
7997
+ }).returning(returning.columns) : insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7998
+ if (last && lastCommits) commitWithNextStatement();
7999
+ const result = await statement;
7397
8000
  const byKey = /* @__PURE__ */ new Map();
7398
8001
  for (const row of result) byKey.set(JSON.stringify(targetFields.map((field) => String(row[field]))), row);
7399
8002
  slice.forEach((row, i) => {
@@ -7402,10 +8005,14 @@ var PersistService = class {
7402
8005
  });
7403
8006
  }
7404
8007
  const saved = [];
7405
- for (let i = 0; i < rows.length; i++) saved.push(written[i] ?? await this.save(collectionPath, rows[i].values, void 0, collection.databaseId, {
8008
+ for (let i = 0; i < rows.length; i++) if (written[i]) saved.push(written[i]);
8009
+ else if (conditional && (options?.ignoreDuplicates || !scope && !trashColumn)) saved.push(void 0);
8010
+ else saved.push(await this.saveUnlessKept(collectionPath, rows[i].values, void 0, collection.databaseId, {
7406
8011
  upsert,
7407
8012
  onConflict: options?.onConflict,
7408
- insertOnlyKeys: rows[i].insertOnlyKeys
8013
+ insertOnlyKeys: rows[i].insertOnlyKeys,
8014
+ ignoreDuplicates: options?.ignoreDuplicates,
8015
+ conflictWhere: options?.conflictWhere
7409
8016
  }));
7410
8017
  return saved;
7411
8018
  }
@@ -7506,31 +8113,124 @@ var PersistService = class {
7506
8113
  return written;
7507
8114
  }
7508
8115
  /**
7509
- * The caller's `beforeQuery` scope over this table, as one condition: what
7510
- * a stored row must satisfy for a write that meets it to change it. The
7511
- * same scope the update gate and the single get apply; `undefined` when the
7512
- * collection declares no hook.
7513
- */
7514
- writeScope(collection, collectionPath, table) {
7515
- const [key] = getPrimaryKeys(collection, this.registry);
7516
- return beforeQueryCondition({
7517
- registry: this.registry,
7518
- callContext: this.callContext
7519
- }, collection, collectionPath, table, {
7520
- operation: "get",
7521
- query: {}
7522
- }, {
7523
- collection,
7524
- registry: this.registry,
7525
- sourceIdColumn: key ? table[key.fieldName] : void 0
7526
- });
7527
- }
7528
- /**
7529
- * Get the RelationService instance for external use
8116
+ * Update every row the conditions match, in one
8117
+ * `UPDATE … SET … WHERE … RETURNING` statement, and return each row as
8118
+ * {@link save} returns it. Field operations are compiled as for one row,
8119
+ * and their declared bounds are checked by the same statement: a matched
8120
+ * row an operation would take out of bounds fails the call.
8121
+ *
8122
+ * `undefined`, before anything is written, for a write that needs what
8123
+ * only the row-by-row update does: a relation in the values, or a
8124
+ * collection whose rows the statement cannot return (`beforeQuery`,
8125
+ * per-field read access). `options.commitsTransaction`: see
8126
+ * {@link PersistSaveOptions.commitsTransaction}; not honoured when bounds
8127
+ * are checked, which takes a statement after the update.
7530
8128
  */
7531
- getRelationService() {
7532
- return this.relationService;
7533
- }
8129
+ async updateWhere(collectionPath, filter, logical, values, options) {
8130
+ const collection = getCollectionByPath(collectionPath, this.registry);
8131
+ const returning = this.fetchService.insertReturning(collection.slug);
8132
+ if (!returning) return void 0;
8133
+ assertNoReadOnlyRelationValues(values, collection);
8134
+ const table = getTableForCollection(collection, this.registry);
8135
+ const { values: plainValues, fieldOps } = splitFieldOps(values, collection.properties);
8136
+ const resolvedRelations = resolveCollectionRelations(collection);
8137
+ if (Object.keys(resolvedRelations).some((key) => resolvedRelations[key]?.cardinality === "many" && Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
8138
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
8139
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
8140
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
8141
+ assertWritableColumns(data, table, collectionPath);
8142
+ const fieldOpKeys = Object.keys(fieldOps);
8143
+ if (fieldOpKeys.length > 0) assertWritableColumns(Object.fromEntries(fieldOpKeys.map((key) => [key, null])), table, collectionPath);
8144
+ if (Object.keys(data).length === 0 && fieldOpKeys.length === 0) throw ApiError.badRequest(`A filtered update of "${collectionPath}" sets nothing: send at least one field to set.`, "INVALID_BULK_BODY");
8145
+ const compiledOps = fieldOpKeys.length > 0 ? compileFieldOps(table, fieldOps, { collectionPath }) : {};
8146
+ const bounds = fieldOpKeys.length > 0 ? compileFieldOpBounds(table, fieldOps, collection.properties ?? {}, { collectionPath }) : [];
8147
+ const conditions = this.fetchService.buildWriteConditions(filter, logical, table, collectionPath);
8148
+ if (conditions.length === 0) throw filterRequired(collectionPath);
8149
+ try {
8150
+ const statement = this.db.update(table).set({
8151
+ ...data,
8152
+ ...compiledOps
8153
+ }).where(and(...conditions, ...bounds.map((bound) => bound.holds))).returning(returning.columns);
8154
+ if (options?.commitsTransaction && bounds.length === 0) commitWithNextStatement();
8155
+ const updated = await statement;
8156
+ if (bounds.length > 0) {
8157
+ const broken = await brokenFieldOpBounds(this.db, table, conditions, bounds);
8158
+ if (broken.length > 0) throw fieldOpBoundsError(collection.slug, broken);
8159
+ }
8160
+ return updated.map((row) => returning.render(row));
8161
+ } catch (error) {
8162
+ throw this.toUserFriendlyError(error, collection.slug, collection);
8163
+ }
8164
+ }
8165
+ /**
8166
+ * Delete every row the conditions match, in one `DELETE … WHERE …
8167
+ * RETURNING` statement, and return each deleted row's key columns.
8168
+ * `options.commitsTransaction`: see {@link PersistSaveOptions.commitsTransaction}.
8169
+ */
8170
+ async deleteWhere(collectionPath, filter, logical, options) {
8171
+ const collection = getCollectionByPath(collectionPath, this.registry);
8172
+ const table = getTableForCollection(collection, this.registry);
8173
+ const keyColumns = Object.fromEntries(requirePrimaryKeys(collection, this.registry).map((info) => [info.fieldName, table[info.fieldName]]));
8174
+ const conditions = this.fetchService.buildWriteConditions(filter, logical, table, collectionPath);
8175
+ if (conditions.length === 0) throw filterRequired(collectionPath);
8176
+ try {
8177
+ const statement = this.db.delete(table).where(and(...conditions)).returning(keyColumns);
8178
+ if (options?.commitsTransaction) commitWithNextStatement();
8179
+ return await statement;
8180
+ } catch (error) {
8181
+ throw this.toUserFriendlyError(error, collection.slug, collection, "delete");
8182
+ }
8183
+ }
8184
+ /**
8185
+ * Whether the row `id` addresses matches `filter`, as the caller reads
8186
+ * it: for an upsert under a `conflictWhere` that found its row first.
8187
+ */
8188
+ async rowMatches(collectionPath, id, filter) {
8189
+ const collection = getCollectionByPath(collectionPath, this.registry);
8190
+ const table = getTableForCollection(collection, this.registry);
8191
+ const condition = rowIdentityCondition(table, requirePrimaryKeys(collection, this.registry), id, collectionPath);
8192
+ const [row] = await this.db.select({ one: sql`1` }).from(table).where(and(condition, ...this.fetchService.buildFilterConditions(filter, table, collectionPath))).limit(1);
8193
+ return row !== void 0;
8194
+ }
8195
+ /**
8196
+ * Whether the stored row on an upsert's conflict target is one the
8197
+ * caller's write may not change at all — outside their `beforeQuery`
8198
+ * scope, or in the trash — rather than one a {@link ConflictRule} kept.
8199
+ * Asked only when there is a scope or a trash: without either, nothing
8200
+ * but the rule can have kept it, and no statement is sent.
8201
+ */
8202
+ async storedRowRefusesWrite(tx, table, key, scope, trashColumn) {
8203
+ if (!scope && !trashColumn) return false;
8204
+ const writable = [...scope ? [scope] : [], ...trashColumn ? [isNull(trashColumn)] : []];
8205
+ const [row] = await tx.select({ writable: sql`${and(...writable)}` }).from(table).where(and(...key)).limit(1);
8206
+ return row !== void 0 && row.writable !== true;
8207
+ }
8208
+ /**
8209
+ * The caller's `beforeQuery` scope over this table, as one condition: what
8210
+ * a stored row must satisfy for a write that meets it to change it. The
8211
+ * same scope the update gate and the single get apply; `undefined` when the
8212
+ * collection declares no hook.
8213
+ */
8214
+ writeScope(collection, collectionPath, table) {
8215
+ const [key] = getPrimaryKeys(collection, this.registry);
8216
+ return beforeQueryCondition({
8217
+ registry: this.registry,
8218
+ callContext: this.callContext
8219
+ }, collection, collectionPath, table, {
8220
+ operation: "get",
8221
+ query: {}
8222
+ }, {
8223
+ collection,
8224
+ registry: this.registry,
8225
+ sourceIdColumn: key ? table[key.fieldName] : void 0
8226
+ });
8227
+ }
8228
+ /**
8229
+ * Get the RelationService instance for external use
8230
+ */
8231
+ getRelationService() {
8232
+ return this.relationService;
8233
+ }
7534
8234
  /**
7535
8235
  * The write half, for external use. Separate from
7536
8236
  * {@link getRelationService} because they are separate objects now: reads
@@ -7575,6 +8275,133 @@ var PersistService = class {
7575
8275
  }
7576
8276
  };
7577
8277
  //#endregion
8278
+ //#region src/utils/positional-params.ts
8279
+ /**
8280
+ * Raw SQL with `$n` placeholders, as one drizzle statement that binds each
8281
+ * parameter once.
8282
+ *
8283
+ * `rebase.sql(text, { params })` takes the text and parameters `pg` takes, and
8284
+ * has to mean what `pg` means by them. It used to split the text on every
8285
+ * `/\$(\d+)/` and bind each occurrence as a new parameter, which broke three
8286
+ * ways:
8287
+ *
8288
+ * - A `$1` written N times became N bind parameters. Postgres infers each
8289
+ * one's type alone, so an uncast reuse failed with `could not determine data
8290
+ * type of parameter $7` where `pg` ran the same text, and the value was sent
8291
+ * N times.
8292
+ * - A `$1` inside a string literal, a quoted identifier, a comment or a
8293
+ * dollar-quoted body was bound as a parameter, changing the statement.
8294
+ * - `a$1`, an identifier Postgres allows, was split in two.
8295
+ *
8296
+ * So the text is scanned the way Postgres's lexer reads it, and only a
8297
+ * placeholder outside those spans is a parameter. The first occurrence of
8298
+ * each `$n` becomes a `sql.param`; drizzle numbers params in the order they
8299
+ * appear, so a later occurrence is written as the number drizzle gave the
8300
+ * first. Each value is sent once, and every occurrence is the same parameter.
8301
+ */
8302
+ var IDENT_CHAR = /[A-Za-z0-9_$\u0080-￿]/;
8303
+ var DOLLAR_TAG = /^\$([A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$/;
8304
+ /**
8305
+ * Split `text` into SQL text and `$n` placeholders, leaving string literals,
8306
+ * quoted identifiers, comments and dollar-quoted bodies whole.
8307
+ */
8308
+ function splitPlaceholders(text) {
8309
+ const pieces = [];
8310
+ let start = 0;
8311
+ let i = 0;
8312
+ const flush = (end) => {
8313
+ if (end > start) pieces.push({ text: text.slice(start, end) });
8314
+ };
8315
+ while (i < text.length) {
8316
+ const ch = text[i];
8317
+ const next = text[i + 1];
8318
+ if (ch === "'") {
8319
+ const escapes = i > 0 && (text[i - 1] === "E" || text[i - 1] === "e") && (i < 2 || !IDENT_CHAR.test(text[i - 2]));
8320
+ i++;
8321
+ while (i < text.length) {
8322
+ if (escapes && text[i] === "\\") {
8323
+ i += 2;
8324
+ continue;
8325
+ }
8326
+ if (text[i] === "'") {
8327
+ if (text[i + 1] === "'") {
8328
+ i += 2;
8329
+ continue;
8330
+ }
8331
+ break;
8332
+ }
8333
+ i++;
8334
+ }
8335
+ i++;
8336
+ } else if (ch === "\"") {
8337
+ i++;
8338
+ while (i < text.length) {
8339
+ if (text[i] === "\"") {
8340
+ if (text[i + 1] === "\"") {
8341
+ i += 2;
8342
+ continue;
8343
+ }
8344
+ break;
8345
+ }
8346
+ i++;
8347
+ }
8348
+ i++;
8349
+ } else if (ch === "-" && next === "-") {
8350
+ const end = text.indexOf("\n", i);
8351
+ i = end === -1 ? text.length : end + 1;
8352
+ } else if (ch === "/" && next === "*") {
8353
+ let depth = 1;
8354
+ i += 2;
8355
+ while (i < text.length && depth > 0) if (text[i] === "/" && text[i + 1] === "*") {
8356
+ depth++;
8357
+ i += 2;
8358
+ } else if (text[i] === "*" && text[i + 1] === "/") {
8359
+ depth--;
8360
+ i += 2;
8361
+ } else i++;
8362
+ } else if (ch === "$" && (i === 0 || !IDENT_CHAR.test(text[i - 1]))) {
8363
+ const digits = /^\$(\d+)/.exec(text.slice(i));
8364
+ if (digits) {
8365
+ flush(i);
8366
+ pieces.push({ param: Number(digits[1]) });
8367
+ i += digits[0].length;
8368
+ start = i;
8369
+ continue;
8370
+ }
8371
+ const tag = DOLLAR_TAG.exec(text.slice(i));
8372
+ if (tag) {
8373
+ const close = text.indexOf(tag[0], i + tag[0].length);
8374
+ i = close === -1 ? text.length : close + tag[0].length;
8375
+ } else i++;
8376
+ } else if (IDENT_CHAR.test(ch)) while (i < text.length && IDENT_CHAR.test(text[i])) i++;
8377
+ else i++;
8378
+ }
8379
+ flush(text.length);
8380
+ return pieces;
8381
+ }
8382
+ /**
8383
+ * `text` and `params` as one drizzle statement: each `$n` bound once, however
8384
+ * often it appears, and nothing inside a literal, identifier or comment bound.
8385
+ */
8386
+ function positionalStatement(text, params) {
8387
+ if (!params || params.length === 0) return sql.raw(text);
8388
+ const chunks = [];
8389
+ const bound = /* @__PURE__ */ new Map();
8390
+ for (const piece of splitPlaceholders(text)) {
8391
+ if ("text" in piece) {
8392
+ chunks.push(sql.raw(piece.text));
8393
+ continue;
8394
+ }
8395
+ const placed = bound.get(piece.param);
8396
+ if (placed !== void 0) chunks.push(sql.raw(`$${placed}`));
8397
+ else {
8398
+ bound.set(piece.param, bound.size + 1);
8399
+ chunks.push(sql`${sql.param(params[piece.param - 1])}`);
8400
+ }
8401
+ }
8402
+ return sql.join(chunks, sql.raw(""));
8403
+ }
8404
+ //#endregion
7578
8405
  //#region src/services/dataService.ts
7579
8406
  /**
7580
8407
  * DataService - Facade for row operations.
@@ -7666,11 +8493,15 @@ var DataService = class {
7666
8493
  async save(collectionPath, values, id, databaseId, options) {
7667
8494
  return this.persistService.save(collectionPath, values, id, databaseId, options);
7668
8495
  }
8496
+ /** See {@link PersistService.saveUnlessKept}. */
8497
+ async saveUnlessKept(collectionPath, values, id, databaseId, options) {
8498
+ return this.persistService.saveUnlessKept(collectionPath, values, id, databaseId, options);
8499
+ }
7669
8500
  /**
7670
8501
  * Delete an row by ID
7671
8502
  */
7672
- async delete(collectionPath, id, databaseId) {
7673
- return this.persistService.delete(collectionPath, id, databaseId);
8503
+ async delete(collectionPath, id, databaseId, options) {
8504
+ await this.persistService.delete(collectionPath, id, databaseId, options);
7674
8505
  }
7675
8506
  /**
7676
8507
  * Delete all rows from a collection
@@ -7686,24 +8517,14 @@ var DataService = class {
7686
8517
  * Execute raw SQL
7687
8518
  */
7688
8519
  async executeSql(sqlText, params) {
8520
+ return rowsOfResult(await this.executeSqlResult(sqlText, params));
8521
+ }
8522
+ /** {@link executeSql}, answering with the driver's whole result: its rows and its column descriptions. */
8523
+ async executeSqlResult(sqlText, params) {
7689
8524
  if (rawQueryLoggingEnabled()) logger.debug(`Executing raw SQL: ${sqlText}${params?.length ? ` with ${params.length} params` : ""}`);
7690
- const { sql } = await import("drizzle-orm");
7691
- let result;
7692
- if (params && params.length > 0) {
7693
- const parts = sqlText.split(/\$(\d+)/);
7694
- const chunks = [];
7695
- for (let i = 0; i < parts.length; i++) if (i % 2 === 0) {
7696
- if (parts[i].length > 0) chunks.push(sql.raw(parts[i]));
7697
- } else {
7698
- const paramIndex = Number(parts[i]) - 1;
7699
- chunks.push(sql.param(params[paramIndex]));
7700
- }
7701
- const query = sql.join(chunks, sql.raw(""));
7702
- result = await this.db.execute(query);
7703
- } else result = await this.db.execute(sql.raw(sqlText));
7704
- const rows = rowsOfResult(result);
7705
- if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rows.length} rows.`);
7706
- return rows;
8525
+ const result = await this.db.execute(positionalStatement(sqlText, params));
8526
+ if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rowsOfResult(result).length} rows.`);
8527
+ return result;
7707
8528
  }
7708
8529
  /**
7709
8530
  * Get the underlying FetchService for advanced use
@@ -7725,6 +8546,261 @@ var DataService = class {
7725
8546
  }
7726
8547
  };
7727
8548
  //#endregion
8549
+ //#region src/security/caller-sql.ts
8550
+ /**
8551
+ * What SQL may run as a caller (`DataDriver.sql` on the authenticated driver).
8552
+ *
8553
+ * That SQL runs in the caller's transaction, as `rebase_user`, with the
8554
+ * caller's identity in transaction-local settings — the same footing as every
8555
+ * SDK read and write, so the tables' policies decide each row. Those settings
8556
+ * are the weak point: a statement running as `rebase_user` can change them.
8557
+ * `RESET ROLE` returns to the connection's owner role, and
8558
+ * `set_config('app.uid', …)` makes the policies see somebody else. Postgres
8559
+ * offers no way to stop a role from doing either.
8560
+ *
8561
+ * So the query text has to be the application's own, and anything a user
8562
+ * typed travels in `params`, which can never become SQL. This check is the
8563
+ * backstop for when that slips — a value interpolated into the text, a query
8564
+ * assembled from pieces: it refuses every statement that can touch session
8565
+ * state, and more than one statement at a time.
8566
+ *
8567
+ * - one statement;
8568
+ * - leading with `SELECT`, `WITH`, `VALUES`, `TABLE`, `INSERT`, `UPDATE`,
8569
+ * `DELETE` or `MERGE` — no `SET`, `RESET`, `DO`, `PREPARE`, DDL or
8570
+ * transaction control;
8571
+ * - never calling `set_config` or naming `pg_settings`, the two ways a query
8572
+ * can write a setting;
8573
+ * - never calling a function of the `rebase` schema but the identity readers
8574
+ * (`uid`, `roles`, `jwt`, `is_anonymous`) — the rest are the server's doors.
8575
+ *
8576
+ * Read after masking string literals, dollar-quoted bodies and comments, so a
8577
+ * value that merely contains `;` or `set_config` is not refused, and
8578
+ * a call hidden in a comment-split name is not missed.
8579
+ */
8580
+ var ALLOWED_LEADS = /* @__PURE__ */ new Set([
8581
+ "select",
8582
+ "with",
8583
+ "values",
8584
+ "table",
8585
+ "insert",
8586
+ "update",
8587
+ "delete",
8588
+ "merge"
8589
+ ]);
8590
+ /** `set_config(` in any spelling Postgres accepts: schema-qualified, quoted, spaced. */
8591
+ var SETS_A_SETTING = /(?:^|[^\w$])"?set_config"?\s*\(/i;
8592
+ /** `pg_settings`, which an `UPDATE` writes through to `set_config`. */
8593
+ var NAMES_PG_SETTINGS = /(?:^|[^\w$])"?pg_settings"?(?:[^\w$]|$)/i;
8594
+ /**
8595
+ * The functions in the `rebase` schema a caller may name: the ones policies
8596
+ * read the identity through. Everything else there is the server's —
8597
+ * `record_history` and `enqueue_job` are `SECURITY DEFINER` doors the request
8598
+ * role can execute, because a write's history and jobs commit in the write's
8599
+ * own transaction, and a statement calling one forges an entry or starts a job.
8600
+ */
8601
+ var CALLER_REBASE_FUNCTIONS = /* @__PURE__ */ new Set([
8602
+ "uid",
8603
+ "roles",
8604
+ "jwt",
8605
+ "is_anonymous"
8606
+ ]);
8607
+ var REBASE_FUNCTION_CALL = /(?:^|[^\w$])"?rebase"?\s*\.\s*"?([A-Za-z_][\w$]*)"?\s*\(/gi;
8608
+ /** The doors by their bare names, for a `search_path` that reaches `rebase`. */
8609
+ var NAMES_A_SERVER_DOOR = /(?:^|[^\w$.])"?(record_history|enqueue_job)"?\s*\(/i;
8610
+ /**
8611
+ * The query with every string literal, dollar-quoted body and comment
8612
+ * replaced by a space. Quoted identifiers are kept, quotes and all, so a name
8613
+ * written `"set_config"` still reads as one.
8614
+ */
8615
+ function maskSqlLiterals(text) {
8616
+ let out = "";
8617
+ let i = 0;
8618
+ while (i < text.length) {
8619
+ const ch = text[i];
8620
+ const next = text[i + 1];
8621
+ if (ch === "-" && next === "-") {
8622
+ const end = text.indexOf("\n", i);
8623
+ i = end === -1 ? text.length : end;
8624
+ out += " ";
8625
+ } else if (ch === "/" && next === "*") {
8626
+ let depth = 1;
8627
+ i += 2;
8628
+ while (i < text.length && depth > 0) if (text[i] === "/" && text[i + 1] === "*") {
8629
+ depth++;
8630
+ i += 2;
8631
+ } else if (text[i] === "*" && text[i + 1] === "/") {
8632
+ depth--;
8633
+ i += 2;
8634
+ } else i++;
8635
+ out += " ";
8636
+ } else if (ch === "'") {
8637
+ const escapes = i > 0 && /[eE]/.test(text[i - 1]) && (i < 2 || !/[\w$]/.test(text[i - 2]));
8638
+ i++;
8639
+ while (i < text.length) {
8640
+ if (escapes && text[i] === "\\") {
8641
+ i += 2;
8642
+ continue;
8643
+ }
8644
+ if (text[i] === "'") {
8645
+ if (text[i + 1] === "'") {
8646
+ i += 2;
8647
+ continue;
8648
+ }
8649
+ break;
8650
+ }
8651
+ i++;
8652
+ }
8653
+ i++;
8654
+ out += " ";
8655
+ } else if (ch === "\"") {
8656
+ const end = text.indexOf("\"", i + 1);
8657
+ const stop = end === -1 ? text.length : end + 1;
8658
+ out += text.slice(i, stop);
8659
+ i = stop;
8660
+ } else if (ch === "$" && (i === 0 || !/[\w$]/.test(text[i - 1]))) {
8661
+ const tag = /^\$(?:[A-Za-z_][\w]*)?\$/.exec(text.slice(i));
8662
+ if (!tag) {
8663
+ out += ch;
8664
+ i++;
8665
+ continue;
8666
+ }
8667
+ const end = text.indexOf(tag[0], i + tag[0].length);
8668
+ i = end === -1 ? text.length : end + tag[0].length;
8669
+ out += " ";
8670
+ } else {
8671
+ out += ch;
8672
+ i++;
8673
+ }
8674
+ }
8675
+ return out;
8676
+ }
8677
+ function refuse(reason) {
8678
+ throw new ApiError(400, "SQL_NOT_ALLOWED", `${reason} SQL run as the caller is one SELECT, WITH, VALUES, TABLE, INSERT, UPDATE, DELETE or MERGE statement, with every value passed in \`params\` (\$1, \$2, …). Session settings carry the caller's identity, so a statement that could change them is refused.`, void 0, true);
8679
+ }
8680
+ /** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
8681
+ function assertCallerSql(text) {
8682
+ const code = maskSqlLiterals(text);
8683
+ const statements = code.split(";").filter((part) => part.trim().length > 0);
8684
+ if (statements.length === 0) refuse("The query is empty.");
8685
+ if (statements.length > 1) refuse("The query holds more than one statement.");
8686
+ const lead = /^[\s(]*([A-Za-z]+)/.exec(statements[0])?.[1]?.toLowerCase();
8687
+ if (!lead || !ALLOWED_LEADS.has(lead)) refuse(`\`${lead?.toUpperCase() ?? "?"}\` cannot run as the caller.`);
8688
+ if (/u&"/i.test(code)) refuse("The query spells an identifier with Unicode escapes (U&\"…\").");
8689
+ if (SETS_A_SETTING.test(code)) refuse("The query calls set_config.");
8690
+ if (NAMES_PG_SETTINGS.test(code)) refuse("The query names pg_settings.");
8691
+ for (const call of code.matchAll(REBASE_FUNCTION_CALL)) if (!CALLER_REBASE_FUNCTIONS.has(call[1].toLowerCase())) refuse(`The query calls rebase.${call[1]}, which is the server's.`);
8692
+ const door = NAMES_A_SERVER_DOOR.exec(code);
8693
+ if (door) refuse(`The query calls ${door[1]}, which is the server's.`);
8694
+ }
8695
+ //#endregion
8696
+ //#region src/security/caller-sql-columns.ts
8697
+ /**
8698
+ * The columns a caller may not read, taken out of what their SQL returned.
8699
+ *
8700
+ * Per-field read rules (`access.read`, and `excludeFromApi`, which is
8701
+ * `read: []`) are not something Postgres can hold for one request role shared
8702
+ * by every user, so the SDK applies them to each row it serves
8703
+ * (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
8704
+ * the SDK never walked — and `SELECT *` from a users table would hand over the
8705
+ * password hash.
8706
+ *
8707
+ * Postgres says where each result column came from: the row description
8708
+ * carries the table's oid and the column's number for every column that is a
8709
+ * plain reference to one, aliased or not, `RETURNING` included. A column whose
8710
+ * origin is a collection property this caller cannot read is dropped from
8711
+ * every row, the way the API drops it.
8712
+ *
8713
+ * What it cannot see is a value computed from such a column — `md5(hash)`,
8714
+ * `hash || ''` — whose origin Postgres reports as none. That is the query
8715
+ * text's business, and the query text is the application's (see
8716
+ * `caller-sql.ts`).
8717
+ *
8718
+ * A driver that reports no origins at all (PGlite) has its result columns
8719
+ * matched by name instead, against every restricted column of every
8720
+ * collection: it may drop a column of the same name from another table, never
8721
+ * keep one it should drop.
8722
+ */
8723
+ /** The columns of a result, from a pg `QueryResult` (or the last of several). */
8724
+ function fieldsOfResult(result) {
8725
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
8726
+ if (typeof last !== "object" || last === null || !("fields" in last)) return [];
8727
+ const fields = last.fields;
8728
+ if (!Array.isArray(fields)) return [];
8729
+ return fields.flatMap((field) => {
8730
+ if (typeof field !== "object" || field === null || !("name" in field)) return [];
8731
+ const { name, tableID, columnID } = field;
8732
+ return [{
8733
+ name: String(name),
8734
+ ...typeof tableID === "number" ? { tableID } : {},
8735
+ ...typeof columnID === "number" ? { columnID } : {}
8736
+ }];
8737
+ });
8738
+ }
8739
+ /**
8740
+ * The relations result columns came from, by oid, read from the catalogue the
8741
+ * first time an oid is seen. An oid never changes meaning: a table that is
8742
+ * dropped and created again gets a new one, which is read when it appears.
8743
+ */
8744
+ var ColumnOrigins = class {
8745
+ relations = /* @__PURE__ */ new Map();
8746
+ async describe(oids, run) {
8747
+ const unseen = [...new Set(oids)].filter((oid) => !this.relations.has(oid));
8748
+ if (unseen.length > 0) {
8749
+ const rows = await run(`SELECT c.oid::int AS oid, n.nspname AS schema, c.relname AS name, a.attnum::int AS attnum, a.attname AS column
8750
+ FROM pg_class c
8751
+ JOIN pg_namespace n ON n.oid = c.relnamespace
8752
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
8753
+ WHERE c.oid = ANY($1::oid[])`, [unseen]);
8754
+ for (const oid of unseen) this.relations.set(oid, null);
8755
+ for (const row of rows) {
8756
+ const oid = Number(row.oid);
8757
+ let relation = this.relations.get(oid);
8758
+ if (!relation) {
8759
+ relation = {
8760
+ schema: String(row.schema),
8761
+ name: String(row.name),
8762
+ columns: /* @__PURE__ */ new Map()
8763
+ };
8764
+ this.relations.set(oid, relation);
8765
+ }
8766
+ relation.columns.set(Number(row.attnum), String(row.column));
8767
+ }
8768
+ }
8769
+ return new Map(oids.map((oid) => [oid, this.relations.get(oid) ?? null]));
8770
+ }
8771
+ };
8772
+ var schemaOf = (collection) => isPostgresCollectionConfig(collection) && collection.schema || "public";
8773
+ /**
8774
+ * `rows` without the columns `viewer` may not read, by the origins `fields`
8775
+ * describe. The rows are changed in place and returned.
8776
+ */
8777
+ async function withoutUnreadableColumns(rows, fields, viewer, collections, origins, run) {
8778
+ const restricted = collections.filter(hasFieldAccessRules);
8779
+ if (restricted.length === 0 || rows.length === 0 || fields.length === 0) return rows;
8780
+ const refusedBy = /* @__PURE__ */ new Map();
8781
+ for (const collection of restricted) {
8782
+ const { refused } = restrictedFieldNames(collection, viewer, "read");
8783
+ if (refused.size > 0) refusedBy.set(`${schemaOf(collection)}.${getTableName$1(collection)}`, refused);
8784
+ }
8785
+ if (refusedBy.size === 0) return rows;
8786
+ const drop = /* @__PURE__ */ new Set();
8787
+ if (fields.every((field) => field.tableID === void 0)) {
8788
+ const everyRefused = new Set([...refusedBy.values()].flatMap((names) => [...names]));
8789
+ for (const field of fields) if (everyRefused.has(field.name)) drop.add(field.name);
8790
+ } else {
8791
+ const fromTables = fields.filter((field) => field.tableID && field.columnID);
8792
+ const relations = await origins.describe(fromTables.map((field) => field.tableID), run);
8793
+ for (const field of fromTables) {
8794
+ const relation = relations.get(field.tableID);
8795
+ const column = relation?.columns.get(field.columnID);
8796
+ if (relation && column && refusedBy.get(`${relation.schema}.${relation.name}`)?.has(column)) drop.add(field.name);
8797
+ }
8798
+ }
8799
+ if (drop.size === 0) return rows;
8800
+ for (const row of rows) for (const name of drop) delete row[name];
8801
+ return rows;
8802
+ }
8803
+ //#endregion
7728
8804
  //#region src/schema/classify-change.ts
7729
8805
  /**
7730
8806
  * What a collection change means for a live database.
@@ -8408,6 +9484,18 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
8408
9484
  }
8409
9485
  for (const trigger of before.triggers) {
8410
9486
  if (after.triggers.some((t) => t.name === trigger.name)) continue;
9487
+ if (trigger.kind === "keep-tenant") {
9488
+ push({
9489
+ kind: "change-constraint",
9490
+ verdict: "needs-migration",
9491
+ property: before.columns.find((c) => c.column === trigger.column)?.source.propName,
9492
+ detail: `The collection no longer declares a tenant, but trigger "${trigger.name}" stays and keeps refusing moves.`,
9493
+ remedy: `Drop it in a migration: DROP TRIGGER "${trigger.name}" ON "${after.schema}"."${after.table}".`,
9494
+ sourceOnly: `Trigger "${trigger.name}" stays and keeps "${trigger.column}" from changing.`,
9495
+ kept: `trigger ${trigger.name} kept`
9496
+ });
9497
+ continue;
9498
+ }
8411
9499
  push({
8412
9500
  kind: "change-constraint",
8413
9501
  verdict: "needs-migration",
@@ -8424,7 +9512,7 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
8424
9512
  kind: "change-constraint",
8425
9513
  verdict: "safe",
8426
9514
  property: after.columns.find((c) => c.column === trigger.column)?.source.propName,
8427
- detail: `"${trigger.column}" is stamped with now() on every update — creates trigger "${trigger.name}".`
9515
+ detail: trigger.kind === "keep-tenant" ? `An update can no longer move a row to another tenant — creates trigger "${trigger.name}".` : `"${trigger.column}" is stamped with now() on every update — creates trigger "${trigger.name}".`
8428
9516
  });
8429
9517
  }
8430
9518
  }
@@ -9742,442 +10830,108 @@ var PgNotifyListener = class {
9742
10830
  this.outageWarned = true;
9743
10831
  logger.warn(`⚠️ ${retry}`);
9744
10832
  }
9745
- this.scheduleReconnect();
9746
- return;
9747
- }
9748
- if (!first && this.options.onReconnect) {
9749
- logger.warn(`⚠️ ${logLabel} LISTEN client reconnected; anything published while it was down was missed.`);
9750
- try {
9751
- this.options.onReconnect();
9752
- } catch (err) {
9753
- logger.error(`❌ ${logLabel} Error resyncing after a reconnect`, { error: err });
9754
- }
9755
- }
9756
- }
9757
- /**
9758
- * Give up on the current connection: it is no longer the listener's, so
9759
- * its late events are ignored and `connected` says so at once; it is
9760
- * ended without waiting on it; and a replacement is scheduled.
9761
- */
9762
- abandon(client) {
9763
- if (client !== this.client) return;
9764
- this.client = void 0;
9765
- this.downSince ??= Date.now();
9766
- this.stopHeartbeat();
9767
- client.end().catch(() => {});
9768
- this.scheduleReconnect();
9769
- }
9770
- startHeartbeat(client) {
9771
- this.stopHeartbeat();
9772
- const interval = this.options.heartbeatIntervalMs ?? 3e4;
9773
- if (interval <= 0) return;
9774
- this.heartbeatTimer = setInterval(() => void this.heartbeat(client), interval);
9775
- unref(this.heartbeatTimer);
9776
- }
9777
- stopHeartbeat() {
9778
- if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
9779
- this.heartbeatTimer = void 0;
9780
- this.heartbeatInFlight = false;
9781
- }
9782
- /**
9783
- * One round trip on the LISTEN connection. Not answered in time, it is
9784
- * treated as dead: the client is ended — which, with the query still
9785
- * outstanding, destroys the socket rather than waiting on a goodbye that
9786
- * cannot arrive — and replaced.
9787
- */
9788
- async heartbeat(client) {
9789
- if (client !== this.client || this.heartbeatInFlight) return;
9790
- this.heartbeatInFlight = true;
9791
- const timeoutMs = this.options.heartbeatTimeoutMs ?? 1e4;
9792
- let timer;
9793
- try {
9794
- await Promise.race([client.query("SELECT 1"), new Promise((_resolve, reject) => {
9795
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no answer in ${timeoutMs}ms`)), timeoutMs);
9796
- })]);
9797
- if (client === this.client) this.lastHeartbeatAt = Date.now();
9798
- } catch (err) {
9799
- if (client !== this.client) return;
9800
- logger.warn(`⚠️ ${this.options.logLabel} LISTEN connection failed its heartbeat (${err instanceof Error ? err.message : String(err)}) — treating it as dead and reconnecting.`);
9801
- this.abandon(client);
9802
- } finally {
9803
- if (timer) clearTimeout(timer);
9804
- if (client === this.client) this.heartbeatInFlight = false;
9805
- }
9806
- }
9807
- scheduleReconnect() {
9808
- if (!this.running || this.reconnectTimer) return;
9809
- this.downSince ??= Date.now();
9810
- this.reconnectTimer = setTimeout(async () => {
9811
- this.reconnectTimer = void 0;
9812
- if (!this.running) return;
9813
- await this.connect();
9814
- }, this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1);
9815
- }
9816
- };
9817
- //#endregion
9818
- //#region src/pipelined-transaction.ts
9819
- /**
9820
- * A request's transaction, opened in the same round trip as its first query.
9821
- *
9822
- * Every request runs in a transaction that starts with two statements of its
9823
- * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
9824
- * and drops to the restricted role (`authContextStatement`). Sent one after
9825
- * the other, each waits for the last, and a lone read paid four round trips —
9826
- * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
9827
- * one. Against a database a few milliseconds away that is most of the request.
9828
- *
9829
- * Postgres accepts several statements in one batch: the extended protocol's
9830
- * Parse/Bind/Execute for each, then one Sync. The server runs them in order
9831
- * and answers them together, so this sends nothing when the transaction is
9832
- * opened and puts its opening statements in front of the first query instead.
9833
- * Should one of them fail, the server skips the rest up to the Sync: a refused
9834
- * role switch fails the batch before the query runs, with the same error a
9835
- * statement of its own would have raised.
9836
- *
9837
- * A read-only transaction at READ COMMITTED goes one step further. Each of its
9838
- * statements reads its own snapshot, so running each statement in a batch of
9839
- * its own with the context in front — a transaction that ends at the Sync —
9840
- * is the same transaction as far as anything inside it can tell, minus the
9841
- * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
9842
- * statement that only means something inside a transaction block (a
9843
- * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
9844
- * one, from that statement on.
9845
- *
9846
- * Statement values are serialized by pg's own `prepareValue`, so a value means
9847
- * the same here as in any other query; rows are parsed with the query's own
9848
- * type parsers, as pg's `Query` parses them.
9849
- */
9850
- var COMMAND_TAG = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
9851
- /**
9852
- * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
9853
- * Sync, one round trip. The last statement's result is the batch's; the
9854
- * others are run for their effect and their rows are dropped unparsed.
9855
- *
9856
- * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
9857
- * nothing for it but what `submit` writes, and hands it each message the
9858
- * server sends back until ReadyForQuery.
9859
- */
9860
- var PipelinedQuery = class {
9861
- /** How many statements this batch sends. */
9862
- statementCount;
9863
- /** Set by `client.query`, which wraps it for its read timeout. */
9864
- callback;
9865
- /** The statements, in the order they are sent, with their serialized values. */
9866
- statements;
9867
- rowMode;
9868
- types;
9869
- /** Statements ahead of the last whose completion has not arrived yet. */
9870
- ahead;
9871
- fields = [];
9872
- parsers = [];
9873
- rows = [];
9874
- command = "";
9875
- rowCount = null;
9876
- oid = 0;
9877
- rowError;
9878
- settled = false;
9879
- constructor(lead, last, callback) {
9880
- this.statements = [...lead, last].map((statement) => ({
9881
- text: statement.text,
9882
- values: (statement.values ?? []).map((value) => prepareValue(value))
9883
- }));
9884
- this.statementCount = this.statements.length;
9885
- this.ahead = lead.length;
9886
- this.rowMode = last.rowMode;
9887
- this.types = last.types ?? pg.types;
9888
- this.callback = callback;
9889
- }
9890
- submit(connection) {
9891
- connection.stream.cork();
9892
- try {
9893
- for (const statement of this.statements) {
9894
- connection.parse({
9895
- text: statement.text,
9896
- name: "",
9897
- types: []
9898
- }, true);
9899
- connection.bind({
9900
- portal: "",
9901
- statement: "",
9902
- values: statement.values
9903
- }, true);
9904
- connection.describe({
9905
- type: "P",
9906
- name: ""
9907
- }, true);
9908
- connection.execute({ portal: "" }, true);
9909
- }
9910
- connection.sync();
9911
- } finally {
9912
- connection.stream.uncork();
9913
- }
9914
- }
9915
- handleRowDescription(message) {
9916
- if (this.ahead > 0) return;
9917
- this.fields = message.fields;
9918
- this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, "text"));
9919
- }
9920
- handleDataRow(message) {
9921
- if (this.ahead > 0 || this.rowError) return;
9922
- const values = message.fields;
9923
- try {
9924
- if (this.rowMode === "array") {
9925
- const row = new Array(values.length);
9926
- for (let i = 0; i < values.length; i++) {
9927
- const raw = values[i];
9928
- row[i] = raw === null ? null : this.parsers[i](raw);
9929
- }
9930
- this.rows.push(row);
9931
- } else {
9932
- const row = {};
9933
- for (let i = 0; i < values.length; i++) {
9934
- const raw = values[i];
9935
- row[this.fields[i].name] = raw === null ? null : this.parsers[i](raw);
9936
- }
9937
- this.rows.push(row);
9938
- }
9939
- } catch (error) {
9940
- this.rowError = error instanceof Error ? error : new Error(String(error));
9941
- }
9942
- }
9943
- handleCommandComplete(message) {
9944
- if (this.ahead > 0) {
9945
- this.ahead -= 1;
9946
- return;
9947
- }
9948
- const match = COMMAND_TAG.exec(message.text);
9949
- if (!match) return;
9950
- this.command = match[1];
9951
- if (match[3]) {
9952
- this.oid = Number.parseInt(match[2], 10);
9953
- this.rowCount = Number.parseInt(match[3], 10);
9954
- } else if (match[2]) this.rowCount = Number.parseInt(match[2], 10);
9955
- }
9956
- /** An empty statement completes with EmptyQueryResponse rather than CommandComplete. */
9957
- handleEmptyQuery() {
9958
- if (this.ahead > 0) this.ahead -= 1;
9959
- }
9960
- handlePortalSuspended() {}
9961
- handleError(error) {
9962
- if (this.settled) return;
9963
- this.settled = true;
9964
- this.callback?.(error);
9965
- }
9966
- handleReadyForQuery() {
9967
- if (this.settled) return;
9968
- this.settled = true;
9969
- if (this.rowError) {
9970
- this.callback?.(this.rowError);
9971
- return;
9972
- }
9973
- const result = {
9974
- command: this.command,
9975
- rowCount: this.rowCount,
9976
- oid: this.oid,
9977
- fields: this.fields,
9978
- rows: this.rows
9979
- };
9980
- this.callback?.(null, result);
9981
- }
9982
- };
9983
- /** Send `lead` and then `last` in one round trip; the result is `last`'s. */
9984
- function runPipelined(client, lead, last) {
9985
- return new Promise((resolve, reject) => {
9986
- client.query(new PipelinedQuery(lead, last, (error, result) => {
9987
- if (error) reject(error);
9988
- else if (result) resolve(result);
9989
- }));
9990
- });
9991
- }
9992
- /**
9993
- * A statement that means something only inside a transaction block, so a
9994
- * read cannot run it in a batch of its own: savepoints, transaction-local
9995
- * settings, cursors and transaction-scoped locks.
9996
- */
9997
- var NEEDS_TRANSACTION_BLOCK = /^\s*(?:savepoint|release|rollback|set\s+local|set\s+transaction|declare|lock|prepare\s+transaction)\b|\bset_config\s*\(|\bpg_advisory_xact_lock|\bpg_try_advisory_xact_lock/i;
9998
- /**
9999
- * A statement pg runs with a protocol of its own: COPY streams, a named
10000
- * statement pg keeps track of, a portal read page by page. Sent as pg sends
10001
- * it, after the transaction's opening has gone ahead in a batch of its own.
10002
- */
10003
- function cannotPipeline(config) {
10004
- return Boolean(config.name) || Boolean(config.rows) || /^\s*copy\b/i.test(config.text);
10005
- }
10006
- function toQueryConfig(statement) {
10007
- return {
10008
- text: statement.text,
10009
- values: statement.values ? [...statement.values] : void 0
10010
- };
10011
- }
10012
- function beginStatement(config) {
10013
- const parts = ["begin"];
10014
- if (config?.isolationLevel) parts.push(`isolation level ${config.isolationLevel}`);
10015
- if (config?.accessMode) parts.push(config.accessMode);
10016
- if (typeof config?.deferrable === "boolean") parts.push(config.deferrable ? "deferrable" : "not deferrable");
10017
- return parts.join(" ");
10018
- }
10019
- /**
10020
- * Whether a transaction with these settings can run each statement in a batch
10021
- * of its own. Read-only, at READ COMMITTED: every statement takes its own
10022
- * snapshot there anyway, and none of them can write.
10023
- */
10024
- function runsStatementByStatement(config) {
10025
- return config?.accessMode === "read only" && (config.isolationLevel === void 0 || config.isolationLevel === "read committed") && config.deferrable !== true;
10026
- }
10027
- /**
10028
- * A savepoint being set or released: a statement with no result to wait for,
10029
- * which can go out with whatever is sent next.
10030
- */
10031
- var DEFERRABLE = /^\s*(?:savepoint|release(?:\s+savepoint)?)\s+[A-Za-z_][A-Za-z0-9_]*\s*;?\s*$/i;
10032
- var ROLLBACK_TO = /^\s*rollback\s+to\s+(?:savepoint\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*;?\s*$/i;
10033
- function settledWithoutSending(text) {
10034
- const command = text.trim().split(/\s+/)[0].toUpperCase();
10035
- return Promise.resolve({
10036
- command,
10037
- rowCount: null,
10038
- oid: 0,
10039
- fields: [],
10040
- rows: []
10041
- });
10042
- }
10043
- /**
10044
- * The client side of one transaction: sends its opening with the first query,
10045
- * holds savepoints back until a statement goes out after them, and sends
10046
- * `COMMIT` or `ROLLBACK` only when something was sent.
10047
- */
10048
- var TransactionOpening = class {
10049
- client;
10050
- begin;
10051
- opening;
10052
- statementByStatement;
10053
- /** `fresh`: nothing sent. `implicit`: each statement ran in a batch of its own. `open`: in a transaction block. */
10054
- state = "fresh";
10055
- /** In a block: statements accepted and not yet sent, which go out ahead of the next one. */
10056
- pending = [];
10057
- /** In a block: whether its `BEGIN` has reached the server. */
10058
- begun = false;
10059
- constructor(client, begin, opening, statementByStatement) {
10060
- this.client = client;
10061
- this.begin = begin;
10062
- this.opening = opening;
10063
- this.statementByStatement = statementByStatement;
10064
- }
10065
- /** The `query` the transaction's drizzle session calls. Decides synchronously, so concurrent calls queue in order. */
10066
- query(config, values) {
10067
- const statement = typeof config === "string" ? {
10068
- text: config,
10069
- values
10070
- } : values !== void 0 ? {
10071
- ...config,
10072
- values
10073
- } : config;
10074
- const pipelinable = !cannotPipeline(statement);
10075
- if (this.state !== "open") {
10076
- if (this.statementByStatement && pipelinable && !NEEDS_TRANSACTION_BLOCK.test(statement.text)) {
10077
- this.state = "implicit";
10078
- return runPipelined(this.client, [READ_ONLY_STATEMENT, ...this.opening], statement);
10079
- }
10080
- this.state = "open";
10081
- this.pending = [{ text: this.begin }, ...this.opening];
10082
- }
10083
- const rollbackTo = ROLLBACK_TO.exec(statement.text);
10084
- if (rollbackTo) {
10085
- const at = this.pending.findLastIndex((pending) => pending.text.trim().toLowerCase() === `savepoint ${rollbackTo[1].toLowerCase()}`);
10086
- if (at >= 0) {
10087
- this.pending = this.pending.slice(0, at);
10088
- return settledWithoutSending(statement.text);
10089
- }
10833
+ this.scheduleReconnect();
10834
+ return;
10090
10835
  }
10091
- if (DEFERRABLE.test(statement.text) && !statement.values?.length) {
10092
- this.pending.push({ text: statement.text });
10093
- return settledWithoutSending(statement.text);
10836
+ if (!first && this.options.onReconnect) {
10837
+ logger.warn(`⚠️ ${logLabel} LISTEN client reconnected; anything published while it was down was missed.`);
10838
+ try {
10839
+ this.options.onReconnect();
10840
+ } catch (err) {
10841
+ logger.error(`❌ ${logLabel} Error resyncing after a reconnect`, { error: err });
10842
+ }
10094
10843
  }
10095
- return this.send(statement, pipelinable);
10096
10844
  }
10097
- /** `statement`, with everything pending in front of it. */
10098
- send(statement, pipelinable = true) {
10099
- const lead = this.pending;
10100
- this.pending = [];
10101
- if (lead.length > 0) this.begun = true;
10102
- if (lead.length === 0) return this.client.query(statement);
10103
- if (pipelinable) return runPipelined(this.client, lead, statement);
10104
- return runPipelined(this.client, lead.slice(0, -1), toQueryConfig(lead[lead.length - 1])).then(() => this.client.query(statement));
10845
+ /**
10846
+ * Give up on the current connection: it is no longer the listener's, so
10847
+ * its late events are ignored and `connected` says so at once; it is
10848
+ * ended without waiting on it; and a replacement is scheduled.
10849
+ */
10850
+ abandon(client) {
10851
+ if (client !== this.client) return;
10852
+ this.client = void 0;
10853
+ this.downSince ??= Date.now();
10854
+ this.stopHeartbeat();
10855
+ client.end().catch(() => {});
10856
+ this.scheduleReconnect();
10105
10857
  }
10106
- async commit() {
10107
- if (this.state === "open" && this.begun) await this.send({ text: "commit" });
10108
- this.pending = [];
10858
+ startHeartbeat(client) {
10859
+ this.stopHeartbeat();
10860
+ const interval = this.options.heartbeatIntervalMs ?? 3e4;
10861
+ if (interval <= 0) return;
10862
+ this.heartbeatTimer = setInterval(() => void this.heartbeat(client), interval);
10863
+ unref(this.heartbeatTimer);
10109
10864
  }
10110
- async rollback() {
10111
- this.pending = [];
10112
- if (this.state === "open" && this.begun) await this.client.query("rollback");
10865
+ stopHeartbeat() {
10866
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
10867
+ this.heartbeatTimer = void 0;
10868
+ this.heartbeatInFlight = false;
10113
10869
  }
10114
- };
10115
- /**
10116
- * What `SET TRANSACTION READ ONLY` sets, as a statement that can run in a batch
10117
- * outside a transaction block — where `SET TRANSACTION` warns and does nothing.
10118
- */
10119
- var READ_ONLY_STATEMENT = { text: "SELECT set_config('transaction_read_only', 'on', true)" };
10120
- /** The relational schema a drizzle handle was built with, for a session over another client. */
10121
- function schemaConfigOf(db) {
10122
- const { schema, fullSchema, tableNamesMap } = db._;
10123
- return schema && fullSchema ? {
10124
- schema,
10125
- fullSchema,
10126
- tableNamesMap
10127
- } : void 0;
10128
- }
10129
- var dialect = new PgDialect();
10130
- /**
10131
- * The drizzle handle and pg pool to run a pipelined transaction on, or
10132
- * `undefined` for a handle that is not a drizzle database over a pg pool of
10133
- * this process's pg (PGlite, a transaction, a caller's own copy of either
10134
- * library), which opens its transactions statement by statement.
10135
- */
10136
- function pipelineTarget(db) {
10137
- if (!(db instanceof NodePgDatabase) || !("$client" in db)) return void 0;
10138
- const client = db.$client;
10139
- return client instanceof pg.Pool ? {
10140
- db,
10141
- pool: client
10142
- } : void 0;
10143
- }
10144
- /**
10145
- * Run `work` in a transaction on a client of `pool`, its opening sent with the
10146
- * first query.
10147
- *
10148
- * `opening` runs at the start of the transaction, after the `BEGIN` that
10149
- * `config` describes — and, for a read-only transaction at READ COMMITTED,
10150
- * ahead of every statement, each in a transaction of its own (see the module
10151
- * comment). `work` gets a drizzle transaction like the one
10152
- * `db.transaction()` hands out: savepoints nest inside it, and it commits
10153
- * when `work` resolves and rolls back when it throws.
10154
- */
10155
- async function runPipelinedTransaction(db, pool, opening, config, work) {
10156
- const client = await pool.connect();
10157
- const transaction = new TransactionOpening(client, beginStatement(config), opening, runsStatementByStatement(config));
10158
- const sessionClient = new Proxy(client, { get(target, property) {
10159
- if (property === "query") return transaction.query.bind(transaction);
10160
- const value = Reflect.get(target, property, target);
10161
- return typeof value === "function" ? value.bind(target) : value;
10162
- } });
10163
- const schema = schemaConfigOf(db);
10164
- const tx = new NodePgTransaction(dialect, new NodePgSession(sessionClient, dialect, schema), schema);
10165
- try {
10166
- let result;
10870
+ /**
10871
+ * One round trip on the LISTEN connection. Not answered in time, it is
10872
+ * treated as dead: the client is ended — which, with the query still
10873
+ * outstanding, destroys the socket rather than waiting on a goodbye that
10874
+ * cannot arrive — and replaced.
10875
+ */
10876
+ async heartbeat(client) {
10877
+ if (client !== this.client || this.heartbeatInFlight) return;
10878
+ this.heartbeatInFlight = true;
10879
+ const timeoutMs = this.options.heartbeatTimeoutMs ?? 1e4;
10880
+ let timer;
10167
10881
  try {
10168
- result = await work(tx);
10169
- } catch (error) {
10170
- await transaction.rollback();
10171
- throw error;
10882
+ await Promise.race([client.query("SELECT 1"), new Promise((_resolve, reject) => {
10883
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no answer in ${timeoutMs}ms`)), timeoutMs);
10884
+ })]);
10885
+ if (client === this.client) this.lastHeartbeatAt = Date.now();
10886
+ } catch (err) {
10887
+ if (client !== this.client) return;
10888
+ logger.warn(`⚠️ ${this.options.logLabel} LISTEN connection failed its heartbeat (${err instanceof Error ? err.message : String(err)}) — treating it as dead and reconnecting.`);
10889
+ this.abandon(client);
10890
+ } finally {
10891
+ if (timer) clearTimeout(timer);
10892
+ if (client === this.client) this.heartbeatInFlight = false;
10172
10893
  }
10173
- await transaction.commit();
10174
- return result;
10175
- } finally {
10176
- client.release();
10177
10894
  }
10178
- }
10895
+ scheduleReconnect() {
10896
+ if (!this.running || this.reconnectTimer) return;
10897
+ this.downSince ??= Date.now();
10898
+ this.reconnectTimer = setTimeout(async () => {
10899
+ this.reconnectTimer = void 0;
10900
+ if (!this.running) return;
10901
+ await this.connect();
10902
+ }, this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1);
10903
+ }
10904
+ };
10179
10905
  //#endregion
10180
10906
  //#region src/read-routing.ts
10907
+ /**
10908
+ * Which connection an authenticated read runs on: the primary, or a standby
10909
+ * (`DATABASE_READ_URL`).
10910
+ *
10911
+ * A standby serves a read as well as the primary does — the RLS context is
10912
+ * transaction-local (`applyAuthContext`), and `SET LOCAL ROLE` and
10913
+ * `set_config(…, true)` both work on a hot standby — but it serves what it
10914
+ * has replayed, which is a little behind. Two rules keep that from being
10915
+ * visible:
10916
+ *
10917
+ * - **Read-your-writes.** A principal that just wrote reads from the primary
10918
+ * for {@link ReadRoutingOptions.stickyMs} afterwards, so a save followed by
10919
+ * a list shows the save. In-process: another instance does not know about
10920
+ * the write, and the lag guard is what bounds what it can serve.
10921
+ * - **Lag guard.** The standby's replay lag is sampled every
10922
+ * {@link ReadRoutingOptions.sampleIntervalMs}; above
10923
+ * {@link ReadRoutingOptions.maxLagMs}, or with no recent sample, every read
10924
+ * goes to the primary. So does every read for a while after the standby
10925
+ * failed one (see {@link isReplicaFallbackError}), and the failed read is
10926
+ * retried on the primary.
10927
+ *
10928
+ * What never comes here is decided by the caller: writes, reads inside a
10929
+ * write's transaction, the service identity (crons, jobs, `dataAsAdmin`), and
10930
+ * everything on the base driver — auth, realtime, idempotency, the SQL
10931
+ * console, `rebase.sql`.
10932
+ *
10933
+ * @module
10934
+ */
10181
10935
  var DEFAULT_READ_STICKY_MS = 5e3;
10182
10936
  var DEFAULT_READ_MAX_LAG_MS = 1e3;
10183
10937
  var DEFAULT_SAMPLE_INTERVAL_MS = 1e3;
@@ -10283,7 +11037,6 @@ var REPLICA_LAG_SQL = `SELECT CASE
10283
11037
  WHEN pg_last_wal_receive_lsn() IS NOT NULL AND pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
10284
11038
  ELSE EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) * 1000
10285
11039
  END AS lag_ms`;
10286
- /** Run {@link REPLICA_LAG_SQL} on `pool`, in milliseconds. */
10287
11040
  async function readReplicaLagMs(pool) {
10288
11041
  const raw = (await pool.query(REPLICA_LAG_SQL)).rows[0]?.lag_ms;
10289
11042
  if (raw === null || raw === void 0) return null;
@@ -10449,7 +11202,7 @@ async function sampleDatabaseHealth(primary, replica) {
10449
11202
  primary.query("SELECT pg_database_size(current_database())::text AS bytes"),
10450
11203
  replica ? readReplicaLagMs(replica) : Promise.resolve(null)
10451
11204
  ]);
10452
- if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [row.state, Number(row.count)]));
11205
+ if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [String(row.state), Number(row.count)]));
10453
11206
  if (max.status === "fulfilled") {
10454
11207
  const value = Number(max.value.rows[0]?.max);
10455
11208
  if (Number.isFinite(value)) sample.maxConnections = value;
@@ -10540,7 +11293,7 @@ var RoleSwitchUnavailableError = class extends Error {
10540
11293
  /** The underlying Postgres error, when the refusal came from a live attempt. */
10541
11294
  pgError;
10542
11295
  constructor(role, pgError) {
10543
- super(`Cannot execute SQL as role "${role}": this connection is not permitted to SET ROLE. The statement was NOT executed — running it as the connection owner would return owner-visible rows, which is a different question from the one that was asked. Grant the connection user membership in "${role}", or set DISABLE_DB_ROLE_SWITCHING=true to run SQL Editor queries as the connection owner.`);
11296
+ super(`Cannot execute SQL as role "${role}": this connection is not permitted to SET ROLE. The statement was NOT executed — running it as the connection owner would return owner-visible rows, which is a different question from the one that was asked. Grant the connection user membership in "${role}" with the right to switch to it — \`GRANT "${role.replace(/"/g, "\"\"")}" TO <connection user> WITH SET TRUE\` on PostgreSQL 16+, where a membership can exist without it (a role created by a non-superuser with CREATEROLE is one), or a plain \`GRANT\` before 16 — or set DISABLE_DB_ROLE_SWITCHING=true to run SQL Editor queries as the connection owner.` + (pgError ? ` Postgres said: ${extractPgError(pgError)?.message ?? (pgError instanceof Error ? pgError.message : String(pgError))}` : ""));
10544
11297
  this.name = "RoleSwitchUnavailableError";
10545
11298
  this.role = role;
10546
11299
  this.pgError = pgError;
@@ -10713,6 +11466,26 @@ function authContextOf(user) {
10713
11466
  function declaresAnyHook(...tiers) {
10714
11467
  return tiers.some((tier) => tier !== void 0 && Object.values(tier).some((value) => typeof value === "function"));
10715
11468
  }
11469
+ /** The `(collection, field)` pairs {@link warnReplacedAutoValues} has spoken about, once each. */
11470
+ var warnedAutoValues = /* @__PURE__ */ new Set();
11471
+ /**
11472
+ * Say, once per field and outside production, that a value the write sent
11473
+ * for an `autoValue` column was replaced or dropped. By design — the stamp is
11474
+ * the server's, never the caller's — and silent, which is how a migration
11475
+ * script that copies `createdAt` across found out its dates were all today's.
11476
+ */
11477
+ function warnReplacedAutoValues(collection, sent, stamped, status) {
11478
+ if (process.env.NODE_ENV === "production") return;
11479
+ for (const [field, property] of Object.entries(collection.properties ?? {})) {
11480
+ const autoValue = property.autoValue;
11481
+ if (!autoValue || sent[field] === void 0 || sent[field] === null) continue;
11482
+ const replaced = stamped[field] === void 0 || stamped[field] !== sent[field];
11483
+ const key = `${collection.slug}.${field}`;
11484
+ if (!replaced || warnedAutoValues.has(key)) continue;
11485
+ warnedAutoValues.add(key);
11486
+ logger.warn(`[DataDriver] The value sent for '${field}' on "${collection.slug}" was ${stamped[field] === void 0 ? "dropped" : "replaced"}: it is \`autoValue: "${autoValue}"\`, which the server stamps on ${status === "existing" ? "an update" : "a create"} whatever the write sends. Copying rows with their original value takes SQL, or a property without autoValue. (Said once per field, outside production.)`);
11487
+ }
11488
+ }
10716
11489
  /**
10717
11490
  * A bulk or batch update's answer for an id that names no row this caller can
10718
11491
  * see: a 404 naming the id, which the entry's own label then wraps.
@@ -10738,6 +11511,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10738
11511
  branchService;
10739
11512
  user;
10740
11513
  data;
11514
+ /** Where the columns of a caller's SQL came from — see `caller-sql-columns.ts`. */
11515
+ columnOrigins = new ColumnOrigins();
10741
11516
  /**
10742
11517
  * The server singleton, attached by `initializeRebaseBackend` after boot —
10743
11518
  * a driver exists before the client does. Typed as what is attached: a
@@ -10746,18 +11521,23 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10746
11521
  */
10747
11522
  client;
10748
11523
  /**
10749
- * Auto-set to `true` once a `SET LOCAL ROLE` has failed with insufficient
10750
- * privileges, so later statements refuse without spending the round trip
10751
- * to be refused again.
11524
+ * Roles a `SET ROLE` has been refused for with insufficient privileges,
11525
+ * with the refusal, so later statements as that role refuse without
11526
+ * spending the round trip to be refused again.
10752
11527
  *
10753
11528
  * Deliberately NOT a mirror of `DISABLE_DB_ROLE_SWITCHING`, which it used
10754
11529
  * to be described as. The env var is an operator saying "run these as the
10755
- * connection owner"; this flag is the database saying "I cannot give you
10756
- * the role you asked for". The first is a decision and permits the
10757
- * fallback, the second is a failure and must not — see the SECURITY note
10758
- * in {@link executeSql}.
11530
+ * connection owner"; this is the database saying "I cannot give you the
11531
+ * role you asked for". The first is a decision and permits the fallback,
11532
+ * the second is a failure and must not — see the SECURITY note in
11533
+ * {@link executeSql}.
11534
+ *
11535
+ * Per role, and keeping Postgres's own error. It was one flag: a single
11536
+ * refusal for a role picked in the SQL editor then refused every other
11537
+ * role too, `rebase_user` included, and every later refusal said "not
11538
+ * permitted to SET ROLE" with the reason Postgres gave already dropped.
10759
11539
  */
10760
- _roleSwitchingUnavailable = false;
11540
+ _roleSwitchRefusals = /* @__PURE__ */ new Map();
10761
11541
  /**
10762
11542
  * Restricted role that authenticated (user-context) requests run as (via
10763
11543
  * `SET LOCAL ROLE`) so RLS binds every statement — reads *and* writes. Set
@@ -10768,6 +11548,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10768
11548
  * migrations, `dataAsAdmin`).
10769
11549
  */
10770
11550
  rlsUserRole;
11551
+ /** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
11552
+ rlsRequest;
10771
11553
  /**
10772
11554
  * The direct (non-pooled) URL {@link listen} holds its `LISTEN` on — this
10773
11555
  * source's, set by the bootstrapper. Never read from `DATABASE_DIRECT_URL`
@@ -10798,6 +11580,17 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10798
11580
  * wrapping transaction commits. Set by `withAuth` → `withTransaction`.
10799
11581
  */
10800
11582
  _deferNotifications = false;
11583
+ /**
11584
+ * Whether the next write on this driver is the last thing its transaction
11585
+ * does, so its last statement may carry the `COMMIT`
11586
+ * (`commitWithNextStatement`). Set by `withTransaction` for a lone write,
11587
+ * and by a row-by-row batch of one row; honoured only by a write that runs
11588
+ * no hook and records no history, which is what would follow the
11589
+ * statement. Never for the last of several rows: a statement that matches
11590
+ * nothing is a 404 raised after it, and the rows before it would already
11591
+ * have committed.
11592
+ */
11593
+ _commitsWithLastWrite = false;
10801
11594
  _pendingNotifications = [];
10802
11595
  constructor(db, realtimeService, registry, user, poolManager, historyService) {
10803
11596
  this.db = db;
@@ -11460,6 +12253,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11460
12253
  for (const key of createStampKeys(collection.properties)) delete kept[key];
11461
12254
  stamped = kept;
11462
12255
  }
12256
+ warnReplacedAutoValues(collection, values, stamped, status);
11463
12257
  return stamped;
11464
12258
  }
11465
12259
  /**
@@ -11508,10 +12302,31 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11508
12302
  return Boolean(callbacks?.beforeSave || globalCallbacks?.beforeSave || propertyCallbacks?.beforeSave || callbacks?.afterSave || globalCallbacks?.afterSave || propertyCallbacks?.afterSave || callbacks?.afterSaveError || globalCallbacks?.afterSaveError || propertyCallbacks?.afterSaveError || callbacks?.beforeQuery || globalCallbacks?.beforeQuery || collection.history || getTenantConfig(collection) || hasFieldAccessRules(collection) || resolveSoftDelete(collection) || isNestedPath(path));
11509
12303
  }
11510
12304
  async save(props) {
12305
+ const saved = await this.saveRowUnlessKept(props);
12306
+ if (!saved) throw new Error(`Saving a row in "${props.path}" answered no row.`);
12307
+ return saved;
12308
+ }
12309
+ /**
12310
+ * {@link save}, for an upsert under a conflict rule (`saveMany`'s
12311
+ * `ignoreDuplicates` / `conflictWhere`): `undefined` when the rule left
12312
+ * the stored row on the conflict target as it was, and nothing ran for
12313
+ * it — no hook, no history, no event.
12314
+ */
12315
+ async saveRowUnlessKept(props, rule) {
11511
12316
  this.assertWritable(props.collection, props.path);
11512
- return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame));
12317
+ return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame, void 0, rule));
12318
+ }
12319
+ /**
12320
+ * Whether the write about to run may send its transaction's `COMMIT` with
12321
+ * its last statement: this driver was told it is the transaction's last
12322
+ * write (`_commitsWithLastWrite`), it is not a write a hook started, and
12323
+ * nothing runs after its statement — no hook (an `afterRead` included,
12324
+ * which may read through `context.data`) and no history entry.
12325
+ */
12326
+ lastWriteCommits(collection, ...hooks) {
12327
+ return this._commitsWithLastWrite && currentWriteDepth() <= 1 && !declaresAnyHook(...hooks) && !collection?.history;
11513
12328
  }
11514
- async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored) {
12329
+ async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored, rule) {
11515
12330
  const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11516
12331
  if (declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) currentWriteScope()?.noteApplicationCode();
11517
12332
  if (resolvedCollection?.history) this.historyService?.assertRecordable(resolvedCollection.slug);
@@ -11531,6 +12346,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11531
12346
  const readsStoredRow = this.writeReadsStoredRow(resolvedCollection, path, hooks);
11532
12347
  if (upserting && resolvedCollection && readsStoredRow) {
11533
12348
  const stored = await this.findUpsertTarget(path, resolvedCollection, values, id, onConflict);
12349
+ if (stored && rule && (rule.ignoreDuplicates || rule.conflictWhere && !await this.dataService.getPersistService().rowMatches(this.storedRowPath(path), stored.id, rule.conflictWhere))) return;
11534
12350
  if (stored) {
11535
12351
  const reusable = !callbacks?.beforeQuery && !globalCallbacks?.beforeQuery && !hasFieldAccessRules(resolvedCollection) && !isNestedPath(path);
11536
12352
  return this.saveInFrame({
@@ -11627,12 +12443,18 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11627
12443
  const softDeleteField = resolveSoftDelete(resolvedCollection)?.field;
11628
12444
  if (insertOnlyKeys && softDeleteField && updatedValues[softDeleteField] !== void 0 && updatedValues[softDeleteField] !== null) insertOnlyKeys.push(softDeleteField);
11629
12445
  try {
11630
- const storedRow = await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, {
12446
+ const persistOptions = {
11631
12447
  upsert: upserting,
11632
12448
  onConflict,
11633
12449
  insertOnlyKeys,
11634
- unreadRow
11635
- });
12450
+ unreadRow,
12451
+ commitsTransaction: this.lastWriteCommits(resolvedCollection, callbacks, globalCallbacks, propertyCallbacks)
12452
+ };
12453
+ const storedRow = upserting && rule ? await this.dataService.saveUnlessKept(path, updatedValues, writeId, resolvedCollection?.databaseId, {
12454
+ ...persistOptions,
12455
+ ...rule
12456
+ }) : await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, persistOptions);
12457
+ if (!storedRow) return void 0;
11636
12458
  const savedRow = await this.viewOfSavedRow(storedRow, resolvedCollection, path, {
11637
12459
  callbacks,
11638
12460
  globalCallbacks,
@@ -11799,10 +12621,20 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11799
12621
  txDriver.client = this.client;
11800
12622
  return txDriver.buildCallContext();
11801
12623
  }
11802
- async saveMany({ path, rows, collection, upsert, onConflict }) {
12624
+ async saveMany({ path, rows, collection, upsert, onConflict, conflictWhere, ignoreDuplicates }) {
11803
12625
  this.assertWritable(collection, path);
12626
+ if ((conflictWhere || ignoreDuplicates) && upsert !== true) throw ApiError.badRequest("`ignoreDuplicates` and `where` describe what an upsert does to a row already on its conflict target; pass them with `upsert: true`.", "INVALID_CONFLICT_RULE");
12627
+ if (conflictWhere && ignoreDuplicates) throw ApiError.badRequest("`ignoreDuplicates` leaves every stored row as it is, so a `where` choosing which ones to update has nothing to choose. Pass one of the two.", "INVALID_CONFLICT_RULE");
12628
+ const rule = conflictWhere || ignoreDuplicates ? {
12629
+ conflictWhere,
12630
+ ignoreDuplicates
12631
+ } : void 0;
12632
+ const commitsWithLastWrite = this._commitsWithLastWrite;
11804
12633
  if (rows.length > 1 && this.writesRowsTogether(collection, path)) try {
11805
- const together = await this.inBatchTransaction((txDriver) => txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict));
12634
+ const together = await this.inBatchTransaction((txDriver) => {
12635
+ txDriver._commitsWithLastWrite = commitsWithLastWrite;
12636
+ return txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict, rule);
12637
+ });
11806
12638
  if (together) return together;
11807
12639
  } catch (error) {
11808
12640
  logger.debug(`[saveMany] A batch write to "${path}" failed; saving its rows one by one to name the row`, { detail: error instanceof Error ? error.message : String(error) });
@@ -11812,15 +12644,17 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11812
12644
  for (let i = 0; i < rows.length; i++) {
11813
12645
  const values = rows[i];
11814
12646
  const id = values?.id;
12647
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && rows.length === 1;
11815
12648
  try {
11816
- saved.push(await txDriver.save({
12649
+ const row = await txDriver.saveRowUnlessKept({
11817
12650
  path,
11818
12651
  values,
11819
12652
  collection,
11820
12653
  status: "new",
11821
12654
  upsert,
11822
12655
  onConflict
11823
- }));
12656
+ }, rule);
12657
+ if (row) saved.push(row);
11824
12658
  } catch (error) {
11825
12659
  const label = id !== void 0 ? `id ${JSON.stringify(id)}` : "no id";
11826
12660
  throw Object.assign(new Error(`Row ${i} of ${rows.length} (${label}) failed: ${error?.message ?? error}`, { cause: error }), {
@@ -11859,7 +12693,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11859
12693
  * anything is written, for a batch `saveRows` declines. Its realtime events
11860
12694
  * join the transaction's only once every row is answered.
11861
12695
  */
11862
- async saveRowsTogether(path, rows, collection, upsert, onConflict) {
12696
+ async saveRowsTogether(path, rows, collection, upsert, onConflict, rule) {
11863
12697
  const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11864
12698
  const resolved = resolvedCollection;
11865
12699
  if (!resolved) return void 0;
@@ -11881,10 +12715,16 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11881
12715
  });
11882
12716
  const stored = await this.dataService.getPersistService().saveRows(path, prepared, {
11883
12717
  upsert,
11884
- onConflict
12718
+ onConflict,
12719
+ ...rule,
12720
+ commitsTransaction: this.lastWriteCommits(resolved, callbacks, globalCallbacks, propertyCallbacks)
11885
12721
  });
11886
12722
  if (!stored) return void 0;
11887
- return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, hooks);
12723
+ const written = stored.flatMap((row, i) => row ? [{
12724
+ row,
12725
+ values: prepared[i].values
12726
+ }] : []);
12727
+ return this.answerRowsWritten(written.map((entry) => entry.row), written.map((entry) => entry.values), resolved, path, hooks);
11888
12728
  }
11889
12729
  /**
11890
12730
  * {@link updateMany}'s updates written together (`PersistService.updateRows`)
@@ -11956,6 +12796,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11956
12796
  */
11957
12797
  async updateMany({ path, updates, collection }) {
11958
12798
  this.assertWritable(collection, path);
12799
+ const commitsWithLastWrite = this._commitsWithLastWrite;
11959
12800
  if (updates.length > 1 && this.writesRowsTogether(collection, path)) try {
11960
12801
  const together = await this.inBatchTransaction((txDriver) => txDriver.updateRowsTogether(path, updates, collection));
11961
12802
  if (together) return together;
@@ -11966,6 +12807,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11966
12807
  const saved = [];
11967
12808
  for (let i = 0; i < updates.length; i++) {
11968
12809
  const { id, values } = updates[i];
12810
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && updates.length === 1;
11969
12811
  try {
11970
12812
  saved.push(await txDriver.save({
11971
12813
  path,
@@ -11999,9 +12841,11 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11999
12841
  */
12000
12842
  async deleteMany({ path, ids, collection, hard }) {
12001
12843
  this.assertWritable(collection, path);
12844
+ const commitsWithLastWrite = this._commitsWithLastWrite;
12002
12845
  await this.inBatchTransaction(async (txDriver) => {
12003
12846
  for (let i = 0; i < ids.length; i++) {
12004
12847
  const id = ids[i];
12848
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && ids.length === 1;
12005
12849
  try {
12006
12850
  await txDriver.delete({
12007
12851
  row: {
@@ -12022,6 +12866,115 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12022
12866
  });
12023
12867
  }
12024
12868
  /**
12869
+ * Update every row a filter matches. One statement (`PersistService.updateWhere`)
12870
+ * when nothing needs the rows one by one; otherwise the rows the caller
12871
+ * reads through the filter, updated by {@link updateMany} through the full
12872
+ * pipeline, in one transaction. A filter matching nothing answers `[]`.
12873
+ */
12874
+ async updateWhere({ path, filter, logical, values, collection }) {
12875
+ this.assertWritable(collection, path);
12876
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12877
+ const resolved = this.assertFilteredWrite(resolvedCollection, path, filter, logical);
12878
+ const written = values;
12879
+ assertUpdateDoesNotSoftDelete(resolved, written, path);
12880
+ const keys = getPrimaryKeys(resolved, this.registry).map((key) => key.fieldName).filter((field) => written[field] !== void 0);
12881
+ if (keys.length > 0) throw ApiError.badRequest(`'${keys[0]}' is the key of '${resolved.slug}', and an update cannot change it — a filtered one least of all, which would give every row it matches the same key.`, "KEY_IMMUTABLE", {
12882
+ collection: resolved.slug,
12883
+ violations: keys.map((field) => ({
12884
+ field,
12885
+ code: "key_immutable"
12886
+ }))
12887
+ });
12888
+ const hooks = {
12889
+ callbacks,
12890
+ globalCallbacks,
12891
+ propertyCallbacks
12892
+ };
12893
+ if (!this.writeReadsStoredRow(resolved, path, hooks)) {
12894
+ const stamped = this.stampAutoValues(resolved, values, "existing", path);
12895
+ const stored = await this.dataService.getPersistService().updateWhere(path, filter, logical, stamped, { commitsTransaction: this.lastWriteCommits(resolved, callbacks, globalCallbacks, propertyCallbacks) });
12896
+ if (stored) return this.answerRowsWritten(stored, stored.map(() => stamped), resolved, path, hooks);
12897
+ }
12898
+ const ids = await this.addressesMatching(resolved, path, filter, logical);
12899
+ if (ids.length === 0) return [];
12900
+ return this.updateMany({
12901
+ path,
12902
+ updates: ids.map((id) => ({
12903
+ id,
12904
+ values
12905
+ })),
12906
+ collection
12907
+ });
12908
+ }
12909
+ /**
12910
+ * Delete every row a filter matches, under the rules of {@link updateWhere}:
12911
+ * one `DELETE` when nothing needs the rows one by one, else
12912
+ * {@link deleteMany} over the rows the caller reads through the filter.
12913
+ * Answers how many rows went.
12914
+ */
12915
+ async deleteWhere({ path, filter, logical, collection, hard }) {
12916
+ this.assertWritable(collection, path);
12917
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12918
+ const resolved = this.assertFilteredWrite(resolvedCollection, path, filter, logical);
12919
+ if (!(!hard && resolveSoftDelete(resolved) !== void 0) && !resolved.history && !declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) {
12920
+ const deleted = await this.dataService.getPersistService().deleteWhere(path, filter, logical, { commitsTransaction: this.lastWriteCommits(resolved) });
12921
+ const notifications = deleted.map((row) => ({
12922
+ path,
12923
+ id: deriveRowAddress(row, resolved, this.registry),
12924
+ row: null,
12925
+ databaseId: resolved.databaseId
12926
+ }));
12927
+ if (this._deferNotifications) this._pendingNotifications.push(...notifications);
12928
+ else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, null, notification.databaseId);
12929
+ return deleted.length;
12930
+ }
12931
+ const ids = await this.addressesMatching(resolved, path, filter, logical);
12932
+ if (ids.length === 0) return 0;
12933
+ await this.deleteMany({
12934
+ path,
12935
+ ids,
12936
+ collection,
12937
+ hard
12938
+ });
12939
+ return ids.length;
12940
+ }
12941
+ /**
12942
+ * A row's address in the spelling a read derives it in — `010` is row
12943
+ * `10` — for an event about a row this write did not read.
12944
+ */
12945
+ canonicalAddress(collection, id) {
12946
+ if (!collection) return String(id);
12947
+ try {
12948
+ return deriveRowAddress(parseIdValues$1(id, getPrimaryKeys(collection, this.registry)), collection, this.registry) || String(id);
12949
+ } catch {
12950
+ return String(id);
12951
+ }
12952
+ }
12953
+ /**
12954
+ * The collection a filtered write addresses, refused when it cannot be
12955
+ * one: a path through a relation (a filter there would reach rows the
12956
+ * path does not), or a filter with no condition (every row).
12957
+ */
12958
+ assertFilteredWrite(collection, path, filter, logical) {
12959
+ if (!collection || isNestedPath(path)) throw ApiError.badRequest(`A filtered write addresses a collection, and "${path}" is ${collection ? "a path through a relation" : "not one"}. Write to the related collection with a filter on its link instead.`, "INVALID_FILTERED_WRITE");
12960
+ if ((!filter || Object.keys(filter).length === 0) && !logical) throw filterRequired(path);
12961
+ return collection;
12962
+ }
12963
+ /**
12964
+ * The addresses of the rows a filter matches, read as this caller reads
12965
+ * them — their policies, their `beforeQuery`, the trash hidden — for a
12966
+ * filtered write that runs row by row.
12967
+ */
12968
+ async addressesMatching(collection, path, filter, logical) {
12969
+ const primaryKeys = getPrimaryKeys(collection, this.registry);
12970
+ return (await this.dataService.getFetchService().fetchCollectionForRest(path, {
12971
+ filter,
12972
+ logical,
12973
+ fields: primaryKeys.map((key) => key.fieldName),
12974
+ databaseId: collection.databaseId
12975
+ })).map((row) => deriveRowAddress(row, collection, this.registry, primaryKeys));
12976
+ }
12977
+ /**
12025
12978
  * A mixed list of writes across collections, as one unit of work.
12026
12979
  *
12027
12980
  * Same transaction, same tx-bound sub-driver and same per-entry error
@@ -12114,6 +13067,19 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12114
13067
  const hop = isNestedPath(targetPath) ? resolveNestedPath(targetPath, this.registry) : void 0;
12115
13068
  const unlinking = hop !== void 0 && isJunctionBackedRelation(hop.relation);
12116
13069
  if (resolvedCollection?.history && !unlinking) this.historyService?.assertRecordable(resolvedCollection.slug);
13070
+ const softDeleting = !hard && !unlinking && resolveSoftDelete(resolvedCollection) !== void 0;
13071
+ if (!precondition && !hop && !softDeleting && !resolvedCollection?.history && !declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) {
13072
+ await this.dataService.delete(targetPath, row.id, resolvedCollection?.databaseId, { commitsTransaction: this.lastWriteCommits(resolvedCollection) });
13073
+ const notification = {
13074
+ path: targetPath,
13075
+ id: this.canonicalAddress(resolvedCollection, row.id),
13076
+ row: null,
13077
+ databaseId: resolvedCollection?.databaseId
13078
+ };
13079
+ if (this._deferNotifications) this._pendingNotifications.push(notification);
13080
+ else await this.realtimeService.notifyUpdate(notification.path, notification.id, null, notification.databaseId);
13081
+ return;
13082
+ }
12117
13083
  if (precondition?.lock) await this.dataService.getPersistService().lockRow(targetPath, row.id);
12118
13084
  const stored = await this.dataService.fetchOneForRest(targetPath, row.id, void 0, resolvedCollection?.databaseId, { withDeleted: hard ? true : void 0 });
12119
13085
  if (precondition) await precondition.check(await this.asRestServes(stored, targetPath));
@@ -12240,7 +13206,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12240
13206
  const collection = this.resolveCollectionCallbacks(void 0, path).collection;
12241
13207
  if (!collection || !isPostgresCollectionConfig(collection) || !collection.view?.materialized) throw ApiError.badRequest(`"${collection?.slug ?? path}" is not a materialized view, so there is nothing to refresh.`, "NOT_A_MATERIALIZED_VIEW");
12242
13208
  const schema = collection.schema ?? "public";
12243
- const qualified = sql`${sql.identifier(schema)}.${sql.identifier(getTableName$1(collection))}`;
13209
+ const qualified = sql`${sql.identifier(schema)}.${sql.identifier(viewRowsName(getTableName$1(collection)))}`;
12244
13210
  await this.db.execute(options?.concurrently ? sql`REFRESH MATERIALIZED VIEW CONCURRENTLY ${qualified}` : sql`REFRESH MATERIALIZED VIEW ${qualified}`);
12245
13211
  await this.realtimeService.notifyUpdate(path, "*", null);
12246
13212
  }
@@ -12334,20 +13300,15 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12334
13300
  return sampleDatabaseHealth(pool, replica instanceof Pool ? replica : void 0);
12335
13301
  }
12336
13302
  /**
12337
- * Build one statement, binding `$n` placeholders as real parameters.
13303
+ * Build one statement, binding `$n` placeholders as real parameters —
13304
+ * each once, however often it appears (`utils/positional-params.ts`).
12338
13305
  *
12339
13306
  * Shared by the role-switched path (inside a transaction) and the
12340
13307
  * unswitched one. They held byte-identical copies of this loop, which is
12341
13308
  * exactly the shape where a fix lands in one copy and not the other.
12342
13309
  */
12343
13310
  buildStatement(sqlText, params) {
12344
- if (!params || params.length === 0) return sql.raw(sqlText);
12345
- const parts = sqlText.split(/\$(\d+)/);
12346
- const chunks = [];
12347
- for (let i = 0; i < parts.length; i++) if (i % 2 === 0) {
12348
- if (parts[i].length > 0) chunks.push(sql.raw(parts[i]));
12349
- } else chunks.push(sql.param(params[Number(parts[i]) - 1]));
12350
- return sql.join(chunks, sql.raw(""));
13311
+ return positionalStatement(sqlText, params);
12351
13312
  }
12352
13313
  async executeSql(sqlText, options) {
12353
13314
  if (options?.isolateSession) return this.onIsolatedSession(await this.getSessionTargetDb(options.database), options.role, (db, role) => this.executeSqlOn(db, sqlText, {
@@ -12439,12 +13400,12 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12439
13400
  logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${role}".`);
12440
13401
  return;
12441
13402
  }
12442
- if (this._roleSwitchingUnavailable) throw new RoleSwitchUnavailableError(role);
13403
+ if (this._roleSwitchRefusals.has(role)) throw new RoleSwitchUnavailableError(role, this._roleSwitchRefusals.get(role));
12443
13404
  try {
12444
13405
  await connection.query(`SET ROLE "${role.replace(/"/g, "\"\"")}"`);
12445
13406
  } catch (roleError) {
12446
13407
  if (isRoleSwitchingPermissionError(roleError)) {
12447
- this._roleSwitchingUnavailable = true;
13408
+ this._roleSwitchRefusals.set(role, roleError);
12448
13409
  throw new RoleSwitchUnavailableError(role, roleError);
12449
13410
  }
12450
13411
  throw roleError;
@@ -12492,7 +13453,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12492
13453
  needsRoleSwitch = true;
12493
13454
  }
12494
13455
  if (needsRoleSwitch && options?.role) if (isRoleSwitchingOptedOut()) logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${options.role}".`);
12495
- else if (this._roleSwitchingUnavailable) throw new RoleSwitchUnavailableError(options.role);
13456
+ else if (this._roleSwitchRefusals.has(options.role)) throw new RoleSwitchUnavailableError(options.role, this._roleSwitchRefusals.get(options.role));
12496
13457
  else {
12497
13458
  const safeRole = options.role.replace(/"/g, "\"\"");
12498
13459
  try {
@@ -12502,7 +13463,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12502
13463
  });
12503
13464
  } catch (roleError) {
12504
13465
  if (isRoleSwitchingPermissionError(roleError)) {
12505
- this._roleSwitchingUnavailable = true;
13466
+ this._roleSwitchRefusals.set(options.role, roleError);
12506
13467
  throw new RoleSwitchUnavailableError(options.role, roleError);
12507
13468
  }
12508
13469
  throw roleError;
@@ -12753,6 +13714,20 @@ var AuthenticatedPostgresBackendDriver = class {
12753
13714
  });
12754
13715
  }
12755
13716
  /**
13717
+ * One statement as this caller — see {@link DataDriver.sql}. The same
13718
+ * transaction every SDK call on this driver opens (`rebase_user`, the
13719
+ * caller's identity), read-only unless `write`, and so on the read replica
13720
+ * when a read may go there.
13721
+ */
13722
+ async sql(query, options) {
13723
+ assertCallerSql(query);
13724
+ return this.withTransaction(async (delegate) => {
13725
+ if (options?.write) commitWithNextStatement();
13726
+ const result = await delegate.dataService.executeSqlResult(query, options?.params);
13727
+ return withoutUnreadableColumns(rowsOfResult(result), fieldsOfResult(result), { roles: this.user?.roles ?? [] }, this.delegate.registry?.getCollections() ?? [], this.delegate.columnOrigins, (text, params) => delegate.dataService.executeSql(text, params));
13728
+ }, { accessMode: options?.write ? "read write" : "read only" });
13729
+ }
13730
+ /**
12756
13731
  * Run `operation` in a transaction as this caller — on the read replica
12757
13732
  * when this is a read the replica may serve (see {@link replicaFor}), else
12758
13733
  * on the primary.
@@ -12833,6 +13808,7 @@ var AuthenticatedPostgresBackendDriver = class {
12833
13808
  });
12834
13809
  const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
12835
13810
  txDelegate.dataService = txEntityService;
13811
+ txDelegate._commitsWithLastWrite = options?.loneWrite === true;
12836
13812
  txDelegate._deferNotifications = true;
12837
13813
  txDelegate._pendingNotifications = pendingNotifications;
12838
13814
  txDelegate.client = this.delegate.client;
@@ -12849,16 +13825,20 @@ var AuthenticatedPostgresBackendDriver = class {
12849
13825
  return out;
12850
13826
  };
12851
13827
  const auth = authContextOf(this.user);
13828
+ const config = options?.accessMode || options?.isolationLevel ? {
13829
+ ...options.accessMode ? { accessMode: options.accessMode } : {},
13830
+ ...options.isolationLevel ? { isolationLevel: options.isolationLevel } : {}
13831
+ } : void 0;
12852
13832
  if (pipelined) {
12853
- const opening = authContextStatement(auth, this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
12854
- return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], options, inTransaction);
13833
+ const opening = authContextStatement(auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
13834
+ return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], config, inTransaction);
12855
13835
  }
12856
13836
  return db.transaction(async (tx) => {
12857
13837
  const transactionSettings = transactionSettingsStatements(pooledSettings);
12858
13838
  if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
12859
- await applyAuthContext(tx, auth, this.delegate.rlsUserRole);
13839
+ await applyAuthContext(tx, auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole);
12860
13840
  return inTransaction(tx);
12861
- }, options);
13841
+ }, config);
12862
13842
  }).finally(() => writeScope?.close())).catch(async (error) => {
12863
13843
  await writeScope?.settled();
12864
13844
  throw error;
@@ -12893,7 +13873,7 @@ var AuthenticatedPostgresBackendDriver = class {
12893
13873
  return this.delegate.listenOne(props, authContextOf(this.user));
12894
13874
  }
12895
13875
  async save(props) {
12896
- return this.withTransaction((delegate) => delegate.save(props));
13876
+ return this.withTransaction((delegate) => delegate.save(props), { loneWrite: true });
12897
13877
  }
12898
13878
  /**
12899
13879
  * One transaction for the whole batch, rather than one per row.
@@ -12905,7 +13885,7 @@ var AuthenticatedPostgresBackendDriver = class {
12905
13885
  * `withTransaction`, so a batch does not flood subscribers mid-flight.
12906
13886
  */
12907
13887
  async saveMany(props) {
12908
- return this.withTransaction((delegate) => delegate.saveMany(props));
13888
+ return this.withTransaction((delegate) => delegate.saveMany(props), { loneWrite: true });
12909
13889
  }
12910
13890
  /**
12911
13891
  * Present for the same reason `saveMany` is, and absent until now.
@@ -12918,10 +13898,16 @@ var AuthenticatedPostgresBackendDriver = class {
12918
13898
  * The methods existed one class down and nothing forwarded to them.
12919
13899
  */
12920
13900
  async updateMany(props) {
12921
- return this.withTransaction((delegate) => delegate.updateMany(props));
13901
+ return this.withTransaction((delegate) => delegate.updateMany(props), { loneWrite: true });
12922
13902
  }
12923
13903
  async deleteMany(props) {
12924
- return this.withTransaction((delegate) => delegate.deleteMany(props));
13904
+ return this.withTransaction((delegate) => delegate.deleteMany(props), { loneWrite: true });
13905
+ }
13906
+ async updateWhere(props) {
13907
+ return this.withTransaction((delegate) => delegate.updateWhere(props), { loneWrite: true });
13908
+ }
13909
+ async deleteWhere(props) {
13910
+ return this.withTransaction((delegate) => delegate.deleteWhere(props), { loneWrite: true });
12925
13911
  }
12926
13912
  /**
12927
13913
  * One transaction, one RLS context, every collection the batch touches.
@@ -12935,7 +13921,7 @@ var AuthenticatedPostgresBackendDriver = class {
12935
13921
  return this.withTransaction((delegate) => delegate.batchWrite(props));
12936
13922
  }
12937
13923
  async delete(props) {
12938
- return this.withTransaction((delegate) => delegate.delete(props));
13924
+ return this.withTransaction((delegate) => delegate.delete(props), { loneWrite: true });
12939
13925
  }
12940
13926
  async deleteAll(path) {
12941
13927
  return this.withTransaction((delegate) => delegate.deleteAll(path));
@@ -15239,7 +16225,7 @@ function terminateIfBacklogged(ws, clientId) {
15239
16225
  const now = Date.now();
15240
16226
  if (now - lastBudgetCheckAt >= PROCESS_BUDGET_CHECK_MS || now < lastBudgetCheckAt) {
15241
16227
  lastBudgetCheckAt = now;
15242
- if (budgetedClients.size > 0 && enforceProcessSendBudget().includes(ws)) return true;
16228
+ if (budgetedClients.size > 0 && enforceProcessSendBudget().some((terminated) => terminated === ws)) return true;
15243
16229
  }
15244
16230
  return false;
15245
16231
  }
@@ -16023,6 +17009,22 @@ function coerceFrame(value) {
16023
17009
  //#endregion
16024
17010
  //#region src/services/channel-bus/index.ts
16025
17011
  /**
17012
+ * Resolution of the channel bus from config, environment, or a supplied instance.
17013
+ *
17014
+ * Opt-in, like every other cross-cutting realtime switch here: with nothing
17015
+ * configured a deployment gets the memory bus and behaves exactly as it did
17016
+ * before this existed. Unlike `REALTIME_CDC=auto`, there is no "try it and see"
17017
+ * default — a bus changes where messages go, and quietly turning on a Postgres
17018
+ * NOTIFY per broadcast because a direct URL happened to be set is not a
17019
+ * decision to make on the user's behalf.
17020
+ *
17021
+ * Two transports ship, and neither adds a service to a deployment. A third is
17022
+ * not a code change here: `realtime.bus` also accepts an already-constructed
17023
+ * {@link ChannelBus}, so a transport published as its own package plugs in
17024
+ * without this file learning about it. See `@rebasepro/types` →
17025
+ * `types/channel_bus.ts` for the contract such a package implements.
17026
+ */
17027
+ /**
16026
17028
  * Merge `REALTIME_CHANNEL_BUS` into the configured bus.
16027
17029
  *
16028
17030
  * The environment wins over a *named* built-in, so the transport can be changed
@@ -16516,6 +17518,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
16516
17518
  * would leak rows the initial (isolated) fetch correctly hid.
16517
17519
  */
16518
17520
  rlsUserRole;
17521
+ /** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
17522
+ rlsRequest;
16519
17523
  /**
16520
17524
  * Verbose subscription tracing.
16521
17525
  *
@@ -17443,7 +18447,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17443
18447
  roles: activeAuth.roles,
17444
18448
  isAnonymous: activeAuth.isAnonymous === true,
17445
18449
  claims: activeAuth.claims
17446
- }, this.rlsUserRole);
18450
+ }, this.rlsRequest ?? this.rlsUserRole);
17447
18451
  let hookContext;
17448
18452
  const txEntityService = new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth));
17449
18453
  const fetchedEntities = collectionRequest.countOnly ? [] : await txEntityService.fetchCollectionForRest(notifyPath, {
@@ -17644,7 +18648,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17644
18648
  roles: activeAuth.roles,
17645
18649
  isAnonymous: activeAuth.isAnonymous === true,
17646
18650
  claims: activeAuth.claims
17647
- }, this.rlsUserRole);
18651
+ }, this.rlsRequest ?? this.rlsUserRole);
17648
18652
  let hookContext;
17649
18653
  let processedEntity = await new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth)).fetchOneForRest(notifyPath, id, include, collection?.databaseId) ?? void 0;
17650
18654
  if (processedEntity) {
@@ -19257,7 +20261,7 @@ var PostgresCollectionRegistry = class extends CollectionRegistry {
19257
20261
  * A concrete table does not satisfy it: its columns have specific types and it
19258
20262
  * carries methods and symbols besides, so `Record<string, AnyPgColumn>` is not
19259
20263
  * a supertype and a direct `as` is refused. Written out, that refusal was
19260
- * answered six times with `as unknown as RebasePgTable`, which also discarded
20264
+ * answered six times with a double cast to `RebasePgTable`, which also discarded
19261
20265
  * the check that the thing being converted is a table at all — the parameter
19262
20266
  * below is what restores it.
19263
20267
  */
@@ -20358,7 +21362,7 @@ var RefreshTokenService = class RefreshTokenService {
20358
21362
  * `selection()` is assembled at runtime from the columns this table actually
20359
21363
  * has, so drizzle types the row as an open record and nothing static
20360
21364
  * connects it to the interface. Both call sites used to assert the
20361
- * connection — `row as unknown as RefreshTokenInfo` — which claims every
21365
+ * connection — a double cast of `row` to `RefreshTokenInfo` — which claims every
20362
21366
  * optional field is present and correctly typed on a row where, by
20363
21367
  * construction, some of them were never selected.
20364
21368
  *
@@ -21313,13 +22317,7 @@ async function ensureHistoryTableExists(db, options = {}) {
21313
22317
  $fn$
21314
22318
  `));
21315
22319
  await db.execute(sql.raw(`REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC`));
21316
- await db.execute(sql.raw(`
21317
- DO $grant$ BEGIN
21318
- IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN
21319
- GRANT EXECUTE ON FUNCTION ${signature} TO ${REBASE_USER_ROLE};
21320
- END IF;
21321
- END $grant$
21322
- `));
22320
+ await db.execute(sql.raw(grantExecuteToRequestRolesSql(signature)));
21323
22321
  return {
21324
22322
  inTransaction: true,
21325
22323
  entryFormat
@@ -21829,15 +22827,15 @@ function patchPgArrayNullSafety(tables) {
21829
22827
  function patchPgNumericToNumber(tables) {
21830
22828
  let patchedCount = 0;
21831
22829
  const patch = (column) => {
21832
- const marked = column;
21833
- if (marked.__rebaseNumericPatched) return;
21834
- marked.__rebaseNumericPatched = true;
21835
- column.mapFromDriverValue = function(value) {
22830
+ if (Object.hasOwn(column, "__rebaseNumericPatched")) return;
22831
+ Object.defineProperty(column, "__rebaseNumericPatched", { value: true });
22832
+ const toNumber = (value) => {
21836
22833
  if (value === null || value === void 0) return value;
21837
22834
  if (typeof value === "number") return value;
21838
22835
  const parsed = Number(value);
21839
22836
  return Number.isNaN(parsed) ? value : parsed;
21840
22837
  };
22838
+ column.mapFromDriverValue = toNumber;
21841
22839
  patchedCount++;
21842
22840
  };
21843
22841
  for (const tableOrRelation of Object.values(tables)) {
@@ -21964,6 +22962,23 @@ function resolveDriftCheckName(col, registeredTableNames) {
21964
22962
  return (isRelationalCollectionConfig(col) ? col.table : void 0) ?? registeredTableNames.find((k) => k === col.slug) ?? col.slug;
21965
22963
  }
21966
22964
  /**
22965
+ * The relations the boot's drift check looks for a collection's table among.
22966
+ *
22967
+ * Deliberately unfiltered by schema: a table that is missing from where the
22968
+ * collection says it lives is very often sitting in another schema entirely
22969
+ * (see the misplaced-table report), and knowing *which* is the whole answer.
22970
+ *
22971
+ * Views as well as tables: a view collection serves a view of its own name (a
22972
+ * materialized one, a plain view over its stored rows), and reading only base
22973
+ * tables reported every one of them as missing on every boot.
22974
+ */
22975
+ var DRIFT_CHECK_RELATIONS_SQL = `
22976
+ SELECT table_name, table_schema
22977
+ FROM information_schema.tables
22978
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
22979
+ AND table_type IN ('BASE TABLE', 'VIEW')
22980
+ `;
22981
+ /**
21967
22982
  * Why the tables this backend serves are not in the database — the part of the
21968
22983
  * drift warning that has to be true rather than merely plausible.
21969
22984
  *
@@ -22100,6 +23115,7 @@ var SCHEMA_META_SCHEMA = "rebase";
22100
23115
  function describeEnsureFailure(failure) {
22101
23116
  switch (failure.kind) {
22102
23117
  case "comment-column": return `🔍 [schema] Could not record the search fingerprint on "${failure.target}" — search works, but a later change to the \`search\` block will not be detected: ${failure.error}`;
23118
+ case "rename-index": return `🐢 [schema] Could not adopt an existing index on "${failure.target}" — the declared index is built beside it instead, and writes maintain both until one is dropped: ${failure.error}`;
22103
23119
  case "create-index": return `🐢 [schema] Could not create an index on "${failure.target}" — the collection serves and returns the same rows, but queries that would have used this index will scan instead. Boot is not failed over an index: ${failure.error}`;
22104
23120
  default: return `🔗 [schema] Could not add foreign key "${failure.target}" — the column exists and the collection still serves, but rows are not policed by this constraint: ${failure.error}`;
22105
23121
  }
@@ -22229,8 +23245,10 @@ function postgresDriverConfigFromEnv(config, env = process.env, sourceKey = DEFA
22229
23245
  const directConnectionString = config.directConnectionString || (isDefaultSource ? read("DATABASE_DIRECT_URL") : void 0);
22230
23246
  const pooled = config.pooled ?? (isDefaultSource ? read("DATABASE_POOLED")?.toLowerCase() === "true" : void 0);
22231
23247
  const readRouting = config.readRouting ?? (read("REBASE_READ_STICKY_MS") || read("REBASE_READ_MAX_LAG_MS") ? readRoutingOptionsFromEnv(env) : void 0);
23248
+ const rls = rlsConfigFromEnv(config.rls, read);
22232
23249
  return {
22233
23250
  ...config,
23251
+ ...rls ? { rls } : {},
22234
23252
  ...readConnectionString ? { readConnectionString } : {},
22235
23253
  ...directConnectionString ? { directConnectionString } : {},
22236
23254
  ...pooled ? { pooled } : {},
@@ -22280,7 +23298,11 @@ async function openPostgresDriver(pgConfig, config) {
22280
23298
  }));
22281
23299
  }
22282
23300
  if (unprotectedJoinTables.length > 0) {
22283
- logger.warn(`🔒 [rls] ${unprotectedJoinTables.length} join table(s) have row-level security disabled: ${unprotectedJoinTables.join(", ")}. The API does not serve a join table, with RLS or without, but ${REBASE_USER_ROLE$1} keeps its grants on these, so SQL your own code runs as a caller reaches every row.`);
23301
+ const requestRoles = resolveRlsSettings({
23302
+ ...declaredDatabaseRls(config.dataSourceKey ?? DEFAULT_DATA_SOURCE_KEY),
23303
+ ...pgConfig.rls
23304
+ }).roles.join(", ");
23305
+ logger.warn(`🔒 [rls] ${unprotectedJoinTables.length} join table(s) have row-level security disabled: ${unprotectedJoinTables.join(", ")}. The API does not serve a join table, with RLS or without, but ${requestRoles} keeps its grants on these, so SQL your own code runs as a caller reaches every row.`);
22284
23306
  for (const t of unprotectedJoinTables) schema.tablesMap.delete(t);
22285
23307
  }
22286
23308
  if (policyless.length > 0) logger.warn(`🔒 [rls] ${policyless.length} table(s) have RLS enabled but no policies, so they will return no rows: ${policyless.join(", ")}`);
@@ -22372,7 +23394,7 @@ async function openPostgresDriver(pgConfig, config) {
22372
23394
  let readRouter;
22373
23395
  let readPool;
22374
23396
  if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
22375
- const { createReadReplicaConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
23397
+ const { createReadReplicaConnection } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
22376
23398
  const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
22377
23399
  ...pgConfig.poolConfig,
22378
23400
  pooled
@@ -22388,7 +23410,7 @@ async function openPostgresDriver(pgConfig, config) {
22388
23410
  let sessionDb;
22389
23411
  let sessionPool;
22390
23412
  if (pooled && directUrl) {
22391
- const { createDirectDatabaseConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
23413
+ const { createDirectDatabaseConnection } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
22392
23414
  const session = createDirectDatabaseConnection(directUrl, void 0, {
22393
23415
  max: 3,
22394
23416
  idleTimeoutMillis: 1e4
@@ -22414,6 +23436,24 @@ async function openPostgresDriver(pgConfig, config) {
22414
23436
  realtimeService.setDataDriver(driver);
22415
23437
  let rlsEnforcement;
22416
23438
  let exposedInternalTables;
23439
+ /** Set where the admin switch is settled; see {@link PostgresDriverInternals.adminPoliciesLive}. */
23440
+ let adminPoliciesLive = false;
23441
+ const rls = resolveRlsSettings({
23442
+ ...declaredDatabaseRls(sourceKey),
23443
+ ...pgConfig.rls
23444
+ });
23445
+ const policyShape = declaredRlsPolicyShape(sourceKey);
23446
+ if (rls.policyTarget !== policyShape.policyTarget || rls.defaultPolicies !== policyShape.defaultPolicies || rls.adminPolicies !== policyShape.adminPolicies) throw new Error(`rls.policyTarget, rls.adminPolicies and rls.defaultPolicies shape the policy SQL that \`rebase db generate\` writes, and the CLI cannot see the driver's code. Declare them on the database instead — database({ rls: { policyTarget: "${rls.policyTarget}", adminPolicies: "${rls.adminPolicies}", defaultPolicies: ${rls.defaultPolicies} } }) — or set REBASE_RLS_POLICY_TARGET / REBASE_RLS_ADMIN_POLICIES / REBASE_RLS_DEFAULT_POLICIES.`);
23447
+ /** The tables this driver serves — collections, junctions — for `grants: "managed"`. */
23448
+ const managedTables = () => registry.getTableNames().flatMap((name) => {
23449
+ const table = registry.getTable(name);
23450
+ if (!table) return [];
23451
+ const config = getTableConfig(table);
23452
+ return [{
23453
+ schema: config.schema ?? "public",
23454
+ table: config.name
23455
+ }];
23456
+ });
22417
23457
  {
22418
23458
  const runSql = async (text) => {
22419
23459
  return (await schemaAwareDb.execute(sql.raw(text))).rows ?? [];
@@ -22427,35 +23467,87 @@ async function openPostgresDriver(pgConfig, config) {
22427
23467
  const posture = await detectConnectionPosture(runSql, managedSchemas);
22428
23468
  if (posture.privileged) {
22429
23469
  const bypassesNow = posture.superuser || posture.bypassRLS || posture.ownsTables;
23470
+ const roleList = rls.roles.map((r) => `"${r}"`).join(", ");
22430
23471
  let switched = true;
22431
23472
  if (!provision) {
22432
- const roleExists = (await runSql(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}'`)).length > 0;
23473
+ const roleExists = (await runSql(`SELECT rolname FROM pg_roles WHERE rolname = ANY(ARRAY[${rls.roles.map((r) => `'${r}'`).join(", ")}]::text[])`)).length === rls.roles.length;
22433
23474
  switched = roleExists || bypassesNow;
22434
23475
  if (roleExists) {
22435
- exposedInternalTables = await findExposedInternalTables(runSql, managedSchemas);
22436
- if (exposedInternalTables.length > 0) logger.warn(`⚠️ RLS enforcement: the request role "${REBASE_USER_ROLE$1}" can reach framework tables no user should: ${exposedInternalTables.join(", ")}. A provisioning boot revokes this; this driver was opened without provisioning, so nothing does.`);
23476
+ try {
23477
+ assertRecordedRequestRoles(rls.roles, await readRecordedRequestRoles(runSql), await roleHoldsTableGrants(runSql, managedSchemas));
23478
+ for (const role of rls.roles) {
23479
+ await assertAppRoleRestricted(runSql, role);
23480
+ await proveRoleSwitch(runSql, managedSchemas, posture.role, role);
23481
+ }
23482
+ } catch (err) {
23483
+ if (bypassesNow) throw err;
23484
+ switched = false;
23485
+ logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" owns no tables yet and is subject to RLS, so requests are served without the switch: ${err instanceof Error ? err.message : String(err)}`);
23486
+ }
23487
+ for (const role of rls.roles) {
23488
+ const exposed = await findExposedInternalTables(runSql, managedSchemas, role);
23489
+ if (exposed.length === 0) continue;
23490
+ exposedInternalTables = [...exposedInternalTables ?? [], ...exposed];
23491
+ logger.warn(`⚠️ RLS enforcement: the request role "${role}" can reach framework tables no user should: ${exposed.join(", ")}. A provisioning boot revokes this; this driver was opened without provisioning, so nothing does.`);
23492
+ }
22437
23493
  }
22438
- if (!roleExists && bypassesNow) logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" bypasses row-level security and the restricted role "${REBASE_USER_ROLE$1}" does not exist yet — this driver was opened without provisioning, so it was not created. Requests made as a user will fail until a server boot (or \`rebase db push\`) creates it; requests as the connection itself are unaffected.`);
23494
+ if (!roleExists && bypassesNow) logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" bypasses row-level security and the restricted role ${roleList} does not exist yet — this driver was opened without provisioning, so it was not created. Requests made as a user will fail until a server boot (or \`rebase db push\`) creates it; requests as the connection itself are unaffected.`);
22439
23495
  } else try {
22440
- await ensureAppRole(runSql, managedSchemas);
23496
+ const recorded = await readRecordedRequestRoles(runSql);
23497
+ assertRecordedRequestRoles(rls.roles, recorded, await roleHoldsTableGrants(runSql, managedSchemas));
23498
+ if (recorded ? recorded.join(",") !== rls.roles.join(",") : rls.roles.join(",") !== REBASE_USER_ROLE$1) await recordRequestRoles(runSql, rls.roles);
23499
+ for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
23500
+ role,
23501
+ provisionRole: rls.provisionRole,
23502
+ grants: rls.grants,
23503
+ managedTables: managedTables(),
23504
+ inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
23505
+ });
22441
23506
  } catch (err) {
22442
23507
  if (bypassesNow) throw err;
22443
23508
  switched = false;
22444
23509
  logger.warn(`⚠️ RLS enforcement: connection role "${posture.role}" owns no tables yet and is subject to RLS, but it may create tables in ${managedSchemas.join(", ")} — and a table's owner bypasses every non-FORCE policy on it. The restricted role could not be provisioned: ${err instanceof Error ? err.message : String(err)}`);
22445
23510
  }
22446
23511
  if (switched) {
22447
- driver.rlsUserRole = REBASE_USER_ROLE$1;
22448
- realtimeService.rlsUserRole = REBASE_USER_ROLE$1;
23512
+ const settled = await settleAdminSwitch(runSql, managedSchemas, rls, { provision });
23513
+ const request = settled.request;
23514
+ adminPoliciesLive = settled.adminPoliciesLive;
23515
+ driver.rlsUserRole = rls.defaultRole;
23516
+ realtimeService.rlsUserRole = rls.defaultRole;
23517
+ driver.rlsRequest = request;
23518
+ realtimeService.rlsRequest = request;
22449
23519
  const why = posture.superuser ? "superuser" : posture.bypassRLS ? "BYPASSRLS" : posture.ownsTables ? "table owner" : "may create (and would then own) tables in the schemas it serves";
22450
- rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as "${REBASE_USER_ROLE$1}" (connection "${posture.role}" bypasses RLS: ${why})`;
23520
+ rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as ${roleList} (connection "${posture.role}" bypasses RLS: ${why})` + (rls.nonDefaults.length > 0 ? `; rls: ${rls.nonDefaults.join(", ")}` : "");
23521
+ for (const note of rlsHandoverNotes(rls)) logger.info(`🔐 [rls] ${note}`);
23522
+ for (const role of [...rls.roles, ...rls.adminRoles.values()]) {
23523
+ if (rls.sharedRole === "ignore") break;
23524
+ const others = await findOtherRoleMembers(runSql, role);
23525
+ if (others.length === 0) continue;
23526
+ const message = `The request role "${role}" can also be used by ${others.map((o) => `"${o}"`).join(", ")}, which can connect to this database, switch into it, and pass its policies as whichever user it likes. Give this project a role of its own (rls.requestRole / REBASE_RLS_REQUEST_ROLE, then \`rebase db request-role migrate\`), revoke CONNECT on this database from PUBLIC, or set rls.sharedRole to "ignore" if the role is shared on purpose.`;
23527
+ if (rls.sharedRole === "refuse") throw new Error(`Refusing to serve: ${message}`);
23528
+ logger.warn(`⚠️ RLS enforcement: ${message}`);
23529
+ }
23530
+ for (const role of rls.roles) {
23531
+ const ungrantable = await findUngrantableTables(runSql, collectionsOnThisSource().map((c) => ({
23532
+ schema: c.schema ?? "public",
23533
+ table: getTableName$1(c)
23534
+ })).filter((t) => Boolean(t.table)), role);
23535
+ if (ungrantable.length === 0) continue;
23536
+ logger.warn(`⚠️ RLS enforcement: requests run as "${role}", which holds no privilege on ${ungrantable.length === 1 ? "this table" : "these tables"}, and connection "${posture.role}" cannot grant one because another role owns them. Every request to them will be refused until the owner runs the grant:
23537
+ ` + ungrantable.map((t) => ` ${t.name} (owner "${t.owner}"): ${t.grant}`).join("\n"));
23538
+ }
22451
23539
  }
22452
23540
  if (posture.superuser || posture.bypassRLS) {
22453
23541
  const message = `The database connection runs as ${posture.superuser ? "a superuser" : "a BYPASSRLS role"} ("${posture.role}"). User requests are isolated via SET LOCAL ROLE, but connect as a non-superuser table-owner role in production so the server/owner context is least-privilege.`;
22454
23542
  if (isScaffoldedLocalDatabase(pgConfig.connectionString)) logger.debug(`🔐 ${message}`);
22455
23543
  else logger.warn(`⚠️ ${message}`);
22456
23544
  }
22457
- } else rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
22458
- await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ?? posture.role);
23545
+ } else {
23546
+ rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
23547
+ if (rls.adminPolicies === "adminRole") await ensureConnectionInheritsAdminRole(runSql, { provision });
23548
+ }
23549
+ if (!driver.rlsUserRole && rls.policyTarget === "requestRole") throw new Error(`rls.policyTarget is "requestRole", but requests are not switching to a request role here (connection "${posture.role}" is ${posture.privileged ? "not able to switch" : "subject to RLS natively"}), so every policy would deny every row. Use policyTarget "public" with this connection, or connect as a role that owns the tables so requests switch.`);
23550
+ await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ? rls.roles : posture.role);
22459
23551
  warnOnAnonymousGrants(collectionsOnThisSource());
22460
23552
  warnOnLegacyRlsFunctions(collectionsOnThisSource());
22461
23553
  }
@@ -22577,12 +23669,7 @@ async function openPostgresDriver(pgConfig, config) {
22577
23669
  try {
22578
23670
  const registeredCollections = collectionsOnThisSource();
22579
23671
  if (registeredCollections.length > 0) {
22580
- const result = await schemaAwareDb.execute(sql.raw(`
22581
- SELECT table_name, table_schema
22582
- FROM information_schema.tables
22583
- WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
22584
- AND table_type = 'BASE TABLE'
22585
- `));
23672
+ const result = await schemaAwareDb.execute(sql.raw(DRIFT_CHECK_RELATIONS_SQL));
22586
23673
  const tablesByName = /* @__PURE__ */ new Map();
22587
23674
  for (const row of result.rows) {
22588
23675
  const schemas = tablesByName.get(row.table_name) ?? [];
@@ -22643,6 +23730,9 @@ async function openPostgresDriver(pgConfig, config) {
22643
23730
  driver,
22644
23731
  poolManager,
22645
23732
  provisioned: provision,
23733
+ rls,
23734
+ adminPoliciesLive,
23735
+ managedTables,
22646
23736
  rlsEnforcement,
22647
23737
  exposedInternalTables,
22648
23738
  provisionCdcForTables
@@ -22715,7 +23805,7 @@ function createPostgresBootstrapper(pgConfig) {
22715
23805
  const openIndexBuildSession = (driverResult) => async () => {
22716
23806
  const db = requireProvisioningDb(driverResult);
22717
23807
  const pool = "$client" in db ? db.$client : void 0;
22718
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
23808
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-DDdnjaOW.js").then((n) => n.r);
22719
23809
  const config = effectiveConfig();
22720
23810
  if (isPooledPool(pool) || config.pooled) {
22721
23811
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -22746,8 +23836,9 @@ function createPostgresBootstrapper(pgConfig) {
22746
23836
  */
22747
23837
  const provisionRlsRuntime = async (driverResult) => {
22748
23838
  const db = requireProvisioningDb(driverResult);
22749
- const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
23839
+ const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent, ensureRequestRoleFunction } = await import("./rls-bootstrap-sql-CxszeSc7.js").then((n) => n.c);
22750
23840
  const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
23841
+ if (declaredRlsPolicyShape().policyTarget === "requestRole") await ensureRequestRoleFunction(run);
22751
23842
  if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
22752
23843
  await db.transaction(async (tx) => {
22753
23844
  await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('rebase_auth_functions_init'))`);
@@ -22770,7 +23861,7 @@ function createPostgresBootstrapper(pgConfig) {
22770
23861
  for (const [qualified, { schema, table }] of withheldTables) try {
22771
23862
  await runSql(revokeUserRoleSql(schema, table));
22772
23863
  } catch (err) {
22773
- throw new Error(`Refusing to start: row-level security could not be enabled on "${qualified}", and the privileges the schema-wide grant just gave ${REBASE_USER_ROLE$1} on it could not be taken back. The table would be served with no row filtering. Fix the database permissions (the connection role must own the table, or be able to ALTER it) and boot again: ` + (err instanceof Error ? err.message : String(err)));
23864
+ throw new Error(`Refusing to start: row-level security could not be enabled on "${qualified}", and the privileges the schema-wide grant just gave the request role on it could not be taken back. The table would be served with no row filtering. Fix the database permissions (the connection role must own the table, or be able to ALTER it) and boot again: ` + (err instanceof Error ? err.message : String(err)));
22774
23865
  }
22775
23866
  };
22776
23867
  return {
@@ -22780,8 +23871,8 @@ function createPostgresBootstrapper(pgConfig) {
22780
23871
  const opened = await openPostgresDriver(effectiveConfig(init.dataSourceKey), init);
22781
23872
  if (opened.internals.rlsEnforcement) logger.info(opened.internals.rlsEnforcement);
22782
23873
  const exposed = opened.internals.exposedInternalTables ?? [];
22783
- if (exposed.length > 0) throw new Error(`The request role "${REBASE_USER_ROLE$1}" can read or write framework tables that hold sessions, key hashes and job payloads: ${exposed.join(", ")}.\nA provisioning boot revokes this, and this backend changes nothing in its database (provisioning is off). Revoke it as part of your change process:
22784
- ` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${REBASE_USER_ROLE$1};`).join("\n"));
23874
+ if (exposed.length > 0) throw new Error(`The request role ${(opened.internals.rls?.roles ?? [REBASE_USER_ROLE$1]).map((r) => `"${r}"`).join(", ")} can read or write framework tables that hold sessions, key hashes and job payloads: ${exposed.join(", ")}.\nA provisioning boot revokes this, and this backend changes nothing in its database (provisioning is off). Revoke it as part of your change process:
23875
+ ` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${(opened.internals.rls?.roles ?? [REBASE_USER_ROLE$1]).join(", ")};`).join("\n"));
22785
23876
  return opened;
22786
23877
  },
22787
23878
  async initializeAuth(config, driverResult) {
@@ -22859,11 +23950,11 @@ function createPostgresBootstrapper(pgConfig) {
22859
23950
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
22860
23951
  }) };
22861
23952
  }
22862
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
23953
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CbZj9ovZ.js").then((n) => n.i);
22863
23954
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
22864
23955
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
22865
23956
  if (historyIndexes.length > 0) {
22866
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
23957
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-DDdnjaOW.js").then((n) => n.r);
22867
23958
  const indexOptions = {
22868
23959
  log: (message) => logger.info(`[history] ${message}`),
22869
23960
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -22919,9 +24010,9 @@ function createPostgresBootstrapper(pgConfig) {
22919
24010
  * proved it can bootstrap with.
22920
24011
  */
22921
24012
  async ensureCollectionSchema(collections, driverResult, log) {
22922
- const { ensureCollectionTables } = await import("./ensure-collection-tables-BK--gDo6.js").then((n) => n.n);
24013
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-h1mUO7Uu.js").then((n) => n.n);
22923
24014
  const queryable = provisioningQueryable(driverResult);
22924
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
24015
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CbZj9ovZ.js").then((n) => n.i);
22925
24016
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
22926
24017
  const plan = await ensureCollectionTables(queryable, collections, log, {
22927
24018
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -22933,7 +24024,7 @@ function createPostgresBootstrapper(pgConfig) {
22933
24024
  pendingIndexBuild?.cancel();
22934
24025
  pendingIndexBuild = void 0;
22935
24026
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
22936
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
24027
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-DDdnjaOW.js").then((n) => n.r);
22937
24028
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
22938
24029
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
22939
24030
  log: (message) => logger.info(`[schema] ${message}`),
@@ -22973,11 +24064,12 @@ function createPostgresBootstrapper(pgConfig) {
22973
24064
  await provisionRlsRuntime(driverResult);
22974
24065
  },
22975
24066
  async ensureCollectionPolicies(collections, driverResult, log) {
22976
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-DUpWJb5D.js");
24067
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-DJsOMpaI.js");
22977
24068
  const queryable = provisioningQueryable(driverResult);
22978
24069
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
22979
24070
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
22980
- const outcome = await ensureCollectionPolicies(queryable, collections, log);
24071
+ const internals = driverResult?.internals;
24072
+ const outcome = await ensureCollectionPolicies(queryable, collections, log, { adminRoleAvailable: internals?.adminPoliciesLive === true });
22981
24073
  withheldTables.clear();
22982
24074
  for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) {
22983
24075
  const dot = u.table.indexOf(".");
@@ -22995,10 +24087,10 @@ function createPostgresBootstrapper(pgConfig) {
22995
24087
  else logger.warn(`${message}; they are re-applied on the next boot.`);
22996
24088
  }
22997
24089
  const unrevoked = outcome.unsecured.filter((u) => !u.grantWithdrawn);
22998
- for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from ${REBASE_USER_ROLE$1}, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
22999
- if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + `, and the privileges granted to ${REBASE_USER_ROLE$1} could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.`);
24090
+ for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from the request role, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
24091
+ if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + ", and the privileges granted to the request role could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.");
23000
24092
  try {
23001
- const { dropLegacyAuthSchema } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
24093
+ const { dropLegacyAuthSchema } = await import("./rls-bootstrap-sql-CxszeSc7.js").then((n) => n.c);
23002
24094
  await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
23003
24095
  info: (m) => logger.info(m),
23004
24096
  warn: (m) => logger.warn(m)
@@ -23064,11 +24156,17 @@ function createPostgresBootstrapper(pgConfig) {
23064
24156
  "rebase",
23065
24157
  ...registry.getCollections().map((c) => c.schema).filter((s) => typeof s === "string")
23066
24158
  ];
24159
+ const rls = internals.rls ?? resolveRlsSettings(void 0);
24160
+ const grantOptions = (role) => ({
24161
+ role,
24162
+ mode: rls.grants,
24163
+ managedTables: internals.managedTables?.() ?? []
24164
+ });
23067
24165
  if (driver.rlsUserRole) {
23068
24166
  try {
23069
- await ensureAppRoleGrants(runSql, managedSchemas);
24167
+ for (const role of rls.roles) await ensureAppRoleGrants(runSql, managedSchemas, grantOptions(role));
23070
24168
  } catch (err) {
23071
- logger.warn(`⚠️ RLS enforcement: could not grant "${REBASE_USER_ROLE$1}" on the schemas provisioning created (${managedSchemas.join(", ")}). Requests that touch them will be refused with "permission denied for schema …" until a boot can: ${err instanceof Error ? err.message : String(err)}`);
24169
+ logger.warn(`⚠️ RLS enforcement: could not grant ${rls.roles.map((r) => `"${r}"`).join(", ")} on the schemas provisioning created (${managedSchemas.join(", ")}). Requests that touch them will be refused with "permission denied for schema …" until a boot can: ${err instanceof Error ? err.message : String(err)}`);
23072
24170
  }
23073
24171
  await withholdAgain(runSql);
23074
24172
  return;
@@ -23076,20 +24174,29 @@ function createPostgresBootstrapper(pgConfig) {
23076
24174
  const posture = await detectConnectionPosture(runSql, managedSchemas);
23077
24175
  if (!posture.superuser && !posture.bypassRLS && !posture.ownsTables) return;
23078
24176
  try {
23079
- await ensureAppRole(runSql, managedSchemas);
24177
+ for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
24178
+ role,
24179
+ provisionRole: rls.provisionRole,
24180
+ grants: rls.grants,
24181
+ managedTables: internals.managedTables?.() ?? [],
24182
+ inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
24183
+ });
23080
24184
  } catch (err) {
23081
24185
  throw new Error(`The database connection role "${posture.role}" now owns tables in this database, so it bypasses every row-level security policy on them — but the restricted role it should switch to could not be provisioned, so authenticated requests would be served with no policy applied at all. Refusing to serve.\n\n${err instanceof Error ? err.message : String(err)}`);
23082
24186
  }
23083
24187
  await withholdAgain(runSql);
23084
- driver.rlsUserRole = REBASE_USER_ROLE$1;
23085
- realtimeService.rlsUserRole = REBASE_USER_ROLE$1;
23086
- logger.info(`🔐 RLS enforcement active: the connection role "${posture.role}" became a table owner during this boot, so authenticated requests now run as "${REBASE_USER_ROLE$1}".`);
24188
+ const { request } = await settleAdminSwitch(runSql, managedSchemas, rls, { provision: true });
24189
+ driver.rlsUserRole = rls.defaultRole;
24190
+ realtimeService.rlsUserRole = rls.defaultRole;
24191
+ driver.rlsRequest = request;
24192
+ realtimeService.rlsRequest = request;
24193
+ logger.info(`🔐 RLS enforcement active: the connection role "${posture.role}" became a table owner during this boot, so authenticated requests now run as ${rls.roles.map((r) => `"${r}"`).join(", ")}.`);
23087
24194
  },
23088
24195
  getAdmin(driverResult) {
23089
24196
  return driverResult.internals.driver.admin;
23090
24197
  },
23091
24198
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
23092
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-D2y88dOa.js").then((n) => n.c);
24199
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-BSYV_KSw.js").then((n) => n.c);
23093
24200
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
23094
24201
  const realtimeConfig = effectiveConfig().realtime;
23095
24202
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -23202,13 +24309,24 @@ async function openRebase(options) {
23202
24309
  throw error;
23203
24310
  }
23204
24311
  const resolveAccessor = createAccessorSlugResolver(() => registry.getCollections());
23205
- const dataAs = async (identity) => buildSdkData(await driver.withAuth(userFor(identity)), { resolveAccessor });
23206
- const dataAsAdmin = await dataAs(SERVICE_IDENTITY);
24312
+ const scopedTo = async (identity) => {
24313
+ const scoped = await driver.withAuth(userFor(identity));
24314
+ return {
24315
+ scoped,
24316
+ data: buildSdkData(scoped, { resolveAccessor })
24317
+ };
24318
+ };
24319
+ const service = await scopedTo(SERVICE_IDENTITY);
24320
+ const dataAsAdmin = service.data;
23207
24321
  const admin = driver.admin;
23208
24322
  let closed = false;
23209
24323
  return {
23210
24324
  dataAsAdmin,
23211
24325
  collections,
24326
+ async sqlAsAdmin(query, sqlOptions) {
24327
+ if (!service.scoped.sql) throw new Error("This driver cannot run SQL under row-level security.");
24328
+ return service.scoped.sql(query, sqlOptions);
24329
+ },
23212
24330
  async sql(query, sqlOptions) {
23213
24331
  if (!isSQLAdmin(admin)) throw new Error("This driver cannot run raw SQL.");
23214
24332
  warnOnTableDdl(query, (message) => logger.warn(message));
@@ -23222,7 +24340,13 @@ async function openRebase(options) {
23222
24340
  });
23223
24341
  },
23224
24342
  async withAuth(user) {
23225
- return { data: await dataAs(user) };
24343
+ const { scoped, data } = await scopedTo(user);
24344
+ const sql = scoped.sql?.bind(scoped);
24345
+ if (!sql) throw new Error("This driver cannot run SQL as a caller.");
24346
+ return {
24347
+ data,
24348
+ sql
24349
+ };
23226
24350
  },
23227
24351
  async close() {
23228
24352
  if (closed) return;
@@ -23234,4 +24358,4 @@ async function openRebase(options) {
23234
24358
  //#endregion
23235
24359
  export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
23236
24360
 
23237
- //# sourceMappingURL=open-rebase-CTNBmmH8.js.map
24361
+ //# sourceMappingURL=open-rebase-Cvid3iwR.js.map