@rebasepro/server-postgres 0.29.1 → 0.29.3

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 (148) hide show
  1. package/dist/{BranchService-BIIBF5ZL.js → BranchService-CrXvcES2.js} +3 -3
  2. package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-CrXvcES2.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +64 -4
  4. package/dist/PostgresBootstrapper.d.ts +27 -0
  5. package/dist/auth/ensure-tables.d.ts +2 -2
  6. package/dist/auth/schema-version.d.ts +5 -5
  7. package/dist/auth/services.d.ts +9 -9
  8. package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CTKCOLpX.js} +3 -3
  9. package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
  10. package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CqGIwSYx.js} +2 -2
  11. package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
  12. package/dist/{cli-console-DTsm96lW.js → cli-console-DBPw-oAz.js} +6 -6
  13. package/dist/{cli-console-DTsm96lW.js.map → cli-console-DBPw-oAz.js.map} +1 -1
  14. package/dist/{cli-errors-DwqFRIWz.js → cli-errors-DYTxnLbW.js} +5 -5
  15. package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
  16. package/dist/cli.js +185 -49
  17. package/dist/cli.js.map +1 -1
  18. package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
  19. package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
  20. package/dist/data-transformer.d.ts +2 -2
  21. package/dist/database-health.d.ts +2 -1
  22. package/dist/{database-preflight-D5JtPt8i.js → database-preflight-iBpT7-vv.js} +36 -3
  23. package/dist/database-preflight-iBpT7-vv.js.map +1 -0
  24. package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
  25. package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
  26. package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-BCU9RoHK.js} +18 -6
  27. package/dist/deferred-index-build-BCU9RoHK.js.map +1 -0
  28. package/dist/{doctor-BaR11xUe.js → doctor-Kg1oUK0Q.js} +11 -11
  29. package/dist/doctor-Kg1oUK0Q.js.map +1 -0
  30. package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-Bo-_fDAy.js} +25 -15
  31. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
  32. package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-DCJINkT_.js} +11 -8
  33. package/dist/ensure-collection-tables-DCJINkT_.js.map +1 -0
  34. package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-BPGaGh0y.js} +4 -4
  35. package/dist/ensure-tables-BPGaGh0y.js.map +1 -0
  36. package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-YAgOZS4I.js} +3 -3
  37. package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
  39. package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
  40. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-LTLZvt6r.js} +3 -3
  41. package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
  42. package/dist/{generate-files-Bl3_D_oP.js → generate-files-CsaVzatS.js} +3 -3
  43. package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-CsaVzatS.js.map} +1 -1
  44. package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +45 -7
  45. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
  46. package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-By4dxyTH.js} +8 -5
  47. package/dist/generated-schema-diff-By4dxyTH.js.map +1 -0
  48. package/dist/history/HistoryService.d.ts +2 -3
  49. package/dist/history/ensure-history-table.d.ts +8 -3
  50. package/dist/index.es.js +15 -15
  51. package/dist/interfaces.d.ts +24 -2
  52. package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
  53. package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
  54. package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CmWXL7qx.js} +163 -502
  55. package/dist/migrate-baseline-CmWXL7qx.js.map +1 -0
  56. package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-BN_Qad6c.js} +42 -13
  57. package/dist/migrate-policy-stamps-BN_Qad6c.js.map +1 -0
  58. package/dist/{open-rebase-CiO_sjMT.js → open-rebase-40paQfVW.js} +1401 -655
  59. package/dist/open-rebase-40paQfVW.js.map +1 -0
  60. package/dist/open-rebase.d.ts +1 -1
  61. package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-DJHjCF7-.js} +2 -2
  62. package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
  63. package/dist/pipelined-transaction.d.ts +24 -37
  64. package/dist/{plan-schema-BYxOzflz.js → plan-schema-vJd3UEmT.js} +41 -11
  65. package/dist/plan-schema-vJd3UEmT.js.map +1 -0
  66. package/dist/{policy-drift-DKuTJHfc.js → policy-drift-C-m0uWHH.js} +78 -10
  67. package/dist/policy-drift-C-m0uWHH.js.map +1 -0
  68. package/dist/push-index-adoption-Cp7oZxSl.js +22 -0
  69. package/dist/push-index-adoption-Cp7oZxSl.js.map +1 -0
  70. package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-DbwKGtQT.js} +4 -4
  71. package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
  72. package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-CLcgsEPt.js} +2 -2
  73. package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
  74. package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-BthD0E9W.js} +4 -4
  75. package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
  76. package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BgcrroxQ.js} +14 -8
  77. package/dist/push-policy-plan-BgcrroxQ.js.map +1 -0
  78. package/dist/read-routing.d.ts +10 -30
  79. package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Ci3S_SoI.js} +34 -3
  80. package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
  81. package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Dy1EgJU9.js} +10 -10
  82. package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
  83. package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-GHTJnPMV.js} +2 -2
  84. package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
  85. package/dist/rls-bootstrap-sql-kPX4-MB1.js +549 -0
  86. package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
  87. package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-Cc_UhOxb.js} +316 -10
  88. package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
  89. package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
  90. package/dist/rls-settings-BCGMIig3.js.map +1 -0
  91. package/dist/schema/doctor-cli.js +9 -9
  92. package/dist/schema/doctor-cli.js.map +1 -1
  93. package/dist/schema/drizzle-ddl.d.ts +2 -2
  94. package/dist/schema/ensure-collection-policies.d.ts +23 -3
  95. package/dist/schema/generate-drizzle-schema.js +1 -1
  96. package/dist/schema/generate-postgres-ddl-logic.d.ts +14 -1
  97. package/dist/schema/generate-postgres-ddl.js +1 -1
  98. package/dist/schema/index-adoption.d.ts +99 -0
  99. package/dist/schema/introspect-db-logic.d.ts +2 -1
  100. package/dist/schema/introspect-db.js +3 -3
  101. package/dist/schema/migrate-policy-stamps.d.ts +19 -1
  102. package/dist/schema/plan/diff-plan.d.ts +8 -1
  103. package/dist/schema/plan/render-ddl.d.ts +7 -0
  104. package/dist/schema/plan/types.d.ts +15 -0
  105. package/dist/schema/push-index-adoption.d.ts +10 -0
  106. package/dist/schema/push-policy-plan.d.ts +5 -1
  107. package/dist/schema/rls-bootstrap-sql.d.ts +19 -2
  108. package/dist/schema/search-column.d.ts +2 -2
  109. package/dist/search-column-BM-GV6vH.js.map +1 -1
  110. package/dist/security/policy-drift.d.ts +31 -1
  111. package/dist/security/rls-enforcement.d.ts +118 -1
  112. package/dist/security/rls-settings.d.ts +33 -0
  113. package/dist/services/FetchService.d.ts +33 -8
  114. package/dist/services/PersistService.d.ts +75 -4
  115. package/dist/services/RelationService.d.ts +1 -1
  116. package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
  117. package/dist/services/channel-bus/index.d.ts +2 -2
  118. package/dist/services/channel-history.d.ts +2 -2
  119. package/dist/services/channel-presence.d.ts +3 -3
  120. package/dist/services/dataService.d.ts +6 -2
  121. package/dist/services/realtimeService.d.ts +18 -5
  122. package/dist/services/socket-liveness.d.ts +6 -1
  123. package/dist/types.d.ts +1 -1
  124. package/dist/utils/drizzle-conditions.d.ts +12 -0
  125. package/dist/utils/positional-params.d.ts +40 -0
  126. package/dist/{websocket-B33YjKhs.js → websocket-B7ex6AQM.js} +3 -3
  127. package/dist/websocket-B7ex6AQM.js.map +1 -0
  128. package/dist/websocket.d.ts +14 -3
  129. package/package.json +7 -7
  130. package/dist/database-preflight-D5JtPt8i.js.map +0 -1
  131. package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
  132. package/dist/doctor-BaR11xUe.js.map +0 -1
  133. package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
  134. package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
  135. package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
  136. package/dist/generate-postgres-ddl-logic-BC3JA93M.js.map +0 -1
  137. package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
  138. package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
  139. package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
  140. package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
  141. package/dist/open-rebase-CiO_sjMT.js.map +0 -1
  142. package/dist/plan-schema-BYxOzflz.js.map +0 -1
  143. package/dist/policy-drift-DKuTJHfc.js.map +0 -1
  144. package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
  145. package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
  146. package/dist/rls-enforcement-BO618rnr.js.map +0 -1
  147. package/dist/rls-settings-De5NoHHy.js.map +0 -1
  148. package/dist/websocket-B33YjKhs.js.map +0 -1
@@ -1,31 +1,31 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-COuS5Fm-.js";
3
+ import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-C1zXTPJq.js";
4
4
  import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
5
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";
6
+ import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, ot as extractCauseMessage, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-DYTxnLbW.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-DJHjCF7-.js";
8
+ import { t as BranchService } from "./BranchService-CrXvcES2.js";
9
+ import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-BCGMIig3.js";
10
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-Cc_UhOxb.js";
10
11
  import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
11
12
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.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";
13
+ import { n as planSchema } from "./plan-schema-vJd3UEmT.js";
14
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-LTLZvt6r.js";
15
+ import { i as renderPgType } from "./render-ddl-Ci3S_SoI.js";
16
+ import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-BCU9RoHK.js";
17
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CqGIwSYx.js";
18
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DCJINkT_.js";
18
19
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
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";
20
+ import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
21
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-BPGaGh0y.js";
22
+ import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-By4dxyTH.js";
23
23
  import pg, { Client, DatabaseError, Pool } from "pg";
24
24
  import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
25
25
  import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
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";
26
+ import { SQL, and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, ne, not, notInArray, or, relations, sql } from "drizzle-orm";
27
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";
28
+ import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, declaredDatabaseRls, declaredRlsPolicyShape, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPercentileFraction, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, isTimeZoneName, joinConditions, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
29
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";
30
30
  import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
31
31
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -823,6 +823,28 @@ function toMembershipList(value) {
823
823
  return Array.isArray(value) ? value : [value];
824
824
  }
825
825
  /**
826
+ * A list as a native array operand: one untyped parameter holding a Postgres
827
+ * array literal (`'{"1","2"}'`).
828
+ *
829
+ * Not `ARRAY[$1, $2]`: untyped parameters in an array constructor resolve to
830
+ * `text`, so against an `integer[]`, `uuid[]`, `boolean[]` or enum array there
831
+ * was no operator ("operator does not exist: integer[] @> text[]") and the
832
+ * filter was a 500. An untyped literal on one side of `@>`, `<@` or `&&` takes
833
+ * the type of the other side, so Postgres types it as the column's own array
834
+ * type. A cast to the drizzle column's type would not do: the runtime
835
+ * catalogue reads an enum array as `text[]`.
836
+ *
837
+ * Every element is quoted and escaped, so a comma, a brace or a quote in a
838
+ * value stays inside its element; a quoted element still parses as a number,
839
+ * a boolean or a uuid.
840
+ */
841
+ function nativeArrayOperand(values) {
842
+ return sql`${`{${values.map((value) => {
843
+ if (value === null || value === void 0) return "NULL";
844
+ return `"${(typeof value === "string" ? value : value instanceof Date ? value.toISOString() : typeof value === "object" ? JSON.stringify(value) : String(value)).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
845
+ }).join(",")}}`}`;
846
+ }
847
+ /**
826
848
  * `array-contains-all` (`@>`: every listed element is in the column) and
827
849
  * `array-contained-by` (`<@`: every element of the column is listed), on a
828
850
  * native array or a JSONB array. Both are containment, so a GIN index on the
@@ -840,7 +862,7 @@ function arraySetCondition(target, op, value, isNativeArray) {
840
862
  return isNativeArray ? sql`cardinality(${target}) = 0` : sql`${target} = '[]'::jsonb`;
841
863
  }
842
864
  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`;
865
+ return isNativeArray ? sql`${target} ${operator} ${nativeArrayOperand(values)}` : sql`${target} ${operator} ${JSON.stringify(values)}::jsonb`;
844
866
  }
845
867
  /**
846
868
  * "The jsonb array holds at least one of `values`", as one containment test per
@@ -1012,6 +1034,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1012
1034
  };
1013
1035
  }
1014
1036
  }
1037
+ const folded = parseCaseFoldedFieldPath(field);
1038
+ if (folded) {
1039
+ const base = columnAt(folded.field);
1040
+ if (!base) throw ApiError.badRequest(`Cannot filter on "${field}": '${folded.field}' is not a column of "${collectionPath}".`, "INVALID_FILTER_FIELD");
1041
+ const text = /^(text|varchar|character|citext)/.test(base.getSQLType?.() ?? "") ? sql`${base}` : sql`${base}::text`;
1042
+ return {
1043
+ kind: "text",
1044
+ expression: folded.fn === "lower" ? sql`lower(${text})` : sql`upper(${text})`
1045
+ };
1046
+ }
1015
1047
  if (collection) {
1016
1048
  const relation = resolveCollectionRelations(collection)[field];
1017
1049
  if (relation?.kind === "belongsTo") {
@@ -1153,6 +1185,7 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1153
1185
  static compileFilterTarget(target, op, value, field, collectionPath) {
1154
1186
  if (target.kind === "column") return this.buildSingleFilterCondition(target.column, op, value);
1155
1187
  if (target.kind === "json") return this.buildJsonPathCondition(target.column, target.path, op, value);
1188
+ if (target.kind === "text") return this.buildTextCondition(target.expression, op, value, field);
1156
1189
  if (target.kind === "relation-field") return this.buildRelationFieldCondition(target, op, value, field, collectionPath);
1157
1190
  return this.buildRelationFilterCondition(target.relation, op, value, target.sourceIdColumn, target.registry, field, collectionPath);
1158
1191
  }
@@ -1193,7 +1226,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1193
1226
  case "<=": return sql`${numeric} <= ${value}`;
1194
1227
  }
1195
1228
  }
1196
- const asText = (v) => typeof v === "boolean" ? String(v) : String(v);
1229
+ return this.buildTextCondition(leaf, op, value, "a JSON path");
1230
+ }
1231
+ /**
1232
+ * A comparison against a text expression: a JSON path's leaf, or a column
1233
+ * folded to one case. Values compare as text — booleans as `->>` renders
1234
+ * them — and the membership operators compile to `= ANY` / `<> ALL` over
1235
+ * one array parameter, so a list of any length is one bound value.
1236
+ */
1237
+ static buildTextCondition(leaf, op, value, what) {
1238
+ const asText = (v) => String(v);
1197
1239
  switch (op) {
1198
1240
  case "==": return value === null || value === void 0 ? sql`${leaf} IS NULL` : sql`${leaf} = ${asText(value)}`;
1199
1241
  case "!=": return value === null || value === void 0 ? sql`${leaf} IS NOT NULL` : sql`${leaf} != ${asText(value)}`;
@@ -1212,10 +1254,10 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1212
1254
  if (value === null || value === void 0) return op === "in" ? sql`${leaf} IS NULL` : sql`${leaf} IS NOT NULL`;
1213
1255
  const values = toMembershipList(value).map(asText);
1214
1256
  if (values.length === 0) return op === "in" ? sql`FALSE` : sql`TRUE`;
1215
- const list = sql.join(values.map((v) => sql`${v}`), sql`, `);
1216
- return op === "in" ? sql`${leaf} IN (${list})` : sql`${leaf} NOT IN (${list})`;
1257
+ const list = sql.param(values);
1258
+ return op === "in" ? sql`${leaf} = ANY(${list}::text[])` : sql`${leaf} <> ALL(${list}::text[])`;
1217
1259
  }
1218
- default: throw ApiError.badRequest(`Operator "${op}" is not supported on a JSON path. Use it on the column itself.`, "INVALID_FILTER_OPERATOR");
1260
+ default: throw ApiError.badRequest(`Operator "${op}" is not supported on ${what}. Use it on the column itself.`, "INVALID_FILTER_OPERATOR");
1219
1261
  }
1220
1262
  }
1221
1263
  /**
@@ -1484,9 +1526,9 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1484
1526
  const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1485
1527
  if (op === "array-contains-any") {
1486
1528
  if (Array.isArray(value) && value.length === 0) return sql`FALSE`;
1487
- if (Array.isArray(value) && value.length > 0) return isNativeArray ? sql`${ref} && ARRAY[${sql.join(value.map((v) => sql`${v}`), sql`, `)}]` : jsonArrayContainsAny(ref, value);
1529
+ if (Array.isArray(value) && value.length > 0) return isNativeArray ? sql`${ref} && ${nativeArrayOperand(value)}` : jsonArrayContainsAny(ref, value);
1488
1530
  }
1489
- return isNativeArray ? sql`${ref} @> ARRAY[${value}]` : sql`${ref} @> ${JSON.stringify([value])}`;
1531
+ return isNativeArray ? sql`${ref} @> ${nativeArrayOperand([value])}` : sql`${ref} @> ${JSON.stringify([value])}`;
1490
1532
  };
1491
1533
  switch (op) {
1492
1534
  case "==": return {
@@ -1676,7 +1718,7 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1676
1718
  return eq(column, value);
1677
1719
  case "!=":
1678
1720
  if (value === null || value === void 0) return sql`${column} IS NOT NULL`;
1679
- return sql`${column} != ${value}`;
1721
+ return ne(column, value);
1680
1722
  case ">": return sql`${column} > ${value}`;
1681
1723
  case ">=": return sql`${column} >= ${value}`;
1682
1724
  case "<": return sql`${column} < ${value}`;
@@ -1688,16 +1730,16 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1688
1730
  }
1689
1731
  case "array-contains": {
1690
1732
  const meta = getColumnMeta(column);
1691
- if (meta.dataType === "array" || meta.columnType === "PgArray") return sql`${column} @> ARRAY[${value}]`;
1733
+ if (meta.dataType === "array" || meta.columnType === "PgArray") return sql`${column} @> ${nativeArrayOperand([value])}`;
1692
1734
  return sql`${column} @> ${JSON.stringify([value])}`;
1693
1735
  }
1694
1736
  case "array-contains-any": {
1695
1737
  const meta = getColumnMeta(column);
1696
1738
  const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1697
1739
  if (Array.isArray(value) && value.length === 0) return sql`FALSE`;
1698
- if (Array.isArray(value) && value.length > 0) if (isNativeArray) return sql`${column} && ARRAY[${sql.join(value.map((v) => sql`${v}`), sql`, `)}]`;
1740
+ if (Array.isArray(value) && value.length > 0) if (isNativeArray) return sql`${column} && ${nativeArrayOperand(value)}`;
1699
1741
  else return jsonArrayContainsAny(column, value);
1700
- if (isNativeArray) return sql`${column} @> ARRAY[${value}]`;
1742
+ if (isNativeArray) return sql`${column} @> ${nativeArrayOperand([value])}`;
1701
1743
  return sql`${column} @> ${JSON.stringify([value])}`;
1702
1744
  }
1703
1745
  case "array-contains-all":
@@ -2145,8 +2187,9 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
2145
2187
  if (!table[spec.column]) return void 0;
2146
2188
  const query = DrizzleConditionBuilder.normalizedTsQuery(searchString, spec);
2147
2189
  const config = sql`${spec.language}`;
2148
- const rows = spec.fields.map((f, i) => sql`(${i}, ${f.path}, ${sql.raw(f.textSql)}, ${sql.raw(f.foldedTextSql)})`);
2149
- const matchedField = spec.mode === "hybrid" ? sql`(to_tsvector(${config}::regconfig, f.txt) @@ ${query} OR ${DrizzleConditionBuilder.foldedSubstringOf(searchString, sql`f.folded`)})` : sql`to_tsvector(${config}::regconfig, f.txt) @@ ${query}`;
2190
+ const hybrid = spec.mode === "hybrid";
2191
+ const rows = spec.fields.map((f, i) => sql`(${i}, ${f.path}, ${sql.raw(f.textSql)}, ${sql.raw(hybrid ? f.foldedTextSql : f.textSql)})`);
2192
+ const matchedField = hybrid ? sql`(to_tsvector(${config}::regconfig, f.txt) @@ ${query} OR ${DrizzleConditionBuilder.foldedSubstringOf(searchString, sql`f.folded`)})` : sql`to_tsvector(${config}::regconfig, f.txt) @@ ${query}`;
2150
2193
  return sql`(
2151
2194
  SELECT coalesce(jsonb_agg(s.m ORDER BY f.ord), '[]'::jsonb)
2152
2195
  FROM (VALUES ${sql.join(rows, sql`, `)}) AS f(ord, path, txt, folded)
@@ -3230,7 +3273,7 @@ async function beforeQueryCondition(env, collection, path, table, description, f
3230
3273
  * the gap with a single confined cast.
3231
3274
  *
3232
3275
  * Exported so `data-transformer` uses this one rather than restating the same
3233
- * fact — it wrote `query.innerJoin(...) as unknown as typeof query`, which is
3276
+ * fact — it double-cast `query.innerJoin(...)` to `typeof query`, which is
3234
3277
  * the same claim about the same drizzle behaviour in a second spelling.
3235
3278
  */
3236
3279
  function applyDynamicJoin(query, joinTable, condition) {
@@ -4686,6 +4729,43 @@ function assertRelationReadable(collection, key, relation, use) {
4686
4729
  }]
4687
4730
  });
4688
4731
  }
4732
+ /**
4733
+ * What `fingerprint()` computes over a table's row versions, from their tuple
4734
+ * headers alone: no column is read, decoded or turned into text.
4735
+ *
4736
+ * Every row version has the xmin of the transaction that wrote it: an insert
4737
+ * or an update adds a new one, a delete takes one away. The count and the xmin
4738
+ * sum alone are linear, and cancel: a transaction that deletes one row,
4739
+ * updates another and inserts a third keeps both whenever the two xmins it
4740
+ * removed add up to twice its own, which two concurrent sessions reach. So
4741
+ * each version also adds a hash of its xmin, which no such arithmetic
4742
+ * cancels: a write only ever adds versions under its own new xid, so the
4743
+ * multiset of xmins after it can never equal the one before. The xmin alone,
4744
+ * and not the ctid beside it, because a materialized view's collection is a
4745
+ * view over its stored rows that passes their `xmin` through and no `ctid`.
4746
+ */
4747
+ function rowVersionsFingerprint(xmin) {
4748
+ return sql`md5(count(*)::text || ':' || coalesce(sum(${xmin}::text::bigint), 0)::text || ':' || coalesce(sum(hashtext(${xmin}::text)::bigint), 0)::text)`;
4749
+ }
4750
+ /**
4751
+ * The column types `percentile_cont` orders by: anything that casts to
4752
+ * `double precision`, and `interval`. A text or a timestamp column is a
4753
+ * Postgres error at execution time, so it is refused before the statement.
4754
+ */
4755
+ var PERCENTILE_TYPES = /^(smallint|integer|int[248]?|bigint|smallserial|serial[248]?|bigserial|real|float[48]?|double precision|numeric|decimal|interval)\b/i;
4756
+ /**
4757
+ * Refuse a `percentile` the statement could not compute, as the 400 the REST
4758
+ * parser answers: a `p` that is not a fraction of at most three decimals (the
4759
+ * key names three, so a fourth made two percentiles share one key), or a column
4760
+ * that is not a number. Here, not only in the parser, because the in-process
4761
+ * SDK hands its aggregates straight to the driver.
4762
+ */
4763
+ function assertPercentileComputable(aggregate, column) {
4764
+ if (!isPercentileFraction(aggregate.p)) throw ApiError.badRequest(`\`percentile\` needs a fraction from 0 to 1 with at most three decimals, e.g. \`percentile(${aggregate.field ?? "field"},0.95)\`; got ${String(aggregate.p)}.`, "INVALID_AGGREGATE_SELECT");
4765
+ if (is(column, SQL)) return;
4766
+ const type = column.getSQLType();
4767
+ if (!PERCENTILE_TYPES.test(type)) throw ApiError.badRequest(`\`percentile\` is defined on a number or interval column, and '${aggregate.field}' is ${type}.`, "INVALID_AGGREGATE_SELECT");
4768
+ }
4689
4769
  var FetchService = class FetchService {
4690
4770
  db;
4691
4771
  registry;
@@ -4806,6 +4886,19 @@ var FetchService = class FetchService {
4806
4886
  return DrizzleConditionBuilder.buildFilterConditions(filter, table, collectionPath, this.filterContext(collectionPath, table));
4807
4887
  }
4808
4888
  /**
4889
+ * A filter and a logical group as conditions, compiled as a read compiles
4890
+ * them: for a write whose rows the filter chooses (`updateWhere`,
4891
+ * `deleteWhere`).
4892
+ */
4893
+ buildWriteConditions(filter, logical, table, collectionPath) {
4894
+ const conditions = filter ? this.buildFilterConditions(filter, table, collectionPath) : [];
4895
+ if (logical) {
4896
+ const condition = DrizzleConditionBuilder.buildLogicalConditions(logical, table, collectionPath, this.filterContext(collectionPath, table));
4897
+ if (condition) conditions.push(condition);
4898
+ }
4899
+ return conditions;
4900
+ }
4901
+ /**
4809
4902
  * Resolves the correct Drizzle column for sorting.
4810
4903
  * Automatically maps owning relation property keys to their underlying foreign key column.
4811
4904
  *
@@ -4824,7 +4917,7 @@ var FetchService = class FetchService {
4824
4917
  * `_score` is only meaningful for a collection that declared a `search`
4825
4918
  * block *and* for a request that carried a search string — ranking rows
4826
4919
  * against no query ranks them all at zero. Outside those two conditions it
4827
- * is an unknown field and gets the same 400 as any other typo, which is the
4920
+ * is an unknown field and gets the same 400 as every other typo, which is the
4828
4921
  * behaviour that matters: a sort that is silently dropped returns 200 with
4829
4922
  * rows in arbitrary order, and paging over that repeats and skips rows.
4830
4923
  */
@@ -5506,7 +5599,7 @@ var FetchService = class FetchService {
5506
5599
  return stripUnreadable(flatRow, collection);
5507
5600
  }
5508
5601
  }
5509
- const visibleOne = visibleColumnProjection(getTableColumns(table), collection);
5602
+ const visibleOne = visibleColumnProjection(getTableColumns(table), collection) ?? getTableColumns(table);
5510
5603
  const result = await this.db.select(visibleOne).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
5511
5604
  if (result.length === 0) return void 0;
5512
5605
  const raw = result[0];
@@ -5667,45 +5760,75 @@ var FetchService = class FetchService {
5667
5760
  }
5668
5761
  return column;
5669
5762
  };
5763
+ const jsonLeafFor = (field, numeric) => {
5764
+ const path = field.includes("->") ? field.split(/->>?/).map((segment) => segment.trim()).filter(Boolean) : [];
5765
+ if (path.length < 2) return void 0;
5766
+ const [columnKey, ...keys] = path;
5767
+ const column = columnFor(columnKey, field);
5768
+ const sqlType = column.getSQLType?.() ?? "";
5769
+ if (sqlType !== "jsonb" && sqlType !== "json") throw ApiError.badRequest(`'${field}' reads inside '${columnKey}', which is ${sqlType || "not a JSON column"} on "${collectionPath}".`, "UNKNOWN_AGGREGATE_FIELD");
5770
+ const literal = (key) => sql.raw(`'${key.replace(/'/g, "''")}'`);
5771
+ let expression = sql`${column}`;
5772
+ for (const key of keys.slice(0, -1)) expression = sql`${expression} -> ${literal(key)}`;
5773
+ const leaf = sql`(${expression} ->> ${literal(keys[keys.length - 1])})`;
5774
+ return numeric ? sql`CASE WHEN ${leaf} ~ '^-?[0-9]+(\.[0-9]+)?$' THEN ${leaf}::numeric END` : leaf;
5775
+ };
5776
+ const NUMERIC_FUNCTIONS = /* @__PURE__ */ new Set([
5777
+ "sum",
5778
+ "avg",
5779
+ "percentile"
5780
+ ]);
5670
5781
  const selection = {};
5782
+ const groupKeys = new Set((options.groupBy ?? []).map((group) => typeof group === "string" ? group : group.key));
5783
+ const aliases = /* @__PURE__ */ new Set();
5671
5784
  for (const aggregate of options.aggregates) {
5785
+ if (aliases.has(aggregate.alias) || groupKeys.has(aggregate.alias)) throw ApiError.badRequest(`Two values of this aggregate would come back as '${aggregate.alias}'. Name one with \`as\`.`, "INVALID_AGGREGATE_SELECT", { alias: aggregate.alias });
5786
+ aliases.add(aggregate.alias);
5787
+ const filtered = aggregate.filter ? this.buildFilterConditions(aggregate.filter, table, collectionPath) : [];
5788
+ if (aggregate.filter && aggregate.fn === "fingerprint") throw ApiError.badRequest("`fingerprint()` covers the rows the query matches; narrow it with the query's own `where`.", "INVALID_AGGREGATE_SELECT");
5789
+ const filterClause = (extra) => {
5790
+ const conditions = [...extra ? [extra] : [], ...filtered];
5791
+ return conditions.length > 0 ? sql` FILTER (WHERE ${and(...conditions)})` : sql``;
5792
+ };
5672
5793
  if (aggregate.fn === "count" && !aggregate.field) {
5673
- selection[aggregate.alias] = sql`count(*)`;
5794
+ selection[aggregate.alias] = sql`count(*)${filterClause()}`;
5674
5795
  continue;
5675
5796
  }
5676
5797
  if (aggregate.fn === "fingerprint") {
5677
5798
  if (isPostgresCollectionConfig(collection) && collection.view && !collection.view.materialized) throw ApiError.badRequest(`\`fingerprint()\` reads the versions of stored rows, and "${collection.slug}" is a view that stores none. Fingerprint the tables it reads, or make it a materialized view.`, "INVALID_AGGREGATE_SELECT");
5678
- selection[aggregate.alias] = sql`md5(count(*)::text || ':' || coalesce(sum(${table}.xmin::text::bigint), 0)::text)`;
5799
+ selection[aggregate.alias] = rowVersionsFingerprint(sql`${table}.xmin`);
5679
5800
  continue;
5680
5801
  }
5681
- const column = columnFor(aggregate.field, `${aggregate.fn}()`);
5802
+ const column = jsonLeafFor(aggregate.field, NUMERIC_FUNCTIONS.has(aggregate.fn)) ?? columnFor(aggregate.field, `${aggregate.fn}()`);
5803
+ const where = filterClause();
5682
5804
  switch (aggregate.fn) {
5683
5805
  case "count":
5684
- selection[aggregate.alias] = sql`count(${column})`;
5806
+ selection[aggregate.alias] = sql`count(${column})${where}`;
5685
5807
  break;
5686
5808
  case "sum":
5687
- selection[aggregate.alias] = sql`sum(${column})::numeric`;
5809
+ selection[aggregate.alias] = sql`(sum(${column})${where})::numeric`;
5688
5810
  break;
5689
5811
  case "avg":
5690
- selection[aggregate.alias] = sql`avg(${column})::numeric`;
5812
+ selection[aggregate.alias] = sql`(avg(${column})${where})::numeric`;
5691
5813
  break;
5692
5814
  case "min":
5693
- selection[aggregate.alias] = sql`min(${column})`;
5815
+ selection[aggregate.alias] = sql`min(${column})${where}`;
5694
5816
  break;
5695
5817
  case "max":
5696
- selection[aggregate.alias] = sql`max(${column})`;
5818
+ selection[aggregate.alias] = sql`max(${column})${where}`;
5697
5819
  break;
5698
5820
  case "countDistinct":
5699
- selection[aggregate.alias] = sql`count(DISTINCT ${column})`;
5821
+ selection[aggregate.alias] = sql`count(DISTINCT ${column})${where}`;
5700
5822
  break;
5701
5823
  case "mode":
5702
- selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})`;
5824
+ selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})${where}`;
5703
5825
  break;
5704
5826
  case "percentile":
5705
- selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column}))::numeric`;
5827
+ assertPercentileComputable(aggregate, column);
5828
+ selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column})${where})::numeric`;
5706
5829
  break;
5707
5830
  case "distinct":
5708
- selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column}) FILTER (WHERE ${column} IS NOT NULL), '[]'::jsonb)`;
5831
+ selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column})${filterClause(sql`${column} IS NOT NULL`)}, '[]'::jsonb)`;
5709
5832
  break;
5710
5833
  }
5711
5834
  }
@@ -5713,7 +5836,7 @@ var FetchService = class FetchService {
5713
5836
  const groupColumns = (options.groupBy ?? []).map((group) => {
5714
5837
  if (typeof group === "string") return {
5715
5838
  field: group,
5716
- column: columnFor(group, "groupBy")
5839
+ column: jsonLeafFor(group, false) ?? columnFor(group, "groupBy")
5717
5840
  };
5718
5841
  const column = columnFor(group.field, `${group.transform}()`);
5719
5842
  return {
@@ -5778,7 +5901,13 @@ var FetchService = class FetchService {
5778
5901
  transform: group.transform
5779
5902
  });
5780
5903
  const format = group.transform === "year" ? "YYYY" : group.transform === "month" ? "YYYY-MM" : "YYYY-MM-DD";
5781
- return sql`to_char(${sqlType.includes("with time zone") ? sql`(${column} AT TIME ZONE 'UTC')` : sql`${column}`}, ${sql.raw(`'${format}'`)})`;
5904
+ if (group.timeZone !== void 0 && !isTimeZoneName(group.timeZone)) throw ApiError.badRequest(`\`${group.transform}(${group.field})\` was asked for in "${group.timeZone}", which is not a time zone. Use an IANA name such as "Europe/Madrid".`, "INVALID_AGGREGATE_GROUP", {
5905
+ field: group.field,
5906
+ transform: group.transform,
5907
+ timeZone: group.timeZone
5908
+ });
5909
+ const zone = sql.raw(`'${group.timeZone ?? "UTC"}'`);
5910
+ return sql`to_char(${sqlType.startsWith("date") ? sql`${column}` : sqlType.includes("with time zone") ? sql`(${column} AT TIME ZONE ${zone})` : group.timeZone ? sql`((${column} AT TIME ZONE 'UTC') AT TIME ZONE ${zone})` : sql`${column}`}, ${sql.raw(`'${format}'`)})`;
5782
5911
  }
5783
5912
  case "unnest": {
5784
5913
  const meta = getColumnMeta(column);
@@ -5924,7 +6053,7 @@ var FetchService = class FetchService {
5924
6053
  const projection = this.columnProjection(table, collection, options?.fields, idInfoArray);
5925
6054
  const narrowing = await this.narrowReadCondition(collectionPath, collection, table, "get", FetchService.describeRead({ fields: options?.fields }));
5926
6055
  const identity = narrowing ? and(addressed, narrowing) : addressed;
5927
- const result = await this.db.select(projection).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
6056
+ const result = await this.db.select(projection ?? getTableColumns(table)).from(table).where(andSoftDelete(identity, collection, table, withDeleted)).limit(1);
5928
6057
  if (result.length === 0) return null;
5929
6058
  const row = toRestRow(result[0], collection, this.registry);
5930
6059
  if (normalizedInclude) await this.loadIncludes([row], collection, collectionPath, normalizedInclude);
@@ -5940,13 +6069,16 @@ var FetchService = class FetchService {
5940
6069
  * `toRestRow`. For a row the statement itself wrote, with nothing written
5941
6070
  * after it, `RETURNING` those same columns is that row — the same values
5942
6071
  * through the same column decoders, in the same order, rendered the same
5943
- * way. Two things narrow the read and not the statement, and either one
5944
- * keeps the read:
6072
+ * way. One thing narrows the read and not the statement, and keeps the
6073
+ * read: a `beforeQuery` adds conditions to it (and runs application code),
6074
+ * so a row outside them is no answer today, and would be one from
6075
+ * `RETURNING`.
5945
6076
  *
5946
- * - a `beforeQuery` adds conditions to the read (and runs application
5947
- * code): a row outside them is no answer today, and would be one from
5948
- * `RETURNING`;
5949
- * - per-field read access, which projects the read for the viewer.
6077
+ * Per-field read access does not: the read selects the same columns and
6078
+ * withholds what the caller may not read when it renders the row
6079
+ * (`toRestRow` → `stripUnreadable`), which is the render here too — so an
6080
+ * `excludeFromApi` column is written, and not answered, without a read
6081
+ * back per row.
5950
6082
  *
5951
6083
  * Row-level security is the same either way. `INSERT … RETURNING` holds
5952
6084
  * the new row to the table's SELECT policies and refuses one they hide
@@ -5955,7 +6087,7 @@ var FetchService = class FetchService {
5955
6087
  */
5956
6088
  insertReturning(collectionPath) {
5957
6089
  const collection = getCollectionByPath(collectionPath, this.registry);
5958
- if (hasBeforeQuery(this.registry, collection) || hasFieldAccessRules(collection)) return void 0;
6090
+ if (hasBeforeQuery(this.registry, collection)) return void 0;
5959
6091
  const table = getTableForCollection(collection, this.registry);
5960
6092
  const tableColumns = getTableColumns(table);
5961
6093
  if (!tableColumns) return void 0;
@@ -6914,60 +7046,493 @@ function runInWriteScope(scope, fn) {
6914
7046
  */
6915
7047
  globalThis[Symbol.for("rebase.server.ambientTransactionResolver")] = currentWriteScope;
6916
7048
  //#endregion
6917
- //#region src/services/PersistService.ts
7049
+ //#region src/pipelined-transaction.ts
6918
7050
  /**
6919
- * The top-level properties whose value is stamped once, when the row is
6920
- * created: `on_create` dates and `user_on_create` identities.
7051
+ * A request's transaction, opened in the same round trip as its first query.
6921
7052
  *
6922
- * What they hold is a fact about the row's creation, so a write to a row that
6923
- * already exists has nothing to say about them — an update, and the
6924
- * conflict-update of an upsert that met a stored row. Top level only: a stamp
6925
- * nested inside a `map` is part of that map's value, not a column a write can
6926
- * leave out.
7053
+ * Every request runs in a transaction that starts with two statements of its
7054
+ * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
7055
+ * and drops to the restricted role (`authContextStatement`). Sent one after
7056
+ * the other, each waits for the last, and a lone read paid four round trips —
7057
+ * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
7058
+ * one. Against a database a few milliseconds away that is most of the request.
7059
+ *
7060
+ * Postgres accepts several statements in one batch: the extended protocol's
7061
+ * Parse/Bind/Execute for each, then one Sync. The server runs them in order
7062
+ * and answers them together, so this sends nothing when the transaction is
7063
+ * opened and puts its opening statements in front of the first query instead.
7064
+ * Should one of them fail, the server skips the rest up to the Sync: a refused
7065
+ * role switch fails the batch before the query runs, with the same error a
7066
+ * statement of its own would have raised.
7067
+ *
7068
+ * A read-only transaction at READ COMMITTED goes one step further. Each of its
7069
+ * statements reads its own snapshot, so running each statement in a batch of
7070
+ * its own with the context in front — a transaction that ends at the Sync —
7071
+ * is the same transaction as far as anything inside it can tell, minus the
7072
+ * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
7073
+ * statement that only means something inside a transaction block (a
7074
+ * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
7075
+ * one, from that statement on.
7076
+ *
7077
+ * A write that knows its last statement (`commitWithNextStatement`) sends its
7078
+ * `COMMIT` in the same batch, behind it: a lone write is then `BEGIN`, the
7079
+ * context, the statement and `COMMIT` in one round trip, where it was two.
7080
+ * Should the statement fail, the server skips the `COMMIT` and the
7081
+ * transaction is rolled back like every failed one. A statement sent after it
7082
+ * opens a new transaction, with the same opening.
7083
+ *
7084
+ * Statement values are serialized by pg's own `prepareValue`, so a value means
7085
+ * the same here as in any other query; rows are parsed with the query's own
7086
+ * type parsers, as pg's `Query` parses them.
6927
7087
  */
6928
- function createStampKeys(properties) {
6929
- const keys = [];
6930
- for (const [key, property] of Object.entries(properties ?? {})) if (property?.type === "date" && property.autoValue === "on_create" || property?.type === "string" && property.autoValue === "user_on_create") keys.push(key);
6931
- return keys;
7088
+ var COMMAND_TAG = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
7089
+ /**
7090
+ * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
7091
+ * Sync, one round trip. The result is the one statement's the caller asked
7092
+ * for (`last`); the statements around it are run for their effect and their
7093
+ * rows are dropped unparsed.
7094
+ *
7095
+ * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
7096
+ * nothing for it but what `submit` writes, and hands it each message the
7097
+ * server sends back until ReadyForQuery.
7098
+ */
7099
+ var PipelinedQuery = class {
7100
+ /** How many statements this batch sends. */
7101
+ statementCount;
7102
+ /** Set by `client.query`, which wraps it for its read timeout. */
7103
+ callback;
7104
+ /** The statements, in the order they are sent, with their serialized values. */
7105
+ statements;
7106
+ rowMode;
7107
+ types;
7108
+ /** Statements ahead of the result's whose completion has not arrived yet. */
7109
+ ahead;
7110
+ /** Whether the result's statement has completed: what follows it is not the result. */
7111
+ answered = false;
7112
+ fields = [];
7113
+ parsers = [];
7114
+ rows = [];
7115
+ command = "";
7116
+ rowCount = null;
7117
+ oid = 0;
7118
+ rowError;
7119
+ settled = false;
7120
+ constructor(lead, last, callback, trail = []) {
7121
+ this.statements = [
7122
+ ...lead,
7123
+ last,
7124
+ ...trail
7125
+ ].map((statement) => ({
7126
+ text: statement.text,
7127
+ values: (statement.values ?? []).map((value) => prepareValue(value))
7128
+ }));
7129
+ this.statementCount = this.statements.length;
7130
+ this.ahead = lead.length;
7131
+ this.rowMode = last.rowMode;
7132
+ this.types = last.types ?? pg.types;
7133
+ this.callback = callback;
7134
+ }
7135
+ submit(connection) {
7136
+ connection.stream.cork();
7137
+ try {
7138
+ for (const statement of this.statements) {
7139
+ connection.parse({
7140
+ text: statement.text,
7141
+ name: "",
7142
+ types: []
7143
+ }, true);
7144
+ connection.bind({
7145
+ portal: "",
7146
+ statement: "",
7147
+ values: statement.values
7148
+ }, true);
7149
+ connection.describe({
7150
+ type: "P",
7151
+ name: ""
7152
+ }, true);
7153
+ connection.execute({ portal: "" }, true);
7154
+ }
7155
+ connection.sync();
7156
+ } finally {
7157
+ connection.stream.uncork();
7158
+ }
7159
+ }
7160
+ handleRowDescription(message) {
7161
+ if (this.ahead > 0 || this.answered) return;
7162
+ this.fields = message.fields;
7163
+ this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, "text"));
7164
+ }
7165
+ handleDataRow(message) {
7166
+ if (this.ahead > 0 || this.answered || this.rowError) return;
7167
+ const values = message.fields;
7168
+ try {
7169
+ if (this.rowMode === "array") {
7170
+ const row = new Array(values.length);
7171
+ for (let i = 0; i < values.length; i++) {
7172
+ const raw = values[i];
7173
+ row[i] = raw === null ? null : this.parsers[i](raw);
7174
+ }
7175
+ this.rows.push(row);
7176
+ } else {
7177
+ const row = {};
7178
+ for (let i = 0; i < values.length; i++) {
7179
+ const raw = values[i];
7180
+ row[this.fields[i].name] = raw === null ? null : this.parsers[i](raw);
7181
+ }
7182
+ this.rows.push(row);
7183
+ }
7184
+ } catch (error) {
7185
+ this.rowError = error instanceof Error ? error : new Error(String(error));
7186
+ }
7187
+ }
7188
+ handleCommandComplete(message) {
7189
+ if (this.ahead > 0) {
7190
+ this.ahead -= 1;
7191
+ return;
7192
+ }
7193
+ if (this.answered) return;
7194
+ this.answered = true;
7195
+ const match = COMMAND_TAG.exec(message.text);
7196
+ if (!match) return;
7197
+ this.command = match[1];
7198
+ if (match[3]) {
7199
+ this.oid = Number.parseInt(match[2], 10);
7200
+ this.rowCount = Number.parseInt(match[3], 10);
7201
+ } else if (match[2]) this.rowCount = Number.parseInt(match[2], 10);
7202
+ }
7203
+ /** An empty statement completes with EmptyQueryResponse rather than CommandComplete. */
7204
+ handleEmptyQuery() {
7205
+ if (this.ahead > 0) this.ahead -= 1;
7206
+ else this.answered = true;
7207
+ }
7208
+ handlePortalSuspended() {}
7209
+ handleError(error) {
7210
+ if (this.settled) return;
7211
+ this.settled = true;
7212
+ this.callback?.(error);
7213
+ }
7214
+ handleReadyForQuery() {
7215
+ if (this.settled) return;
7216
+ this.settled = true;
7217
+ if (this.rowError) {
7218
+ this.callback?.(this.rowError);
7219
+ return;
7220
+ }
7221
+ const result = {
7222
+ command: this.command,
7223
+ rowCount: this.rowCount,
7224
+ oid: this.oid,
7225
+ fields: this.fields,
7226
+ rows: this.rows
7227
+ };
7228
+ this.callback?.(null, result);
7229
+ }
7230
+ };
7231
+ /** Send `lead`, `last` and `trail` in one round trip; the result is `last`'s. */
7232
+ function runPipelined(client, lead, last, trail = []) {
7233
+ return new Promise((resolve, reject) => {
7234
+ client.query(new PipelinedQuery(lead, last, (error, result) => {
7235
+ if (error) reject(error);
7236
+ else if (result) resolve(result);
7237
+ }, trail));
7238
+ });
6932
7239
  }
6933
7240
  /**
6934
- * The most rows one INSERT of a batch carries, and the most values: Postgres
6935
- * takes at most 65,535 parameters in a statement.
7241
+ * A statement that means something only inside a transaction block, so a
7242
+ * read cannot run it in a batch of its own: savepoints, transaction-local
7243
+ * settings, cursors and transaction-scoped locks.
6936
7244
  */
6937
- var BATCH_MAX_ROWS = 1e3;
6938
- var BATCH_MAX_PARAMS = 3e4;
7245
+ var NEEDS_TRANSACTION_BLOCK = /^\s*(?:savepoint|release|rollback|set\s+local|set\s+transaction|declare|lock|prepare\s+transaction)\b|\bset_config\s*\(|\bpg_advisory_xact_lock|\bpg_try_advisory_xact_lock/i;
6939
7246
  /**
6940
- * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
6941
- * when nothing could catch its failure and carry on, straight on `db`.
6942
- *
6943
- * The savepoint exists for a write a hook started (`context.data`): a hook may
6944
- * catch the database refusing it, and the write it runs inside must stay
6945
- * usable. A write a caller started directly inside a request's transaction
6946
- * (frame depth 1, an open write scope) has no such catcher — the REST route,
6947
- * the socket handler and the bulk and batch loops all rethrow, and the
6948
- * request's transaction rolls back whole — so its savepoint only cost two
6949
- * round trips per row: 2,000 of a 1,000-row bulk's statements. Outside a
6950
- * request's transaction (`db` is the pool) a real transaction is still opened,
6951
- * so the row and its relation writes land together.
7247
+ * A statement pg runs with a protocol of its own: COPY streams, a named
7248
+ * statement pg keeps track of, a portal read page by page. Sent as pg sends
7249
+ * it, after the transaction's opening has gone ahead in a batch of its own.
6952
7250
  */
6953
- function inOwnTransactionUnlessTopLevel(db, write) {
6954
- if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
6955
- return db.transaction((tx) => write(tx));
7251
+ function cannotPipeline(config) {
7252
+ return Boolean(config.name) || Boolean(config.rows) || /^\s*copy\b/i.test(config.text);
6956
7253
  }
6957
- /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
6958
- function castableType(sqlType) {
7254
+ function toQueryConfig(statement) {
6959
7255
  return {
6960
- smallserial: "smallint",
6961
- serial: "integer",
6962
- bigserial: "bigint"
6963
- }[sqlType.toLowerCase()] ?? sqlType;
7256
+ text: statement.text,
7257
+ values: statement.values ? [...statement.values] : void 0
7258
+ };
7259
+ }
7260
+ function beginStatement(config) {
7261
+ const parts = ["begin"];
7262
+ if (config?.isolationLevel) parts.push(`isolation level ${config.isolationLevel}`);
7263
+ if (config?.accessMode) parts.push(config.accessMode);
7264
+ if (typeof config?.deferrable === "boolean") parts.push(config.deferrable ? "deferrable" : "not deferrable");
7265
+ return parts.join(" ");
6964
7266
  }
6965
7267
  /**
6966
- * Service for handling all row write operations.
6967
- * Handles saving, deleting, and updating rows.
7268
+ * Whether a transaction with these settings can run each statement in a batch
7269
+ * of its own. Read-only, at READ COMMITTED: every statement takes its own
7270
+ * snapshot there anyway, and none of them can write.
6968
7271
  */
6969
- var PersistService = class {
6970
- db;
7272
+ function runsStatementByStatement(config) {
7273
+ return config?.accessMode === "read only" && (config.isolationLevel === void 0 || config.isolationLevel === "read committed") && config.deferrable !== true;
7274
+ }
7275
+ /**
7276
+ * A savepoint being set or released: a statement with no result to wait for,
7277
+ * which can go out with whatever is sent next.
7278
+ */
7279
+ var DEFERRABLE = /^\s*(?:savepoint|release(?:\s+savepoint)?)\s+[A-Za-z_][A-Za-z0-9_]*\s*;?\s*$/i;
7280
+ var ROLLBACK_TO = /^\s*rollback\s+to\s+(?:savepoint\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*;?\s*$/i;
7281
+ function settledWithoutSending(text) {
7282
+ const command = text.trim().split(/\s+/)[0].toUpperCase();
7283
+ return Promise.resolve({
7284
+ command,
7285
+ rowCount: null,
7286
+ oid: 0,
7287
+ fields: [],
7288
+ rows: []
7289
+ });
7290
+ }
7291
+ var COMMIT = { text: "commit" };
7292
+ /**
7293
+ * The client side of one transaction: sends its opening with the first query,
7294
+ * holds savepoints back until a statement goes out after them, and sends
7295
+ * `COMMIT` or `ROLLBACK` only when something was sent — or sends the `COMMIT`
7296
+ * behind the statement it was told is the last.
7297
+ */
7298
+ var TransactionOpening = class {
7299
+ client;
7300
+ begin;
7301
+ opening;
7302
+ statementByStatement;
7303
+ /**
7304
+ * `fresh`: nothing sent, or what was sent has committed (the next
7305
+ * statement opens a new transaction). `implicit`: each statement ran in a
7306
+ * batch of its own. `open`: in a transaction block.
7307
+ */
7308
+ state = "fresh";
7309
+ /** In a block: statements accepted and not yet sent, which go out ahead of the next one. */
7310
+ pending = [];
7311
+ /** In a block: whether its `BEGIN` has reached the server. */
7312
+ begun = false;
7313
+ /** Whether the next statement sent carries the `COMMIT` behind it. See {@link commitWithNext}. */
7314
+ commitsWithNext = false;
7315
+ constructor(client, begin, opening, statementByStatement) {
7316
+ this.client = client;
7317
+ this.begin = begin;
7318
+ this.opening = opening;
7319
+ this.statementByStatement = statementByStatement;
7320
+ }
7321
+ /** The `query` the transaction's drizzle session calls. Decides synchronously, so concurrent calls queue in order. */
7322
+ query(config, values) {
7323
+ const statement = typeof config === "string" ? {
7324
+ text: config,
7325
+ values
7326
+ } : values !== void 0 ? {
7327
+ ...config,
7328
+ values
7329
+ } : config;
7330
+ const pipelinable = !cannotPipeline(statement);
7331
+ if (this.state !== "open") {
7332
+ if (this.statementByStatement && pipelinable && !NEEDS_TRANSACTION_BLOCK.test(statement.text)) {
7333
+ this.state = "implicit";
7334
+ return runPipelined(this.client, [READ_ONLY_STATEMENT, ...this.opening], statement);
7335
+ }
7336
+ this.state = "open";
7337
+ this.pending = [{ text: this.begin }, ...this.opening];
7338
+ }
7339
+ const rollbackTo = ROLLBACK_TO.exec(statement.text);
7340
+ if (rollbackTo) {
7341
+ const at = this.pending.findLastIndex((pending) => pending.text.trim().toLowerCase() === `savepoint ${rollbackTo[1].toLowerCase()}`);
7342
+ if (at >= 0) {
7343
+ this.pending = this.pending.slice(0, at);
7344
+ return settledWithoutSending(statement.text);
7345
+ }
7346
+ }
7347
+ if (DEFERRABLE.test(statement.text) && !statement.values?.length) {
7348
+ this.pending.push({ text: statement.text });
7349
+ return settledWithoutSending(statement.text);
7350
+ }
7351
+ return this.send(statement, pipelinable);
7352
+ }
7353
+ /**
7354
+ * Send the `COMMIT` behind the next statement, in its batch. `false`, and
7355
+ * nothing changes, for a transaction that runs each statement in a batch
7356
+ * of its own (a read has no `COMMIT` to send).
7357
+ */
7358
+ commitWithNext() {
7359
+ if (this.statementByStatement) return false;
7360
+ this.commitsWithNext = true;
7361
+ return true;
7362
+ }
7363
+ /** `statement`, with everything pending in front of it. */
7364
+ send(statement, pipelinable = true) {
7365
+ const lead = this.pending;
7366
+ this.pending = [];
7367
+ if (lead.length > 0) this.begun = true;
7368
+ if (this.commitsWithNext && pipelinable) {
7369
+ this.commitsWithNext = false;
7370
+ return runPipelined(this.client, lead, statement, [COMMIT]).then((result) => {
7371
+ this.state = "fresh";
7372
+ this.begun = false;
7373
+ return result;
7374
+ });
7375
+ }
7376
+ if (lead.length === 0) return this.client.query(statement);
7377
+ if (pipelinable) return runPipelined(this.client, lead, statement);
7378
+ return runPipelined(this.client, lead.slice(0, -1), toQueryConfig(lead[lead.length - 1])).then(() => this.client.query(statement));
7379
+ }
7380
+ async commit() {
7381
+ this.commitsWithNext = false;
7382
+ if (this.state === "open" && this.begun) await this.send({ text: "commit" });
7383
+ this.pending = [];
7384
+ }
7385
+ async rollback() {
7386
+ this.commitsWithNext = false;
7387
+ this.pending = [];
7388
+ if (this.state === "open" && this.begun) await this.client.query("rollback");
7389
+ }
7390
+ };
7391
+ /**
7392
+ * What `SET TRANSACTION READ ONLY` sets, as a statement that can run in a batch
7393
+ * outside a transaction block — where `SET TRANSACTION` warns and does nothing.
7394
+ */
7395
+ var READ_ONLY_STATEMENT = { text: "SELECT set_config('transaction_read_only', 'on', true)" };
7396
+ /** The relational schema a drizzle handle was built with, for a session over another client. */
7397
+ function schemaConfigOf(db) {
7398
+ const { schema, fullSchema, tableNamesMap } = db._;
7399
+ return schema && fullSchema ? {
7400
+ schema,
7401
+ fullSchema,
7402
+ tableNamesMap
7403
+ } : void 0;
7404
+ }
7405
+ var dialect = new PgDialect();
7406
+ /** The pipelined transaction the current async context runs in. */
7407
+ var currentTransaction = new AsyncLocalStorage();
7408
+ /**
7409
+ * Send the current transaction's `COMMIT` in the same batch as its next
7410
+ * statement: for a write whose next statement is its last, so it is one round
7411
+ * trip rather than two. Call it right before that statement, with nothing in
7412
+ * between that could send another.
7413
+ *
7414
+ * `false`, with nothing changed, outside a pipelined write transaction (a
7415
+ * PGlite handle, a read, no transaction at all): the caller's statement runs
7416
+ * as it would have, and the transaction commits when it ends.
7417
+ *
7418
+ * Nothing sent after that statement belongs to its transaction: it opens a
7419
+ * new one, with the same opening. So only the reads that explain why a write
7420
+ * changed nothing may follow it — the write committed nothing to undo.
7421
+ */
7422
+ function commitWithNextStatement() {
7423
+ return currentTransaction.getStore()?.commitWithNext() ?? false;
7424
+ }
7425
+ /**
7426
+ * The drizzle handle and pg pool to run a pipelined transaction on, or
7427
+ * `undefined` for a handle that is not a drizzle database over a pg pool of
7428
+ * this process's pg (PGlite, a transaction, a caller's own copy of either
7429
+ * library), which opens its transactions statement by statement.
7430
+ */
7431
+ function pipelineTarget(db) {
7432
+ if (!(db instanceof NodePgDatabase) || !("$client" in db)) return void 0;
7433
+ const client = db.$client;
7434
+ return client instanceof pg.Pool ? {
7435
+ db,
7436
+ pool: client
7437
+ } : void 0;
7438
+ }
7439
+ /**
7440
+ * Run `work` in a transaction on a client of `pool`, its opening sent with the
7441
+ * first query.
7442
+ *
7443
+ * `opening` runs at the start of the transaction, after the `BEGIN` that
7444
+ * `config` describes — and, for a read-only transaction at READ COMMITTED,
7445
+ * ahead of every statement, each in a transaction of its own (see the module
7446
+ * comment). `work` gets a drizzle transaction like the one
7447
+ * `db.transaction()` hands out: savepoints nest inside it, and it commits
7448
+ * when `work` resolves and rolls back when it throws.
7449
+ */
7450
+ async function runPipelinedTransaction(db, pool, opening, config, work) {
7451
+ const client = await pool.connect();
7452
+ const transaction = new TransactionOpening(client, beginStatement(config), opening, runsStatementByStatement(config));
7453
+ const sessionClient = new Proxy(client, { get(target, property) {
7454
+ if (property === "query") return transaction.query.bind(transaction);
7455
+ const value = Reflect.get(target, property, target);
7456
+ return typeof value === "function" ? value.bind(target) : value;
7457
+ } });
7458
+ const schema = schemaConfigOf(db);
7459
+ const tx = new NodePgTransaction(dialect, new NodePgSession(sessionClient, dialect, schema), schema);
7460
+ try {
7461
+ let result;
7462
+ try {
7463
+ result = await currentTransaction.run(transaction, () => work(tx));
7464
+ } catch (error) {
7465
+ await transaction.rollback();
7466
+ throw error;
7467
+ }
7468
+ await transaction.commit();
7469
+ return result;
7470
+ } finally {
7471
+ client.release();
7472
+ }
7473
+ }
7474
+ //#endregion
7475
+ //#region src/services/PersistService.ts
7476
+ /**
7477
+ * The top-level properties whose value is stamped once, when the row is
7478
+ * created: `on_create` dates and `user_on_create` identities.
7479
+ *
7480
+ * What they hold is a fact about the row's creation, so a write to a row that
7481
+ * already exists has nothing to say about them — an update, and the
7482
+ * conflict-update of an upsert that met a stored row. Top level only: a stamp
7483
+ * nested inside a `map` is part of that map's value, not a column a write can
7484
+ * leave out.
7485
+ */
7486
+ function createStampKeys(properties) {
7487
+ const keys = [];
7488
+ for (const [key, property] of Object.entries(properties ?? {})) if (property?.type === "date" && property.autoValue === "on_create" || property?.type === "string" && property.autoValue === "user_on_create") keys.push(key);
7489
+ return keys;
7490
+ }
7491
+ /**
7492
+ * The most rows one INSERT of a batch carries, and the most values: Postgres
7493
+ * takes at most 65,535 parameters in a statement.
7494
+ */
7495
+ var BATCH_MAX_ROWS = 1e3;
7496
+ var BATCH_MAX_PARAMS = 3e4;
7497
+ /**
7498
+ * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
7499
+ * when nothing could catch its failure and carry on, straight on `db`.
7500
+ *
7501
+ * The savepoint exists for a write a hook started (`context.data`): a hook may
7502
+ * catch the database refusing it, and the write it runs inside must stay
7503
+ * usable. A write a caller started directly inside a request's transaction
7504
+ * (frame depth 1, an open write scope) has no such catcher — the REST route,
7505
+ * the socket handler and the bulk and batch loops all rethrow, and the
7506
+ * request's transaction rolls back whole — so its savepoint only cost two
7507
+ * round trips per row: 2,000 of a 1,000-row bulk's statements. Outside a
7508
+ * request's transaction (`db` is the pool) a real transaction is still opened,
7509
+ * so the row and its relation writes land together.
7510
+ */
7511
+ function inOwnTransactionUnlessTopLevel(db, write) {
7512
+ if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
7513
+ return db.transaction((tx) => write(tx));
7514
+ }
7515
+ /**
7516
+ * A filtered write whose filter compiled to no condition: it would address
7517
+ * every row, and is refused rather than run.
7518
+ */
7519
+ function filterRequired(collectionPath) {
7520
+ return ApiError.badRequest(`A filtered write to "${collectionPath}" needs at least one condition: without one it would address every row.`, "FILTER_REQUIRED");
7521
+ }
7522
+ /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
7523
+ function castableType(sqlType) {
7524
+ return {
7525
+ smallserial: "smallint",
7526
+ serial: "integer",
7527
+ bigserial: "bigint"
7528
+ }[sqlType.toLowerCase()] ?? sqlType;
7529
+ }
7530
+ /**
7531
+ * Service for handling all row write operations.
7532
+ * Handles saving, deleting, and updating rows.
7533
+ */
7534
+ var PersistService = class {
7535
+ db;
6971
7536
  registry;
6972
7537
  callContext;
6973
7538
  /** Reads: whether a row is under a parent, the key a link joins on. */
@@ -7031,9 +7596,10 @@ var PersistService = class {
7031
7596
  await this.db.select({ locked: sql`1` }).from(table).where(condition).for("no key update");
7032
7597
  }
7033
7598
  /**
7034
- * Delete an row by ID
7599
+ * Delete a row by ID. `options.commitsTransaction`: see
7600
+ * {@link PersistSaveOptions.commitsTransaction}.
7035
7601
  */
7036
- async delete(collectionPath, id, _databaseId) {
7602
+ async delete(collectionPath, id, _databaseId, options) {
7037
7603
  const hop = isNestedPath(collectionPath) ? resolveNestedPath(collectionPath, this.registry) : void 0;
7038
7604
  if (hop) {
7039
7605
  assertWritableThrough(hop, collectionPath);
@@ -7049,7 +7615,11 @@ var PersistService = class {
7049
7615
  const condition = rowIdentityCondition(table, requirePrimaryKeys(collection, this.registry), id, collectionPath);
7050
7616
  let result;
7051
7617
  try {
7052
- result = await inOwnTransactionUnlessTopLevel(this.db, (tx) => tx.delete(table).where(condition));
7618
+ result = await inOwnTransactionUnlessTopLevel(this.db, (tx) => {
7619
+ const statement = tx.delete(table).where(condition);
7620
+ if (options?.commitsTransaction) commitWithNextStatement();
7621
+ return statement;
7622
+ });
7053
7623
  } catch (error) {
7054
7624
  throw this.toUserFriendlyError(error, collection.slug, collection, "delete");
7055
7625
  }
@@ -7109,6 +7679,15 @@ var PersistService = class {
7109
7679
  * not have. What they compile to is `field-op-sql.ts`.
7110
7680
  */
7111
7681
  async save(collectionPath, values, id, databaseId, options) {
7682
+ const saved = await this.saveUnlessKept(collectionPath, values, id, databaseId, options);
7683
+ if (!saved) throw new Error(`Saving a row in "${collectionPath}" answered no row.`);
7684
+ return saved;
7685
+ }
7686
+ /**
7687
+ * {@link save}, for an upsert with a {@link ConflictRule}: `undefined`
7688
+ * when the rule left the stored row on the conflict target as it was.
7689
+ */
7690
+ async saveUnlessKept(collectionPath, values, id, databaseId, options) {
7112
7691
  let effectiveCollectionPath = collectionPath;
7113
7692
  const effectiveValues = { ...values };
7114
7693
  let junctionTableInfo;
@@ -7179,7 +7758,11 @@ var PersistService = class {
7179
7758
  const entityData = sanitizeAndConvertDates(serializedResult.scalarData);
7180
7759
  assertWritableColumns(entityData, table, effectiveCollectionPath);
7181
7760
  if (fieldOpKeys.length > 0) assertWritableColumns(Object.fromEntries(fieldOpKeys.map((key) => [key, null])), table, effectiveCollectionPath);
7182
- savedId = await inOwnTransactionUnlessTopLevel(this.db, async (tx) => {
7761
+ const lastStatement = () => {
7762
+ if (options?.commitsTransaction && rowIsWrittenLast) commitWithNextStatement();
7763
+ };
7764
+ const conditional = Boolean(options?.ignoreDuplicates || options?.conflictWhere);
7765
+ const kept = await inOwnTransactionUnlessTopLevel(this.db, async (tx) => {
7183
7766
  let currentId;
7184
7767
  if (id && !options?.upsert) {
7185
7768
  currentId = id;
@@ -7194,7 +7777,9 @@ var PersistService = class {
7194
7777
  ...compiledOps ?? {}
7195
7778
  });
7196
7779
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7197
- const updated = await updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds))).returning(returning?.columns ?? returningKeys);
7780
+ const statement = updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds))).returning(returning?.columns ?? returningKeys);
7781
+ lastStatement();
7782
+ const updated = await statement;
7198
7783
  if (returning && updated[0]) returnedRow = returning.render(updated[0]);
7199
7784
  if (updated.length === 0) {
7200
7785
  const broken = await brokenFieldOpBounds(tx, table, [condition], bounds);
@@ -7228,14 +7813,19 @@ var PersistService = class {
7228
7813
  const softDelete = resolveSoftDelete(collection);
7229
7814
  const trashColumn = softDelete ? softDeleteColumn(collection, table) : void 0;
7230
7815
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7231
- const updating = Object.keys(set).length > 0;
7816
+ const updating = Object.keys(set).length > 0 && !options.ignoreDuplicates;
7817
+ const condition = options.conflictWhere ? this.fetchService.buildFilterConditions(options.conflictWhere, table, effectiveCollectionPath) : [];
7818
+ const setWhere = condition.length > 0 ? and(...writable ? [writable] : [], ...condition) : writable;
7232
7819
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7233
- result = updating ? await insertQuery.onConflictDoUpdate({
7820
+ const statement = updating ? insertQuery.onConflictDoUpdate({
7234
7821
  target,
7235
7822
  set,
7236
- setWhere: writable
7237
- }).returning(returning?.columns ?? returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7823
+ setWhere
7824
+ }).returning(returning?.columns ?? returningKeys) : insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7825
+ lastStatement();
7826
+ result = await statement;
7238
7827
  if (returning && result[0]) returnedRow = returning.render(result[0]);
7828
+ if (result.length === 0 && conditional && (options.ignoreDuplicates || !await this.storedRowRefusesWrite(tx, table, target.map((column, i) => eq(column, dataForInsert[targetFields[i]])), scope, trashColumn))) return;
7239
7829
  if (result.length === 0) {
7240
7830
  const keyConditions = target.map((column, i) => eq(column, dataForInsert[targetFields[i]]));
7241
7831
  if (scope) keyConditions.push(scope);
@@ -7251,7 +7841,9 @@ var PersistService = class {
7251
7841
  }
7252
7842
  } else {
7253
7843
  const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7254
- result = await insertQuery.returning(returning?.columns ?? returningKeys);
7844
+ const statement = insertQuery.returning(returning?.columns ?? returningKeys);
7845
+ lastStatement();
7846
+ result = await statement;
7255
7847
  if (returning && result[0]) returnedRow = returning.render(result[0]);
7256
7848
  }
7257
7849
  const resultRow = result[0];
@@ -7265,6 +7857,8 @@ var PersistService = class {
7265
7857
  if (junctionTableInfo) await this.relationWrites.handleJunctionTableCreation(tx, currentId, junctionTableInfo);
7266
7858
  return currentId;
7267
7859
  });
7860
+ if (kept === void 0) return void 0;
7861
+ savedId = kept;
7268
7862
  } catch (error) {
7269
7863
  throw this.toUserFriendlyError(error, collection.slug, collection);
7270
7864
  }
@@ -7348,6 +7942,10 @@ var PersistService = class {
7348
7942
  const scope = upsert ? await this.writeScope(collection, collectionPath, table) : void 0;
7349
7943
  const trashColumn = (upsert ? resolveSoftDelete(collection) : void 0) ? softDeleteColumn(collection, table) : void 0;
7350
7944
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7945
+ const conditional = Boolean(options?.ignoreDuplicates || options?.conflictWhere);
7946
+ const condition = upsert && options?.conflictWhere ? this.fetchService.buildFilterConditions(options.conflictWhere, table, collectionPath) : [];
7947
+ const setWhere = condition.length > 0 ? and(...writable ? [writable] : [], ...condition) : writable;
7948
+ const lastCommits = options?.commitsTransaction === true && (!upsert || options.ignoreDuplicates === true || !scope && !trashColumn);
7351
7949
  const runs = [];
7352
7950
  let start = 0;
7353
7951
  let params = 0;
@@ -7375,8 +7973,11 @@ var PersistService = class {
7375
7973
  for (const run of runs) {
7376
7974
  const slice = prepared.slice(run.start, run.end);
7377
7975
  const insertQuery = this.db.insert(table).values(slice.map((row) => row.data));
7976
+ const last = run === runs[runs.length - 1];
7378
7977
  if (!upsert) {
7379
- const result = await insertQuery.returning(returning.columns);
7978
+ const statement = insertQuery.returning(returning.columns);
7979
+ if (last && lastCommits) commitWithNextStatement();
7980
+ const result = await statement;
7380
7981
  if (result.length !== slice.length) throw new Error(`Inserted ${slice.length} rows into "${collectionPath}" and got ${result.length} back.`);
7381
7982
  result.forEach((row, i) => {
7382
7983
  written[run.start + i] = returning.render(row);
@@ -7389,11 +7990,13 @@ var PersistService = class {
7389
7990
  const column = table[field];
7390
7991
  set[field] = sql`excluded.${sql.identifier(column.name)}`;
7391
7992
  }
7392
- const result = setColumns.length > 0 ? await insertQuery.onConflictDoUpdate({
7993
+ const statement = setColumns.length > 0 && !options?.ignoreDuplicates ? insertQuery.onConflictDoUpdate({
7393
7994
  target,
7394
7995
  set,
7395
- setWhere: writable
7396
- }).returning(returning.columns) : await insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7996
+ setWhere
7997
+ }).returning(returning.columns) : insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7998
+ if (last && lastCommits) commitWithNextStatement();
7999
+ const result = await statement;
7397
8000
  const byKey = /* @__PURE__ */ new Map();
7398
8001
  for (const row of result) byKey.set(JSON.stringify(targetFields.map((field) => String(row[field]))), row);
7399
8002
  slice.forEach((row, i) => {
@@ -7402,10 +8005,14 @@ var PersistService = class {
7402
8005
  });
7403
8006
  }
7404
8007
  const saved = [];
7405
- for (let i = 0; i < rows.length; i++) saved.push(written[i] ?? await this.save(collectionPath, rows[i].values, void 0, collection.databaseId, {
8008
+ for (let i = 0; i < rows.length; i++) if (written[i]) saved.push(written[i]);
8009
+ else if (conditional && (options?.ignoreDuplicates || !scope && !trashColumn)) saved.push(void 0);
8010
+ else saved.push(await this.saveUnlessKept(collectionPath, rows[i].values, void 0, collection.databaseId, {
7406
8011
  upsert,
7407
8012
  onConflict: options?.onConflict,
7408
- insertOnlyKeys: rows[i].insertOnlyKeys
8013
+ insertOnlyKeys: rows[i].insertOnlyKeys,
8014
+ ignoreDuplicates: options?.ignoreDuplicates,
8015
+ conflictWhere: options?.conflictWhere
7409
8016
  }));
7410
8017
  return saved;
7411
8018
  }
@@ -7506,31 +8113,124 @@ var PersistService = class {
7506
8113
  return written;
7507
8114
  }
7508
8115
  /**
7509
- * The caller's `beforeQuery` scope over this table, as one condition: what
7510
- * a stored row must satisfy for a write that meets it to change it. The
7511
- * same scope the update gate and the single get apply; `undefined` when the
7512
- * collection declares no hook.
7513
- */
7514
- writeScope(collection, collectionPath, table) {
7515
- const [key] = getPrimaryKeys(collection, this.registry);
7516
- return beforeQueryCondition({
7517
- registry: this.registry,
7518
- callContext: this.callContext
7519
- }, collection, collectionPath, table, {
7520
- operation: "get",
7521
- query: {}
7522
- }, {
7523
- collection,
7524
- registry: this.registry,
7525
- sourceIdColumn: key ? table[key.fieldName] : void 0
7526
- });
7527
- }
7528
- /**
7529
- * Get the RelationService instance for external use
8116
+ * Update every row the conditions match, in one
8117
+ * `UPDATE … SET … WHERE … RETURNING` statement, and return each row as
8118
+ * {@link save} returns it. Field operations are compiled as for one row,
8119
+ * and their declared bounds are checked by the same statement: a matched
8120
+ * row an operation would take out of bounds fails the call.
8121
+ *
8122
+ * `undefined`, before anything is written, for a write that needs what
8123
+ * only the row-by-row update does: a relation in the values, or a
8124
+ * collection whose rows the statement cannot return (`beforeQuery`,
8125
+ * per-field read access). `options.commitsTransaction`: see
8126
+ * {@link PersistSaveOptions.commitsTransaction}; not honoured when bounds
8127
+ * are checked, which takes a statement after the update.
7530
8128
  */
7531
- getRelationService() {
7532
- return this.relationService;
7533
- }
8129
+ async updateWhere(collectionPath, filter, logical, values, options) {
8130
+ const collection = getCollectionByPath(collectionPath, this.registry);
8131
+ const returning = this.fetchService.insertReturning(collection.slug);
8132
+ if (!returning) return void 0;
8133
+ assertNoReadOnlyRelationValues(values, collection);
8134
+ const table = getTableForCollection(collection, this.registry);
8135
+ const { values: plainValues, fieldOps } = splitFieldOps(values, collection.properties);
8136
+ const resolvedRelations = resolveCollectionRelations(collection);
8137
+ if (Object.keys(resolvedRelations).some((key) => resolvedRelations[key]?.cardinality === "many" && Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
8138
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
8139
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
8140
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
8141
+ assertWritableColumns(data, table, collectionPath);
8142
+ const fieldOpKeys = Object.keys(fieldOps);
8143
+ if (fieldOpKeys.length > 0) assertWritableColumns(Object.fromEntries(fieldOpKeys.map((key) => [key, null])), table, collectionPath);
8144
+ if (Object.keys(data).length === 0 && fieldOpKeys.length === 0) throw ApiError.badRequest(`A filtered update of "${collectionPath}" sets nothing: send at least one field to set.`, "INVALID_BULK_BODY");
8145
+ const compiledOps = fieldOpKeys.length > 0 ? compileFieldOps(table, fieldOps, { collectionPath }) : {};
8146
+ const bounds = fieldOpKeys.length > 0 ? compileFieldOpBounds(table, fieldOps, collection.properties ?? {}, { collectionPath }) : [];
8147
+ const conditions = this.fetchService.buildWriteConditions(filter, logical, table, collectionPath);
8148
+ if (conditions.length === 0) throw filterRequired(collectionPath);
8149
+ try {
8150
+ const statement = this.db.update(table).set({
8151
+ ...data,
8152
+ ...compiledOps
8153
+ }).where(and(...conditions, ...bounds.map((bound) => bound.holds))).returning(returning.columns);
8154
+ if (options?.commitsTransaction && bounds.length === 0) commitWithNextStatement();
8155
+ const updated = await statement;
8156
+ if (bounds.length > 0) {
8157
+ const broken = await brokenFieldOpBounds(this.db, table, conditions, bounds);
8158
+ if (broken.length > 0) throw fieldOpBoundsError(collection.slug, broken);
8159
+ }
8160
+ return updated.map((row) => returning.render(row));
8161
+ } catch (error) {
8162
+ throw this.toUserFriendlyError(error, collection.slug, collection);
8163
+ }
8164
+ }
8165
+ /**
8166
+ * Delete every row the conditions match, in one `DELETE … WHERE …
8167
+ * RETURNING` statement, and return each deleted row's key columns.
8168
+ * `options.commitsTransaction`: see {@link PersistSaveOptions.commitsTransaction}.
8169
+ */
8170
+ async deleteWhere(collectionPath, filter, logical, options) {
8171
+ const collection = getCollectionByPath(collectionPath, this.registry);
8172
+ const table = getTableForCollection(collection, this.registry);
8173
+ const keyColumns = Object.fromEntries(requirePrimaryKeys(collection, this.registry).map((info) => [info.fieldName, table[info.fieldName]]));
8174
+ const conditions = this.fetchService.buildWriteConditions(filter, logical, table, collectionPath);
8175
+ if (conditions.length === 0) throw filterRequired(collectionPath);
8176
+ try {
8177
+ const statement = this.db.delete(table).where(and(...conditions)).returning(keyColumns);
8178
+ if (options?.commitsTransaction) commitWithNextStatement();
8179
+ return await statement;
8180
+ } catch (error) {
8181
+ throw this.toUserFriendlyError(error, collection.slug, collection, "delete");
8182
+ }
8183
+ }
8184
+ /**
8185
+ * Whether the row `id` addresses matches `filter`, as the caller reads
8186
+ * it: for an upsert under a `conflictWhere` that found its row first.
8187
+ */
8188
+ async rowMatches(collectionPath, id, filter) {
8189
+ const collection = getCollectionByPath(collectionPath, this.registry);
8190
+ const table = getTableForCollection(collection, this.registry);
8191
+ const condition = rowIdentityCondition(table, requirePrimaryKeys(collection, this.registry), id, collectionPath);
8192
+ const [row] = await this.db.select({ one: sql`1` }).from(table).where(and(condition, ...this.fetchService.buildFilterConditions(filter, table, collectionPath))).limit(1);
8193
+ return row !== void 0;
8194
+ }
8195
+ /**
8196
+ * Whether the stored row on an upsert's conflict target is one the
8197
+ * caller's write may not change at all — outside their `beforeQuery`
8198
+ * scope, or in the trash — rather than one a {@link ConflictRule} kept.
8199
+ * Asked only when there is a scope or a trash: without either, nothing
8200
+ * but the rule can have kept it, and no statement is sent.
8201
+ */
8202
+ async storedRowRefusesWrite(tx, table, key, scope, trashColumn) {
8203
+ if (!scope && !trashColumn) return false;
8204
+ const writable = [...scope ? [scope] : [], ...trashColumn ? [isNull(trashColumn)] : []];
8205
+ const [row] = await tx.select({ writable: sql`${and(...writable)}` }).from(table).where(and(...key)).limit(1);
8206
+ return row !== void 0 && row.writable !== true;
8207
+ }
8208
+ /**
8209
+ * The caller's `beforeQuery` scope over this table, as one condition: what
8210
+ * a stored row must satisfy for a write that meets it to change it. The
8211
+ * same scope the update gate and the single get apply; `undefined` when the
8212
+ * collection declares no hook.
8213
+ */
8214
+ writeScope(collection, collectionPath, table) {
8215
+ const [key] = getPrimaryKeys(collection, this.registry);
8216
+ return beforeQueryCondition({
8217
+ registry: this.registry,
8218
+ callContext: this.callContext
8219
+ }, collection, collectionPath, table, {
8220
+ operation: "get",
8221
+ query: {}
8222
+ }, {
8223
+ collection,
8224
+ registry: this.registry,
8225
+ sourceIdColumn: key ? table[key.fieldName] : void 0
8226
+ });
8227
+ }
8228
+ /**
8229
+ * Get the RelationService instance for external use
8230
+ */
8231
+ getRelationService() {
8232
+ return this.relationService;
8233
+ }
7534
8234
  /**
7535
8235
  * The write half, for external use. Separate from
7536
8236
  * {@link getRelationService} because they are separate objects now: reads
@@ -7575,6 +8275,133 @@ var PersistService = class {
7575
8275
  }
7576
8276
  };
7577
8277
  //#endregion
8278
+ //#region src/utils/positional-params.ts
8279
+ /**
8280
+ * Raw SQL with `$n` placeholders, as one drizzle statement that binds each
8281
+ * parameter once.
8282
+ *
8283
+ * `rebase.sql(text, { params })` takes the text and parameters `pg` takes, and
8284
+ * has to mean what `pg` means by them. It used to split the text on every
8285
+ * `/\$(\d+)/` and bind each occurrence as a new parameter, which broke three
8286
+ * ways:
8287
+ *
8288
+ * - A `$1` written N times became N bind parameters. Postgres infers each
8289
+ * one's type alone, so an uncast reuse failed with `could not determine data
8290
+ * type of parameter $7` where `pg` ran the same text, and the value was sent
8291
+ * N times.
8292
+ * - A `$1` inside a string literal, a quoted identifier, a comment or a
8293
+ * dollar-quoted body was bound as a parameter, changing the statement.
8294
+ * - `a$1`, an identifier Postgres allows, was split in two.
8295
+ *
8296
+ * So the text is scanned the way Postgres's lexer reads it, and only a
8297
+ * placeholder outside those spans is a parameter. The first occurrence of
8298
+ * each `$n` becomes a `sql.param`; drizzle numbers params in the order they
8299
+ * appear, so a later occurrence is written as the number drizzle gave the
8300
+ * first. Each value is sent once, and every occurrence is the same parameter.
8301
+ */
8302
+ var IDENT_CHAR = /[A-Za-z0-9_$\u0080-￿]/;
8303
+ var DOLLAR_TAG = /^\$([A-Za-z_\u0080-￿][A-Za-z0-9_\u0080-￿]*)?\$/;
8304
+ /**
8305
+ * Split `text` into SQL text and `$n` placeholders, leaving string literals,
8306
+ * quoted identifiers, comments and dollar-quoted bodies whole.
8307
+ */
8308
+ function splitPlaceholders(text) {
8309
+ const pieces = [];
8310
+ let start = 0;
8311
+ let i = 0;
8312
+ const flush = (end) => {
8313
+ if (end > start) pieces.push({ text: text.slice(start, end) });
8314
+ };
8315
+ while (i < text.length) {
8316
+ const ch = text[i];
8317
+ const next = text[i + 1];
8318
+ if (ch === "'") {
8319
+ const escapes = i > 0 && (text[i - 1] === "E" || text[i - 1] === "e") && (i < 2 || !IDENT_CHAR.test(text[i - 2]));
8320
+ i++;
8321
+ while (i < text.length) {
8322
+ if (escapes && text[i] === "\\") {
8323
+ i += 2;
8324
+ continue;
8325
+ }
8326
+ if (text[i] === "'") {
8327
+ if (text[i + 1] === "'") {
8328
+ i += 2;
8329
+ continue;
8330
+ }
8331
+ break;
8332
+ }
8333
+ i++;
8334
+ }
8335
+ i++;
8336
+ } else if (ch === "\"") {
8337
+ i++;
8338
+ while (i < text.length) {
8339
+ if (text[i] === "\"") {
8340
+ if (text[i + 1] === "\"") {
8341
+ i += 2;
8342
+ continue;
8343
+ }
8344
+ break;
8345
+ }
8346
+ i++;
8347
+ }
8348
+ i++;
8349
+ } else if (ch === "-" && next === "-") {
8350
+ const end = text.indexOf("\n", i);
8351
+ i = end === -1 ? text.length : end + 1;
8352
+ } else if (ch === "/" && next === "*") {
8353
+ let depth = 1;
8354
+ i += 2;
8355
+ while (i < text.length && depth > 0) if (text[i] === "/" && text[i + 1] === "*") {
8356
+ depth++;
8357
+ i += 2;
8358
+ } else if (text[i] === "*" && text[i + 1] === "/") {
8359
+ depth--;
8360
+ i += 2;
8361
+ } else i++;
8362
+ } else if (ch === "$" && (i === 0 || !IDENT_CHAR.test(text[i - 1]))) {
8363
+ const digits = /^\$(\d+)/.exec(text.slice(i));
8364
+ if (digits) {
8365
+ flush(i);
8366
+ pieces.push({ param: Number(digits[1]) });
8367
+ i += digits[0].length;
8368
+ start = i;
8369
+ continue;
8370
+ }
8371
+ const tag = DOLLAR_TAG.exec(text.slice(i));
8372
+ if (tag) {
8373
+ const close = text.indexOf(tag[0], i + tag[0].length);
8374
+ i = close === -1 ? text.length : close + tag[0].length;
8375
+ } else i++;
8376
+ } else if (IDENT_CHAR.test(ch)) while (i < text.length && IDENT_CHAR.test(text[i])) i++;
8377
+ else i++;
8378
+ }
8379
+ flush(text.length);
8380
+ return pieces;
8381
+ }
8382
+ /**
8383
+ * `text` and `params` as one drizzle statement: each `$n` bound once, however
8384
+ * often it appears, and nothing inside a literal, identifier or comment bound.
8385
+ */
8386
+ function positionalStatement(text, params) {
8387
+ if (!params || params.length === 0) return sql.raw(text);
8388
+ const chunks = [];
8389
+ const bound = /* @__PURE__ */ new Map();
8390
+ for (const piece of splitPlaceholders(text)) {
8391
+ if ("text" in piece) {
8392
+ chunks.push(sql.raw(piece.text));
8393
+ continue;
8394
+ }
8395
+ const placed = bound.get(piece.param);
8396
+ if (placed !== void 0) chunks.push(sql.raw(`$${placed}`));
8397
+ else {
8398
+ bound.set(piece.param, bound.size + 1);
8399
+ chunks.push(sql`${sql.param(params[piece.param - 1])}`);
8400
+ }
8401
+ }
8402
+ return sql.join(chunks, sql.raw(""));
8403
+ }
8404
+ //#endregion
7578
8405
  //#region src/services/dataService.ts
7579
8406
  /**
7580
8407
  * DataService - Facade for row operations.
@@ -7666,11 +8493,15 @@ var DataService = class {
7666
8493
  async save(collectionPath, values, id, databaseId, options) {
7667
8494
  return this.persistService.save(collectionPath, values, id, databaseId, options);
7668
8495
  }
8496
+ /** See {@link PersistService.saveUnlessKept}. */
8497
+ async saveUnlessKept(collectionPath, values, id, databaseId, options) {
8498
+ return this.persistService.saveUnlessKept(collectionPath, values, id, databaseId, options);
8499
+ }
7669
8500
  /**
7670
8501
  * Delete an row by ID
7671
8502
  */
7672
- async delete(collectionPath, id, databaseId) {
7673
- return this.persistService.delete(collectionPath, id, databaseId);
8503
+ async delete(collectionPath, id, databaseId, options) {
8504
+ await this.persistService.delete(collectionPath, id, databaseId, options);
7674
8505
  }
7675
8506
  /**
7676
8507
  * Delete all rows from a collection
@@ -7691,20 +8522,7 @@ var DataService = class {
7691
8522
  /** {@link executeSql}, answering with the driver's whole result: its rows and its column descriptions. */
7692
8523
  async executeSqlResult(sqlText, params) {
7693
8524
  if (rawQueryLoggingEnabled()) logger.debug(`Executing raw SQL: ${sqlText}${params?.length ? ` with ${params.length} params` : ""}`);
7694
- const { sql } = await import("drizzle-orm");
7695
- let result;
7696
- if (params && params.length > 0) {
7697
- const parts = sqlText.split(/\$(\d+)/);
7698
- const chunks = [];
7699
- for (let i = 0; i < parts.length; i++) if (i % 2 === 0) {
7700
- if (parts[i].length > 0) chunks.push(sql.raw(parts[i]));
7701
- } else {
7702
- const paramIndex = Number(parts[i]) - 1;
7703
- chunks.push(sql.param(params[paramIndex]));
7704
- }
7705
- const query = sql.join(chunks, sql.raw(""));
7706
- result = await this.db.execute(query);
7707
- } else result = await this.db.execute(sql.raw(sqlText));
8525
+ const result = await this.db.execute(positionalStatement(sqlText, params));
7708
8526
  if (rawQueryLoggingEnabled()) logger.debug(`SQL executed successfully. Returned ${rowsOfResult(result).length} rows.`);
7709
8527
  return result;
7710
8528
  }
@@ -9996,458 +10814,124 @@ var PgNotifyListener = class {
9996
10814
  await client.query(`LISTEN ${channel}`);
9997
10815
  this.client = client;
9998
10816
  pending = void 0;
9999
- this.downSince = void 0;
10000
- this.outageWarned = false;
10001
- this.lastHeartbeatAt = Date.now();
10002
- this.startHeartbeat(client);
10003
- logger.debug(`📡 ${logLabel} Listening on channel "${channel}".`);
10004
- } catch (err) {
10005
- if (pending) try {
10006
- await pending.end();
10007
- } catch {}
10008
- if (first && !this.options.retryInitialConnect) throw err;
10009
- const retry = `${logLabel} LISTEN connection could not be opened (${connectFailureReason(err)}); retrying every ${Math.round((this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1) / 1e3)} s.`;
10010
- if (this.outageWarned) logger.debug(retry);
10011
- else {
10012
- this.outageWarned = true;
10013
- logger.warn(`⚠️ ${retry}`);
10014
- }
10015
- this.scheduleReconnect();
10016
- return;
10017
- }
10018
- if (!first && this.options.onReconnect) {
10019
- logger.warn(`⚠️ ${logLabel} LISTEN client reconnected; anything published while it was down was missed.`);
10020
- try {
10021
- this.options.onReconnect();
10022
- } catch (err) {
10023
- logger.error(`❌ ${logLabel} Error resyncing after a reconnect`, { error: err });
10024
- }
10025
- }
10026
- }
10027
- /**
10028
- * Give up on the current connection: it is no longer the listener's, so
10029
- * its late events are ignored and `connected` says so at once; it is
10030
- * ended without waiting on it; and a replacement is scheduled.
10031
- */
10032
- abandon(client) {
10033
- if (client !== this.client) return;
10034
- this.client = void 0;
10035
- this.downSince ??= Date.now();
10036
- this.stopHeartbeat();
10037
- client.end().catch(() => {});
10038
- this.scheduleReconnect();
10039
- }
10040
- startHeartbeat(client) {
10041
- this.stopHeartbeat();
10042
- const interval = this.options.heartbeatIntervalMs ?? 3e4;
10043
- if (interval <= 0) return;
10044
- this.heartbeatTimer = setInterval(() => void this.heartbeat(client), interval);
10045
- unref(this.heartbeatTimer);
10046
- }
10047
- stopHeartbeat() {
10048
- if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
10049
- this.heartbeatTimer = void 0;
10050
- this.heartbeatInFlight = false;
10051
- }
10052
- /**
10053
- * One round trip on the LISTEN connection. Not answered in time, it is
10054
- * treated as dead: the client is ended — which, with the query still
10055
- * outstanding, destroys the socket rather than waiting on a goodbye that
10056
- * cannot arrive — and replaced.
10057
- */
10058
- async heartbeat(client) {
10059
- if (client !== this.client || this.heartbeatInFlight) return;
10060
- this.heartbeatInFlight = true;
10061
- const timeoutMs = this.options.heartbeatTimeoutMs ?? 1e4;
10062
- let timer;
10063
- try {
10064
- await Promise.race([client.query("SELECT 1"), new Promise((_resolve, reject) => {
10065
- timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no answer in ${timeoutMs}ms`)), timeoutMs);
10066
- })]);
10067
- if (client === this.client) this.lastHeartbeatAt = Date.now();
10068
- } catch (err) {
10069
- if (client !== this.client) return;
10070
- logger.warn(`⚠️ ${this.options.logLabel} LISTEN connection failed its heartbeat (${err instanceof Error ? err.message : String(err)}) — treating it as dead and reconnecting.`);
10071
- this.abandon(client);
10072
- } finally {
10073
- if (timer) clearTimeout(timer);
10074
- if (client === this.client) this.heartbeatInFlight = false;
10075
- }
10076
- }
10077
- scheduleReconnect() {
10078
- if (!this.running || this.reconnectTimer) return;
10079
- this.downSince ??= Date.now();
10080
- this.reconnectTimer = setTimeout(async () => {
10081
- this.reconnectTimer = void 0;
10082
- if (!this.running) return;
10083
- await this.connect();
10084
- }, this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1);
10085
- }
10086
- };
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);
10817
+ this.downSince = void 0;
10818
+ this.outageWarned = false;
10819
+ this.lastHeartbeatAt = Date.now();
10820
+ this.startHeartbeat(client);
10821
+ logger.debug(`📡 ${logLabel} Listening on channel "${channel}".`);
10822
+ } catch (err) {
10823
+ if (pending) try {
10824
+ await pending.end();
10825
+ } catch {}
10826
+ if (first && !this.options.retryInitialConnect) throw err;
10827
+ const retry = `${logLabel} LISTEN connection could not be opened (${connectFailureReason(err)}); retrying every ${Math.round((this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1) / 1e3)} s.`;
10828
+ if (this.outageWarned) logger.debug(retry);
10829
+ else {
10830
+ this.outageWarned = true;
10831
+ logger.warn(`⚠️ ${retry}`);
10349
10832
  }
10350
- this.state = "open";
10351
- this.pending = [{ text: this.begin }, ...this.opening];
10833
+ this.scheduleReconnect();
10834
+ return;
10352
10835
  }
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);
10836
+ if (!first && this.options.onReconnect) {
10837
+ logger.warn(`⚠️ ${logLabel} LISTEN client reconnected; anything published while it was down was missed.`);
10838
+ try {
10839
+ this.options.onReconnect();
10840
+ } catch (err) {
10841
+ logger.error(`❌ ${logLabel} Error resyncing after a reconnect`, { error: err });
10359
10842
  }
10360
10843
  }
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
10844
  }
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));
10845
+ /**
10846
+ * Give up on the current connection: it is no longer the listener's, so
10847
+ * its late events are ignored and `connected` says so at once; it is
10848
+ * ended without waiting on it; and a replacement is scheduled.
10849
+ */
10850
+ abandon(client) {
10851
+ if (client !== this.client) return;
10852
+ this.client = void 0;
10853
+ this.downSince ??= Date.now();
10854
+ this.stopHeartbeat();
10855
+ client.end().catch(() => {});
10856
+ this.scheduleReconnect();
10375
10857
  }
10376
- async commit() {
10377
- if (this.state === "open" && this.begun) await this.send({ text: "commit" });
10378
- this.pending = [];
10858
+ startHeartbeat(client) {
10859
+ this.stopHeartbeat();
10860
+ const interval = this.options.heartbeatIntervalMs ?? 3e4;
10861
+ if (interval <= 0) return;
10862
+ this.heartbeatTimer = setInterval(() => void this.heartbeat(client), interval);
10863
+ unref(this.heartbeatTimer);
10379
10864
  }
10380
- async rollback() {
10381
- this.pending = [];
10382
- if (this.state === "open" && this.begun) await this.client.query("rollback");
10865
+ stopHeartbeat() {
10866
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
10867
+ this.heartbeatTimer = void 0;
10868
+ this.heartbeatInFlight = false;
10383
10869
  }
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;
10870
+ /**
10871
+ * One round trip on the LISTEN connection. Not answered in time, it is
10872
+ * treated as dead: the client is ended — which, with the query still
10873
+ * outstanding, destroys the socket rather than waiting on a goodbye that
10874
+ * cannot arrive — and replaced.
10875
+ */
10876
+ async heartbeat(client) {
10877
+ if (client !== this.client || this.heartbeatInFlight) return;
10878
+ this.heartbeatInFlight = true;
10879
+ const timeoutMs = this.options.heartbeatTimeoutMs ?? 1e4;
10880
+ let timer;
10437
10881
  try {
10438
- result = await work(tx);
10439
- } catch (error) {
10440
- await transaction.rollback();
10441
- throw error;
10882
+ await Promise.race([client.query("SELECT 1"), new Promise((_resolve, reject) => {
10883
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`no answer in ${timeoutMs}ms`)), timeoutMs);
10884
+ })]);
10885
+ if (client === this.client) this.lastHeartbeatAt = Date.now();
10886
+ } catch (err) {
10887
+ if (client !== this.client) return;
10888
+ logger.warn(`⚠️ ${this.options.logLabel} LISTEN connection failed its heartbeat (${err instanceof Error ? err.message : String(err)}) — treating it as dead and reconnecting.`);
10889
+ this.abandon(client);
10890
+ } finally {
10891
+ if (timer) clearTimeout(timer);
10892
+ if (client === this.client) this.heartbeatInFlight = false;
10442
10893
  }
10443
- await transaction.commit();
10444
- return result;
10445
- } finally {
10446
- client.release();
10447
10894
  }
10448
- }
10895
+ scheduleReconnect() {
10896
+ if (!this.running || this.reconnectTimer) return;
10897
+ this.downSince ??= Date.now();
10898
+ this.reconnectTimer = setTimeout(async () => {
10899
+ this.reconnectTimer = void 0;
10900
+ if (!this.running) return;
10901
+ await this.connect();
10902
+ }, this.options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS$1);
10903
+ }
10904
+ };
10449
10905
  //#endregion
10450
10906
  //#region src/read-routing.ts
10907
+ /**
10908
+ * Which connection an authenticated read runs on: the primary, or a standby
10909
+ * (`DATABASE_READ_URL`).
10910
+ *
10911
+ * A standby serves a read as well as the primary does — the RLS context is
10912
+ * transaction-local (`applyAuthContext`), and `SET LOCAL ROLE` and
10913
+ * `set_config(…, true)` both work on a hot standby — but it serves what it
10914
+ * has replayed, which is a little behind. Two rules keep that from being
10915
+ * visible:
10916
+ *
10917
+ * - **Read-your-writes.** A principal that just wrote reads from the primary
10918
+ * for {@link ReadRoutingOptions.stickyMs} afterwards, so a save followed by
10919
+ * a list shows the save. In-process: another instance does not know about
10920
+ * the write, and the lag guard is what bounds what it can serve.
10921
+ * - **Lag guard.** The standby's replay lag is sampled every
10922
+ * {@link ReadRoutingOptions.sampleIntervalMs}; above
10923
+ * {@link ReadRoutingOptions.maxLagMs}, or with no recent sample, every read
10924
+ * goes to the primary. So does every read for a while after the standby
10925
+ * failed one (see {@link isReplicaFallbackError}), and the failed read is
10926
+ * retried on the primary.
10927
+ *
10928
+ * What never comes here is decided by the caller: writes, reads inside a
10929
+ * write's transaction, the service identity (crons, jobs, `dataAsAdmin`), and
10930
+ * everything on the base driver — auth, realtime, idempotency, the SQL
10931
+ * console, `rebase.sql`.
10932
+ *
10933
+ * @module
10934
+ */
10451
10935
  var DEFAULT_READ_STICKY_MS = 5e3;
10452
10936
  var DEFAULT_READ_MAX_LAG_MS = 1e3;
10453
10937
  var DEFAULT_SAMPLE_INTERVAL_MS = 1e3;
@@ -10553,7 +11037,6 @@ var REPLICA_LAG_SQL = `SELECT CASE
10553
11037
  WHEN pg_last_wal_receive_lsn() IS NOT NULL AND pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
10554
11038
  ELSE EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) * 1000
10555
11039
  END AS lag_ms`;
10556
- /** Run {@link REPLICA_LAG_SQL} on `pool`, in milliseconds. */
10557
11040
  async function readReplicaLagMs(pool) {
10558
11041
  const raw = (await pool.query(REPLICA_LAG_SQL)).rows[0]?.lag_ms;
10559
11042
  if (raw === null || raw === void 0) return null;
@@ -10719,7 +11202,7 @@ async function sampleDatabaseHealth(primary, replica) {
10719
11202
  primary.query("SELECT pg_database_size(current_database())::text AS bytes"),
10720
11203
  replica ? readReplicaLagMs(replica) : Promise.resolve(null)
10721
11204
  ]);
10722
- if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [row.state, Number(row.count)]));
11205
+ if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [String(row.state), Number(row.count)]));
10723
11206
  if (max.status === "fulfilled") {
10724
11207
  const value = Number(max.value.rows[0]?.max);
10725
11208
  if (Number.isFinite(value)) sample.maxConnections = value;
@@ -10983,6 +11466,26 @@ function authContextOf(user) {
10983
11466
  function declaresAnyHook(...tiers) {
10984
11467
  return tiers.some((tier) => tier !== void 0 && Object.values(tier).some((value) => typeof value === "function"));
10985
11468
  }
11469
+ /** The `(collection, field)` pairs {@link warnReplacedAutoValues} has spoken about, once each. */
11470
+ var warnedAutoValues = /* @__PURE__ */ new Set();
11471
+ /**
11472
+ * Say, once per field and outside production, that a value the write sent
11473
+ * for an `autoValue` column was replaced or dropped. By design — the stamp is
11474
+ * the server's, never the caller's — and silent, which is how a migration
11475
+ * script that copies `createdAt` across found out its dates were all today's.
11476
+ */
11477
+ function warnReplacedAutoValues(collection, sent, stamped, status) {
11478
+ if (process.env.NODE_ENV === "production") return;
11479
+ for (const [field, property] of Object.entries(collection.properties ?? {})) {
11480
+ const autoValue = property.autoValue;
11481
+ if (!autoValue || sent[field] === void 0 || sent[field] === null) continue;
11482
+ const replaced = stamped[field] === void 0 || stamped[field] !== sent[field];
11483
+ const key = `${collection.slug}.${field}`;
11484
+ if (!replaced || warnedAutoValues.has(key)) continue;
11485
+ warnedAutoValues.add(key);
11486
+ logger.warn(`[DataDriver] The value sent for '${field}' on "${collection.slug}" was ${stamped[field] === void 0 ? "dropped" : "replaced"}: it is \`autoValue: "${autoValue}"\`, which the server stamps on ${status === "existing" ? "an update" : "a create"} whatever the write sends. Copying rows with their original value takes SQL, or a property without autoValue. (Said once per field, outside production.)`);
11487
+ }
11488
+ }
10986
11489
  /**
10987
11490
  * A bulk or batch update's answer for an id that names no row this caller can
10988
11491
  * see: a 404 naming the id, which the entry's own label then wraps.
@@ -11077,6 +11580,17 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11077
11580
  * wrapping transaction commits. Set by `withAuth` → `withTransaction`.
11078
11581
  */
11079
11582
  _deferNotifications = false;
11583
+ /**
11584
+ * Whether the next write on this driver is the last thing its transaction
11585
+ * does, so its last statement may carry the `COMMIT`
11586
+ * (`commitWithNextStatement`). Set by `withTransaction` for a lone write,
11587
+ * and by a row-by-row batch of one row; honoured only by a write that runs
11588
+ * no hook and records no history, which is what would follow the
11589
+ * statement. Never for the last of several rows: a statement that matches
11590
+ * nothing is a 404 raised after it, and the rows before it would already
11591
+ * have committed.
11592
+ */
11593
+ _commitsWithLastWrite = false;
11080
11594
  _pendingNotifications = [];
11081
11595
  constructor(db, realtimeService, registry, user, poolManager, historyService) {
11082
11596
  this.db = db;
@@ -11739,6 +12253,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11739
12253
  for (const key of createStampKeys(collection.properties)) delete kept[key];
11740
12254
  stamped = kept;
11741
12255
  }
12256
+ warnReplacedAutoValues(collection, values, stamped, status);
11742
12257
  return stamped;
11743
12258
  }
11744
12259
  /**
@@ -11787,10 +12302,31 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11787
12302
  return Boolean(callbacks?.beforeSave || globalCallbacks?.beforeSave || propertyCallbacks?.beforeSave || callbacks?.afterSave || globalCallbacks?.afterSave || propertyCallbacks?.afterSave || callbacks?.afterSaveError || globalCallbacks?.afterSaveError || propertyCallbacks?.afterSaveError || callbacks?.beforeQuery || globalCallbacks?.beforeQuery || collection.history || getTenantConfig(collection) || hasFieldAccessRules(collection) || resolveSoftDelete(collection) || isNestedPath(path));
11788
12303
  }
11789
12304
  async save(props) {
12305
+ const saved = await this.saveRowUnlessKept(props);
12306
+ if (!saved) throw new Error(`Saving a row in "${props.path}" answered no row.`);
12307
+ return saved;
12308
+ }
12309
+ /**
12310
+ * {@link save}, for an upsert under a conflict rule (`saveMany`'s
12311
+ * `ignoreDuplicates` / `conflictWhere`): `undefined` when the rule left
12312
+ * the stored row on the conflict target as it was, and nothing ran for
12313
+ * it — no hook, no history, no event.
12314
+ */
12315
+ async saveRowUnlessKept(props, rule) {
11790
12316
  this.assertWritable(props.collection, props.path);
11791
- return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame));
12317
+ return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame, void 0, rule));
12318
+ }
12319
+ /**
12320
+ * Whether the write about to run may send its transaction's `COMMIT` with
12321
+ * its last statement: this driver was told it is the transaction's last
12322
+ * write (`_commitsWithLastWrite`), it is not a write a hook started, and
12323
+ * nothing runs after its statement — no hook (an `afterRead` included,
12324
+ * which may read through `context.data`) and no history entry.
12325
+ */
12326
+ lastWriteCommits(collection, ...hooks) {
12327
+ return this._commitsWithLastWrite && currentWriteDepth() <= 1 && !declaresAnyHook(...hooks) && !collection?.history;
11792
12328
  }
11793
- async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored) {
12329
+ async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored, rule) {
11794
12330
  const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11795
12331
  if (declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) currentWriteScope()?.noteApplicationCode();
11796
12332
  if (resolvedCollection?.history) this.historyService?.assertRecordable(resolvedCollection.slug);
@@ -11810,6 +12346,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11810
12346
  const readsStoredRow = this.writeReadsStoredRow(resolvedCollection, path, hooks);
11811
12347
  if (upserting && resolvedCollection && readsStoredRow) {
11812
12348
  const stored = await this.findUpsertTarget(path, resolvedCollection, values, id, onConflict);
12349
+ if (stored && rule && (rule.ignoreDuplicates || rule.conflictWhere && !await this.dataService.getPersistService().rowMatches(this.storedRowPath(path), stored.id, rule.conflictWhere))) return;
11813
12350
  if (stored) {
11814
12351
  const reusable = !callbacks?.beforeQuery && !globalCallbacks?.beforeQuery && !hasFieldAccessRules(resolvedCollection) && !isNestedPath(path);
11815
12352
  return this.saveInFrame({
@@ -11906,12 +12443,18 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11906
12443
  const softDeleteField = resolveSoftDelete(resolvedCollection)?.field;
11907
12444
  if (insertOnlyKeys && softDeleteField && updatedValues[softDeleteField] !== void 0 && updatedValues[softDeleteField] !== null) insertOnlyKeys.push(softDeleteField);
11908
12445
  try {
11909
- const storedRow = await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, {
12446
+ const persistOptions = {
11910
12447
  upsert: upserting,
11911
12448
  onConflict,
11912
12449
  insertOnlyKeys,
11913
- unreadRow
11914
- });
12450
+ unreadRow,
12451
+ commitsTransaction: this.lastWriteCommits(resolvedCollection, callbacks, globalCallbacks, propertyCallbacks)
12452
+ };
12453
+ const storedRow = upserting && rule ? await this.dataService.saveUnlessKept(path, updatedValues, writeId, resolvedCollection?.databaseId, {
12454
+ ...persistOptions,
12455
+ ...rule
12456
+ }) : await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, persistOptions);
12457
+ if (!storedRow) return void 0;
11915
12458
  const savedRow = await this.viewOfSavedRow(storedRow, resolvedCollection, path, {
11916
12459
  callbacks,
11917
12460
  globalCallbacks,
@@ -12078,10 +12621,20 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12078
12621
  txDriver.client = this.client;
12079
12622
  return txDriver.buildCallContext();
12080
12623
  }
12081
- async saveMany({ path, rows, collection, upsert, onConflict }) {
12624
+ async saveMany({ path, rows, collection, upsert, onConflict, conflictWhere, ignoreDuplicates }) {
12082
12625
  this.assertWritable(collection, path);
12626
+ if ((conflictWhere || ignoreDuplicates) && upsert !== true) throw ApiError.badRequest("`ignoreDuplicates` and `where` describe what an upsert does to a row already on its conflict target; pass them with `upsert: true`.", "INVALID_CONFLICT_RULE");
12627
+ if (conflictWhere && ignoreDuplicates) throw ApiError.badRequest("`ignoreDuplicates` leaves every stored row as it is, so a `where` choosing which ones to update has nothing to choose. Pass one of the two.", "INVALID_CONFLICT_RULE");
12628
+ const rule = conflictWhere || ignoreDuplicates ? {
12629
+ conflictWhere,
12630
+ ignoreDuplicates
12631
+ } : void 0;
12632
+ const commitsWithLastWrite = this._commitsWithLastWrite;
12083
12633
  if (rows.length > 1 && this.writesRowsTogether(collection, path)) try {
12084
- const together = await this.inBatchTransaction((txDriver) => txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict));
12634
+ const together = await this.inBatchTransaction((txDriver) => {
12635
+ txDriver._commitsWithLastWrite = commitsWithLastWrite;
12636
+ return txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict, rule);
12637
+ });
12085
12638
  if (together) return together;
12086
12639
  } catch (error) {
12087
12640
  logger.debug(`[saveMany] A batch write to "${path}" failed; saving its rows one by one to name the row`, { detail: error instanceof Error ? error.message : String(error) });
@@ -12091,15 +12644,17 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12091
12644
  for (let i = 0; i < rows.length; i++) {
12092
12645
  const values = rows[i];
12093
12646
  const id = values?.id;
12647
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && rows.length === 1;
12094
12648
  try {
12095
- saved.push(await txDriver.save({
12649
+ const row = await txDriver.saveRowUnlessKept({
12096
12650
  path,
12097
12651
  values,
12098
12652
  collection,
12099
12653
  status: "new",
12100
12654
  upsert,
12101
12655
  onConflict
12102
- }));
12656
+ }, rule);
12657
+ if (row) saved.push(row);
12103
12658
  } catch (error) {
12104
12659
  const label = id !== void 0 ? `id ${JSON.stringify(id)}` : "no id";
12105
12660
  throw Object.assign(new Error(`Row ${i} of ${rows.length} (${label}) failed: ${error?.message ?? error}`, { cause: error }), {
@@ -12138,7 +12693,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12138
12693
  * anything is written, for a batch `saveRows` declines. Its realtime events
12139
12694
  * join the transaction's only once every row is answered.
12140
12695
  */
12141
- async saveRowsTogether(path, rows, collection, upsert, onConflict) {
12696
+ async saveRowsTogether(path, rows, collection, upsert, onConflict, rule) {
12142
12697
  const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12143
12698
  const resolved = resolvedCollection;
12144
12699
  if (!resolved) return void 0;
@@ -12160,10 +12715,16 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12160
12715
  });
12161
12716
  const stored = await this.dataService.getPersistService().saveRows(path, prepared, {
12162
12717
  upsert,
12163
- onConflict
12718
+ onConflict,
12719
+ ...rule,
12720
+ commitsTransaction: this.lastWriteCommits(resolved, callbacks, globalCallbacks, propertyCallbacks)
12164
12721
  });
12165
12722
  if (!stored) return void 0;
12166
- return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, hooks);
12723
+ const written = stored.flatMap((row, i) => row ? [{
12724
+ row,
12725
+ values: prepared[i].values
12726
+ }] : []);
12727
+ return this.answerRowsWritten(written.map((entry) => entry.row), written.map((entry) => entry.values), resolved, path, hooks);
12167
12728
  }
12168
12729
  /**
12169
12730
  * {@link updateMany}'s updates written together (`PersistService.updateRows`)
@@ -12235,6 +12796,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12235
12796
  */
12236
12797
  async updateMany({ path, updates, collection }) {
12237
12798
  this.assertWritable(collection, path);
12799
+ const commitsWithLastWrite = this._commitsWithLastWrite;
12238
12800
  if (updates.length > 1 && this.writesRowsTogether(collection, path)) try {
12239
12801
  const together = await this.inBatchTransaction((txDriver) => txDriver.updateRowsTogether(path, updates, collection));
12240
12802
  if (together) return together;
@@ -12245,6 +12807,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12245
12807
  const saved = [];
12246
12808
  for (let i = 0; i < updates.length; i++) {
12247
12809
  const { id, values } = updates[i];
12810
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && updates.length === 1;
12248
12811
  try {
12249
12812
  saved.push(await txDriver.save({
12250
12813
  path,
@@ -12278,9 +12841,11 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12278
12841
  */
12279
12842
  async deleteMany({ path, ids, collection, hard }) {
12280
12843
  this.assertWritable(collection, path);
12844
+ const commitsWithLastWrite = this._commitsWithLastWrite;
12281
12845
  await this.inBatchTransaction(async (txDriver) => {
12282
12846
  for (let i = 0; i < ids.length; i++) {
12283
12847
  const id = ids[i];
12848
+ txDriver._commitsWithLastWrite = commitsWithLastWrite && ids.length === 1;
12284
12849
  try {
12285
12850
  await txDriver.delete({
12286
12851
  row: {
@@ -12301,6 +12866,115 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12301
12866
  });
12302
12867
  }
12303
12868
  /**
12869
+ * Update every row a filter matches. One statement (`PersistService.updateWhere`)
12870
+ * when nothing needs the rows one by one; otherwise the rows the caller
12871
+ * reads through the filter, updated by {@link updateMany} through the full
12872
+ * pipeline, in one transaction. A filter matching nothing answers `[]`.
12873
+ */
12874
+ async updateWhere({ path, filter, logical, values, collection }) {
12875
+ this.assertWritable(collection, path);
12876
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12877
+ const resolved = this.assertFilteredWrite(resolvedCollection, path, filter, logical);
12878
+ const written = values;
12879
+ assertUpdateDoesNotSoftDelete(resolved, written, path);
12880
+ const keys = getPrimaryKeys(resolved, this.registry).map((key) => key.fieldName).filter((field) => written[field] !== void 0);
12881
+ if (keys.length > 0) throw ApiError.badRequest(`'${keys[0]}' is the key of '${resolved.slug}', and an update cannot change it — a filtered one least of all, which would give every row it matches the same key.`, "KEY_IMMUTABLE", {
12882
+ collection: resolved.slug,
12883
+ violations: keys.map((field) => ({
12884
+ field,
12885
+ code: "key_immutable"
12886
+ }))
12887
+ });
12888
+ const hooks = {
12889
+ callbacks,
12890
+ globalCallbacks,
12891
+ propertyCallbacks
12892
+ };
12893
+ if (!this.writeReadsStoredRow(resolved, path, hooks)) {
12894
+ const stamped = this.stampAutoValues(resolved, values, "existing", path);
12895
+ const stored = await this.dataService.getPersistService().updateWhere(path, filter, logical, stamped, { commitsTransaction: this.lastWriteCommits(resolved, callbacks, globalCallbacks, propertyCallbacks) });
12896
+ if (stored) return this.answerRowsWritten(stored, stored.map(() => stamped), resolved, path, hooks);
12897
+ }
12898
+ const ids = await this.addressesMatching(resolved, path, filter, logical);
12899
+ if (ids.length === 0) return [];
12900
+ return this.updateMany({
12901
+ path,
12902
+ updates: ids.map((id) => ({
12903
+ id,
12904
+ values
12905
+ })),
12906
+ collection
12907
+ });
12908
+ }
12909
+ /**
12910
+ * Delete every row a filter matches, under the rules of {@link updateWhere}:
12911
+ * one `DELETE` when nothing needs the rows one by one, else
12912
+ * {@link deleteMany} over the rows the caller reads through the filter.
12913
+ * Answers how many rows went.
12914
+ */
12915
+ async deleteWhere({ path, filter, logical, collection, hard }) {
12916
+ this.assertWritable(collection, path);
12917
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
12918
+ const resolved = this.assertFilteredWrite(resolvedCollection, path, filter, logical);
12919
+ if (!(!hard && resolveSoftDelete(resolved) !== void 0) && !resolved.history && !declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) {
12920
+ const deleted = await this.dataService.getPersistService().deleteWhere(path, filter, logical, { commitsTransaction: this.lastWriteCommits(resolved) });
12921
+ const notifications = deleted.map((row) => ({
12922
+ path,
12923
+ id: deriveRowAddress(row, resolved, this.registry),
12924
+ row: null,
12925
+ databaseId: resolved.databaseId
12926
+ }));
12927
+ if (this._deferNotifications) this._pendingNotifications.push(...notifications);
12928
+ else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, null, notification.databaseId);
12929
+ return deleted.length;
12930
+ }
12931
+ const ids = await this.addressesMatching(resolved, path, filter, logical);
12932
+ if (ids.length === 0) return 0;
12933
+ await this.deleteMany({
12934
+ path,
12935
+ ids,
12936
+ collection,
12937
+ hard
12938
+ });
12939
+ return ids.length;
12940
+ }
12941
+ /**
12942
+ * A row's address in the spelling a read derives it in — `010` is row
12943
+ * `10` — for an event about a row this write did not read.
12944
+ */
12945
+ canonicalAddress(collection, id) {
12946
+ if (!collection) return String(id);
12947
+ try {
12948
+ return deriveRowAddress(parseIdValues$1(id, getPrimaryKeys(collection, this.registry)), collection, this.registry) || String(id);
12949
+ } catch {
12950
+ return String(id);
12951
+ }
12952
+ }
12953
+ /**
12954
+ * The collection a filtered write addresses, refused when it cannot be
12955
+ * one: a path through a relation (a filter there would reach rows the
12956
+ * path does not), or a filter with no condition (every row).
12957
+ */
12958
+ assertFilteredWrite(collection, path, filter, logical) {
12959
+ if (!collection || isNestedPath(path)) throw ApiError.badRequest(`A filtered write addresses a collection, and "${path}" is ${collection ? "a path through a relation" : "not one"}. Write to the related collection with a filter on its link instead.`, "INVALID_FILTERED_WRITE");
12960
+ if ((!filter || Object.keys(filter).length === 0) && !logical) throw filterRequired(path);
12961
+ return collection;
12962
+ }
12963
+ /**
12964
+ * The addresses of the rows a filter matches, read as this caller reads
12965
+ * them — their policies, their `beforeQuery`, the trash hidden — for a
12966
+ * filtered write that runs row by row.
12967
+ */
12968
+ async addressesMatching(collection, path, filter, logical) {
12969
+ const primaryKeys = getPrimaryKeys(collection, this.registry);
12970
+ return (await this.dataService.getFetchService().fetchCollectionForRest(path, {
12971
+ filter,
12972
+ logical,
12973
+ fields: primaryKeys.map((key) => key.fieldName),
12974
+ databaseId: collection.databaseId
12975
+ })).map((row) => deriveRowAddress(row, collection, this.registry, primaryKeys));
12976
+ }
12977
+ /**
12304
12978
  * A mixed list of writes across collections, as one unit of work.
12305
12979
  *
12306
12980
  * Same transaction, same tx-bound sub-driver and same per-entry error
@@ -12393,6 +13067,19 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12393
13067
  const hop = isNestedPath(targetPath) ? resolveNestedPath(targetPath, this.registry) : void 0;
12394
13068
  const unlinking = hop !== void 0 && isJunctionBackedRelation(hop.relation);
12395
13069
  if (resolvedCollection?.history && !unlinking) this.historyService?.assertRecordable(resolvedCollection.slug);
13070
+ const softDeleting = !hard && !unlinking && resolveSoftDelete(resolvedCollection) !== void 0;
13071
+ if (!precondition && !hop && !softDeleting && !resolvedCollection?.history && !declaresAnyHook(callbacks, globalCallbacks, propertyCallbacks)) {
13072
+ await this.dataService.delete(targetPath, row.id, resolvedCollection?.databaseId, { commitsTransaction: this.lastWriteCommits(resolvedCollection) });
13073
+ const notification = {
13074
+ path: targetPath,
13075
+ id: this.canonicalAddress(resolvedCollection, row.id),
13076
+ row: null,
13077
+ databaseId: resolvedCollection?.databaseId
13078
+ };
13079
+ if (this._deferNotifications) this._pendingNotifications.push(notification);
13080
+ else await this.realtimeService.notifyUpdate(notification.path, notification.id, null, notification.databaseId);
13081
+ return;
13082
+ }
12396
13083
  if (precondition?.lock) await this.dataService.getPersistService().lockRow(targetPath, row.id);
12397
13084
  const stored = await this.dataService.fetchOneForRest(targetPath, row.id, void 0, resolvedCollection?.databaseId, { withDeleted: hard ? true : void 0 });
12398
13085
  if (precondition) await precondition.check(await this.asRestServes(stored, targetPath));
@@ -12613,20 +13300,15 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12613
13300
  return sampleDatabaseHealth(pool, replica instanceof Pool ? replica : void 0);
12614
13301
  }
12615
13302
  /**
12616
- * Build one statement, binding `$n` placeholders as real parameters.
13303
+ * Build one statement, binding `$n` placeholders as real parameters —
13304
+ * each once, however often it appears (`utils/positional-params.ts`).
12617
13305
  *
12618
13306
  * Shared by the role-switched path (inside a transaction) and the
12619
13307
  * unswitched one. They held byte-identical copies of this loop, which is
12620
13308
  * exactly the shape where a fix lands in one copy and not the other.
12621
13309
  */
12622
13310
  buildStatement(sqlText, params) {
12623
- if (!params || params.length === 0) return sql.raw(sqlText);
12624
- const parts = sqlText.split(/\$(\d+)/);
12625
- const chunks = [];
12626
- for (let i = 0; i < parts.length; i++) if (i % 2 === 0) {
12627
- if (parts[i].length > 0) chunks.push(sql.raw(parts[i]));
12628
- } else chunks.push(sql.param(params[Number(parts[i]) - 1]));
12629
- return sql.join(chunks, sql.raw(""));
13311
+ return positionalStatement(sqlText, params);
12630
13312
  }
12631
13313
  async executeSql(sqlText, options) {
12632
13314
  if (options?.isolateSession) return this.onIsolatedSession(await this.getSessionTargetDb(options.database), options.role, (db, role) => this.executeSqlOn(db, sqlText, {
@@ -13040,6 +13722,7 @@ var AuthenticatedPostgresBackendDriver = class {
13040
13722
  async sql(query, options) {
13041
13723
  assertCallerSql(query);
13042
13724
  return this.withTransaction(async (delegate) => {
13725
+ if (options?.write) commitWithNextStatement();
13043
13726
  const result = await delegate.dataService.executeSqlResult(query, options?.params);
13044
13727
  return withoutUnreadableColumns(rowsOfResult(result), fieldsOfResult(result), { roles: this.user?.roles ?? [] }, this.delegate.registry?.getCollections() ?? [], this.delegate.columnOrigins, (text, params) => delegate.dataService.executeSql(text, params));
13045
13728
  }, { accessMode: options?.write ? "read write" : "read only" });
@@ -13125,6 +13808,7 @@ var AuthenticatedPostgresBackendDriver = class {
13125
13808
  });
13126
13809
  const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
13127
13810
  txDelegate.dataService = txEntityService;
13811
+ txDelegate._commitsWithLastWrite = options?.loneWrite === true;
13128
13812
  txDelegate._deferNotifications = true;
13129
13813
  txDelegate._pendingNotifications = pendingNotifications;
13130
13814
  txDelegate.client = this.delegate.client;
@@ -13141,16 +13825,20 @@ var AuthenticatedPostgresBackendDriver = class {
13141
13825
  return out;
13142
13826
  };
13143
13827
  const auth = authContextOf(this.user);
13828
+ const config = options?.accessMode || options?.isolationLevel ? {
13829
+ ...options.accessMode ? { accessMode: options.accessMode } : {},
13830
+ ...options.isolationLevel ? { isolationLevel: options.isolationLevel } : {}
13831
+ } : void 0;
13144
13832
  if (pipelined) {
13145
13833
  const opening = authContextStatement(auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
13146
- return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], options, inTransaction);
13834
+ return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], config, inTransaction);
13147
13835
  }
13148
13836
  return db.transaction(async (tx) => {
13149
13837
  const transactionSettings = transactionSettingsStatements(pooledSettings);
13150
13838
  if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
13151
13839
  await applyAuthContext(tx, auth, this.delegate.rlsRequest ?? this.delegate.rlsUserRole);
13152
13840
  return inTransaction(tx);
13153
- }, options);
13841
+ }, config);
13154
13842
  }).finally(() => writeScope?.close())).catch(async (error) => {
13155
13843
  await writeScope?.settled();
13156
13844
  throw error;
@@ -13185,7 +13873,7 @@ var AuthenticatedPostgresBackendDriver = class {
13185
13873
  return this.delegate.listenOne(props, authContextOf(this.user));
13186
13874
  }
13187
13875
  async save(props) {
13188
- return this.withTransaction((delegate) => delegate.save(props));
13876
+ return this.withTransaction((delegate) => delegate.save(props), { loneWrite: true });
13189
13877
  }
13190
13878
  /**
13191
13879
  * One transaction for the whole batch, rather than one per row.
@@ -13197,7 +13885,7 @@ var AuthenticatedPostgresBackendDriver = class {
13197
13885
  * `withTransaction`, so a batch does not flood subscribers mid-flight.
13198
13886
  */
13199
13887
  async saveMany(props) {
13200
- return this.withTransaction((delegate) => delegate.saveMany(props));
13888
+ return this.withTransaction((delegate) => delegate.saveMany(props), { loneWrite: true });
13201
13889
  }
13202
13890
  /**
13203
13891
  * Present for the same reason `saveMany` is, and absent until now.
@@ -13210,10 +13898,16 @@ var AuthenticatedPostgresBackendDriver = class {
13210
13898
  * The methods existed one class down and nothing forwarded to them.
13211
13899
  */
13212
13900
  async updateMany(props) {
13213
- return this.withTransaction((delegate) => delegate.updateMany(props));
13901
+ return this.withTransaction((delegate) => delegate.updateMany(props), { loneWrite: true });
13214
13902
  }
13215
13903
  async deleteMany(props) {
13216
- return this.withTransaction((delegate) => delegate.deleteMany(props));
13904
+ return this.withTransaction((delegate) => delegate.deleteMany(props), { loneWrite: true });
13905
+ }
13906
+ async updateWhere(props) {
13907
+ return this.withTransaction((delegate) => delegate.updateWhere(props), { loneWrite: true });
13908
+ }
13909
+ async deleteWhere(props) {
13910
+ return this.withTransaction((delegate) => delegate.deleteWhere(props), { loneWrite: true });
13217
13911
  }
13218
13912
  /**
13219
13913
  * One transaction, one RLS context, every collection the batch touches.
@@ -13227,7 +13921,7 @@ var AuthenticatedPostgresBackendDriver = class {
13227
13921
  return this.withTransaction((delegate) => delegate.batchWrite(props));
13228
13922
  }
13229
13923
  async delete(props) {
13230
- return this.withTransaction((delegate) => delegate.delete(props));
13924
+ return this.withTransaction((delegate) => delegate.delete(props), { loneWrite: true });
13231
13925
  }
13232
13926
  async deleteAll(path) {
13233
13927
  return this.withTransaction((delegate) => delegate.deleteAll(path));
@@ -15531,7 +16225,7 @@ function terminateIfBacklogged(ws, clientId) {
15531
16225
  const now = Date.now();
15532
16226
  if (now - lastBudgetCheckAt >= PROCESS_BUDGET_CHECK_MS || now < lastBudgetCheckAt) {
15533
16227
  lastBudgetCheckAt = now;
15534
- if (budgetedClients.size > 0 && enforceProcessSendBudget().includes(ws)) return true;
16228
+ if (budgetedClients.size > 0 && enforceProcessSendBudget().some((terminated) => terminated === ws)) return true;
15535
16229
  }
15536
16230
  return false;
15537
16231
  }
@@ -16315,6 +17009,22 @@ function coerceFrame(value) {
16315
17009
  //#endregion
16316
17010
  //#region src/services/channel-bus/index.ts
16317
17011
  /**
17012
+ * Resolution of the channel bus from config, environment, or a supplied instance.
17013
+ *
17014
+ * Opt-in, like every other cross-cutting realtime switch here: with nothing
17015
+ * configured a deployment gets the memory bus and behaves exactly as it did
17016
+ * before this existed. Unlike `REALTIME_CDC=auto`, there is no "try it and see"
17017
+ * default — a bus changes where messages go, and quietly turning on a Postgres
17018
+ * NOTIFY per broadcast because a direct URL happened to be set is not a
17019
+ * decision to make on the user's behalf.
17020
+ *
17021
+ * Two transports ship, and neither adds a service to a deployment. A third is
17022
+ * not a code change here: `realtime.bus` also accepts an already-constructed
17023
+ * {@link ChannelBus}, so a transport published as its own package plugs in
17024
+ * without this file learning about it. See `@rebasepro/types` →
17025
+ * `types/channel_bus.ts` for the contract such a package implements.
17026
+ */
17027
+ /**
16318
17028
  * Merge `REALTIME_CHANNEL_BUS` into the configured bus.
16319
17029
  *
16320
17030
  * The environment wins over a *named* built-in, so the transport can be changed
@@ -19551,7 +20261,7 @@ var PostgresCollectionRegistry = class extends CollectionRegistry {
19551
20261
  * A concrete table does not satisfy it: its columns have specific types and it
19552
20262
  * carries methods and symbols besides, so `Record<string, AnyPgColumn>` is not
19553
20263
  * a supertype and a direct `as` is refused. Written out, that refusal was
19554
- * answered six times with `as unknown as RebasePgTable`, which also discarded
20264
+ * answered six times with a double cast to `RebasePgTable`, which also discarded
19555
20265
  * the check that the thing being converted is a table at all — the parameter
19556
20266
  * below is what restores it.
19557
20267
  */
@@ -20652,7 +21362,7 @@ var RefreshTokenService = class RefreshTokenService {
20652
21362
  * `selection()` is assembled at runtime from the columns this table actually
20653
21363
  * has, so drizzle types the row as an open record and nothing static
20654
21364
  * connects it to the interface. Both call sites used to assert the
20655
- * connection — `row as unknown as RefreshTokenInfo` — which claims every
21365
+ * connection — a double cast of `row` to `RefreshTokenInfo` — which claims every
20656
21366
  * optional field is present and correctly typed on a row where, by
20657
21367
  * construction, some of them were never selected.
20658
21368
  *
@@ -22117,15 +22827,15 @@ function patchPgArrayNullSafety(tables) {
22117
22827
  function patchPgNumericToNumber(tables) {
22118
22828
  let patchedCount = 0;
22119
22829
  const patch = (column) => {
22120
- const marked = column;
22121
- if (marked.__rebaseNumericPatched) return;
22122
- marked.__rebaseNumericPatched = true;
22123
- column.mapFromDriverValue = function(value) {
22830
+ if (Object.hasOwn(column, "__rebaseNumericPatched")) return;
22831
+ Object.defineProperty(column, "__rebaseNumericPatched", { value: true });
22832
+ const toNumber = (value) => {
22124
22833
  if (value === null || value === void 0) return value;
22125
22834
  if (typeof value === "number") return value;
22126
22835
  const parsed = Number(value);
22127
22836
  return Number.isNaN(parsed) ? value : parsed;
22128
22837
  };
22838
+ column.mapFromDriverValue = toNumber;
22129
22839
  patchedCount++;
22130
22840
  };
22131
22841
  for (const tableOrRelation of Object.values(tables)) {
@@ -22252,6 +22962,23 @@ function resolveDriftCheckName(col, registeredTableNames) {
22252
22962
  return (isRelationalCollectionConfig(col) ? col.table : void 0) ?? registeredTableNames.find((k) => k === col.slug) ?? col.slug;
22253
22963
  }
22254
22964
  /**
22965
+ * The relations the boot's drift check looks for a collection's table among.
22966
+ *
22967
+ * Deliberately unfiltered by schema: a table that is missing from where the
22968
+ * collection says it lives is very often sitting in another schema entirely
22969
+ * (see the misplaced-table report), and knowing *which* is the whole answer.
22970
+ *
22971
+ * Views as well as tables: a view collection serves a view of its own name (a
22972
+ * materialized one, a plain view over its stored rows), and reading only base
22973
+ * tables reported every one of them as missing on every boot.
22974
+ */
22975
+ var DRIFT_CHECK_RELATIONS_SQL = `
22976
+ SELECT table_name, table_schema
22977
+ FROM information_schema.tables
22978
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
22979
+ AND table_type IN ('BASE TABLE', 'VIEW')
22980
+ `;
22981
+ /**
22255
22982
  * Why the tables this backend serves are not in the database — the part of the
22256
22983
  * drift warning that has to be true rather than merely plausible.
22257
22984
  *
@@ -22388,6 +23115,7 @@ var SCHEMA_META_SCHEMA = "rebase";
22388
23115
  function describeEnsureFailure(failure) {
22389
23116
  switch (failure.kind) {
22390
23117
  case "comment-column": return `🔍 [schema] Could not record the search fingerprint on "${failure.target}" — search works, but a later change to the \`search\` block will not be detected: ${failure.error}`;
23118
+ case "rename-index": return `🐢 [schema] Could not adopt an existing index on "${failure.target}" — the declared index is built beside it instead, and writes maintain both until one is dropped: ${failure.error}`;
22391
23119
  case "create-index": return `🐢 [schema] Could not create an index on "${failure.target}" — the collection serves and returns the same rows, but queries that would have used this index will scan instead. Boot is not failed over an index: ${failure.error}`;
22392
23120
  default: return `🔗 [schema] Could not add foreign key "${failure.target}" — the column exists and the collection still serves, but rows are not policed by this constraint: ${failure.error}`;
22393
23121
  }
@@ -22666,7 +23394,7 @@ async function openPostgresDriver(pgConfig, config) {
22666
23394
  let readRouter;
22667
23395
  let readPool;
22668
23396
  if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
22669
- const { createReadReplicaConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
23397
+ const { createReadReplicaConnection } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
22670
23398
  const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
22671
23399
  ...pgConfig.poolConfig,
22672
23400
  pooled
@@ -22682,7 +23410,7 @@ async function openPostgresDriver(pgConfig, config) {
22682
23410
  let sessionDb;
22683
23411
  let sessionPool;
22684
23412
  if (pooled && directUrl) {
22685
- const { createDirectDatabaseConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
23413
+ const { createDirectDatabaseConnection } = await import("./connection-C1zXTPJq.js").then((n) => n.r);
22686
23414
  const session = createDirectDatabaseConnection(directUrl, void 0, {
22687
23415
  max: 3,
22688
23416
  idleTimeoutMillis: 1e4
@@ -22708,12 +23436,16 @@ async function openPostgresDriver(pgConfig, config) {
22708
23436
  realtimeService.setDataDriver(driver);
22709
23437
  let rlsEnforcement;
22710
23438
  let exposedInternalTables;
23439
+ /** Set where the admin switch is settled; see {@link PostgresDriverInternals.adminPoliciesLive}. */
23440
+ let adminPoliciesLive = false;
23441
+ /** Set where the admin switch is settled; see {@link PostgresDriverInternals.adminRequestPoliciesLive}. */
23442
+ let adminRequestPoliciesLive = false;
22711
23443
  const rls = resolveRlsSettings({
22712
23444
  ...declaredDatabaseRls(sourceKey),
22713
23445
  ...pgConfig.rls
22714
23446
  });
22715
23447
  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.`);
23448
+ if (rls.policyTarget !== policyShape.policyTarget || rls.defaultPolicies !== policyShape.defaultPolicies || rls.adminPolicies !== policyShape.adminPolicies) throw new Error(`rls.policyTarget, rls.adminPolicies and rls.defaultPolicies shape the policy SQL that \`rebase db generate\` writes, and the CLI cannot see the driver's code. Declare them on the database instead — database({ rls: { policyTarget: "${rls.policyTarget}", adminPolicies: "${rls.adminPolicies}", defaultPolicies: ${rls.defaultPolicies} } }) — or set REBASE_RLS_POLICY_TARGET / REBASE_RLS_ADMIN_POLICIES / REBASE_RLS_DEFAULT_POLICIES.`);
22717
23449
  /** The tables this driver serves — collections, junctions — for `grants: "managed"`. */
22718
23450
  const managedTables = () => registry.getTableNames().flatMap((name) => {
22719
23451
  const table = registry.getTable(name);
@@ -22779,14 +23511,18 @@ async function openPostgresDriver(pgConfig, config) {
22779
23511
  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)}`);
22780
23512
  }
22781
23513
  if (switched) {
23514
+ const settled = await settleAdminSwitch(runSql, managedSchemas, rls, { provision });
23515
+ const request = settled.request;
23516
+ adminPoliciesLive = settled.adminPoliciesLive;
23517
+ adminRequestPoliciesLive = settled.adminRequestPoliciesLive;
22782
23518
  driver.rlsUserRole = rls.defaultRole;
22783
23519
  realtimeService.rlsUserRole = rls.defaultRole;
22784
- driver.rlsRequest = rls.request;
22785
- realtimeService.rlsRequest = rls.request;
23520
+ driver.rlsRequest = request;
23521
+ realtimeService.rlsRequest = request;
22786
23522
  const why = posture.superuser ? "superuser" : posture.bypassRLS ? "BYPASSRLS" : posture.ownsTables ? "table owner" : "may create (and would then own) tables in the schemas it serves";
22787
23523
  rlsEnforcement = `🔐 RLS enforcement active: authenticated requests run as ${roleList} (connection "${posture.role}" bypasses RLS: ${why})` + (rls.nonDefaults.length > 0 ? `; rls: ${rls.nonDefaults.join(", ")}` : "");
22788
23524
  for (const note of rlsHandoverNotes(rls)) logger.info(`🔐 [rls] ${note}`);
22789
- for (const role of rls.roles) {
23525
+ for (const role of [...rls.roles, ...rls.adminRoles.values()]) {
22790
23526
  if (rls.sharedRole === "ignore") break;
22791
23527
  const others = await findOtherRoleMembers(runSql, role);
22792
23528
  if (others.length === 0) continue;
@@ -22809,7 +23545,10 @@ async function openPostgresDriver(pgConfig, config) {
22809
23545
  if (isScaffoldedLocalDatabase(pgConfig.connectionString)) logger.debug(`🔐 ${message}`);
22810
23546
  else logger.warn(`⚠️ ${message}`);
22811
23547
  }
22812
- } else rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
23548
+ } else {
23549
+ rlsEnforcement = `🔐 RLS enforcement: connection role "${posture.role}" is subject to RLS natively; no role switch needed.`;
23550
+ if (rls.adminPolicies === "adminRole") await ensureConnectionInheritsAdminRole(runSql, { provision });
23551
+ }
22813
23552
  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
23553
  await validatePolicyPgRoles(runSql, collectionsOnThisSource(), driver.rlsUserRole ? rls.roles : posture.role);
22815
23554
  warnOnAnonymousGrants(collectionsOnThisSource());
@@ -22933,12 +23672,7 @@ async function openPostgresDriver(pgConfig, config) {
22933
23672
  try {
22934
23673
  const registeredCollections = collectionsOnThisSource();
22935
23674
  if (registeredCollections.length > 0) {
22936
- const result = await schemaAwareDb.execute(sql.raw(`
22937
- SELECT table_name, table_schema
22938
- FROM information_schema.tables
22939
- WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
22940
- AND table_type = 'BASE TABLE'
22941
- `));
23675
+ const result = await schemaAwareDb.execute(sql.raw(DRIFT_CHECK_RELATIONS_SQL));
22942
23676
  const tablesByName = /* @__PURE__ */ new Map();
22943
23677
  for (const row of result.rows) {
22944
23678
  const schemas = tablesByName.get(row.table_name) ?? [];
@@ -23000,6 +23734,8 @@ async function openPostgresDriver(pgConfig, config) {
23000
23734
  poolManager,
23001
23735
  provisioned: provision,
23002
23736
  rls,
23737
+ adminPoliciesLive,
23738
+ adminRequestPoliciesLive,
23003
23739
  managedTables,
23004
23740
  rlsEnforcement,
23005
23741
  exposedInternalTables,
@@ -23073,7 +23809,7 @@ function createPostgresBootstrapper(pgConfig) {
23073
23809
  const openIndexBuildSession = (driverResult) => async () => {
23074
23810
  const db = requireProvisioningDb(driverResult);
23075
23811
  const pool = "$client" in db ? db.$client : void 0;
23076
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
23812
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BCU9RoHK.js").then((n) => n.r);
23077
23813
  const config = effectiveConfig();
23078
23814
  if (isPooledPool(pool) || config.pooled) {
23079
23815
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -23104,7 +23840,7 @@ function createPostgresBootstrapper(pgConfig) {
23104
23840
  */
23105
23841
  const provisionRlsRuntime = async (driverResult) => {
23106
23842
  const db = requireProvisioningDb(driverResult);
23107
- const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent, ensureRequestRoleFunction } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
23843
+ const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent, ensureRequestRoleFunction } = await import("./rls-bootstrap-sql-kPX4-MB1.js").then((n) => n.l);
23108
23844
  const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
23109
23845
  if (declaredRlsPolicyShape().policyTarget === "requestRole") await ensureRequestRoleFunction(run);
23110
23846
  if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
@@ -23218,11 +23954,11 @@ function createPostgresBootstrapper(pgConfig) {
23218
23954
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
23219
23955
  }) };
23220
23956
  }
23221
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
23957
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CqGIwSYx.js").then((n) => n.i);
23222
23958
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
23223
23959
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
23224
23960
  if (historyIndexes.length > 0) {
23225
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
23961
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BCU9RoHK.js").then((n) => n.r);
23226
23962
  const indexOptions = {
23227
23963
  log: (message) => logger.info(`[history] ${message}`),
23228
23964
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -23278,9 +24014,9 @@ function createPostgresBootstrapper(pgConfig) {
23278
24014
  * proved it can bootstrap with.
23279
24015
  */
23280
24016
  async ensureCollectionSchema(collections, driverResult, log) {
23281
- const { ensureCollectionTables } = await import("./ensure-collection-tables-DR_WcxLA.js").then((n) => n.n);
24017
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-DCJINkT_.js").then((n) => n.n);
23282
24018
  const queryable = provisioningQueryable(driverResult);
23283
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-BSNpEUOS.js").then((n) => n.i);
24019
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CqGIwSYx.js").then((n) => n.i);
23284
24020
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
23285
24021
  const plan = await ensureCollectionTables(queryable, collections, log, {
23286
24022
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -23292,7 +24028,7 @@ function createPostgresBootstrapper(pgConfig) {
23292
24028
  pendingIndexBuild?.cancel();
23293
24029
  pendingIndexBuild = void 0;
23294
24030
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
23295
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-B8feKnUj.js").then((n) => n.r);
24031
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BCU9RoHK.js").then((n) => n.r);
23296
24032
  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.`);
23297
24033
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
23298
24034
  log: (message) => logger.info(`[schema] ${message}`),
@@ -23332,11 +24068,15 @@ function createPostgresBootstrapper(pgConfig) {
23332
24068
  await provisionRlsRuntime(driverResult);
23333
24069
  },
23334
24070
  async ensureCollectionPolicies(collections, driverResult, log) {
23335
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-85HiG-k1.js");
24071
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-Bo-_fDAy.js");
23336
24072
  const queryable = provisioningQueryable(driverResult);
23337
24073
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
23338
24074
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
23339
- const outcome = await ensureCollectionPolicies(queryable, collections, log);
24075
+ const internals = driverResult?.internals;
24076
+ const outcome = await ensureCollectionPolicies(queryable, collections, log, {
24077
+ adminRoleAvailable: internals?.adminPoliciesLive === true,
24078
+ adminRequestRoleAvailable: internals?.adminRequestPoliciesLive === true
24079
+ });
23340
24080
  withheldTables.clear();
23341
24081
  for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) {
23342
24082
  const dot = u.table.indexOf(".");
@@ -23357,7 +24097,7 @@ function createPostgresBootstrapper(pgConfig) {
23357
24097
  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
24098
  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.");
23359
24099
  try {
23360
- const { dropLegacyAuthSchema } = await import("./migrate-baseline-BfHmq3vN.js").then((n) => n.D);
24100
+ const { dropLegacyAuthSchema } = await import("./rls-bootstrap-sql-kPX4-MB1.js").then((n) => n.l);
23361
24101
  await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
23362
24102
  info: (m) => logger.info(m),
23363
24103
  warn: (m) => logger.warn(m)
@@ -23452,17 +24192,18 @@ function createPostgresBootstrapper(pgConfig) {
23452
24192
  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)}`);
23453
24193
  }
23454
24194
  await withholdAgain(runSql);
24195
+ const { request } = await settleAdminSwitch(runSql, managedSchemas, rls, { provision: true });
23455
24196
  driver.rlsUserRole = rls.defaultRole;
23456
24197
  realtimeService.rlsUserRole = rls.defaultRole;
23457
- driver.rlsRequest = rls.request;
23458
- realtimeService.rlsRequest = rls.request;
24198
+ driver.rlsRequest = request;
24199
+ realtimeService.rlsRequest = request;
23459
24200
  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(", ")}.`);
23460
24201
  },
23461
24202
  getAdmin(driverResult) {
23462
24203
  return driverResult.internals.driver.admin;
23463
24204
  },
23464
24205
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
23465
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-B33YjKhs.js").then((n) => n.c);
24206
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-B7ex6AQM.js").then((n) => n.c);
23466
24207
  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.`);
23467
24208
  const realtimeConfig = effectiveConfig().realtime;
23468
24209
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -23582,12 +24323,17 @@ async function openRebase(options) {
23582
24323
  data: buildSdkData(scoped, { resolveAccessor })
23583
24324
  };
23584
24325
  };
23585
- const dataAsAdmin = (await scopedTo(SERVICE_IDENTITY)).data;
24326
+ const service = await scopedTo(SERVICE_IDENTITY);
24327
+ const dataAsAdmin = service.data;
23586
24328
  const admin = driver.admin;
23587
24329
  let closed = false;
23588
24330
  return {
23589
24331
  dataAsAdmin,
23590
24332
  collections,
24333
+ async sqlAsAdmin(query, sqlOptions) {
24334
+ if (!service.scoped.sql) throw new Error("This driver cannot run SQL under row-level security.");
24335
+ return service.scoped.sql(query, sqlOptions);
24336
+ },
23591
24337
  async sql(query, sqlOptions) {
23592
24338
  if (!isSQLAdmin(admin)) throw new Error("This driver cannot run raw SQL.");
23593
24339
  warnOnTableDdl(query, (message) => logger.warn(message));
@@ -23619,4 +24365,4 @@ async function openRebase(options) {
23619
24365
  //#endregion
23620
24366
  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 };
23621
24367
 
23622
- //# sourceMappingURL=open-rebase-CiO_sjMT.js.map
24368
+ //# sourceMappingURL=open-rebase-40paQfVW.js.map