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

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 (127) hide show
  1. package/dist/{BranchService-BPssiD8_.js → BranchService-BIIBF5ZL.js} +3 -3
  2. package/dist/{BranchService-BPssiD8_.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +105 -9
  4. package/dist/PostgresBootstrapper.d.ts +14 -0
  5. package/dist/{backup-cli-C1wcj-rc.js → backup-cli-QcOpmRpQ.js} +3 -3
  6. package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
  7. package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-BSNpEUOS.js} +2 -2
  8. package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
  9. package/dist/{cli-console-CJLtH58M.js → cli-console-DTsm96lW.js} +6 -6
  10. package/dist/{cli-console-CJLtH58M.js.map → cli-console-DTsm96lW.js.map} +1 -1
  11. package/dist/{cli-errors-DYets7cp.js → cli-errors-DwqFRIWz.js} +69 -6
  12. package/dist/cli-errors-DwqFRIWz.js.map +1 -0
  13. package/dist/cli-helpers.d.ts +10 -0
  14. package/dist/cli.js +90 -44
  15. package/dist/cli.js.map +1 -1
  16. package/dist/{connection-CcYqncW5.js → connection-COuS5Fm-.js} +15 -2
  17. package/dist/connection-COuS5Fm-.js.map +1 -0
  18. package/dist/connection.d.ts +6 -0
  19. package/dist/database-preflight-D5JtPt8i.js +151 -0
  20. package/dist/database-preflight-D5JtPt8i.js.map +1 -0
  21. package/dist/{databasePoolManager-XmhMczz0.js → databasePoolManager-7hXVurmG.js} +2 -2
  22. package/dist/{databasePoolManager-XmhMczz0.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
  23. package/dist/db-subcommands.d.ts +1 -1
  24. package/dist/{deferred-index-build-BwH6k1Og.js → deferred-index-build-B8feKnUj.js} +12 -8
  25. package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
  26. package/dist/{doctor-TJApVglQ.js → doctor-BaR11xUe.js} +20 -6
  27. package/dist/doctor-BaR11xUe.js.map +1 -0
  28. package/dist/{ensure-collection-policies-f0LIwiwp.js → ensure-collection-policies-85HiG-k1.js} +8 -8
  29. package/dist/{ensure-collection-policies-f0LIwiwp.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
  30. package/dist/{ensure-collection-tables-DvaCEy6X.js → ensure-collection-tables-DR_WcxLA.js} +20 -9
  31. package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
  32. package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Dh5UP_Zs.js} +4 -4
  33. package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
  34. package/dist/{enum-labels-kept-DAbJ_IIl.js → enum-labels-kept-DSU8lAnd.js} +3 -3
  35. package/dist/{enum-labels-kept-DAbJ_IIl.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
  36. package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
  37. package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
  39. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
  40. package/dist/{generate-files-DutUrsSS.js → generate-files-Bl3_D_oP.js} +11 -4
  41. package/dist/generate-files-Bl3_D_oP.js.map +1 -0
  42. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-BC3JA93M.js} +11 -4
  43. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
  44. package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-Jm93vyJB.js} +29 -6
  45. package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
  46. package/dist/index.d.ts +2 -1
  47. package/dist/index.es.js +22 -14
  48. package/dist/index.es.js.map +1 -1
  49. package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BfHmq3vN.js} +49 -4
  50. package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
  51. package/dist/{migrate-policy-stamps-CdljD_y1.js → migrate-policy-stamps-B4k1ggma.js} +7 -7
  52. package/dist/{migrate-policy-stamps-CdljD_y1.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
  53. package/dist/{open-rebase-DvmKIu7q.js → open-rebase-CiO_sjMT.js} +1574 -195
  54. package/dist/open-rebase-CiO_sjMT.js.map +1 -0
  55. package/dist/open-rebase.d.ts +6 -1
  56. package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-D1Nc0UML.js} +2 -2
  57. package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
  58. package/dist/pipelined-transaction.d.ts +131 -0
  59. package/dist/{plan-schema-DMVh77yb.js → plan-schema-BYxOzflz.js} +147 -8
  60. package/dist/plan-schema-BYxOzflz.js.map +1 -0
  61. package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-DKuTJHfc.js} +2 -2
  62. package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
  63. package/dist/{push-index-prebuild-C6wKdjYV.js → push-index-prebuild-bqXimSZz.js} +4 -4
  64. package/dist/{push-index-prebuild-C6wKdjYV.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
  65. package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CN9R8cHf.js} +2 -2
  66. package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
  67. package/dist/{push-legacy-renames-BFF72tHG.js → push-legacy-renames-CU_UYPbz.js} +4 -4
  68. package/dist/{push-legacy-renames-BFF72tHG.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
  69. package/dist/{push-policy-plan-lOTPeQ1u.js → push-policy-plan-JcyK94bc.js} +4 -4
  70. package/dist/{push-policy-plan-lOTPeQ1u.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
  71. package/dist/{render-ddl-NpPPDACz.js → render-ddl-DCdVP-pQ.js} +95 -4
  72. package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
  73. package/dist/request-role-cli-DSdRtvgH.js +260 -0
  74. package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
  75. package/dist/request-role-cli.d.ts +86 -0
  76. package/dist/request-role-migration-D9BZ5Uba.js +150 -0
  77. package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
  78. package/dist/rls-enforcement-BO618rnr.js +992 -0
  79. package/dist/rls-enforcement-BO618rnr.js.map +1 -0
  80. package/dist/rls-settings-De5NoHHy.js +211 -0
  81. package/dist/rls-settings-De5NoHHy.js.map +1 -0
  82. package/dist/schema/doctor-cli.js +144 -6
  83. package/dist/schema/doctor-cli.js.map +1 -1
  84. package/dist/schema/doctor-database.d.ts +27 -0
  85. package/dist/schema/generate-drizzle-schema.js +1 -1
  86. package/dist/schema/generate-files.d.ts +2 -1
  87. package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
  88. package/dist/schema/generate-postgres-ddl.js +1 -1
  89. package/dist/schema/introspect-db.js +2 -2
  90. package/dist/schema/introspect-runtime.d.ts +10 -1
  91. package/dist/schema/plan/diff-plan.d.ts +6 -1
  92. package/dist/schema/plan/plan-schema.d.ts +9 -1
  93. package/dist/schema/plan/render-ddl.d.ts +32 -1
  94. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  95. package/dist/schema/plan/types.d.ts +39 -0
  96. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  97. package/dist/schema/plan/view-names.d.ts +6 -0
  98. package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
  99. package/dist/security/caller-sql-columns.d.ts +60 -0
  100. package/dist/security/caller-sql.d.ts +8 -0
  101. package/dist/security/database-preflight.d.ts +24 -0
  102. package/dist/security/request-role-migration.d.ts +36 -0
  103. package/dist/security/rls-enforcement.d.ts +201 -20
  104. package/dist/security/rls-settings.d.ts +177 -0
  105. package/dist/services/FetchService.d.ts +12 -12
  106. package/dist/services/PersistService.d.ts +59 -0
  107. package/dist/services/collection-helpers.d.ts +3 -1
  108. package/dist/services/dataService.d.ts +2 -0
  109. package/dist/services/realtimeService.d.ts +3 -0
  110. package/dist/services/view-access.d.ts +21 -0
  111. package/dist/view-names-Dscp6--B.js +24 -0
  112. package/dist/view-names-Dscp6--B.js.map +1 -0
  113. package/dist/{websocket-CCJnghvG.js → websocket-B33YjKhs.js} +3 -3
  114. package/dist/{websocket-CCJnghvG.js.map → websocket-B33YjKhs.js.map} +1 -1
  115. package/package.json +7 -7
  116. package/dist/cli-errors-DYets7cp.js.map +0 -1
  117. package/dist/connection-CcYqncW5.js.map +0 -1
  118. package/dist/deferred-index-build-BwH6k1Og.js.map +0 -1
  119. package/dist/doctor-TJApVglQ.js.map +0 -1
  120. package/dist/ensure-collection-tables-DvaCEy6X.js.map +0 -1
  121. package/dist/generate-files-DutUrsSS.js.map +0 -1
  122. package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
  123. package/dist/open-rebase-DvmKIu7q.js.map +0 -1
  124. package/dist/plan-schema-DMVh77yb.js.map +0 -1
  125. package/dist/render-ddl-NpPPDACz.js.map +0 -1
  126. package/dist/rls-enforcement-BOHuHVlc.js +0 -502
  127. package/dist/rls-enforcement-BOHuHVlc.js.map +0 -1
@@ -1,33 +1,36 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, l as isPooledPool, m as transactionSettingsStatements, n as closeWithPool, p as searchPathList } from "./connection-CcYqncW5.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-COuS5Fm-.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, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-DYets7cp.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-BIHfsGZL.js";
7
- import { t as BranchService } from "./BranchService-BPssiD8_.js";
8
- import { a as ensureAppRoleGrants, c as revokeUserRoleSql, d as warnOnAnonymousGrants, f as warnOnLegacyRlsFunctions, i as ensureAppRole, n as applyAuthContext, o as findExposedInternalTables, p as warnOnRoleSchemaCollision, r as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as validatePolicyPgRoles } from "./rls-enforcement-BOHuHVlc.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-DwqFRIWz.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-D1Nc0UML.js";
8
+ import { t as BranchService } from "./BranchService-BIIBF5ZL.js";
9
+ import { C as warnOnRoleSchemaCollision, S as warnOnLegacyRlsFunctions, _ as revokeUserRoleSql, a as assertRecordedRequestRoles, b as validatePolicyPgRoles, c as ensureAppRole, d as findOtherRoleMembers, f as findUngrantableTables, g as recordRequestRoles, h as readRecordedRequestRoles, i as assertAppRoleRestricted, l as ensureAppRoleGrants, m as proveRoleSwitch, o as authContextStatement, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as findExposedInternalTables, x as warnOnAnonymousGrants, y as roleHoldsTableGrants } from "./rls-enforcement-BO618rnr.js";
9
10
  import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
10
11
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
11
- import { n as planSchema } from "./plan-schema-DMVh77yb.js";
12
- import { t as generateSchema } from "./generate-drizzle-schema-logic-CVRmZjP3.js";
13
- import { i as renderPgType } from "./render-ddl-NpPPDACz.js";
14
- import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-BwH6k1Og.js";
15
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CIGoIGcC.js";
16
- import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DvaCEy6X.js";
12
+ import { n as planSchema } from "./plan-schema-BYxOzflz.js";
13
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-C5FB7Fpo.js";
14
+ import { i as renderPgType } from "./render-ddl-DCdVP-pQ.js";
15
+ import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-B8feKnUj.js";
16
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-BSNpEUOS.js";
17
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DR_WcxLA.js";
17
18
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
18
- import { t as DatabasePoolManager } from "./databasePoolManager-XmhMczz0.js";
19
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CF-8zgYA.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-ChFg6UxI.js";
21
- import { Client, DatabaseError, Pool } from "pg";
22
- import { drizzle } from "drizzle-orm/node-postgres";
19
+ import { t as DatabasePoolManager } from "./databasePoolManager-7hXVurmG.js";
20
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-Dh5UP_Zs.js";
21
+ 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-Jm93vyJB.js";
22
+ import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-De5NoHHy.js";
23
+ import pg, { Client, DatabaseError, Pool } from "pg";
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
26
  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";
25
- import { PgArray, 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, 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, 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";
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";
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, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, joinConditions, 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";
33
+ import { prepareValue } from "pg/lib/utils.js";
31
34
  import { WebSocket } from "ws";
32
35
  import { EventEmitter } from "events";
33
36
  import { createHash as createHash$1, randomBytes, randomUUID } from "crypto";
@@ -536,8 +539,8 @@ function warnOnKeysTheAdminCannotResolve(collections, registry) {
536
539
  * callers decide what that means, since "unaddressable" is a different answer
537
540
  * in a notification (broadcast a wildcard) than in a save (fail).
538
541
  */
539
- function deriveRowAddress(row, collection, registry) {
540
- const composite = buildCompositeId(row, getPrimaryKeys(collection, registry));
542
+ function deriveRowAddress(row, collection, registry, primaryKeys = getPrimaryKeys(collection, registry)) {
543
+ const composite = buildCompositeId(row, primaryKeys);
541
544
  if (composite && composite.split(COMPOSITE_ID_SEPARATOR).some((part) => part !== "")) return composite;
542
545
  if (row.id !== void 0 && row.id !== null) return String(row.id);
543
546
  return "";
@@ -820,6 +823,26 @@ function toMembershipList(value) {
820
823
  return Array.isArray(value) ? value : [value];
821
824
  }
822
825
  /**
826
+ * `array-contains-all` (`@>`: every listed element is in the column) and
827
+ * `array-contained-by` (`<@`: every element of the column is listed), on a
828
+ * native array or a JSONB array. Both are containment, so a GIN index on the
829
+ * column serves them.
830
+ *
831
+ * A bare element is the one-element list and `null` a null check, as for
832
+ * `array-contains-any`. The empty list is answered without one: every array
833
+ * contains it, and only an empty array is contained by it.
834
+ */
835
+ function arraySetCondition(target, op, value, isNativeArray) {
836
+ if (value === null || value === void 0) return sql`${target} IS NULL`;
837
+ const values = Array.isArray(value) ? value : [value];
838
+ if (values.length === 0) {
839
+ if (op === "array-contains-all") return sql`${target} IS NOT NULL`;
840
+ return isNativeArray ? sql`cardinality(${target}) = 0` : sql`${target} = '[]'::jsonb`;
841
+ }
842
+ const operator = op === "array-contains-all" ? sql`@>` : sql`<@`;
843
+ return isNativeArray ? sql`${target} ${operator} ARRAY[${sql.join(values.map((v) => sql`${v}`), sql`, `)}]` : sql`${target} ${operator} ${JSON.stringify(values)}::jsonb`;
844
+ }
845
+ /**
823
846
  * "The jsonb array holds at least one of `values`", as one containment test per
824
847
  * value: `(col @> '[3]' OR col @> '[7]')`.
825
848
  *
@@ -1526,6 +1549,15 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1526
1549
  predicate: contains(),
1527
1550
  negate: false
1528
1551
  };
1552
+ case "array-contains-all":
1553
+ case "array-contained-by": {
1554
+ const meta = getColumnMeta(column);
1555
+ const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1556
+ return {
1557
+ predicate: arraySetCondition(ref, op, value, isNativeArray),
1558
+ negate: false
1559
+ };
1560
+ }
1529
1561
  default: throw ApiError.badRequest(`Unknown filter operator '${op}'. Valid operators: ${ALL_WHERE_FILTER_OPS.join(", ")}.`, "UNKNOWN_FILTER_OPERATOR", {
1530
1562
  operator: op,
1531
1563
  validOperators: ALL_WHERE_FILTER_OPS
@@ -1668,6 +1700,11 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1668
1700
  if (isNativeArray) return sql`${column} @> ARRAY[${value}]`;
1669
1701
  return sql`${column} @> ${JSON.stringify([value])}`;
1670
1702
  }
1703
+ case "array-contains-all":
1704
+ case "array-contained-by": {
1705
+ const meta = getColumnMeta(column);
1706
+ return arraySetCondition(column, op, value, meta.dataType === "array" || meta.columnType === "PgArray");
1707
+ }
1671
1708
  case "not-in": {
1672
1709
  if (value === null || value === void 0) return sql`${column} IS NOT NULL`;
1673
1710
  const values = toMembershipList(value);
@@ -2481,6 +2518,27 @@ function toRestDate(value) {
2481
2518
  const date = new Date(value);
2482
2519
  return isNaN(date.getTime()) ? value : date.toISOString();
2483
2520
  }
2521
+ var restRowPlans = /* @__PURE__ */ new WeakMap();
2522
+ function restRowPlan(collection) {
2523
+ let plan = restRowPlans.get(collection);
2524
+ if (!plan) {
2525
+ const properties = collection.properties ?? {};
2526
+ plan = {
2527
+ steps: /* @__PURE__ */ new Map(),
2528
+ restricted: Object.entries(properties).filter(([, property]) => effectiveAccess(property) !== void 0)
2529
+ };
2530
+ restRowPlans.set(collection, plan);
2531
+ }
2532
+ return plan;
2533
+ }
2534
+ function restKeyStep(collection, key) {
2535
+ const relation = findRelation(resolveCollectionRelations(collection), key);
2536
+ if (relation) return { relation };
2537
+ const property = collection.properties?.[key];
2538
+ if (property?.type === "date") return toRestDate;
2539
+ if (property?.type === "number") return (value) => coerceDeclaredNumber(value, property);
2540
+ return null;
2541
+ }
2484
2542
  /**
2485
2543
  * One scalar, as REST serves it: declared numbers as numbers, declared dates as
2486
2544
  * RFC 3339, everything else exactly as the database returned it.
@@ -2536,8 +2594,9 @@ function toRestValues(row, collection) {
2536
2594
  * though the array itself is theirs to see.
2537
2595
  */
2538
2596
  function stripUnreadable(row, collection) {
2539
- const properties = collection.properties;
2540
- if (!properties) return row;
2597
+ if (!collection.properties) return row;
2598
+ const { restricted } = restRowPlan(collection);
2599
+ if (restricted.length === 0) return row;
2541
2600
  const viewer = currentFieldViewer();
2542
2601
  const hidden = /* @__PURE__ */ new Set();
2543
2602
  const hide = (name) => {
@@ -2545,7 +2604,7 @@ function stripUnreadable(row, collection) {
2545
2604
  delete row[name];
2546
2605
  };
2547
2606
  let relations;
2548
- for (const [key, property] of Object.entries(properties)) {
2607
+ for (const [key, property] of restricted) {
2549
2608
  if (canReadField(property, viewer)) continue;
2550
2609
  hide(key);
2551
2610
  if (property.columnName) hide(property.columnName);
@@ -2656,12 +2715,21 @@ function toFlatRow(row, collection, registry) {
2656
2715
  * actually there.
2657
2716
  */
2658
2717
  function toRestRow(row, collection, registry) {
2659
- const resolvedRelations = resolveCollectionRelations(collection);
2718
+ const { steps } = restRowPlan(collection);
2660
2719
  const flat = {};
2661
- for (const [key, value] of Object.entries(row)) {
2662
- const relation = findRelation(resolvedRelations, key);
2663
- if (relation && Array.isArray(value)) flat[key] = value.map((item) => renderTarget(isJunctionRelation(relation) ? unwrapJunctionRow(item, relation) : item, relation.target(), "inline", registry));
2664
- else if (relation && typeof value === "object" && value !== null) flat[key] = renderTarget(value, relation.target(), "inline", registry);
2720
+ for (const key of Object.keys(row)) {
2721
+ const value = row[key];
2722
+ let step = steps.get(key);
2723
+ if (step === void 0) {
2724
+ step = restKeyStep(collection, key);
2725
+ steps.set(key, step);
2726
+ }
2727
+ if (step === null) flat[key] = value;
2728
+ else if (typeof step === "function") flat[key] = step(value);
2729
+ else if (Array.isArray(value)) {
2730
+ const { relation } = step;
2731
+ flat[key] = value.map((item) => renderTarget(isJunctionRelation(relation) ? unwrapJunctionRow(item, relation) : item, relation.target(), "inline", registry));
2732
+ } else if (typeof value === "object" && value !== null) flat[key] = renderTarget(value, step.relation.target(), "inline", registry);
2665
2733
  else flat[key] = toRestScalar(value, collection.properties?.[key]);
2666
2734
  }
2667
2735
  return stripUnreadable(flat, collection);
@@ -2999,6 +3067,38 @@ function rowInTrashError(path, key, softDelete) {
2999
3067
  return ApiError.conflict(`"${key}" in "${path}" is in the trash, so an upsert cannot write it. Restore the row first (an update setting '${softDelete.field}' to null), or purge it (a delete with ?hard=true) and upsert again.`, "ROW_IN_TRASH");
3000
3068
  }
3001
3069
  //#endregion
3070
+ //#region src/services/view-access.ts
3071
+ /**
3072
+ * What a collection that serves a SQL view (`PostgresCollectionConfig.view`)
3073
+ * allows: reads, and for a materialized view only by the roles it names.
3074
+ *
3075
+ * A plain view runs as the caller (`security_invoker`), so the policies of the
3076
+ * tables it reads already decide every row, and a read of one needs nothing
3077
+ * here. A materialized view stores its rows and Postgres puts no row-level
3078
+ * security on it: whoever may select from it sees all of it. So the role check
3079
+ * is the driver's, made before every read of one by a caller (see
3080
+ * `beforeQueryConditions`) — and not of the server's own work, which reads
3081
+ * with no viewer at all.
3082
+ */
3083
+ /** Whether a collection serves a view rather than a table. */
3084
+ function isViewCollection(collection) {
3085
+ return Boolean(collection && isPostgresCollectionConfig(collection) && collection.view);
3086
+ }
3087
+ /** Refuse a caller who holds none of a materialized view's roles. A no-op for anything else. */
3088
+ function assertViewReadable(collection) {
3089
+ if (!collection || !isPostgresCollectionConfig(collection) || !collection.view?.materialized) return;
3090
+ const viewer = currentFieldViewer();
3091
+ if (!viewer) return;
3092
+ const allowed = collection.view.roles ?? DEFAULT_VIEW_ROLES;
3093
+ if ((viewer.roles ?? []).some((role) => allowed.includes(role))) return;
3094
+ throw ApiError.forbidden(`"${collection.slug}" is a materialized view, which has no row-level security, so it is served whole and only to ${allowed.map((role) => `'${role}'`).join(", ")}.`, "VIEW_NOT_READABLE");
3095
+ }
3096
+ /** Refuse a write to a collection that serves a view. */
3097
+ function assertCollectionWritable(collection, path) {
3098
+ if (!isViewCollection(collection)) return;
3099
+ throw new ApiError(405, "COLLECTION_READ_ONLY", `"${collection?.slug ?? path}" serves a SQL view, which is read-only: write to the tables it reads.`, { collection: collection?.slug ?? path }, true);
3100
+ }
3101
+ //#endregion
3002
3102
  //#region src/services/read-scope.ts
3003
3103
  /**
3004
3104
  * `beforeQuery`: the one place a collection callback can change *which* rows a
@@ -3081,6 +3181,7 @@ function hasBeforeQuery(registry, collection) {
3081
3181
  * narrow, it is only ever given a way to.
3082
3182
  */
3083
3183
  async function beforeQueryConditions(env, collection, path, table, description, filterContext) {
3184
+ assertViewReadable(collection);
3084
3185
  const hooks = resolveBeforeQuery(env.registry, collection);
3085
3186
  if (hooks.length === 0) return [];
3086
3187
  if (!collection) throw new Error(`[beforeQuery] "${path}" resolves to no registered collection, so a global \`beforeQuery\` cannot be compiled against it. Register the collection, or narrow the hook to the collections it applies to.`);
@@ -4555,7 +4656,7 @@ function assertWritableThrough(hop, path) {
4555
4656
  */
4556
4657
  function numericAggregateAliases(aggregates, properties) {
4557
4658
  const isNumberField = (field) => Boolean(field) && properties[field]?.type === "number";
4558
- return new Set(aggregates.filter((a) => a.fn === "count" || a.fn === "sum" || a.fn === "avg" || (a.fn === "min" || a.fn === "max") && isNumberField(a.field)).map((a) => a.alias));
4659
+ return new Set(aggregates.filter((a) => a.fn === "count" || a.fn === "sum" || a.fn === "avg" || a.fn === "countDistinct" || a.fn === "percentile" || (a.fn === "min" || a.fn === "max" || a.fn === "mode") && isNumberField(a.field)).map((a) => a.alias));
4559
4660
  }
4560
4661
  /**
4561
4662
  * Refuse a read that names a relation property its caller may not read.
@@ -5572,6 +5673,11 @@ var FetchService = class FetchService {
5572
5673
  selection[aggregate.alias] = sql`count(*)`;
5573
5674
  continue;
5574
5675
  }
5676
+ if (aggregate.fn === "fingerprint") {
5677
+ 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)`;
5679
+ continue;
5680
+ }
5575
5681
  const column = columnFor(aggregate.field, `${aggregate.fn}()`);
5576
5682
  switch (aggregate.fn) {
5577
5683
  case "count":
@@ -5589,14 +5695,34 @@ var FetchService = class FetchService {
5589
5695
  case "max":
5590
5696
  selection[aggregate.alias] = sql`max(${column})`;
5591
5697
  break;
5698
+ case "countDistinct":
5699
+ selection[aggregate.alias] = sql`count(DISTINCT ${column})`;
5700
+ break;
5701
+ case "mode":
5702
+ selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})`;
5703
+ break;
5704
+ case "percentile":
5705
+ selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column}))::numeric`;
5706
+ break;
5707
+ case "distinct":
5708
+ selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column}) FILTER (WHERE ${column} IS NOT NULL), '[]'::jsonb)`;
5709
+ break;
5592
5710
  }
5593
5711
  }
5594
- const groupColumns = (options.groupBy ?? []).map((field) => ({
5595
- field,
5596
- column: columnFor(field, "groupBy")
5597
- }));
5712
+ const lateral = [];
5713
+ const groupColumns = (options.groupBy ?? []).map((group) => {
5714
+ if (typeof group === "string") return {
5715
+ field: group,
5716
+ column: columnFor(group, "groupBy")
5717
+ };
5718
+ const column = columnFor(group.field, `${group.transform}()`);
5719
+ return {
5720
+ field: group.key,
5721
+ column: this.groupExpression(group, column, lateral, collectionPath)
5722
+ };
5723
+ });
5598
5724
  for (const group of groupColumns) selection[group.field] = sql`${group.column}`;
5599
- let query = this.db.select(selection).from(table).$dynamic();
5725
+ let query = (lateral.length > 0 ? this.db.select(selection).from(sql`${table} ${sql.join(lateral, sql` `)}`) : this.db.select(selection).from(table)).$dynamic();
5600
5726
  const conditions = [];
5601
5727
  withSoftDelete(conditions, collection, table, options.withDeleted);
5602
5728
  if (options.searchString) {
@@ -5633,6 +5759,41 @@ var FetchService = class FetchService {
5633
5759
  });
5634
5760
  }
5635
5761
  /**
5762
+ * A transformed group (`AggregateGroup`) as SQL. `lower`/`upper` read the
5763
+ * column as text; `year`/`month`/`day` truncate a date or timestamp, in UTC
5764
+ * when it has a time zone, to `YYYY`, `YYYY-MM` or `YYYY-MM-DD`; `unnest`
5765
+ * adds a lateral join over the array's elements to `lateral` and groups by
5766
+ * the element.
5767
+ */
5768
+ groupExpression(group, column, lateral, collectionPath) {
5769
+ const sqlType = column.getSQLType?.() ?? "";
5770
+ switch (group.transform) {
5771
+ case "lower": return sql`lower(${column}::text)`;
5772
+ case "upper": return sql`upper(${column}::text)`;
5773
+ case "year":
5774
+ case "month":
5775
+ case "day": {
5776
+ if (!/^(timestamp|date)/.test(sqlType)) throw ApiError.badRequest(`\`${group.transform}(${group.field})\` groups a date, and '${group.field}' on "${collectionPath}" is ${sqlType || "not one"}.`, "INVALID_AGGREGATE_GROUP", {
5777
+ field: group.field,
5778
+ transform: group.transform
5779
+ });
5780
+ 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}'`)})`;
5782
+ }
5783
+ case "unnest": {
5784
+ const meta = getColumnMeta(column);
5785
+ const alias = sql.identifier(`unnest_${lateral.length}`);
5786
+ if (meta.dataType === "array" || meta.columnType === "PgArray") lateral.push(sql`CROSS JOIN LATERAL unnest(${column}) AS ${alias}(element)`);
5787
+ else if (sqlType === "jsonb") lateral.push(sql`CROSS JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(${column}) = 'array' THEN ${column} ELSE '[]'::jsonb END) AS ${alias}(element)`);
5788
+ else throw ApiError.badRequest(`\`unnest(${group.field})\` groups by the elements of an array, and '${group.field}' on "${collectionPath}" is ${sqlType || "not one"}.`, "INVALID_AGGREGATE_GROUP", {
5789
+ field: group.field,
5790
+ transform: group.transform
5791
+ });
5792
+ return sql`${alias}.element`;
5793
+ }
5794
+ }
5795
+ }
5796
+ /**
5636
5797
  * The `ORDER BY` of a grouped aggregate: the caller's keys, then every
5637
5798
  * group key they did not name.
5638
5799
  *
@@ -5895,6 +6056,23 @@ var FetchService = class FetchService {
5895
6056
  }
5896
6057
  };
5897
6058
  //#endregion
6059
+ //#region src/utils/result-rows.ts
6060
+ /**
6061
+ * The rows a query answered with, whatever shape the driver handed them in.
6062
+ *
6063
+ * node-postgres answers one result for one statement, and an array of results
6064
+ * — one per statement — for a string holding several (`SELECT 1; SELECT 2`).
6065
+ * Reading `.rows` off that array gave `undefined`, and the caller got no rows
6066
+ * at all for a script that ended in a SELECT. The last statement's rows are
6067
+ * the script's answer, as in psql.
6068
+ */
6069
+ function rowsOfResult(result) {
6070
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
6071
+ if (typeof last !== "object" || last === null || !("rows" in last)) return [];
6072
+ const rows = last.rows;
6073
+ return Array.isArray(rows) ? rows : [];
6074
+ }
6075
+ //#endregion
5898
6076
  //#region src/services/RelationWriteService.ts
5899
6077
  /**
5900
6078
  * The same reading, keeping the link's own values.
@@ -6753,6 +6931,12 @@ function createStampKeys(properties) {
6753
6931
  return keys;
6754
6932
  }
6755
6933
  /**
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.
6936
+ */
6937
+ var BATCH_MAX_ROWS = 1e3;
6938
+ var BATCH_MAX_PARAMS = 3e4;
6939
+ /**
6756
6940
  * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
6757
6941
  * when nothing could catch its failure and carry on, straight on `db`.
6758
6942
  *
@@ -6770,6 +6954,14 @@ function inOwnTransactionUnlessTopLevel(db, write) {
6770
6954
  if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
6771
6955
  return db.transaction((tx) => write(tx));
6772
6956
  }
6957
+ /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
6958
+ function castableType(sqlType) {
6959
+ return {
6960
+ smallserial: "smallint",
6961
+ serial: "integer",
6962
+ bigserial: "bigint"
6963
+ }[sqlType.toLowerCase()] ?? sqlType;
6964
+ }
6773
6965
  /**
6774
6966
  * Service for handling all row write operations.
6775
6967
  * Handles saving, deleting, and updating rows.
@@ -6995,17 +7187,23 @@ var PersistService = class {
6995
7187
  const scalarKeys = Object.keys(entityData);
6996
7188
  const compiledOps = fieldOpKeys.length > 0 ? compileFieldOps(table, fieldOps, { collectionPath: effectiveCollectionPath }) : void 0;
6997
7189
  const bounds = fieldOpKeys.length > 0 ? compileFieldOpBounds(table, fieldOps, collection.properties ?? {}, { collectionPath: effectiveCollectionPath }) : [];
7190
+ const condition = rowIdentityCondition(table, idInfoArray, id, effectiveCollectionPath);
6998
7191
  if (scalarKeys.length > 0 || compiledOps) {
6999
7192
  const updateQuery = tx.update(table).set({
7000
7193
  ...entityData,
7001
7194
  ...compiledOps ?? {}
7002
7195
  });
7003
- const condition = rowIdentityCondition(table, idInfoArray, id, effectiveCollectionPath);
7004
- if (((await updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds)))).rowCount ?? 0) === 0) {
7196
+ 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);
7198
+ if (returning && updated[0]) returnedRow = returning.render(updated[0]);
7199
+ if (updated.length === 0) {
7005
7200
  const broken = await brokenFieldOpBounds(tx, table, [condition], bounds);
7006
7201
  if (broken.length > 0) throw fieldOpBoundsError(collection.slug, broken);
7007
7202
  throw await this.explainZeroRowWrite(tx, table, [condition], effectiveCollectionPath, currentId, "update");
7008
7203
  }
7204
+ } else if (options?.unreadRow) {
7205
+ const [present] = await tx.select(returningKeys).from(table).where(condition).limit(1);
7206
+ if (!present) throw ApiError.notFound(`No row "${id}" in "${effectiveCollectionPath}" to update.`);
7009
7207
  }
7010
7208
  } else {
7011
7209
  const dataForInsert = { ...entityData };
@@ -7031,11 +7229,13 @@ var PersistService = class {
7031
7229
  const trashColumn = softDelete ? softDeleteColumn(collection, table) : void 0;
7032
7230
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7033
7231
  const updating = Object.keys(set).length > 0;
7232
+ const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7034
7233
  result = updating ? await insertQuery.onConflictDoUpdate({
7035
7234
  target,
7036
7235
  set,
7037
7236
  setWhere: writable
7038
- }).returning(returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returningKeys);
7237
+ }).returning(returning?.columns ?? returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7238
+ if (returning && result[0]) returnedRow = returning.render(result[0]);
7039
7239
  if (result.length === 0) {
7040
7240
  const keyConditions = target.map((column, i) => eq(column, dataForInsert[targetFields[i]]));
7041
7241
  if (scope) keyConditions.push(scope);
@@ -7074,6 +7274,238 @@ var PersistService = class {
7074
7274
  return finalEntity;
7075
7275
  }
7076
7276
  /**
7277
+ * Write a batch of new rows — inserted, or upserted with `options.upsert` —
7278
+ * as multi-row statements, and return each row as {@link save} returns it.
7279
+ *
7280
+ * The statements are the ones {@link save} sends for one row, carrying up
7281
+ * to {@link BATCH_MAX_ROWS} rows each: the same columns, defaults, conflict
7282
+ * target, conflict-update and scope. A batch of 1,000 rows is one or two
7283
+ * statements instead of a thousand.
7284
+ *
7285
+ * `undefined`, before anything is written, for a batch that needs what
7286
+ * only the row-by-row save does: a nested path, a relation or field
7287
+ * operation in a row, an upsert row without its whole conflict key, or a
7288
+ * collection whose rows cannot be returned by the write itself (a
7289
+ * `beforeQuery` or per-field read access). The caller then saves the rows
7290
+ * one by one.
7291
+ *
7292
+ * Run inside the caller's transaction, which a statement the database
7293
+ * refuses aborts: the caller undoes the batch and replays its rows one by
7294
+ * one to say which row failed.
7295
+ *
7296
+ * Rows go out in order, in consecutive runs: a run ends where the next
7297
+ * row's conflict-update would set other columns, or where an upsert names
7298
+ * a key the run already holds (one statement cannot update a row twice),
7299
+ * so a key written twice still ends with the later values.
7300
+ */
7301
+ async saveRows(collectionPath, rows, options) {
7302
+ if (isNestedPath(collectionPath)) return void 0;
7303
+ const collection = getCollectionByPath(collectionPath, this.registry);
7304
+ const returning = this.fetchService.insertReturning(collection.slug);
7305
+ if (!returning) return void 0;
7306
+ const table = getTableForCollection(collection, this.registry);
7307
+ const idInfoArray = getPrimaryKeys(collection, this.registry);
7308
+ const resolvedRelations = resolveCollectionRelations(collection);
7309
+ const manyRelationKeys = Object.keys(resolvedRelations).filter((key) => resolvedRelations[key]?.cardinality === "many");
7310
+ const upsert = options?.upsert === true;
7311
+ const targetFields = options?.onConflict && options.onConflict.length > 0 ? [...options.onConflict] : idInfoArray.map((info) => info.fieldName);
7312
+ const createStamps = createStampKeys(collection.properties);
7313
+ const prepared = [];
7314
+ for (const row of rows) {
7315
+ assertNoReadOnlyRelationValues(row.values, collection);
7316
+ const { values: plainValues, fieldOps } = splitFieldOps(row.values, collection.properties);
7317
+ if (Object.keys(fieldOps).length > 0) return void 0;
7318
+ if (manyRelationKeys.some((key) => Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
7319
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
7320
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
7321
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
7322
+ assertWritableColumns(data, table, collectionPath);
7323
+ for (const info of idInfoArray) if (data[info.fieldName] === "" || data[info.fieldName] === null || data[info.fieldName] === void 0) delete data[info.fieldName];
7324
+ let set = [];
7325
+ let key = "";
7326
+ if (upsert) {
7327
+ if (targetFields.length === 0 || targetFields.some((field) => data[field] === void 0)) return void 0;
7328
+ const excluded = /* @__PURE__ */ new Set([
7329
+ ...idInfoArray.map((info) => info.fieldName),
7330
+ ...targetFields,
7331
+ ...createStamps,
7332
+ ...row.insertOnlyKeys ?? []
7333
+ ]);
7334
+ set = Object.keys(data).filter((field) => !excluded.has(field)).sort();
7335
+ key = JSON.stringify(targetFields.map((field) => String(data[field])));
7336
+ }
7337
+ prepared.push({
7338
+ data,
7339
+ set,
7340
+ key
7341
+ });
7342
+ }
7343
+ const target = upsert ? targetFields.map((field) => {
7344
+ const column = table[field];
7345
+ if (!column) throw ApiError.badRequest(`'${field}' is not a column of "${collectionPath}", so it cannot be an upsert target.`, "INVALID_CONFLICT_TARGET");
7346
+ return column;
7347
+ }) : [];
7348
+ const scope = upsert ? await this.writeScope(collection, collectionPath, table) : void 0;
7349
+ const trashColumn = (upsert ? resolveSoftDelete(collection) : void 0) ? softDeleteColumn(collection, table) : void 0;
7350
+ const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7351
+ const runs = [];
7352
+ let start = 0;
7353
+ let params = 0;
7354
+ let keys = /* @__PURE__ */ new Set();
7355
+ for (let i = 0; i < prepared.length; i++) {
7356
+ const row = prepared[i];
7357
+ const width = Object.keys(row.data).length;
7358
+ if (i > start && (i - start >= BATCH_MAX_ROWS || params + width > BATCH_MAX_PARAMS || upsert && (keys.has(row.key) || row.set.join(",") !== prepared[start].set.join(",")))) {
7359
+ runs.push({
7360
+ start,
7361
+ end: i
7362
+ });
7363
+ start = i;
7364
+ params = 0;
7365
+ keys = /* @__PURE__ */ new Set();
7366
+ }
7367
+ params += width;
7368
+ keys.add(row.key);
7369
+ }
7370
+ if (prepared.length > 0) runs.push({
7371
+ start,
7372
+ end: prepared.length
7373
+ });
7374
+ const written = new Array(prepared.length);
7375
+ for (const run of runs) {
7376
+ const slice = prepared.slice(run.start, run.end);
7377
+ const insertQuery = this.db.insert(table).values(slice.map((row) => row.data));
7378
+ if (!upsert) {
7379
+ const result = await insertQuery.returning(returning.columns);
7380
+ if (result.length !== slice.length) throw new Error(`Inserted ${slice.length} rows into "${collectionPath}" and got ${result.length} back.`);
7381
+ result.forEach((row, i) => {
7382
+ written[run.start + i] = returning.render(row);
7383
+ });
7384
+ continue;
7385
+ }
7386
+ const setColumns = slice[0].set;
7387
+ const set = {};
7388
+ for (const field of setColumns) {
7389
+ const column = table[field];
7390
+ set[field] = sql`excluded.${sql.identifier(column.name)}`;
7391
+ }
7392
+ const result = setColumns.length > 0 ? await insertQuery.onConflictDoUpdate({
7393
+ target,
7394
+ set,
7395
+ setWhere: writable
7396
+ }).returning(returning.columns) : await insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7397
+ const byKey = /* @__PURE__ */ new Map();
7398
+ for (const row of result) byKey.set(JSON.stringify(targetFields.map((field) => String(row[field]))), row);
7399
+ slice.forEach((row, i) => {
7400
+ const stored = byKey.get(row.key);
7401
+ if (stored) written[run.start + i] = returning.render(stored);
7402
+ });
7403
+ }
7404
+ 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, {
7406
+ upsert,
7407
+ onConflict: options?.onConflict,
7408
+ insertOnlyKeys: rows[i].insertOnlyKeys
7409
+ }));
7410
+ return saved;
7411
+ }
7412
+ /**
7413
+ * Update rows by id, each with its own values, as
7414
+ * `UPDATE … FROM (VALUES …) … RETURNING` statements, and return each row as
7415
+ * {@link save} returns it — or `undefined`, before anything is written,
7416
+ * for updates that need what only the row-by-row update does: a nested
7417
+ * path, a relation or field operation in a row, a collection whose rows the
7418
+ * write cannot return (`beforeQuery`, per-field read access) or that has a
7419
+ * trash. Consecutive updates setting the same columns share a statement;
7420
+ * an id named twice starts a new one, so the later values win.
7421
+ *
7422
+ * An id the statement did not update — not there, or not the caller's to
7423
+ * update — fails the call: the caller replays the updates one by one to say
7424
+ * which, and why.
7425
+ */
7426
+ async updateRows(collectionPath, updates) {
7427
+ if (isNestedPath(collectionPath)) return void 0;
7428
+ const collection = getCollectionByPath(collectionPath, this.registry);
7429
+ if (resolveSoftDelete(collection)) return void 0;
7430
+ const returning = this.fetchService.insertReturning(collection.slug);
7431
+ if (!returning) return void 0;
7432
+ const table = getTableForCollection(collection, this.registry);
7433
+ const idInfoArray = requirePrimaryKeys(collection, this.registry);
7434
+ const resolvedRelations = resolveCollectionRelations(collection);
7435
+ const manyRelationKeys = Object.keys(resolvedRelations).filter((key) => resolvedRelations[key]?.cardinality === "many");
7436
+ const columnOf = (field) => table[field];
7437
+ const prepared = [];
7438
+ for (const { id, values } of updates) {
7439
+ assertNoReadOnlyRelationValues(values, collection);
7440
+ const { values: plainValues, fieldOps } = splitFieldOps(values, collection.properties);
7441
+ if (Object.keys(fieldOps).length > 0) return void 0;
7442
+ if (manyRelationKeys.some((key) => Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
7443
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
7444
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
7445
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
7446
+ assertWritableColumns(data, table, collectionPath);
7447
+ for (const info of idInfoArray) delete data[info.fieldName];
7448
+ if (Object.keys(data).length === 0) return void 0;
7449
+ if (!idCanAddressTable(id, table, idInfoArray)) return void 0;
7450
+ const key = parseIdValues$1(String(id), idInfoArray);
7451
+ prepared.push({
7452
+ key,
7453
+ data,
7454
+ columns: Object.keys(data).sort().join(","),
7455
+ id: JSON.stringify(idInfoArray.map((info) => String(key[info.fieldName])))
7456
+ });
7457
+ }
7458
+ const runs = [];
7459
+ let start = 0;
7460
+ let ids = /* @__PURE__ */ new Set();
7461
+ for (let i = 0; i < prepared.length; i++) {
7462
+ const row = prepared[i];
7463
+ const width = idInfoArray.length + Object.keys(row.data).length;
7464
+ if (i > start && (i - start >= BATCH_MAX_ROWS || (i - start) * width > BATCH_MAX_PARAMS || ids.has(row.id) || row.columns !== prepared[start].columns)) {
7465
+ runs.push({
7466
+ start,
7467
+ end: i
7468
+ });
7469
+ start = i;
7470
+ ids = /* @__PURE__ */ new Set();
7471
+ }
7472
+ ids.add(row.id);
7473
+ }
7474
+ if (prepared.length > 0) runs.push({
7475
+ start,
7476
+ end: prepared.length
7477
+ });
7478
+ const written = new Array(prepared.length);
7479
+ for (const run of runs) {
7480
+ const slice = prepared.slice(run.start, run.end);
7481
+ const keyFields = idInfoArray.map((info) => info.fieldName);
7482
+ const setFields = slice[0].columns.split(",");
7483
+ const valueOf = (field, value) => {
7484
+ const column = columnOf(field);
7485
+ return sql`${sql.param(value ?? null, column)}::${sql.raw(castableType(column.getSQLType()))}`;
7486
+ };
7487
+ const rows = slice.map((row) => sql`(${sql.join([...keyFields.map((field) => valueOf(field, row.key[field])), ...setFields.map((field) => valueOf(field, row.data[field]))], sql`, `)})`);
7488
+ const names = [...keyFields.map((_, i) => `k${i}`), ...setFields.map((_, i) => `c${i}`)];
7489
+ const returnedColumns = Object.entries(returning.columns);
7490
+ const result = await this.db.execute(sql`UPDATE ${table} SET ${sql.join(setFields.map((field, i) => sql`${sql.identifier(columnOf(field).name)} = ${sql.identifier("v")}.${sql.identifier(`c${i}`)}`), sql`, `)} FROM (VALUES ${sql.join(rows, sql`, `)}) AS ${sql.identifier("v")}(${sql.raw(names.map((name) => `"${name}"`).join(", "))}) WHERE ${sql.join(keyFields.map((field, i) => sql`${columnOf(field)} = ${sql.identifier("v")}.${sql.identifier(`k${i}`)}`), sql` AND `)} RETURNING ${sql.join(returnedColumns.map(([, column]) => sql`${column}`), sql`, `)}`);
7491
+ const byId = /* @__PURE__ */ new Map();
7492
+ for (const raw of rowsOfResult(result)) {
7493
+ const row = {};
7494
+ for (const [field, column] of returnedColumns) {
7495
+ const value = raw[column.name];
7496
+ row[field] = value === null || value === void 0 ? null : column.mapFromDriverValue(value);
7497
+ }
7498
+ byId.set(JSON.stringify(keyFields.map((field) => String(row[field]))), row);
7499
+ }
7500
+ slice.forEach((row, i) => {
7501
+ const stored = byId.get(row.id);
7502
+ if (!stored) throw new Error(`Update ${run.start + i} of ${prepared.length} matched no row in "${collectionPath}".`);
7503
+ written[run.start + i] = returning.render(stored);
7504
+ });
7505
+ }
7506
+ return written;
7507
+ }
7508
+ /**
7077
7509
  * The caller's `beforeQuery` scope over this table, as one condition: what
7078
7510
  * a stored row must satisfy for a write that meets it to change it. The
7079
7511
  * same scope the update gate and the single get apply; `undefined` when the
@@ -7143,23 +7575,6 @@ var PersistService = class {
7143
7575
  }
7144
7576
  };
7145
7577
  //#endregion
7146
- //#region src/utils/result-rows.ts
7147
- /**
7148
- * The rows a query answered with, whatever shape the driver handed them in.
7149
- *
7150
- * node-postgres answers one result for one statement, and an array of results
7151
- * — one per statement — for a string holding several (`SELECT 1; SELECT 2`).
7152
- * Reading `.rows` off that array gave `undefined`, and the caller got no rows
7153
- * at all for a script that ended in a SELECT. The last statement's rows are
7154
- * the script's answer, as in psql.
7155
- */
7156
- function rowsOfResult(result) {
7157
- const last = Array.isArray(result) ? result[result.length - 1] : result;
7158
- if (typeof last !== "object" || last === null || !("rows" in last)) return [];
7159
- const rows = last.rows;
7160
- return Array.isArray(rows) ? rows : [];
7161
- }
7162
- //#endregion
7163
7578
  //#region src/services/dataService.ts
7164
7579
  /**
7165
7580
  * DataService - Facade for row operations.
@@ -7271,6 +7686,10 @@ var DataService = class {
7271
7686
  * Execute raw SQL
7272
7687
  */
7273
7688
  async executeSql(sqlText, params) {
7689
+ return rowsOfResult(await this.executeSqlResult(sqlText, params));
7690
+ }
7691
+ /** {@link executeSql}, answering with the driver's whole result: its rows and its column descriptions. */
7692
+ async executeSqlResult(sqlText, params) {
7274
7693
  if (rawQueryLoggingEnabled()) logger.debug(`Executing raw SQL: ${sqlText}${params?.length ? ` with ${params.length} params` : ""}`);
7275
7694
  const { sql } = await import("drizzle-orm");
7276
7695
  let result;
@@ -7286,9 +7705,8 @@ var DataService = class {
7286
7705
  const query = sql.join(chunks, sql.raw(""));
7287
7706
  result = await this.db.execute(query);
7288
7707
  } else result = await this.db.execute(sql.raw(sqlText));
7289
- const rows = rowsOfResult(result);
7290
- if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rows.length} rows.`);
7291
- return rows;
7708
+ if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rowsOfResult(result).length} rows.`);
7709
+ return result;
7292
7710
  }
7293
7711
  /**
7294
7712
  * Get the underlying FetchService for advanced use
@@ -7310,6 +7728,261 @@ var DataService = class {
7310
7728
  }
7311
7729
  };
7312
7730
  //#endregion
7731
+ //#region src/security/caller-sql.ts
7732
+ /**
7733
+ * What SQL may run as a caller (`DataDriver.sql` on the authenticated driver).
7734
+ *
7735
+ * That SQL runs in the caller's transaction, as `rebase_user`, with the
7736
+ * caller's identity in transaction-local settings — the same footing as every
7737
+ * SDK read and write, so the tables' policies decide each row. Those settings
7738
+ * are the weak point: a statement running as `rebase_user` can change them.
7739
+ * `RESET ROLE` returns to the connection's owner role, and
7740
+ * `set_config('app.uid', …)` makes the policies see somebody else. Postgres
7741
+ * offers no way to stop a role from doing either.
7742
+ *
7743
+ * So the query text has to be the application's own, and anything a user
7744
+ * typed travels in `params`, which can never become SQL. This check is the
7745
+ * backstop for when that slips — a value interpolated into the text, a query
7746
+ * assembled from pieces: it refuses every statement that can touch session
7747
+ * state, and more than one statement at a time.
7748
+ *
7749
+ * - one statement;
7750
+ * - leading with `SELECT`, `WITH`, `VALUES`, `TABLE`, `INSERT`, `UPDATE`,
7751
+ * `DELETE` or `MERGE` — no `SET`, `RESET`, `DO`, `PREPARE`, DDL or
7752
+ * transaction control;
7753
+ * - never calling `set_config` or naming `pg_settings`, the two ways a query
7754
+ * can write a setting;
7755
+ * - never calling a function of the `rebase` schema but the identity readers
7756
+ * (`uid`, `roles`, `jwt`, `is_anonymous`) — the rest are the server's doors.
7757
+ *
7758
+ * Read after masking string literals, dollar-quoted bodies and comments, so a
7759
+ * value that merely contains `;` or `set_config` is not refused, and
7760
+ * a call hidden in a comment-split name is not missed.
7761
+ */
7762
+ var ALLOWED_LEADS = /* @__PURE__ */ new Set([
7763
+ "select",
7764
+ "with",
7765
+ "values",
7766
+ "table",
7767
+ "insert",
7768
+ "update",
7769
+ "delete",
7770
+ "merge"
7771
+ ]);
7772
+ /** `set_config(` in any spelling Postgres accepts: schema-qualified, quoted, spaced. */
7773
+ var SETS_A_SETTING = /(?:^|[^\w$])"?set_config"?\s*\(/i;
7774
+ /** `pg_settings`, which an `UPDATE` writes through to `set_config`. */
7775
+ var NAMES_PG_SETTINGS = /(?:^|[^\w$])"?pg_settings"?(?:[^\w$]|$)/i;
7776
+ /**
7777
+ * The functions in the `rebase` schema a caller may name: the ones policies
7778
+ * read the identity through. Everything else there is the server's —
7779
+ * `record_history` and `enqueue_job` are `SECURITY DEFINER` doors the request
7780
+ * role can execute, because a write's history and jobs commit in the write's
7781
+ * own transaction, and a statement calling one forges an entry or starts a job.
7782
+ */
7783
+ var CALLER_REBASE_FUNCTIONS = /* @__PURE__ */ new Set([
7784
+ "uid",
7785
+ "roles",
7786
+ "jwt",
7787
+ "is_anonymous"
7788
+ ]);
7789
+ var REBASE_FUNCTION_CALL = /(?:^|[^\w$])"?rebase"?\s*\.\s*"?([A-Za-z_][\w$]*)"?\s*\(/gi;
7790
+ /** The doors by their bare names, for a `search_path` that reaches `rebase`. */
7791
+ var NAMES_A_SERVER_DOOR = /(?:^|[^\w$.])"?(record_history|enqueue_job)"?\s*\(/i;
7792
+ /**
7793
+ * The query with every string literal, dollar-quoted body and comment
7794
+ * replaced by a space. Quoted identifiers are kept, quotes and all, so a name
7795
+ * written `"set_config"` still reads as one.
7796
+ */
7797
+ function maskSqlLiterals(text) {
7798
+ let out = "";
7799
+ let i = 0;
7800
+ while (i < text.length) {
7801
+ const ch = text[i];
7802
+ const next = text[i + 1];
7803
+ if (ch === "-" && next === "-") {
7804
+ const end = text.indexOf("\n", i);
7805
+ i = end === -1 ? text.length : end;
7806
+ out += " ";
7807
+ } else if (ch === "/" && next === "*") {
7808
+ let depth = 1;
7809
+ i += 2;
7810
+ while (i < text.length && depth > 0) if (text[i] === "/" && text[i + 1] === "*") {
7811
+ depth++;
7812
+ i += 2;
7813
+ } else if (text[i] === "*" && text[i + 1] === "/") {
7814
+ depth--;
7815
+ i += 2;
7816
+ } else i++;
7817
+ out += " ";
7818
+ } else if (ch === "'") {
7819
+ const escapes = i > 0 && /[eE]/.test(text[i - 1]) && (i < 2 || !/[\w$]/.test(text[i - 2]));
7820
+ i++;
7821
+ while (i < text.length) {
7822
+ if (escapes && text[i] === "\\") {
7823
+ i += 2;
7824
+ continue;
7825
+ }
7826
+ if (text[i] === "'") {
7827
+ if (text[i + 1] === "'") {
7828
+ i += 2;
7829
+ continue;
7830
+ }
7831
+ break;
7832
+ }
7833
+ i++;
7834
+ }
7835
+ i++;
7836
+ out += " ";
7837
+ } else if (ch === "\"") {
7838
+ const end = text.indexOf("\"", i + 1);
7839
+ const stop = end === -1 ? text.length : end + 1;
7840
+ out += text.slice(i, stop);
7841
+ i = stop;
7842
+ } else if (ch === "$" && (i === 0 || !/[\w$]/.test(text[i - 1]))) {
7843
+ const tag = /^\$(?:[A-Za-z_][\w]*)?\$/.exec(text.slice(i));
7844
+ if (!tag) {
7845
+ out += ch;
7846
+ i++;
7847
+ continue;
7848
+ }
7849
+ const end = text.indexOf(tag[0], i + tag[0].length);
7850
+ i = end === -1 ? text.length : end + tag[0].length;
7851
+ out += " ";
7852
+ } else {
7853
+ out += ch;
7854
+ i++;
7855
+ }
7856
+ }
7857
+ return out;
7858
+ }
7859
+ function refuse(reason) {
7860
+ 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);
7861
+ }
7862
+ /** Throw `SQL_NOT_ALLOWED` unless `text` may run as the caller (see the module docs). */
7863
+ function assertCallerSql(text) {
7864
+ const code = maskSqlLiterals(text);
7865
+ const statements = code.split(";").filter((part) => part.trim().length > 0);
7866
+ if (statements.length === 0) refuse("The query is empty.");
7867
+ if (statements.length > 1) refuse("The query holds more than one statement.");
7868
+ const lead = /^[\s(]*([A-Za-z]+)/.exec(statements[0])?.[1]?.toLowerCase();
7869
+ if (!lead || !ALLOWED_LEADS.has(lead)) refuse(`\`${lead?.toUpperCase() ?? "?"}\` cannot run as the caller.`);
7870
+ if (/u&"/i.test(code)) refuse("The query spells an identifier with Unicode escapes (U&\"…\").");
7871
+ if (SETS_A_SETTING.test(code)) refuse("The query calls set_config.");
7872
+ if (NAMES_PG_SETTINGS.test(code)) refuse("The query names pg_settings.");
7873
+ 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.`);
7874
+ const door = NAMES_A_SERVER_DOOR.exec(code);
7875
+ if (door) refuse(`The query calls ${door[1]}, which is the server's.`);
7876
+ }
7877
+ //#endregion
7878
+ //#region src/security/caller-sql-columns.ts
7879
+ /**
7880
+ * The columns a caller may not read, taken out of what their SQL returned.
7881
+ *
7882
+ * Per-field read rules (`access.read`, and `excludeFromApi`, which is
7883
+ * `read: []`) are not something Postgres can hold for one request role shared
7884
+ * by every user, so the SDK applies them to each row it serves
7885
+ * (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
7886
+ * the SDK never walked — and `SELECT *` from a users table would hand over the
7887
+ * password hash.
7888
+ *
7889
+ * Postgres says where each result column came from: the row description
7890
+ * carries the table's oid and the column's number for every column that is a
7891
+ * plain reference to one, aliased or not, `RETURNING` included. A column whose
7892
+ * origin is a collection property this caller cannot read is dropped from
7893
+ * every row, the way the API drops it.
7894
+ *
7895
+ * What it cannot see is a value computed from such a column — `md5(hash)`,
7896
+ * `hash || ''` — whose origin Postgres reports as none. That is the query
7897
+ * text's business, and the query text is the application's (see
7898
+ * `caller-sql.ts`).
7899
+ *
7900
+ * A driver that reports no origins at all (PGlite) has its result columns
7901
+ * matched by name instead, against every restricted column of every
7902
+ * collection: it may drop a column of the same name from another table, never
7903
+ * keep one it should drop.
7904
+ */
7905
+ /** The columns of a result, from a pg `QueryResult` (or the last of several). */
7906
+ function fieldsOfResult(result) {
7907
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
7908
+ if (typeof last !== "object" || last === null || !("fields" in last)) return [];
7909
+ const fields = last.fields;
7910
+ if (!Array.isArray(fields)) return [];
7911
+ return fields.flatMap((field) => {
7912
+ if (typeof field !== "object" || field === null || !("name" in field)) return [];
7913
+ const { name, tableID, columnID } = field;
7914
+ return [{
7915
+ name: String(name),
7916
+ ...typeof tableID === "number" ? { tableID } : {},
7917
+ ...typeof columnID === "number" ? { columnID } : {}
7918
+ }];
7919
+ });
7920
+ }
7921
+ /**
7922
+ * The relations result columns came from, by oid, read from the catalogue the
7923
+ * first time an oid is seen. An oid never changes meaning: a table that is
7924
+ * dropped and created again gets a new one, which is read when it appears.
7925
+ */
7926
+ var ColumnOrigins = class {
7927
+ relations = /* @__PURE__ */ new Map();
7928
+ async describe(oids, run) {
7929
+ const unseen = [...new Set(oids)].filter((oid) => !this.relations.has(oid));
7930
+ if (unseen.length > 0) {
7931
+ 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
7932
+ FROM pg_class c
7933
+ JOIN pg_namespace n ON n.oid = c.relnamespace
7934
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
7935
+ WHERE c.oid = ANY($1::oid[])`, [unseen]);
7936
+ for (const oid of unseen) this.relations.set(oid, null);
7937
+ for (const row of rows) {
7938
+ const oid = Number(row.oid);
7939
+ let relation = this.relations.get(oid);
7940
+ if (!relation) {
7941
+ relation = {
7942
+ schema: String(row.schema),
7943
+ name: String(row.name),
7944
+ columns: /* @__PURE__ */ new Map()
7945
+ };
7946
+ this.relations.set(oid, relation);
7947
+ }
7948
+ relation.columns.set(Number(row.attnum), String(row.column));
7949
+ }
7950
+ }
7951
+ return new Map(oids.map((oid) => [oid, this.relations.get(oid) ?? null]));
7952
+ }
7953
+ };
7954
+ var schemaOf = (collection) => isPostgresCollectionConfig(collection) && collection.schema || "public";
7955
+ /**
7956
+ * `rows` without the columns `viewer` may not read, by the origins `fields`
7957
+ * describe. The rows are changed in place and returned.
7958
+ */
7959
+ async function withoutUnreadableColumns(rows, fields, viewer, collections, origins, run) {
7960
+ const restricted = collections.filter(hasFieldAccessRules);
7961
+ if (restricted.length === 0 || rows.length === 0 || fields.length === 0) return rows;
7962
+ const refusedBy = /* @__PURE__ */ new Map();
7963
+ for (const collection of restricted) {
7964
+ const { refused } = restrictedFieldNames(collection, viewer, "read");
7965
+ if (refused.size > 0) refusedBy.set(`${schemaOf(collection)}.${getTableName$1(collection)}`, refused);
7966
+ }
7967
+ if (refusedBy.size === 0) return rows;
7968
+ const drop = /* @__PURE__ */ new Set();
7969
+ if (fields.every((field) => field.tableID === void 0)) {
7970
+ const everyRefused = new Set([...refusedBy.values()].flatMap((names) => [...names]));
7971
+ for (const field of fields) if (everyRefused.has(field.name)) drop.add(field.name);
7972
+ } else {
7973
+ const fromTables = fields.filter((field) => field.tableID && field.columnID);
7974
+ const relations = await origins.describe(fromTables.map((field) => field.tableID), run);
7975
+ for (const field of fromTables) {
7976
+ const relation = relations.get(field.tableID);
7977
+ const column = relation?.columns.get(field.columnID);
7978
+ if (relation && column && refusedBy.get(`${relation.schema}.${relation.name}`)?.has(column)) drop.add(field.name);
7979
+ }
7980
+ }
7981
+ if (drop.size === 0) return rows;
7982
+ for (const row of rows) for (const name of drop) delete row[name];
7983
+ return rows;
7984
+ }
7985
+ //#endregion
7313
7986
  //#region src/schema/classify-change.ts
7314
7987
  /**
7315
7988
  * What a collection change means for a live database.
@@ -7993,6 +8666,18 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
7993
8666
  }
7994
8667
  for (const trigger of before.triggers) {
7995
8668
  if (after.triggers.some((t) => t.name === trigger.name)) continue;
8669
+ if (trigger.kind === "keep-tenant") {
8670
+ push({
8671
+ kind: "change-constraint",
8672
+ verdict: "needs-migration",
8673
+ property: before.columns.find((c) => c.column === trigger.column)?.source.propName,
8674
+ detail: `The collection no longer declares a tenant, but trigger "${trigger.name}" stays and keeps refusing moves.`,
8675
+ remedy: `Drop it in a migration: DROP TRIGGER "${trigger.name}" ON "${after.schema}"."${after.table}".`,
8676
+ sourceOnly: `Trigger "${trigger.name}" stays and keeps "${trigger.column}" from changing.`,
8677
+ kept: `trigger ${trigger.name} kept`
8678
+ });
8679
+ continue;
8680
+ }
7996
8681
  push({
7997
8682
  kind: "change-constraint",
7998
8683
  verdict: "needs-migration",
@@ -8009,7 +8694,7 @@ function classifyTable$1(wasCollection, collection, before, after, changes, fact
8009
8694
  kind: "change-constraint",
8010
8695
  verdict: "safe",
8011
8696
  property: after.columns.find((c) => c.column === trigger.column)?.source.propName,
8012
- detail: `"${trigger.column}" is stamped with now() on every update — creates trigger "${trigger.name}".`
8697
+ 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}".`
8013
8698
  });
8014
8699
  }
8015
8700
  }
@@ -9400,6 +10085,368 @@ var PgNotifyListener = class {
9400
10085
  }
9401
10086
  };
9402
10087
  //#endregion
10088
+ //#region src/pipelined-transaction.ts
10089
+ /**
10090
+ * A request's transaction, opened in the same round trip as its first query.
10091
+ *
10092
+ * Every request runs in a transaction that starts with two statements of its
10093
+ * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
10094
+ * and drops to the restricted role (`authContextStatement`). Sent one after
10095
+ * the other, each waits for the last, and a lone read paid four round trips —
10096
+ * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
10097
+ * one. Against a database a few milliseconds away that is most of the request.
10098
+ *
10099
+ * Postgres accepts several statements in one batch: the extended protocol's
10100
+ * Parse/Bind/Execute for each, then one Sync. The server runs them in order
10101
+ * and answers them together, so this sends nothing when the transaction is
10102
+ * opened and puts its opening statements in front of the first query instead.
10103
+ * Should one of them fail, the server skips the rest up to the Sync: a refused
10104
+ * role switch fails the batch before the query runs, with the same error a
10105
+ * statement of its own would have raised.
10106
+ *
10107
+ * A read-only transaction at READ COMMITTED goes one step further. Each of its
10108
+ * statements reads its own snapshot, so running each statement in a batch of
10109
+ * its own with the context in front — a transaction that ends at the Sync —
10110
+ * is the same transaction as far as anything inside it can tell, minus the
10111
+ * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
10112
+ * statement that only means something inside a transaction block (a
10113
+ * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
10114
+ * one, from that statement on.
10115
+ *
10116
+ * Statement values are serialized by pg's own `prepareValue`, so a value means
10117
+ * the same here as in any other query; rows are parsed with the query's own
10118
+ * type parsers, as pg's `Query` parses them.
10119
+ */
10120
+ var COMMAND_TAG = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
10121
+ /**
10122
+ * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
10123
+ * Sync, one round trip. The last statement's result is the batch's; the
10124
+ * others are run for their effect and their rows are dropped unparsed.
10125
+ *
10126
+ * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
10127
+ * nothing for it but what `submit` writes, and hands it each message the
10128
+ * server sends back until ReadyForQuery.
10129
+ */
10130
+ var PipelinedQuery = class {
10131
+ /** How many statements this batch sends. */
10132
+ statementCount;
10133
+ /** Set by `client.query`, which wraps it for its read timeout. */
10134
+ callback;
10135
+ /** The statements, in the order they are sent, with their serialized values. */
10136
+ statements;
10137
+ rowMode;
10138
+ types;
10139
+ /** Statements ahead of the last whose completion has not arrived yet. */
10140
+ ahead;
10141
+ fields = [];
10142
+ parsers = [];
10143
+ rows = [];
10144
+ command = "";
10145
+ rowCount = null;
10146
+ oid = 0;
10147
+ rowError;
10148
+ settled = false;
10149
+ constructor(lead, last, callback) {
10150
+ this.statements = [...lead, last].map((statement) => ({
10151
+ text: statement.text,
10152
+ values: (statement.values ?? []).map((value) => prepareValue(value))
10153
+ }));
10154
+ this.statementCount = this.statements.length;
10155
+ this.ahead = lead.length;
10156
+ this.rowMode = last.rowMode;
10157
+ this.types = last.types ?? pg.types;
10158
+ this.callback = callback;
10159
+ }
10160
+ submit(connection) {
10161
+ connection.stream.cork();
10162
+ try {
10163
+ for (const statement of this.statements) {
10164
+ connection.parse({
10165
+ text: statement.text,
10166
+ name: "",
10167
+ types: []
10168
+ }, true);
10169
+ connection.bind({
10170
+ portal: "",
10171
+ statement: "",
10172
+ values: statement.values
10173
+ }, true);
10174
+ connection.describe({
10175
+ type: "P",
10176
+ name: ""
10177
+ }, true);
10178
+ connection.execute({ portal: "" }, true);
10179
+ }
10180
+ connection.sync();
10181
+ } finally {
10182
+ connection.stream.uncork();
10183
+ }
10184
+ }
10185
+ handleRowDescription(message) {
10186
+ if (this.ahead > 0) return;
10187
+ this.fields = message.fields;
10188
+ this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, "text"));
10189
+ }
10190
+ handleDataRow(message) {
10191
+ if (this.ahead > 0 || this.rowError) return;
10192
+ const values = message.fields;
10193
+ try {
10194
+ if (this.rowMode === "array") {
10195
+ const row = new Array(values.length);
10196
+ for (let i = 0; i < values.length; i++) {
10197
+ const raw = values[i];
10198
+ row[i] = raw === null ? null : this.parsers[i](raw);
10199
+ }
10200
+ this.rows.push(row);
10201
+ } else {
10202
+ const row = {};
10203
+ for (let i = 0; i < values.length; i++) {
10204
+ const raw = values[i];
10205
+ row[this.fields[i].name] = raw === null ? null : this.parsers[i](raw);
10206
+ }
10207
+ this.rows.push(row);
10208
+ }
10209
+ } catch (error) {
10210
+ this.rowError = error instanceof Error ? error : new Error(String(error));
10211
+ }
10212
+ }
10213
+ handleCommandComplete(message) {
10214
+ if (this.ahead > 0) {
10215
+ this.ahead -= 1;
10216
+ return;
10217
+ }
10218
+ const match = COMMAND_TAG.exec(message.text);
10219
+ if (!match) return;
10220
+ this.command = match[1];
10221
+ if (match[3]) {
10222
+ this.oid = Number.parseInt(match[2], 10);
10223
+ this.rowCount = Number.parseInt(match[3], 10);
10224
+ } else if (match[2]) this.rowCount = Number.parseInt(match[2], 10);
10225
+ }
10226
+ /** An empty statement completes with EmptyQueryResponse rather than CommandComplete. */
10227
+ handleEmptyQuery() {
10228
+ if (this.ahead > 0) this.ahead -= 1;
10229
+ }
10230
+ handlePortalSuspended() {}
10231
+ handleError(error) {
10232
+ if (this.settled) return;
10233
+ this.settled = true;
10234
+ this.callback?.(error);
10235
+ }
10236
+ handleReadyForQuery() {
10237
+ if (this.settled) return;
10238
+ this.settled = true;
10239
+ if (this.rowError) {
10240
+ this.callback?.(this.rowError);
10241
+ return;
10242
+ }
10243
+ const result = {
10244
+ command: this.command,
10245
+ rowCount: this.rowCount,
10246
+ oid: this.oid,
10247
+ fields: this.fields,
10248
+ rows: this.rows
10249
+ };
10250
+ this.callback?.(null, result);
10251
+ }
10252
+ };
10253
+ /** Send `lead` and then `last` in one round trip; the result is `last`'s. */
10254
+ function runPipelined(client, lead, last) {
10255
+ return new Promise((resolve, reject) => {
10256
+ client.query(new PipelinedQuery(lead, last, (error, result) => {
10257
+ if (error) reject(error);
10258
+ else if (result) resolve(result);
10259
+ }));
10260
+ });
10261
+ }
10262
+ /**
10263
+ * A statement that means something only inside a transaction block, so a
10264
+ * read cannot run it in a batch of its own: savepoints, transaction-local
10265
+ * settings, cursors and transaction-scoped locks.
10266
+ */
10267
+ 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;
10268
+ /**
10269
+ * A statement pg runs with a protocol of its own: COPY streams, a named
10270
+ * statement pg keeps track of, a portal read page by page. Sent as pg sends
10271
+ * it, after the transaction's opening has gone ahead in a batch of its own.
10272
+ */
10273
+ function cannotPipeline(config) {
10274
+ return Boolean(config.name) || Boolean(config.rows) || /^\s*copy\b/i.test(config.text);
10275
+ }
10276
+ function toQueryConfig(statement) {
10277
+ return {
10278
+ text: statement.text,
10279
+ values: statement.values ? [...statement.values] : void 0
10280
+ };
10281
+ }
10282
+ function beginStatement(config) {
10283
+ const parts = ["begin"];
10284
+ if (config?.isolationLevel) parts.push(`isolation level ${config.isolationLevel}`);
10285
+ if (config?.accessMode) parts.push(config.accessMode);
10286
+ if (typeof config?.deferrable === "boolean") parts.push(config.deferrable ? "deferrable" : "not deferrable");
10287
+ return parts.join(" ");
10288
+ }
10289
+ /**
10290
+ * Whether a transaction with these settings can run each statement in a batch
10291
+ * of its own. Read-only, at READ COMMITTED: every statement takes its own
10292
+ * snapshot there anyway, and none of them can write.
10293
+ */
10294
+ function runsStatementByStatement(config) {
10295
+ return config?.accessMode === "read only" && (config.isolationLevel === void 0 || config.isolationLevel === "read committed") && config.deferrable !== true;
10296
+ }
10297
+ /**
10298
+ * A savepoint being set or released: a statement with no result to wait for,
10299
+ * which can go out with whatever is sent next.
10300
+ */
10301
+ var DEFERRABLE = /^\s*(?:savepoint|release(?:\s+savepoint)?)\s+[A-Za-z_][A-Za-z0-9_]*\s*;?\s*$/i;
10302
+ var ROLLBACK_TO = /^\s*rollback\s+to\s+(?:savepoint\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*;?\s*$/i;
10303
+ function settledWithoutSending(text) {
10304
+ const command = text.trim().split(/\s+/)[0].toUpperCase();
10305
+ return Promise.resolve({
10306
+ command,
10307
+ rowCount: null,
10308
+ oid: 0,
10309
+ fields: [],
10310
+ rows: []
10311
+ });
10312
+ }
10313
+ /**
10314
+ * The client side of one transaction: sends its opening with the first query,
10315
+ * holds savepoints back until a statement goes out after them, and sends
10316
+ * `COMMIT` or `ROLLBACK` only when something was sent.
10317
+ */
10318
+ var TransactionOpening = class {
10319
+ client;
10320
+ begin;
10321
+ opening;
10322
+ statementByStatement;
10323
+ /** `fresh`: nothing sent. `implicit`: each statement ran in a batch of its own. `open`: in a transaction block. */
10324
+ state = "fresh";
10325
+ /** In a block: statements accepted and not yet sent, which go out ahead of the next one. */
10326
+ pending = [];
10327
+ /** In a block: whether its `BEGIN` has reached the server. */
10328
+ begun = false;
10329
+ constructor(client, begin, opening, statementByStatement) {
10330
+ this.client = client;
10331
+ this.begin = begin;
10332
+ this.opening = opening;
10333
+ this.statementByStatement = statementByStatement;
10334
+ }
10335
+ /** The `query` the transaction's drizzle session calls. Decides synchronously, so concurrent calls queue in order. */
10336
+ query(config, values) {
10337
+ const statement = typeof config === "string" ? {
10338
+ text: config,
10339
+ values
10340
+ } : values !== void 0 ? {
10341
+ ...config,
10342
+ values
10343
+ } : config;
10344
+ const pipelinable = !cannotPipeline(statement);
10345
+ if (this.state !== "open") {
10346
+ if (this.statementByStatement && pipelinable && !NEEDS_TRANSACTION_BLOCK.test(statement.text)) {
10347
+ this.state = "implicit";
10348
+ return runPipelined(this.client, [READ_ONLY_STATEMENT, ...this.opening], statement);
10349
+ }
10350
+ this.state = "open";
10351
+ this.pending = [{ text: this.begin }, ...this.opening];
10352
+ }
10353
+ const rollbackTo = ROLLBACK_TO.exec(statement.text);
10354
+ if (rollbackTo) {
10355
+ const at = this.pending.findLastIndex((pending) => pending.text.trim().toLowerCase() === `savepoint ${rollbackTo[1].toLowerCase()}`);
10356
+ if (at >= 0) {
10357
+ this.pending = this.pending.slice(0, at);
10358
+ return settledWithoutSending(statement.text);
10359
+ }
10360
+ }
10361
+ if (DEFERRABLE.test(statement.text) && !statement.values?.length) {
10362
+ this.pending.push({ text: statement.text });
10363
+ return settledWithoutSending(statement.text);
10364
+ }
10365
+ return this.send(statement, pipelinable);
10366
+ }
10367
+ /** `statement`, with everything pending in front of it. */
10368
+ send(statement, pipelinable = true) {
10369
+ const lead = this.pending;
10370
+ this.pending = [];
10371
+ if (lead.length > 0) this.begun = true;
10372
+ if (lead.length === 0) return this.client.query(statement);
10373
+ if (pipelinable) return runPipelined(this.client, lead, statement);
10374
+ return runPipelined(this.client, lead.slice(0, -1), toQueryConfig(lead[lead.length - 1])).then(() => this.client.query(statement));
10375
+ }
10376
+ async commit() {
10377
+ if (this.state === "open" && this.begun) await this.send({ text: "commit" });
10378
+ this.pending = [];
10379
+ }
10380
+ async rollback() {
10381
+ this.pending = [];
10382
+ if (this.state === "open" && this.begun) await this.client.query("rollback");
10383
+ }
10384
+ };
10385
+ /**
10386
+ * What `SET TRANSACTION READ ONLY` sets, as a statement that can run in a batch
10387
+ * outside a transaction block — where `SET TRANSACTION` warns and does nothing.
10388
+ */
10389
+ var READ_ONLY_STATEMENT = { text: "SELECT set_config('transaction_read_only', 'on', true)" };
10390
+ /** The relational schema a drizzle handle was built with, for a session over another client. */
10391
+ function schemaConfigOf(db) {
10392
+ const { schema, fullSchema, tableNamesMap } = db._;
10393
+ return schema && fullSchema ? {
10394
+ schema,
10395
+ fullSchema,
10396
+ tableNamesMap
10397
+ } : void 0;
10398
+ }
10399
+ var dialect = new PgDialect();
10400
+ /**
10401
+ * The drizzle handle and pg pool to run a pipelined transaction on, or
10402
+ * `undefined` for a handle that is not a drizzle database over a pg pool of
10403
+ * this process's pg (PGlite, a transaction, a caller's own copy of either
10404
+ * library), which opens its transactions statement by statement.
10405
+ */
10406
+ function pipelineTarget(db) {
10407
+ if (!(db instanceof NodePgDatabase) || !("$client" in db)) return void 0;
10408
+ const client = db.$client;
10409
+ return client instanceof pg.Pool ? {
10410
+ db,
10411
+ pool: client
10412
+ } : void 0;
10413
+ }
10414
+ /**
10415
+ * Run `work` in a transaction on a client of `pool`, its opening sent with the
10416
+ * first query.
10417
+ *
10418
+ * `opening` runs at the start of the transaction, after the `BEGIN` that
10419
+ * `config` describes — and, for a read-only transaction at READ COMMITTED,
10420
+ * ahead of every statement, each in a transaction of its own (see the module
10421
+ * comment). `work` gets a drizzle transaction like the one
10422
+ * `db.transaction()` hands out: savepoints nest inside it, and it commits
10423
+ * when `work` resolves and rolls back when it throws.
10424
+ */
10425
+ async function runPipelinedTransaction(db, pool, opening, config, work) {
10426
+ const client = await pool.connect();
10427
+ const transaction = new TransactionOpening(client, beginStatement(config), opening, runsStatementByStatement(config));
10428
+ const sessionClient = new Proxy(client, { get(target, property) {
10429
+ if (property === "query") return transaction.query.bind(transaction);
10430
+ const value = Reflect.get(target, property, target);
10431
+ return typeof value === "function" ? value.bind(target) : value;
10432
+ } });
10433
+ const schema = schemaConfigOf(db);
10434
+ const tx = new NodePgTransaction(dialect, new NodePgSession(sessionClient, dialect, schema), schema);
10435
+ try {
10436
+ let result;
10437
+ try {
10438
+ result = await work(tx);
10439
+ } catch (error) {
10440
+ await transaction.rollback();
10441
+ throw error;
10442
+ }
10443
+ await transaction.commit();
10444
+ return result;
10445
+ } finally {
10446
+ client.release();
10447
+ }
10448
+ }
10449
+ //#endregion
9403
10450
  //#region src/read-routing.ts
9404
10451
  var DEFAULT_READ_STICKY_MS = 5e3;
9405
10452
  var DEFAULT_READ_MAX_LAG_MS = 1e3;
@@ -9763,7 +10810,7 @@ var RoleSwitchUnavailableError = class extends Error {
9763
10810
  /** The underlying Postgres error, when the refusal came from a live attempt. */
9764
10811
  pgError;
9765
10812
  constructor(role, pgError) {
9766
- 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.`);
10813
+ 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))}` : ""));
9767
10814
  this.name = "RoleSwitchUnavailableError";
9768
10815
  this.role = role;
9769
10816
  this.pgError = pgError;
@@ -9961,6 +11008,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9961
11008
  branchService;
9962
11009
  user;
9963
11010
  data;
11011
+ /** Where the columns of a caller's SQL came from — see `caller-sql-columns.ts`. */
11012
+ columnOrigins = new ColumnOrigins();
9964
11013
  /**
9965
11014
  * The server singleton, attached by `initializeRebaseBackend` after boot —
9966
11015
  * a driver exists before the client does. Typed as what is attached: a
@@ -9969,18 +11018,23 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9969
11018
  */
9970
11019
  client;
9971
11020
  /**
9972
- * Auto-set to `true` once a `SET LOCAL ROLE` has failed with insufficient
9973
- * privileges, so later statements refuse without spending the round trip
9974
- * to be refused again.
11021
+ * Roles a `SET ROLE` has been refused for with insufficient privileges,
11022
+ * with the refusal, so later statements as that role refuse without
11023
+ * spending the round trip to be refused again.
9975
11024
  *
9976
11025
  * Deliberately NOT a mirror of `DISABLE_DB_ROLE_SWITCHING`, which it used
9977
11026
  * to be described as. The env var is an operator saying "run these as the
9978
- * connection owner"; this flag is the database saying "I cannot give you
9979
- * the role you asked for". The first is a decision and permits the
9980
- * fallback, the second is a failure and must not — see the SECURITY note
9981
- * in {@link executeSql}.
11027
+ * connection owner"; this is the database saying "I cannot give you the
11028
+ * role you asked for". The first is a decision and permits the fallback,
11029
+ * the second is a failure and must not — see the SECURITY note in
11030
+ * {@link executeSql}.
11031
+ *
11032
+ * Per role, and keeping Postgres's own error. It was one flag: a single
11033
+ * refusal for a role picked in the SQL editor then refused every other
11034
+ * role too, `rebase_user` included, and every later refusal said "not
11035
+ * permitted to SET ROLE" with the reason Postgres gave already dropped.
9982
11036
  */
9983
- _roleSwitchingUnavailable = false;
11037
+ _roleSwitchRefusals = /* @__PURE__ */ new Map();
9984
11038
  /**
9985
11039
  * Restricted role that authenticated (user-context) requests run as (via
9986
11040
  * `SET LOCAL ROLE`) so RLS binds every statement — reads *and* writes. Set
@@ -9991,6 +11045,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
9991
11045
  * migrations, `dataAsAdmin`).
9992
11046
  */
9993
11047
  rlsUserRole;
11048
+ /** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
11049
+ rlsRequest;
9994
11050
  /**
9995
11051
  * The direct (non-pooled) URL {@link listen} holds its `LISTEN` on — this
9996
11052
  * source's, set by the bootstrapper. Never read from `DATABASE_DIRECT_URL`
@@ -10267,9 +11323,9 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10267
11323
  * property) the callback sits on.
10268
11324
  */
10269
11325
  assertAggregateUnmasked(path, options) {
10270
- if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => aggregate.fn === "count" && !aggregate.field)) return;
11326
+ if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => (aggregate.fn === "count" || aggregate.fn === "fingerprint") && !aggregate.field)) return;
10271
11327
  if (!PostgresBackendDriver.hasAfterRead(this.resolveCollectionCallbacks(void 0, path))) return;
10272
- throw ApiError.badRequest(`Aggregates other than count are refused on a collection whose rows an afterRead callback rewrites ("${path}"): a sum, average, minimum, maximum, field count or group would read the stored values the callback hides. Use \`count()\` without \`groupBy\`, or read the rows.`, "AGGREGATE_MASKED_BY_AFTER_READ", { collection: path });
11328
+ throw ApiError.badRequest(`Aggregates other than count are refused on a collection whose rows an afterRead callback rewrites ("${path}"): a sum, average, minimum, maximum, field count or group would read the stored values the callback hides. Use \`count()\` or \`fingerprint()\` without \`groupBy\`, or read the rows.`, "AGGREGATE_MASKED_BY_AFTER_READ", { collection: path });
10273
11329
  }
10274
11330
  /**
10275
11331
  * Apply afterRead to REST/SDK read results.
@@ -10298,7 +11354,6 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10298
11354
  async applyAfterReadForRest(rows, path) {
10299
11355
  if (!rows || rows.length === 0) return rows;
10300
11356
  const resolved = this.resolveCollectionCallbacks(void 0, path);
10301
- const contextForCallback = this.buildCallContext();
10302
11357
  const hasOwn = PostgresBackendDriver.hasAfterRead(resolved);
10303
11358
  const relationTargets = {};
10304
11359
  if (resolved.collection) try {
@@ -10317,6 +11372,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10317
11372
  const relKeys = Object.keys(relationTargets);
10318
11373
  if (!hasOwn && relKeys.length === 0) return rows;
10319
11374
  currentWriteScope()?.noteApplicationCode();
11375
+ const contextForCallback = this.buildCallContext();
10320
11376
  const maskEmbedded = async (value, target) => {
10321
11377
  if (Array.isArray(value)) return Promise.all(value.map((v) => maskEmbedded(v, target)));
10322
11378
  if (!value || typeof value !== "object") return value;
@@ -10644,7 +11700,94 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10644
11700
  row
10645
11701
  };
10646
11702
  }
11703
+ /**
11704
+ * Refuse a write to a collection that serves a SQL view; see
11705
+ * `view-access.ts`. A path this cannot resolve is the write's own to
11706
+ * answer — this refuses views, and never fails a write over a lookup.
11707
+ */
11708
+ assertWritable(collection, path) {
11709
+ let resolved = collection;
11710
+ if (!resolved) try {
11711
+ resolved = this.resolveCollectionCallbacks(void 0, path).collection;
11712
+ } catch {
11713
+ return;
11714
+ }
11715
+ assertCollectionWritable(resolved, path);
11716
+ }
11717
+ /**
11718
+ * The stamps a write takes after its hooks: `autoValue` dates and acting
11719
+ * users, and on an update the create-time stamps dropped, which record who
11720
+ * made the row and when — facts no later write can change.
11721
+ */
11722
+ stampAutoValues(collection, values, status, path) {
11723
+ if (!collection?.properties) return values;
11724
+ let stamped = updateDateAutoValues({
11725
+ inputValues: values,
11726
+ properties: collection.properties,
11727
+ status,
11728
+ timestampNowValue: /* @__PURE__ */ new Date()
11729
+ });
11730
+ assertActingUserForAutoValues(collection.properties, status, this.user?.uid, path);
11731
+ stamped = updateUserAutoValues({
11732
+ inputValues: stamped,
11733
+ properties: collection.properties,
11734
+ status,
11735
+ uid: this.user?.uid
11736
+ });
11737
+ if (status === "existing") {
11738
+ const kept = { ...stamped };
11739
+ for (const key of createStampKeys(collection.properties)) delete kept[key];
11740
+ stamped = kept;
11741
+ }
11742
+ return stamped;
11743
+ }
11744
+ /**
11745
+ * What the caller reads of a row it just wrote: the stored row through the
11746
+ * `afterRead` hooks, on a copy, so a hook that edits its argument in place
11747
+ * edits only the view. The stored row itself is what `afterSave` judges and
11748
+ * history records.
11749
+ */
11750
+ async viewOfSavedRow(storedRow, collection, path, hooks, context) {
11751
+ const { callbacks, globalCallbacks, propertyCallbacks } = hooks;
11752
+ if (!storedRow || !(globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) return storedRow;
11753
+ const callbackCollection = requireCallbackCollection(collection, path);
11754
+ let savedRow = { ...storedRow };
11755
+ if (globalCallbacks?.afterRead) savedRow = await globalCallbacks.afterRead({
11756
+ collection: callbackCollection,
11757
+ path,
11758
+ row: savedRow,
11759
+ context
11760
+ }) ?? savedRow;
11761
+ if (callbacks?.afterRead) savedRow = await callbacks.afterRead({
11762
+ collection: callbackCollection,
11763
+ path,
11764
+ row: savedRow,
11765
+ context
11766
+ }) ?? savedRow;
11767
+ if (propertyCallbacks?.afterRead) savedRow = await propertyCallbacks.afterRead({
11768
+ collection: callbackCollection,
11769
+ path,
11770
+ row: savedRow,
11771
+ context
11772
+ }) ?? savedRow;
11773
+ return savedRow;
11774
+ }
11775
+ /**
11776
+ * Whether a write to `collection` has to read the stored row before it
11777
+ * writes: for the hooks and history that are handed it, the tenancy and
11778
+ * per-field rules that judge it, a `beforeQuery` that scopes which rows
11779
+ * the caller addresses, the trash an update must not reach, and a nested
11780
+ * path, which reads its row from elsewhere. Without any of those the write
11781
+ * itself is the read — an UPDATE that matches nothing is the 404, an
11782
+ * upsert's conflict branch finds the stored row.
11783
+ */
11784
+ writeReadsStoredRow(collection, path, hooks) {
11785
+ if (!collection) return true;
11786
+ const { callbacks, globalCallbacks, propertyCallbacks } = hooks;
11787
+ 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));
11788
+ }
10647
11789
  async save(props) {
11790
+ this.assertWritable(props.collection, props.path);
10648
11791
  return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame));
10649
11792
  }
10650
11793
  async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored) {
@@ -10659,7 +11802,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10659
11802
  const preconditionFirst = precondition !== void 0 && status === "existing" && Boolean(id);
10660
11803
  if (!preconditionFirst) assertUpdateShape();
10661
11804
  const upserting = upsert === true && status !== "existing";
10662
- if (upserting && resolvedCollection) {
11805
+ const hooks = {
11806
+ callbacks,
11807
+ globalCallbacks,
11808
+ propertyCallbacks
11809
+ };
11810
+ const readsStoredRow = this.writeReadsStoredRow(resolvedCollection, path, hooks);
11811
+ if (upserting && resolvedCollection && readsStoredRow) {
10663
11812
  const stored = await this.findUpsertTarget(path, resolvedCollection, values, id, onConflict);
10664
11813
  if (stored) {
10665
11814
  const reusable = !callbacks?.beforeQuery && !globalCallbacks?.beforeQuery && !hasFieldAccessRules(resolvedCollection) && !isNestedPath(path);
@@ -10676,7 +11825,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10676
11825
  const contextForCallback = this.buildCallContext();
10677
11826
  if ((status === "new" || status === "copy") && resolvedCollection?.properties) updatedValues = applyDefaultValuesOnCreate(updatedValues, resolvedCollection.properties);
10678
11827
  let previousValuesForHistory;
10679
- if (status === "existing" && id) try {
11828
+ const unreadRow = status === "existing" && Boolean(id) && !precondition && !readsStoredRow;
11829
+ if (status === "existing" && id && !unreadRow) try {
10680
11830
  const withDeleted = restoresSoftDeletedRow(resolvedCollection, values) ? true : void 0;
10681
11831
  if (precondition?.lock) await this.dataService.getPersistService().lockRow(path, id);
10682
11832
  const storedPath = this.storedRowPath(path);
@@ -10742,26 +11892,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10742
11892
  }
10743
11893
  const afterHooks = updatedValues;
10744
11894
  if (status === "existing" && isPresentKey(id)) assertKeyUnchanged(resolvedCollection, this.registry, id, updatedValues, path);
10745
- if (resolvedCollection?.properties) {
10746
- updatedValues = updateDateAutoValues({
10747
- inputValues: updatedValues,
10748
- properties: resolvedCollection.properties,
10749
- status: status ?? "new",
10750
- timestampNowValue: /* @__PURE__ */ new Date()
10751
- });
10752
- assertActingUserForAutoValues(resolvedCollection.properties, status ?? "new", this.user?.uid, path);
10753
- updatedValues = updateUserAutoValues({
10754
- inputValues: updatedValues,
10755
- properties: resolvedCollection.properties,
10756
- status: status ?? "new",
10757
- uid: this.user?.uid
10758
- });
10759
- if (status === "existing") {
10760
- const kept = { ...updatedValues };
10761
- for (const key of createStampKeys(resolvedCollection.properties)) delete kept[key];
10762
- updatedValues = kept;
10763
- }
10764
- }
11895
+ updatedValues = this.stampAutoValues(resolvedCollection, updatedValues, status ?? "new", path);
10765
11896
  updatedValues = await this.applyTenantScope(resolvedCollection, path, updatedValues, status ?? "new", previousValuesForHistory);
10766
11897
  let writeId = id;
10767
11898
  if ((status === "new" || status === "copy") && !upsert && isPresentKey(id) && resolvedCollection) {
@@ -10778,31 +11909,14 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10778
11909
  const storedRow = await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, {
10779
11910
  upsert: upserting,
10780
11911
  onConflict,
10781
- insertOnlyKeys
11912
+ insertOnlyKeys,
11913
+ unreadRow
10782
11914
  });
10783
- let savedRow = storedRow;
10784
- if (storedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
10785
- const callbackCollection = requireCallbackCollection(resolvedCollection, path);
10786
- savedRow = { ...storedRow };
10787
- if (globalCallbacks?.afterRead) savedRow = await globalCallbacks.afterRead({
10788
- collection: callbackCollection,
10789
- path,
10790
- row: savedRow,
10791
- context: contextForCallback
10792
- }) ?? savedRow;
10793
- if (callbacks?.afterRead) savedRow = await callbacks.afterRead({
10794
- collection: callbackCollection,
10795
- path,
10796
- row: savedRow,
10797
- context: contextForCallback
10798
- }) ?? savedRow;
10799
- if (propertyCallbacks?.afterRead) savedRow = await propertyCallbacks.afterRead({
10800
- collection: callbackCollection,
10801
- path,
10802
- row: savedRow,
10803
- context: contextForCallback
10804
- }) ?? savedRow;
10805
- }
11915
+ const savedRow = await this.viewOfSavedRow(storedRow, resolvedCollection, path, {
11916
+ callbacks,
11917
+ globalCallbacks,
11918
+ propertyCallbacks
11919
+ }, contextForCallback);
10806
11920
  const savedId = deriveRowAddress(storedRow, resolvedCollection ?? collection, this.registry);
10807
11921
  const savedValues = storedRow;
10808
11922
  try {
@@ -10965,6 +12079,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10965
12079
  return txDriver.buildCallContext();
10966
12080
  }
10967
12081
  async saveMany({ path, rows, collection, upsert, onConflict }) {
12082
+ this.assertWritable(collection, path);
12083
+ if (rows.length > 1 && this.writesRowsTogether(collection, path)) try {
12084
+ const together = await this.inBatchTransaction((txDriver) => txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict));
12085
+ if (together) return together;
12086
+ } catch (error) {
12087
+ 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) });
12088
+ }
10968
12089
  return this.inBatchTransaction(async (txDriver) => {
10969
12090
  const saved = [];
10970
12091
  for (let i = 0; i < rows.length; i++) {
@@ -10992,6 +12113,112 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10992
12113
  });
10993
12114
  }
10994
12115
  /**
12116
+ * Whether {@link saveMany} may write a collection's rows together
12117
+ * ({@link saveRowsTogether}): no `beforeSave`, `afterSave` or
12118
+ * `afterSaveError` hook, no history and no tenancy, at its own path. A
12119
+ * hook runs once per row between that row's writes, and history and
12120
+ * tenancy read per row, so those batches keep the row-by-row pipeline.
12121
+ */
12122
+ writesRowsTogether(collection, path) {
12123
+ const { collection: resolved, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12124
+ if (!resolved || isNestedPath(path) || resolved.history || getTenantConfig(resolved)) return false;
12125
+ return [
12126
+ callbacks,
12127
+ globalCallbacks,
12128
+ propertyCallbacks
12129
+ ].every((tier) => !tier?.beforeSave && !tier?.afterSave && !tier?.afterSaveError);
12130
+ }
12131
+ /**
12132
+ * {@link saveMany}'s rows written together, a few multi-row statements in
12133
+ * place of one statement per row (`PersistService.saveRows`), and answered
12134
+ * as {@link save} answers each: defaults and `autoValue` stamps applied,
12135
+ * the stored row through `afterRead`, a realtime event per row.
12136
+ *
12137
+ * For a collection {@link writesRowsTogether} allows; `undefined`, before
12138
+ * anything is written, for a batch `saveRows` declines. Its realtime events
12139
+ * join the transaction's only once every row is answered.
12140
+ */
12141
+ async saveRowsTogether(path, rows, collection, upsert, onConflict) {
12142
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12143
+ const resolved = resolvedCollection;
12144
+ if (!resolved) return void 0;
12145
+ const hooks = {
12146
+ callbacks,
12147
+ globalCallbacks,
12148
+ propertyCallbacks
12149
+ };
12150
+ const softDeleteField = resolveSoftDelete(resolved)?.field;
12151
+ const prepared = rows.map((values) => {
12152
+ const withDefaults = resolved.properties ? applyDefaultValuesOnCreate(values, resolved.properties) : values;
12153
+ const stamped = this.stampAutoValues(resolved, withDefaults, "new", path);
12154
+ const insertOnlyKeys = upsert ? insertOnlyKeysOf(stamped, values, withDefaults, withDefaults, resolved.properties) : void 0;
12155
+ if (insertOnlyKeys && softDeleteField && stamped[softDeleteField] !== void 0 && stamped[softDeleteField] !== null) insertOnlyKeys.push(softDeleteField);
12156
+ return {
12157
+ values: stamped,
12158
+ insertOnlyKeys
12159
+ };
12160
+ });
12161
+ const stored = await this.dataService.getPersistService().saveRows(path, prepared, {
12162
+ upsert,
12163
+ onConflict
12164
+ });
12165
+ if (!stored) return void 0;
12166
+ return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, hooks);
12167
+ }
12168
+ /**
12169
+ * {@link updateMany}'s updates written together (`PersistService.updateRows`)
12170
+ * and answered as {@link save} answers each: the `on_update` stamps
12171
+ * applied, the stored row through `afterRead`, a realtime event per row.
12172
+ * For a collection {@link writesRowsTogether} allows; `undefined`, before
12173
+ * anything is written, for updates `updateRows` declines.
12174
+ */
12175
+ async updateRowsTogether(path, updates, collection) {
12176
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12177
+ const resolved = resolvedCollection;
12178
+ if (!resolved) return void 0;
12179
+ const prepared = updates.map(({ id, values }) => {
12180
+ assertUpdateDoesNotSoftDelete(resolved, values, path);
12181
+ assertKeyUnchanged(resolved, this.registry, String(id), values, path);
12182
+ return {
12183
+ id,
12184
+ values: this.stampAutoValues(resolved, values, "existing", path)
12185
+ };
12186
+ });
12187
+ const stored = await this.dataService.getPersistService().updateRows(path, prepared);
12188
+ if (!stored) return void 0;
12189
+ return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, {
12190
+ callbacks,
12191
+ globalCallbacks,
12192
+ propertyCallbacks
12193
+ });
12194
+ }
12195
+ /**
12196
+ * Rows a batch wrote, answered as {@link save} answers one: each through
12197
+ * `afterRead`, and a realtime event per row, joining the transaction's
12198
+ * only once every row is answered.
12199
+ */
12200
+ async answerRowsWritten(stored, written, collection, path, hooks) {
12201
+ const context = this.buildCallContext();
12202
+ const primaryKeys = getPrimaryKeys(collection, this.registry);
12203
+ const saved = [];
12204
+ const notifications = [];
12205
+ for (let i = 0; i < stored.length; i++) {
12206
+ const storedRow = stored[i];
12207
+ const savedRow = await this.viewOfSavedRow(storedRow, collection, path, hooks, context);
12208
+ const savedId = deriveRowAddress(storedRow, collection, this.registry, primaryKeys);
12209
+ notifications.push({
12210
+ path,
12211
+ id: savedId,
12212
+ row: savedRow,
12213
+ databaseId: collection.databaseId
12214
+ }, ...this.childListNotifications(collection, savedId, written[i]));
12215
+ saved.push(savedRow);
12216
+ }
12217
+ if (this._deferNotifications) this._pendingNotifications.push(...notifications);
12218
+ else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId);
12219
+ return saved;
12220
+ }
12221
+ /**
10995
12222
  * Update many rows through the same pipeline as {@link save}, in one
10996
12223
  * transaction.
10997
12224
  *
@@ -11007,6 +12234,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11007
12234
  * half landed without re-reading everything.
11008
12235
  */
11009
12236
  async updateMany({ path, updates, collection }) {
12237
+ this.assertWritable(collection, path);
12238
+ if (updates.length > 1 && this.writesRowsTogether(collection, path)) try {
12239
+ const together = await this.inBatchTransaction((txDriver) => txDriver.updateRowsTogether(path, updates, collection));
12240
+ if (together) return together;
12241
+ } catch (error) {
12242
+ logger.debug(`[updateMany] A batch update of "${path}" failed; updating its rows one by one to name the row`, { detail: error instanceof Error ? error.message : String(error) });
12243
+ }
11010
12244
  return this.inBatchTransaction(async (txDriver) => {
11011
12245
  const saved = [];
11012
12246
  for (let i = 0; i < updates.length; i++) {
@@ -11043,6 +12277,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11043
12277
  * happened to delete at once. Same pipeline, one transaction.
11044
12278
  */
11045
12279
  async deleteMany({ path, ids, collection, hard }) {
12280
+ this.assertWritable(collection, path);
11046
12281
  await this.inBatchTransaction(async (txDriver) => {
11047
12282
  for (let i = 0; i < ids.length; i++) {
11048
12283
  const id = ids[i];
@@ -11148,6 +12383,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11148
12383
  });
11149
12384
  }
11150
12385
  async delete(props) {
12386
+ this.assertWritable(props.collection, props.row.path);
11151
12387
  return inWriteFrame(props.row.path, "delete", (frame) => this.deleteInFrame(props, frame));
11152
12388
  }
11153
12389
  async deleteInFrame({ row, collection, hard, precondition }, frame) {
@@ -11274,11 +12510,26 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11274
12510
  databaseId: collection.databaseId
11275
12511
  }));
11276
12512
  }
12513
+ /**
12514
+ * Recompute the rows of a collection that serves a materialized view,
12515
+ * on this driver's connection — the owner's on the base driver, which a
12516
+ * refresh needs: Postgres lets only a view's owner refresh it.
12517
+ */
12518
+ async refreshView(path, options) {
12519
+ const collection = this.resolveCollectionCallbacks(void 0, path).collection;
12520
+ 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");
12521
+ const schema = collection.schema ?? "public";
12522
+ const qualified = sql`${sql.identifier(schema)}.${sql.identifier(viewRowsName(getTableName$1(collection)))}`;
12523
+ await this.db.execute(options?.concurrently ? sql`REFRESH MATERIALIZED VIEW CONCURRENTLY ${qualified}` : sql`REFRESH MATERIALIZED VIEW ${qualified}`);
12524
+ await this.realtimeService.notifyUpdate(path, "*", null);
12525
+ }
11277
12526
  async deleteAll(path) {
12527
+ this.assertWritable(void 0, path);
11278
12528
  await this.dataService.deleteAll(path);
11279
12529
  await this.realtimeService.notifyUpdate(path, "*", null);
11280
12530
  }
11281
12531
  async updateRelationPivot({ path, targetId, pivot }) {
12532
+ this.assertWritable(void 0, path);
11282
12533
  await this.dataService.updateRelationPivot(path, targetId, pivot);
11283
12534
  if (this.realtimeService.isCdcActive()) return;
11284
12535
  const notification = {
@@ -11467,12 +12718,12 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11467
12718
  logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${role}".`);
11468
12719
  return;
11469
12720
  }
11470
- if (this._roleSwitchingUnavailable) throw new RoleSwitchUnavailableError(role);
12721
+ if (this._roleSwitchRefusals.has(role)) throw new RoleSwitchUnavailableError(role, this._roleSwitchRefusals.get(role));
11471
12722
  try {
11472
12723
  await connection.query(`SET ROLE "${role.replace(/"/g, "\"\"")}"`);
11473
12724
  } catch (roleError) {
11474
12725
  if (isRoleSwitchingPermissionError(roleError)) {
11475
- this._roleSwitchingUnavailable = true;
12726
+ this._roleSwitchRefusals.set(role, roleError);
11476
12727
  throw new RoleSwitchUnavailableError(role, roleError);
11477
12728
  }
11478
12729
  throw roleError;
@@ -11520,7 +12771,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11520
12771
  needsRoleSwitch = true;
11521
12772
  }
11522
12773
  if (needsRoleSwitch && options?.role) if (isRoleSwitchingOptedOut()) logger.debug(`[PostgresBackendDriver] DISABLE_DB_ROLE_SWITCHING=true — running as the connection owner rather than "${options.role}".`);
11523
- else if (this._roleSwitchingUnavailable) throw new RoleSwitchUnavailableError(options.role);
12774
+ else if (this._roleSwitchRefusals.has(options.role)) throw new RoleSwitchUnavailableError(options.role, this._roleSwitchRefusals.get(options.role));
11524
12775
  else {
11525
12776
  const safeRole = options.role.replace(/"/g, "\"\"");
11526
12777
  try {
@@ -11530,7 +12781,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11530
12781
  });
11531
12782
  } catch (roleError) {
11532
12783
  if (isRoleSwitchingPermissionError(roleError)) {
11533
- this._roleSwitchingUnavailable = true;
12784
+ this._roleSwitchRefusals.set(options.role, roleError);
11534
12785
  throw new RoleSwitchUnavailableError(options.role, roleError);
11535
12786
  }
11536
12787
  throw roleError;
@@ -11781,6 +13032,19 @@ var AuthenticatedPostgresBackendDriver = class {
11781
13032
  });
11782
13033
  }
11783
13034
  /**
13035
+ * One statement as this caller — see {@link DataDriver.sql}. The same
13036
+ * transaction every SDK call on this driver opens (`rebase_user`, the
13037
+ * caller's identity), read-only unless `write`, and so on the read replica
13038
+ * when a read may go there.
13039
+ */
13040
+ async sql(query, options) {
13041
+ assertCallerSql(query);
13042
+ return this.withTransaction(async (delegate) => {
13043
+ const result = await delegate.dataService.executeSqlResult(query, options?.params);
13044
+ return withoutUnreadableColumns(rowsOfResult(result), fieldsOfResult(result), { roles: this.user?.roles ?? [] }, this.delegate.registry?.getCollections() ?? [], this.delegate.columnOrigins, (text, params) => delegate.dataService.executeSql(text, params));
13045
+ }, { accessMode: options?.write ? "read write" : "read only" });
13046
+ }
13047
+ /**
11784
13048
  * Run `operation` in a transaction as this caller — on the read replica
11785
13049
  * when this is a read the replica may serve (see {@link replicaFor}), else
11786
13050
  * on the primary.
@@ -11835,7 +13099,8 @@ var AuthenticatedPostgresBackendDriver = class {
11835
13099
  return router.db;
11836
13100
  }
11837
13101
  async runTransaction(db, operation, options) {
11838
- const transactionSettings = transactionSettingsStatements(pooledTransactionSettings("$client" in db ? db.$client : void 0));
13102
+ const pooledSettings = pooledTransactionSettings("$client" in db ? db.$client : void 0);
13103
+ const pipelined = pipelineTarget(db);
11839
13104
  const pendingNotifications = [];
11840
13105
  const writeScope = options?.accessMode === "read only" ? void 0 : new WriteTransactionScope();
11841
13106
  const client = this.delegate.client;
@@ -11849,33 +13114,44 @@ var AuthenticatedPostgresBackendDriver = class {
11849
13114
  },
11850
13115
  storageSource: client?.storage
11851
13116
  });
11852
- const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => db.transaction(async (tx) => {
11853
- if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
11854
- if (!this.user?.uid) logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
11855
- if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
11856
- await applyAuthContext(tx, authContextOf(this.user), this.delegate.rlsUserRole);
11857
- let hookContext;
11858
- const txEntityService = new DataService(tx, this.delegate.registry, () => {
11859
- writeScope?.noteApplicationCode();
11860
- return hookContext ??= this.delegate.callContextWithin(tx, this.user);
11861
- });
11862
- const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
11863
- txDelegate.dataService = txEntityService;
11864
- txDelegate._deferNotifications = true;
11865
- txDelegate._pendingNotifications = pendingNotifications;
11866
- txDelegate.client = this.delegate.client;
11867
- writeScope?.bind(tx, (sqlText, params) => txEntityService.executeSql(sqlText, params));
11868
- let out;
11869
- try {
11870
- out = await operation(txDelegate);
11871
- } catch (error) {
11872
- writeScope?.close();
11873
- throw error;
13117
+ const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => {
13118
+ const inTransaction = async (tx) => {
13119
+ if (!this.user?.uid) logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
13120
+ if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
13121
+ let hookContext;
13122
+ const txEntityService = new DataService(tx, this.delegate.registry, () => {
13123
+ writeScope?.noteApplicationCode();
13124
+ return hookContext ??= this.delegate.callContextWithin(tx, this.user);
13125
+ });
13126
+ const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
13127
+ txDelegate.dataService = txEntityService;
13128
+ txDelegate._deferNotifications = true;
13129
+ txDelegate._pendingNotifications = pendingNotifications;
13130
+ txDelegate.client = this.delegate.client;
13131
+ writeScope?.bind(tx, (sqlText, params) => txEntityService.executeSql(sqlText, params));
13132
+ let out;
13133
+ try {
13134
+ out = await operation(txDelegate);
13135
+ } catch (error) {
13136
+ writeScope?.close();
13137
+ throw error;
13138
+ }
13139
+ await writeScope?.settle();
13140
+ await writeScope?.assertCommittable();
13141
+ return out;
13142
+ };
13143
+ const auth = authContextOf(this.user);
13144
+ if (pipelined) {
13145
+ const opening = authContextStatement(auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
13146
+ return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], options, inTransaction);
11874
13147
  }
11875
- await writeScope?.settle();
11876
- await writeScope?.assertCommittable();
11877
- return out;
11878
- }, options)).finally(() => writeScope?.close())).catch(async (error) => {
13148
+ return db.transaction(async (tx) => {
13149
+ const transactionSettings = transactionSettingsStatements(pooledSettings);
13150
+ if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
13151
+ await applyAuthContext(tx, auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole);
13152
+ return inTransaction(tx);
13153
+ }, options);
13154
+ }).finally(() => writeScope?.close())).catch(async (error) => {
11879
13155
  await writeScope?.settled();
11880
13156
  throw error;
11881
13157
  });
@@ -11956,6 +13232,16 @@ var AuthenticatedPostgresBackendDriver = class {
11956
13232
  async deleteAll(path) {
11957
13233
  return this.withTransaction((delegate) => delegate.deleteAll(path));
11958
13234
  }
13235
+ /**
13236
+ * For a caller holding one of the view's roles, refreshed on the owner's
13237
+ * connection rather than in this caller's transaction: Postgres lets only
13238
+ * the owner refresh, and the caller's restricted role is not it.
13239
+ */
13240
+ async refreshView(path, options) {
13241
+ const collection = this.delegate.registry?.getCollectionByPath(path);
13242
+ await withFieldViewer({ roles: (this.user?.roles ?? []).map((role) => typeof role === "string" ? role : String(role.id ?? role)) }, async () => assertViewReadable(collection));
13243
+ return this.delegate.refreshView(path, options);
13244
+ }
11959
13245
  async updateRelationPivot(props) {
11960
13246
  return this.withTransaction((delegate) => delegate.updateRelationPivot(props));
11961
13247
  }
@@ -15522,6 +16808,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
15522
16808
  * would leak rows the initial (isolated) fetch correctly hid.
15523
16809
  */
15524
16810
  rlsUserRole;
16811
+ /** How a request picks its role and identity settings (`rls`), set with {@link rlsUserRole}. */
16812
+ rlsRequest;
15525
16813
  /**
15526
16814
  * Verbose subscription tracing.
15527
16815
  *
@@ -16449,7 +17737,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
16449
17737
  roles: activeAuth.roles,
16450
17738
  isAnonymous: activeAuth.isAnonymous === true,
16451
17739
  claims: activeAuth.claims
16452
- }, this.rlsUserRole);
17740
+ }, this.rlsRequest ?? this.rlsUserRole);
16453
17741
  let hookContext;
16454
17742
  const txEntityService = new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth));
16455
17743
  const fetchedEntities = collectionRequest.countOnly ? [] : await txEntityService.fetchCollectionForRest(notifyPath, {
@@ -16650,7 +17938,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
16650
17938
  roles: activeAuth.roles,
16651
17939
  isAnonymous: activeAuth.isAnonymous === true,
16652
17940
  claims: activeAuth.claims
16653
- }, this.rlsUserRole);
17941
+ }, this.rlsRequest ?? this.rlsUserRole);
16654
17942
  let hookContext;
16655
17943
  let processedEntity = await new DataService(tx, this.registry, () => hookContext ??= callbackContextWithin(this.driver, tx, activeAuth)).fetchOneForRest(notifyPath, id, include, collection?.databaseId) ?? void 0;
16656
17944
  if (processedEntity) {
@@ -20319,13 +21607,7 @@ async function ensureHistoryTableExists(db, options = {}) {
20319
21607
  $fn$
20320
21608
  `));
20321
21609
  await db.execute(sql.raw(`REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC`));
20322
- await db.execute(sql.raw(`
20323
- DO $grant$ BEGIN
20324
- IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE}') THEN
20325
- GRANT EXECUTE ON FUNCTION ${signature} TO ${REBASE_USER_ROLE};
20326
- END IF;
20327
- END $grant$
20328
- `));
21610
+ await db.execute(sql.raw(grantExecuteToRequestRolesSql(signature)));
20329
21611
  return {
20330
21612
  inTransaction: true,
20331
21613
  entryFormat
@@ -21235,8 +22517,10 @@ function postgresDriverConfigFromEnv(config, env = process.env, sourceKey = DEFA
21235
22517
  const directConnectionString = config.directConnectionString || (isDefaultSource ? read("DATABASE_DIRECT_URL") : void 0);
21236
22518
  const pooled = config.pooled ?? (isDefaultSource ? read("DATABASE_POOLED")?.toLowerCase() === "true" : void 0);
21237
22519
  const readRouting = config.readRouting ?? (read("REBASE_READ_STICKY_MS") || read("REBASE_READ_MAX_LAG_MS") ? readRoutingOptionsFromEnv(env) : void 0);
22520
+ const rls = rlsConfigFromEnv(config.rls, read);
21238
22521
  return {
21239
22522
  ...config,
22523
+ ...rls ? { rls } : {},
21240
22524
  ...readConnectionString ? { readConnectionString } : {},
21241
22525
  ...directConnectionString ? { directConnectionString } : {},
21242
22526
  ...pooled ? { pooled } : {},
@@ -21286,7 +22570,11 @@ async function openPostgresDriver(pgConfig, config) {
21286
22570
  }));
21287
22571
  }
21288
22572
  if (unprotectedJoinTables.length > 0) {
21289
- 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.`);
22573
+ const requestRoles = resolveRlsSettings({
22574
+ ...declaredDatabaseRls(config.dataSourceKey ?? DEFAULT_DATA_SOURCE_KEY),
22575
+ ...pgConfig.rls
22576
+ }).roles.join(", ");
22577
+ 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.`);
21290
22578
  for (const t of unprotectedJoinTables) schema.tablesMap.delete(t);
21291
22579
  }
21292
22580
  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(", ")}`);
@@ -21378,7 +22666,7 @@ async function openPostgresDriver(pgConfig, config) {
21378
22666
  let readRouter;
21379
22667
  let readPool;
21380
22668
  if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
21381
- const { createReadReplicaConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
22669
+ const { createReadReplicaConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
21382
22670
  const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
21383
22671
  ...pgConfig.poolConfig,
21384
22672
  pooled
@@ -21394,7 +22682,7 @@ async function openPostgresDriver(pgConfig, config) {
21394
22682
  let sessionDb;
21395
22683
  let sessionPool;
21396
22684
  if (pooled && directUrl) {
21397
- const { createDirectDatabaseConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
22685
+ const { createDirectDatabaseConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
21398
22686
  const session = createDirectDatabaseConnection(directUrl, void 0, {
21399
22687
  max: 3,
21400
22688
  idleTimeoutMillis: 1e4
@@ -21420,6 +22708,22 @@ async function openPostgresDriver(pgConfig, config) {
21420
22708
  realtimeService.setDataDriver(driver);
21421
22709
  let rlsEnforcement;
21422
22710
  let exposedInternalTables;
22711
+ const rls = resolveRlsSettings({
22712
+ ...declaredDatabaseRls(sourceKey),
22713
+ ...pgConfig.rls
22714
+ });
22715
+ const policyShape = declaredRlsPolicyShape(sourceKey);
22716
+ if (rls.policyTarget !== policyShape.policyTarget || rls.defaultPolicies !== policyShape.defaultPolicies) throw new Error(`rls.policyTarget 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}", defaultPolicies: ${rls.defaultPolicies} } }) — or set REBASE_RLS_POLICY_TARGET / REBASE_RLS_DEFAULT_POLICIES.`);
22717
+ /** The tables this driver serves — collections, junctions — for `grants: "managed"`. */
22718
+ const managedTables = () => registry.getTableNames().flatMap((name) => {
22719
+ const table = registry.getTable(name);
22720
+ if (!table) return [];
22721
+ const config = getTableConfig(table);
22722
+ return [{
22723
+ schema: config.schema ?? "public",
22724
+ table: config.name
22725
+ }];
22726
+ });
21423
22727
  {
21424
22728
  const runSql = async (text) => {
21425
22729
  return (await schemaAwareDb.execute(sql.raw(text))).rows ?? [];
@@ -21433,27 +22737,72 @@ async function openPostgresDriver(pgConfig, config) {
21433
22737
  const posture = await detectConnectionPosture(runSql, managedSchemas);
21434
22738
  if (posture.privileged) {
21435
22739
  const bypassesNow = posture.superuser || posture.bypassRLS || posture.ownsTables;
22740
+ const roleList = rls.roles.map((r) => `"${r}"`).join(", ");
21436
22741
  let switched = true;
21437
22742
  if (!provision) {
21438
- const roleExists = (await runSql(`SELECT 1 FROM pg_roles WHERE rolname = '${REBASE_USER_ROLE$1}'`)).length > 0;
22743
+ const roleExists = (await runSql(`SELECT rolname FROM pg_roles WHERE rolname = ANY(ARRAY[${rls.roles.map((r) => `'${r}'`).join(", ")}]::text[])`)).length === rls.roles.length;
21439
22744
  switched = roleExists || bypassesNow;
21440
22745
  if (roleExists) {
21441
- exposedInternalTables = await findExposedInternalTables(runSql, managedSchemas);
21442
- 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.`);
22746
+ try {
22747
+ assertRecordedRequestRoles(rls.roles, await readRecordedRequestRoles(runSql), await roleHoldsTableGrants(runSql, managedSchemas));
22748
+ for (const role of rls.roles) {
22749
+ await assertAppRoleRestricted(runSql, role);
22750
+ await proveRoleSwitch(runSql, managedSchemas, posture.role, role);
22751
+ }
22752
+ } catch (err) {
22753
+ if (bypassesNow) throw err;
22754
+ switched = false;
22755
+ 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)}`);
22756
+ }
22757
+ for (const role of rls.roles) {
22758
+ const exposed = await findExposedInternalTables(runSql, managedSchemas, role);
22759
+ if (exposed.length === 0) continue;
22760
+ exposedInternalTables = [...exposedInternalTables ?? [], ...exposed];
22761
+ 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.`);
22762
+ }
21443
22763
  }
21444
- 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.`);
22764
+ 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.`);
21445
22765
  } else try {
21446
- await ensureAppRole(runSql, managedSchemas);
22766
+ const recorded = await readRecordedRequestRoles(runSql);
22767
+ assertRecordedRequestRoles(rls.roles, recorded, await roleHoldsTableGrants(runSql, managedSchemas));
22768
+ if (recorded ? recorded.join(",") !== rls.roles.join(",") : rls.roles.join(",") !== REBASE_USER_ROLE$1) await recordRequestRoles(runSql, rls.roles);
22769
+ for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
22770
+ role,
22771
+ provisionRole: rls.provisionRole,
22772
+ grants: rls.grants,
22773
+ managedTables: managedTables(),
22774
+ inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
22775
+ });
21447
22776
  } catch (err) {
21448
22777
  if (bypassesNow) throw err;
21449
22778
  switched = false;
21450
22779
  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)}`);
21451
22780
  }
21452
22781
  if (switched) {
21453
- driver.rlsUserRole = REBASE_USER_ROLE$1;
21454
- realtimeService.rlsUserRole = REBASE_USER_ROLE$1;
22782
+ driver.rlsUserRole = rls.defaultRole;
22783
+ realtimeService.rlsUserRole = rls.defaultRole;
22784
+ driver.rlsRequest = rls.request;
22785
+ realtimeService.rlsRequest = rls.request;
21455
22786
  const why = posture.superuser ? "superuser" : posture.bypassRLS ? "BYPASSRLS" : posture.ownsTables ? "table owner" : "may create (and would then own) tables in the schemas it serves";
21456
- rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as "${REBASE_USER_ROLE$1}" (connection "${posture.role}" bypasses RLS: ${why})`;
22787
+ rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as ${roleList} (connection "${posture.role}" bypasses RLS: ${why})` + (rls.nonDefaults.length > 0 ? `; rls: ${rls.nonDefaults.join(", ")}` : "");
22788
+ for (const note of rlsHandoverNotes(rls)) logger.info(`🔐 [rls] ${note}`);
22789
+ for (const role of rls.roles) {
22790
+ if (rls.sharedRole === "ignore") break;
22791
+ const others = await findOtherRoleMembers(runSql, role);
22792
+ if (others.length === 0) continue;
22793
+ 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.`;
22794
+ if (rls.sharedRole === "refuse") throw new Error(`Refusing to serve: ${message}`);
22795
+ logger.warn(`⚠️ RLS enforcement: ${message}`);
22796
+ }
22797
+ for (const role of rls.roles) {
22798
+ const ungrantable = await findUngrantableTables(runSql, collectionsOnThisSource().map((c) => ({
22799
+ schema: c.schema ?? "public",
22800
+ table: getTableName$1(c)
22801
+ })).filter((t) => Boolean(t.table)), role);
22802
+ if (ungrantable.length === 0) continue;
22803
+ 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:
22804
+ ` + ungrantable.map((t) => ` ${t.name} (owner "${t.owner}"): ${t.grant}`).join("\n"));
22805
+ }
21457
22806
  }
21458
22807
  if (posture.superuser || posture.bypassRLS) {
21459
22808
  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.`;
@@ -21461,7 +22810,8 @@ async function openPostgresDriver(pgConfig, config) {
21461
22810
  else logger.warn(`⚠️ ${message}`);
21462
22811
  }
21463
22812
  } else rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
21464
- await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ?? posture.role);
22813
+ 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.`);
22814
+ await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ? rls.roles : posture.role);
21465
22815
  warnOnAnonymousGrants(collectionsOnThisSource());
21466
22816
  warnOnLegacyRlsFunctions(collectionsOnThisSource());
21467
22817
  }
@@ -21499,7 +22849,7 @@ async function openPostgresDriver(pgConfig, config) {
21499
22849
  if (explicitCdc) logger.warn(`⚠️ [CDC] REALTIME_CDC=${cdcMode} but ${reason} — using app-level realtime.`);
21500
22850
  else logger.info(`ℹ️ [CDC] Using app-level realtime — ${reason}.`);
21501
22851
  } else if (wantsCdc && directUrl) {
21502
- const cdcTables = collectionsOnThisSource().map((c) => ({
22852
+ const cdcTables = collectionsOnThisSource().filter((c) => !(isPostgresCollectionConfig(c) && c.view)).map((c) => ({
21503
22853
  schema: c.schema ?? "public",
21504
22854
  table: getTableName$1(c),
21505
22855
  identityColumns: collectionKeyColumns(c, registry).map((k) => k.columnName)
@@ -21649,6 +22999,8 @@ async function openPostgresDriver(pgConfig, config) {
21649
22999
  driver,
21650
23000
  poolManager,
21651
23001
  provisioned: provision,
23002
+ rls,
23003
+ managedTables,
21652
23004
  rlsEnforcement,
21653
23005
  exposedInternalTables,
21654
23006
  provisionCdcForTables
@@ -21721,7 +23073,7 @@ function createPostgresBootstrapper(pgConfig) {
21721
23073
  const openIndexBuildSession = (driverResult) => async () => {
21722
23074
  const db = requireProvisioningDb(driverResult);
21723
23075
  const pool = "$client" in db ? db.$client : void 0;
21724
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
23076
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
21725
23077
  const config = effectiveConfig();
21726
23078
  if (isPooledPool(pool) || config.pooled) {
21727
23079
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -21752,8 +23104,9 @@ function createPostgresBootstrapper(pgConfig) {
21752
23104
  */
21753
23105
  const provisionRlsRuntime = async (driverResult) => {
21754
23106
  const db = requireProvisioningDb(driverResult);
21755
- const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-DPawvckr.js").then((n) => n.E);
23107
+ const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent, ensureRequestRoleFunction } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
21756
23108
  const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
23109
+ if (declaredRlsPolicyShape().policyTarget === "requestRole") await ensureRequestRoleFunction(run);
21757
23110
  if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
21758
23111
  await db.transaction(async (tx) => {
21759
23112
  await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext('rebase_auth_functions_init'))`);
@@ -21776,7 +23129,7 @@ function createPostgresBootstrapper(pgConfig) {
21776
23129
  for (const [qualified, { schema, table }] of withheldTables) try {
21777
23130
  await runSql(revokeUserRoleSql(schema, table));
21778
23131
  } catch (err) {
21779
- 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)));
23132
+ 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)));
21780
23133
  }
21781
23134
  };
21782
23135
  return {
@@ -21786,8 +23139,8 @@ function createPostgresBootstrapper(pgConfig) {
21786
23139
  const opened = await openPostgresDriver(effectiveConfig(init.dataSourceKey), init);
21787
23140
  if (opened.internals.rlsEnforcement) logger.info(opened.internals.rlsEnforcement);
21788
23141
  const exposed = opened.internals.exposedInternalTables ?? [];
21789
- 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:
21790
- ` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${REBASE_USER_ROLE$1};`).join("\n"));
23142
+ 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:
23143
+ ` + exposed.map((table) => ` REVOKE ALL ON ${table.split(".").map((part) => `"${part}"`).join(".")} FROM ${(opened.internals.rls?.roles ?? [REBASE_USER_ROLE$1]).join(", ")};`).join("\n"));
21791
23144
  return opened;
21792
23145
  },
21793
23146
  async initializeAuth(config, driverResult) {
@@ -21865,11 +23218,11 @@ function createPostgresBootstrapper(pgConfig) {
21865
23218
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
21866
23219
  }) };
21867
23220
  }
21868
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CIGoIGcC.js").then((n) => n.i);
23221
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
21869
23222
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21870
23223
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21871
23224
  if (historyIndexes.length > 0) {
21872
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
23225
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
21873
23226
  const indexOptions = {
21874
23227
  log: (message) => logger.info(`[history] ${message}`),
21875
23228
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -21925,9 +23278,9 @@ function createPostgresBootstrapper(pgConfig) {
21925
23278
  * proved it can bootstrap with.
21926
23279
  */
21927
23280
  async ensureCollectionSchema(collections, driverResult, log) {
21928
- const { ensureCollectionTables } = await import("./ensure-collection-tables-DvaCEy6X.js").then((n) => n.n);
23281
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-DR_WcxLA.js").then((n) => n.n);
21929
23282
  const queryable = provisioningQueryable(driverResult);
21930
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CIGoIGcC.js").then((n) => n.i);
23283
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
21931
23284
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
21932
23285
  const plan = await ensureCollectionTables(queryable, collections, log, {
21933
23286
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -21939,7 +23292,7 @@ function createPostgresBootstrapper(pgConfig) {
21939
23292
  pendingIndexBuild?.cancel();
21940
23293
  pendingIndexBuild = void 0;
21941
23294
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
21942
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
23295
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
21943
23296
  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.`);
21944
23297
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
21945
23298
  log: (message) => logger.info(`[schema] ${message}`),
@@ -21979,7 +23332,7 @@ function createPostgresBootstrapper(pgConfig) {
21979
23332
  await provisionRlsRuntime(driverResult);
21980
23333
  },
21981
23334
  async ensureCollectionPolicies(collections, driverResult, log) {
21982
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-f0LIwiwp.js");
23335
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-85HiG-k1.js");
21983
23336
  const queryable = provisioningQueryable(driverResult);
21984
23337
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
21985
23338
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -22001,10 +23354,10 @@ function createPostgresBootstrapper(pgConfig) {
22001
23354
  else logger.warn(`${message}; they are re-applied on the next boot.`);
22002
23355
  }
22003
23356
  const unrevoked = outcome.unsecured.filter((u) => !u.grantWithdrawn);
22004
- 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.`);
22005
- 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.`);
23357
+ 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.`);
23358
+ 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.");
22006
23359
  try {
22007
- const { dropLegacyAuthSchema } = await import("./migrate-baseline-DPawvckr.js").then((n) => n.E);
23360
+ const { dropLegacyAuthSchema } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
22008
23361
  await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
22009
23362
  info: (m) => logger.info(m),
22010
23363
  warn: (m) => logger.warn(m)
@@ -22070,11 +23423,17 @@ function createPostgresBootstrapper(pgConfig) {
22070
23423
  "rebase",
22071
23424
  ...registry.getCollections().map((c) => c.schema).filter((s) => typeof s === "string")
22072
23425
  ];
23426
+ const rls = internals.rls ?? resolveRlsSettings(void 0);
23427
+ const grantOptions = (role) => ({
23428
+ role,
23429
+ mode: rls.grants,
23430
+ managedTables: internals.managedTables?.() ?? []
23431
+ });
22073
23432
  if (driver.rlsUserRole) {
22074
23433
  try {
22075
- await ensureAppRoleGrants(runSql, managedSchemas);
23434
+ for (const role of rls.roles) await ensureAppRoleGrants(runSql, managedSchemas, grantOptions(role));
22076
23435
  } catch (err) {
22077
- 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)}`);
23436
+ 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)}`);
22078
23437
  }
22079
23438
  await withholdAgain(runSql);
22080
23439
  return;
@@ -22082,20 +23441,28 @@ function createPostgresBootstrapper(pgConfig) {
22082
23441
  const posture = await detectConnectionPosture(runSql, managedSchemas);
22083
23442
  if (!posture.superuser && !posture.bypassRLS && !posture.ownsTables) return;
22084
23443
  try {
22085
- await ensureAppRole(runSql, managedSchemas);
23444
+ for (const role of rls.roles) await ensureAppRole(runSql, managedSchemas, {
23445
+ role,
23446
+ provisionRole: rls.provisionRole,
23447
+ grants: rls.grants,
23448
+ managedTables: internals.managedTables?.() ?? [],
23449
+ inheritRoles: rls.inheritTo.includes(role) ? rls.inheritRoles : []
23450
+ });
22086
23451
  } catch (err) {
22087
23452
  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)}`);
22088
23453
  }
22089
23454
  await withholdAgain(runSql);
22090
- driver.rlsUserRole = REBASE_USER_ROLE$1;
22091
- realtimeService.rlsUserRole = REBASE_USER_ROLE$1;
22092
- 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}".`);
23455
+ driver.rlsUserRole = rls.defaultRole;
23456
+ realtimeService.rlsUserRole = rls.defaultRole;
23457
+ driver.rlsRequest = rls.request;
23458
+ realtimeService.rlsRequest = rls.request;
23459
+ 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(", ")}.`);
22093
23460
  },
22094
23461
  getAdmin(driverResult) {
22095
23462
  return driverResult.internals.driver.admin;
22096
23463
  },
22097
23464
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
22098
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-CCJnghvG.js").then((n) => n.c);
23465
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-B33YjKhs.js").then((n) => n.c);
22099
23466
  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.`);
22100
23467
  const realtimeConfig = effectiveConfig().realtime;
22101
23468
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -22208,8 +23575,14 @@ async function openRebase(options) {
22208
23575
  throw error;
22209
23576
  }
22210
23577
  const resolveAccessor = createAccessorSlugResolver(() => registry.getCollections());
22211
- const dataAs = async (identity) => buildSdkData(await driver.withAuth(userFor(identity)), { resolveAccessor });
22212
- const dataAsAdmin = await dataAs(SERVICE_IDENTITY);
23578
+ const scopedTo = async (identity) => {
23579
+ const scoped = await driver.withAuth(userFor(identity));
23580
+ return {
23581
+ scoped,
23582
+ data: buildSdkData(scoped, { resolveAccessor })
23583
+ };
23584
+ };
23585
+ const dataAsAdmin = (await scopedTo(SERVICE_IDENTITY)).data;
22213
23586
  const admin = driver.admin;
22214
23587
  let closed = false;
22215
23588
  return {
@@ -22228,7 +23601,13 @@ async function openRebase(options) {
22228
23601
  });
22229
23602
  },
22230
23603
  async withAuth(user) {
22231
- return { data: await dataAs(user) };
23604
+ const { scoped, data } = await scopedTo(user);
23605
+ const sql = scoped.sql?.bind(scoped);
23606
+ if (!sql) throw new Error("This driver cannot run SQL as a caller.");
23607
+ return {
23608
+ data,
23609
+ sql
23610
+ };
22232
23611
  },
22233
23612
  async close() {
22234
23613
  if (closed) return;
@@ -22240,4 +23619,4 @@ async function openRebase(options) {
22240
23619
  //#endregion
22241
23620
  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 };
22242
23621
 
22243
- //# sourceMappingURL=open-rebase-DvmKIu7q.js.map
23622
+ //# sourceMappingURL=open-rebase-CiO_sjMT.js.map