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

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 (94) hide show
  1. package/dist/{BranchService-BPssiD8_.js → BranchService-JiYJ_n9E.js} +3 -3
  2. package/dist/{BranchService-BPssiD8_.js.map → BranchService-JiYJ_n9E.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +78 -0
  4. package/dist/{backup-cli-C1wcj-rc.js → backup-cli-D_aKXPyX.js} +3 -3
  5. package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-D_aKXPyX.js.map} +1 -1
  6. package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-D4W9o9xE.js} +2 -2
  7. package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-D4W9o9xE.js.map} +1 -1
  8. package/dist/{cli-console-CJLtH58M.js → cli-console-DPdZCWTi.js} +6 -6
  9. package/dist/{cli-console-CJLtH58M.js.map → cli-console-DPdZCWTi.js.map} +1 -1
  10. package/dist/{cli-errors-DYets7cp.js → cli-errors-D8s4z_3g.js} +26 -6
  11. package/dist/cli-errors-D8s4z_3g.js.map +1 -0
  12. package/dist/cli-helpers.d.ts +10 -0
  13. package/dist/cli.js +41 -35
  14. package/dist/cli.js.map +1 -1
  15. package/dist/{connection-CcYqncW5.js → connection-COuS5Fm-.js} +15 -2
  16. package/dist/connection-COuS5Fm-.js.map +1 -0
  17. package/dist/connection.d.ts +6 -0
  18. package/dist/{databasePoolManager-XmhMczz0.js → databasePoolManager-7hXVurmG.js} +2 -2
  19. package/dist/{databasePoolManager-XmhMczz0.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
  20. package/dist/{deferred-index-build-BwH6k1Og.js → deferred-index-build-F2GWu009.js} +5 -5
  21. package/dist/{deferred-index-build-BwH6k1Og.js.map → deferred-index-build-F2GWu009.js.map} +1 -1
  22. package/dist/{doctor-TJApVglQ.js → doctor-_g2tHRtG.js} +20 -6
  23. package/dist/doctor-_g2tHRtG.js.map +1 -0
  24. package/dist/{ensure-collection-policies-f0LIwiwp.js → ensure-collection-policies-DUpWJb5D.js} +8 -8
  25. package/dist/{ensure-collection-policies-f0LIwiwp.js.map → ensure-collection-policies-DUpWJb5D.js.map} +1 -1
  26. package/dist/{ensure-collection-tables-DvaCEy6X.js → ensure-collection-tables-BK--gDo6.js} +13 -7
  27. package/dist/ensure-collection-tables-BK--gDo6.js.map +1 -0
  28. package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Bx1DYarz.js} +4 -4
  29. package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Bx1DYarz.js.map} +1 -1
  30. package/dist/{enum-labels-kept-DAbJ_IIl.js → enum-labels-kept-DyFE4Gaq.js} +3 -3
  31. package/dist/{enum-labels-kept-DAbJ_IIl.js.map → enum-labels-kept-DyFE4Gaq.js.map} +1 -1
  32. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-DpFA1UVd.js} +2 -2
  33. package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-DpFA1UVd.js.map} +1 -1
  34. package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-taNTu3xv.js} +2 -2
  35. package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-taNTu3xv.js.map} +1 -1
  36. package/dist/{generate-files-DutUrsSS.js → generate-files-DbwU8Btx.js} +11 -4
  37. package/dist/generate-files-DbwU8Btx.js.map +1 -0
  38. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-ISVgsP34.js} +11 -4
  39. package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-ISVgsP34.js.map} +1 -1
  40. package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-4lOC0g1_.js} +21 -6
  41. package/dist/generated-schema-diff-4lOC0g1_.js.map +1 -0
  42. package/dist/index.es.js +13 -13
  43. package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BeepEphh.js} +2 -2
  44. package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BeepEphh.js.map} +1 -1
  45. package/dist/{migrate-policy-stamps-CdljD_y1.js → migrate-policy-stamps-cYMJ_9Ha.js} +7 -7
  46. package/dist/{migrate-policy-stamps-CdljD_y1.js.map → migrate-policy-stamps-cYMJ_9Ha.js.map} +1 -1
  47. package/dist/{open-rebase-DvmKIu7q.js → open-rebase-CTNBmmH8.js} +1139 -145
  48. package/dist/open-rebase-CTNBmmH8.js.map +1 -0
  49. package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-BLOVXK67.js} +2 -2
  50. package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-BLOVXK67.js.map} +1 -1
  51. package/dist/pipelined-transaction.d.ts +131 -0
  52. package/dist/{plan-schema-DMVh77yb.js → plan-schema-CMNWvqIa.js} +62 -3
  53. package/dist/plan-schema-CMNWvqIa.js.map +1 -0
  54. package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-IjD2AUD-.js} +2 -2
  55. package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-IjD2AUD-.js.map} +1 -1
  56. package/dist/{push-index-prebuild-C6wKdjYV.js → push-index-prebuild-CIvajIrL.js} +4 -4
  57. package/dist/{push-index-prebuild-C6wKdjYV.js.map → push-index-prebuild-CIvajIrL.js.map} +1 -1
  58. package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CLbsuSmo.js} +2 -2
  59. package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CLbsuSmo.js.map} +1 -1
  60. package/dist/{push-legacy-renames-BFF72tHG.js → push-legacy-renames-DeW_HTLJ.js} +4 -4
  61. package/dist/{push-legacy-renames-BFF72tHG.js.map → push-legacy-renames-DeW_HTLJ.js.map} +1 -1
  62. package/dist/{push-policy-plan-lOTPeQ1u.js → push-policy-plan--oRXOj4X.js} +4 -4
  63. package/dist/{push-policy-plan-lOTPeQ1u.js.map → push-policy-plan--oRXOj4X.js.map} +1 -1
  64. package/dist/{render-ddl-NpPPDACz.js → render-ddl-CzVcbbR1.js} +77 -3
  65. package/dist/render-ddl-CzVcbbR1.js.map +1 -0
  66. package/dist/{rls-enforcement-BOHuHVlc.js → rls-enforcement-jZTv1yci.js} +48 -16
  67. package/dist/{rls-enforcement-BOHuHVlc.js.map → rls-enforcement-jZTv1yci.js.map} +1 -1
  68. package/dist/schema/doctor-cli.js +4 -4
  69. package/dist/schema/generate-drizzle-schema.js +1 -1
  70. package/dist/schema/generate-files.d.ts +2 -1
  71. package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
  72. package/dist/schema/generate-postgres-ddl.js +1 -1
  73. package/dist/schema/introspect-db.js +2 -2
  74. package/dist/schema/introspect-runtime.d.ts +10 -1
  75. package/dist/schema/plan/plan-schema.d.ts +9 -1
  76. package/dist/schema/plan/render-ddl.d.ts +25 -1
  77. package/dist/schema/plan/types.d.ts +24 -0
  78. package/dist/security/rls-enforcement.d.ts +11 -0
  79. package/dist/services/FetchService.d.ts +12 -12
  80. package/dist/services/PersistService.d.ts +59 -0
  81. package/dist/services/collection-helpers.d.ts +3 -1
  82. package/dist/services/view-access.d.ts +21 -0
  83. package/dist/{websocket-CCJnghvG.js → websocket-D2y88dOa.js} +3 -3
  84. package/dist/{websocket-CCJnghvG.js.map → websocket-D2y88dOa.js.map} +1 -1
  85. package/package.json +7 -7
  86. package/dist/cli-errors-DYets7cp.js.map +0 -1
  87. package/dist/connection-CcYqncW5.js.map +0 -1
  88. package/dist/doctor-TJApVglQ.js.map +0 -1
  89. package/dist/ensure-collection-tables-DvaCEy6X.js.map +0 -1
  90. package/dist/generate-files-DutUrsSS.js.map +0 -1
  91. package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
  92. package/dist/open-rebase-DvmKIu7q.js.map +0 -1
  93. package/dist/plan-schema-DMVh77yb.js.map +0 -1
  94. package/dist/render-ddl-NpPPDACz.js.map +0 -1
@@ -1,33 +1,34 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, l as isPooledPool, m as transactionSettingsStatements, n as closeWithPool, p as searchPathList } from "./connection-CcYqncW5.js";
3
+ import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-COuS5Fm-.js";
4
4
  import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
5
- import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-DYets7cp.js";
6
- import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BIHfsGZL.js";
7
- import { t as BranchService } from "./BranchService-BPssiD8_.js";
8
- import { a as ensureAppRoleGrants, c as revokeUserRoleSql, d as warnOnAnonymousGrants, f as warnOnLegacyRlsFunctions, i as ensureAppRole, n as applyAuthContext, o as findExposedInternalTables, p as warnOnRoleSchemaCollision, r as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as validatePolicyPgRoles } from "./rls-enforcement-BOHuHVlc.js";
5
+ import { a as diagnoseDbError, at as extractCauseMessage, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, u as parseHostInfo } from "./cli-errors-D8s4z_3g.js";
6
+ import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BLOVXK67.js";
7
+ import { t as BranchService } from "./BranchService-JiYJ_n9E.js";
8
+ import { a as ensureAppRole, d as validatePolicyPgRoles, f as warnOnAnonymousGrants, i as detectConnectionPosture, l as revokeUserRoleSql, m as warnOnRoleSchemaCollision, n as applyAuthContext, o as ensureAppRoleGrants, p as warnOnLegacyRlsFunctions, r as authContextStatement, s as findExposedInternalTables, t as REBASE_USER_ROLE$1 } from "./rls-enforcement-jZTv1yci.js";
9
9
  import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
10
10
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
11
- import { n as planSchema } from "./plan-schema-DMVh77yb.js";
12
- import { t as generateSchema } from "./generate-drizzle-schema-logic-CVRmZjP3.js";
13
- import { i as renderPgType } from "./render-ddl-NpPPDACz.js";
14
- import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-BwH6k1Og.js";
15
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-CIGoIGcC.js";
16
- import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-DvaCEy6X.js";
11
+ import { n as planSchema } from "./plan-schema-CMNWvqIa.js";
12
+ import { t as generateSchema } from "./generate-drizzle-schema-logic-DpFA1UVd.js";
13
+ import { i as renderPgType } from "./render-ddl-CzVcbbR1.js";
14
+ import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-F2GWu009.js";
15
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-D4W9o9xE.js";
16
+ import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-BK--gDo6.js";
17
17
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
18
- import { t as DatabasePoolManager } from "./databasePoolManager-XmhMczz0.js";
19
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CF-8zgYA.js";
20
- import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-ChFg6UxI.js";
21
- import { Client, DatabaseError, Pool } from "pg";
22
- import { drizzle } from "drizzle-orm/node-postgres";
18
+ import { t as DatabasePoolManager } from "./databasePoolManager-7hXVurmG.js";
19
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-Bx1DYarz.js";
20
+ import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-4lOC0g1_.js";
21
+ import pg, { Client, DatabaseError, Pool } from "pg";
22
+ import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
23
23
  import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
24
24
  import { and, asc, count, desc, eq, getTableColumns, getTableName, gt, ilike, inArray, is, isNotNull, isNull, isTable, lt, lte, not, notInArray, or, relations, sql } from "drizzle-orm";
25
- import { PgArray, PgNumeric, PgTable, PgTimestamp, PgTimestampString, PgTransaction, bigint, boolean, getTableConfig, index, integer, jsonb, pgSchema, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
26
- import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isRelationalCollectionConfig, isSQLAdmin, joinConditions, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
27
- import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, REBASE_USER_ROLE, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, warnOnTableDdl, withRelationReferencesOnly } from "@rebasepro/common";
25
+ import { PgArray, PgDialect, PgNumeric, PgTable, PgTimestamp, PgTimestampString, PgTransaction, bigint, boolean, getTableConfig, index, integer, jsonb, pgSchema, pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
26
+ import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, ListLimitError, MAX_INCLUDE_DEPTH, Vector, encodeRelationAggregateSort, hasForeignKeyOnTarget, isChannelBusInstance, isChannelBusInstance as isChannelBusInstance$1, isManyToMany, isPostgresCollectionConfig, isRelationalCollectionConfig, isSQLAdmin, joinConditions, parseEnvBoolean, parseRelationAggregateSort, resolveClientListLimit, resourceEnvSuffix, resourceKeyOf, roleNameProblem, soleJoinCondition } from "@rebasepro/types";
27
+ import { COMPOSITE_ID_SEPARATOR, COMPOSITE_ID_SEPARATOR as COMPOSITE_ID_SEPARATOR$1, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, OrderBySpecError, REBASE_USER_ROLE, UnknownFilterOperatorError, apiHiddenFieldNames, applyDefaultValuesOnCreate, buildCompositeId, buildCompositeId as buildCompositeId$1, buildPropertyCallbacks, buildSdkData, callbackRefusal, canReadField, classifyTable, createAccessorSlugResolver, createRelationRef, createRelationRefWithData, deserializeFilter, detectJunctionTables, effectiveAccess, encodeCursor, fieldKeyForColumn, findRelation, firstSqlRow, getColumnName, getDeclaredPrimaryKeys, getJunctionConfigForRelation, getTableName as getTableName$1, getTenantConfig, hasFieldAccessRules, includableRelationNames, isAddressableId, normalizeDriverOrderBy, normalizeEmail, normalizeInclude, normalizeToEntityRelation, parseIdValues, parseIdValues as parseIdValues$1, parseOrderBySpecStrict, queryableFieldNames, requireCallbackClient, requireCallbackCollection, resolveCollectionRelations, resolveTenantWrite, restoresSoftDeletedRow, revokeInternalTableSql, softDeleteFieldOf, sqlRows, tenantBypassRoles, toCallbackError, toFilterTuples, unknownAggregateField, unknownFilterField, unknownIncludeRelation, unknownOrderByField, unknownProjectionField, unknownRelationTargetField, unknownVectorProperty, updateDateAutoValues, updateUserAutoValues, warnOnTableDdl, withRelationReferencesOnly } from "@rebasepro/common";
28
28
  import { camelCase, generateForeignKeyName, isPrototypePollutingKey, legacyForeignKeyName, splitSearchTerms, toSnakeCase, toWireKey, unref } from "@rebasepro/utils";
29
29
  import { AsyncLocalStorage } from "node:async_hooks";
30
30
  import { createHash } from "node:crypto";
31
+ import { prepareValue } from "pg/lib/utils.js";
31
32
  import { WebSocket } from "ws";
32
33
  import { EventEmitter } from "events";
33
34
  import { createHash as createHash$1, randomBytes, randomUUID } from "crypto";
@@ -536,8 +537,8 @@ function warnOnKeysTheAdminCannotResolve(collections, registry) {
536
537
  * callers decide what that means, since "unaddressable" is a different answer
537
538
  * in a notification (broadcast a wildcard) than in a save (fail).
538
539
  */
539
- function deriveRowAddress(row, collection, registry) {
540
- const composite = buildCompositeId(row, getPrimaryKeys(collection, registry));
540
+ function deriveRowAddress(row, collection, registry, primaryKeys = getPrimaryKeys(collection, registry)) {
541
+ const composite = buildCompositeId(row, primaryKeys);
541
542
  if (composite && composite.split(COMPOSITE_ID_SEPARATOR).some((part) => part !== "")) return composite;
542
543
  if (row.id !== void 0 && row.id !== null) return String(row.id);
543
544
  return "";
@@ -820,6 +821,26 @@ function toMembershipList(value) {
820
821
  return Array.isArray(value) ? value : [value];
821
822
  }
822
823
  /**
824
+ * `array-contains-all` (`@>`: every listed element is in the column) and
825
+ * `array-contained-by` (`<@`: every element of the column is listed), on a
826
+ * native array or a JSONB array. Both are containment, so a GIN index on the
827
+ * column serves them.
828
+ *
829
+ * A bare element is the one-element list and `null` a null check, as for
830
+ * `array-contains-any`. The empty list is answered without one: every array
831
+ * contains it, and only an empty array is contained by it.
832
+ */
833
+ function arraySetCondition(target, op, value, isNativeArray) {
834
+ if (value === null || value === void 0) return sql`${target} IS NULL`;
835
+ const values = Array.isArray(value) ? value : [value];
836
+ if (values.length === 0) {
837
+ if (op === "array-contains-all") return sql`${target} IS NOT NULL`;
838
+ return isNativeArray ? sql`cardinality(${target}) = 0` : sql`${target} = '[]'::jsonb`;
839
+ }
840
+ const operator = op === "array-contains-all" ? sql`@>` : sql`<@`;
841
+ return isNativeArray ? sql`${target} ${operator} ARRAY[${sql.join(values.map((v) => sql`${v}`), sql`, `)}]` : sql`${target} ${operator} ${JSON.stringify(values)}::jsonb`;
842
+ }
843
+ /**
823
844
  * "The jsonb array holds at least one of `values`", as one containment test per
824
845
  * value: `(col @> '[3]' OR col @> '[7]')`.
825
846
  *
@@ -1526,6 +1547,15 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1526
1547
  predicate: contains(),
1527
1548
  negate: false
1528
1549
  };
1550
+ case "array-contains-all":
1551
+ case "array-contained-by": {
1552
+ const meta = getColumnMeta(column);
1553
+ const isNativeArray = meta.dataType === "array" || meta.columnType === "PgArray";
1554
+ return {
1555
+ predicate: arraySetCondition(ref, op, value, isNativeArray),
1556
+ negate: false
1557
+ };
1558
+ }
1529
1559
  default: throw ApiError.badRequest(`Unknown filter operator '${op}'. Valid operators: ${ALL_WHERE_FILTER_OPS.join(", ")}.`, "UNKNOWN_FILTER_OPERATOR", {
1530
1560
  operator: op,
1531
1561
  validOperators: ALL_WHERE_FILTER_OPS
@@ -1668,6 +1698,11 @@ var DrizzleConditionBuilder = class DrizzleConditionBuilder {
1668
1698
  if (isNativeArray) return sql`${column} @> ARRAY[${value}]`;
1669
1699
  return sql`${column} @> ${JSON.stringify([value])}`;
1670
1700
  }
1701
+ case "array-contains-all":
1702
+ case "array-contained-by": {
1703
+ const meta = getColumnMeta(column);
1704
+ return arraySetCondition(column, op, value, meta.dataType === "array" || meta.columnType === "PgArray");
1705
+ }
1671
1706
  case "not-in": {
1672
1707
  if (value === null || value === void 0) return sql`${column} IS NOT NULL`;
1673
1708
  const values = toMembershipList(value);
@@ -2481,6 +2516,27 @@ function toRestDate(value) {
2481
2516
  const date = new Date(value);
2482
2517
  return isNaN(date.getTime()) ? value : date.toISOString();
2483
2518
  }
2519
+ var restRowPlans = /* @__PURE__ */ new WeakMap();
2520
+ function restRowPlan(collection) {
2521
+ let plan = restRowPlans.get(collection);
2522
+ if (!plan) {
2523
+ const properties = collection.properties ?? {};
2524
+ plan = {
2525
+ steps: /* @__PURE__ */ new Map(),
2526
+ restricted: Object.entries(properties).filter(([, property]) => effectiveAccess(property) !== void 0)
2527
+ };
2528
+ restRowPlans.set(collection, plan);
2529
+ }
2530
+ return plan;
2531
+ }
2532
+ function restKeyStep(collection, key) {
2533
+ const relation = findRelation(resolveCollectionRelations(collection), key);
2534
+ if (relation) return { relation };
2535
+ const property = collection.properties?.[key];
2536
+ if (property?.type === "date") return toRestDate;
2537
+ if (property?.type === "number") return (value) => coerceDeclaredNumber(value, property);
2538
+ return null;
2539
+ }
2484
2540
  /**
2485
2541
  * One scalar, as REST serves it: declared numbers as numbers, declared dates as
2486
2542
  * RFC 3339, everything else exactly as the database returned it.
@@ -2536,8 +2592,9 @@ function toRestValues(row, collection) {
2536
2592
  * though the array itself is theirs to see.
2537
2593
  */
2538
2594
  function stripUnreadable(row, collection) {
2539
- const properties = collection.properties;
2540
- if (!properties) return row;
2595
+ if (!collection.properties) return row;
2596
+ const { restricted } = restRowPlan(collection);
2597
+ if (restricted.length === 0) return row;
2541
2598
  const viewer = currentFieldViewer();
2542
2599
  const hidden = /* @__PURE__ */ new Set();
2543
2600
  const hide = (name) => {
@@ -2545,7 +2602,7 @@ function stripUnreadable(row, collection) {
2545
2602
  delete row[name];
2546
2603
  };
2547
2604
  let relations;
2548
- for (const [key, property] of Object.entries(properties)) {
2605
+ for (const [key, property] of restricted) {
2549
2606
  if (canReadField(property, viewer)) continue;
2550
2607
  hide(key);
2551
2608
  if (property.columnName) hide(property.columnName);
@@ -2656,12 +2713,21 @@ function toFlatRow(row, collection, registry) {
2656
2713
  * actually there.
2657
2714
  */
2658
2715
  function toRestRow(row, collection, registry) {
2659
- const resolvedRelations = resolveCollectionRelations(collection);
2716
+ const { steps } = restRowPlan(collection);
2660
2717
  const flat = {};
2661
- for (const [key, value] of Object.entries(row)) {
2662
- const relation = findRelation(resolvedRelations, key);
2663
- if (relation && Array.isArray(value)) flat[key] = value.map((item) => renderTarget(isJunctionRelation(relation) ? unwrapJunctionRow(item, relation) : item, relation.target(), "inline", registry));
2664
- else if (relation && typeof value === "object" && value !== null) flat[key] = renderTarget(value, relation.target(), "inline", registry);
2718
+ for (const key of Object.keys(row)) {
2719
+ const value = row[key];
2720
+ let step = steps.get(key);
2721
+ if (step === void 0) {
2722
+ step = restKeyStep(collection, key);
2723
+ steps.set(key, step);
2724
+ }
2725
+ if (step === null) flat[key] = value;
2726
+ else if (typeof step === "function") flat[key] = step(value);
2727
+ else if (Array.isArray(value)) {
2728
+ const { relation } = step;
2729
+ flat[key] = value.map((item) => renderTarget(isJunctionRelation(relation) ? unwrapJunctionRow(item, relation) : item, relation.target(), "inline", registry));
2730
+ } else if (typeof value === "object" && value !== null) flat[key] = renderTarget(value, step.relation.target(), "inline", registry);
2665
2731
  else flat[key] = toRestScalar(value, collection.properties?.[key]);
2666
2732
  }
2667
2733
  return stripUnreadable(flat, collection);
@@ -2999,6 +3065,40 @@ function rowInTrashError(path, key, softDelete) {
2999
3065
  return ApiError.conflict(`"${key}" in "${path}" is in the trash, so an upsert cannot write it. Restore the row first (an update setting '${softDelete.field}' to null), or purge it (a delete with ?hard=true) and upsert again.`, "ROW_IN_TRASH");
3000
3066
  }
3001
3067
  //#endregion
3068
+ //#region src/services/view-access.ts
3069
+ /**
3070
+ * What a collection that serves a SQL view (`PostgresCollectionConfig.view`)
3071
+ * allows: reads, and for a materialized view only by the roles it names.
3072
+ *
3073
+ * A plain view runs as the caller (`security_invoker`), so the policies of the
3074
+ * tables it reads already decide every row, and a read of one needs nothing
3075
+ * here. A materialized view stores its rows and Postgres puts no row-level
3076
+ * security on it: whoever may select from it sees all of it. So the role check
3077
+ * is the driver's, made before every read of one by a caller (see
3078
+ * `beforeQueryConditions`) — and not of the server's own work, which reads
3079
+ * with no viewer at all.
3080
+ */
3081
+ /** The roles a materialized view is served to when it names none. */
3082
+ var DEFAULT_VIEW_ROLES = ["admin"];
3083
+ /** Whether a collection serves a view rather than a table. */
3084
+ function isViewCollection(collection) {
3085
+ return Boolean(collection && isPostgresCollectionConfig(collection) && collection.view);
3086
+ }
3087
+ /** Refuse a caller who holds none of a materialized view's roles. A no-op for anything else. */
3088
+ function assertViewReadable(collection) {
3089
+ if (!collection || !isPostgresCollectionConfig(collection) || !collection.view?.materialized) return;
3090
+ const viewer = currentFieldViewer();
3091
+ if (!viewer) return;
3092
+ const allowed = collection.view.roles ?? DEFAULT_VIEW_ROLES;
3093
+ if ((viewer.roles ?? []).some((role) => allowed.includes(role))) return;
3094
+ throw ApiError.forbidden(`"${collection.slug}" is a materialized view, which has no row-level security, so it is served whole and only to ${allowed.map((role) => `'${role}'`).join(", ")}.`, "VIEW_NOT_READABLE");
3095
+ }
3096
+ /** Refuse a write to a collection that serves a view. */
3097
+ function assertCollectionWritable(collection, path) {
3098
+ if (!isViewCollection(collection)) return;
3099
+ throw new ApiError(405, "COLLECTION_READ_ONLY", `"${collection?.slug ?? path}" serves a SQL view, which is read-only: write to the tables it reads.`, { collection: collection?.slug ?? path }, true);
3100
+ }
3101
+ //#endregion
3002
3102
  //#region src/services/read-scope.ts
3003
3103
  /**
3004
3104
  * `beforeQuery`: the one place a collection callback can change *which* rows a
@@ -3081,6 +3181,7 @@ function hasBeforeQuery(registry, collection) {
3081
3181
  * narrow, it is only ever given a way to.
3082
3182
  */
3083
3183
  async function beforeQueryConditions(env, collection, path, table, description, filterContext) {
3184
+ assertViewReadable(collection);
3084
3185
  const hooks = resolveBeforeQuery(env.registry, collection);
3085
3186
  if (hooks.length === 0) return [];
3086
3187
  if (!collection) throw new Error(`[beforeQuery] "${path}" resolves to no registered collection, so a global \`beforeQuery\` cannot be compiled against it. Register the collection, or narrow the hook to the collections it applies to.`);
@@ -4555,7 +4656,7 @@ function assertWritableThrough(hop, path) {
4555
4656
  */
4556
4657
  function numericAggregateAliases(aggregates, properties) {
4557
4658
  const isNumberField = (field) => Boolean(field) && properties[field]?.type === "number";
4558
- return new Set(aggregates.filter((a) => a.fn === "count" || a.fn === "sum" || a.fn === "avg" || (a.fn === "min" || a.fn === "max") && isNumberField(a.field)).map((a) => a.alias));
4659
+ return new Set(aggregates.filter((a) => a.fn === "count" || a.fn === "sum" || a.fn === "avg" || a.fn === "countDistinct" || a.fn === "percentile" || (a.fn === "min" || a.fn === "max" || a.fn === "mode") && isNumberField(a.field)).map((a) => a.alias));
4559
4660
  }
4560
4661
  /**
4561
4662
  * Refuse a read that names a relation property its caller may not read.
@@ -5572,6 +5673,11 @@ var FetchService = class FetchService {
5572
5673
  selection[aggregate.alias] = sql`count(*)`;
5573
5674
  continue;
5574
5675
  }
5676
+ if (aggregate.fn === "fingerprint") {
5677
+ if (isPostgresCollectionConfig(collection) && collection.view && !collection.view.materialized) throw ApiError.badRequest(`\`fingerprint()\` reads the versions of stored rows, and "${collection.slug}" is a view that stores none. Fingerprint the tables it reads, or make it a materialized view.`, "INVALID_AGGREGATE_SELECT");
5678
+ selection[aggregate.alias] = sql`md5(count(*)::text || ':' || coalesce(sum(${table}.xmin::text::bigint), 0)::text)`;
5679
+ continue;
5680
+ }
5575
5681
  const column = columnFor(aggregate.field, `${aggregate.fn}()`);
5576
5682
  switch (aggregate.fn) {
5577
5683
  case "count":
@@ -5589,14 +5695,34 @@ var FetchService = class FetchService {
5589
5695
  case "max":
5590
5696
  selection[aggregate.alias] = sql`max(${column})`;
5591
5697
  break;
5698
+ case "countDistinct":
5699
+ selection[aggregate.alias] = sql`count(DISTINCT ${column})`;
5700
+ break;
5701
+ case "mode":
5702
+ selection[aggregate.alias] = sql`mode() WITHIN GROUP (ORDER BY ${column})`;
5703
+ break;
5704
+ case "percentile":
5705
+ selection[aggregate.alias] = sql`(percentile_cont(${aggregate.p ?? .5}::float8) WITHIN GROUP (ORDER BY ${column}))::numeric`;
5706
+ break;
5707
+ case "distinct":
5708
+ selection[aggregate.alias] = sql`coalesce(jsonb_agg(DISTINCT ${column} ORDER BY ${column}) FILTER (WHERE ${column} IS NOT NULL), '[]'::jsonb)`;
5709
+ break;
5592
5710
  }
5593
5711
  }
5594
- const groupColumns = (options.groupBy ?? []).map((field) => ({
5595
- field,
5596
- column: columnFor(field, "groupBy")
5597
- }));
5712
+ const lateral = [];
5713
+ const groupColumns = (options.groupBy ?? []).map((group) => {
5714
+ if (typeof group === "string") return {
5715
+ field: group,
5716
+ column: columnFor(group, "groupBy")
5717
+ };
5718
+ const column = columnFor(group.field, `${group.transform}()`);
5719
+ return {
5720
+ field: group.key,
5721
+ column: this.groupExpression(group, column, lateral, collectionPath)
5722
+ };
5723
+ });
5598
5724
  for (const group of groupColumns) selection[group.field] = sql`${group.column}`;
5599
- let query = this.db.select(selection).from(table).$dynamic();
5725
+ let query = (lateral.length > 0 ? this.db.select(selection).from(sql`${table} ${sql.join(lateral, sql` `)}`) : this.db.select(selection).from(table)).$dynamic();
5600
5726
  const conditions = [];
5601
5727
  withSoftDelete(conditions, collection, table, options.withDeleted);
5602
5728
  if (options.searchString) {
@@ -5633,6 +5759,41 @@ var FetchService = class FetchService {
5633
5759
  });
5634
5760
  }
5635
5761
  /**
5762
+ * A transformed group (`AggregateGroup`) as SQL. `lower`/`upper` read the
5763
+ * column as text; `year`/`month`/`day` truncate a date or timestamp, in UTC
5764
+ * when it has a time zone, to `YYYY`, `YYYY-MM` or `YYYY-MM-DD`; `unnest`
5765
+ * adds a lateral join over the array's elements to `lateral` and groups by
5766
+ * the element.
5767
+ */
5768
+ groupExpression(group, column, lateral, collectionPath) {
5769
+ const sqlType = column.getSQLType?.() ?? "";
5770
+ switch (group.transform) {
5771
+ case "lower": return sql`lower(${column}::text)`;
5772
+ case "upper": return sql`upper(${column}::text)`;
5773
+ case "year":
5774
+ case "month":
5775
+ case "day": {
5776
+ if (!/^(timestamp|date)/.test(sqlType)) throw ApiError.badRequest(`\`${group.transform}(${group.field})\` groups a date, and '${group.field}' on "${collectionPath}" is ${sqlType || "not one"}.`, "INVALID_AGGREGATE_GROUP", {
5777
+ field: group.field,
5778
+ transform: group.transform
5779
+ });
5780
+ const format = group.transform === "year" ? "YYYY" : group.transform === "month" ? "YYYY-MM" : "YYYY-MM-DD";
5781
+ return sql`to_char(${sqlType.includes("with time zone") ? sql`(${column} AT TIME ZONE 'UTC')` : sql`${column}`}, ${sql.raw(`'${format}'`)})`;
5782
+ }
5783
+ case "unnest": {
5784
+ const meta = getColumnMeta(column);
5785
+ const alias = sql.identifier(`unnest_${lateral.length}`);
5786
+ if (meta.dataType === "array" || meta.columnType === "PgArray") lateral.push(sql`CROSS JOIN LATERAL unnest(${column}) AS ${alias}(element)`);
5787
+ else if (sqlType === "jsonb") lateral.push(sql`CROSS JOIN LATERAL jsonb_array_elements_text(CASE WHEN jsonb_typeof(${column}) = 'array' THEN ${column} ELSE '[]'::jsonb END) AS ${alias}(element)`);
5788
+ else throw ApiError.badRequest(`\`unnest(${group.field})\` groups by the elements of an array, and '${group.field}' on "${collectionPath}" is ${sqlType || "not one"}.`, "INVALID_AGGREGATE_GROUP", {
5789
+ field: group.field,
5790
+ transform: group.transform
5791
+ });
5792
+ return sql`${alias}.element`;
5793
+ }
5794
+ }
5795
+ }
5796
+ /**
5636
5797
  * The `ORDER BY` of a grouped aggregate: the caller's keys, then every
5637
5798
  * group key they did not name.
5638
5799
  *
@@ -5895,6 +6056,23 @@ var FetchService = class FetchService {
5895
6056
  }
5896
6057
  };
5897
6058
  //#endregion
6059
+ //#region src/utils/result-rows.ts
6060
+ /**
6061
+ * The rows a query answered with, whatever shape the driver handed them in.
6062
+ *
6063
+ * node-postgres answers one result for one statement, and an array of results
6064
+ * — one per statement — for a string holding several (`SELECT 1; SELECT 2`).
6065
+ * Reading `.rows` off that array gave `undefined`, and the caller got no rows
6066
+ * at all for a script that ended in a SELECT. The last statement's rows are
6067
+ * the script's answer, as in psql.
6068
+ */
6069
+ function rowsOfResult(result) {
6070
+ const last = Array.isArray(result) ? result[result.length - 1] : result;
6071
+ if (typeof last !== "object" || last === null || !("rows" in last)) return [];
6072
+ const rows = last.rows;
6073
+ return Array.isArray(rows) ? rows : [];
6074
+ }
6075
+ //#endregion
5898
6076
  //#region src/services/RelationWriteService.ts
5899
6077
  /**
5900
6078
  * The same reading, keeping the link's own values.
@@ -6753,6 +6931,12 @@ function createStampKeys(properties) {
6753
6931
  return keys;
6754
6932
  }
6755
6933
  /**
6934
+ * The most rows one INSERT of a batch carries, and the most values: Postgres
6935
+ * takes at most 65,535 parameters in a statement.
6936
+ */
6937
+ var BATCH_MAX_ROWS = 1e3;
6938
+ var BATCH_MAX_PARAMS = 3e4;
6939
+ /**
6756
6940
  * Run `write` in a transaction of its own — a SAVEPOINT inside a write — or,
6757
6941
  * when nothing could catch its failure and carry on, straight on `db`.
6758
6942
  *
@@ -6770,6 +6954,14 @@ function inOwnTransactionUnlessTopLevel(db, write) {
6770
6954
  if ("rollback" in db && currentWriteDepth() === 1 && currentWriteScope()?.tx !== void 0) return write(db);
6771
6955
  return db.transaction((tx) => write(tx));
6772
6956
  }
6957
+ /** A column's SQL type as a cast can name it: the serial pseudo-types are their integers. */
6958
+ function castableType(sqlType) {
6959
+ return {
6960
+ smallserial: "smallint",
6961
+ serial: "integer",
6962
+ bigserial: "bigint"
6963
+ }[sqlType.toLowerCase()] ?? sqlType;
6964
+ }
6773
6965
  /**
6774
6966
  * Service for handling all row write operations.
6775
6967
  * Handles saving, deleting, and updating rows.
@@ -6995,17 +7187,23 @@ var PersistService = class {
6995
7187
  const scalarKeys = Object.keys(entityData);
6996
7188
  const compiledOps = fieldOpKeys.length > 0 ? compileFieldOps(table, fieldOps, { collectionPath: effectiveCollectionPath }) : void 0;
6997
7189
  const bounds = fieldOpKeys.length > 0 ? compileFieldOpBounds(table, fieldOps, collection.properties ?? {}, { collectionPath: effectiveCollectionPath }) : [];
7190
+ const condition = rowIdentityCondition(table, idInfoArray, id, effectiveCollectionPath);
6998
7191
  if (scalarKeys.length > 0 || compiledOps) {
6999
7192
  const updateQuery = tx.update(table).set({
7000
7193
  ...entityData,
7001
7194
  ...compiledOps ?? {}
7002
7195
  });
7003
- const condition = rowIdentityCondition(table, idInfoArray, id, effectiveCollectionPath);
7004
- if (((await updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds)))).rowCount ?? 0) === 0) {
7196
+ const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7197
+ const updated = await updateQuery.where(and(condition, ...bounds.map((bound) => bound.holds))).returning(returning?.columns ?? returningKeys);
7198
+ if (returning && updated[0]) returnedRow = returning.render(updated[0]);
7199
+ if (updated.length === 0) {
7005
7200
  const broken = await brokenFieldOpBounds(tx, table, [condition], bounds);
7006
7201
  if (broken.length > 0) throw fieldOpBoundsError(collection.slug, broken);
7007
7202
  throw await this.explainZeroRowWrite(tx, table, [condition], effectiveCollectionPath, currentId, "update");
7008
7203
  }
7204
+ } else if (options?.unreadRow) {
7205
+ const [present] = await tx.select(returningKeys).from(table).where(condition).limit(1);
7206
+ if (!present) throw ApiError.notFound(`No row "${id}" in "${effectiveCollectionPath}" to update.`);
7009
7207
  }
7010
7208
  } else {
7011
7209
  const dataForInsert = { ...entityData };
@@ -7031,11 +7229,13 @@ var PersistService = class {
7031
7229
  const trashColumn = softDelete ? softDeleteColumn(collection, table) : void 0;
7032
7230
  const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7033
7231
  const updating = Object.keys(set).length > 0;
7232
+ const returning = rowIsWrittenLast ? this.fetchService.insertReturning(collection.slug) : void 0;
7034
7233
  result = updating ? await insertQuery.onConflictDoUpdate({
7035
7234
  target,
7036
7235
  set,
7037
7236
  setWhere: writable
7038
- }).returning(returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returningKeys);
7237
+ }).returning(returning?.columns ?? returningKeys) : await insertQuery.onConflictDoNothing({ target }).returning(returning?.columns ?? returningKeys);
7238
+ if (returning && result[0]) returnedRow = returning.render(result[0]);
7039
7239
  if (result.length === 0) {
7040
7240
  const keyConditions = target.map((column, i) => eq(column, dataForInsert[targetFields[i]]));
7041
7241
  if (scope) keyConditions.push(scope);
@@ -7074,6 +7274,238 @@ var PersistService = class {
7074
7274
  return finalEntity;
7075
7275
  }
7076
7276
  /**
7277
+ * Write a batch of new rows — inserted, or upserted with `options.upsert` —
7278
+ * as multi-row statements, and return each row as {@link save} returns it.
7279
+ *
7280
+ * The statements are the ones {@link save} sends for one row, carrying up
7281
+ * to {@link BATCH_MAX_ROWS} rows each: the same columns, defaults, conflict
7282
+ * target, conflict-update and scope. A batch of 1,000 rows is one or two
7283
+ * statements instead of a thousand.
7284
+ *
7285
+ * `undefined`, before anything is written, for a batch that needs what
7286
+ * only the row-by-row save does: a nested path, a relation or field
7287
+ * operation in a row, an upsert row without its whole conflict key, or a
7288
+ * collection whose rows cannot be returned by the write itself (a
7289
+ * `beforeQuery` or per-field read access). The caller then saves the rows
7290
+ * one by one.
7291
+ *
7292
+ * Run inside the caller's transaction, which a statement the database
7293
+ * refuses aborts: the caller undoes the batch and replays its rows one by
7294
+ * one to say which row failed.
7295
+ *
7296
+ * Rows go out in order, in consecutive runs: a run ends where the next
7297
+ * row's conflict-update would set other columns, or where an upsert names
7298
+ * a key the run already holds (one statement cannot update a row twice),
7299
+ * so a key written twice still ends with the later values.
7300
+ */
7301
+ async saveRows(collectionPath, rows, options) {
7302
+ if (isNestedPath(collectionPath)) return void 0;
7303
+ const collection = getCollectionByPath(collectionPath, this.registry);
7304
+ const returning = this.fetchService.insertReturning(collection.slug);
7305
+ if (!returning) return void 0;
7306
+ const table = getTableForCollection(collection, this.registry);
7307
+ const idInfoArray = getPrimaryKeys(collection, this.registry);
7308
+ const resolvedRelations = resolveCollectionRelations(collection);
7309
+ const manyRelationKeys = Object.keys(resolvedRelations).filter((key) => resolvedRelations[key]?.cardinality === "many");
7310
+ const upsert = options?.upsert === true;
7311
+ const targetFields = options?.onConflict && options.onConflict.length > 0 ? [...options.onConflict] : idInfoArray.map((info) => info.fieldName);
7312
+ const createStamps = createStampKeys(collection.properties);
7313
+ const prepared = [];
7314
+ for (const row of rows) {
7315
+ assertNoReadOnlyRelationValues(row.values, collection);
7316
+ const { values: plainValues, fieldOps } = splitFieldOps(row.values, collection.properties);
7317
+ if (Object.keys(fieldOps).length > 0) return void 0;
7318
+ if (manyRelationKeys.some((key) => Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
7319
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
7320
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
7321
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
7322
+ assertWritableColumns(data, table, collectionPath);
7323
+ for (const info of idInfoArray) if (data[info.fieldName] === "" || data[info.fieldName] === null || data[info.fieldName] === void 0) delete data[info.fieldName];
7324
+ let set = [];
7325
+ let key = "";
7326
+ if (upsert) {
7327
+ if (targetFields.length === 0 || targetFields.some((field) => data[field] === void 0)) return void 0;
7328
+ const excluded = /* @__PURE__ */ new Set([
7329
+ ...idInfoArray.map((info) => info.fieldName),
7330
+ ...targetFields,
7331
+ ...createStamps,
7332
+ ...row.insertOnlyKeys ?? []
7333
+ ]);
7334
+ set = Object.keys(data).filter((field) => !excluded.has(field)).sort();
7335
+ key = JSON.stringify(targetFields.map((field) => String(data[field])));
7336
+ }
7337
+ prepared.push({
7338
+ data,
7339
+ set,
7340
+ key
7341
+ });
7342
+ }
7343
+ const target = upsert ? targetFields.map((field) => {
7344
+ const column = table[field];
7345
+ if (!column) throw ApiError.badRequest(`'${field}' is not a column of "${collectionPath}", so it cannot be an upsert target.`, "INVALID_CONFLICT_TARGET");
7346
+ return column;
7347
+ }) : [];
7348
+ const scope = upsert ? await this.writeScope(collection, collectionPath, table) : void 0;
7349
+ const trashColumn = (upsert ? resolveSoftDelete(collection) : void 0) ? softDeleteColumn(collection, table) : void 0;
7350
+ const writable = trashColumn ? scope ? and(scope, isNull(trashColumn)) : isNull(trashColumn) : scope;
7351
+ const runs = [];
7352
+ let start = 0;
7353
+ let params = 0;
7354
+ let keys = /* @__PURE__ */ new Set();
7355
+ for (let i = 0; i < prepared.length; i++) {
7356
+ const row = prepared[i];
7357
+ const width = Object.keys(row.data).length;
7358
+ if (i > start && (i - start >= BATCH_MAX_ROWS || params + width > BATCH_MAX_PARAMS || upsert && (keys.has(row.key) || row.set.join(",") !== prepared[start].set.join(",")))) {
7359
+ runs.push({
7360
+ start,
7361
+ end: i
7362
+ });
7363
+ start = i;
7364
+ params = 0;
7365
+ keys = /* @__PURE__ */ new Set();
7366
+ }
7367
+ params += width;
7368
+ keys.add(row.key);
7369
+ }
7370
+ if (prepared.length > 0) runs.push({
7371
+ start,
7372
+ end: prepared.length
7373
+ });
7374
+ const written = new Array(prepared.length);
7375
+ for (const run of runs) {
7376
+ const slice = prepared.slice(run.start, run.end);
7377
+ const insertQuery = this.db.insert(table).values(slice.map((row) => row.data));
7378
+ if (!upsert) {
7379
+ const result = await insertQuery.returning(returning.columns);
7380
+ if (result.length !== slice.length) throw new Error(`Inserted ${slice.length} rows into "${collectionPath}" and got ${result.length} back.`);
7381
+ result.forEach((row, i) => {
7382
+ written[run.start + i] = returning.render(row);
7383
+ });
7384
+ continue;
7385
+ }
7386
+ const setColumns = slice[0].set;
7387
+ const set = {};
7388
+ for (const field of setColumns) {
7389
+ const column = table[field];
7390
+ set[field] = sql`excluded.${sql.identifier(column.name)}`;
7391
+ }
7392
+ const result = setColumns.length > 0 ? await insertQuery.onConflictDoUpdate({
7393
+ target,
7394
+ set,
7395
+ setWhere: writable
7396
+ }).returning(returning.columns) : await insertQuery.onConflictDoNothing({ target }).returning(returning.columns);
7397
+ const byKey = /* @__PURE__ */ new Map();
7398
+ for (const row of result) byKey.set(JSON.stringify(targetFields.map((field) => String(row[field]))), row);
7399
+ slice.forEach((row, i) => {
7400
+ const stored = byKey.get(row.key);
7401
+ if (stored) written[run.start + i] = returning.render(stored);
7402
+ });
7403
+ }
7404
+ const saved = [];
7405
+ for (let i = 0; i < rows.length; i++) saved.push(written[i] ?? await this.save(collectionPath, rows[i].values, void 0, collection.databaseId, {
7406
+ upsert,
7407
+ onConflict: options?.onConflict,
7408
+ insertOnlyKeys: rows[i].insertOnlyKeys
7409
+ }));
7410
+ return saved;
7411
+ }
7412
+ /**
7413
+ * Update rows by id, each with its own values, as
7414
+ * `UPDATE … FROM (VALUES …) … RETURNING` statements, and return each row as
7415
+ * {@link save} returns it — or `undefined`, before anything is written,
7416
+ * for updates that need what only the row-by-row update does: a nested
7417
+ * path, a relation or field operation in a row, a collection whose rows the
7418
+ * write cannot return (`beforeQuery`, per-field read access) or that has a
7419
+ * trash. Consecutive updates setting the same columns share a statement;
7420
+ * an id named twice starts a new one, so the later values win.
7421
+ *
7422
+ * An id the statement did not update — not there, or not the caller's to
7423
+ * update — fails the call: the caller replays the updates one by one to say
7424
+ * which, and why.
7425
+ */
7426
+ async updateRows(collectionPath, updates) {
7427
+ if (isNestedPath(collectionPath)) return void 0;
7428
+ const collection = getCollectionByPath(collectionPath, this.registry);
7429
+ if (resolveSoftDelete(collection)) return void 0;
7430
+ const returning = this.fetchService.insertReturning(collection.slug);
7431
+ if (!returning) return void 0;
7432
+ const table = getTableForCollection(collection, this.registry);
7433
+ const idInfoArray = requirePrimaryKeys(collection, this.registry);
7434
+ const resolvedRelations = resolveCollectionRelations(collection);
7435
+ const manyRelationKeys = Object.keys(resolvedRelations).filter((key) => resolvedRelations[key]?.cardinality === "many");
7436
+ const columnOf = (field) => table[field];
7437
+ const prepared = [];
7438
+ for (const { id, values } of updates) {
7439
+ assertNoReadOnlyRelationValues(values, collection);
7440
+ const { values: plainValues, fieldOps } = splitFieldOps(values, collection.properties);
7441
+ if (Object.keys(fieldOps).length > 0) return void 0;
7442
+ if (manyRelationKeys.some((key) => Object.prototype.hasOwnProperty.call(plainValues, key))) return void 0;
7443
+ const serialized = serializeDataToServer(plainValues, collection.properties, collection, this.registry);
7444
+ if (serialized.inverseRelationUpdates.length > 0 || serialized.joinPathRelationUpdates.length > 0) return void 0;
7445
+ const data = { ...sanitizeAndConvertDates(serialized.scalarData) };
7446
+ assertWritableColumns(data, table, collectionPath);
7447
+ for (const info of idInfoArray) delete data[info.fieldName];
7448
+ if (Object.keys(data).length === 0) return void 0;
7449
+ if (!idCanAddressTable(id, table, idInfoArray)) return void 0;
7450
+ const key = parseIdValues$1(String(id), idInfoArray);
7451
+ prepared.push({
7452
+ key,
7453
+ data,
7454
+ columns: Object.keys(data).sort().join(","),
7455
+ id: JSON.stringify(idInfoArray.map((info) => String(key[info.fieldName])))
7456
+ });
7457
+ }
7458
+ const runs = [];
7459
+ let start = 0;
7460
+ let ids = /* @__PURE__ */ new Set();
7461
+ for (let i = 0; i < prepared.length; i++) {
7462
+ const row = prepared[i];
7463
+ const width = idInfoArray.length + Object.keys(row.data).length;
7464
+ if (i > start && (i - start >= BATCH_MAX_ROWS || (i - start) * width > BATCH_MAX_PARAMS || ids.has(row.id) || row.columns !== prepared[start].columns)) {
7465
+ runs.push({
7466
+ start,
7467
+ end: i
7468
+ });
7469
+ start = i;
7470
+ ids = /* @__PURE__ */ new Set();
7471
+ }
7472
+ ids.add(row.id);
7473
+ }
7474
+ if (prepared.length > 0) runs.push({
7475
+ start,
7476
+ end: prepared.length
7477
+ });
7478
+ const written = new Array(prepared.length);
7479
+ for (const run of runs) {
7480
+ const slice = prepared.slice(run.start, run.end);
7481
+ const keyFields = idInfoArray.map((info) => info.fieldName);
7482
+ const setFields = slice[0].columns.split(",");
7483
+ const valueOf = (field, value) => {
7484
+ const column = columnOf(field);
7485
+ return sql`${sql.param(value ?? null, column)}::${sql.raw(castableType(column.getSQLType()))}`;
7486
+ };
7487
+ const rows = slice.map((row) => sql`(${sql.join([...keyFields.map((field) => valueOf(field, row.key[field])), ...setFields.map((field) => valueOf(field, row.data[field]))], sql`, `)})`);
7488
+ const names = [...keyFields.map((_, i) => `k${i}`), ...setFields.map((_, i) => `c${i}`)];
7489
+ const returnedColumns = Object.entries(returning.columns);
7490
+ const result = await this.db.execute(sql`UPDATE ${table} SET ${sql.join(setFields.map((field, i) => sql`${sql.identifier(columnOf(field).name)} = ${sql.identifier("v")}.${sql.identifier(`c${i}`)}`), sql`, `)} FROM (VALUES ${sql.join(rows, sql`, `)}) AS ${sql.identifier("v")}(${sql.raw(names.map((name) => `"${name}"`).join(", "))}) WHERE ${sql.join(keyFields.map((field, i) => sql`${columnOf(field)} = ${sql.identifier("v")}.${sql.identifier(`k${i}`)}`), sql` AND `)} RETURNING ${sql.join(returnedColumns.map(([, column]) => sql`${column}`), sql`, `)}`);
7491
+ const byId = /* @__PURE__ */ new Map();
7492
+ for (const raw of rowsOfResult(result)) {
7493
+ const row = {};
7494
+ for (const [field, column] of returnedColumns) {
7495
+ const value = raw[column.name];
7496
+ row[field] = value === null || value === void 0 ? null : column.mapFromDriverValue(value);
7497
+ }
7498
+ byId.set(JSON.stringify(keyFields.map((field) => String(row[field]))), row);
7499
+ }
7500
+ slice.forEach((row, i) => {
7501
+ const stored = byId.get(row.id);
7502
+ if (!stored) throw new Error(`Update ${run.start + i} of ${prepared.length} matched no row in "${collectionPath}".`);
7503
+ written[run.start + i] = returning.render(stored);
7504
+ });
7505
+ }
7506
+ return written;
7507
+ }
7508
+ /**
7077
7509
  * The caller's `beforeQuery` scope over this table, as one condition: what
7078
7510
  * a stored row must satisfy for a write that meets it to change it. The
7079
7511
  * same scope the update gate and the single get apply; `undefined` when the
@@ -7143,23 +7575,6 @@ var PersistService = class {
7143
7575
  }
7144
7576
  };
7145
7577
  //#endregion
7146
- //#region src/utils/result-rows.ts
7147
- /**
7148
- * The rows a query answered with, whatever shape the driver handed them in.
7149
- *
7150
- * node-postgres answers one result for one statement, and an array of results
7151
- * — one per statement — for a string holding several (`SELECT 1; SELECT 2`).
7152
- * Reading `.rows` off that array gave `undefined`, and the caller got no rows
7153
- * at all for a script that ended in a SELECT. The last statement's rows are
7154
- * the script's answer, as in psql.
7155
- */
7156
- function rowsOfResult(result) {
7157
- const last = Array.isArray(result) ? result[result.length - 1] : result;
7158
- if (typeof last !== "object" || last === null || !("rows" in last)) return [];
7159
- const rows = last.rows;
7160
- return Array.isArray(rows) ? rows : [];
7161
- }
7162
- //#endregion
7163
7578
  //#region src/services/dataService.ts
7164
7579
  /**
7165
7580
  * DataService - Facade for row operations.
@@ -9400,6 +9815,368 @@ var PgNotifyListener = class {
9400
9815
  }
9401
9816
  };
9402
9817
  //#endregion
9818
+ //#region src/pipelined-transaction.ts
9819
+ /**
9820
+ * A request's transaction, opened in the same round trip as its first query.
9821
+ *
9822
+ * Every request runs in a transaction that starts with two statements of its
9823
+ * own: `BEGIN`, and the `set_config` that hands Postgres the caller's identity
9824
+ * and drops to the restricted role (`authContextStatement`). Sent one after
9825
+ * the other, each waits for the last, and a lone read paid four round trips —
9826
+ * `BEGIN`, the context, the read, `COMMIT` — where the same read in SQL pays
9827
+ * one. Against a database a few milliseconds away that is most of the request.
9828
+ *
9829
+ * Postgres accepts several statements in one batch: the extended protocol's
9830
+ * Parse/Bind/Execute for each, then one Sync. The server runs them in order
9831
+ * and answers them together, so this sends nothing when the transaction is
9832
+ * opened and puts its opening statements in front of the first query instead.
9833
+ * Should one of them fail, the server skips the rest up to the Sync: a refused
9834
+ * role switch fails the batch before the query runs, with the same error a
9835
+ * statement of its own would have raised.
9836
+ *
9837
+ * A read-only transaction at READ COMMITTED goes one step further. Each of its
9838
+ * statements reads its own snapshot, so running each statement in a batch of
9839
+ * its own with the context in front — a transaction that ends at the Sync —
9840
+ * is the same transaction as far as anything inside it can tell, minus the
9841
+ * `BEGIN` and `COMMIT`. A lone read is then one round trip, as in SQL. A
9842
+ * statement that only means something inside a transaction block (a
9843
+ * savepoint, `SET LOCAL`, a cursor, a transaction-scoped lock) opens a real
9844
+ * one, from that statement on.
9845
+ *
9846
+ * Statement values are serialized by pg's own `prepareValue`, so a value means
9847
+ * the same here as in any other query; rows are parsed with the query's own
9848
+ * type parsers, as pg's `Query` parses them.
9849
+ */
9850
+ var COMMAND_TAG = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
9851
+ /**
9852
+ * Statements sent as one batch: Parse/Bind/Describe/Execute for each, one
9853
+ * Sync, one round trip. The last statement's result is the batch's; the
9854
+ * others are run for their effect and their rows are dropped unparsed.
9855
+ *
9856
+ * A pg {@link Submittable}, the interface pg-cursor is built on: pg writes
9857
+ * nothing for it but what `submit` writes, and hands it each message the
9858
+ * server sends back until ReadyForQuery.
9859
+ */
9860
+ var PipelinedQuery = class {
9861
+ /** How many statements this batch sends. */
9862
+ statementCount;
9863
+ /** Set by `client.query`, which wraps it for its read timeout. */
9864
+ callback;
9865
+ /** The statements, in the order they are sent, with their serialized values. */
9866
+ statements;
9867
+ rowMode;
9868
+ types;
9869
+ /** Statements ahead of the last whose completion has not arrived yet. */
9870
+ ahead;
9871
+ fields = [];
9872
+ parsers = [];
9873
+ rows = [];
9874
+ command = "";
9875
+ rowCount = null;
9876
+ oid = 0;
9877
+ rowError;
9878
+ settled = false;
9879
+ constructor(lead, last, callback) {
9880
+ this.statements = [...lead, last].map((statement) => ({
9881
+ text: statement.text,
9882
+ values: (statement.values ?? []).map((value) => prepareValue(value))
9883
+ }));
9884
+ this.statementCount = this.statements.length;
9885
+ this.ahead = lead.length;
9886
+ this.rowMode = last.rowMode;
9887
+ this.types = last.types ?? pg.types;
9888
+ this.callback = callback;
9889
+ }
9890
+ submit(connection) {
9891
+ connection.stream.cork();
9892
+ try {
9893
+ for (const statement of this.statements) {
9894
+ connection.parse({
9895
+ text: statement.text,
9896
+ name: "",
9897
+ types: []
9898
+ }, true);
9899
+ connection.bind({
9900
+ portal: "",
9901
+ statement: "",
9902
+ values: statement.values
9903
+ }, true);
9904
+ connection.describe({
9905
+ type: "P",
9906
+ name: ""
9907
+ }, true);
9908
+ connection.execute({ portal: "" }, true);
9909
+ }
9910
+ connection.sync();
9911
+ } finally {
9912
+ connection.stream.uncork();
9913
+ }
9914
+ }
9915
+ handleRowDescription(message) {
9916
+ if (this.ahead > 0) return;
9917
+ this.fields = message.fields;
9918
+ this.parsers = message.fields.map((field) => this.types.getTypeParser(field.dataTypeID, "text"));
9919
+ }
9920
+ handleDataRow(message) {
9921
+ if (this.ahead > 0 || this.rowError) return;
9922
+ const values = message.fields;
9923
+ try {
9924
+ if (this.rowMode === "array") {
9925
+ const row = new Array(values.length);
9926
+ for (let i = 0; i < values.length; i++) {
9927
+ const raw = values[i];
9928
+ row[i] = raw === null ? null : this.parsers[i](raw);
9929
+ }
9930
+ this.rows.push(row);
9931
+ } else {
9932
+ const row = {};
9933
+ for (let i = 0; i < values.length; i++) {
9934
+ const raw = values[i];
9935
+ row[this.fields[i].name] = raw === null ? null : this.parsers[i](raw);
9936
+ }
9937
+ this.rows.push(row);
9938
+ }
9939
+ } catch (error) {
9940
+ this.rowError = error instanceof Error ? error : new Error(String(error));
9941
+ }
9942
+ }
9943
+ handleCommandComplete(message) {
9944
+ if (this.ahead > 0) {
9945
+ this.ahead -= 1;
9946
+ return;
9947
+ }
9948
+ const match = COMMAND_TAG.exec(message.text);
9949
+ if (!match) return;
9950
+ this.command = match[1];
9951
+ if (match[3]) {
9952
+ this.oid = Number.parseInt(match[2], 10);
9953
+ this.rowCount = Number.parseInt(match[3], 10);
9954
+ } else if (match[2]) this.rowCount = Number.parseInt(match[2], 10);
9955
+ }
9956
+ /** An empty statement completes with EmptyQueryResponse rather than CommandComplete. */
9957
+ handleEmptyQuery() {
9958
+ if (this.ahead > 0) this.ahead -= 1;
9959
+ }
9960
+ handlePortalSuspended() {}
9961
+ handleError(error) {
9962
+ if (this.settled) return;
9963
+ this.settled = true;
9964
+ this.callback?.(error);
9965
+ }
9966
+ handleReadyForQuery() {
9967
+ if (this.settled) return;
9968
+ this.settled = true;
9969
+ if (this.rowError) {
9970
+ this.callback?.(this.rowError);
9971
+ return;
9972
+ }
9973
+ const result = {
9974
+ command: this.command,
9975
+ rowCount: this.rowCount,
9976
+ oid: this.oid,
9977
+ fields: this.fields,
9978
+ rows: this.rows
9979
+ };
9980
+ this.callback?.(null, result);
9981
+ }
9982
+ };
9983
+ /** Send `lead` and then `last` in one round trip; the result is `last`'s. */
9984
+ function runPipelined(client, lead, last) {
9985
+ return new Promise((resolve, reject) => {
9986
+ client.query(new PipelinedQuery(lead, last, (error, result) => {
9987
+ if (error) reject(error);
9988
+ else if (result) resolve(result);
9989
+ }));
9990
+ });
9991
+ }
9992
+ /**
9993
+ * A statement that means something only inside a transaction block, so a
9994
+ * read cannot run it in a batch of its own: savepoints, transaction-local
9995
+ * settings, cursors and transaction-scoped locks.
9996
+ */
9997
+ var NEEDS_TRANSACTION_BLOCK = /^\s*(?:savepoint|release|rollback|set\s+local|set\s+transaction|declare|lock|prepare\s+transaction)\b|\bset_config\s*\(|\bpg_advisory_xact_lock|\bpg_try_advisory_xact_lock/i;
9998
+ /**
9999
+ * A statement pg runs with a protocol of its own: COPY streams, a named
10000
+ * statement pg keeps track of, a portal read page by page. Sent as pg sends
10001
+ * it, after the transaction's opening has gone ahead in a batch of its own.
10002
+ */
10003
+ function cannotPipeline(config) {
10004
+ return Boolean(config.name) || Boolean(config.rows) || /^\s*copy\b/i.test(config.text);
10005
+ }
10006
+ function toQueryConfig(statement) {
10007
+ return {
10008
+ text: statement.text,
10009
+ values: statement.values ? [...statement.values] : void 0
10010
+ };
10011
+ }
10012
+ function beginStatement(config) {
10013
+ const parts = ["begin"];
10014
+ if (config?.isolationLevel) parts.push(`isolation level ${config.isolationLevel}`);
10015
+ if (config?.accessMode) parts.push(config.accessMode);
10016
+ if (typeof config?.deferrable === "boolean") parts.push(config.deferrable ? "deferrable" : "not deferrable");
10017
+ return parts.join(" ");
10018
+ }
10019
+ /**
10020
+ * Whether a transaction with these settings can run each statement in a batch
10021
+ * of its own. Read-only, at READ COMMITTED: every statement takes its own
10022
+ * snapshot there anyway, and none of them can write.
10023
+ */
10024
+ function runsStatementByStatement(config) {
10025
+ return config?.accessMode === "read only" && (config.isolationLevel === void 0 || config.isolationLevel === "read committed") && config.deferrable !== true;
10026
+ }
10027
+ /**
10028
+ * A savepoint being set or released: a statement with no result to wait for,
10029
+ * which can go out with whatever is sent next.
10030
+ */
10031
+ var DEFERRABLE = /^\s*(?:savepoint|release(?:\s+savepoint)?)\s+[A-Za-z_][A-Za-z0-9_]*\s*;?\s*$/i;
10032
+ var ROLLBACK_TO = /^\s*rollback\s+to\s+(?:savepoint\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*;?\s*$/i;
10033
+ function settledWithoutSending(text) {
10034
+ const command = text.trim().split(/\s+/)[0].toUpperCase();
10035
+ return Promise.resolve({
10036
+ command,
10037
+ rowCount: null,
10038
+ oid: 0,
10039
+ fields: [],
10040
+ rows: []
10041
+ });
10042
+ }
10043
+ /**
10044
+ * The client side of one transaction: sends its opening with the first query,
10045
+ * holds savepoints back until a statement goes out after them, and sends
10046
+ * `COMMIT` or `ROLLBACK` only when something was sent.
10047
+ */
10048
+ var TransactionOpening = class {
10049
+ client;
10050
+ begin;
10051
+ opening;
10052
+ statementByStatement;
10053
+ /** `fresh`: nothing sent. `implicit`: each statement ran in a batch of its own. `open`: in a transaction block. */
10054
+ state = "fresh";
10055
+ /** In a block: statements accepted and not yet sent, which go out ahead of the next one. */
10056
+ pending = [];
10057
+ /** In a block: whether its `BEGIN` has reached the server. */
10058
+ begun = false;
10059
+ constructor(client, begin, opening, statementByStatement) {
10060
+ this.client = client;
10061
+ this.begin = begin;
10062
+ this.opening = opening;
10063
+ this.statementByStatement = statementByStatement;
10064
+ }
10065
+ /** The `query` the transaction's drizzle session calls. Decides synchronously, so concurrent calls queue in order. */
10066
+ query(config, values) {
10067
+ const statement = typeof config === "string" ? {
10068
+ text: config,
10069
+ values
10070
+ } : values !== void 0 ? {
10071
+ ...config,
10072
+ values
10073
+ } : config;
10074
+ const pipelinable = !cannotPipeline(statement);
10075
+ if (this.state !== "open") {
10076
+ if (this.statementByStatement && pipelinable && !NEEDS_TRANSACTION_BLOCK.test(statement.text)) {
10077
+ this.state = "implicit";
10078
+ return runPipelined(this.client, [READ_ONLY_STATEMENT, ...this.opening], statement);
10079
+ }
10080
+ this.state = "open";
10081
+ this.pending = [{ text: this.begin }, ...this.opening];
10082
+ }
10083
+ const rollbackTo = ROLLBACK_TO.exec(statement.text);
10084
+ if (rollbackTo) {
10085
+ const at = this.pending.findLastIndex((pending) => pending.text.trim().toLowerCase() === `savepoint ${rollbackTo[1].toLowerCase()}`);
10086
+ if (at >= 0) {
10087
+ this.pending = this.pending.slice(0, at);
10088
+ return settledWithoutSending(statement.text);
10089
+ }
10090
+ }
10091
+ if (DEFERRABLE.test(statement.text) && !statement.values?.length) {
10092
+ this.pending.push({ text: statement.text });
10093
+ return settledWithoutSending(statement.text);
10094
+ }
10095
+ return this.send(statement, pipelinable);
10096
+ }
10097
+ /** `statement`, with everything pending in front of it. */
10098
+ send(statement, pipelinable = true) {
10099
+ const lead = this.pending;
10100
+ this.pending = [];
10101
+ if (lead.length > 0) this.begun = true;
10102
+ if (lead.length === 0) return this.client.query(statement);
10103
+ if (pipelinable) return runPipelined(this.client, lead, statement);
10104
+ return runPipelined(this.client, lead.slice(0, -1), toQueryConfig(lead[lead.length - 1])).then(() => this.client.query(statement));
10105
+ }
10106
+ async commit() {
10107
+ if (this.state === "open" && this.begun) await this.send({ text: "commit" });
10108
+ this.pending = [];
10109
+ }
10110
+ async rollback() {
10111
+ this.pending = [];
10112
+ if (this.state === "open" && this.begun) await this.client.query("rollback");
10113
+ }
10114
+ };
10115
+ /**
10116
+ * What `SET TRANSACTION READ ONLY` sets, as a statement that can run in a batch
10117
+ * outside a transaction block — where `SET TRANSACTION` warns and does nothing.
10118
+ */
10119
+ var READ_ONLY_STATEMENT = { text: "SELECT set_config('transaction_read_only', 'on', true)" };
10120
+ /** The relational schema a drizzle handle was built with, for a session over another client. */
10121
+ function schemaConfigOf(db) {
10122
+ const { schema, fullSchema, tableNamesMap } = db._;
10123
+ return schema && fullSchema ? {
10124
+ schema,
10125
+ fullSchema,
10126
+ tableNamesMap
10127
+ } : void 0;
10128
+ }
10129
+ var dialect = new PgDialect();
10130
+ /**
10131
+ * The drizzle handle and pg pool to run a pipelined transaction on, or
10132
+ * `undefined` for a handle that is not a drizzle database over a pg pool of
10133
+ * this process's pg (PGlite, a transaction, a caller's own copy of either
10134
+ * library), which opens its transactions statement by statement.
10135
+ */
10136
+ function pipelineTarget(db) {
10137
+ if (!(db instanceof NodePgDatabase) || !("$client" in db)) return void 0;
10138
+ const client = db.$client;
10139
+ return client instanceof pg.Pool ? {
10140
+ db,
10141
+ pool: client
10142
+ } : void 0;
10143
+ }
10144
+ /**
10145
+ * Run `work` in a transaction on a client of `pool`, its opening sent with the
10146
+ * first query.
10147
+ *
10148
+ * `opening` runs at the start of the transaction, after the `BEGIN` that
10149
+ * `config` describes — and, for a read-only transaction at READ COMMITTED,
10150
+ * ahead of every statement, each in a transaction of its own (see the module
10151
+ * comment). `work` gets a drizzle transaction like the one
10152
+ * `db.transaction()` hands out: savepoints nest inside it, and it commits
10153
+ * when `work` resolves and rolls back when it throws.
10154
+ */
10155
+ async function runPipelinedTransaction(db, pool, opening, config, work) {
10156
+ const client = await pool.connect();
10157
+ const transaction = new TransactionOpening(client, beginStatement(config), opening, runsStatementByStatement(config));
10158
+ const sessionClient = new Proxy(client, { get(target, property) {
10159
+ if (property === "query") return transaction.query.bind(transaction);
10160
+ const value = Reflect.get(target, property, target);
10161
+ return typeof value === "function" ? value.bind(target) : value;
10162
+ } });
10163
+ const schema = schemaConfigOf(db);
10164
+ const tx = new NodePgTransaction(dialect, new NodePgSession(sessionClient, dialect, schema), schema);
10165
+ try {
10166
+ let result;
10167
+ try {
10168
+ result = await work(tx);
10169
+ } catch (error) {
10170
+ await transaction.rollback();
10171
+ throw error;
10172
+ }
10173
+ await transaction.commit();
10174
+ return result;
10175
+ } finally {
10176
+ client.release();
10177
+ }
10178
+ }
10179
+ //#endregion
9403
10180
  //#region src/read-routing.ts
9404
10181
  var DEFAULT_READ_STICKY_MS = 5e3;
9405
10182
  var DEFAULT_READ_MAX_LAG_MS = 1e3;
@@ -10267,9 +11044,9 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10267
11044
  * property) the callback sits on.
10268
11045
  */
10269
11046
  assertAggregateUnmasked(path, options) {
10270
- if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => aggregate.fn === "count" && !aggregate.field)) return;
11047
+ if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => (aggregate.fn === "count" || aggregate.fn === "fingerprint") && !aggregate.field)) return;
10271
11048
  if (!PostgresBackendDriver.hasAfterRead(this.resolveCollectionCallbacks(void 0, path))) return;
10272
- throw ApiError.badRequest(`Aggregates other than count are refused on a collection whose rows an afterRead callback rewrites ("${path}"): a sum, average, minimum, maximum, field count or group would read the stored values the callback hides. Use \`count()\` without \`groupBy\`, or read the rows.`, "AGGREGATE_MASKED_BY_AFTER_READ", { collection: path });
11049
+ throw ApiError.badRequest(`Aggregates other than count are refused on a collection whose rows an afterRead callback rewrites ("${path}"): a sum, average, minimum, maximum, field count or group would read the stored values the callback hides. Use \`count()\` or \`fingerprint()\` without \`groupBy\`, or read the rows.`, "AGGREGATE_MASKED_BY_AFTER_READ", { collection: path });
10273
11050
  }
10274
11051
  /**
10275
11052
  * Apply afterRead to REST/SDK read results.
@@ -10298,7 +11075,6 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10298
11075
  async applyAfterReadForRest(rows, path) {
10299
11076
  if (!rows || rows.length === 0) return rows;
10300
11077
  const resolved = this.resolveCollectionCallbacks(void 0, path);
10301
- const contextForCallback = this.buildCallContext();
10302
11078
  const hasOwn = PostgresBackendDriver.hasAfterRead(resolved);
10303
11079
  const relationTargets = {};
10304
11080
  if (resolved.collection) try {
@@ -10317,6 +11093,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10317
11093
  const relKeys = Object.keys(relationTargets);
10318
11094
  if (!hasOwn && relKeys.length === 0) return rows;
10319
11095
  currentWriteScope()?.noteApplicationCode();
11096
+ const contextForCallback = this.buildCallContext();
10320
11097
  const maskEmbedded = async (value, target) => {
10321
11098
  if (Array.isArray(value)) return Promise.all(value.map((v) => maskEmbedded(v, target)));
10322
11099
  if (!value || typeof value !== "object") return value;
@@ -10644,7 +11421,94 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10644
11421
  row
10645
11422
  };
10646
11423
  }
11424
+ /**
11425
+ * Refuse a write to a collection that serves a SQL view; see
11426
+ * `view-access.ts`. A path this cannot resolve is the write's own to
11427
+ * answer — this refuses views, and never fails a write over a lookup.
11428
+ */
11429
+ assertWritable(collection, path) {
11430
+ let resolved = collection;
11431
+ if (!resolved) try {
11432
+ resolved = this.resolveCollectionCallbacks(void 0, path).collection;
11433
+ } catch {
11434
+ return;
11435
+ }
11436
+ assertCollectionWritable(resolved, path);
11437
+ }
11438
+ /**
11439
+ * The stamps a write takes after its hooks: `autoValue` dates and acting
11440
+ * users, and on an update the create-time stamps dropped, which record who
11441
+ * made the row and when — facts no later write can change.
11442
+ */
11443
+ stampAutoValues(collection, values, status, path) {
11444
+ if (!collection?.properties) return values;
11445
+ let stamped = updateDateAutoValues({
11446
+ inputValues: values,
11447
+ properties: collection.properties,
11448
+ status,
11449
+ timestampNowValue: /* @__PURE__ */ new Date()
11450
+ });
11451
+ assertActingUserForAutoValues(collection.properties, status, this.user?.uid, path);
11452
+ stamped = updateUserAutoValues({
11453
+ inputValues: stamped,
11454
+ properties: collection.properties,
11455
+ status,
11456
+ uid: this.user?.uid
11457
+ });
11458
+ if (status === "existing") {
11459
+ const kept = { ...stamped };
11460
+ for (const key of createStampKeys(collection.properties)) delete kept[key];
11461
+ stamped = kept;
11462
+ }
11463
+ return stamped;
11464
+ }
11465
+ /**
11466
+ * What the caller reads of a row it just wrote: the stored row through the
11467
+ * `afterRead` hooks, on a copy, so a hook that edits its argument in place
11468
+ * edits only the view. The stored row itself is what `afterSave` judges and
11469
+ * history records.
11470
+ */
11471
+ async viewOfSavedRow(storedRow, collection, path, hooks, context) {
11472
+ const { callbacks, globalCallbacks, propertyCallbacks } = hooks;
11473
+ if (!storedRow || !(globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) return storedRow;
11474
+ const callbackCollection = requireCallbackCollection(collection, path);
11475
+ let savedRow = { ...storedRow };
11476
+ if (globalCallbacks?.afterRead) savedRow = await globalCallbacks.afterRead({
11477
+ collection: callbackCollection,
11478
+ path,
11479
+ row: savedRow,
11480
+ context
11481
+ }) ?? savedRow;
11482
+ if (callbacks?.afterRead) savedRow = await callbacks.afterRead({
11483
+ collection: callbackCollection,
11484
+ path,
11485
+ row: savedRow,
11486
+ context
11487
+ }) ?? savedRow;
11488
+ if (propertyCallbacks?.afterRead) savedRow = await propertyCallbacks.afterRead({
11489
+ collection: callbackCollection,
11490
+ path,
11491
+ row: savedRow,
11492
+ context
11493
+ }) ?? savedRow;
11494
+ return savedRow;
11495
+ }
11496
+ /**
11497
+ * Whether a write to `collection` has to read the stored row before it
11498
+ * writes: for the hooks and history that are handed it, the tenancy and
11499
+ * per-field rules that judge it, a `beforeQuery` that scopes which rows
11500
+ * the caller addresses, the trash an update must not reach, and a nested
11501
+ * path, which reads its row from elsewhere. Without any of those the write
11502
+ * itself is the read — an UPDATE that matches nothing is the 404, an
11503
+ * upsert's conflict branch finds the stored row.
11504
+ */
11505
+ writeReadsStoredRow(collection, path, hooks) {
11506
+ if (!collection) return true;
11507
+ const { callbacks, globalCallbacks, propertyCallbacks } = hooks;
11508
+ return Boolean(callbacks?.beforeSave || globalCallbacks?.beforeSave || propertyCallbacks?.beforeSave || callbacks?.afterSave || globalCallbacks?.afterSave || propertyCallbacks?.afterSave || callbacks?.afterSaveError || globalCallbacks?.afterSaveError || propertyCallbacks?.afterSaveError || callbacks?.beforeQuery || globalCallbacks?.beforeQuery || collection.history || getTenantConfig(collection) || hasFieldAccessRules(collection) || resolveSoftDelete(collection) || isNestedPath(path));
11509
+ }
10647
11510
  async save(props) {
11511
+ this.assertWritable(props.collection, props.path);
10648
11512
  return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame));
10649
11513
  }
10650
11514
  async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored) {
@@ -10659,7 +11523,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10659
11523
  const preconditionFirst = precondition !== void 0 && status === "existing" && Boolean(id);
10660
11524
  if (!preconditionFirst) assertUpdateShape();
10661
11525
  const upserting = upsert === true && status !== "existing";
10662
- if (upserting && resolvedCollection) {
11526
+ const hooks = {
11527
+ callbacks,
11528
+ globalCallbacks,
11529
+ propertyCallbacks
11530
+ };
11531
+ const readsStoredRow = this.writeReadsStoredRow(resolvedCollection, path, hooks);
11532
+ if (upserting && resolvedCollection && readsStoredRow) {
10663
11533
  const stored = await this.findUpsertTarget(path, resolvedCollection, values, id, onConflict);
10664
11534
  if (stored) {
10665
11535
  const reusable = !callbacks?.beforeQuery && !globalCallbacks?.beforeQuery && !hasFieldAccessRules(resolvedCollection) && !isNestedPath(path);
@@ -10676,7 +11546,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10676
11546
  const contextForCallback = this.buildCallContext();
10677
11547
  if ((status === "new" || status === "copy") && resolvedCollection?.properties) updatedValues = applyDefaultValuesOnCreate(updatedValues, resolvedCollection.properties);
10678
11548
  let previousValuesForHistory;
10679
- if (status === "existing" && id) try {
11549
+ const unreadRow = status === "existing" && Boolean(id) && !precondition && !readsStoredRow;
11550
+ if (status === "existing" && id && !unreadRow) try {
10680
11551
  const withDeleted = restoresSoftDeletedRow(resolvedCollection, values) ? true : void 0;
10681
11552
  if (precondition?.lock) await this.dataService.getPersistService().lockRow(path, id);
10682
11553
  const storedPath = this.storedRowPath(path);
@@ -10742,26 +11613,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10742
11613
  }
10743
11614
  const afterHooks = updatedValues;
10744
11615
  if (status === "existing" && isPresentKey(id)) assertKeyUnchanged(resolvedCollection, this.registry, id, updatedValues, path);
10745
- if (resolvedCollection?.properties) {
10746
- updatedValues = updateDateAutoValues({
10747
- inputValues: updatedValues,
10748
- properties: resolvedCollection.properties,
10749
- status: status ?? "new",
10750
- timestampNowValue: /* @__PURE__ */ new Date()
10751
- });
10752
- assertActingUserForAutoValues(resolvedCollection.properties, status ?? "new", this.user?.uid, path);
10753
- updatedValues = updateUserAutoValues({
10754
- inputValues: updatedValues,
10755
- properties: resolvedCollection.properties,
10756
- status: status ?? "new",
10757
- uid: this.user?.uid
10758
- });
10759
- if (status === "existing") {
10760
- const kept = { ...updatedValues };
10761
- for (const key of createStampKeys(resolvedCollection.properties)) delete kept[key];
10762
- updatedValues = kept;
10763
- }
10764
- }
11616
+ updatedValues = this.stampAutoValues(resolvedCollection, updatedValues, status ?? "new", path);
10765
11617
  updatedValues = await this.applyTenantScope(resolvedCollection, path, updatedValues, status ?? "new", previousValuesForHistory);
10766
11618
  let writeId = id;
10767
11619
  if ((status === "new" || status === "copy") && !upsert && isPresentKey(id) && resolvedCollection) {
@@ -10778,31 +11630,14 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10778
11630
  const storedRow = await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, {
10779
11631
  upsert: upserting,
10780
11632
  onConflict,
10781
- insertOnlyKeys
11633
+ insertOnlyKeys,
11634
+ unreadRow
10782
11635
  });
10783
- let savedRow = storedRow;
10784
- if (storedRow && (globalCallbacks?.afterRead || callbacks?.afterRead || propertyCallbacks?.afterRead)) {
10785
- const callbackCollection = requireCallbackCollection(resolvedCollection, path);
10786
- savedRow = { ...storedRow };
10787
- if (globalCallbacks?.afterRead) savedRow = await globalCallbacks.afterRead({
10788
- collection: callbackCollection,
10789
- path,
10790
- row: savedRow,
10791
- context: contextForCallback
10792
- }) ?? savedRow;
10793
- if (callbacks?.afterRead) savedRow = await callbacks.afterRead({
10794
- collection: callbackCollection,
10795
- path,
10796
- row: savedRow,
10797
- context: contextForCallback
10798
- }) ?? savedRow;
10799
- if (propertyCallbacks?.afterRead) savedRow = await propertyCallbacks.afterRead({
10800
- collection: callbackCollection,
10801
- path,
10802
- row: savedRow,
10803
- context: contextForCallback
10804
- }) ?? savedRow;
10805
- }
11636
+ const savedRow = await this.viewOfSavedRow(storedRow, resolvedCollection, path, {
11637
+ callbacks,
11638
+ globalCallbacks,
11639
+ propertyCallbacks
11640
+ }, contextForCallback);
10806
11641
  const savedId = deriveRowAddress(storedRow, resolvedCollection ?? collection, this.registry);
10807
11642
  const savedValues = storedRow;
10808
11643
  try {
@@ -10965,6 +11800,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10965
11800
  return txDriver.buildCallContext();
10966
11801
  }
10967
11802
  async saveMany({ path, rows, collection, upsert, onConflict }) {
11803
+ this.assertWritable(collection, path);
11804
+ if (rows.length > 1 && this.writesRowsTogether(collection, path)) try {
11805
+ const together = await this.inBatchTransaction((txDriver) => txDriver.saveRowsTogether(path, rows, collection, upsert === true, onConflict));
11806
+ if (together) return together;
11807
+ } catch (error) {
11808
+ 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) });
11809
+ }
10968
11810
  return this.inBatchTransaction(async (txDriver) => {
10969
11811
  const saved = [];
10970
11812
  for (let i = 0; i < rows.length; i++) {
@@ -10992,6 +11834,112 @@ var PostgresBackendDriver = class PostgresBackendDriver {
10992
11834
  });
10993
11835
  }
10994
11836
  /**
11837
+ * Whether {@link saveMany} may write a collection's rows together
11838
+ * ({@link saveRowsTogether}): no `beforeSave`, `afterSave` or
11839
+ * `afterSaveError` hook, no history and no tenancy, at its own path. A
11840
+ * hook runs once per row between that row's writes, and history and
11841
+ * tenancy read per row, so those batches keep the row-by-row pipeline.
11842
+ */
11843
+ writesRowsTogether(collection, path) {
11844
+ const { collection: resolved, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11845
+ if (!resolved || isNestedPath(path) || resolved.history || getTenantConfig(resolved)) return false;
11846
+ return [
11847
+ callbacks,
11848
+ globalCallbacks,
11849
+ propertyCallbacks
11850
+ ].every((tier) => !tier?.beforeSave && !tier?.afterSave && !tier?.afterSaveError);
11851
+ }
11852
+ /**
11853
+ * {@link saveMany}'s rows written together, a few multi-row statements in
11854
+ * place of one statement per row (`PersistService.saveRows`), and answered
11855
+ * as {@link save} answers each: defaults and `autoValue` stamps applied,
11856
+ * the stored row through `afterRead`, a realtime event per row.
11857
+ *
11858
+ * For a collection {@link writesRowsTogether} allows; `undefined`, before
11859
+ * anything is written, for a batch `saveRows` declines. Its realtime events
11860
+ * join the transaction's only once every row is answered.
11861
+ */
11862
+ async saveRowsTogether(path, rows, collection, upsert, onConflict) {
11863
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11864
+ const resolved = resolvedCollection;
11865
+ if (!resolved) return void 0;
11866
+ const hooks = {
11867
+ callbacks,
11868
+ globalCallbacks,
11869
+ propertyCallbacks
11870
+ };
11871
+ const softDeleteField = resolveSoftDelete(resolved)?.field;
11872
+ const prepared = rows.map((values) => {
11873
+ const withDefaults = resolved.properties ? applyDefaultValuesOnCreate(values, resolved.properties) : values;
11874
+ const stamped = this.stampAutoValues(resolved, withDefaults, "new", path);
11875
+ const insertOnlyKeys = upsert ? insertOnlyKeysOf(stamped, values, withDefaults, withDefaults, resolved.properties) : void 0;
11876
+ if (insertOnlyKeys && softDeleteField && stamped[softDeleteField] !== void 0 && stamped[softDeleteField] !== null) insertOnlyKeys.push(softDeleteField);
11877
+ return {
11878
+ values: stamped,
11879
+ insertOnlyKeys
11880
+ };
11881
+ });
11882
+ const stored = await this.dataService.getPersistService().saveRows(path, prepared, {
11883
+ upsert,
11884
+ onConflict
11885
+ });
11886
+ if (!stored) return void 0;
11887
+ return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, hooks);
11888
+ }
11889
+ /**
11890
+ * {@link updateMany}'s updates written together (`PersistService.updateRows`)
11891
+ * and answered as {@link save} answers each: the `on_update` stamps
11892
+ * applied, the stored row through `afterRead`, a realtime event per row.
11893
+ * For a collection {@link writesRowsTogether} allows; `undefined`, before
11894
+ * anything is written, for updates `updateRows` declines.
11895
+ */
11896
+ async updateRowsTogether(path, updates, collection) {
11897
+ const { collection: resolvedCollection, callbacks, globalCallbacks, propertyCallbacks } = this.resolveCollectionCallbacks(collection, path);
11898
+ const resolved = resolvedCollection;
11899
+ if (!resolved) return void 0;
11900
+ const prepared = updates.map(({ id, values }) => {
11901
+ assertUpdateDoesNotSoftDelete(resolved, values, path);
11902
+ assertKeyUnchanged(resolved, this.registry, String(id), values, path);
11903
+ return {
11904
+ id,
11905
+ values: this.stampAutoValues(resolved, values, "existing", path)
11906
+ };
11907
+ });
11908
+ const stored = await this.dataService.getPersistService().updateRows(path, prepared);
11909
+ if (!stored) return void 0;
11910
+ return this.answerRowsWritten(stored, prepared.map((row) => row.values), resolved, path, {
11911
+ callbacks,
11912
+ globalCallbacks,
11913
+ propertyCallbacks
11914
+ });
11915
+ }
11916
+ /**
11917
+ * Rows a batch wrote, answered as {@link save} answers one: each through
11918
+ * `afterRead`, and a realtime event per row, joining the transaction's
11919
+ * only once every row is answered.
11920
+ */
11921
+ async answerRowsWritten(stored, written, collection, path, hooks) {
11922
+ const context = this.buildCallContext();
11923
+ const primaryKeys = getPrimaryKeys(collection, this.registry);
11924
+ const saved = [];
11925
+ const notifications = [];
11926
+ for (let i = 0; i < stored.length; i++) {
11927
+ const storedRow = stored[i];
11928
+ const savedRow = await this.viewOfSavedRow(storedRow, collection, path, hooks, context);
11929
+ const savedId = deriveRowAddress(storedRow, collection, this.registry, primaryKeys);
11930
+ notifications.push({
11931
+ path,
11932
+ id: savedId,
11933
+ row: savedRow,
11934
+ databaseId: collection.databaseId
11935
+ }, ...this.childListNotifications(collection, savedId, written[i]));
11936
+ saved.push(savedRow);
11937
+ }
11938
+ if (this._deferNotifications) this._pendingNotifications.push(...notifications);
11939
+ else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId);
11940
+ return saved;
11941
+ }
11942
+ /**
10995
11943
  * Update many rows through the same pipeline as {@link save}, in one
10996
11944
  * transaction.
10997
11945
  *
@@ -11007,6 +11955,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11007
11955
  * half landed without re-reading everything.
11008
11956
  */
11009
11957
  async updateMany({ path, updates, collection }) {
11958
+ this.assertWritable(collection, path);
11959
+ if (updates.length > 1 && this.writesRowsTogether(collection, path)) try {
11960
+ const together = await this.inBatchTransaction((txDriver) => txDriver.updateRowsTogether(path, updates, collection));
11961
+ if (together) return together;
11962
+ } catch (error) {
11963
+ logger.debug(`[updateMany] A batch update of "${path}" failed; updating its rows one by one to name the row`, { detail: error instanceof Error ? error.message : String(error) });
11964
+ }
11010
11965
  return this.inBatchTransaction(async (txDriver) => {
11011
11966
  const saved = [];
11012
11967
  for (let i = 0; i < updates.length; i++) {
@@ -11043,6 +11998,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11043
11998
  * happened to delete at once. Same pipeline, one transaction.
11044
11999
  */
11045
12000
  async deleteMany({ path, ids, collection, hard }) {
12001
+ this.assertWritable(collection, path);
11046
12002
  await this.inBatchTransaction(async (txDriver) => {
11047
12003
  for (let i = 0; i < ids.length; i++) {
11048
12004
  const id = ids[i];
@@ -11148,6 +12104,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11148
12104
  });
11149
12105
  }
11150
12106
  async delete(props) {
12107
+ this.assertWritable(props.collection, props.row.path);
11151
12108
  return inWriteFrame(props.row.path, "delete", (frame) => this.deleteInFrame(props, frame));
11152
12109
  }
11153
12110
  async deleteInFrame({ row, collection, hard, precondition }, frame) {
@@ -11274,11 +12231,26 @@ var PostgresBackendDriver = class PostgresBackendDriver {
11274
12231
  databaseId: collection.databaseId
11275
12232
  }));
11276
12233
  }
12234
+ /**
12235
+ * Recompute the rows of a collection that serves a materialized view,
12236
+ * on this driver's connection — the owner's on the base driver, which a
12237
+ * refresh needs: Postgres lets only a view's owner refresh it.
12238
+ */
12239
+ async refreshView(path, options) {
12240
+ const collection = this.resolveCollectionCallbacks(void 0, path).collection;
12241
+ if (!collection || !isPostgresCollectionConfig(collection) || !collection.view?.materialized) throw ApiError.badRequest(`"${collection?.slug ?? path}" is not a materialized view, so there is nothing to refresh.`, "NOT_A_MATERIALIZED_VIEW");
12242
+ const schema = collection.schema ?? "public";
12243
+ const qualified = sql`${sql.identifier(schema)}.${sql.identifier(getTableName$1(collection))}`;
12244
+ await this.db.execute(options?.concurrently ? sql`REFRESH MATERIALIZED VIEW CONCURRENTLY ${qualified}` : sql`REFRESH MATERIALIZED VIEW ${qualified}`);
12245
+ await this.realtimeService.notifyUpdate(path, "*", null);
12246
+ }
11277
12247
  async deleteAll(path) {
12248
+ this.assertWritable(void 0, path);
11278
12249
  await this.dataService.deleteAll(path);
11279
12250
  await this.realtimeService.notifyUpdate(path, "*", null);
11280
12251
  }
11281
12252
  async updateRelationPivot({ path, targetId, pivot }) {
12253
+ this.assertWritable(void 0, path);
11282
12254
  await this.dataService.updateRelationPivot(path, targetId, pivot);
11283
12255
  if (this.realtimeService.isCdcActive()) return;
11284
12256
  const notification = {
@@ -11835,7 +12807,8 @@ var AuthenticatedPostgresBackendDriver = class {
11835
12807
  return router.db;
11836
12808
  }
11837
12809
  async runTransaction(db, operation, options) {
11838
- const transactionSettings = transactionSettingsStatements(pooledTransactionSettings("$client" in db ? db.$client : void 0));
12810
+ const pooledSettings = pooledTransactionSettings("$client" in db ? db.$client : void 0);
12811
+ const pipelined = pipelineTarget(db);
11839
12812
  const pendingNotifications = [];
11840
12813
  const writeScope = options?.accessMode === "read only" ? void 0 : new WriteTransactionScope();
11841
12814
  const client = this.delegate.client;
@@ -11849,33 +12822,44 @@ var AuthenticatedPostgresBackendDriver = class {
11849
12822
  },
11850
12823
  storageSource: client?.storage
11851
12824
  });
11852
- const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => db.transaction(async (tx) => {
11853
- if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
11854
- if (!this.user?.uid) logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
11855
- if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
11856
- await applyAuthContext(tx, authContextOf(this.user), this.delegate.rlsUserRole);
11857
- let hookContext;
11858
- const txEntityService = new DataService(tx, this.delegate.registry, () => {
11859
- writeScope?.noteApplicationCode();
11860
- return hookContext ??= this.delegate.callContextWithin(tx, this.user);
11861
- });
11862
- const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
11863
- txDelegate.dataService = txEntityService;
11864
- txDelegate._deferNotifications = true;
11865
- txDelegate._pendingNotifications = pendingNotifications;
11866
- txDelegate.client = this.delegate.client;
11867
- writeScope?.bind(tx, (sqlText, params) => txEntityService.executeSql(sqlText, params));
11868
- let out;
11869
- try {
11870
- out = await operation(txDelegate);
11871
- } catch (error) {
11872
- writeScope?.close();
11873
- throw error;
12825
+ const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () => {
12826
+ const inTransaction = async (tx) => {
12827
+ if (!this.user?.uid) logger.warn("[DataDriver] User ID (uid) is missing for authenticated delegate. Using 'anonymous'. User object", { detail: this.user });
12828
+ if (!this.user?.roles) logger.warn("[DataDriver] User roles are missing for authenticated delegate. Using empty array. User object", { detail: this.user });
12829
+ let hookContext;
12830
+ const txEntityService = new DataService(tx, this.delegate.registry, () => {
12831
+ writeScope?.noteApplicationCode();
12832
+ return hookContext ??= this.delegate.callContextWithin(tx, this.user);
12833
+ });
12834
+ const txDelegate = new PostgresBackendDriver(tx, this.delegate.realtimeService, this.delegate.registry, this.user, this.delegate.poolManager, this.delegate.historyService);
12835
+ txDelegate.dataService = txEntityService;
12836
+ txDelegate._deferNotifications = true;
12837
+ txDelegate._pendingNotifications = pendingNotifications;
12838
+ txDelegate.client = this.delegate.client;
12839
+ writeScope?.bind(tx, (sqlText, params) => txEntityService.executeSql(sqlText, params));
12840
+ let out;
12841
+ try {
12842
+ out = await operation(txDelegate);
12843
+ } catch (error) {
12844
+ writeScope?.close();
12845
+ throw error;
12846
+ }
12847
+ await writeScope?.settle();
12848
+ await writeScope?.assertCommittable();
12849
+ return out;
12850
+ };
12851
+ const auth = authContextOf(this.user);
12852
+ if (pipelined) {
12853
+ const opening = authContextStatement(auth, this.delegate.rlsUserRole, transactionSettingsConfig(pooledSettings));
12854
+ return runPipelinedTransaction(pipelined.db, pipelined.pool, [opening], options, inTransaction);
11874
12855
  }
11875
- await writeScope?.settle();
11876
- await writeScope?.assertCommittable();
11877
- return out;
11878
- }, options)).finally(() => writeScope?.close())).catch(async (error) => {
12856
+ return db.transaction(async (tx) => {
12857
+ const transactionSettings = transactionSettingsStatements(pooledSettings);
12858
+ if (transactionSettings.length > 0) await tx.execute(sql.raw(transactionSettings.join("; ")));
12859
+ await applyAuthContext(tx, auth, this.delegate.rlsUserRole);
12860
+ return inTransaction(tx);
12861
+ }, options);
12862
+ }).finally(() => writeScope?.close())).catch(async (error) => {
11879
12863
  await writeScope?.settled();
11880
12864
  throw error;
11881
12865
  });
@@ -11956,6 +12940,16 @@ var AuthenticatedPostgresBackendDriver = class {
11956
12940
  async deleteAll(path) {
11957
12941
  return this.withTransaction((delegate) => delegate.deleteAll(path));
11958
12942
  }
12943
+ /**
12944
+ * For a caller holding one of the view's roles, refreshed on the owner's
12945
+ * connection rather than in this caller's transaction: Postgres lets only
12946
+ * the owner refresh, and the caller's restricted role is not it.
12947
+ */
12948
+ async refreshView(path, options) {
12949
+ const collection = this.delegate.registry?.getCollectionByPath(path);
12950
+ await withFieldViewer({ roles: (this.user?.roles ?? []).map((role) => typeof role === "string" ? role : String(role.id ?? role)) }, async () => assertViewReadable(collection));
12951
+ return this.delegate.refreshView(path, options);
12952
+ }
11959
12953
  async updateRelationPivot(props) {
11960
12954
  return this.withTransaction((delegate) => delegate.updateRelationPivot(props));
11961
12955
  }
@@ -21378,7 +22372,7 @@ async function openPostgresDriver(pgConfig, config) {
21378
22372
  let readRouter;
21379
22373
  let readPool;
21380
22374
  if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
21381
- const { createReadReplicaConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
22375
+ const { createReadReplicaConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
21382
22376
  const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
21383
22377
  ...pgConfig.poolConfig,
21384
22378
  pooled
@@ -21394,7 +22388,7 @@ async function openPostgresDriver(pgConfig, config) {
21394
22388
  let sessionDb;
21395
22389
  let sessionPool;
21396
22390
  if (pooled && directUrl) {
21397
- const { createDirectDatabaseConnection } = await import("./connection-CcYqncW5.js").then((n) => n.r);
22391
+ const { createDirectDatabaseConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
21398
22392
  const session = createDirectDatabaseConnection(directUrl, void 0, {
21399
22393
  max: 3,
21400
22394
  idleTimeoutMillis: 1e4
@@ -21499,7 +22493,7 @@ async function openPostgresDriver(pgConfig, config) {
21499
22493
  if (explicitCdc) logger.warn(`⚠️ [CDC] REALTIME_CDC=${cdcMode} but ${reason} — using app-level realtime.`);
21500
22494
  else logger.info(`ℹ️ [CDC] Using app-level realtime — ${reason}.`);
21501
22495
  } else if (wantsCdc && directUrl) {
21502
- const cdcTables = collectionsOnThisSource().map((c) => ({
22496
+ const cdcTables = collectionsOnThisSource().filter((c) => !(isPostgresCollectionConfig(c) && c.view)).map((c) => ({
21503
22497
  schema: c.schema ?? "public",
21504
22498
  table: getTableName$1(c),
21505
22499
  identityColumns: collectionKeyColumns(c, registry).map((k) => k.columnName)
@@ -21721,7 +22715,7 @@ function createPostgresBootstrapper(pgConfig) {
21721
22715
  const openIndexBuildSession = (driverResult) => async () => {
21722
22716
  const db = requireProvisioningDb(driverResult);
21723
22717
  const pool = "$client" in db ? db.$client : void 0;
21724
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
22718
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
21725
22719
  const config = effectiveConfig();
21726
22720
  if (isPooledPool(pool) || config.pooled) {
21727
22721
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -21752,7 +22746,7 @@ function createPostgresBootstrapper(pgConfig) {
21752
22746
  */
21753
22747
  const provisionRlsRuntime = async (driverResult) => {
21754
22748
  const db = requireProvisioningDb(driverResult);
21755
- const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-DPawvckr.js").then((n) => n.E);
22749
+ const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
21756
22750
  const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
21757
22751
  if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
21758
22752
  await db.transaction(async (tx) => {
@@ -21865,11 +22859,11 @@ function createPostgresBootstrapper(pgConfig) {
21865
22859
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
21866
22860
  }) };
21867
22861
  }
21868
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CIGoIGcC.js").then((n) => n.i);
22862
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
21869
22863
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21870
22864
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
21871
22865
  if (historyIndexes.length > 0) {
21872
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
22866
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
21873
22867
  const indexOptions = {
21874
22868
  log: (message) => logger.info(`[history] ${message}`),
21875
22869
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -21925,9 +22919,9 @@ function createPostgresBootstrapper(pgConfig) {
21925
22919
  * proved it can bootstrap with.
21926
22920
  */
21927
22921
  async ensureCollectionSchema(collections, driverResult, log) {
21928
- const { ensureCollectionTables } = await import("./ensure-collection-tables-DvaCEy6X.js").then((n) => n.n);
22922
+ const { ensureCollectionTables } = await import("./ensure-collection-tables-BK--gDo6.js").then((n) => n.n);
21929
22923
  const queryable = provisioningQueryable(driverResult);
21930
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-CIGoIGcC.js").then((n) => n.i);
22924
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
21931
22925
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
21932
22926
  const plan = await ensureCollectionTables(queryable, collections, log, {
21933
22927
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -21939,7 +22933,7 @@ function createPostgresBootstrapper(pgConfig) {
21939
22933
  pendingIndexBuild?.cancel();
21940
22934
  pendingIndexBuild = void 0;
21941
22935
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
21942
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-BwH6k1Og.js").then((n) => n.r);
22936
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
21943
22937
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
21944
22938
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
21945
22939
  log: (message) => logger.info(`[schema] ${message}`),
@@ -21979,7 +22973,7 @@ function createPostgresBootstrapper(pgConfig) {
21979
22973
  await provisionRlsRuntime(driverResult);
21980
22974
  },
21981
22975
  async ensureCollectionPolicies(collections, driverResult, log) {
21982
- const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-f0LIwiwp.js");
22976
+ const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-DUpWJb5D.js");
21983
22977
  const queryable = provisioningQueryable(driverResult);
21984
22978
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
21985
22979
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -22004,7 +22998,7 @@ function createPostgresBootstrapper(pgConfig) {
22004
22998
  for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from ${REBASE_USER_ROLE$1}, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
22005
22999
  if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + `, and the privileges granted to ${REBASE_USER_ROLE$1} could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.`);
22006
23000
  try {
22007
- const { dropLegacyAuthSchema } = await import("./migrate-baseline-DPawvckr.js").then((n) => n.E);
23001
+ const { dropLegacyAuthSchema } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
22008
23002
  await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
22009
23003
  info: (m) => logger.info(m),
22010
23004
  warn: (m) => logger.warn(m)
@@ -22095,7 +23089,7 @@ function createPostgresBootstrapper(pgConfig) {
22095
23089
  return driverResult.internals.driver.admin;
22096
23090
  },
22097
23091
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
22098
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-CCJnghvG.js").then((n) => n.c);
23092
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-D2y88dOa.js").then((n) => n.c);
22099
23093
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
22100
23094
  const realtimeConfig = effectiveConfig().realtime;
22101
23095
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -22240,4 +23234,4 @@ async function openRebase(options) {
22240
23234
  //#endregion
22241
23235
  export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
22242
23236
 
22243
- //# sourceMappingURL=open-rebase-DvmKIu7q.js.map
23237
+ //# sourceMappingURL=open-rebase-CTNBmmH8.js.map