@rebasepro/server-postgres 0.28.2 → 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.
- package/dist/{BranchService-BPssiD8_.js → BranchService-JiYJ_n9E.js} +3 -3
- package/dist/{BranchService-BPssiD8_.js.map → BranchService-JiYJ_n9E.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +147 -1
- package/dist/PostgresBootstrapper.d.ts +34 -1
- package/dist/{backup-cli-C1wcj-rc.js → backup-cli-D_aKXPyX.js} +3 -3
- package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-D_aKXPyX.js.map} +1 -1
- package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-D4W9o9xE.js} +2 -2
- package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-D4W9o9xE.js.map} +1 -1
- package/dist/{cli-console-C0FYkICX.js → cli-console-DPdZCWTi.js} +6 -6
- package/dist/{cli-console-C0FYkICX.js.map → cli-console-DPdZCWTi.js.map} +1 -1
- package/dist/{cli-errors-DYets7cp.js → cli-errors-D8s4z_3g.js} +26 -6
- package/dist/cli-errors-D8s4z_3g.js.map +1 -0
- package/dist/cli-helpers.d.ts +10 -0
- package/dist/cli.js +41 -35
- package/dist/cli.js.map +1 -1
- package/dist/{connection-czvI7TZL.js → connection-COuS5Fm-.js} +126 -36
- package/dist/connection-COuS5Fm-.js.map +1 -0
- package/dist/connection.d.ts +63 -0
- package/dist/database-health.d.ts +23 -0
- package/dist/{databasePoolManager-BjoVvuAq.js → databasePoolManager-7hXVurmG.js} +2 -2
- package/dist/{databasePoolManager-BjoVvuAq.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
- package/dist/{deferred-index-build-BcJ_oulu.js → deferred-index-build-F2GWu009.js} +34 -5
- package/dist/{deferred-index-build-BcJ_oulu.js.map → deferred-index-build-F2GWu009.js.map} +1 -1
- package/dist/{doctor-TJApVglQ.js → doctor-_g2tHRtG.js} +20 -6
- package/dist/doctor-_g2tHRtG.js.map +1 -0
- package/dist/{ensure-collection-policies-BNwSQfVx.js → ensure-collection-policies-DUpWJb5D.js} +8 -8
- package/dist/{ensure-collection-policies-BNwSQfVx.js.map → ensure-collection-policies-DUpWJb5D.js.map} +1 -1
- package/dist/{ensure-collection-tables-CSbgkTBx.js → ensure-collection-tables-BK--gDo6.js} +15 -9
- package/dist/ensure-collection-tables-BK--gDo6.js.map +1 -0
- package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Bx1DYarz.js} +4 -4
- package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Bx1DYarz.js.map} +1 -1
- package/dist/{enum-labels-kept-BCgFGAbJ.js → enum-labels-kept-DyFE4Gaq.js} +3 -3
- package/dist/{enum-labels-kept-BCgFGAbJ.js.map → enum-labels-kept-DyFE4Gaq.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-DpFA1UVd.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-DpFA1UVd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-taNTu3xv.js} +2 -2
- package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-taNTu3xv.js.map} +1 -1
- package/dist/{generate-files-DutUrsSS.js → generate-files-DbwU8Btx.js} +11 -4
- package/dist/generate-files-DbwU8Btx.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-ISVgsP34.js} +11 -4
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-ISVgsP34.js.map} +1 -1
- package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-4lOC0g1_.js} +21 -6
- package/dist/generated-schema-diff-4lOC0g1_.js.map +1 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.es.js +13 -13
- package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BeepEphh.js} +2 -2
- package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BeepEphh.js.map} +1 -1
- package/dist/{migrate-policy-stamps-B-8vTSIm.js → migrate-policy-stamps-cYMJ_9Ha.js} +7 -7
- package/dist/{migrate-policy-stamps-B-8vTSIm.js.map → migrate-policy-stamps-cYMJ_9Ha.js.map} +1 -1
- package/dist/{open-rebase-D9n8idex.js → open-rebase-CTNBmmH8.js} +1712 -164
- package/dist/open-rebase-CTNBmmH8.js.map +1 -0
- package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-BLOVXK67.js} +2 -2
- package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-BLOVXK67.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +131 -0
- package/dist/{plan-schema-DMVh77yb.js → plan-schema-CMNWvqIa.js} +62 -3
- package/dist/plan-schema-CMNWvqIa.js.map +1 -0
- package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-IjD2AUD-.js} +2 -2
- package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-IjD2AUD-.js.map} +1 -1
- package/dist/pooled-database.d.ts +38 -0
- package/dist/{push-index-prebuild-DR3P4yOw.js → push-index-prebuild-CIvajIrL.js} +4 -4
- package/dist/{push-index-prebuild-DR3P4yOw.js.map → push-index-prebuild-CIvajIrL.js.map} +1 -1
- package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CLbsuSmo.js} +2 -2
- package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CLbsuSmo.js.map} +1 -1
- package/dist/{push-legacy-renames-BIxBmVLl.js → push-legacy-renames-DeW_HTLJ.js} +4 -4
- package/dist/{push-legacy-renames-BIxBmVLl.js.map → push-legacy-renames-DeW_HTLJ.js.map} +1 -1
- package/dist/{push-policy-plan-BHsasXa7.js → push-policy-plan--oRXOj4X.js} +4 -4
- package/dist/{push-policy-plan-BHsasXa7.js.map → push-policy-plan--oRXOj4X.js.map} +1 -1
- package/dist/read-routing.d.ts +139 -0
- package/dist/{render-ddl-NpPPDACz.js → render-ddl-CzVcbbR1.js} +77 -3
- package/dist/render-ddl-CzVcbbR1.js.map +1 -0
- package/dist/{rls-enforcement-BOHuHVlc.js → rls-enforcement-jZTv1yci.js} +48 -16
- package/dist/{rls-enforcement-BOHuHVlc.js.map → rls-enforcement-jZTv1yci.js.map} +1 -1
- package/dist/schema/deferred-index-build.d.ts +9 -0
- package/dist/schema/doctor-cli.js +4 -4
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-files.d.ts +2 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +2 -2
- package/dist/schema/introspect-runtime.d.ts +10 -1
- package/dist/schema/plan/plan-schema.d.ts +9 -1
- package/dist/schema/plan/render-ddl.d.ts +25 -1
- package/dist/schema/plan/types.d.ts +24 -0
- package/dist/security/rls-enforcement.d.ts +11 -0
- package/dist/services/FetchService.d.ts +12 -12
- package/dist/services/PersistService.d.ts +59 -0
- package/dist/services/collection-helpers.d.ts +3 -1
- package/dist/services/view-access.d.ts +21 -0
- package/dist/{websocket-D4wrzF3b.js → websocket-D2y88dOa.js} +3 -3
- package/dist/{websocket-D4wrzF3b.js.map → websocket-D2y88dOa.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-errors-DYets7cp.js.map +0 -1
- package/dist/connection-czvI7TZL.js.map +0 -1
- package/dist/doctor-TJApVglQ.js.map +0 -1
- package/dist/ensure-collection-tables-CSbgkTBx.js.map +0 -1
- package/dist/generate-files-DutUrsSS.js.map +0 -1
- package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
- package/dist/open-rebase-D9n8idex.js.map +0 -1
- package/dist/plan-schema-DMVh77yb.js.map +0 -1
- 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 {
|
|
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,
|
|
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-
|
|
7
|
-
import { t as BranchService } from "./BranchService-
|
|
8
|
-
import { a as
|
|
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-
|
|
12
|
-
import { t as generateSchema } from "./generate-drizzle-schema-logic-
|
|
13
|
-
import { i as renderPgType } from "./render-ddl-
|
|
14
|
-
import { s as diffPlanAgainstCatalogue, u as typesAgree } from "./deferred-index-build-
|
|
15
|
-
import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-
|
|
16
|
-
import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-
|
|
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-
|
|
19
|
-
import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-
|
|
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-
|
|
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,
|
|
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
|
-
|
|
2540
|
-
|
|
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
|
|
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
|
|
2716
|
+
const { steps } = restRowPlan(collection);
|
|
2660
2717
|
const flat = {};
|
|
2661
|
-
for (const
|
|
2662
|
-
const
|
|
2663
|
-
|
|
2664
|
-
|
|
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
|
|
5595
|
-
|
|
5596
|
-
|
|
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
|
|
7004
|
-
|
|
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.
|
|
@@ -8296,7 +8711,10 @@ async function generateSchemaCommit(input) {
|
|
|
8296
8711
|
* This plans both, for a person to read. It relaxes every column the
|
|
8297
8712
|
* collections declare optional and the database still requires — the
|
|
8298
8713
|
* `drop-not-null` actions the live editor's `converge` policy already plans —
|
|
8299
|
-
* and it lists every column no collection declares.
|
|
8714
|
+
* and it lists every column no collection declares. An undeclared column that
|
|
8715
|
+
* blocks inserts (NOT NULL, no default) is relaxed too, unless it is being
|
|
8716
|
+
* dropped: that keeps its data and makes the table writable again, which is
|
|
8717
|
+
* the one thing a removed property must not prevent. It drops only the columns
|
|
8300
8718
|
* the caller names, one by one: removing a property is not consent to destroy
|
|
8301
8719
|
* the column's data, so the drop is a separate, explicit act.
|
|
8302
8720
|
*
|
|
@@ -8371,6 +8789,16 @@ function planSchemaReconcile(collections, existing, options = {}) {
|
|
|
8371
8789
|
}
|
|
8372
8790
|
problems.push(table.columns.some((c) => c.column === column) ? `"${request}": the "${slug}" collection still declares "${column}". Remove the property, deploy, then drop it.` : `"${request}": "${table.qualified}" has no column "${column}".`);
|
|
8373
8791
|
}
|
|
8792
|
+
for (const column of undeclared) {
|
|
8793
|
+
if (!column.blocksInserts || dropped.includes(column)) continue;
|
|
8794
|
+
relaxed.push({
|
|
8795
|
+
collection: column.collection,
|
|
8796
|
+
table: column.table,
|
|
8797
|
+
column: column.column,
|
|
8798
|
+
undeclared: true
|
|
8799
|
+
});
|
|
8800
|
+
relaxStatements.push(`ALTER TABLE ${relation(column.tablePlan)} ALTER COLUMN "${column.column}" DROP NOT NULL;`);
|
|
8801
|
+
}
|
|
8374
8802
|
const statements = [...relaxStatements, ...dropped.map((d) => `ALTER TABLE ${relation(d.tablePlan)} DROP COLUMN "${d.column}";`)];
|
|
8375
8803
|
const strip = ({ tablePlan: _table, ...column }) => column;
|
|
8376
8804
|
return {
|
|
@@ -9387,6 +9815,653 @@ var PgNotifyListener = class {
|
|
|
9387
9815
|
}
|
|
9388
9816
|
};
|
|
9389
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
|
|
10180
|
+
//#region src/read-routing.ts
|
|
10181
|
+
var DEFAULT_READ_STICKY_MS = 5e3;
|
|
10182
|
+
var DEFAULT_READ_MAX_LAG_MS = 1e3;
|
|
10183
|
+
var DEFAULT_SAMPLE_INTERVAL_MS = 1e3;
|
|
10184
|
+
var DEFAULT_FAILURE_COOLDOWN_MS = 1e4;
|
|
10185
|
+
var DEFAULT_MAX_PINNED = 1e4;
|
|
10186
|
+
/** A sample older than this many intervals is no evidence about the standby now. */
|
|
10187
|
+
var STALE_SAMPLE_INTERVALS = 3;
|
|
10188
|
+
var FAILURE_WARNING_INTERVAL_MS = 6e4;
|
|
10189
|
+
/**
|
|
10190
|
+
* Parse one of the routing variables: a whole number of milliseconds, zero
|
|
10191
|
+
* allowed. A value that is set and malformed throws, naming the variable — a
|
|
10192
|
+
* mistyped guard must not quietly become another number.
|
|
10193
|
+
*/
|
|
10194
|
+
function parseReadRoutingMs(raw, variable) {
|
|
10195
|
+
const trimmed = raw.trim();
|
|
10196
|
+
if (!/^[0-9]+$/.test(trimmed)) throw new Error(`${variable} must be a whole number of milliseconds, got "${raw}".`);
|
|
10197
|
+
return Number(trimmed);
|
|
10198
|
+
}
|
|
10199
|
+
/** The routing options from the environment, defaults filled in. */
|
|
10200
|
+
function readRoutingOptionsFromEnv(env) {
|
|
10201
|
+
const sticky = env.REBASE_READ_STICKY_MS?.trim();
|
|
10202
|
+
const lag = env.REBASE_READ_MAX_LAG_MS?.trim();
|
|
10203
|
+
return {
|
|
10204
|
+
stickyMs: sticky ? parseReadRoutingMs(sticky, "REBASE_READ_STICKY_MS") : DEFAULT_READ_STICKY_MS,
|
|
10205
|
+
maxLagMs: lag ? parseReadRoutingMs(lag, "REBASE_READ_MAX_LAG_MS") : DEFAULT_READ_MAX_LAG_MS
|
|
10206
|
+
};
|
|
10207
|
+
}
|
|
10208
|
+
/**
|
|
10209
|
+
* Whether two connection strings name the same database on the same server as
|
|
10210
|
+
* the same role — ignoring the query string, where the boot pins
|
|
10211
|
+
* `options=-c search_path=…` onto the primary's URL. Comparing the strings
|
|
10212
|
+
* themselves is how the read pool came to be opened for a `DATABASE_READ_URL`
|
|
10213
|
+
* that named the primary: the pinned primary URL never equalled the bare one.
|
|
10214
|
+
*
|
|
10215
|
+
* Unparseable strings are compared as given.
|
|
10216
|
+
*/
|
|
10217
|
+
function sameDatabaseTarget(a, b) {
|
|
10218
|
+
let left;
|
|
10219
|
+
let right;
|
|
10220
|
+
try {
|
|
10221
|
+
left = new URL(a);
|
|
10222
|
+
right = new URL(b);
|
|
10223
|
+
} catch {
|
|
10224
|
+
return a === b;
|
|
10225
|
+
}
|
|
10226
|
+
const port = (url) => url.port || "5432";
|
|
10227
|
+
return left.hostname.toLowerCase() === right.hostname.toLowerCase() && port(left) === port(right) && decodeURIComponent(left.pathname) === decodeURIComponent(right.pathname) && decodeURIComponent(left.username) === decodeURIComponent(right.username);
|
|
10228
|
+
}
|
|
10229
|
+
/**
|
|
10230
|
+
* SQLSTATEs after which a read is retried on the primary: the standby could
|
|
10231
|
+
* not serve it, not a judgement of the statement. Class 08 (connection), class
|
|
10232
|
+
* 53 (out of connections or resources), `57P0x` (shutting down, restarting,
|
|
10233
|
+
* starting), `57014` (statement cancelled — a standby cancels queries that
|
|
10234
|
+
* conflict with replay), and `40001` (the same conflict, reported as a
|
|
10235
|
+
* serialization failure).
|
|
10236
|
+
*/
|
|
10237
|
+
function isReplicaSqlState(code) {
|
|
10238
|
+
return code.startsWith("08") || code.startsWith("53") || code.startsWith("57P") || code === "57014" || code === "40001";
|
|
10239
|
+
}
|
|
10240
|
+
var REPLICA_NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
10241
|
+
"ECONNREFUSED",
|
|
10242
|
+
"ECONNRESET",
|
|
10243
|
+
"ENOTFOUND",
|
|
10244
|
+
"EAI_AGAIN",
|
|
10245
|
+
"EHOSTUNREACH",
|
|
10246
|
+
"ENETUNREACH",
|
|
10247
|
+
"ETIMEDOUT",
|
|
10248
|
+
"EPIPE"
|
|
10249
|
+
]);
|
|
10250
|
+
var REPLICA_POOL_MESSAGES = [
|
|
10251
|
+
"timeout exceeded when trying to connect",
|
|
10252
|
+
"Connection terminated due to connection timeout",
|
|
10253
|
+
"Connection terminated unexpectedly",
|
|
10254
|
+
"Client has encountered a connection error and is not queryable",
|
|
10255
|
+
"Query read timeout"
|
|
10256
|
+
];
|
|
10257
|
+
/**
|
|
10258
|
+
* Whether a read that failed on the standby should be run again on the
|
|
10259
|
+
* primary: the standby (or the way to it) failed, anywhere down the cause
|
|
10260
|
+
* chain. A policy denial, a bad filter or an error a hook threw is the read's
|
|
10261
|
+
* own answer, and the primary would give it too — those are not retried, so a
|
|
10262
|
+
* hook with side effects does not run twice for them.
|
|
10263
|
+
*/
|
|
10264
|
+
function isReplicaFallbackError(error, depth = 0) {
|
|
10265
|
+
if (!error || typeof error !== "object" || depth > 8) return false;
|
|
10266
|
+
const code = Reflect.get(error, "code");
|
|
10267
|
+
if (typeof code === "string" && (REPLICA_NETWORK_CODES.has(code) || /^[0-9A-Z]{5}$/.test(code) && isReplicaSqlState(code))) return true;
|
|
10268
|
+
const message = Reflect.get(error, "message");
|
|
10269
|
+
if (typeof message === "string" && REPLICA_POOL_MESSAGES.some((m) => message.startsWith(m))) return true;
|
|
10270
|
+
if (error instanceof AggregateError && error.errors.some((e) => isReplicaFallbackError(e, depth + 1))) return true;
|
|
10271
|
+
return isReplicaFallbackError(Reflect.get(error, "cause"), depth + 1);
|
|
10272
|
+
}
|
|
10273
|
+
/**
|
|
10274
|
+
* Replay lag in milliseconds, as the standby sees it: zero when it has
|
|
10275
|
+
* replayed everything it received (an idle primary sends nothing, and the
|
|
10276
|
+
* last replayed transaction's age would otherwise grow without bound), else
|
|
10277
|
+
* the age of the last transaction it replayed. Zero on a server that is not
|
|
10278
|
+
* in recovery — a read URL that names a primary has no lag. `null` when the
|
|
10279
|
+
* standby cannot say.
|
|
10280
|
+
*/
|
|
10281
|
+
var REPLICA_LAG_SQL = `SELECT CASE
|
|
10282
|
+
WHEN NOT pg_is_in_recovery() THEN 0
|
|
10283
|
+
WHEN pg_last_wal_receive_lsn() IS NOT NULL AND pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
|
|
10284
|
+
ELSE EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) * 1000
|
|
10285
|
+
END AS lag_ms`;
|
|
10286
|
+
/** Run {@link REPLICA_LAG_SQL} on `pool`, in milliseconds. */
|
|
10287
|
+
async function readReplicaLagMs(pool) {
|
|
10288
|
+
const raw = (await pool.query(REPLICA_LAG_SQL)).rows[0]?.lag_ms;
|
|
10289
|
+
if (raw === null || raw === void 0) return null;
|
|
10290
|
+
const lag = Number(raw);
|
|
10291
|
+
return Number.isFinite(lag) ? Math.max(0, lag) : null;
|
|
10292
|
+
}
|
|
10293
|
+
/**
|
|
10294
|
+
* The standby's routing state for one data source: recent writers, the last
|
|
10295
|
+
* lag sample, and whether the standby failed a read recently. One per source,
|
|
10296
|
+
* held by the base driver, so every request's authenticated driver shares it.
|
|
10297
|
+
*/
|
|
10298
|
+
var ReadRouter = class {
|
|
10299
|
+
db;
|
|
10300
|
+
sampleLag;
|
|
10301
|
+
stickyMs;
|
|
10302
|
+
maxLagMs;
|
|
10303
|
+
sampleIntervalMs;
|
|
10304
|
+
failureCooldownMs;
|
|
10305
|
+
maxPinned;
|
|
10306
|
+
now;
|
|
10307
|
+
/** Principal → when its read-your-writes window ends. Insertion order is age. */
|
|
10308
|
+
pinnedUntil = /* @__PURE__ */ new Map();
|
|
10309
|
+
lagMs = null;
|
|
10310
|
+
sampledAt = Number.NEGATIVE_INFINITY;
|
|
10311
|
+
unavailableUntil = 0;
|
|
10312
|
+
lastFailureWarningAt = Number.NEGATIVE_INFINITY;
|
|
10313
|
+
timer;
|
|
10314
|
+
sampling;
|
|
10315
|
+
constructor(db, sampleLag, options) {
|
|
10316
|
+
this.db = db;
|
|
10317
|
+
this.sampleLag = sampleLag;
|
|
10318
|
+
this.stickyMs = options.stickyMs;
|
|
10319
|
+
this.maxLagMs = options.maxLagMs;
|
|
10320
|
+
this.sampleIntervalMs = options.sampleIntervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS;
|
|
10321
|
+
this.failureCooldownMs = options.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
|
|
10322
|
+
this.maxPinned = options.maxPinnedPrincipals ?? DEFAULT_MAX_PINNED;
|
|
10323
|
+
this.now = options.now ?? Date.now;
|
|
10324
|
+
}
|
|
10325
|
+
/** Take the first sample and keep sampling. Unref'd: it never holds the process open. */
|
|
10326
|
+
start() {
|
|
10327
|
+
if (this.timer) return;
|
|
10328
|
+
this.sample();
|
|
10329
|
+
this.timer = setInterval(() => void this.sample(), this.sampleIntervalMs);
|
|
10330
|
+
this.timer.unref?.();
|
|
10331
|
+
}
|
|
10332
|
+
stop() {
|
|
10333
|
+
if (this.timer) clearInterval(this.timer);
|
|
10334
|
+
this.timer = void 0;
|
|
10335
|
+
}
|
|
10336
|
+
/** One lag sample. A failed sample leaves no sample, so reads go to the primary. */
|
|
10337
|
+
sample() {
|
|
10338
|
+
this.sampling ??= (async () => {
|
|
10339
|
+
try {
|
|
10340
|
+
const lag = await this.sampleLag();
|
|
10341
|
+
this.lagMs = lag;
|
|
10342
|
+
this.sampledAt = lag === null ? Number.NEGATIVE_INFINITY : this.now();
|
|
10343
|
+
} catch (error) {
|
|
10344
|
+
this.lagMs = null;
|
|
10345
|
+
this.sampledAt = Number.NEGATIVE_INFINITY;
|
|
10346
|
+
this.noteReplicaFailure(error);
|
|
10347
|
+
} finally {
|
|
10348
|
+
this.sampling = void 0;
|
|
10349
|
+
}
|
|
10350
|
+
})();
|
|
10351
|
+
return this.sampling;
|
|
10352
|
+
}
|
|
10353
|
+
/** The last sampled lag in seconds, or `undefined` with no current sample. */
|
|
10354
|
+
get lagSeconds() {
|
|
10355
|
+
return this.hasFreshSample() && this.lagMs !== null ? this.lagMs / 1e3 : void 0;
|
|
10356
|
+
}
|
|
10357
|
+
/**
|
|
10358
|
+
* Where `principal`'s read goes. A read with no principal is routed on the
|
|
10359
|
+
* standby's health alone: there is no write of its own to see.
|
|
10360
|
+
*/
|
|
10361
|
+
route(principal) {
|
|
10362
|
+
const now = this.now();
|
|
10363
|
+
if (now < this.unavailableUntil) return {
|
|
10364
|
+
target: "primary",
|
|
10365
|
+
reason: "unavailable"
|
|
10366
|
+
};
|
|
10367
|
+
if (principal !== void 0) {
|
|
10368
|
+
const until = this.pinnedUntil.get(principal);
|
|
10369
|
+
if (until !== void 0) {
|
|
10370
|
+
if (now < until) return {
|
|
10371
|
+
target: "primary",
|
|
10372
|
+
reason: "sticky"
|
|
10373
|
+
};
|
|
10374
|
+
this.pinnedUntil.delete(principal);
|
|
10375
|
+
}
|
|
10376
|
+
}
|
|
10377
|
+
if (!this.hasFreshSample() || this.lagMs === null) return {
|
|
10378
|
+
target: "primary",
|
|
10379
|
+
reason: "no-sample"
|
|
10380
|
+
};
|
|
10381
|
+
if (this.lagMs > this.maxLagMs) return {
|
|
10382
|
+
target: "primary",
|
|
10383
|
+
reason: "lag"
|
|
10384
|
+
};
|
|
10385
|
+
return { target: "replica" };
|
|
10386
|
+
}
|
|
10387
|
+
/**
|
|
10388
|
+
* `principal` is writing: its reads go to the primary until
|
|
10389
|
+
* {@link stickyMs} after this. Called when the write starts AND when it
|
|
10390
|
+
* ends, so a read during a long write is pinned too and the window runs
|
|
10391
|
+
* from the commit.
|
|
10392
|
+
*/
|
|
10393
|
+
notePrimaryWrite(principal) {
|
|
10394
|
+
if (this.stickyMs <= 0) return;
|
|
10395
|
+
this.pinnedUntil.delete(principal);
|
|
10396
|
+
this.pinnedUntil.set(principal, this.now() + this.stickyMs);
|
|
10397
|
+
while (this.pinnedUntil.size > this.maxPinned) {
|
|
10398
|
+
const oldest = this.pinnedUntil.keys().next().value;
|
|
10399
|
+
if (oldest === void 0) break;
|
|
10400
|
+
this.pinnedUntil.delete(oldest);
|
|
10401
|
+
}
|
|
10402
|
+
}
|
|
10403
|
+
/** The standby failed: leave it alone for the cooldown, and say so once a minute. */
|
|
10404
|
+
noteReplicaFailure(error) {
|
|
10405
|
+
const now = this.now();
|
|
10406
|
+
this.unavailableUntil = now + this.failureCooldownMs;
|
|
10407
|
+
if (now - this.lastFailureWarningAt >= FAILURE_WARNING_INTERVAL_MS) {
|
|
10408
|
+
this.lastFailureWarningAt = now;
|
|
10409
|
+
logger.warn("⚠️ The read replica (DATABASE_READ_URL) failed, so reads are served by the primary for now. Not repeated for a minute.", { error: error instanceof Error ? error.message : String(error) });
|
|
10410
|
+
}
|
|
10411
|
+
}
|
|
10412
|
+
hasFreshSample() {
|
|
10413
|
+
return this.now() - this.sampledAt <= this.sampleIntervalMs * STALE_SAMPLE_INTERVALS;
|
|
10414
|
+
}
|
|
10415
|
+
};
|
|
10416
|
+
//#endregion
|
|
10417
|
+
//#region src/database-health.ts
|
|
10418
|
+
/** The three counts `pg.Pool` keeps, as a stats row for `pool`. */
|
|
10419
|
+
function poolStatsOf(pool, name) {
|
|
10420
|
+
return {
|
|
10421
|
+
pool: name,
|
|
10422
|
+
total: pool.totalCount,
|
|
10423
|
+
idle: pool.idleCount,
|
|
10424
|
+
waiting: pool.waitingCount
|
|
10425
|
+
};
|
|
10426
|
+
}
|
|
10427
|
+
/**
|
|
10428
|
+
* Connections by state, across the server — `max_connections` is a server
|
|
10429
|
+
* limit, so a count of one database's would understate how close it is.
|
|
10430
|
+
* Client backends only: the server's own workers do not count against it.
|
|
10431
|
+
* A role without `pg_read_all_stats` sees other roles' sessions with a null
|
|
10432
|
+
* state, which is counted as `unknown` rather than dropped.
|
|
10433
|
+
*/
|
|
10434
|
+
var CONNECTIONS_SQL = `SELECT COALESCE(state, 'unknown') AS state, count(*)::int AS count
|
|
10435
|
+
FROM pg_stat_activity
|
|
10436
|
+
WHERE backend_type = 'client backend'
|
|
10437
|
+
GROUP BY 1`;
|
|
10438
|
+
/**
|
|
10439
|
+
* Sample the server behind `primary`, and the standby behind `replica` when
|
|
10440
|
+
* there is one. Each part is read on its own: a role that may not read one
|
|
10441
|
+
* answer still reports the others, and the part it could not read is left
|
|
10442
|
+
* out rather than reported as zero.
|
|
10443
|
+
*/
|
|
10444
|
+
async function sampleDatabaseHealth(primary, replica) {
|
|
10445
|
+
const sample = {};
|
|
10446
|
+
const [connections, max, size, lag] = await Promise.allSettled([
|
|
10447
|
+
primary.query(CONNECTIONS_SQL),
|
|
10448
|
+
primary.query("SELECT current_setting('max_connections') AS max"),
|
|
10449
|
+
primary.query("SELECT pg_database_size(current_database())::text AS bytes"),
|
|
10450
|
+
replica ? readReplicaLagMs(replica) : Promise.resolve(null)
|
|
10451
|
+
]);
|
|
10452
|
+
if (connections.status === "fulfilled") sample.connections = Object.fromEntries(connections.value.rows.map((row) => [row.state, Number(row.count)]));
|
|
10453
|
+
if (max.status === "fulfilled") {
|
|
10454
|
+
const value = Number(max.value.rows[0]?.max);
|
|
10455
|
+
if (Number.isFinite(value)) sample.maxConnections = value;
|
|
10456
|
+
}
|
|
10457
|
+
if (size.status === "fulfilled") {
|
|
10458
|
+
const value = Number(size.value.rows[0]?.bytes);
|
|
10459
|
+
if (Number.isFinite(value)) sample.sizeBytes = value;
|
|
10460
|
+
}
|
|
10461
|
+
if (lag.status === "fulfilled" && lag.value !== null) sample.replicaLagSeconds = lag.value / 1e3;
|
|
10462
|
+
return sample;
|
|
10463
|
+
}
|
|
10464
|
+
//#endregion
|
|
9390
10465
|
//#region src/PostgresBackendDriver.ts
|
|
9391
10466
|
/**
|
|
9392
10467
|
* Has an operator opted out of database role switching entirely?
|
|
@@ -9701,6 +10776,24 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9701
10776
|
*/
|
|
9702
10777
|
listenConnectionString;
|
|
9703
10778
|
/**
|
|
10779
|
+
* A handle on this source's direct URL for the work that needs a session
|
|
10780
|
+
* of its own — the Studio SQL console's runs, cursors and cancels — set by
|
|
10781
|
+
* the bootstrapper when the pool reaches the database through a
|
|
10782
|
+
* transaction-mode pooler (`DATABASE_POOLED=true`). There, `SET ROLE` for a
|
|
10783
|
+
* session, a cursor held across reads and `pg_cancel_backend` of "this
|
|
10784
|
+
* run's backend" mean nothing: each transaction may land on another server
|
|
10785
|
+
* connection. Unset, the pool itself is direct and serves them.
|
|
10786
|
+
*/
|
|
10787
|
+
sessionDb;
|
|
10788
|
+
/**
|
|
10789
|
+
* Where authenticated reads may go instead of the primary: this source's
|
|
10790
|
+
* read replica, with its lag guard and read-your-writes pins. Set by the
|
|
10791
|
+
* bootstrapper when `DATABASE_READ_URL` names another server. Read by
|
|
10792
|
+
* {@link AuthenticatedPostgresBackendDriver}; this driver's own reads stay
|
|
10793
|
+
* on the primary.
|
|
10794
|
+
*/
|
|
10795
|
+
readRouter;
|
|
10796
|
+
/**
|
|
9704
10797
|
* When true, realtime notifications are deferred until after the
|
|
9705
10798
|
* wrapping transaction commits. Set by `withAuth` → `withTransaction`.
|
|
9706
10799
|
*/
|
|
@@ -9749,6 +10842,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9749
10842
|
}),
|
|
9750
10843
|
planSchemaReconcile: async (collections, options) => readReconcileFacts(this.schemaFactsQueryable(), collections, options),
|
|
9751
10844
|
listen: (...args) => this.listen(...args),
|
|
10845
|
+
poolStats: () => this.poolStats(),
|
|
10846
|
+
sampleHealth: () => this.sampleHealth(),
|
|
9752
10847
|
...this.branchService ? {
|
|
9753
10848
|
createBranch: this.branchService.createBranch.bind(this.branchService),
|
|
9754
10849
|
deleteBranch: this.branchService.deleteBranch.bind(this.branchService),
|
|
@@ -9789,7 +10884,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9789
10884
|
*/
|
|
9790
10885
|
async listen(channel, onNotify, options) {
|
|
9791
10886
|
const pool = "$client" in this.db ? this.db.$client : void 0;
|
|
9792
|
-
const connectionString = this.listenConnectionString || (pool instanceof Pool ? pool.options.connectionString : void 0);
|
|
10887
|
+
const connectionString = this.listenConnectionString || (pool instanceof Pool && !isPooledPool(pool) ? pool.options.connectionString : void 0);
|
|
9793
10888
|
if (!connectionString) throw new Error("no database URL to hold a LISTEN connection on (set DATABASE_DIRECT_URL)");
|
|
9794
10889
|
const listener = new PgNotifyListener({
|
|
9795
10890
|
connectionString,
|
|
@@ -9835,6 +10930,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9835
10930
|
return masked;
|
|
9836
10931
|
},
|
|
9837
10932
|
aggregate: async (collectionPath, options) => {
|
|
10933
|
+
this.assertAggregateUnmasked(collectionPath, options);
|
|
9838
10934
|
return raw.aggregate(collectionPath, options);
|
|
9839
10935
|
},
|
|
9840
10936
|
cursorFor: (collectionPath, row, orderBy) => raw.cursorFor(collectionPath, row, orderBy)
|
|
@@ -9936,6 +11032,23 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9936
11032
|
return !!(resolved.globalCallbacks?.afterRead || resolved.callbacks?.afterRead || resolved.propertyCallbacks?.afterRead);
|
|
9937
11033
|
}
|
|
9938
11034
|
/**
|
|
11035
|
+
* Refuse an aggregate that would read what `afterRead` hides.
|
|
11036
|
+
*
|
|
11037
|
+
* An aggregate reads the stored columns and never passes through the
|
|
11038
|
+
* callbacks, so on a collection whose rows one rewrites, `max(email)` or
|
|
11039
|
+
* `groupBy=salary` hands back the value the mask exists to withhold, one
|
|
11040
|
+
* bucket at a time. What a callback does to a row cannot be known from
|
|
11041
|
+
* here, so the rule is closed: on such a collection only `count()` with no
|
|
11042
|
+
* `groupBy` is served — the number `GET /count` already gives — and any
|
|
11043
|
+
* other aggregate is refused, whichever tier (global, collection or
|
|
11044
|
+
* property) the callback sits on.
|
|
11045
|
+
*/
|
|
11046
|
+
assertAggregateUnmasked(path, options) {
|
|
11047
|
+
if ((options.groupBy?.length ?? 0) === 0 && options.aggregates.every((aggregate) => (aggregate.fn === "count" || aggregate.fn === "fingerprint") && !aggregate.field)) return;
|
|
11048
|
+
if (!PostgresBackendDriver.hasAfterRead(this.resolveCollectionCallbacks(void 0, path))) return;
|
|
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 });
|
|
11050
|
+
}
|
|
11051
|
+
/**
|
|
9939
11052
|
* Apply afterRead to REST/SDK read results.
|
|
9940
11053
|
*
|
|
9941
11054
|
* The REST / `include` path fetches rows through the raw fetch service, which
|
|
@@ -9962,7 +11075,6 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9962
11075
|
async applyAfterReadForRest(rows, path) {
|
|
9963
11076
|
if (!rows || rows.length === 0) return rows;
|
|
9964
11077
|
const resolved = this.resolveCollectionCallbacks(void 0, path);
|
|
9965
|
-
const contextForCallback = this.buildCallContext();
|
|
9966
11078
|
const hasOwn = PostgresBackendDriver.hasAfterRead(resolved);
|
|
9967
11079
|
const relationTargets = {};
|
|
9968
11080
|
if (resolved.collection) try {
|
|
@@ -9981,6 +11093,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9981
11093
|
const relKeys = Object.keys(relationTargets);
|
|
9982
11094
|
if (!hasOwn && relKeys.length === 0) return rows;
|
|
9983
11095
|
currentWriteScope()?.noteApplicationCode();
|
|
11096
|
+
const contextForCallback = this.buildCallContext();
|
|
9984
11097
|
const maskEmbedded = async (value, target) => {
|
|
9985
11098
|
if (Array.isArray(value)) return Promise.all(value.map((v) => maskEmbedded(v, target)));
|
|
9986
11099
|
if (!value || typeof value !== "object") return value;
|
|
@@ -10308,7 +11421,94 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10308
11421
|
row
|
|
10309
11422
|
};
|
|
10310
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
|
+
}
|
|
10311
11510
|
async save(props) {
|
|
11511
|
+
this.assertWritable(props.collection, props.path);
|
|
10312
11512
|
return inWriteFrame(props.path, "save", (frame) => this.saveInFrame(props, frame));
|
|
10313
11513
|
}
|
|
10314
11514
|
async saveInFrame({ path, id, values, collection, status, upsert, onConflict, precondition }, frame, knownStored) {
|
|
@@ -10323,7 +11523,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10323
11523
|
const preconditionFirst = precondition !== void 0 && status === "existing" && Boolean(id);
|
|
10324
11524
|
if (!preconditionFirst) assertUpdateShape();
|
|
10325
11525
|
const upserting = upsert === true && status !== "existing";
|
|
10326
|
-
|
|
11526
|
+
const hooks = {
|
|
11527
|
+
callbacks,
|
|
11528
|
+
globalCallbacks,
|
|
11529
|
+
propertyCallbacks
|
|
11530
|
+
};
|
|
11531
|
+
const readsStoredRow = this.writeReadsStoredRow(resolvedCollection, path, hooks);
|
|
11532
|
+
if (upserting && resolvedCollection && readsStoredRow) {
|
|
10327
11533
|
const stored = await this.findUpsertTarget(path, resolvedCollection, values, id, onConflict);
|
|
10328
11534
|
if (stored) {
|
|
10329
11535
|
const reusable = !callbacks?.beforeQuery && !globalCallbacks?.beforeQuery && !hasFieldAccessRules(resolvedCollection) && !isNestedPath(path);
|
|
@@ -10340,7 +11546,8 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10340
11546
|
const contextForCallback = this.buildCallContext();
|
|
10341
11547
|
if ((status === "new" || status === "copy") && resolvedCollection?.properties) updatedValues = applyDefaultValuesOnCreate(updatedValues, resolvedCollection.properties);
|
|
10342
11548
|
let previousValuesForHistory;
|
|
10343
|
-
|
|
11549
|
+
const unreadRow = status === "existing" && Boolean(id) && !precondition && !readsStoredRow;
|
|
11550
|
+
if (status === "existing" && id && !unreadRow) try {
|
|
10344
11551
|
const withDeleted = restoresSoftDeletedRow(resolvedCollection, values) ? true : void 0;
|
|
10345
11552
|
if (precondition?.lock) await this.dataService.getPersistService().lockRow(path, id);
|
|
10346
11553
|
const storedPath = this.storedRowPath(path);
|
|
@@ -10406,26 +11613,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10406
11613
|
}
|
|
10407
11614
|
const afterHooks = updatedValues;
|
|
10408
11615
|
if (status === "existing" && isPresentKey(id)) assertKeyUnchanged(resolvedCollection, this.registry, id, updatedValues, path);
|
|
10409
|
-
|
|
10410
|
-
updatedValues = updateDateAutoValues({
|
|
10411
|
-
inputValues: updatedValues,
|
|
10412
|
-
properties: resolvedCollection.properties,
|
|
10413
|
-
status: status ?? "new",
|
|
10414
|
-
timestampNowValue: /* @__PURE__ */ new Date()
|
|
10415
|
-
});
|
|
10416
|
-
assertActingUserForAutoValues(resolvedCollection.properties, status ?? "new", this.user?.uid, path);
|
|
10417
|
-
updatedValues = updateUserAutoValues({
|
|
10418
|
-
inputValues: updatedValues,
|
|
10419
|
-
properties: resolvedCollection.properties,
|
|
10420
|
-
status: status ?? "new",
|
|
10421
|
-
uid: this.user?.uid
|
|
10422
|
-
});
|
|
10423
|
-
if (status === "existing") {
|
|
10424
|
-
const kept = { ...updatedValues };
|
|
10425
|
-
for (const key of createStampKeys(resolvedCollection.properties)) delete kept[key];
|
|
10426
|
-
updatedValues = kept;
|
|
10427
|
-
}
|
|
10428
|
-
}
|
|
11616
|
+
updatedValues = this.stampAutoValues(resolvedCollection, updatedValues, status ?? "new", path);
|
|
10429
11617
|
updatedValues = await this.applyTenantScope(resolvedCollection, path, updatedValues, status ?? "new", previousValuesForHistory);
|
|
10430
11618
|
let writeId = id;
|
|
10431
11619
|
if ((status === "new" || status === "copy") && !upsert && isPresentKey(id) && resolvedCollection) {
|
|
@@ -10442,31 +11630,14 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10442
11630
|
const storedRow = await this.dataService.save(path, updatedValues, writeId, resolvedCollection?.databaseId, {
|
|
10443
11631
|
upsert: upserting,
|
|
10444
11632
|
onConflict,
|
|
10445
|
-
insertOnlyKeys
|
|
11633
|
+
insertOnlyKeys,
|
|
11634
|
+
unreadRow
|
|
10446
11635
|
});
|
|
10447
|
-
|
|
10448
|
-
|
|
10449
|
-
|
|
10450
|
-
|
|
10451
|
-
|
|
10452
|
-
collection: callbackCollection,
|
|
10453
|
-
path,
|
|
10454
|
-
row: savedRow,
|
|
10455
|
-
context: contextForCallback
|
|
10456
|
-
}) ?? savedRow;
|
|
10457
|
-
if (callbacks?.afterRead) savedRow = await callbacks.afterRead({
|
|
10458
|
-
collection: callbackCollection,
|
|
10459
|
-
path,
|
|
10460
|
-
row: savedRow,
|
|
10461
|
-
context: contextForCallback
|
|
10462
|
-
}) ?? savedRow;
|
|
10463
|
-
if (propertyCallbacks?.afterRead) savedRow = await propertyCallbacks.afterRead({
|
|
10464
|
-
collection: callbackCollection,
|
|
10465
|
-
path,
|
|
10466
|
-
row: savedRow,
|
|
10467
|
-
context: contextForCallback
|
|
10468
|
-
}) ?? savedRow;
|
|
10469
|
-
}
|
|
11636
|
+
const savedRow = await this.viewOfSavedRow(storedRow, resolvedCollection, path, {
|
|
11637
|
+
callbacks,
|
|
11638
|
+
globalCallbacks,
|
|
11639
|
+
propertyCallbacks
|
|
11640
|
+
}, contextForCallback);
|
|
10470
11641
|
const savedId = deriveRowAddress(storedRow, resolvedCollection ?? collection, this.registry);
|
|
10471
11642
|
const savedValues = storedRow;
|
|
10472
11643
|
try {
|
|
@@ -10629,6 +11800,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10629
11800
|
return txDriver.buildCallContext();
|
|
10630
11801
|
}
|
|
10631
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
|
+
}
|
|
10632
11810
|
return this.inBatchTransaction(async (txDriver) => {
|
|
10633
11811
|
const saved = [];
|
|
10634
11812
|
for (let i = 0; i < rows.length; i++) {
|
|
@@ -10656,6 +11834,112 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10656
11834
|
});
|
|
10657
11835
|
}
|
|
10658
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
|
+
/**
|
|
10659
11943
|
* Update many rows through the same pipeline as {@link save}, in one
|
|
10660
11944
|
* transaction.
|
|
10661
11945
|
*
|
|
@@ -10671,6 +11955,13 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10671
11955
|
* half landed without re-reading everything.
|
|
10672
11956
|
*/
|
|
10673
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
|
+
}
|
|
10674
11965
|
return this.inBatchTransaction(async (txDriver) => {
|
|
10675
11966
|
const saved = [];
|
|
10676
11967
|
for (let i = 0; i < updates.length; i++) {
|
|
@@ -10707,6 +11998,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10707
11998
|
* happened to delete at once. Same pipeline, one transaction.
|
|
10708
11999
|
*/
|
|
10709
12000
|
async deleteMany({ path, ids, collection, hard }) {
|
|
12001
|
+
this.assertWritable(collection, path);
|
|
10710
12002
|
await this.inBatchTransaction(async (txDriver) => {
|
|
10711
12003
|
for (let i = 0; i < ids.length; i++) {
|
|
10712
12004
|
const id = ids[i];
|
|
@@ -10812,6 +12104,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10812
12104
|
});
|
|
10813
12105
|
}
|
|
10814
12106
|
async delete(props) {
|
|
12107
|
+
this.assertWritable(props.collection, props.row.path);
|
|
10815
12108
|
return inWriteFrame(props.row.path, "delete", (frame) => this.deleteInFrame(props, frame));
|
|
10816
12109
|
}
|
|
10817
12110
|
async deleteInFrame({ row, collection, hard, precondition }, frame) {
|
|
@@ -10938,11 +12231,26 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10938
12231
|
databaseId: collection.databaseId
|
|
10939
12232
|
}));
|
|
10940
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
|
+
}
|
|
10941
12247
|
async deleteAll(path) {
|
|
12248
|
+
this.assertWritable(void 0, path);
|
|
10942
12249
|
await this.dataService.deleteAll(path);
|
|
10943
12250
|
await this.realtimeService.notifyUpdate(path, "*", null);
|
|
10944
12251
|
}
|
|
10945
12252
|
async updateRelationPivot({ path, targetId, pivot }) {
|
|
12253
|
+
this.assertWritable(void 0, path);
|
|
10946
12254
|
await this.dataService.updateRelationPivot(path, targetId, pivot);
|
|
10947
12255
|
if (this.realtimeService.isCdcActive()) return;
|
|
10948
12256
|
const notification = {
|
|
@@ -10997,6 +12305,35 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10997
12305
|
return this.poolManager.getDrizzle(databaseName);
|
|
10998
12306
|
}
|
|
10999
12307
|
/**
|
|
12308
|
+
* {@link getTargetDb} for work that needs one session from start to end:
|
|
12309
|
+
* the app database is reached through {@link sessionDb} when there is one.
|
|
12310
|
+
* Other databases come from the pool manager, whose URL is already the
|
|
12311
|
+
* direct one (`DATABASE_DIRECT_URL` before `DATABASE_URL`).
|
|
12312
|
+
*/
|
|
12313
|
+
async getSessionTargetDb(databaseName) {
|
|
12314
|
+
if (this.sessionDb && (!databaseName || databaseName === await this.appDatabaseName())) return this.sessionDb;
|
|
12315
|
+
return this.getTargetDb(databaseName);
|
|
12316
|
+
}
|
|
12317
|
+
/** `SQLAdmin.poolStats`: the pools this driver opened beside the server's. */
|
|
12318
|
+
poolStats() {
|
|
12319
|
+
const stats = [];
|
|
12320
|
+
const replica = this.readRouter && "$client" in this.readRouter.db ? this.readRouter.db.$client : void 0;
|
|
12321
|
+
if (replica instanceof Pool) stats.push(poolStatsOf(replica, "read"));
|
|
12322
|
+
const session = this.sessionDb && "$client" in this.sessionDb ? this.sessionDb.$client : void 0;
|
|
12323
|
+
if (session instanceof Pool) stats.push(poolStatsOf(session, "session"));
|
|
12324
|
+
return stats;
|
|
12325
|
+
}
|
|
12326
|
+
/**
|
|
12327
|
+
* `SQLAdmin.sampleHealth`: the server behind the pool, and the replica's
|
|
12328
|
+
* lag. Without a pg pool (PGlite) there is no server to sample.
|
|
12329
|
+
*/
|
|
12330
|
+
async sampleHealth() {
|
|
12331
|
+
const pool = "$client" in this.db ? this.db.$client : void 0;
|
|
12332
|
+
if (!(pool instanceof Pool)) return {};
|
|
12333
|
+
const replica = this.readRouter && "$client" in this.readRouter.db ? this.readRouter.db.$client : void 0;
|
|
12334
|
+
return sampleDatabaseHealth(pool, replica instanceof Pool ? replica : void 0);
|
|
12335
|
+
}
|
|
12336
|
+
/**
|
|
11000
12337
|
* Build one statement, binding `$n` placeholders as real parameters.
|
|
11001
12338
|
*
|
|
11002
12339
|
* Shared by the role-switched path (inside a transaction) and the
|
|
@@ -11013,7 +12350,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
11013
12350
|
return sql.join(chunks, sql.raw(""));
|
|
11014
12351
|
}
|
|
11015
12352
|
async executeSql(sqlText, options) {
|
|
11016
|
-
if (options?.isolateSession) return this.onIsolatedSession(await this.
|
|
12353
|
+
if (options?.isolateSession) return this.onIsolatedSession(await this.getSessionTargetDb(options.database), options.role, (db, role) => this.executeSqlOn(db, sqlText, {
|
|
11017
12354
|
...options,
|
|
11018
12355
|
role
|
|
11019
12356
|
}), options.maxResultBytes);
|
|
@@ -11036,7 +12373,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
11036
12373
|
...pool.options,
|
|
11037
12374
|
connectionTimeoutMillis: timeoutMs,
|
|
11038
12375
|
query_timeout: timeoutMs,
|
|
11039
|
-
statement_timeout: timeoutMs
|
|
12376
|
+
...isPooledPool(pool) ? {} : { statement_timeout: timeoutMs }
|
|
11040
12377
|
});
|
|
11041
12378
|
client.on("error", () => {});
|
|
11042
12379
|
try {
|
|
@@ -11051,7 +12388,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
11051
12388
|
* result. See `SQLAdmin.runSqlScript` and `services/sql-script.ts`.
|
|
11052
12389
|
*/
|
|
11053
12390
|
async runSqlScript(sqlText, options) {
|
|
11054
|
-
const targetDb = await this.
|
|
12391
|
+
const targetDb = await this.getSessionTargetDb(options?.database);
|
|
11055
12392
|
const pool = "$client" in targetDb ? targetDb.$client : void 0;
|
|
11056
12393
|
if (!(pool instanceof Pool)) return sqlScriptResultFromRows(await this.executeSql(sqlText, {
|
|
11057
12394
|
database: options?.database,
|
|
@@ -11071,7 +12408,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
11071
12408
|
* role it may not take) is the caller's to read, as on the socket.
|
|
11072
12409
|
*/
|
|
11073
12410
|
async openSqlCursor(sqlText, options) {
|
|
11074
|
-
const targetDb = await this.
|
|
12411
|
+
const targetDb = await this.getSessionTargetDb(options?.database);
|
|
11075
12412
|
const pool = "$client" in targetDb ? targetDb.$client : void 0;
|
|
11076
12413
|
if (!(pool instanceof Pool)) throw new ApiError(501, "SQL_EXPORT_UNSUPPORTED", "Downloading a whole result reads it through a cursor on a connection of its own, and the in-process development database has one connection. Point DATABASE_URL at a Postgres of your own (`rebase dev --docker` starts one), or add a LIMIT and export the rows on screen.");
|
|
11077
12414
|
const role = options?.role;
|
|
@@ -11353,6 +12690,11 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
11353
12690
|
return new AuthenticatedPostgresBackendDriver(this, user);
|
|
11354
12691
|
}
|
|
11355
12692
|
};
|
|
12693
|
+
/**
|
|
12694
|
+
* The uid `dataAsAdmin`, crons and jobs act as (`SERVICE_IDENTITY` in
|
|
12695
|
+
* `@rebasepro/server`). Its reads stay on the primary.
|
|
12696
|
+
*/
|
|
12697
|
+
var SERVICE_PRINCIPAL = "service";
|
|
11356
12698
|
var AuthenticatedPostgresBackendDriver = class {
|
|
11357
12699
|
delegate;
|
|
11358
12700
|
key = "postgres";
|
|
@@ -11410,7 +12752,63 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
11410
12752
|
isolationLevel: "repeatable read"
|
|
11411
12753
|
});
|
|
11412
12754
|
}
|
|
12755
|
+
/**
|
|
12756
|
+
* Run `operation` in a transaction as this caller — on the read replica
|
|
12757
|
+
* when this is a read the replica may serve (see {@link replicaFor}), else
|
|
12758
|
+
* on the primary.
|
|
12759
|
+
*
|
|
12760
|
+
* A read the replica fails for the replica's own reasons (it is down,
|
|
12761
|
+
* full, or cancelled the read to replay WAL — see
|
|
12762
|
+
* `isReplicaFallbackError`) runs again on the primary; anything else it
|
|
12763
|
+
* answered is the answer. A write pins this caller to the primary for
|
|
12764
|
+
* `REBASE_READ_STICKY_MS`, from when it starts until that long after it
|
|
12765
|
+
* ends, so the caller's next list shows what it just saved.
|
|
12766
|
+
*/
|
|
11413
12767
|
async withTransaction(operation, options) {
|
|
12768
|
+
const router = this.delegate.readRouter;
|
|
12769
|
+
const principal = this.user?.uid;
|
|
12770
|
+
if (options?.accessMode !== "read only") {
|
|
12771
|
+
if (!router || !principal) return this.runTransaction(this.delegate.db, operation, options);
|
|
12772
|
+
router.notePrimaryWrite(principal);
|
|
12773
|
+
try {
|
|
12774
|
+
return await this.runTransaction(this.delegate.db, operation, options);
|
|
12775
|
+
} finally {
|
|
12776
|
+
router.notePrimaryWrite(principal);
|
|
12777
|
+
}
|
|
12778
|
+
}
|
|
12779
|
+
const replica = this.replicaFor();
|
|
12780
|
+
if (replica) try {
|
|
12781
|
+
return await this.runTransaction(replica, operation, options);
|
|
12782
|
+
} catch (error) {
|
|
12783
|
+
if (!isReplicaFallbackError(error)) throw error;
|
|
12784
|
+
router?.noteReplicaFailure(error);
|
|
12785
|
+
}
|
|
12786
|
+
return this.runTransaction(this.delegate.db, operation, options);
|
|
12787
|
+
}
|
|
12788
|
+
/**
|
|
12789
|
+
* The replica's handle for a read by this caller, or `undefined` for the
|
|
12790
|
+
* primary: there is no replica, the read is inside a write's transaction
|
|
12791
|
+
* (it must see what that write has not committed), the caller is the
|
|
12792
|
+
* service identity (crons, jobs, `dataAsAdmin` — server work that reads
|
|
12793
|
+
* what it acts on), or the router says the replica is behind, failing, or
|
|
12794
|
+
* this caller just wrote.
|
|
12795
|
+
*/
|
|
12796
|
+
replicaFor() {
|
|
12797
|
+
const router = this.delegate.readRouter;
|
|
12798
|
+
if (!router) return void 0;
|
|
12799
|
+
if (currentWriteScope()) return void 0;
|
|
12800
|
+
const principal = this.user?.uid;
|
|
12801
|
+
if (principal === SERVICE_PRINCIPAL) return void 0;
|
|
12802
|
+
const route = router.route(principal);
|
|
12803
|
+
if (route.target === "primary") {
|
|
12804
|
+
logger.debug(`[DataDriver] read served by the primary (${route.reason})`);
|
|
12805
|
+
return;
|
|
12806
|
+
}
|
|
12807
|
+
return router.db;
|
|
12808
|
+
}
|
|
12809
|
+
async runTransaction(db, operation, options) {
|
|
12810
|
+
const pooledSettings = pooledTransactionSettings("$client" in db ? db.$client : void 0);
|
|
12811
|
+
const pipelined = pipelineTarget(db);
|
|
11414
12812
|
const pendingNotifications = [];
|
|
11415
12813
|
const writeScope = options?.accessMode === "read only" ? void 0 : new WriteTransactionScope();
|
|
11416
12814
|
const client = this.delegate.client;
|
|
@@ -11424,32 +12822,44 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
11424
12822
|
},
|
|
11425
12823
|
storageSource: client?.storage
|
|
11426
12824
|
});
|
|
11427
|
-
const result = await withFieldViewer({ roles: this.user?.roles ?? [] }, async () => await runInWriteScope(writeScope, () =>
|
|
11428
|
-
|
|
11429
|
-
|
|
11430
|
-
|
|
11431
|
-
|
|
11432
|
-
|
|
11433
|
-
|
|
11434
|
-
|
|
11435
|
-
|
|
11436
|
-
|
|
11437
|
-
|
|
11438
|
-
|
|
11439
|
-
|
|
11440
|
-
|
|
11441
|
-
|
|
11442
|
-
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11446
|
-
|
|
11447
|
-
|
|
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);
|
|
11448
12855
|
}
|
|
11449
|
-
|
|
11450
|
-
|
|
11451
|
-
|
|
11452
|
-
|
|
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) => {
|
|
11453
12863
|
await writeScope?.settled();
|
|
11454
12864
|
throw error;
|
|
11455
12865
|
});
|
|
@@ -11530,6 +12940,16 @@ var AuthenticatedPostgresBackendDriver = class {
|
|
|
11530
12940
|
async deleteAll(path) {
|
|
11531
12941
|
return this.withTransaction((delegate) => delegate.deleteAll(path));
|
|
11532
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
|
+
}
|
|
11533
12953
|
async updateRelationPivot(props) {
|
|
11534
12954
|
return this.withTransaction((delegate) => delegate.updateRelationPivot(props));
|
|
11535
12955
|
}
|
|
@@ -12049,7 +13469,7 @@ var MAX_NOTIFY_BYTES = 7900;
|
|
|
12049
13469
|
* notification.
|
|
12050
13470
|
*/
|
|
12051
13471
|
var CHUNK_SLACK_BYTES = 64;
|
|
12052
|
-
var quoteIdent$
|
|
13472
|
+
var quoteIdent$2 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
12053
13473
|
var quoteLiteral$1 = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
12054
13474
|
/**
|
|
12055
13475
|
* The row-level function: `{ schema, table, op, row }`, one per changed row.
|
|
@@ -12319,8 +13739,8 @@ $rebase_cdc$;
|
|
|
12319
13739
|
* function serves every table. Empty means "the primary key".
|
|
12320
13740
|
*/
|
|
12321
13741
|
function buildCdcTriggerSql(schema, table, identityColumns = [], level = "statement") {
|
|
12322
|
-
const qualified = `${quoteIdent$
|
|
12323
|
-
return ALL_TRIGGER_NAMES.map((name) => `DROP TRIGGER IF EXISTS ${quoteIdent$
|
|
13742
|
+
const qualified = `${quoteIdent$2(schema)}.${quoteIdent$2(table)}`;
|
|
13743
|
+
return ALL_TRIGGER_NAMES.map((name) => `DROP TRIGGER IF EXISTS ${quoteIdent$2(name)} ON ${qualified};\n`).join("") + buildCdcTriggerCreateSql(schema, table, identityColumns, level);
|
|
12324
13744
|
}
|
|
12325
13745
|
/**
|
|
12326
13746
|
* `CREATE TRIGGER` alone, for a table that has no capture trigger yet.
|
|
@@ -12330,9 +13750,9 @@ function buildCdcTriggerSql(schema, table, identityColumns = [], level = "statem
|
|
|
12330
13750
|
* `CREATE TRIGGER` takes SHARE ROW EXCLUSIVE, which readers never wait for.
|
|
12331
13751
|
*/
|
|
12332
13752
|
var buildCdcTriggerCreateSql = (schema, table, identityColumns, level) => {
|
|
12333
|
-
const qualified = `${quoteIdent$
|
|
13753
|
+
const qualified = `${quoteIdent$2(schema)}.${quoteIdent$2(table)}`;
|
|
12334
13754
|
const args = [...new Set(identityColumns)].map(quoteLiteral$1).join(", ");
|
|
12335
|
-
return triggersFor(level).map((spec) => `CREATE TRIGGER ${quoteIdent$
|
|
13755
|
+
return triggersFor(level).map((spec) => `CREATE TRIGGER ${quoteIdent$2(spec.name)} ${spec.timing} ON ${qualified} ${spec.forEach} EXECUTE FUNCTION ${spec.fn === "statement" ? CDC_STATEMENT_FUNCTION : CDC_TRIGGER_FUNCTION}(${args});`).join("\n");
|
|
12336
13756
|
};
|
|
12337
13757
|
/** `to_regprocedure` of each function, as a SQL expression. */
|
|
12338
13758
|
var ROW_FUNCTION_OID = `to_regprocedure(${quoteLiteral$1(`${CDC_TRIGGER_FUNCTION}()`)})`;
|
|
@@ -12454,7 +13874,7 @@ async function settleInstalledCapture(run, options) {
|
|
|
12454
13874
|
*/
|
|
12455
13875
|
async function resolveIdentityColumns(run, ref) {
|
|
12456
13876
|
const requested = ref.identityColumns ?? [];
|
|
12457
|
-
const qualified = `${quoteIdent$
|
|
13877
|
+
const qualified = `${quoteIdent$2(ref.schema)}.${quoteIdent$2(ref.table)}`;
|
|
12458
13878
|
let columns;
|
|
12459
13879
|
let relkind = null;
|
|
12460
13880
|
try {
|
|
@@ -12498,7 +13918,7 @@ var decodeTriggerArgs = (hex) => {
|
|
|
12498
13918
|
* 4.4 s while a report read the table.
|
|
12499
13919
|
*/
|
|
12500
13920
|
async function readCaptureState(run, refs) {
|
|
12501
|
-
const rows = await run(`WITH target(key, rel) AS (VALUES ${refs.map((ref) => `(${quoteLiteral$1(`${ref.schema}.${ref.table}`)}, to_regclass(${quoteLiteral$1(`${quoteIdent$
|
|
13921
|
+
const rows = await run(`WITH target(key, rel) AS (VALUES ${refs.map((ref) => `(${quoteLiteral$1(`${ref.schema}.${ref.table}`)}, to_regclass(${quoteLiteral$1(`${quoteIdent$2(ref.schema)}.${quoteIdent$2(ref.table)}`)}))`).join(", ")})
|
|
12502
13922
|
SELECT t.key,
|
|
12503
13923
|
(SELECT c.relkind::text FROM pg_class c WHERE c.oid = t.rel) AS relkind,
|
|
12504
13924
|
(SELECT coalesce(json_agg(json_build_object('name', a.attname,
|
|
@@ -13546,7 +14966,7 @@ var WalCdcListener = class {
|
|
|
13546
14966
|
*/
|
|
13547
14967
|
/** The publication WAL capture streams. A plain identifier: it is interpolated into replication commands. */
|
|
13548
14968
|
var CDC_PUBLICATION = "rebase_cdc";
|
|
13549
|
-
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
14969
|
+
var quoteIdent$1 = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
13550
14970
|
var quoteLiteral = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
13551
14971
|
/** SQLSTATE 42710: the publication, or the table's membership of it, already exists — another instance got there first. */
|
|
13552
14972
|
function isDuplicateObject(err) {
|
|
@@ -13570,7 +14990,7 @@ async function walCaptureBlocker(run) {
|
|
|
13570
14990
|
async function readTableStates(run, tables) {
|
|
13571
14991
|
const states = /* @__PURE__ */ new Map();
|
|
13572
14992
|
if (tables.length === 0) return states;
|
|
13573
|
-
const names = tables.map((t) => quoteLiteral(`${quoteIdent(t.schema)}.${quoteIdent(t.table)}`)).join(", ");
|
|
14993
|
+
const names = tables.map((t) => quoteLiteral(`${quoteIdent$1(t.schema)}.${quoteIdent$1(t.table)}`)).join(", ");
|
|
13574
14994
|
const rows = await run(`SELECT n.name, c.oid IS NOT NULL AS exists, c.relkind::text AS relkind, c.relreplident::text AS replica_identity, EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary) AS has_pk, EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisreplident) AS has_identity_index, EXISTS (SELECT 1 FROM pg_publication_rel r JOIN pg_publication p ON p.oid = r.prpubid WHERE r.prrelid = c.oid AND p.pubname = ${quoteLiteral(CDC_PUBLICATION)}) AS published FROM unnest(ARRAY[${names}]::text[]) AS n(name) LEFT JOIN pg_class c ON c.oid = to_regclass(n.name)`);
|
|
13575
14995
|
for (const row of rows) states.set(String(row.name), {
|
|
13576
14996
|
exists: row.exists === true,
|
|
@@ -13612,13 +15032,13 @@ async function provisionWalPublication(run, tables) {
|
|
|
13612
15032
|
if ((await run(`SELECT 1 FROM pg_publication WHERE pubname = ${quoteLiteral("rebase_cdc")}`)).length === 0) {
|
|
13613
15033
|
const options = "publish = 'insert, update, delete, truncate'" + (version >= 13e4 ? ", publish_via_partition_root = true" : "");
|
|
13614
15034
|
try {
|
|
13615
|
-
await run(`CREATE PUBLICATION ${quoteIdent(CDC_PUBLICATION)} WITH (${options})`);
|
|
15035
|
+
await run(`CREATE PUBLICATION ${quoteIdent$1(CDC_PUBLICATION)} WITH (${options})`);
|
|
13616
15036
|
} catch (err) {
|
|
13617
15037
|
if (!isDuplicateObject(err)) throw err;
|
|
13618
15038
|
}
|
|
13619
15039
|
}
|
|
13620
15040
|
const byTable = /* @__PURE__ */ new Map();
|
|
13621
|
-
for (const ref of tables) byTable.set(`${quoteIdent(ref.schema)}.${quoteIdent(ref.table)}`, ref);
|
|
15041
|
+
for (const ref of tables) byTable.set(`${quoteIdent$1(ref.schema)}.${quoteIdent$1(ref.table)}`, ref);
|
|
13622
15042
|
const states = await readTableStates(run, [...byTable.values()]);
|
|
13623
15043
|
const published = [];
|
|
13624
15044
|
const skipped = [];
|
|
@@ -13637,7 +15057,7 @@ async function provisionWalPublication(run, tables) {
|
|
|
13637
15057
|
continue;
|
|
13638
15058
|
}
|
|
13639
15059
|
try {
|
|
13640
|
-
await withLockBudget(run, `ALTER PUBLICATION ${quoteIdent(CDC_PUBLICATION)} ADD TABLE ${qualified}`);
|
|
15060
|
+
await withLockBudget(run, `ALTER PUBLICATION ${quoteIdent$1(CDC_PUBLICATION)} ADD TABLE ${qualified}`);
|
|
13641
15061
|
published.push(ref);
|
|
13642
15062
|
} catch (err) {
|
|
13643
15063
|
if (isDuplicateObject(err)) published.push(ref);
|
|
@@ -20433,6 +21853,79 @@ function patchPgNumericToNumber(tables) {
|
|
|
20433
21853
|
if (patchedCount > 0) logger.debug(`[PgNumeric] ${patchedCount} numeric column(s) will be served as numbers`);
|
|
20434
21854
|
}
|
|
20435
21855
|
//#endregion
|
|
21856
|
+
//#region src/pooled-database.ts
|
|
21857
|
+
/**
|
|
21858
|
+
* Running behind a transaction-mode pooler (PgBouncer, `DATABASE_POOLED=true`).
|
|
21859
|
+
*
|
|
21860
|
+
* The pool sends no session settings at connect behind one — the pooler would
|
|
21861
|
+
* refuse or drop them — and a transaction sets its own (`SET LOCAL`, see
|
|
21862
|
+
* `pooledTransactionSettings`). What that leaves is a statement outside any
|
|
21863
|
+
* transaction: it runs with the role's defaults, and the default
|
|
21864
|
+
* `search_path` is `"$user", public`. This framework's role is usually called
|
|
21865
|
+
* `rebase`, and so is its schema, so an unqualified table resolves to
|
|
21866
|
+
* `rebase.<name>` before `public.<name>` — the hazard `pinSearchPath` exists
|
|
21867
|
+
* for, which a pooled pool cannot pin.
|
|
21868
|
+
*
|
|
21869
|
+
* So the boot gives the role a default `search_path` of `public` in this
|
|
21870
|
+
* database, the same value every direct connection of this framework already
|
|
21871
|
+
* pins, over the direct URL. It applies to server connections the pooler opens
|
|
21872
|
+
* from then on.
|
|
21873
|
+
*
|
|
21874
|
+
* @module
|
|
21875
|
+
*/
|
|
21876
|
+
function quoteIdent(name) {
|
|
21877
|
+
return `"${name.replace(/"/g, "\"\"")}"`;
|
|
21878
|
+
}
|
|
21879
|
+
/** The statement that gives `role` a default `search_path` in `database`. */
|
|
21880
|
+
function roleSearchPathStatement(role, database, searchPath) {
|
|
21881
|
+
return `ALTER ROLE ${quoteIdent(role)} IN DATABASE ${quoteIdent(database)} SET search_path TO ${searchPathList(searchPath)}`;
|
|
21882
|
+
}
|
|
21883
|
+
/** Whether a reported `search_path` already is `wanted`, spelling aside. */
|
|
21884
|
+
function searchPathMatches(reported, wanted) {
|
|
21885
|
+
const normalise = (value) => value.split(",").map((part) => part.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean).join(",");
|
|
21886
|
+
return normalise(reported) === normalise(wanted);
|
|
21887
|
+
}
|
|
21888
|
+
/**
|
|
21889
|
+
* Make the role the pooled pool connects as default to `searchPath` in its
|
|
21890
|
+
* database, when it does not already. Asked through the pool (what the pooler
|
|
21891
|
+
* hands out is what matters), changed through `directUrl`.
|
|
21892
|
+
*
|
|
21893
|
+
* With `provision: false` — a boot that runs no DDL — nothing is changed and
|
|
21894
|
+
* the statement to run is logged. A role that may not change its own
|
|
21895
|
+
* defaults is logged the same way; neither stops the boot, because every
|
|
21896
|
+
* transaction still sets the path for itself.
|
|
21897
|
+
*/
|
|
21898
|
+
async function ensurePooledRoleDefaults(pool, directUrl, options) {
|
|
21899
|
+
const wanted = options.searchPath ?? "public";
|
|
21900
|
+
let facts;
|
|
21901
|
+
try {
|
|
21902
|
+
facts = (await pool.query("SELECT current_setting('search_path') AS search_path, current_user AS role, current_database() AS database")).rows[0];
|
|
21903
|
+
} catch (error) {
|
|
21904
|
+
logger.warn("[pooler] Could not read the search_path the pooler hands out", { error: error instanceof Error ? error.message : String(error) });
|
|
21905
|
+
return;
|
|
21906
|
+
}
|
|
21907
|
+
if (!facts || searchPathMatches(facts.search_path, wanted)) return;
|
|
21908
|
+
const statement = roleSearchPathStatement(facts.role, facts.database, wanted);
|
|
21909
|
+
if (!options.provision) {
|
|
21910
|
+
logger.warn(`⚠️ [pooler] Statements outside a transaction resolve unqualified tables with search_path "${facts.search_path}", not "${wanted}", and this process runs no DDL at boot. Run once:\n ${statement};`);
|
|
21911
|
+
return;
|
|
21912
|
+
}
|
|
21913
|
+
const client = new Client({
|
|
21914
|
+
connectionString: directUrl,
|
|
21915
|
+
connectionTimeoutMillis: 1e4
|
|
21916
|
+
});
|
|
21917
|
+
client.on("error", () => void 0);
|
|
21918
|
+
try {
|
|
21919
|
+
await client.connect();
|
|
21920
|
+
await client.query(statement);
|
|
21921
|
+
logger.info(`[pooler] Set the default search_path of role "${facts.role}" in "${facts.database}" to ${wanted} (was ` + JSON.stringify(facts.search_path) + "), for statements outside a transaction.");
|
|
21922
|
+
} catch (error) {
|
|
21923
|
+
logger.warn(`⚠️ [pooler] Could not set the default search_path of role "${facts.role}": ${error instanceof Error ? error.message : String(error)}. Run once as a role that may:\n ${statement};`);
|
|
21924
|
+
} finally {
|
|
21925
|
+
await client.end().catch(() => void 0);
|
|
21926
|
+
}
|
|
21927
|
+
}
|
|
21928
|
+
//#endregion
|
|
20436
21929
|
//#region src/PostgresBootstrapper.ts
|
|
20437
21930
|
/**
|
|
20438
21931
|
* PostgresBootstrapper
|
|
@@ -20528,10 +22021,18 @@ function resolveSourceUrls(pgConfig, sourceKey, env = process.env) {
|
|
|
20528
22021
|
const isDefault = sourceKey === DEFAULT_DATA_SOURCE_KEY;
|
|
20529
22022
|
return {
|
|
20530
22023
|
readUrl: pgConfig.readConnectionString || (isDefault ? env.DATABASE_READ_URL : void 0) || void 0,
|
|
20531
|
-
directUrl: pgConfig.directConnectionString || (isDefault ? env.DATABASE_DIRECT_URL : void 0) || pgConfig.connectionString || void 0
|
|
22024
|
+
directUrl: pgConfig.directConnectionString || (isDefault ? env.DATABASE_DIRECT_URL : void 0) || (pgConfig.pooled ? void 0 : pgConfig.connectionString) || void 0
|
|
20532
22025
|
};
|
|
20533
22026
|
}
|
|
20534
22027
|
/**
|
|
22028
|
+
* The refusal for a pooled source with no direct URL — named so the
|
|
22029
|
+
* control plane's log line and the self-hoster's both say what to set.
|
|
22030
|
+
*/
|
|
22031
|
+
function pooledWithoutDirectUrlError(sourceKey) {
|
|
22032
|
+
const suffix = resourceEnvSuffix(sourceKey);
|
|
22033
|
+
return /* @__PURE__ */ new Error(`DATABASE_POOLED${suffix}=true says DATABASE_URL${suffix} goes through a transaction-mode pooler, but DATABASE_DIRECT_URL${suffix} is not set. Realtime, the job queue's wake-up, index builds and the SQL console need a connection that keeps its session, which a transaction-mode pooler does not give. Set DATABASE_DIRECT_URL${suffix} to the database itself (not the pooler), or unset DATABASE_POOLED${suffix}.`);
|
|
22034
|
+
}
|
|
22035
|
+
/**
|
|
20535
22036
|
* Is this the local database `rebase init` scaffolds — i.e. the one case where
|
|
20536
22037
|
* "you are connected as a superuser" is not news?
|
|
20537
22038
|
*
|
|
@@ -20726,10 +22227,14 @@ function postgresDriverConfigFromEnv(config, env = process.env, sourceKey = DEFA
|
|
|
20726
22227
|
const isDefaultSource = sourceKey === DEFAULT_DATA_SOURCE_KEY;
|
|
20727
22228
|
const readConnectionString = config.readConnectionString || (isDefaultSource ? read("DATABASE_READ_URL") : void 0);
|
|
20728
22229
|
const directConnectionString = config.directConnectionString || (isDefaultSource ? read("DATABASE_DIRECT_URL") : void 0);
|
|
22230
|
+
const pooled = config.pooled ?? (isDefaultSource ? read("DATABASE_POOLED")?.toLowerCase() === "true" : void 0);
|
|
22231
|
+
const readRouting = config.readRouting ?? (read("REBASE_READ_STICKY_MS") || read("REBASE_READ_MAX_LAG_MS") ? readRoutingOptionsFromEnv(env) : void 0);
|
|
20729
22232
|
return {
|
|
20730
22233
|
...config,
|
|
20731
22234
|
...readConnectionString ? { readConnectionString } : {},
|
|
20732
22235
|
...directConnectionString ? { directConnectionString } : {},
|
|
22236
|
+
...pooled ? { pooled } : {},
|
|
22237
|
+
...readRouting ? { readRouting } : {},
|
|
20733
22238
|
realtime
|
|
20734
22239
|
};
|
|
20735
22240
|
}
|
|
@@ -20856,18 +22361,56 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
20856
22361
|
realtimeService.recountIntervalMs = tuning(pgConfig.realtime?.recountIntervalMs, "realtime.recountIntervalMs", "milliseconds");
|
|
20857
22362
|
const recountMinRows = tuning(pgConfig.realtime?.recountMinRows, "realtime.recountMinRows", "rows");
|
|
20858
22363
|
if (recountMinRows !== void 0) realtimeService.recountMinRows = recountMinRows;
|
|
20859
|
-
const
|
|
22364
|
+
const pooled = pgConfig.pooled === true || isPooledPool(rawClient);
|
|
22365
|
+
const { readUrl, directUrl } = resolveSourceUrls({
|
|
22366
|
+
...pgConfig,
|
|
22367
|
+
pooled
|
|
22368
|
+
}, sourceKey, {});
|
|
22369
|
+
if (pooled && !directUrl) throw pooledWithoutDirectUrlError(sourceKey);
|
|
22370
|
+
const primaryUrl = pgConfig.connectionString || (rawClient && typeof rawClient === "object" && "options" in rawClient ? rawClient.options.connectionString : void 0);
|
|
20860
22371
|
let readDb;
|
|
20861
|
-
|
|
20862
|
-
|
|
20863
|
-
|
|
20864
|
-
|
|
22372
|
+
let readRouter;
|
|
22373
|
+
let readPool;
|
|
22374
|
+
if (readUrl && !(primaryUrl && sameDatabaseTarget(readUrl, primaryUrl))) try {
|
|
22375
|
+
const { createReadReplicaConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
|
|
22376
|
+
const readResources = createReadReplicaConnection(readUrl, mergedSchema, {
|
|
22377
|
+
...pgConfig.poolConfig,
|
|
22378
|
+
pooled
|
|
22379
|
+
});
|
|
22380
|
+
readDb = readResources.db;
|
|
22381
|
+
readPool = readResources.pool;
|
|
22382
|
+
readRouter = new ReadRouter(readDb, () => readReplicaLagMs(readResources.pool), pgConfig.readRouting ?? readRoutingOptionsFromEnv({}));
|
|
22383
|
+
readRouter.start();
|
|
22384
|
+
logger.info(`📖 [PostgresBootstrapper] Authenticated reads may use the read replica (read-your-writes ${readRouter.stickyMs} ms, lag limit ${readRouter.maxLagMs} ms)`);
|
|
20865
22385
|
} catch (err) {
|
|
20866
22386
|
logger.warn("⚠️ Could not connect to read replica, falling back to primary for all queries", { error: err });
|
|
20867
22387
|
}
|
|
20868
|
-
|
|
22388
|
+
let sessionDb;
|
|
22389
|
+
let sessionPool;
|
|
22390
|
+
if (pooled && directUrl) {
|
|
22391
|
+
const { createDirectDatabaseConnection } = await import("./connection-COuS5Fm-.js").then((n) => n.r);
|
|
22392
|
+
const session = createDirectDatabaseConnection(directUrl, void 0, {
|
|
22393
|
+
max: 3,
|
|
22394
|
+
idleTimeoutMillis: 1e4
|
|
22395
|
+
});
|
|
22396
|
+
sessionDb = session.db;
|
|
22397
|
+
sessionPool = session.pool;
|
|
22398
|
+
}
|
|
22399
|
+
const adminUrl = pooled && directUrl && pgConfig.adminConnectionString && primaryUrl && sameDatabaseTarget(pgConfig.adminConnectionString, primaryUrl) ? directUrl : pgConfig.adminConnectionString;
|
|
22400
|
+
const poolManager = adminUrl ? new DatabasePoolManager(adminUrl) : void 0;
|
|
22401
|
+
closeWithPool(rawClient, async () => {
|
|
22402
|
+
readRouter?.stop();
|
|
22403
|
+
await Promise.allSettled([
|
|
22404
|
+
readPool?.end(),
|
|
22405
|
+
sessionPool?.end(),
|
|
22406
|
+
poolManager?.shutdown()
|
|
22407
|
+
]);
|
|
22408
|
+
});
|
|
20869
22409
|
const driver = new PostgresBackendDriver(schemaAwareDb, realtimeService, registry, void 0, poolManager);
|
|
20870
22410
|
driver.listenConnectionString = directUrl;
|
|
22411
|
+
driver.sessionDb = sessionDb;
|
|
22412
|
+
driver.readRouter = readRouter;
|
|
22413
|
+
if (pooled && directUrl) await ensurePooledRoleDefaults(rawClient, directUrl, { provision });
|
|
20871
22414
|
realtimeService.setDataDriver(driver);
|
|
20872
22415
|
let rlsEnforcement;
|
|
20873
22416
|
let exposedInternalTables;
|
|
@@ -20950,7 +22493,7 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
20950
22493
|
if (explicitCdc) logger.warn(`⚠️ [CDC] REALTIME_CDC=${cdcMode} but ${reason} — using app-level realtime.`);
|
|
20951
22494
|
else logger.info(`ℹ️ [CDC] Using app-level realtime — ${reason}.`);
|
|
20952
22495
|
} else if (wantsCdc && directUrl) {
|
|
20953
|
-
const cdcTables = collectionsOnThisSource().map((c) => ({
|
|
22496
|
+
const cdcTables = collectionsOnThisSource().filter((c) => !(isPostgresCollectionConfig(c) && c.view)).map((c) => ({
|
|
20954
22497
|
schema: c.schema ?? "public",
|
|
20955
22498
|
table: getTableName$1(c),
|
|
20956
22499
|
identityColumns: collectionKeyColumns(c, registry).map((k) => k.columnName)
|
|
@@ -21172,7 +22715,12 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21172
22715
|
const openIndexBuildSession = (driverResult) => async () => {
|
|
21173
22716
|
const db = requireProvisioningDb(driverResult);
|
|
21174
22717
|
const pool = "$client" in db ? db.$client : void 0;
|
|
21175
|
-
const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-
|
|
22718
|
+
const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
|
|
22719
|
+
const config = effectiveConfig();
|
|
22720
|
+
if (isPooledPool(pool) || config.pooled) {
|
|
22721
|
+
if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
|
|
22722
|
+
return clientIndexBuildSession(config.directConnectionString)();
|
|
22723
|
+
}
|
|
21176
22724
|
if (isPgPool(pool)) return poolIndexBuildSession(pool)();
|
|
21177
22725
|
const queryable = provisioningQueryable(driverResult);
|
|
21178
22726
|
return {
|
|
@@ -21198,7 +22746,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21198
22746
|
*/
|
|
21199
22747
|
const provisionRlsRuntime = async (driverResult) => {
|
|
21200
22748
|
const db = requireProvisioningDb(driverResult);
|
|
21201
|
-
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-
|
|
22749
|
+
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
|
|
21202
22750
|
const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
|
|
21203
22751
|
if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
|
|
21204
22752
|
await db.transaction(async (tx) => {
|
|
@@ -21311,11 +22859,11 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21311
22859
|
unavailable: historyUnavailableReason(state, { requireTransaction: false })
|
|
21312
22860
|
}) };
|
|
21313
22861
|
}
|
|
21314
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
22862
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
|
|
21315
22863
|
const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
21316
22864
|
const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
21317
22865
|
if (historyIndexes.length > 0) {
|
|
21318
|
-
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
22866
|
+
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
|
|
21319
22867
|
const indexOptions = {
|
|
21320
22868
|
log: (message) => logger.info(`[history] ${message}`),
|
|
21321
22869
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
|
|
@@ -21371,9 +22919,9 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21371
22919
|
* proved it can bootstrap with.
|
|
21372
22920
|
*/
|
|
21373
22921
|
async ensureCollectionSchema(collections, driverResult, log) {
|
|
21374
|
-
const { ensureCollectionTables } = await import("./ensure-collection-tables-
|
|
22922
|
+
const { ensureCollectionTables } = await import("./ensure-collection-tables-BK--gDo6.js").then((n) => n.n);
|
|
21375
22923
|
const queryable = provisioningQueryable(driverResult);
|
|
21376
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
22924
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-D4W9o9xE.js").then((n) => n.i);
|
|
21377
22925
|
const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
|
|
21378
22926
|
const plan = await ensureCollectionTables(queryable, collections, log, {
|
|
21379
22927
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
|
|
@@ -21385,7 +22933,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21385
22933
|
pendingIndexBuild?.cancel();
|
|
21386
22934
|
pendingIndexBuild = void 0;
|
|
21387
22935
|
if (!provisionOnly && plan.deferredIndexes.length > 0) {
|
|
21388
|
-
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
22936
|
+
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-F2GWu009.js").then((n) => n.r);
|
|
21389
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.`);
|
|
21390
22938
|
pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
|
|
21391
22939
|
log: (message) => logger.info(`[schema] ${message}`),
|
|
@@ -21425,7 +22973,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21425
22973
|
await provisionRlsRuntime(driverResult);
|
|
21426
22974
|
},
|
|
21427
22975
|
async ensureCollectionPolicies(collections, driverResult, log) {
|
|
21428
|
-
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-
|
|
22976
|
+
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-DUpWJb5D.js");
|
|
21429
22977
|
const queryable = provisioningQueryable(driverResult);
|
|
21430
22978
|
const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
|
|
21431
22979
|
if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
|
|
@@ -21450,7 +22998,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21450
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.`);
|
|
21451
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.`);
|
|
21452
23000
|
try {
|
|
21453
|
-
const { dropLegacyAuthSchema } = await import("./migrate-baseline-
|
|
23001
|
+
const { dropLegacyAuthSchema } = await import("./migrate-baseline-BeepEphh.js").then((n) => n.E);
|
|
21454
23002
|
await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
|
|
21455
23003
|
info: (m) => logger.info(m),
|
|
21456
23004
|
warn: (m) => logger.warn(m)
|
|
@@ -21541,7 +23089,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
21541
23089
|
return driverResult.internals.driver.admin;
|
|
21542
23090
|
},
|
|
21543
23091
|
async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
|
|
21544
|
-
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-
|
|
23092
|
+
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-D2y88dOa.js").then((n) => n.c);
|
|
21545
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.`);
|
|
21546
23094
|
const realtimeConfig = effectiveConfig().realtime;
|
|
21547
23095
|
const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
|
|
@@ -21686,4 +23234,4 @@ async function openRebase(options) {
|
|
|
21686
23234
|
//#endregion
|
|
21687
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 };
|
|
21688
23236
|
|
|
21689
|
-
//# sourceMappingURL=open-rebase-
|
|
23237
|
+
//# sourceMappingURL=open-rebase-CTNBmmH8.js.map
|