@dbsp/adapter-pgsql 5.0.0 → 7.0.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/index.d.ts CHANGED
@@ -1,1885 +1,63 @@
1
- import * as _dbsp_core from '@dbsp/core';
2
- import { IndexInfo, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions, ExpressionRef, ModelIR as ModelIR$1, ValidatedManagedStepManifest, ExecutionCoordinator, CapabilityDescriptor } from '@dbsp/core';
1
+ import { C as ChangeKind, G as GeneratedPostconditionSession, S as SqlIdentifier, D as Decision, a as CompilerContext, b as CompilerState, P as ProjectionEnvelope, T as TransitionJournalQueryable, c as PgLockedRun, d as PgOutcomeCheckpointObserver, e as ConvergePgOptions$1, f as PgPhysicalModel, g as PgConvergeResult, h as PgConvergeCheckResult, i as PgLedgerScopeCurrency, r as readTransitionJournal } from './outcome-protocol-B3vRIj2q.js';
2
+ export { A as AddedEnumValue, j as AutoIncrementTransitionUnsupportedError, k as CanonicalizeCheckConstraintsOptions, l as CheckConstraintCanonicalizationError, m as CheckConstraintCanonicalizationWarning, n as CheckConstraintNewEnumValueError, o as ColumnDefaultCanonicalizationError, p as ColumnDefaultCanonicalizationWarning, q as ComparePgDatabaseSchemaOptions, s as CompareSchemataOptions, t as DEFAULT_PK_COLUMN, u as DetectedHierarchy, v as DiffSummary, E as ExpressionCanonicalizationUnavailableError, w as ExpressionCanonicalizationWarning, x as ExpressionHandler, y as ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError, F as FkColumnDerivation, z as GenerateDDLOptions, B as GeneratedPostcondition, H as GeneratedPostconditionBindingAddress, I as GeneratedPostconditionBindingResolutionError, J as GeneratedPostconditionProofInFlightError, K as GeneratedPostconditionReplanRequiredError, L as GeneratedPostconditionSessionDeactivatedError, M as GeneratedPostconditionWorkInFlightError, N as IncludeHandler, O as IncludeResult, Q as IndexCapabilityContext, R as IndexFeatureUnsupportedError, U as IndexPredicateCanonicalizationError, V as IndexRenderSpec, W as IntrospectedModelIR, X as IntrospectionOptions, Y as MigrationSQLOptions, Z as NonConvergentSchemaDiffError, _ as NonConvergentSchemaDiffSurface, $ as PG_LEDGER_SHAPE_VERSION, a0 as PartialIndexPredicateNewEnumValueError, a1 as PgAdapter, a2 as PgAdapterOptions, a3 as PgAdmittedOperation, a4 as PgAdmittedOperationResult, a5 as PgAdvisoryLockKey, a6 as PgAdvisoryLockOptionsError, a7 as PgAdvisoryLockResult, a8 as PgApplicationStepOwnedState, a9 as PgApplicationStepTx, aa as PgBorrowedClientAdapterOptions, ab as PgCatalogueIdentityQueryable, ac as PgCompileOnlyAdapterOptions, ad as PgConvergeApplicationStep, ae as PgConvergeAssertStep, af as PgConvergeInitializationFailure, ag as PgConvergeOnceStep, ah as PgConvergePlannedStep, ai as PgConvergeRefusal, aj as PgConvergeRefusalChange, ak as PgConvergeRefusalError, al as PgLedgerLockResult, am as PgLedgerStorageUnsupportedError, an as PgLedgerTarget, ao as PgOutcomeCheckpoint, ap as PgOutcomeClaimRequest, aq as PgOutcomeExecutionRequest, ar as PgOutcomeNonTransactionalRequest, as as PgOutcomeReadBackFactory, at as PgOutcomeRecoveryRequest, au as PgOutcomeRecoveryResult, av as PgOutcomeResolution, aw as PgOutcomeResolutionAppendResult, ax as PgOutcomeResult, ay as PgOutcomeTransactionalRequest, az as PgOwnedCheckState, aA as PgPhysicalModelInput, aB as PgPhysicalModelInputError, aC as PgPhysicalNameClaim, aD as PgPhysicalNameCollision, aE as PgPhysicalNameCollisionError, aF as PgPhysicalNamespace, aG as PgPinnedConnectionAbortSignalError, aH as PgPoolAdapterOptions, aI as PgPreparedStatementReplayError, aJ as PgPreparedStatementsOptions, aK as PgRawSqlTransactionControlError, aL as PgReinitializePreflightOptions, aM as PgReinitializePreflightPool, aN as PgRollbackOnlyScope, aO as PgSchemaDiff, aP as PgTransactionAbortSignalError, aQ as PgTransactionAbortedCommitError, aR as PgTransactionAbortedError, aS as PgTransactionOptionsError, aT as PgTransactionTimeoutError, aU as RawIndexPredicateFallbackError, aV as ReferencedKeyKind, aW as ReferencedKeyRemovalConflict, aX as ReferencedKeyRemovalError, aY as SchemaChange, aZ as SchemaDiff, a_ as SchemaScopeOptions, a$ as TransitionRunIdentityMismatchError, b0 as WhereDispatcher, b1 as WhereHandler, b2 as acquirePgLedgerLocks, b3 as appendIntentJournal, b4 as appendTransitionAuthorization, b5 as assertCreateIndexSupported, b6 as assertCreateIndexesSupported, b7 as assertDeclarableChangeKind, b8 as assertGeneratedPostconditionSession, b9 as assertNoRepeatedExpressionSurfaceDrift, ba as canGenerateCreateIndex, bb as canonicalizeCheckConstraints, bc as comparePgDatabaseSchema, bd as compareSchemata, be as createPgAdapter, bf as createPgCompileOnlyAdapter, bg as createPgGeneratedManagedStep, bh as createPgPhysicalModel, bi as createPgTransitionRunPersister, bj as decodeGeneratedPostcondition, bk as decodeGeneratedPostconditionPayload, bl as defaultFkDerivation, bm as ensureDbspMetaLedger, bn as ensurePgLedger, bo as ensurePgLedgerStorageVersion, bp as ensureTransitionJournal, bq as executePgAdmittedOperation, br as generateCreateIndex, bs as generateDDL, bt as generateDownSQL, bu as generateMigrationSQL, bv as generatedPostconditionDigest, bw as generatedPostconditionForChange, bx as introspect, by as readPgCatalogueIdentity, bz as readPgLedgerMarker, bA as readPgLedgerReservationsForExecution, bB as readPgLedgerScopeCurrency, bC as readPgOutcomeRecoveryReadBack, bD as readVerifiedPgLedgerReservationsForPair, bE as recordPgLedgerIdentity, bF as renderCreateDbspMetaSchemaSql, bG as renderCreateIndex, bH as renderCreateLedgerEventTableSql, bI as renderCreateLedgerIdentityTableSql, bJ as renderCreateLedgerImmutabilityFunctionSql, bK as renderCreateLedgerImmutabilityTriggerSql, bL as renderCreateLedgerMarkerTableSql, bM as renderCreateLedgerReservationTableSql, bN as renderCreateLedgerTerminalMemberIndexSql, bO as renderCreateTransitionAuthorizationTableSql, bP as renderCreateTransitionJournalTableSql, bQ as renderCreateTransitionRunPlanTableSql, bR as renderCreateTransitionRunTableSql, bS as runPgReinitializePreflight, bT as toGeneratedPostconditionBindingAddress, bU as validatePgLedgerRuntimeIntegrity, bV as verifyGeneratedCheckPostcondition, bW as verifyGeneratedColumnPostcondition, bX as verifyGeneratedIdentityPostcondition, bY as verifyGeneratedIndexPostcondition, bZ as verifyGeneratedTablePostcondition, b_ as withGeneratedPostconditionSession } from './outcome-protocol-B3vRIj2q.js';
3
+ import { ExpressionRef, ModelIR } from '@dbsp/core';
3
4
  export { normalizeSQL } from '@dbsp/core';
4
5
  import * as _dbsp_types from '@dbsp/types';
5
- import { DialectCapabilities, ModelIR, ColumnListInput, ParamIntent, JsonAggOrderByEntry, IndexIR, HierarchyIR, Adapter, DbCasing, AdapterLogger, AdapterCapabilities, ConnectionAvailability, PlanReport, CompiledNqlQuery, CompileOptions, CompiledQuery, CompileResultWithIncludes, SubqueryIncludeInfo, ExpressionIntent, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, RecursivePlanReport, CteQueryIntent, SetOperationIntent, DumpMeta, Dump, AdapterStreamOptions, PinnedConnectionOptions, TransactionOptions, ColumnIR, MutationReturningItem, WhereIntent, OutputDescriptor, QueryIntent, LedgerHome, LedgerAddress, LedgerPayload, ScopedApprovalSet, NormalizedManagedStep, LedgerChainMember, OperationKindRef, SemanticArtifactRef, ProvenPlanShape, PostgreSqlObservationTargetIdentity, ExecutionContract, TransitionSessionClient, TransitionLessor, ExclusiveTransitionTarget, ObservationIssuer, ObservationRequest, ObservationContext, EvidenceObservation, TypeRef, ExpressionValue, CollationRef, LogicalIdentity, PhysicalOperation, OperationEffectAssessment, FingerprintManifest, DurableIntentRecord, IssuedObservation, ApplyGuard, AdvisoryObservation, TransactionalCompletionRecord, StepJournal, UnsafeNativeFragment, ResourceAddress, ExecutableAssertion, Assumption, TransitionRule, TransitionCompositionFact, TrustRoot, RequiredEnumLabelIR, TableReaddressDeclaration, LedgerReservationRow, LedgerRefusal, ContainmentClosureDestructiveOutcome, LedgerClaimKind } from '@dbsp/types';
6
- import * as _pgsql_types from '@pgsql/types';
6
+ import { LedgerPayload, LedgerAddress, NormalizedManagedStep, ColumnIR, MutationReturningItem, WhereIntent, DialectCapabilities, QueryIntent, CompiledQuery, SetOperationIntent, PlanReport, CompileOptions, LedgerHome, LedgerChainMember, OperationKindRef, SemanticArtifactRef, ProvenPlanShape, ExecutionContract, TransitionSessionClient, TransitionLessor, ExclusiveTransitionTarget, ObservationIssuer, ObservationRequest, ObservationContext, EvidenceObservation, ExpressionValue, LogicalIdentity, PhysicalOperation, OperationEffectAssessment, FingerprintManifest, DurableIntentRecord, IssuedObservation, ApplyGuard, AdvisoryObservation, TransactionalCompletionRecord, StepJournal, ResourceAddress, Assumption, TransitionRule, TransitionCompositionFact, ModelIR as ModelIR$1, TrustRoot, TableReaddressDeclaration, LedgerClaimKind } from '@dbsp/types';
7
7
  import { Node, OnConflictClause, ParamRef } from '@pgsql/types';
8
- import { C as ChangeKind, a as CompareSchemataOptions, S as SchemaDiff, T as TransitionJournalQueryable, P as PgLockedRun, b as PgOutcomeCheckpointObserver } from './outcome-protocol-CACJDzli.js';
9
- export { D as DiffSummary, E as ExpressionCanonicalizationUnavailableError, G as GeneratedPostcondition, c as GeneratedPostconditionBindingAddress, d as GeneratedPostconditionBindingResolutionError, e as GeneratedPostconditionProofInFlightError, f as GeneratedPostconditionReplanRequiredError, g as GeneratedPostconditionSession, h as GeneratedPostconditionSessionDeactivatedError, i as GeneratedPostconditionWorkInFlightError, j as PG_LEDGER_SHAPE_VERSION, k as PgAdmittedOperation, l as PgAdmittedOperationResult, m as PgCatalogueIdentityQueryable, n as PgLedgerLockResult, o as PgLedgerScopeCurrency, p as PgLedgerStorageUnsupportedError, q as PgLedgerTarget, r as PgOutcomeCheckpoint, s as PgOutcomeClaimRequest, t as PgOutcomeExecutionRequest, u as PgOutcomeNonTransactionalRequest, v as PgOutcomeReadBackFactory, w as PgOutcomeRecoveryRequest, x as PgOutcomeRecoveryResult, y as PgOutcomeResolution, z as PgOutcomeResolutionAppendResult, A as PgOutcomeResult, B as PgOutcomeTransactionalRequest, F as PgReinitializePreflightOptions, H as PgReinitializePreflightPool, I as SchemaChange, J as TransitionRunIdentityMismatchError, K as acquirePgLedgerLocks, L as appendIntentJournal, M as appendTransitionAuthorization, N as assertDeclarableChangeKind, O as assertGeneratedPostconditionSession, Q as compareSchemata, R as createPgTransitionRunPersister, U as createPgsqlGeneratedManagedStep, V as decodeGeneratedPostcondition, W as decodeGeneratedPostconditionPayload, X as ensureDbspMetaLedger, Y as ensurePgLedger, Z as ensurePgLedgerStorageVersion, _ as ensureTransitionJournal, $ as executePgAdmittedOperation, a0 as generatedPostconditionDigest, a1 as generatedPostconditionForChange, a2 as readPgCatalogueIdentity, a3 as readPgLedgerMarker, a4 as readPgLedgerReservationsForExecution, a5 as readPgLedgerScopeCurrency, a6 as readPgOutcomeRecoveryReadBack, a7 as readTransitionJournal, a8 as readVerifiedPgLedgerReservationsForPair, a9 as recordPgLedgerIdentity, aa as renderCreateDbspMetaSchemaSql, ab as renderCreateLedgerEventTableSql, ac as renderCreateLedgerIdentityTableSql, ad as renderCreateLedgerImmutabilityFunctionSql, ae as renderCreateLedgerImmutabilityTriggerSql, af as renderCreateLedgerMarkerTableSql, ag as renderCreateLedgerReservationTableSql, ah as renderCreateLedgerTerminalMemberIndexSql, ai as renderCreateTransitionAuthorizationTableSql, aj as renderCreateTransitionJournalTableSql, ak as renderCreateTransitionRunPlanTableSql, al as renderCreateTransitionRunTableSql, am as runPgReinitializePreflight, an as toGeneratedPostconditionBindingAddress, ao as validatePgLedgerRuntimeIntegrity, ap as verifyGeneratedCheckPostcondition, aq as verifyGeneratedColumnPostcondition, ar as verifyGeneratedIdentityPostcondition, as as verifyGeneratedIndexPostcondition, at as verifyGeneratedTablePostcondition, au as withGeneratedPostconditionSession } from './outcome-protocol-CACJDzli.js';
10
- import { Pool, PoolClient } from 'pg';
11
- import '@dbsp/core/internal';
8
+ import { ScopedApprovalSet, PostgreSqlObservationTargetIdentity, TypeRef, CollationRef, UnsafeNativeFragment, ExecutableAssertion, NamingPlugin, RequiredEnumLabelIR, LedgerReservationRow, LedgerRefusal, ContainmentClosureDestructiveOutcome } from '@dbsp/types/internal';
9
+ export { CamelCaseNamingPlugin, IdentityNamingPlugin, NamingPlugin, camelCaseNaming, getNamingPluginForDbCasing, identityNaming } from '@dbsp/types/internal';
10
+ import * as _dbsp_core_internal from '@dbsp/core/internal';
11
+ import { ValidatedManagedStepManifest, ExecutionCoordinator, CapabilityDescriptor } from '@dbsp/core/internal';
12
+ export { escapeDiagnosticText } from '@dbsp/core/internal';
13
+ import { PoolClient, Pool } from 'pg';
12
14
 
13
- /**
14
- * Default primary key column name used as convention fallback
15
- * when schema metadata doesn't provide an explicit PK.
16
- *
17
- * Consumers (handlers, compiler) must NOT use this directly —
18
- * they use `requiredColumn()` to throw on missing data.
19
- * Only convention mappers (extractors, introspection) should reference this.
20
- */
21
- declare const DEFAULT_PK_COLUMN = "id";
22
- /**
23
- * Derive a foreign key column name from a table name and the PK column it references.
24
- *
25
- * Convention: `${singularTableName}_${pkColumnName}`
26
- * e.g. (authors, id) → author_id, (categories, id) → category_id
27
- *
28
- * Consumers should use `deriveFkColumnName` from CompilerContext or options
29
- * for configurable behavior.
30
- */
31
- type FkColumnDerivation = (tableName: string, pkColumnName: string) => string;
32
- declare const defaultFkDerivation: FkColumnDerivation;
33
-
34
- /**
35
- * NamingPlugin - Identifier transformation between model and database naming conventions
36
- *
37
- * Inspired by Kysely's CamelCasePlugin architecture.
38
- * The plugin transforms identifiers bidirectionally:
39
- * - toDatabase: model name (camelCase) → database name (snake_case)
40
- * - toModel: database name (snake_case) → model name (camelCase)
41
- */
42
- /**
43
- * Interface for naming convention transformation plugins
44
- */
45
- interface NamingPlugin {
46
- /**
47
- * Transform a model identifier to database format
48
- * Example: "createdAt" → "created_at"
49
- */
50
- toDatabase(identifier: string): string;
51
- /**
52
- * Transform a database identifier to model format
53
- * Example: "created_at" → "createdAt"
54
- */
55
- toModel(identifier: string): string;
56
- }
57
- /**
58
- * Identity plugin - no transformation
59
- * Use this when model and database naming conventions match
60
- */
61
- declare class IdentityNamingPlugin implements NamingPlugin {
62
- toDatabase(identifier: string): string;
63
- toModel(identifier: string): string;
64
- }
65
- /**
66
- * CamelCase ↔ snake_case transformation plugin
67
- *
68
- * Follows the same logic as Kysely's CamelCasePlugin:
69
- * - Handles consecutive uppercase letters (e.g., "parseJSON" → "parse_json")
70
- * - Handles numbers (e.g., "field1Name" → "field1_name")
71
- * - Preserves leading underscores
72
- */
73
- declare class CamelCaseNamingPlugin implements NamingPlugin {
74
- /**
75
- * camelCase → snake_case
76
- */
77
- toDatabase(identifier: string): string;
78
- /**
79
- * snake_case → camelCase
80
- */
81
- toModel(identifier: string): string;
82
- }
83
- /**
84
- * Singleton instances for convenience
85
- */
86
- declare const identityNaming: IdentityNamingPlugin;
87
- declare const camelCaseNaming: CamelCaseNamingPlugin;
88
- /**
89
- * Get a naming plugin by DbCasing (intuitive semantics).
90
- * - `'snake_case'`: DB uses snake_case → CamelCaseNamingPlugin (transforms to camelCase)
91
- * - `'camelCase'`: DB uses camelCase → IdentityNamingPlugin (no transform)
92
- * - `'preserve'`: No transformation → IdentityNamingPlugin
93
- */
94
- declare function getNamingPluginForDbCasing(casing: 'snake_case' | 'camelCase' | 'preserve'): NamingPlugin;
95
-
96
- /**
97
- * Internal registry of NQL `| bind name` CTE names visible to a compile pass.
98
- *
99
- * Binding names are query-local identifiers, not physical tables. When an active
100
- * schema is present, real table FROM sources must be schema-qualified, while CTE
101
- * binding names must remain unqualified.
102
- */
103
-
104
- type BindingNameRegistry = ReadonlySet<string>;
105
-
106
- /**
107
- * Immutable context passed to all handlers during compilation.
108
- */
109
- interface CompilerContext {
110
- /** Naming convention transformer */
111
- readonly naming: NamingPlugin;
112
- /** Schema name for table qualification (optional) */
113
- readonly schema?: string;
114
- /** Dialect capabilities for adapter-layer SQL surface gates */
115
- readonly dialectCapabilities?: DialectCapabilities;
116
- /** Root table name for the query */
117
- readonly rootTable: string;
118
- /** Current table alias (for JOINs) */
119
- readonly currentAlias?: string;
120
- /** Final relation path/name → SQL join alias map for relation-aware expression contexts */
121
- readonly aliases?: ReadonlyMap<string, string>;
122
- /** Maximum recursive depth (default: 100) */
123
- readonly maxRecursiveDepth: number;
124
- /** Optional callback for raw SQL audit trail */
125
- readonly onRawSQL?: (sql: string) => void;
126
- /** Default primary key column name for convention fallbacks (default: 'id') */
127
- readonly defaultPkColumnName?: string;
128
- /** Convention for deriving FK column names: (tableName, pkName) => fkColumnName */
129
- readonly deriveFkColumnName?: FkColumnDerivation;
130
- /** Alias of the outer (parent) query — used for FieldRef scope:'outer' resolution in EXISTS subqueries */
131
- readonly outerAlias?: string;
132
- /** Query-local CTE/binding names that must not be schema-qualified. */
133
- readonly bindingNames?: BindingNameRegistry;
134
- /**
135
- * Optional callback to compile a QueryIntent into an AST Node (SubLink subselect).
136
- * Set by PlanCompiler when compiling selectCustomExpression — enables SubqueryExpressionIntent
137
- * to embed a fully compiled sub-SELECT into the parent SELECT column list.
138
- *
139
- * @param query - The inner QueryIntent to compile
140
- * @param paramOffset - Current outer paramIndex; inner $N are renumbered by this offset
141
- * @returns The compiled SelectStmt AST node and the inner parameters
142
- */
143
- readonly compileSubquery?: (query: _dbsp_types.QueryIntent, paramOffset: number) => {
144
- ast: Node;
145
- parameters: readonly unknown[];
146
- };
147
- /**
148
- * Optional recursive compiler for NQL-origin SELECT expression values nested
149
- * inside handler arguments, such as coalesce(upper(name), :fallback) or
150
- * (price + :a) * :b.
151
- */
152
- readonly compileNqlSelectExpression?: (value: unknown, ctx: CompilerContext, state: CompilerState) => Node;
153
- /**
154
- * Optional callback to compile a custom fn() FILTER (WHERE ...) condition.
155
- * Set by PlanCompiler to keep WHERE-dispatcher dependencies out of expression
156
- * handlers while still applying FILTER in every expression position.
157
- */
158
- readonly compileCustomFnFilter?: (filterIntent: _dbsp_types.WhereIntent, ctx: CompilerContext, state: CompilerState) => Node | undefined;
159
- /**
160
- * Optional ModelIR for type-aware parameter casting.
161
- * When provided, WHERE comparisons emit `$N::type` to eliminate
162
- * PostgreSQL type inference ambiguity for nullable columns.
163
- */
164
- readonly model?: ModelIR;
165
- }
166
- /**
167
- * Mutable state maintained during compilation.
168
- */
169
- interface CompilerState {
170
- /** Collected parameters in order */
171
- parameters: unknown[];
172
- /** Current parameter index (1-based for PostgreSQL) */
173
- paramIndex: number;
174
- /** Registered CTEs for the query */
175
- ctes: Map<string, Node>;
176
- /** Table aliases in use */
177
- aliases: Map<string, string>;
178
- /** JOIN clauses accumulated */
179
- joins: Node[];
180
- }
181
- /**
182
- * Base decision interface matching core's PlanDecision structure.
183
- */
184
- interface Decision {
185
- readonly type: string;
186
- readonly table?: string;
187
- readonly column?: string;
188
- readonly alias?: string;
189
- readonly operator?: string;
190
- readonly value?: unknown;
191
- readonly paramIndex?: number;
192
- readonly dataType?: string;
193
- readonly direction?: 'ASC' | 'DESC';
194
- readonly nulls?: 'FIRST' | 'LAST';
195
- readonly joinType?: 'inner' | 'left';
196
- readonly sourceColumn?: ColumnListInput;
197
- readonly targetColumn?: ColumnListInput;
198
- readonly targetTable?: string;
199
- readonly function?: string;
200
- /** Apply DISTINCT to a SELECT-list aggregate (e.g. COUNT(DISTINCT col)). */
201
- readonly distinct?: boolean;
202
- readonly args?: readonly unknown[];
203
- readonly conditions?: readonly Decision[];
204
- readonly columns?: readonly string[];
205
- readonly values?: readonly unknown[];
206
- readonly set?: readonly {
207
- column: string;
208
- value: unknown;
209
- }[];
210
- readonly limit?: number | ParamIntent | {
211
- paramIndex: number;
212
- };
213
- readonly offset?: number | ParamIntent | {
214
- paramIndex: number;
215
- };
216
- readonly strategy?: 'join' | 'lateral' | 'json_agg' | 'cte';
217
- readonly relation?: string;
218
- readonly relationName?: string;
219
- readonly relationPath?: string;
220
- readonly hydrationPrefix?: string;
221
- readonly include?: readonly Decision[];
222
- readonly relationType?: 'belongsTo' | 'hasMany' | 'hasOne';
223
- readonly foreignKey?: ColumnListInput;
224
- readonly parentKey?: ColumnListInput;
225
- readonly orderByFallback?: boolean;
226
- readonly children?: readonly Decision[];
227
- readonly partition?: readonly string[];
228
- readonly orderBy?: readonly {
229
- column: string;
230
- direction?: 'ASC' | 'DESC';
231
- }[] | readonly JsonAggOrderByEntry[];
232
- readonly frame?: string;
233
- readonly maxDepth?: number;
234
- readonly pathColumn?: string;
235
- readonly cycleDetection?: boolean;
236
- readonly selectColumn?: string;
237
- readonly aggregate?: string;
238
- /**
239
- * Apply DISTINCT to a scalar subquery's aggregate (e.g. AVG(DISTINCT price)).
240
- * Deliberately NOT named `distinct` — `assertNoDroppedDecisionModifiers`
241
- * (subquery-emission.ts) treats a top-level `distinct === true` on ANY
242
- * subquery decision as an unsupported query-level DISTINCT modifier and
243
- * throws. This field is scoped to the aggregate projection only, so it
244
- * must not collide with that generic guard.
245
- */
246
- readonly aggregateDistinct?: boolean;
247
- readonly subqueryOperator?: string;
248
- readonly traversal?: string;
249
- readonly traversals?: readonly {
250
- traversal: string;
251
- targetColumn?: string;
252
- }[];
253
- readonly isRecursive?: boolean;
254
- readonly fkColumn?: string;
255
- readonly pkColumn?: string;
256
- readonly expandRelation?: string;
257
- readonly relationColumns?: readonly string[];
258
- readonly columnAliases?: Readonly<Record<string, string>>;
259
- readonly jsonPath?: readonly unknown[];
260
- readonly jsonMode?: 'json' | 'text';
261
- readonly _compiledFilterWhere?: _pgsql_types.Node;
262
- readonly filterWhere?: _pgsql_types.Node;
263
- readonly expressionIntent?: unknown;
264
- readonly escape?: string;
265
- /**
266
- * Provenance: the ORIGINAL QueryIntent before lowering.
267
- * Set by every lowering site (convertIn, convertSubquery, normalizeToDecision,
268
- * dispatchWhere, mapInSubqueryCondition) so that `buildPredicateSubquerySelect`
269
- * (subquery-emission.ts) can validate the true caller intent rather than the
270
- * stripped-down lowered decision fields.
271
- *
272
- * Required for IN / scalar / inSubquery / notInSubquery decisions.
273
- * Optional on other decision types.
274
- */
275
- readonly subqueryIntent?: _dbsp_types.QueryIntent;
276
- }
277
- /**
278
- * Handler for WHERE clause conditions.
279
- * Transforms condition decisions into PostgreSQL AST expressions.
280
- */
281
- interface WhereHandler {
282
- /** Operator(s) this handler supports */
283
- readonly operators: readonly string[];
284
- /**
285
- * Compile a WHERE condition to AST.
286
- * @param decision The condition decision
287
- * @param ctx Immutable compiler context
288
- * @param state Mutable compiler state
289
- * @param dispatch Callback to compile nested conditions
290
- * @returns PostgreSQL AST node for the condition
291
- */
292
- compile(decision: Decision, ctx: CompilerContext, state: CompilerState, dispatch: WhereDispatcher): Node;
293
- }
294
- /**
295
- * Dispatcher for recursive WHERE compilation.
296
- * The same function object may be passed to every level of a recursive compilation, so it is an opaque callback.
297
- * Handlers must not use its identity to distinguish frames or carry frame-local state.
298
- */
299
- type WhereDispatcher = (decision: Decision, ctx: CompilerContext, state: CompilerState) => Node;
300
- /**
301
- * Handler for SELECT expressions.
302
- * Transforms expression decisions into PostgreSQL AST nodes.
303
- */
304
- interface ExpressionHandler {
305
- /** Expression type(s) this handler supports */
306
- readonly types: readonly string[];
307
- /**
308
- * Safe to use when a function name comes from NQL text.
309
- *
310
- * Raw/escape-hatch handlers must not set this. NQL-origin function names use
311
- * this opt-in surface only, then fall back to generic FuncCall emission.
312
- */
313
- readonly nqlSafe?: boolean;
314
- /**
315
- * Compile an expression to AST.
316
- * @param decision The expression decision
317
- * @param ctx Immutable compiler context
318
- * @param state Mutable compiler state
319
- * @returns PostgreSQL AST node for the expression
320
- */
321
- compile(decision: Decision, ctx: CompilerContext, state: CompilerState): Node;
322
- }
323
- /**
324
- * Handler for include/relation strategies.
325
- * Transforms include decisions into PostgreSQL constructs (JOIN, LATERAL, json_agg, CTE).
326
- */
327
- interface IncludeHandler {
328
- /** Strategy this handler implements */
329
- readonly strategy: 'join' | 'lateral' | 'json_agg' | 'cte';
330
- /**
331
- * Compile an include to AST.
332
- * @param decision The include decision
333
- * @param ctx Immutable compiler context
334
- * @param state Mutable compiler state
335
- * @returns Object with modifications to apply
336
- */
337
- compile(decision: Decision, ctx: CompilerContext, state: CompilerState): IncludeResult;
338
- }
339
- /**
340
- * Result of include compilation.
341
- */
342
- interface IncludeResult {
343
- /** Additional target list items (SELECT columns) */
344
- targets?: Node[];
345
- /** JOIN to add to FROM clause */
346
- join?: Node;
347
- /** Additional JOINs for cascaded includes (e.g., flat deep nesting) */
348
- additionalJoins?: Node[];
349
- /** CTE to add to WITH clause */
350
- cte?: Node;
351
- /** Subquery for LATERAL */
352
- lateral?: Node;
353
- }
354
-
355
- type PlanExpressionOrderBy = readonly {
356
- field: string;
357
- direction?: 'asc' | 'desc';
358
- }[];
359
- /**
360
- * Simplified PlanDecision for the spike
361
- * (In production, import from @dbsp/core)
362
- */
363
- interface PlanDecision {
364
- readonly type: string;
365
- readonly table?: string;
366
- readonly column?: string;
367
- readonly alias?: string;
368
- readonly field?: string;
369
- readonly operator?: string;
370
- readonly value?: unknown;
371
- readonly paramIndex?: number;
372
- readonly direction?: 'ASC' | 'DESC';
373
- readonly nulls?: 'FIRST' | 'LAST';
374
- readonly joinType?: 'inner' | 'left';
375
- readonly sourceColumn?: ColumnListInput;
376
- readonly targetColumn?: ColumnListInput;
377
- readonly targetTable?: string;
378
- readonly function?: string;
379
- readonly distinct?: boolean;
380
- readonly args?: readonly unknown[];
381
- readonly conditions?: readonly PlanDecision[];
382
- readonly columns?: readonly string[];
383
- readonly values?: readonly unknown[];
384
- readonly set?: readonly {
385
- column: string;
386
- value: unknown;
387
- }[];
388
- readonly limit?: number | ParamIntent | {
389
- paramIndex: number;
390
- };
391
- readonly offset?: number | ParamIntent | {
392
- paramIndex: number;
393
- };
394
- readonly partitionBy?: readonly string[];
395
- readonly orderBy?: PlanExpressionOrderBy | readonly JsonAggOrderByEntry[];
396
- readonly dataType?: string;
397
- readonly sourceTable?: string;
398
- readonly relationName?: string;
399
- readonly relationPath?: string;
400
- readonly hydrationPrefix?: string;
401
- readonly relationType?: 'belongsTo' | 'hasMany' | 'hasOne';
402
- readonly foreignKey?: ColumnListInput;
403
- readonly parentKey?: ColumnListInput;
404
- readonly orderByFallback?: boolean;
405
- readonly children?: readonly PlanDecision[];
406
- readonly intentPath?: string;
407
- readonly choice?: string;
408
- readonly subquery?: {
409
- readonly from: string;
410
- readonly select: string;
411
- readonly where?: PlanDecision;
412
- readonly limit?: number | ParamIntent;
413
- readonly orderBy?: readonly {
414
- field: string;
415
- direction?: string;
416
- }[];
417
- };
418
- readonly expressionType?: string;
419
- readonly relation?: string;
420
- readonly columnAliases?: Readonly<Record<string, string>>;
421
- readonly traversal?: string;
422
- readonly pkColumn?: string;
423
- readonly fkColumn?: string;
424
- readonly maxDepth?: number;
425
- readonly role?: string;
426
- readonly jsonPath?: readonly string[];
427
- readonly jsonMode?: 'json' | 'text';
428
- readonly selectColumn?: string;
429
- readonly aggregate?: string;
430
- /**
431
- * Apply DISTINCT to a scalar subquery's aggregate (e.g. AVG(DISTINCT price)).
432
- * Deliberately NOT named `distinct` — that field means "this decision's own
433
- * query-level DISTINCT modifier" and `assertNoDroppedDecisionModifiers`
434
- * (subquery-emission.ts) rejects it as unsupported on subquery decisions.
435
- */
436
- readonly aggregateDistinct?: boolean;
437
- readonly subqueryOperator?: string;
438
- readonly filterCondition?: PlanDecision;
439
- readonly expressionIntent?: unknown;
440
- readonly escape?: string;
441
- readonly include?: readonly PlanDecision[];
442
- readonly joinRarg?: Node;
443
- readonly joinOnNode?: Node;
444
- readonly batchValuesParams?: readonly unknown[];
445
- /**
446
- * Provenance: the ORIGINAL QueryIntent before lowering.
447
- * Carried through every lowering site (convertIn, convertSubquery,
448
- * normalizeToDecision, dispatchWhere, mapInSubqueryCondition) so that
449
- * `buildPredicateSubquerySelect` can validate the true caller intent.
450
- *
451
- * Required for IN / scalar / inSubquery / notInSubquery decisions.
452
- * Optional on other decision types.
453
- */
454
- readonly subqueryIntent?: _dbsp_types.QueryIntent;
455
- }
456
- /**
457
- * Any decision of type 'join'.
458
- * Narrows `type` to the literal 'join' for safe switch exhaustion.
459
- */
460
- interface JoinDecision extends PlanDecision {
461
- readonly type: 'join';
462
- }
463
- /**
464
- * A 'join' decision that carries pre-compiled PostgreSQL AST nodes.
465
- * Used by both table-mode and BatchValues-mode joins when the ON condition
466
- * has been compiled ahead of time in adapter-compiler-select.ts.
467
- *
468
- * The `joinRarg` is the right-hand RangeVar/RangeFunction; `joinOnNode` is
469
- * the A_Expr tree for the ON clause.
470
- */
471
- interface PrecompiledJoinDecision extends JoinDecision {
472
- readonly joinRarg: Node;
473
- readonly joinOnNode: Node;
474
- readonly joinOnParams?: readonly unknown[];
475
- }
476
- /**
477
- * A pre-compiled 'join' decision backed by a BatchValues unnest() source.
478
- * `batchValuesParams` must be spliced into compiler state BEFORE other query
479
- * parameters so that $1/$2/… ParamRefs in the RangeFunction align correctly.
480
- */
481
- interface BatchValuesJoinDecision extends PrecompiledJoinDecision {
482
- readonly batchValuesParams: readonly unknown[];
483
- }
484
- /** Narrows a PlanDecision to JoinDecision (type === 'join'). */
485
- declare function isJoinDecision(d: PlanDecision): d is JoinDecision;
486
- /**
487
- * Narrows a PlanDecision to PrecompiledJoinDecision.
488
- * True when the join carries pre-compiled `joinRarg` + `joinOnNode` AST nodes
489
- * (table mode or BatchValues mode).
490
- */
491
- declare function isPrecompiledJoinDecision(d: PlanDecision): d is PrecompiledJoinDecision;
492
- /**
493
- * Narrows a PlanDecision to BatchValuesJoinDecision.
494
- * True when the join is a BatchValues unnest() join and carries pre-spliced
495
- * parameter arrays in `batchValuesParams`.
496
- */
497
- declare function isBatchValuesJoinDecision(d: PlanDecision): d is BatchValuesJoinDecision;
498
- /**
499
- * Simplified PlanReport for the spike
500
- */
501
- interface SimplifiedPlanReport {
502
- readonly rootTable: string;
503
- readonly decisions: readonly PlanDecision[];
504
- readonly schema?: string;
505
- /** If true, wrap result in SELECT EXISTS(SELECT 1 ...) AS "exists" */
506
- readonly existsWrap?: boolean;
507
- /** Row-level lock (FOR UPDATE/SHARE/etc.) */
508
- readonly lock?: _dbsp_types.LockIntent;
509
- /**
510
- * When present, the FROM clause is replaced by a pre-compiled RangeFunction node
511
- * (e.g. unnest() AS alias) instead of the root table rangeVar.
512
- * `batchValuesFromParams` holds the parameter arrays to splice into state first.
513
- */
514
- readonly batchValuesFromNode?: unknown;
515
- readonly batchValuesFromParams?: readonly unknown[];
516
- }
517
- /**
518
- * Compiled query result
519
- */
520
- interface CompiledResult {
521
- readonly sql: string;
522
- readonly parameters: readonly unknown[];
523
- readonly ast: Node;
524
- }
525
- interface CompilerOptions {
526
- readonly naming?: NamingPlugin;
527
- readonly schema?: string;
528
- readonly dialectCapabilities?: DialectCapabilities;
529
- /** Default primary key column name convention (default: 'id') */
530
- readonly defaultPkColumnName?: string;
531
- /** Convention for deriving FK column names: (tableName, pkName) => fkColumnName */
532
- readonly deriveFkColumnName?: FkColumnDerivation;
533
- /** ModelIR for type-aware parameter casting in WHERE clauses */
534
- readonly model?: _dbsp_types.ModelIR;
535
- /** Query-local CTE/binding names that must not be schema-qualified. */
536
- readonly bindingNames?: BindingNameRegistry;
537
- }
538
- declare class PlanCompiler {
539
- private readonly naming;
540
- private readonly schema;
541
- private readonly defaultPk;
542
- private readonly deriveFk;
543
- private readonly model;
544
- private readonly dialectCapabilities;
545
- private readonly bindingNames;
546
- /** Mutable state shared with extracted condition/value compilation functions */
547
- private state;
548
- /** Track root table for EXISTS FK correlation */
549
- private currentRootTable;
550
- /** Pending JOINs registered by filter/include strategies (flushed in compileSelect) */
551
- private pendingJoins;
552
- /** Raw JOIN AST nodes from include handlers (e.g., LATERAL) */
553
- private rawJoins;
554
- /** CTE nodes from include handlers (e.g., CTE strategy) */
555
- private pendingCtes;
556
- /** Local aliases for binding relation-column scalar subqueries. */
557
- private bindingRelationColumnSubqueryIndex;
558
- /**
559
- * Maps relation-dotted include path → JOIN alias for multi-hop FK resolution.
560
- * Populated as join decisions are compiled so later hops can find the
561
- * correct source alias (e.g., 'callee.file' reads parent path 'callee').
562
- */
563
- private joinAliasMap;
564
- /**
565
- * Tracks all join aliases in use for the current query.
566
- * Entries are stored in emitted database-alias space, after naming.toDatabase().
567
- * Ensures no two JOINs share the same alias (DOUBLE-ALIAS prevention).
568
- */
569
- private usedJoinAliases;
570
- constructor(options?: CompilerOptions);
571
- private childCompilerOptions;
572
- /** Build immutable context for handler-based WHERE compilation */
573
- private handlerCtx;
574
- private findAliasForLegacySourceTable;
575
- private emittedJoinAlias;
576
- private resolvedJoinAliases;
577
- /**
578
- * Dispatch a PlanDecision through the unified WHERE handler system.
579
- * Bridges PlanCompiler's state to handler types, calls dispatcher, syncs back.
580
- */
581
- private dispatchWhere;
582
- /**
583
- * Recursively convert a PlanDecision (potentially with nested in+subquery
584
- * or a logical group whose children contain in+subquery nodes) into a
585
- * HandlerDecision suitable for the WHERE dispatcher.
586
- *
587
- * When a PlanDecision has operator='in'/'notIn' with a subquery object,
588
- * mapToHandlerDecision loses the subquery because HandlerDecision has no
589
- * `subquery` field. This method detects that pattern and converts it to the
590
- * inSubquery/notInSubquery form that buildScalarSubquery expects.
591
- *
592
- * When the node is a logical group (whereAnd / whereOr / whereNot), each
593
- * child in `conditions` / `condition` is mapped recursively so that nested
594
- * IN+subquery nodes at any depth are guarded and remapped correctly, rather
595
- * than falling through to mapToHandlerDecision which would silently drop the
596
- * subquery and produce a malformed plain-IN binding.
597
- *
598
- * Called recursively so 2+ levels of nesting all work.
599
- */
600
- private mapInSubqueryCondition;
601
- /**
602
- * Bridge PlanDecision to handler Decision and dispatch to include handler.
603
- * Returns targets and optional pending joins to apply.
604
- */
605
- private compileIncludeViaHandler;
606
- /**
607
- * Compile a simplified plan report to SQL
608
- */
609
- compile(plan: SimplifiedPlanReport): CompiledResult;
610
- private detectQueryType;
611
- /** Build a HandlerCompilerContext for the given plan and optional alias override. */
612
- private createHandlerContext;
613
- /** Build a fresh HandlerCompilerState sharing the current parameter array. */
614
- private createHandlerState;
615
- private schemaForRangeVar;
616
- private isNqlBindingRoot;
617
- private allocateBindingRelationAlias;
618
- private buildCorrelatedRelationRefs;
619
- private bindingRelationHasCompleteManyToManyProof;
620
- private bindingRelationName;
621
- private bindingRelationNameLooksRecursive;
622
- private compileBindingRecursiveRelationColumnSubquery;
623
- private compileBindingRelationColumnSubquery;
624
- private compileExpressionSubquery;
625
- private compileGenericNqlFunction;
626
- private compileNqlFunctionArg;
627
- private compileNqlCaseExpressionArg;
628
- /**
629
- * Compile a SELECT-list target via expression handler.
630
- * Wraps the node in a ResTarget and pushes it onto targetList.
631
- */
632
- private compileSelectTarget;
633
- /**
634
- * Compile an includeStrategy decision and register its results.
635
- * Pushes targets onto targetList, raw joins / CTEs onto instance collections.
636
- */
637
- private registerIncludeCompilationResult;
638
- private compileIncludeDecision;
639
- private compileJoinIncludeAllocationPass;
640
- /**
641
- * Fold a WHERE-family decision into an existing where expression.
642
- * Returns the updated (or new) where node.
643
- */
644
- private compileWhereDecision;
645
- /**
646
- * Flush pendingJoins and rawJoins into the FROM clause.
647
- * Mutates the from array in-place.
648
- */
649
- private flushPendingJoins;
650
- /**
651
- * Build the initial FROM clause array and register batch-values parameters.
652
- * For batch-values queries, the unnest RangeFunction replaces the root rangeVar.
653
- */
654
- private compileFromClause;
655
- /**
656
- * Fold WHERE conditions from a join-strategy include decision into the
657
- * accumulated WHERE expression. The join alias is used as currentAlias so
658
- * column refs like `project_id` resolve against the joined table, not root.
659
- */
660
- private compileIncludeWhereConditions;
661
- private reserveManualJoinAliases;
662
- /**
663
- * Apply a single join decision to the FROM clause in-place.
664
- * Chains multiple joins by wrapping from[0] as the left-arg each time.
665
- */
666
- private compileJoinDecision;
667
- /**
668
- * Compile a single orderBy decision into a SortBy AST node.
669
- * Supports both expression-intent and plain column references.
670
- */
671
- /**
672
- * Compile a single orderBy decision into a SortBy AST node.
673
- * Supports both expression-intent and plain column references.
674
- * Returns undefined when neither expressionIntent nor column is present.
675
- */
676
- private compileOrderByDecision;
677
- /**
678
- * Compile a column reference that may use dotted 'relation.column' notation.
679
- */
680
- private compileRelationAwareColumnRef;
681
- /**
682
- * Compile a single groupBy decision into a ColumnRef AST node.
683
- * Supports dotted 'relation.column' notation for joined tables.
684
- */
685
- private compileGroupByDecision;
686
- /**
687
- * Compile a DISTINCT ON column into a ColumnRef AST node.
688
- * Mirrors GROUP BY relation-alias resolution while preserving unqualified
689
- * DISTINCT ON columns as unqualified references.
690
- */
691
- private compileDistinctOnColumn;
692
- /**
693
- * Assemble the final SelectStmt from all accumulated clause nodes.
694
- * Also handles the default SELECT *, CTEs, and row-level locking.
695
- */
696
- private buildSelectStmt;
697
- private compileSelect;
698
- /**
699
- * Wrap a SELECT statement in SELECT EXISTS(SELECT 1 ...) AS "exists"
700
- *
701
- * This transforms the inner SELECT by:
702
- * 1. Replacing targetList with just `1` (constant)
703
- * 2. Wrapping in SubLink with EXISTS_SUBLINK
704
- * 3. Creating outer SELECT with EXISTS result aliased as "exists"
705
- */
706
- private wrapSelectInExists;
707
- private compileCaseExpression;
708
- /**
709
- * Compile a CASE THEN/ELSE value based on its ExpressionIntent kind.
710
- * Delegates to shared resolveCaseValue with nested CASE support.
711
- */
712
- private compileCaseValue;
713
- /**
714
- * Compile a custom ExpressionIntent (customFn, customOp, ref, cast, unary,
715
- * array, function, subquery, …) to an AST node through the shared expression
716
- * compiler. Shared by the `selectCustomExpression` target path and CASE
717
- * THEN/ELSE values so both render the full expression surface identically.
718
- */
719
- private compileCustomExpressionNode;
720
- private compileInsert;
721
- private compileUpdate;
722
- private compileDelete;
723
- /**
724
- * Register an INNER JOIN for a belongsTo filter-strategy decision.
725
- * The JOIN replaces the EXISTS subquery when the planner chooses 'join'.
726
- * The ON condition correlates FK → PK (belongsTo: source.FK = target.PK).
727
- */
728
- private registerJoinFilter;
729
- private compileJoin;
730
- }
731
- /**
732
- * Convenience function to compile a plan
733
- */
734
- declare function compilePlan(plan: SimplifiedPlanReport, options?: CompilerOptions): CompiledResult;
735
-
736
- declare function dbTypesEqual(a: string, b: string): boolean;
737
-
738
- type IndexRenderKey = {
739
- readonly column?: string | undefined;
740
- readonly expression?: string | undefined;
741
- readonly opclass?: string | undefined;
742
- };
743
- type IndexRenderSpec = {
744
- readonly name: string;
745
- readonly table: string;
746
- readonly schema?: string | undefined;
747
- readonly unique: boolean;
748
- readonly method?: string | undefined;
749
- readonly keys: readonly IndexRenderKey[];
750
- readonly include?: readonly string[] | undefined;
751
- readonly nullsNotDistinct?: boolean | undefined;
752
- readonly with?: Readonly<Record<string, unknown>> | undefined;
753
- readonly where?: string | undefined;
754
- /** The in-process index value that owns a deparsed `where` predicate. */
755
- readonly whereSource?: IndexIR | undefined;
756
- readonly concurrently?: boolean | undefined;
757
- readonly ifNotExists?: boolean | undefined;
758
- };
759
- type IndexCapabilityContext = {
760
- readonly caps: DialectCapabilities;
761
- readonly targetVersion?: string | undefined;
762
- };
763
- type IndexFeature = 'INCLUDE' | 'PARTIAL INDEX' | 'EXPRESSION INDEX' | 'INDEX METHOD' | 'OPCLASS' | 'NULLS NOT DISTINCT';
764
- declare class IndexFeatureUnsupportedError extends Error {
765
- readonly indexName: string;
766
- readonly unsupportedFeatures: readonly IndexFeature[];
767
- constructor(indexName: string, unsupportedFeatures: readonly IndexFeature[], message: string);
768
- }
769
- declare function assertCreateIndexSupported(spec: IndexRenderSpec, ctx?: IndexCapabilityContext): void;
770
- declare function assertCreateIndexesSupported(specs: readonly IndexRenderSpec[], ctx?: IndexCapabilityContext): void;
771
- declare function renderCreateIndex(spec: IndexRenderSpec, ctx?: IndexCapabilityContext): string;
772
-
773
- /**
774
- * DDL Generator - Generates PostgreSQL DDL statements from ModelIR
775
- *
776
- * Generates SQL strings directly for better compatibility and control.
777
- * Two-pass strategy handles circular FK dependencies.
778
- *
779
- * @module ddl/ddl-generator
780
- */
781
-
782
- interface GenerateDDLOptions {
783
- /** Include DROP TABLE IF EXISTS statements before CREATE TABLE */
784
- readonly includeDropStatements?: boolean;
785
- /**
786
- * Database schema name (e.g., 'public', 'tenant_123').
787
- * Required when emitted DDL would otherwise mix non-default target-scoped
788
- * custom types/enums with unqualified table SQL.
789
- */
790
- readonly schemaName?: string;
791
- /**
792
- * Automatically create indexes on foreign key columns.
793
- * FK columns are frequently used in JOINs, so indexing is a best practice.
794
- * @default true
795
- */
796
- readonly fkAutoIndex?: boolean;
797
- /** Naming plugin for identifier transformation */
798
- readonly naming?: NamingPlugin;
799
- /** Dialect capabilities — unsupported index features throw during DDL generation */
800
- readonly dialectCapabilities?: DialectCapabilities;
801
- }
802
- /**
803
- * Generate DDL statements from a ModelIR schema.
804
- *
805
- * Uses a two-pass approach to handle circular FK dependencies:
806
- * 1. CREATE TABLE (without FK constraints)
807
- * 2. ALTER TABLE ADD CONSTRAINT for foreign keys
808
- * 3. CREATE INDEX (explicit + auto-generated for FKs)
809
- *
810
- * @param schema - The ModelIR schema to generate DDL from
811
- * @param options - Optional configuration
812
- * @returns Array of DDL statements in dependency order
813
- */
814
- declare function generateDDL(schema: ModelIR, options?: GenerateDDLOptions): string[];
815
- declare function generateCreateIndex(tableName: string, idx: IndexIR, schemaName: string | undefined, naming: NamingPlugin, context?: IndexCapabilityContext, ifNotExists?: boolean): string;
816
- /**
817
- * Returns whether the PostgreSQL DDL generator can emit this IndexIR.
818
- *
819
- * Keep this as the single representability predicate for generated schema
820
- * omission and destructive-drop classification: both sides must agree on the
821
- * exact validation surface used by generateCreateIndex().
822
- */
823
- declare function canGenerateCreateIndex(tableName: string, idx: IndexIR, schemaName?: string | undefined, naming?: NamingPlugin): boolean;
824
-
825
- /** EFF-04's closed generated-mutation result domain. */
826
- type GeneratedMutationClassification = 'non-destructive' | 'removal' | 'data-destructive'
827
- /** A table rename is executed only by the paired re-address protocol. */
828
- | 'paired-readdress';
829
- /**
830
- * Total, fail-closed classifier for generator mutations. `string` is deliberate:
831
- * a newly-added ChangeKind cannot silently become safe before this table names it.
832
- */
833
- declare function classifyGeneratedMutation(kind: ChangeKind | string, change?: {
834
- readonly destructive?: boolean;
835
- }): GeneratedMutationClassification;
836
- declare function isGeneratedMutationDestructive(kind: ChangeKind | string, change?: {
837
- readonly destructive?: boolean;
838
- }): boolean;
839
- /** All removal statements remain generator-only; no transition operation maps one. */
840
- declare function refusesRecordedPlanRemoval(kind: ChangeKind | string, change?: {
841
- readonly destructive?: boolean;
842
- }): boolean;
843
-
844
- /**
845
- * PostgreSQL Schema Introspection (ADAPTER-006)
846
- *
847
- * Queries information_schema/pg_catalog to build ModelIR
848
- * from an existing database. Supports:
849
- * - Table/column/PK discovery
850
- * - FK → bidirectional relation inference
851
- * - Hierarchy detection (adjacency + edge-table)
852
- * - Include/exclude filtering
853
- *
854
- * @module introspection
855
- */
856
-
857
- /** The minimum every schema-level operation needs: which schema. */
858
- interface SchemaScopeOptions {
859
- /** Schema name to operate on (default: 'public') */
860
- readonly schema?: string;
861
- }
862
- /**
863
- * Introspection additionally chooses WHICH TABLES to read. It is a read-only
864
- * path, so narrowing it is safe — that is why the table filters live here and
865
- * nowhere else.
866
- */
867
- interface IntrospectionOptions extends SchemaScopeOptions {
868
- /** Tables to exclude (glob patterns: * matches any chars) */
869
- readonly exclude?: readonly string[];
870
- /** Tables to include (default: all). Applied before exclude. */
871
- readonly include?: readonly string[];
872
- }
873
- /** Hierarchy pattern detected during introspection */
874
- /**
875
- * Hierarchy pattern detected during introspection.
876
- * Alias of {@link HierarchyIR} from \@dbsp/types — kept here for
877
- * public-API backwards compatibility (re-exported from \@dbsp/adapter-pgsql).
878
- */
879
- type DetectedHierarchy = HierarchyIR;
880
- /** Extended ModelIR with hierarchy metadata */
881
- interface IntrospectedModelIR extends ModelIR {
882
- readonly hierarchies: readonly DetectedHierarchy[];
883
- readonly introspectedAt: Date;
884
- readonly warnings: readonly string[];
885
- }
886
- /**
887
- * Introspect a database through a pool.
888
- *
889
- * This does NOT accept a checked-out `PoolClient`, and that is deliberate. A
890
- * client may be sitting inside a transaction that belongs to its owner, and a
891
- * catalog query that fails there aborts *their* transaction. Protecting that
892
- * needs a savepoint, and knowing whether to take one needs the caller to say
893
- * whose transaction it is — which is what `PgsqlAdapter`'s `borrowedClient`
894
- * declaration is for. Guessing it from the object's shape is the exact defect
895
- * this adapter was rewritten to remove.
896
- *
897
- * Saying so in a comment is not enough: `CatalogQueryExecutor` is structural, so
898
- * a `PoolClient` — which has a `query()` — satisfies it, and the prose would have
899
- * been the only thing standing in the way. It is branded instead, and only the
900
- * adapter's own protected executor carries the brand. A client cannot be passed
901
- * here at all.
902
- *
903
- * So: hold a client, use `new PgsqlAdapter(client, { borrowedClient: true })`
904
- * and call `.introspect()` on it.
905
- */
906
- declare function introspect(pool: Pool, options?: IntrospectionOptions): Promise<IntrospectedModelIR>;
907
-
908
- type PgsqlTransactionTimeoutParameter = 'lock_timeout' | 'statement_timeout';
909
-
910
- /**
911
- * PgsqlAdapter - Implements the Adapter interface for PostgreSQL using native pg driver.
912
- *
913
- * This adapter wraps a pg Pool instance and provides the unified
914
- * adapter interface for the db-semantic-planner ORM.
915
- *
916
- * @module pgsql-adapter
917
- */
918
-
919
- declare const rollbackOnlyPgsqlScopeBrand: unique symbol;
920
- /** A scope minted by withScratchScope and guaranteed to roll back on success. */
921
- type RollbackOnlyPgsqlScope<DB = unknown> = PgsqlAdapter<DB> & {
922
- readonly [rollbackOnlyPgsqlScopeBrand]: typeof rollbackOnlyPgsqlScopeBrand;
923
- };
924
- type PgAdvisoryLockKey = bigint | {
925
- readonly classId: number;
926
- readonly objId: number;
927
- };
928
- type PgAdvisoryLockResult<T> = {
929
- readonly acquired: true;
930
- readonly value: T;
931
- } | {
932
- readonly acquired: false;
933
- };
934
- declare class PgsqlRawSqlTransactionControlError extends Error {
935
- readonly dbspRawSqlTransactionControl = true;
936
- constructor(cause: unknown);
937
- }
938
- declare class PgsqlTransactionAbortedCommitError extends Error {
939
- readonly dbspTransactionAbortedCommit = true;
940
- constructor(cause: unknown);
941
- }
942
- declare class PgsqlTransactionAbortedError extends Error {
943
- readonly dbspTransactionAborted = true;
944
- constructor(cause: unknown);
945
- }
946
- /**
947
- * Raised when a pool-owned top-level transaction is aborted through
948
- * `TransactionOptions.signal`. If the signal aborts while `pool.connect()` is
949
- * still pending, dbsp honors it only after a client is acquired.
950
- */
951
- declare class PgsqlTransactionAbortSignalError extends Error {
952
- readonly dbspTransactionAbortSignal = true;
953
- constructor();
954
- }
955
- declare class PgsqlPinnedConnectionAbortSignalError extends Error {
956
- readonly dbspPinnedConnectionAbortSignal = true;
957
- constructor();
958
- }
959
- declare class PgsqlTransactionOptionsError extends Error {
960
- readonly dbspTransactionOptions = true;
961
- constructor(message: string);
962
- }
963
- declare class PgsqlAdvisoryLockOptionsError extends Error {
964
- readonly dbspAdvisoryLockOptions = true;
965
- constructor(message: string);
966
- }
967
- /**
968
- * Raised when a statement inside a dbsp-managed transaction fails with a SQLSTATE
969
- * that matches a timeout the caller configured for that transaction: `55P03`
970
- * (`lock_not_available`) when `lockTimeoutMs` was set, or `57014` (`query_canceled`)
971
- * when `statementTimeoutMs` was set. The original PostgreSQL error is preserved as
972
- * `cause`.
973
- *
974
- * Classification is by SQLSTATE only. PostgreSQL assigns these codes to the OUTCOME,
975
- * not the cause: `55P03` is also raised by `FOR UPDATE NOWAIT`, and `57014` is also
976
- * raised by an external cancel (e.g. `pg_cancel_backend`). There is no locale-stable
977
- * structured field that separates the timeout from the other cause, so the message
978
- * text is deliberately NOT parsed. dbsp never emits `NOWAIT` itself, so a `55P03`
979
- * here is the configured `lock_timeout` unless the caller's own raw SQL used
980
- * `NOWAIT`; a `57014` is the configured `statement_timeout` unless the backend was
981
- * cancelled from outside. Inspect `cause` when that distinction matters.
982
- */
983
- declare class PgsqlTransactionTimeoutError extends Error {
984
- readonly timeout: PgsqlTransactionTimeoutParameter;
985
- readonly dbspTransactionTimeout = true;
986
- constructor(cause: unknown, timeout: PgsqlTransactionTimeoutParameter);
987
- }
988
- /**
989
- * Raised when the single safe unnamed replay after a prepared-statement
990
- * infrastructure failure also fails. `message` is always the safe constant
991
- * `Prepared statement recovery replay failed.`; `cause` is the replay error;
992
- * `infrastructureError` is the original infrastructure error; and
993
- * `admissionFingerprint` identifies the admitted statement. DBSP-authored
994
- * messages carry no parameter values; preserved upstream errors, including the
995
- * standard Error `cause`, are unsanitized.
996
- */
997
- declare class PgsqlPreparedStatementReplayError extends Error {
998
- readonly admissionFingerprint: string;
999
- readonly infrastructureError: unknown;
1000
- readonly dbspPreparedStatementReplay = true;
1001
- readonly originalInfrastructureError: unknown;
1002
- readonly originalError: unknown;
1003
- constructor(admissionFingerprint: string, infrastructureError: unknown, cause: unknown);
1004
- }
1005
- /**
1006
- * Options for PgsqlAdapter.
1007
- */
1008
- interface PgsqlPreparedStatementsOptions {
1009
- /** Maximum distinct compiled statements admitted per executor (default: 500). */
1010
- readonly maxStatements?: number;
1011
- }
1012
- interface PgsqlAdapterOptions {
1013
- /** Schema name for multi-tenant queries */
1014
- readonly schemaName?: string;
1015
- /**
1016
- * DB column casing convention (intuitive semantics).
1017
- * - `'snake_case'`: DB columns are snake_case → transform to camelCase for JS
1018
- * - `'camelCase'`: DB columns are camelCase → no transformation
1019
- * - `'preserve'`: No transformation
1020
- */
1021
- readonly dbCasing?: DbCasing;
1022
- /** Optional model for WHERE compilation */
1023
- readonly model?: ModelIR;
1024
- /** Optional logger for debug/error messages */
1025
- readonly logger?: AdapterLogger;
1026
- /** Default primary key column name for convention fallbacks (default: 'id') */
1027
- readonly defaultPkColumnName?: string;
1028
- /** Convention for deriving FK column names: (tableName, pkName) => fkColumnName */
1029
- readonly deriveFkColumnName?: FkColumnDerivation;
1030
- /**
1031
- * Opt in to node-postgres named prepared statements for compiled queries with
1032
- * parameters. `true` uses the default statement cap; an object overrides it.
1033
- */
1034
- readonly preparedStatements?: boolean | PgsqlPreparedStatementsOptions;
1035
- }
1036
- interface PgsqlPoolAdapterOptionsBase extends PgsqlAdapterOptions {
1037
- readonly borrowedClient?: false;
1038
- }
1039
- type PgsqlPoolAdapterOptions = (PgsqlPoolAdapterOptionsBase & {
1040
- readonly replayInvalidatedPlans?: false | undefined;
1041
- }) | (Omit<PgsqlPoolAdapterOptionsBase, 'preparedStatements'> & {
1042
- readonly preparedStatements: true | PgsqlPreparedStatementsOptions;
1043
- /**
1044
- * Enable one unnamed replay after `0A000`/`RevalidateCachedQuery` only when
1045
- * you assert that your statements do not invoke functions performing
1046
- * effectful work before nested prepared-statement operations. This requires
1047
- * `preparedStatements: true` (or a prepared-statements options object).
1048
- *
1049
- * Replay snapshots JSON-like values (finite numbers, strings, booleans,
1050
- * `null`, arrays, plain or null-prototype objects) and clean `Date`/`Buffer`
1051
- * instances. It excludes non-finite numbers, `undefined`, `bigint`, functions,
1052
- * proxies, cycles, sparse arrays, accessors, symbol-valued
1053
- * parameters, symbol keys on plain objects, exotic prototypes, custom built-ins,
1054
- * and values with their own node-postgres
1055
- * `toPostgres` behavior.
1056
- * Serialization-irrelevant symbol metadata on arrays and Buffers is ignored.
1057
- * The detached snapshot covers later mutations to the supplied value graph,
1058
- * not built-in prototypes, timezone state, or node-postgres serialization
1059
- * configuration; a process-global `toPostgres` or `toJSON` installed while
1060
- * the call is in flight is outside the guarantee. Each capture or replay copy
1061
- * is independently limited to 64 Ki visited values, 16 MiB of UTF-8 strings,
1062
- * and 16 MiB of Buffer data. An ineligible or over-budget value still receives
1063
- * the initial named submission, but disables transparent replay.
1064
- * These budgets bound copied nodes and payload bytes; enumerating a plain
1065
- * object's existing property table is proportional to the caller's own object.
1066
- *
1067
- * Replay needs the adapter-owned serialized physical client available from a
1068
- * pool; it is therefore not supported by borrowed or compile-only adapters.
1069
- */
1070
- readonly replayInvalidatedPlans: true;
1071
- });
1072
- interface PgsqlBorrowedClientAdapterOptions extends PgsqlAdapterOptions {
1073
- /** Replay is only available to a pool-owned pinned scope. */
1074
- readonly replayInvalidatedPlans?: never;
1075
- /** This connection belongs to the caller. dbsp never releases it. */
1076
- readonly borrowedClient: true;
1077
- /**
1078
- * Let dbsp run transactions on your connection, through a savepoint.
1079
- *
1080
- * When your connection is already inside a transaction, dbsp creates a
1081
- * savepoint and rolls back dbsp's changes after that savepoint if the callback
1082
- * fails. `RELEASE SAVEPOINT` does not commit; it merges the work into your
1083
- * surrounding transaction, so a callback that succeeded is still undone if you
1084
- * later roll back. Deferred constraints or triggers can still make your outer
1085
- * `COMMIT` fail after dbsp has returned. `SET LOCAL` changes inside the callback
1086
- * remain in effect for the rest of your transaction after the savepoint is
1087
- * released. `ON COMMIT DROP` and `ON COMMIT DELETE ROWS` fire at your transaction
1088
- * boundary, not at the savepoint. Sequences are not transactional:
1089
- * `nextval`/`setval` are not reclaimed by a savepoint rollback. Session-level
1090
- * advisory locks ignore rollback; transaction-level advisory locks taken by a
1091
- * successful callback last until your transaction ends.
1092
- *
1093
- * Transaction control through raw SQL inside a scope dbsp is managing is
1094
- * unsupported. `COMMIT`, `ROLLBACK`, and `PREPARE TRANSACTION` end the
1095
- * transaction dbsp is working inside; dbsp detects that and fails loudly, but
1096
- * the data is already whatever your statement made it. Raw savepoint control
1097
- * (`SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`) can alter the
1098
- * savepoint stack before dbsp sees the command tag; dbsp poisons the scope, but
1099
- * it cannot make that command un-run. Manage your transaction outside dbsp's
1100
- * calls.
1101
- */
1102
- readonly managedTransactions?: true;
1103
- }
1104
- /** Options for a connectionless adapter, which cannot own replay serialization. */
1105
- interface PgsqlCompileOnlyAdapterOptions extends PgsqlAdapterOptions {
1106
- readonly replayInvalidatedPlans?: never;
1107
- }
1108
- /**
1109
- * Adapter implementation for PostgreSQL using native pg driver.
1110
- *
1111
- * @typeParam DB - Database schema type
1112
- *
1113
- * @example
1114
- * ```typescript
1115
- * import { Pool } from 'pg';
1116
- * import { createPgsqlAdapter } from '@dbsp/adapter-pgsql';
1117
- *
1118
- * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
1119
- * const adapter = createPgsqlAdapter(pool);
1120
- * const orm = createOrm({ model, adapter });
1121
- * ```
1122
- */
1123
- declare class PgsqlAdapter<DB = unknown> implements Adapter<DB> {
1124
- private readonly pool;
1125
- private readonly client;
1126
- private readonly borrowedClient;
1127
- private readonly managedTransactions;
1128
- private readonly adapterManagedTransaction;
1129
- private readonly adapterManagedPinnedConnection;
1130
- private readonly rollbackOnlyScope;
1131
- private readonly scopeToken;
1132
- private readonly scopeState;
1133
- private readonly schemaName;
1134
- private readonly _dbCasing;
1135
- private readonly naming;
1136
- private readonly model;
1137
- private readonly logger;
1138
- private readonly replayInvalidatedPlans;
1139
- private readonly preparedStatements;
1140
- private readonly preparedStatementRegistry;
1141
- private readonly _capabilities;
1142
- private readonly defaultPk;
1143
- private readonly deriveFk;
1144
- /**
1145
- * Create a new PgsqlAdapter.
1146
- *
1147
- * Ownership of the connection is **declared**, never inferred. Handing over a
1148
- * `PoolClient` means nothing on its own — it says the object has a `release()`
1149
- * method, not that a transaction is open or that the caller owns the lifecycle.
1150
- * Pass `borrowedClient: true` to say so.
1151
- *
1152
- * @param pool - a pg.Pool, a caller-owned pg.PoolClient (with `borrowedClient: true`),
1153
- * or nothing at all for compile-only mode
1154
- * @param options - configuration; declares connection ownership
1155
- */
1156
- constructor(pool: Pool, options?: PgsqlPoolAdapterOptions);
1157
- constructor(client: PoolClient, options: PgsqlBorrowedClientAdapterOptions);
1158
- constructor(pool?: undefined, options?: PgsqlCompileOnlyAdapterOptions);
1159
- /**
1160
- * Shared compilation dependencies — built lazily from adapter fields.
1161
- * Passed to compiler sub-modules instead of `this`.
1162
- */
1163
- /**
1164
- * Return a new PgsqlAdapterOptions that merges current config with overrides.
1165
- * Ensures that all configuration fields (logger, defaultPkColumnName,
1166
- * deriveFkColumnName, etc.) are propagated to scoped/transactional adapters.
1167
- */
1168
- private cloneOptions;
1169
- private buildCompileDeps;
1170
- private requireNqlCompileModel;
1171
- private assertNqlBindingNamesDisjointFromTables;
1172
- private compileNqlMutation;
1173
- private compileNqlBundleLeafEnvelope;
1174
- private compileNqlBundle;
1175
- /**
1176
- * Returns the pool/client executor, or refuses a connectionless adapter.
1177
- */
1178
- private requireConnection;
1179
- /** Adapter capabilities for feature detection */
1180
- get capabilities(): AdapterCapabilities;
1181
- /** Per-instance connection state, distinct from PostgreSQL capabilities. */
1182
- get connectionAvailability(): ConnectionAvailability;
1183
- /** Side-effect-free execution availability for core feature detection. */
1184
- executionAvailable(): boolean;
1185
- /** PostgreSQL dialect capabilities for planner strategy selection */
1186
- get dialectCapabilities(): DialectCapabilities;
1187
- /**
1188
- * DB column casing convention used by this adapter.
1189
- */
1190
- get dbCasing(): DbCasing;
1191
- /**
1192
- * Get the underlying pg Pool or borrowed PoolClient instance.
1193
- *
1194
- * Exposing raw access from a pool-owned dbsp-managed scope permanently taints that
1195
- * physical client: external callers can queue commands outside dbsp's statement
1196
- * lock, so replay is disabled and dbsp destroys the client at scope release.
1197
- * Expect pool churn; session state on that exposed connection does not survive the
1198
- * release. A borrowed client remains caller-owned: dbsp never releases it, and the
1199
- * caller decides its fate after raw exposure.
1200
- */
1201
- getPoolInstance(): Pool | PoolClient;
1202
- /**
1203
- * Compile a plan to executable SQL.
1204
- *
1205
- * When passed a direct `CompiledNqlQuery`, the adapter trusts that the bundle
1206
- * has already been semantically validated by the NQL compiler. This method
1207
- * still performs adapter-owned SQL safety checks for emitted binding names
1208
- * before CTE emission.
1209
- */
1210
- compile<T = unknown>(plan: PlanReport | CompiledNqlQuery, options?: CompileOptions): CompiledQuery<T>;
1211
- /**
1212
- * Compile a plan with includes, returning subquery include metadata (DX-033).
1213
- */
1214
- compileWithIncludes<T = unknown>(plan: PlanReport, options?: CompileOptions): CompileResultWithIncludes<T>;
1215
- /**
1216
- * Compile a subquery include query for given parent IDs (DX-033).
1217
- * Generates: SELECT * FROM targetTable WHERE foreignKey IN ($1, $2, ...)
1218
- *
1219
- * @param info - Subquery include metadata
1220
- * @param parentIds - Parent record IDs to fetch related records for
1221
- * @param options - Compile options
1222
- * @returns Compiled query for fetching related records
1223
- */
1224
- compileSubqueryInclude(info: SubqueryIncludeInfo, parentIds: readonly unknown[], options?: CompileOptions): CompiledQuery;
1225
- /**
1226
- * Compile a FROM-less SELECT expression to SQL.
1227
- *
1228
- * Produces: SELECT <expr>
1229
- * Example: SELECT nextval('my_seq')
1230
- *
1231
- * @param expr - ExpressionIntent to evaluate
1232
- * @returns Compiled SQL and parameters
1233
- */
1234
- compileSelectExpression<T = unknown>(expr: ExpressionIntent): CompiledQuery<T>;
1235
- /**
1236
- * Compile an insert intent to executable SQL.
1237
- *
1238
- * Strategy switch (per CompileOptions):
1239
- * - rows <= batchThreshold (default 50): VALUES ($1,$2),($3,$4),...
1240
- * - rows > batchThreshold OR batchThreshold === 0: SELECT unnest($1::type[]),...
1241
- */
1242
- compileInsert(intent: InsertIntent, options?: CompileOptions): CompiledQuery;
1243
- /**
1244
- * Compile an insert-from intent to executable SQL (NQL-ALIGN).
1245
- * INSERT INTO target (cols) SELECT cols FROM source WHERE ... LIMIT ... RETURNING ...
1246
- */
1247
- compileInsertFrom(intent: InsertFromIntent, options?: CompileOptions): CompiledQuery;
1248
- /**
1249
- * Compile an update intent to executable SQL.
1250
- */
1251
- compileUpdate(intent: UpdateIntent, options?: CompileOptions): CompiledQuery;
1252
- /**
1253
- * Compile a batch update intent to executable SQL using unnest FROM strategy (BATCH-001).
1254
- *
1255
- * Generates:
1256
- * UPDATE "table" SET "update_col" = t."update_col" [, "scalar_col" = $N]
1257
- * FROM unnest(CAST($1 AS type[]), CAST($2 AS type[])) AS t("match_col", "update_col")
1258
- * WHERE "table"."match_col" = t."match_col"
1259
- * [RETURNING ...]
1260
- */
1261
- compileBatchUpdate(intent: BatchUpdateIntent, options?: CompileOptions): CompiledQuery;
1262
- /**
1263
- * Compile a delete intent to executable SQL.
1264
- */
1265
- compileDelete(intent: DeleteIntent, options?: CompileOptions): CompiledQuery;
1266
- /**
1267
- * Compile an upsert intent to executable SQL (DX-026).
1268
- */
1269
- compileUpsert(intent: UpsertIntent, options?: CompileOptions): CompiledQuery;
1270
- /**
1271
- * Compile an upsert-from intent to executable SQL (NQL-BIND).
1272
- * INSERT INTO target SELECT ... FROM source ON CONFLICT (cols) DO UPDATE SET ...
1273
- */
1274
- compileUpsertFrom(intent: UpsertFromIntent, options?: CompileOptions): CompiledQuery;
1275
- /**
1276
- * Compile a recursive CTE plan to executable SQL.
1277
- * Supports adjacency-list and edge-table traversal modes.
1278
- */
1279
- compileRecursive<T = unknown>(report: RecursivePlanReport, model: ModelIR, options?: CompileOptions): CompiledQuery<T>;
1280
- /**
1281
- * Compile a CTE query backed by unnest() arrays (BATCH-001 Block 5).
1282
- *
1283
- * Strategy: compile CTE nodes to SQL fragments, compile outer query
1284
- * independently (parameters starting at $1), then renumber outer params
1285
- * to start after CTE params and prepend WITH clause.
1286
- */
1287
- compileCteQuery<T = unknown>(intent: CteQueryIntent, options?: CompileOptions): CompiledQuery<T>;
1288
- /**
1289
- * Compile a set operation (UNION / INTERSECT / EXCEPT) to SQL.
1290
- */
1291
- compileSetOperation<T = unknown>(intent: SetOperationIntent, model: ModelIR, options?: CompileOptions): CompiledQuery<T>;
1292
- private compileSetOperationWithBindings;
1293
- /**
1294
- * Create a dump for observability.
1295
- */
1296
- createDump(plan: PlanReport, query: CompiledQuery, meta?: DumpMeta): Dump;
1297
- /**
1298
- * Execute a query and return all results.
1299
- * Results are transformed to use model naming convention (e.g., snake_case → camelCase)
1300
- */
1301
- execute<T>(query: CompiledQuery<T>): Promise<T[]>;
1302
- /**
1303
- * Execute a query and return rows plus PostgreSQL result metadata.
1304
- * Results are transformed to use model naming convention (e.g., snake_case → camelCase)
1305
- */
1306
- executeWithMeta(query: CompiledQuery): Promise<{
1307
- readonly rows: readonly unknown[];
1308
- readonly rowCount: number;
1309
- readonly command?: string;
1310
- }>;
1311
- /**
1312
- * Transform result rows from database naming to model naming convention.
1313
- * For CamelCaseNamingPlugin: price_cents → priceCents
1314
- */
1315
- private transformResultRows;
1316
- /**
1317
- * Execute a query and return the first result or null.
1318
- */
1319
- executeOne<T>(query: CompiledQuery<T>): Promise<T | null>;
1320
- /**
1321
- * Execute a query and return the first result or throw.
1322
- */
1323
- executeOneOrThrow<T>(query: CompiledQuery<T>): Promise<T>;
1324
- /**
1325
- * Stream query results as an async iterable iterator.
1326
- * Uses PostgreSQL cursors for efficient streaming.
1327
- *
1328
- * Note: The cursor must be used within a transaction. If not already
1329
- * in a transaction, this method wraps the streaming in one.
1330
- *
1331
- * @param query - Compiled query to stream
1332
- * @param options - Stream options (chunkSize)
1333
- * @returns AsyncIterableIterator that yields rows one by one
1334
- */
1335
- stream<T>(query: CompiledQuery<T>, options?: AdapterStreamOptions): AsyncIterableIterator<T>;
1336
- /** Stream raw SQL directly using the same cursor machinery as stream(). */
1337
- streamRaw<T = unknown>(sql: string, parameters?: readonly unknown[], options?: AdapterStreamOptions): AsyncIterableIterator<T>;
1338
- private streamCursor;
1339
- /**
1340
- * Internal: Stream with an existing client using cursors.
1341
- */
1342
- private streamWithClient;
1343
- private streamWithManagedClient;
1344
- private streamWithManagedClientSavepointScope;
1345
- private streamWithClientTransaction;
1346
- /**
1347
- * Introspect the database schema and return a ModelIR.
1348
- *
1349
- * @param options - Optional introspection options (schema, include/exclude filters)
1350
- * @returns IntrospectedModelIR with tables, relations, and hierarchy metadata
1351
- *
1352
- * @example
1353
- * ```typescript
1354
- * const model = await adapter.introspect();
1355
- * const model = await adapter.introspect({ schema: 'tenant_1' });
1356
- * const model = await adapter.introspect({ exclude: ['_prisma*'] });
1357
- * ```
1358
- */
1359
- introspect(options?: IntrospectionOptions): Promise<IntrospectedModelIR>;
1360
- /**
1361
- * Acquire an exclusive session-level PostgreSQL advisory lock for the callback.
1362
- *
1363
- * The lock, callback, and unlock run on one `withPinnedConnection()` adapter.
1364
- * dbsp performs one PostgreSQL acquire and one matching unlock per call. It
1365
- * does not track reentrant depth in v1; PostgreSQL's session-level stacking
1366
- * still applies when callers deliberately nest on the same pinned adapter.
1367
- */
1368
- withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>): Promise<T>;
1369
- withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options: {
1370
- readonly wait?: 'block';
1371
- readonly signal?: AbortSignal;
1372
- }): Promise<T>;
1373
- withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options: {
1374
- readonly wait: 'try';
1375
- readonly signal?: AbortSignal;
1376
- }): Promise<PgAdvisoryLockResult<T>>;
1377
- withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options?: {
1378
- readonly wait?: 'block' | 'try';
1379
- readonly signal?: AbortSignal;
1380
- }): Promise<T | PgAdvisoryLockResult<T>>;
1381
- private unlockAdvisoryLock;
1382
- withPinnedConnection<T>(fn: (adapter: Adapter<DB>) => Promise<T>, options?: PinnedConnectionOptions): Promise<T>;
1383
- private pinnedConnectionReleaseReason;
1384
- private pinnedConnectionWithClient;
1385
- /**
1386
- * Execute a callback within a database transaction.
1387
- *
1388
- * ## What this guarantees
1389
- *
1390
- * The callback's work commits together or not at all; a statement issued inside
1391
- * the transaction never executes after its boundary, even if you forget to
1392
- * `await` it; a nested `transaction()` is a real savepoint; and the connection
1393
- * never goes back to the pool with a transaction still open on it.
1394
- *
1395
- * ## What it cannot guarantee, and you should know before you reach for raw SQL
1396
- *
1397
- * **Raw SQL that ends the transaction ends it.** `COMMIT`, `ROLLBACK` and
1398
- * `PREPARE TRANSACTION` issued through `executeRaw` — or through several commands
1399
- * in one call — reach PostgreSQL and take effect *before* dbsp is told what they
1400
- * were: the command tag arrives after the statement has run. dbsp detects it, kills
1401
- * the scope so nothing else escapes, and throws — but **it cannot un-run what your
1402
- * statement already did**, and `transaction()` rejecting does not mean nothing was
1403
- * committed.
1404
- *
1405
- * The same holds for session state raw SQL creates: a sequence that advanced stays
1406
- * advanced, an advisory lock stays held, a `PREPARE` or a `SET` you issued survives
1407
- * on a pooled connection. dbsp cleans up only what dbsp created.
1408
- *
1409
- * This is the contract of an escape hatch, not an oversight — see #327. If you need
1410
- * transaction control, own the transaction: take a client, `BEGIN` on it yourself,
1411
- * and hand dbsp a `borrowedClient` **without** `managedTransactions`. dbsp will then
1412
- * contain its own statements inside *your* transaction instead of the other way round.
1413
- */
1414
- transaction<T>(fn: (adapter: Adapter<DB>) => Promise<T>, options?: TransactionOptions): Promise<T>;
1415
- /**
1416
- * Execute scratch PostgreSQL work in a scope that always rolls back on success.
1417
- *
1418
- * This is intentionally PostgreSQL-adapter-specific. It is used for catalog
1419
- * shaped scratch DDL such as expression canonicalisation, where the caller
1420
- * needs PostgreSQL's rendering but must not keep the scratch objects. This
1421
- * scope has exactly one successful exit: rollback. In a caller transaction,
1422
- * only this outer savepoint is retained after rollback; nested work releases
1423
- * normally, so a large canonicalisation run cannot retain one subtransaction
1424
- * per expression.
1425
- * Rollback here is cleanup of dbsp-created work, not a sandbox for arbitrary
1426
- * session effects.
1427
- */
1428
- withScratchScope<T>(fn: (adapter: RollbackOnlyPgsqlScope<DB>) => Promise<T>): Promise<T>;
1429
- private createManagedClientAdapter;
1430
- private createPinnedConnectionAdapter;
1431
- private createChildTransactionObserver;
1432
- private observeChildTransaction;
1433
- private markChildTransactionObserved;
1434
- private refreshScopeChildrenFailure;
1435
- private transactionWithManagedClient;
1436
- private transactionWithManagedClientSavepointScope;
1437
- private applyTransactionTimeouts;
1438
- private captureAndApplySavepointTimeouts;
1439
- private restoreSavepointTimeouts;
1440
- private transactionWithClientTransaction;
1441
- private releaseClient;
1442
- private rollbackAndReleaseSavepoint;
1443
- private rollbackSavepoint;
1444
- private releaseSavepoint;
1445
- private rollbackTransactionIfOpen;
1446
- private classifyTransactionStateError;
1447
- private probeTransactionState;
1448
- private classifySavepointReleaseFailure;
1449
- private rollbackSavepointAfterReleaseFailure;
1450
- private enterTransactionScope;
1451
- private enterPinnedConnectionScope;
1452
- private enterSavepointScope;
1453
- private pushClientScope;
1454
- private currentClientScope;
1455
- private managedScopeEndedMessage;
1456
- private assertCanUseClient;
1457
- private assertUsableScopeAncestors;
1458
- private findClientScope;
1459
- private assertScopeNotPoisoned;
1460
- private throwIfScopePoisoned;
1461
- private scopePoisonOutranksError;
1462
- private poisonScopeState;
1463
- private poisonClientScope;
1464
- private poisonClientScopeStack;
1465
- private runWithScopeStatementLock;
1466
- private closeScope;
1467
- private closeScopeAndAssertChildren;
1468
- private drainScopeStatements;
1469
- private drainScopeChildren;
1470
- private assertScopeChildrenSettled;
1471
- private drainScopeWork;
1472
- private executeScopeBoundaryStatement;
1473
- private assertCommitSucceeded;
1474
- /**
1475
- * Create a schema-scoped adapter for multi-tenant queries.
1476
- */
1477
- withSchema(schemaName: string): Adapter<DB>;
1478
- /**
1479
- * Execute raw SQL directly.
1480
- *
1481
- * ⚠️ WARNING: Use parameter placeholders ($1, $2, etc.) for all values.
1482
- *
1483
- * Transaction control through raw SQL inside a scope dbsp is managing is
1484
- * unsupported. `COMMIT`, `ROLLBACK`, and `PREPARE TRANSACTION` end the
1485
- * transaction dbsp is working inside; dbsp detects that and fails loudly, but
1486
- * the data is already whatever your statement made it. Raw savepoint control
1487
- * (`SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`) can alter the
1488
- * savepoint stack before dbsp sees the command tag; dbsp poisons the scope, but
1489
- * it cannot make that command un-run. Manage your transaction outside dbsp's
1490
- * calls.
1491
- */
1492
- executeRaw<T = unknown>(sql: string, parameters?: readonly unknown[]): Promise<T[]>;
1493
- /**
1494
- * Generate DDL statements from a ModelIR schema.
1495
- *
1496
- * Uses PostgreSQL AST nodes and pgsql-deparser for consistent SQL generation.
1497
- * Applies the naming plugin for identifier transformation.
1498
- *
1499
- * @param schema - The ModelIR schema to generate DDL from
1500
- * @param overrideOptions - Optional overrides for DDL generation (e.g., includeDropStatements)
1501
- * @returns Array of DDL statements in dependency order
1502
- */
1503
- generateDDL(schema: ModelIR, overrideOptions?: Partial<GenerateDDLOptions>): string[];
1504
- /**
1505
- * Execute a DDL statement directly (e.g. TRUNCATE, VACUUM, ALTER TABLE, CREATE INDEX).
1506
- *
1507
- * @throws Error if called on a compile-only adapter (no pool)
1508
- * @since DDL-TABLE-001
1509
- */
1510
- executeDDL(sql: string): Promise<void>;
1511
- /**
1512
- * Whether a transaction is open on this adapter's connection.
1513
- * This is true for dbsp-managed scopes and for borrowed pg clients whose
1514
- * ReadyForQuery status says the caller has an open transaction.
1515
- *
1516
- * @since DDL-TABLE-001
1517
- */
1518
- get inTransaction(): boolean;
1519
- private adapterManagedScopeIsLive;
1520
- private shouldProtectBorrowedClientTransaction;
1521
- /**
1522
- * An idle ReadyForQuery status says nothing about commands another owner has
1523
- * already queued on a PoolClient. Only a dbsp-created pinned scope both owns
1524
- * the checked-out physical client and holds its statement lock across the
1525
- * failed named execution and any unnamed replay.
1526
- */
1527
- private ownsSerializedClientForPreparedStatementReplay;
1528
- private executeQueryProtectingOpenTransaction;
1529
- private executeConnectionStatement;
1530
- private executeConnectionStatementUnlocked;
1531
- private executeConnectionStatementInSavepoint;
1532
- private issueConnectionQuery;
1533
- private assertNoMultiCommandRawCall;
1534
- private assertNoTransactionControlCommand;
1535
- private assertPrepareDidNotEndTransaction;
1536
- /**
1537
- * Resolve the explicit schema for a catalog read: an explicit argument, else
1538
- * the adapter's configured schema, else `undefined` (resolve in-query). NOT a
1539
- * hard-coded 'public' — an unresolved schema is handled by the SQL, which
1540
- * finds the table's schema search_path-aware, in the SAME session, so a
1541
- * non-public search_path and a pooled connection both stay correct.
1542
- */
1543
- private explicitSchema;
1544
- /**
1545
- * List all indexes on a table by querying pg_indexes.
1546
- *
1547
- * @param table - Table name
1548
- * @param schema - Schema name (defaults to the search_path-resolved schema)
1549
- */
1550
- listIndexes(table: string, schema?: string, options?: {
1551
- namePattern?: string;
1552
- }): Promise<IndexInfo[]>;
1553
- /**
1554
- * Check whether an index with the given name exists on a table.
1555
- *
1556
- * @param name - Index name
1557
- * @param table - Table name
1558
- * @param schema - Schema name (defaults to the search_path-resolved schema)
1559
- */
1560
- indexExists(name: string, table: string, schema?: string): Promise<boolean>;
1561
- /**
1562
- * Return the total storage size of a table in bytes (includes indexes and TOAST).
1563
- *
1564
- * The table name is a SQL identifier — it is double-quoted, not parameterized,
1565
- * because PostgreSQL does not allow parameterized table names in FROM clauses.
1566
- * With no known schema the table is left unqualified so ::regclass resolves it
1567
- * through search_path (the same table an unqualified reference would hit).
1568
- *
1569
- * @param table - Table name
1570
- * @param schema - Schema name (defaults to the search_path-resolved schema)
1571
- */
1572
- storageSize(table: string, schema?: string): Promise<number>;
1573
- /**
1574
- * Generate SQL for TRUNCATE TABLE.
1575
- * Implements TableDDLGeneratorAdapter.generateTruncate.
1576
- */
1577
- generateTruncate(table: string, schemaName: string, options?: TruncateOptions): string;
1578
- /**
1579
- * Generate SQL for VACUUM.
1580
- * Implements TableDDLGeneratorAdapter.generateVacuum.
1581
- */
1582
- generateVacuum(table: string, schemaName: string, options?: VacuumOptions): string;
1583
- /**
1584
- * Generate SQL for ALTER TABLE ... ALTER COLUMN.
1585
- * Implements TableDDLGeneratorAdapter.generateAlterColumn.
1586
- */
1587
- generateAlterColumn(table: string, schemaName: string, column: string, options: AlterColumnOptions): string;
1588
- /**
1589
- * Generate SQL for CREATE INDEX.
1590
- * Implements TableDDLGeneratorAdapter.generateCreateIndex.
1591
- */
1592
- generateCreateIndex(table: string, schemaName: string, options: CreateIndexOptions): string;
1593
- /**
1594
- * Generate SQL for DROP INDEX.
1595
- * Implements TableDDLGeneratorAdapter.generateDropIndex.
1596
- */
1597
- generateDropIndex(name: string, schemaName: string, options?: DropIndexOptions): string;
1598
- /**
1599
- * Validate an identifier (table name, column name, schema name).
1600
- */
1601
- validateIdentifier(value: string, type: string): void;
1602
- }
1603
- /**
1604
- * Create a PgsqlAdapter from a pg Pool instance.
1605
- *
1606
- * @param pool - pg Pool instance
1607
- * @param options - Optional configuration
1608
- * @returns A new PgsqlAdapter instance
1609
- *
1610
- * @example
1611
- * ```typescript
1612
- * import { Pool } from 'pg';
1613
- * import { createPgsqlAdapter } from '@dbsp/adapter-pgsql';
1614
- *
1615
- * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
1616
- * const adapter = createPgsqlAdapter(pool);
1617
- *
1618
- * // With naming convention
1619
- * const adapter = createPgsqlAdapter(pool, { dbCasing: 'snake_case' });
1620
- * ```
1621
- */
1622
- declare function createPgsqlAdapter<DB = unknown>(pool: Pool, options?: PgsqlPoolAdapterOptions): PgsqlAdapter<DB>;
1623
- declare function createPgsqlAdapter<DB = unknown>(client: PoolClient, options: PgsqlBorrowedClientAdapterOptions): PgsqlAdapter<DB>;
1624
- /**
1625
- * Creates a connectionless PgsqlAdapter for SQL generation without a database connection.
1626
- *
1627
- * All compilation methods (compile, compileInsert, etc.), createDump(), and generateDDL()
1628
- * work normally. The adapter has the full PgsqlAdapter surface; database operations refuse
1629
- * at runtime until it is constructed with a connection via createPgsqlAdapter(pool).
1630
- *
1631
- * @example
1632
- * ```typescript
1633
- * import { createPgsqlCompileOnlyAdapter } from '@dbsp/adapter-pgsql';
1634
- * import { createOrm } from '@dbsp/core';
1635
- *
1636
- * const adapter = createPgsqlCompileOnlyAdapter();
1637
- * const orm = createOrm({ model, adapter });
1638
- * const dump = await orm.select('users').dump();
1639
- * console.log(dump.sql);
1640
- * ```
1641
- */
1642
- declare function createPgsqlCompileOnlyAdapter<DB = unknown>(options?: PgsqlCompileOnlyAdapterOptions): PgsqlAdapter<DB>;
15
+ declare function dbTypesEqual(a: string, b: string): boolean;
1643
16
 
1644
- interface CheckConstraintCanonicalizationWarning {
1645
- readonly table: string;
1646
- readonly kind: 'check_constraint';
1647
- readonly name: string;
1648
- readonly constraint: string;
1649
- readonly message: string;
1650
- readonly cause: unknown;
1651
- }
1652
- interface ColumnDefaultCanonicalizationWarning {
1653
- readonly table: string;
1654
- readonly kind: 'column_default';
1655
- readonly name: string;
1656
- readonly message: string;
1657
- readonly cause: unknown;
1658
- readonly outcome?: 'unavailable' | 'rejected' | 'refused';
1659
- /** Whether this warning represents a raw fallback or absent counterpart. */
1660
- readonly comparison: 'raw' | 'unpaired';
1661
- /** Present when the default could not be paired with the opposite model side. */
1662
- readonly side?: 'desired' | 'database';
1663
- }
1664
- interface IndexPredicateCanonicalizationWarning {
1665
- readonly table: string;
1666
- readonly kind: 'index_predicate';
1667
- readonly name: string;
1668
- readonly message: string;
1669
- readonly cause: unknown;
1670
- readonly outcome: 'unavailable' | 'rejected' | 'refused';
1671
- /** Predicate fallback always compares both complete models raw. */
1672
- readonly comparison: 'raw';
1673
- readonly side?: 'desired' | 'database';
1674
- }
1675
- type ExpressionCanonicalizationWarning = CheckConstraintCanonicalizationWarning | ColumnDefaultCanonicalizationWarning | IndexPredicateCanonicalizationWarning;
1676
- interface CanonicalizeCheckConstraintsOptions {
1677
- /** Database schema that owns the target tables and target-scoped enum types. */
1678
- readonly schemaName?: string;
1679
- /** Naming convention used when matching desired table names to DB table names. */
1680
- readonly dbCasing?: DbCasing;
1681
- /** Called when PostgreSQL CHECK canonicalisation fails and raw comparison is used. */
1682
- readonly onWarning?: (warning: CheckConstraintCanonicalizationWarning) => void;
1683
- /** Throw instead of falling back to raw comparison when canonicalisation fails. */
1684
- readonly requireCanonicalization?: boolean;
1685
- /** Skip CHECK scratch work when the caller's dialect does not support CHECK DDL. */
1686
- readonly canonicalizeCheckConstraints?: boolean;
1687
- /** Capabilities used to generate the migration this scope is staging for. */
1688
- readonly dialectCapabilities?: DialectCapabilities;
1689
- }
1690
- declare class CheckConstraintCanonicalizationError extends Error {
1691
- readonly table: string;
1692
- readonly constraints: readonly string[];
1693
- readonly cause: unknown;
1694
- constructor(table: string, constraints: readonly string[], cause: unknown);
1695
- }
1696
- declare class ColumnDefaultCanonicalizationError extends Error {
1697
- readonly table: string;
1698
- readonly column: string;
1699
- readonly cause: unknown;
1700
- constructor(table: string, column: string, cause: unknown);
1701
- }
17
+ /** EFF-04's closed generated-mutation result domain. */
18
+ type GeneratedMutationClassification = 'non-destructive' | 'removal' | 'data-destructive'
19
+ /** A table rename is executed only by the paired re-address protocol. */
20
+ | 'paired-readdress';
1702
21
  /**
1703
- * Canonicalise PostgreSQL CHECK constraint expressions in a desired model.
22
+ * Total, fail-closed classifier for generator mutations. `string` is deliberate:
23
+ * a newly-added ChangeKind cannot silently become safe before this table names it.
1704
24
  */
1705
- declare function canonicalizeCheckConstraints(adapter: RollbackOnlyPgsqlScope, desired: ModelIR, dbModel: ModelIR, options?: CanonicalizeCheckConstraintsOptions): Promise<ModelIR>;
25
+ declare function classifyGeneratedMutation(kind: ChangeKind | string, change?: {
26
+ readonly destructive?: boolean;
27
+ }): GeneratedMutationClassification;
28
+ declare function isGeneratedMutationDestructive(kind: ChangeKind | string, change?: {
29
+ readonly destructive?: boolean;
30
+ }): boolean;
31
+ /** All removal statements remain generator-only; no transition operation maps one. */
32
+ declare function refusesRecordedPlanRemoval(kind: ChangeKind | string, change?: {
33
+ readonly destructive?: boolean;
34
+ }): boolean;
1706
35
 
1707
- interface ComparePgsqlDatabaseSchemaOptions extends CompareSchemataOptions, SchemaScopeOptions {
1708
- /**
1709
- * Whether to canonicalise PostgreSQL CHECK constraint expressions, column defaults, and predicates on column-keyed
1710
- * partial indexes before comparing. Defaults to `true`. Expression-keyed
1711
- * partial-index predicates are reported as unavailable. Set to `false` only for compatibility with
1712
- * legacy raw-string live diffs.
1713
- *
1714
- * Live canonicalisation creates temporary scratch tables inside an adapter
1715
- * scratch scope whose successful cleanup is rollback. The database role needs
1716
- * permission to create temporary tables and use the scratch column types. If
1717
- * PostgreSQL refuses that scratch DDL, non-strict mode warns and falls back to
1718
- * best-effort raw string comparison for the affected expression surfaces.
1719
- */
1720
- readonly canonicalizeExpressions?: boolean;
1721
- /**
1722
- * Receives live expression canonicalisation warnings. Defaults to console.warn.
1723
- */
1724
- readonly onWarning?: (message: string) => void;
1725
- /** Receives the identity-bearing canonicalisation warning before its string form. */
1726
- readonly onExpressionCanonicalizationWarning?: (warning: ExpressionCanonicalizationWarning) => void;
1727
- /**
1728
- * Diff that the caller just applied before this live re-diff. Used only when
1729
- * expression surfaces are compared by raw text to fail loudly if the exact same
1730
- * expression-surface drift appears again after re-introspection.
1731
- */
1732
- readonly previouslyAppliedDiff?: SchemaDiff;
1733
- }
1734
- type NonConvergentSchemaDiffSurface = {
1735
- readonly kind: 'check_constraint';
1736
- readonly table: string;
1737
- readonly constraint: string;
1738
- } | {
1739
- readonly kind: 'column_default';
1740
- readonly table: string;
1741
- readonly column: string;
36
+ /** Durable payload roles are disjoint before the outcome protocol serializes them. */
37
+ type GeneratedIdentityObservation = LedgerPayload & {
38
+ readonly payloadKind: 'generated-identity-observation';
39
+ };
40
+ type GeneratedStructuralObservation = LedgerPayload & {
41
+ readonly payloadKind: 'generated-structural-observation';
42
+ };
43
+ type GeneratedPostconditionObservation = GeneratedIdentityObservation | GeneratedStructuralObservation;
44
+ type GeneratedPostconditionReadBack = {
45
+ readonly observed: GeneratedPostconditionObservation;
46
+ readonly catalogueIdentity?: NonNullable<LedgerAddress['catalogueIdentity']>;
1742
47
  };
1743
- declare class NonConvergentSchemaDiffError extends Error {
1744
- readonly surface: NonConvergentSchemaDiffSurface;
1745
- readonly desiredExpressionHash: string;
1746
- readonly databaseExpressionHash: string;
1747
- constructor(surface: NonConvergentSchemaDiffSurface, desiredExpressionHash: string, databaseExpressionHash: string);
1748
- }
1749
- /** An enum value this diff adds, reported as a candidate cause — never asserted. */
1750
- interface AddedEnumValue {
1751
- readonly enumName: string;
1752
- readonly value: string;
1753
- }
1754
- declare class CheckConstraintNewEnumValueError extends Error {
1755
- readonly table: string;
1756
- readonly constraint: string;
1757
- readonly addedEnumValues: readonly AddedEnumValue[];
1758
- constructor(table: string, constraint: string, addedEnumValues: readonly AddedEnumValue[]);
1759
- }
1760
- /** A raw partial-index predicate and added enum values cannot share one migration. */
1761
- declare class PartialIndexPredicateNewEnumValueError extends Error {
1762
- readonly addedEnumValues: readonly AddedEnumValue[];
1763
- constructor(addedEnumValues: readonly AddedEnumValue[]);
1764
- }
1765
- /** #454: Predicate canonicalization is not implemented for indexes with expression keys. */
1766
- declare class ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError extends Error {
1767
- readonly predicates: readonly {
1768
- readonly side: 'desired' | 'database';
1769
- readonly table: string;
1770
- readonly index: string;
1771
- }[];
1772
- constructor(predicates: readonly {
1773
- readonly side: 'desired' | 'database';
1774
- readonly table: string;
1775
- readonly index: string;
1776
- }[]);
1777
- }
1778
- /**
1779
- * A raw partial-index predicate cannot be proven to converge after PostgreSQL
1780
- * deparses it, so emitting its CREATE statement is unsafe.
1781
- */
1782
- declare class RawIndexPredicateFallbackError extends Error {
1783
- constructor(cause?: unknown);
1784
- }
1785
- declare class IndexPredicateCanonicalizationError extends Error {
1786
- readonly rejectedPredicates: readonly {
1787
- readonly side: 'desired' | 'database';
1788
- readonly table: string;
1789
- readonly index: string;
1790
- readonly reason?: unknown;
1791
- }[];
1792
- /**
1793
- * Enum values added by this migration are diagnostic candidates only. They
1794
- * are collected from the schema diff, never matched to a rejected index.
1795
- */
1796
- readonly addedEnumValues: readonly AddedEnumValue[];
1797
- constructor(rejectedPredicates: readonly {
1798
- readonly side: 'desired' | 'database';
1799
- readonly table: string;
1800
- readonly index: string;
1801
- readonly reason?: unknown;
1802
- }[],
1803
- /**
1804
- * Enum values added by this migration are diagnostic candidates only. They
1805
- * are collected from the schema diff, never matched to a rejected index.
1806
- */
1807
- addedEnumValues?: readonly AddedEnumValue[]);
1808
- }
1809
- /**
1810
- * Live PostgreSQL schema diff: introspect, canonicalise desired CHECK
1811
- * constraint expressions, column defaults, and predicates on column-keyed
1812
- * partial indexes through PostgreSQL, then call the pure synchronous
1813
- * schema comparator.
1814
- *
1815
- * If CHECK canonicalisation falls back while the same diff adds a plausibly
1816
- * referenced enum value, the diff is refused. dbsp currently applies each
1817
- * migration in one transaction, and PostgreSQL forbids using a newly added enum
1818
- * value in that same transaction; emitting the CHECK would produce a migration
1819
- * that cannot run. Apply the enum addition by itself first, then add or update
1820
- * the CHECK constraint in a later migration.
1821
- *
1822
- * Index expressions are intentionally not canonicalised here; partial-index
1823
- * predicates on expression-keyed indexes are reported as unavailable and are
1824
- * therefore rejected by strict mode. They need their own key-shape substrate.
1825
- */
1826
- declare function comparePgsqlDatabaseSchema(adapter: PgsqlAdapter, desired: ModelIR, options?: ComparePgsqlDatabaseSchemaOptions): Promise<SchemaDiff>;
1827
- declare function assertNoRepeatedExpressionSurfaceDrift(previouslyAppliedDiff: SchemaDiff, currentDiff: SchemaDiff, rawExpressionSurfaces?: ReadonlySet<string>): void;
1828
-
1829
- /**
1830
- * Migration SQL Generator (DDL-PROV Block 1)
1831
- *
1832
- * Generates ordered SQL statements from a SchemaDiff.
1833
- * Statements are topologically sorted: DROP constraints → DROP objects → CREATE objects → ADD constraints.
1834
- *
1835
- * @module migration-sql
1836
- */
1837
-
1838
- interface MigrationSQLOptions {
1839
- /**
1840
- * Schema namespace (default: none — unqualified).
1841
- * Required when emitted migration SQL would otherwise mix non-default
1842
- * target-scoped custom types/enums with unqualified table SQL.
1843
- */
1844
- readonly schemaName?: string;
1845
- /** Whether to include destructive changes (drops) */
1846
- readonly includeDestructive?: boolean;
1847
- /** Automatically create indexes on FK columns for new tables (default: true) */
1848
- readonly fkAutoIndex?: boolean;
1849
- /** Dialect capabilities — unsupported index features throw during migration SQL generation */
1850
- readonly dialectCapabilities?: DialectCapabilities;
1851
- }
1852
48
  /**
1853
- * Generate ordered SQL statements from a SchemaDiff.
1854
- *
1855
- * Topological order:
1856
- * 0. DROP FK/CHECK constraints (must drop before referenced tables)
1857
- * 1. DROP indexes
1858
- * 2. DROP columns
1859
- * 3. DROP primary keys
1860
- * 4. DROP tables, DROP ENUMs
1861
- * 5. CREATE ENUMs (must exist before tables that use them)
1862
- * 6. CREATE tables
1863
- * 7. ADD columns
1864
- * 8. ALTER columns (type, nullable, default)
1865
- * 9. ADD primary keys / column UNIQUE constraints
1866
- * 10. ADD FK constraints (must add after referenced tables exist)
1867
- * 11. ALTER FK (drop + re-add)
1868
- * 12. CREATE indexes
1869
- * 13. ADD CHECK constraints
1870
- * 14. ALTER ENUM ADD VALUE (must be last — has transaction visibility caveats in PG)
1871
- * 15. COMMENT ON TABLE / COLUMN (very last)
49
+ * Reads a generated declaration's terminal observation and catalogue identity.
50
+ * The decoded declaration remains module-private so every public path enters
51
+ * through the versioned decoder before it can dispatch on a declaration kind.
1872
52
  */
1873
- declare function generateMigrationSQL(diff: SchemaDiff, options?: MigrationSQLOptions): readonly string[];
53
+ declare function readGeneratedPostconditionReadBack(executor: GeneratedPostconditionSession, step: NormalizedManagedStep, address: LedgerAddress): Promise<GeneratedPostconditionReadBack>;
1874
54
  /**
1875
- * Generate ordered DOWN SQL statements from a SchemaDiff.
1876
- *
1877
- * Reverses the topological order used in UP migrations:
1878
- * phases run in descending order (11, 10, 9, ..., 0).
1879
- *
1880
- * Irreversible changes (drops that lose data) produce SQL WARNING comments.
55
+ * Generated DDL has no operation runtime to supply an observation. Structural
56
+ * declarations read the precise catalogue fields they change; the four #597
57
+ * identity-only declarations prove existence and catalogue identity, not shape.
58
+ * A same-named object is never enough to write an `observed` terminal.
1881
59
  */
1882
- declare function generateDownSQL(diff: SchemaDiff, options?: MigrationSQLOptions): readonly string[];
60
+ declare function readGeneratedPostcondition(executor: GeneratedPostconditionSession, step: NormalizedManagedStep, address: LedgerAddress): Promise<GeneratedPostconditionObservation>;
1883
61
 
1884
62
  /**
1885
63
  * Type Mapping - Maps ModelIR ColumnType to PostgreSQL data types
@@ -2236,55 +414,76 @@ declare function vectorDims(column: string): ExpressionRef;
2236
414
  * - RETURNING clause for all mutations
2237
415
  */
2238
416
 
417
+ /** Resolver-addressed declared column carried beside its physical SQL name. */
418
+ interface MutationColumnAddress {
419
+ readonly logicalTable: string;
420
+ readonly logicalColumn: string;
421
+ readonly physicalName: SqlIdentifier;
422
+ }
423
+ interface MutationColumnMetadata extends MutationColumnAddress {
424
+ readonly databaseType: string;
425
+ }
426
+ interface MutationTableMetadata {
427
+ readonly logicalTable: string;
428
+ readonly physicalName: SqlIdentifier;
429
+ }
430
+ type MutationColumnTypes = Record<string, string | MutationColumnMetadata>;
2239
431
  /**
2240
432
  * Configuration for INSERT compilation
2241
433
  */
2242
434
  interface InsertConfig {
2243
435
  /** Table to insert into */
2244
- table: string;
436
+ table: SqlIdentifier;
437
+ tableMetadata?: MutationTableMetadata;
2245
438
  /** Columns to insert */
2246
- columns: string[];
439
+ columns: SqlIdentifier[];
2247
440
  /** Values for each column (array of rows) */
2248
441
  values: unknown[][];
2249
442
  /** Columns to return (RETURNING clause) */
2250
443
  returning?: string[];
444
+ /** Addressed declared sources for RETURNING labels. */
445
+ returningSources?: SqlIdentifier[];
2251
446
  /** Alias-aware RETURNING projection items */
2252
447
  returningItems?: readonly MutationReturningItem[];
2253
448
  /** Subquery for INSERT ... SELECT */
2254
449
  selectQuery?: Node;
2255
450
  /** Column database types for type-cast emission (e.g. range types) */
2256
- columnTypes?: Record<string, string>;
451
+ columnTypes?: MutationColumnTypes;
2257
452
  }
2258
453
  /**
2259
454
  * Configuration for UPDATE compilation
2260
455
  */
2261
456
  interface UpdateConfig {
2262
457
  /** Table to update */
2263
- table: string;
458
+ table: SqlIdentifier;
459
+ tableMetadata?: MutationTableMetadata;
2264
460
  /** Column-value pairs to set */
2265
461
  set: {
2266
- column: string;
462
+ column: SqlIdentifier;
2267
463
  value: unknown;
2268
464
  }[];
2269
465
  /** WHERE conditions */
2270
466
  where?: Decision[];
2271
467
  /** Columns to return (RETURNING clause) */
2272
468
  returning?: string[];
469
+ returningSources?: SqlIdentifier[];
2273
470
  /** Alias-aware RETURNING projection items */
2274
471
  returningItems?: readonly MutationReturningItem[];
2275
472
  /** Column database types for type-cast emission (e.g. range types) */
2276
- columnTypes?: Record<string, string>;
473
+ columnTypes?: MutationColumnTypes;
2277
474
  }
2278
475
  /**
2279
476
  * Configuration for DELETE compilation
2280
477
  */
2281
478
  interface DeleteConfig {
2282
479
  /** Table to delete from */
2283
- table: string;
480
+ table: SqlIdentifier;
481
+ tableMetadata?: MutationTableMetadata;
2284
482
  /** WHERE conditions */
2285
483
  where?: Decision[];
2286
484
  /** Columns to return (RETURNING clause) */
2287
485
  returning?: string[];
486
+ returningSources?: SqlIdentifier[];
2288
487
  /** Alias-aware RETURNING projection items */
2289
488
  returningItems?: readonly MutationReturningItem[];
2290
489
  }
@@ -2323,9 +522,15 @@ type ConflictAction = 'nothing' | 'update';
2323
522
  */
2324
523
  interface ConflictTarget {
2325
524
  /** Column names that form the unique constraint */
2326
- columns?: string[];
2327
- /** Named constraint */
2328
- constraint?: string;
525
+ columns?: SqlIdentifier[];
526
+ columnAddresses?: MutationColumnAddress[];
527
+ /** Addressed constraint declared by the target table. */
528
+ constraint?: SqlIdentifier;
529
+ constraintAddress?: {
530
+ readonly logicalTable: string;
531
+ readonly logicalConstraint: string;
532
+ readonly physicalName: SqlIdentifier;
533
+ };
2329
534
  /** WHERE clause for partial index */
2330
535
  where?: Decision[];
2331
536
  }
@@ -2334,9 +539,10 @@ interface ConflictTarget {
2334
539
  */
2335
540
  interface UpsertConfig {
2336
541
  /** Table to upsert into */
2337
- table: string;
542
+ table: SqlIdentifier;
543
+ tableMetadata?: MutationTableMetadata;
2338
544
  /** Columns to insert */
2339
- columns: string[];
545
+ columns: SqlIdentifier[];
2340
546
  /** Values for each column (array of rows) */
2341
547
  values: unknown[][];
2342
548
  /** Conflict target (unique columns or constraint) */
@@ -2344,7 +550,8 @@ interface UpsertConfig {
2344
550
  /** What to do on conflict */
2345
551
  conflictAction: ConflictAction;
2346
552
  /** Columns to update on conflict (for 'update' action) */
2347
- updateColumns?: string[];
553
+ updateColumns?: SqlIdentifier[];
554
+ updateColumnAddresses?: MutationColumnAddress[];
2348
555
  /** Optional WHERE clause for ON CONFLICT DO UPDATE */
2349
556
  actionWhere?: Decision[];
2350
557
  /** Optional direct WHERE intent for ON CONFLICT DO UPDATE */
@@ -2353,23 +560,26 @@ interface UpsertConfig {
2353
560
  compileActionWhere?: (where: WhereIntent, state: CompilerState) => Node;
2354
561
  /** Use EXCLUDED.column for update values (default: true) */
2355
562
  useExcluded?: boolean;
563
+ /** Explicit scalar SET values, independent of INSERT values. */
564
+ updateValues?: ReadonlyMap<SqlIdentifier, unknown>;
2356
565
  /** Columns to return (RETURNING clause) */
2357
566
  returning?: string[];
567
+ returningSources?: SqlIdentifier[];
2358
568
  /** Alias-aware RETURNING projection items */
2359
569
  returningItems?: readonly MutationReturningItem[];
2360
570
  /** Optional column type hints for unnest casting (schema-driven) */
2361
- columnTypes?: Record<string, string>;
571
+ columnTypes?: Record<string, string | MutationColumnMetadata>;
2362
572
  /**
2363
573
  * Raw SQL expressions for specific update columns.
2364
574
  * These are injected verbatim into the ON CONFLICT DO UPDATE SET clause.
2365
- * Keys are logical column names (before naming plugin), values are raw SQL fragments.
575
+ * Keys are addressed target columns, values are raw SQL fragments.
2366
576
  *
2367
577
  * @warning SECURITY: fragments are inserted without parameterization.
2368
578
  * Only use with hardcoded expressions. Never with user input.
2369
579
  *
2370
580
  * @example { last_parsed: 'now()', count: 'excluded.count + 1' }
2371
581
  */
2372
- updateExpressions?: Record<string, string>;
582
+ updateExpressions?: ReadonlyMap<SqlIdentifier, string>;
2373
583
  }
2374
584
  /**
2375
585
  * Build ON CONFLICT clause for INSERT statement.
@@ -2384,46 +594,14 @@ declare function compileUpsert(config: UpsertConfig, ctx: CompilerContext, state
2384
594
  * EXCLUDED is a special table alias in ON CONFLICT ... DO UPDATE
2385
595
  * that refers to the row that would have been inserted.
2386
596
  */
2387
- declare function excludedRef(column: string, naming: {
2388
- toDatabase: (s: string) => string;
2389
- }): Node;
597
+ declare function excludedRef(column: SqlIdentifier): Node;
2390
598
  /**
2391
599
  * Build conditional update using COALESCE.
2392
600
  *
2393
601
  * Produces: COALESCE(EXCLUDED.col, table.col)
2394
602
  * This keeps existing value if new value is NULL.
2395
603
  */
2396
- declare function conditionalUpdate(column: string, table: string, ctx: CompilerContext): Node;
2397
-
2398
- /**
2399
- * @module naming
2400
- * Utilities for resolving database names to logical model names.
2401
- *
2402
- * The ModelIR.getTable() method expects logical (camelCase) names,
2403
- * but the adapter often works with database (snake_case) names.
2404
- * This module bridges that gap.
2405
- */
2406
-
2407
- /**
2408
- * Resolve a database table name to the corresponding logical model name.
2409
- *
2410
- * Converts the DB name using the naming convention, then looks it up in the model.
2411
- * Falls back to exact match if conversion doesn't find a match.
2412
- *
2413
- * @param model - The model IR to search in
2414
- * @param dbName - Database table name (e.g. "post_comments")
2415
- * @param convention - Naming convention used by the adapter
2416
- * @returns The logical table name if found, undefined otherwise
2417
- *
2418
- * @example
2419
- * ```typescript
2420
- * // With camelCase convention:
2421
- * resolveLogicalName(model, "post_comments", "camelCase") // → "postComments"
2422
- * resolveLogicalName(model, "posts", "camelCase") // → "posts"
2423
- * resolveLogicalName(model, "unknown", "camelCase") // → undefined
2424
- * ```
2425
- */
2426
- declare function resolveLogicalName(model: ModelIR, dbName: string, casing: DbCasing): string | undefined;
604
+ declare function conditionalUpdate(column: SqlIdentifier, table: SqlIdentifier, ctx: CompilerContext): Node;
2427
605
 
2428
606
  /**
2429
607
  * ParamRef validation and helpers for PostgreSQL AST
@@ -2480,7 +658,7 @@ declare function collectAndValidateParamRefs(node: unknown): {
2480
658
  allValid: boolean;
2481
659
  };
2482
660
 
2483
- declare function derivePostgresqlCapabilitiesForVersion(version: string): DialectCapabilities;
661
+ declare function derivePgCapabilitiesForVersion(version: string): DialectCapabilities;
2484
662
 
2485
663
  /**
2486
664
  * Redact sensitive values in a query dump's `params` array before logging.
@@ -2512,28 +690,6 @@ declare const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp>;
2512
690
  */
2513
691
  declare function redactParams(params: readonly unknown[], config: RedactionConfig): readonly unknown[];
2514
692
 
2515
- declare const projectionEnvelopeBrand: unique symbol;
2516
- type ProjectionEnvelope<T = unknown> = {
2517
- readonly [projectionEnvelopeBrand]: true;
2518
- readonly sql: string;
2519
- readonly parameters: readonly unknown[];
2520
- readonly ast?: Node;
2521
- readonly projection: ProjectionState;
2522
- readonly hydrationPlan?: PlanReport;
2523
- readonly __resultType?: T;
2524
- };
2525
- type ProjectionState = {
2526
- readonly kind: 'known';
2527
- readonly outputs: ReadonlyMap<string, OutputProjection>;
2528
- } | {
2529
- readonly kind: 'dropped';
2530
- readonly reason: ProjectionDropReason;
2531
- readonly hadConvertibleSource: boolean;
2532
- };
2533
- type OutputProjection = OutputDescriptor;
2534
-
2535
- type ProjectionDropReason = 'set-operation-positional-merge' | 'raw-recursive-cte-positional-merge' | 'unknown-raw-sql' | 'unsupported-source';
2536
-
2537
693
  /**
2538
694
  * Set operation compiler (UNION / INTERSECT / EXCEPT)
2539
695
  *
@@ -2577,7 +733,7 @@ declare function compileSetOperation(intent: SetOperationIntent, compileFn: Leaf
2577
733
  /**
2578
734
  * Create a leaf compile function from adapter + model + capabilities.
2579
735
  *
2580
- * Convenience factory for the common case where you have a PgsqlAdapter
736
+ * Convenience factory for the common case where you have a PgAdapter
2581
737
  * and need a compileFn for `compileSetOperation`.
2582
738
  *
2583
739
  * @param adapter - Adapter with compile() and dialectCapabilities
@@ -2586,10 +742,10 @@ declare function compileSetOperation(intent: SetOperationIntent, compileFn: Leaf
2586
742
  */
2587
743
  declare function createLeafCompileFn(adapter: {
2588
744
  compile(plan: PlanReport, options: CompileOptions & {
2589
- model: ModelIR$1;
745
+ model: ModelIR;
2590
746
  }): CompiledQuery;
2591
747
  dialectCapabilities: DialectCapabilities;
2592
- }, model: ModelIR$1, planFn: (intent: QueryIntent, model: ModelIR$1, options: {
748
+ }, model: ModelIR, planFn: (intent: QueryIntent, model: ModelIR, options: {
2593
749
  dialectCapabilities: DialectCapabilities;
2594
750
  }) => PlanReport, options?: CompileOptions): LeafCompileFn;
2595
751
 
@@ -3294,10 +1450,7 @@ interface SetNotNullMatch {
3294
1450
  readonly expectedColumnShape: SetNotNullColumnShapeExpectation;
3295
1451
  readonly assumptions?: readonly Assumption[];
3296
1452
  }
3297
- interface SetNotNullRuleOptions {
3298
- readonly naming?: NamingPlugin;
3299
- }
3300
- declare function createSetNotNullRule(options?: SetNotNullRuleOptions): TransitionRule<SetNotNullMatch>;
1453
+ declare function createSetNotNullRule(): TransitionRule<SetNotNullMatch>;
3301
1454
 
3302
1455
  interface EnumAddValueMatch {
3303
1456
  readonly schema?: string;
@@ -3310,9 +1463,12 @@ interface EnumAddValueMatch {
3310
1463
  readonly assumptions?: readonly Assumption[];
3311
1464
  }
3312
1465
  interface EnumAddValueRuleOptions {
1466
+ /**
1467
+ * @deprecated Ignored because declared enum names are physical identifiers (#825).
1468
+ */
3313
1469
  readonly naming?: NamingPlugin;
3314
1470
  }
3315
- declare function satisfiesPgEnumLabelVisibleCompositionFact(fact: TransitionCompositionFact, current: ModelIR, _context: ObservationContext): boolean;
1471
+ declare function satisfiesPgEnumLabelVisibleCompositionFact(fact: TransitionCompositionFact, current: ModelIR$1, _context: ObservationContext): boolean;
3316
1472
  declare function createEnumAddValueRule(options?: EnumAddValueRuleOptions): TransitionRule<EnumAddValueMatch>;
3317
1473
 
3318
1474
  interface CreateUniqueIndexConcurrentlyMatch {
@@ -3338,7 +1494,6 @@ interface LogicalIdentityAdoptionMatch {
3338
1494
  readonly selectionBasis: string;
3339
1495
  }
3340
1496
  interface LogicalIdentityAdoptionRuleOptions {
3341
- readonly naming?: NamingPlugin;
3342
1497
  readonly asserter?: IdentityAdoptionAsserter;
3343
1498
  readonly selectionBasis?: string;
3344
1499
  }
@@ -3355,71 +1510,69 @@ interface AddCheckMatch {
3355
1510
  }
3356
1511
 
3357
1512
  interface PgTransitionPackOptions {
3358
- readonly dbCasing?: DbCasing;
3359
- readonly naming?: NamingPlugin;
3360
1513
  readonly identityAdoptionAsserter?: IdentityAdoptionAsserter;
3361
1514
  readonly identityAdoptionSelectionBasis?: string;
3362
1515
  }
3363
1516
  declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3364
- rules: (_dbsp_types.TransitionRule<AddCheckMatch> | _dbsp_types.TransitionRule<LogicalIdentityAdoptionMatch> | _dbsp_types.TransitionRule<CreateUniqueIndexConcurrentlyMatch> | _dbsp_types.TransitionRule<EnumAddValueMatch> | _dbsp_types.TransitionRule<SetNotNullMatch>)[];
1517
+ rules: (_dbsp_core_internal.TransitionRule<AddCheckMatch> | _dbsp_core_internal.TransitionRule<LogicalIdentityAdoptionMatch> | _dbsp_core_internal.TransitionRule<CreateUniqueIndexConcurrentlyMatch> | _dbsp_core_internal.TransitionRule<EnumAddValueMatch> | _dbsp_core_internal.TransitionRule<SetNotNullMatch>)[];
3365
1518
  operationSemantics: ({
3366
1519
  artifact: _dbsp_types.SemanticArtifactRef;
3367
1520
  operationKind: _dbsp_types.OperationKindRef;
3368
1521
  executionContractEligibility: {
3369
1522
  readonly eligible: true;
3370
1523
  };
3371
- supportsOperation(operation: _dbsp_types.PhysicalOperation): boolean;
3372
- renderPlanSql(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): string;
3373
- effectsOf(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): _dbsp_types.OperationEffectAssessment;
3374
- buildFingerprints: (operation: _dbsp_types.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_types.ObservationContext) => {
3375
- expectedBefore: _dbsp_types.FingerprintManifest;
3376
- expectedAfter: _dbsp_types.FingerprintManifest;
1524
+ supportsOperation(operation: _dbsp_core_internal.PhysicalOperation): boolean;
1525
+ renderPlanSql(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): string;
1526
+ effectsOf(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): _dbsp_core_internal.OperationEffectAssessment;
1527
+ buildFingerprints: (operation: _dbsp_core_internal.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_core_internal.ObservationContext) => {
1528
+ expectedBefore: _dbsp_core_internal.FingerprintManifest;
1529
+ expectedAfter: _dbsp_core_internal.FingerprintManifest;
3377
1530
  };
3378
1531
  writeIntentJournal(client: {
3379
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3380
- }, record: _dbsp_types.DurableIntentRecord): Promise<void>;
1532
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1533
+ }, record: _dbsp_core_internal.DurableIntentRecord): Promise<void>;
3381
1534
  begin(client: {
3382
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1535
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3383
1536
  }): Promise<void>;
3384
1537
  setLockTimeout(client: {
3385
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1538
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3386
1539
  }, maxWaitMs: number): Promise<void>;
3387
1540
  acquireLocks(client: {
3388
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3389
- }, operation: _dbsp_types.PhysicalOperation, _effects: _dbsp_types.OperationEffectAssessment, context: _dbsp_types.ObservationContext): Promise<void>;
1541
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1542
+ }, operation: _dbsp_core_internal.PhysicalOperation, _effects: _dbsp_core_internal.OperationEffectAssessment, context: _dbsp_core_internal.ObservationContext): Promise<void>;
3390
1543
  observeContext(client: {
3391
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3392
- }, operation: _dbsp_types.PhysicalOperation, _proofContext: _dbsp_types.ObservationContext): Promise<_dbsp_types.ObservationContext>;
1544
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1545
+ }, operation: _dbsp_core_internal.PhysicalOperation, _proofContext: _dbsp_core_internal.ObservationContext): Promise<_dbsp_core_internal.ObservationContext>;
3393
1546
  observeOperation(client: {
3394
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3395
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, _phase: "before" | "after", issuer: _dbsp_types.ObservationIssuer): Promise<{
1547
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1548
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, _phase: "before" | "after", issuer: _dbsp_core_internal.ObservationIssuer): Promise<{
3396
1549
  observations: _dbsp_types.IssuedObservation[];
3397
- fingerprint: _dbsp_types.FingerprintManifest;
1550
+ fingerprint: _dbsp_core_internal.FingerprintManifest;
3398
1551
  }>;
3399
1552
  checkGuard(client: {
3400
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3401
- }, operation: _dbsp_types.PhysicalOperation, guard: _dbsp_types.ApplyGuard, context: _dbsp_types.ObservationContext): Promise<{
1553
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1554
+ }, operation: _dbsp_core_internal.PhysicalOperation, guard: _dbsp_types.ApplyGuard, context: _dbsp_core_internal.ObservationContext): Promise<{
3402
1555
  passed: boolean;
3403
1556
  observations: _dbsp_types.AdvisoryObservation[];
3404
1557
  recovery: readonly _dbsp_types.RecoveryArtefact[];
3405
1558
  }>;
3406
1559
  executeOperation(client: {
3407
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3408
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[]): Promise<{
1560
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1561
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[]): Promise<{
3409
1562
  kind: string;
3410
1563
  }>;
3411
1564
  writeCompletionJournal(client: {
3412
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3413
- }, operation: _dbsp_types.PhysicalOperation, record: _dbsp_types.TransactionalCompletionRecord): Promise<void>;
1565
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1566
+ }, operation: _dbsp_core_internal.PhysicalOperation, record: _dbsp_core_internal.TransactionalCompletionRecord): Promise<void>;
3414
1567
  commit(client: {
3415
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1568
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3416
1569
  }): Promise<void>;
3417
1570
  rollback(client: {
3418
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1571
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3419
1572
  }): Promise<void>;
3420
1573
  writeObservedJournal(client: {
3421
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3422
- }, journal: _dbsp_types.StepJournal): Promise<void>;
1574
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1575
+ }, journal: _dbsp_core_internal.StepJournal): Promise<void>;
3423
1576
  isLockTimeout(error: unknown): boolean;
3424
1577
  } | {
3425
1578
  artifact: _dbsp_types.SemanticArtifactRef;
@@ -3431,58 +1584,58 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3431
1584
  readonly setting: "standard_conforming_strings";
3432
1585
  readonly value: "on";
3433
1586
  }];
3434
- supportsOperation(operation: _dbsp_types.PhysicalOperation): boolean;
3435
- renderPlanSql(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): string;
3436
- effectsOf(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): _dbsp_types.OperationEffectAssessment;
3437
- buildFingerprints: (operation: _dbsp_types.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_types.ObservationContext) => {
3438
- expectedBefore: _dbsp_types.FingerprintManifest;
3439
- expectedAfter: _dbsp_types.FingerprintManifest;
1587
+ supportsOperation(operation: _dbsp_core_internal.PhysicalOperation): boolean;
1588
+ renderPlanSql(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): string;
1589
+ effectsOf(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): _dbsp_core_internal.OperationEffectAssessment;
1590
+ buildFingerprints: (operation: _dbsp_core_internal.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_core_internal.ObservationContext) => {
1591
+ expectedBefore: _dbsp_core_internal.FingerprintManifest;
1592
+ expectedAfter: _dbsp_core_internal.FingerprintManifest;
3440
1593
  };
3441
1594
  writeIntentJournal(client: {
3442
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3443
- }, record: _dbsp_types.DurableIntentRecord): Promise<void>;
1595
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1596
+ }, record: _dbsp_core_internal.DurableIntentRecord): Promise<void>;
3444
1597
  begin(client: {
3445
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1598
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3446
1599
  }): Promise<void>;
3447
1600
  setLockTimeout(client: {
3448
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1601
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3449
1602
  }, maxWaitMs: number): Promise<void>;
3450
1603
  acquireLocks(client: {
3451
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3452
- }, operation: _dbsp_types.PhysicalOperation): Promise<void>;
1604
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1605
+ }, operation: _dbsp_core_internal.PhysicalOperation): Promise<void>;
3453
1606
  observeContext(client: {
3454
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3455
- }, operation: _dbsp_types.PhysicalOperation, _proofContext: _dbsp_types.ObservationContext): Promise<_dbsp_types.ObservationContext>;
1607
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1608
+ }, operation: _dbsp_core_internal.PhysicalOperation, _proofContext: _dbsp_core_internal.ObservationContext): Promise<_dbsp_core_internal.ObservationContext>;
3456
1609
  observeOperation(client: {
3457
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3458
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, _phase: "before" | "after", issuer: _dbsp_types.ObservationIssuer): Promise<{
1610
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1611
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, _phase: "before" | "after", issuer: _dbsp_core_internal.ObservationIssuer): Promise<{
3459
1612
  observations: _dbsp_types.IssuedObservation[];
3460
- fingerprint: _dbsp_types.FingerprintManifest;
1613
+ fingerprint: _dbsp_core_internal.FingerprintManifest;
3461
1614
  }>;
3462
1615
  checkGuard(client: {
3463
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3464
- }, operation: _dbsp_types.PhysicalOperation, guard: _dbsp_types.ApplyGuard, context: _dbsp_types.ObservationContext): Promise<{
1616
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1617
+ }, operation: _dbsp_core_internal.PhysicalOperation, guard: _dbsp_types.ApplyGuard, context: _dbsp_core_internal.ObservationContext): Promise<{
3465
1618
  passed: boolean;
3466
1619
  observations: _dbsp_types.EvidenceObservation[];
3467
1620
  recovery: readonly _dbsp_types.RecoveryArtefact[];
3468
1621
  }>;
3469
1622
  executeOperation(client: {
3470
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3471
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[]): Promise<{
1623
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1624
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[]): Promise<{
3472
1625
  kind: string;
3473
1626
  }>;
3474
1627
  writeCompletionJournal(client: {
3475
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3476
- }, operation: _dbsp_types.PhysicalOperation, record: _dbsp_types.TransactionalCompletionRecord): Promise<void>;
1628
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1629
+ }, operation: _dbsp_core_internal.PhysicalOperation, record: _dbsp_core_internal.TransactionalCompletionRecord): Promise<void>;
3477
1630
  commit(client: {
3478
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1631
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3479
1632
  }): Promise<void>;
3480
1633
  rollback(client: {
3481
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1634
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3482
1635
  }): Promise<void>;
3483
1636
  writeObservedJournal(client: {
3484
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3485
- }, journal: _dbsp_types.StepJournal): Promise<void>;
1637
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1638
+ }, journal: _dbsp_core_internal.StepJournal): Promise<void>;
3486
1639
  isLockTimeout(error: unknown): boolean;
3487
1640
  } | {
3488
1641
  artifact: _dbsp_types.SemanticArtifactRef;
@@ -3490,33 +1643,33 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3490
1643
  readonly eligible: false;
3491
1644
  readonly detail: "PostgreSQL AttachLogicalIdentity has no derivable execution requirements yet";
3492
1645
  };
3493
- supportsOperation(operation: _dbsp_types.PhysicalOperation): boolean;
3494
- renderPlanSql(operation: _dbsp_types.PhysicalOperation): string;
3495
- effectsOf(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): _dbsp_types.OperationEffectAssessment;
3496
- buildFingerprints: (operation: _dbsp_types.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_types.ObservationContext) => {
3497
- expectedBefore: _dbsp_types.FingerprintManifest;
3498
- expectedAfter: _dbsp_types.FingerprintManifest;
1646
+ supportsOperation(operation: _dbsp_core_internal.PhysicalOperation): boolean;
1647
+ renderPlanSql(operation: _dbsp_core_internal.PhysicalOperation): string;
1648
+ effectsOf(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): _dbsp_core_internal.OperationEffectAssessment;
1649
+ buildFingerprints: (operation: _dbsp_core_internal.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_core_internal.ObservationContext) => {
1650
+ expectedBefore: _dbsp_core_internal.FingerprintManifest;
1651
+ expectedAfter: _dbsp_core_internal.FingerprintManifest;
3499
1652
  };
3500
1653
  writeIntentJournal(client: {
3501
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3502
- }, record: _dbsp_types.DurableIntentRecord): Promise<void>;
1654
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1655
+ }, record: _dbsp_core_internal.DurableIntentRecord): Promise<void>;
3503
1656
  begin(client: {
3504
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1657
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3505
1658
  }): Promise<void>;
3506
1659
  setLockTimeout(client: {
3507
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1660
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3508
1661
  }, maxWaitMs: number): Promise<void>;
3509
1662
  acquireLocks(client: {
3510
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3511
- }, operation: _dbsp_types.PhysicalOperation): Promise<void>;
1663
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1664
+ }, operation: _dbsp_core_internal.PhysicalOperation): Promise<void>;
3512
1665
  observeContext(client: {
3513
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3514
- }, operation: _dbsp_types.PhysicalOperation, _proofContext: _dbsp_types.ObservationContext): Promise<_dbsp_types.ObservationContext>;
1666
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1667
+ }, operation: _dbsp_core_internal.PhysicalOperation, _proofContext: _dbsp_core_internal.ObservationContext): Promise<_dbsp_core_internal.ObservationContext>;
3515
1668
  observeOperation(client: {
3516
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3517
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, phase: "before" | "after", issuer: _dbsp_types.ObservationIssuer): Promise<{
1669
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1670
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, phase: "before" | "after", issuer: _dbsp_core_internal.ObservationIssuer): Promise<{
3518
1671
  observations: _dbsp_types.IssuedObservation[];
3519
- fingerprint: _dbsp_types.FingerprintManifest;
1672
+ fingerprint: _dbsp_core_internal.FingerprintManifest;
3520
1673
  }>;
3521
1674
  checkGuard(): Promise<{
3522
1675
  passed: boolean;
@@ -3524,22 +1677,22 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3524
1677
  recovery: never[];
3525
1678
  }>;
3526
1679
  executeOperation(client: {
3527
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3528
- }, operation: _dbsp_types.PhysicalOperation): Promise<{
1680
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1681
+ }, operation: _dbsp_core_internal.PhysicalOperation): Promise<{
3529
1682
  kind: "completed";
3530
1683
  }>;
3531
1684
  writeCompletionJournal(client: {
3532
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3533
- }, operation: _dbsp_types.PhysicalOperation, record: _dbsp_types.TransactionalCompletionRecord): Promise<void>;
1685
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1686
+ }, operation: _dbsp_core_internal.PhysicalOperation, record: _dbsp_core_internal.TransactionalCompletionRecord): Promise<void>;
3534
1687
  commit(client: {
3535
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1688
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3536
1689
  }): Promise<void>;
3537
1690
  rollback(client: {
3538
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1691
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3539
1692
  }): Promise<void>;
3540
1693
  writeObservedJournal(client: {
3541
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3542
- }, journal: _dbsp_types.StepJournal): Promise<void>;
1694
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1695
+ }, journal: _dbsp_core_internal.StepJournal): Promise<void>;
3543
1696
  isLockTimeout(error: unknown): boolean;
3544
1697
  } | {
3545
1698
  artifact: _dbsp_types.SemanticArtifactRef;
@@ -3547,38 +1700,38 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3547
1700
  executionContractEligibility: {
3548
1701
  readonly eligible: true;
3549
1702
  };
3550
- supportsOperation(operation: _dbsp_types.PhysicalOperation): boolean;
3551
- renderPlanSql(operation: _dbsp_types.PhysicalOperation): string;
3552
- effectsOf(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): _dbsp_types.OperationEffectAssessment;
3553
- buildFingerprints: (operation: _dbsp_types.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_types.ObservationContext) => {
3554
- expectedBefore: _dbsp_types.FingerprintManifest;
3555
- expectedAfter: _dbsp_types.FingerprintManifest;
1703
+ supportsOperation(operation: _dbsp_core_internal.PhysicalOperation): boolean;
1704
+ renderPlanSql(operation: _dbsp_core_internal.PhysicalOperation): string;
1705
+ effectsOf(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): _dbsp_core_internal.OperationEffectAssessment;
1706
+ buildFingerprints: (operation: _dbsp_core_internal.PhysicalOperation, evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_core_internal.ObservationContext) => {
1707
+ expectedBefore: _dbsp_core_internal.FingerprintManifest;
1708
+ expectedAfter: _dbsp_core_internal.FingerprintManifest;
3556
1709
  };
3557
1710
  writeIntentJournal(client: {
3558
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3559
- }, record: _dbsp_types.DurableIntentRecord): Promise<void>;
1711
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1712
+ }, record: _dbsp_core_internal.DurableIntentRecord): Promise<void>;
3560
1713
  begin(_client: {
3561
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1714
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3562
1715
  }): Promise<never>;
3563
1716
  setLockTimeout(_client: {
3564
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1717
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3565
1718
  }, _maxWaitMs: number): Promise<void>;
3566
1719
  acquireLocks(): Promise<void>;
3567
1720
  observeContext(client: {
3568
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3569
- }, operation: _dbsp_types.PhysicalOperation, _proofContext: _dbsp_types.ObservationContext): Promise<_dbsp_types.ObservationContext>;
1721
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1722
+ }, operation: _dbsp_core_internal.PhysicalOperation, _proofContext: _dbsp_core_internal.ObservationContext): Promise<_dbsp_core_internal.ObservationContext>;
3570
1723
  observeOperation(client: {
3571
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3572
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, phase: "before" | "after", issuer: _dbsp_types.ObservationIssuer): Promise<{
1724
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1725
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, phase: "before" | "after", issuer: _dbsp_core_internal.ObservationIssuer): Promise<{
3573
1726
  observations: _dbsp_types.IssuedObservation[];
3574
- fingerprint: _dbsp_types.FingerprintManifest;
1727
+ fingerprint: _dbsp_core_internal.FingerprintManifest;
3575
1728
  }>;
3576
1729
  checkGuard(_client: {
3577
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3578
- }, _operation: _dbsp_types.PhysicalOperation, guard: _dbsp_types.ApplyGuard): Promise<never>;
1730
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1731
+ }, _operation: _dbsp_core_internal.PhysicalOperation, guard: _dbsp_types.ApplyGuard): Promise<never>;
3579
1732
  executeOperation(client: {
3580
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3581
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[], executionTracker?: _dbsp_core.NonRollbackableExecutionTracker): Promise<{
1733
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1734
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, duringGuards?: readonly _dbsp_types.ApplyGuard[], executionTracker?: _dbsp_core_internal.NonRollbackableExecutionTracker): Promise<{
3582
1735
  kind: "partially-applied";
3583
1736
  recovery: _dbsp_types.RecoveryArtefact[];
3584
1737
  detail: string;
@@ -3594,17 +1747,17 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3594
1747
  nonRollbackableFootprint: string;
3595
1748
  }>;
3596
1749
  writeCompletionJournal(client: {
3597
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3598
- }, operation: _dbsp_types.PhysicalOperation, record: _dbsp_types.TransactionalCompletionRecord): Promise<void>;
1750
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1751
+ }, operation: _dbsp_core_internal.PhysicalOperation, record: _dbsp_core_internal.TransactionalCompletionRecord): Promise<void>;
3599
1752
  commit(_client: {
3600
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1753
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3601
1754
  }): Promise<never>;
3602
1755
  rollback(_client: {
3603
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1756
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3604
1757
  }): Promise<never>;
3605
1758
  writeObservedJournal(client: {
3606
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3607
- }, journal: _dbsp_types.StepJournal): Promise<void>;
1759
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1760
+ }, journal: _dbsp_core_internal.StepJournal): Promise<void>;
3608
1761
  isLockTimeout(error: unknown): boolean;
3609
1762
  } | {
3610
1763
  artifact: _dbsp_types.SemanticArtifactRef;
@@ -3613,31 +1766,31 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3613
1766
  readonly eligible: false;
3614
1767
  readonly detail: "PostgreSQL ManualSql has no derivable execution requirements because its statement has no declared schema target";
3615
1768
  };
3616
- supportsOperation(operation: _dbsp_types.PhysicalOperation): boolean;
3617
- renderPlanSql(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): string;
3618
- effectsOf(operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): _dbsp_types.OperationEffectAssessment;
3619
- buildFingerprints: (operation: _dbsp_types.PhysicalOperation, _evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_types.ObservationContext) => {
3620
- expectedBefore: _dbsp_types.FingerprintManifest;
3621
- expectedAfter: _dbsp_types.FingerprintManifest;
1769
+ supportsOperation(operation: _dbsp_core_internal.PhysicalOperation): boolean;
1770
+ renderPlanSql(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): string;
1771
+ effectsOf(operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): _dbsp_core_internal.OperationEffectAssessment;
1772
+ buildFingerprints: (operation: _dbsp_core_internal.PhysicalOperation, _evidence: readonly _dbsp_types.EvidenceObservation[], context: _dbsp_core_internal.ObservationContext) => {
1773
+ expectedBefore: _dbsp_core_internal.FingerprintManifest;
1774
+ expectedAfter: _dbsp_core_internal.FingerprintManifest;
3622
1775
  };
3623
1776
  writeIntentJournal(client: {
3624
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3625
- }, record: _dbsp_types.DurableIntentRecord): Promise<void>;
1777
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1778
+ }, record: _dbsp_core_internal.DurableIntentRecord): Promise<void>;
3626
1779
  begin(client: {
3627
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1780
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3628
1781
  }): Promise<void>;
3629
1782
  setLockTimeout(_client: {
3630
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1783
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3631
1784
  }, _maxWaitMs: number): Promise<void>;
3632
1785
  acquireLocks(): Promise<void>;
3633
1786
  observeContext(client: {
3634
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3635
- }, _operation: _dbsp_types.PhysicalOperation, proofContext: _dbsp_types.ObservationContext): Promise<_dbsp_types.ObservationContext>;
1787
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1788
+ }, _operation: _dbsp_core_internal.PhysicalOperation, proofContext: _dbsp_core_internal.ObservationContext): Promise<_dbsp_core_internal.ObservationContext>;
3636
1789
  observeOperation(_client: {
3637
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3638
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext, phase: "before" | "after"): Promise<{
1790
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1791
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext, phase: "before" | "after"): Promise<{
3639
1792
  observations: never[];
3640
- fingerprint: _dbsp_types.FingerprintManifest;
1793
+ fingerprint: _dbsp_core_internal.FingerprintManifest;
3641
1794
  }>;
3642
1795
  checkGuard(): Promise<{
3643
1796
  passed: boolean;
@@ -3645,25 +1798,25 @@ declare function createPgTransitionPack(options?: PgTransitionPackOptions): {
3645
1798
  recovery: never[];
3646
1799
  }>;
3647
1800
  executeOperation(client: {
3648
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3649
- }, operation: _dbsp_types.PhysicalOperation, context: _dbsp_types.ObservationContext): Promise<{
1801
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1802
+ }, operation: _dbsp_core_internal.PhysicalOperation, context: _dbsp_core_internal.ObservationContext): Promise<{
3650
1803
  kind: "completed";
3651
1804
  }>;
3652
1805
  writeCompletionJournal(client: {
3653
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3654
- }, operation: _dbsp_types.PhysicalOperation, record: _dbsp_types.TransactionalCompletionRecord): Promise<void>;
1806
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1807
+ }, operation: _dbsp_core_internal.PhysicalOperation, record: _dbsp_core_internal.TransactionalCompletionRecord): Promise<void>;
3655
1808
  commit(client: {
3656
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1809
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3657
1810
  }): Promise<void>;
3658
1811
  rollback(client: {
3659
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
1812
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
3660
1813
  }): Promise<void>;
3661
1814
  writeObservedJournal(client: {
3662
- readonly opaqueClient: _dbsp_types.TransitionSessionClient;
3663
- }, journal: _dbsp_types.StepJournal): Promise<void>;
1815
+ readonly opaqueClient: _dbsp_core_internal.TransitionSessionClient;
1816
+ }, journal: _dbsp_core_internal.StepJournal): Promise<void>;
3664
1817
  isLockTimeout(error: unknown): boolean;
3665
1818
  })[];
3666
- issuer: _dbsp_types.ObservationIssuer;
1819
+ issuer: _dbsp_core_internal.ObservationIssuer;
3667
1820
  executionCoordinator: ExecutionCoordinator;
3668
1821
  transactionDomain: string;
3669
1822
  equivalence: _dbsp_types.EquivalenceCapability;
@@ -3870,12 +2023,93 @@ declare function readPgRemovalEffectsClosure(input: {
3870
2023
  readonly isManaged: (address: LedgerAddress) => Promise<boolean>;
3871
2024
  }): Promise<PgRemovalEffectsClosure>;
3872
2025
 
2026
+ interface ConvergePgBaseOptions extends Omit<ConvergePgOptions$1, 'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'> {
2027
+ }
2028
+ interface ConvergePgOptions extends ConvergePgBaseOptions {
2029
+ readonly mode?: 'apply';
2030
+ }
2031
+ interface ConvergePgCheckOptions extends ConvergePgBaseOptions {
2032
+ readonly mode: 'check';
2033
+ }
2034
+ declare function convergePg(pool: Pool, physical: PgPhysicalModel, options?: ConvergePgOptions): Promise<PgConvergeResult>;
2035
+ declare function convergePg(pool: Pool, physical: PgPhysicalModel, options: ConvergePgCheckOptions): Promise<PgConvergeCheckResult>;
2036
+
2037
+ type PgReconcileRecoveryOutcome = 'appended' | 'already-appended' | 'indeterminate-appended' | 'no-open-claim' | 'pending' | 'blocked' | 'malformed-chain' | 'protocol-refused' | 'transport-ambiguous' | 'refused-pair' | 'indeterminate-pair';
2038
+ type PgReconcileRecoveryFailureCause = 'catalogue' | 'malformed-journal' | 'transport';
2039
+ /** One ordered recovery attempt; diagnostics are raw and presentation-free. */
2040
+ interface PgReconcileRecoveryReport {
2041
+ readonly address: LedgerAddress;
2042
+ readonly outcome: PgReconcileRecoveryOutcome;
2043
+ readonly reason?: string;
2044
+ readonly pairId?: string;
2045
+ readonly failureCause?: PgReconcileRecoveryFailureCause;
2046
+ }
2047
+ /** The selected semantic refusal condition, never a CLI refusal document. */
2048
+ type PgReconcileSelectedIssue = {
2049
+ readonly kind: 'ledger-not-current';
2050
+ readonly currency: Exclude<PgLedgerScopeCurrency, {
2051
+ readonly kind: 'current';
2052
+ }>;
2053
+ readonly affectedAddresses: readonly LedgerAddress[];
2054
+ } | {
2055
+ readonly kind: 'database-read-only';
2056
+ readonly reason: string;
2057
+ readonly affectedAddresses: readonly LedgerAddress[];
2058
+ } | {
2059
+ readonly kind: 'catalogue-unavailable';
2060
+ readonly address: LedgerAddress;
2061
+ } | {
2062
+ readonly kind: 'malformed-chain';
2063
+ readonly address: LedgerAddress;
2064
+ };
2065
+ interface PgReconcileBaseResult {
2066
+ readonly runId: string;
2067
+ readonly addresses: readonly ResourceAddress[];
2068
+ readonly recovery?: readonly PgReconcileRecoveryReport[];
2069
+ readonly selectedIssue?: PgReconcileSelectedIssue;
2070
+ }
2071
+ type PgReconcileTransitionRunResult = (PgReconcileBaseResult & {
2072
+ readonly kind: 'completed';
2073
+ }) | (PgReconcileBaseResult & {
2074
+ readonly kind: 'unresolved';
2075
+ }) | (PgReconcileBaseResult & {
2076
+ readonly kind: 'selection-unavailable';
2077
+ readonly detail?: string;
2078
+ }) | (PgReconcileBaseResult & {
2079
+ readonly kind: 'database-read-only';
2080
+ readonly selectedIssue: Extract<PgReconcileSelectedIssue, {
2081
+ readonly kind: 'database-read-only';
2082
+ }>;
2083
+ }) | {
2084
+ readonly kind: 'busy';
2085
+ readonly runId: string;
2086
+ readonly addresses: readonly ResourceAddress[];
2087
+ };
2088
+ type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';
2089
+ /** A read/recovery failure whose original cause remains available to callers. */
2090
+ declare class PgReconcileTransitionRunError extends Error {
2091
+ readonly stage: PgReconcileFailureStage;
2092
+ readonly originalCause: unknown;
2093
+ constructor(stage: PgReconcileFailureStage, originalCause: unknown);
2094
+ }
2095
+ /**
2096
+ * Returns recovery decisions for one durable run without reissuing DDL.
2097
+ *
2098
+ * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`
2099
+ * acquires its own outcome session. The supplied pool must allow at least two
2100
+ * concurrent connections: a pool with `max: 1` waits forever under the lock.
2101
+ */
2102
+ declare function reconcilePgTransitionRun(pool: Pool, runId: string): Promise<PgReconcileTransitionRunResult>;
2103
+ /** Finds every execution id durably attributable to one transition run. */
2104
+ declare function executionIdsForRun(journal: Awaited<ReturnType<typeof readTransitionJournal>>): readonly string[];
2105
+
3873
2106
  /**
3874
2107
  * Identifier Validation for adapter-pgsql
3875
2108
  *
3876
2109
  * Security layer to prevent SQL injection via identifiers.
3877
2110
  * All table names, column names, schema names, and aliases MUST pass validation.
3878
2111
  */
2112
+
3879
2113
  /**
3880
2114
  * Error thrown when an identifier fails validation.
3881
2115
  */
@@ -3928,11 +2162,6 @@ declare function validateIdentifiers(identifiers: Record<string, 'table' | 'colu
3928
2162
  * NOT for use in SQL - use validateIdentifier + AST helpers for that.
3929
2163
  */
3930
2164
  declare function sanitizeForDisplay(value: string): string;
3931
- /**
3932
- * Preserve hostile diagnostic text as one printable line without losing which
3933
- * control character was supplied. This is for diagnostics only, never SQL.
3934
- */
3935
- declare function escapeDiagnosticText(value: string): string;
3936
2165
  /**
3937
2166
  * Validate a raw SQL expression used in DDL contexts (defaults, policy USING/CHECK).
3938
2167
  * Rejects injection vectors: semicolons, line-comment markers, block-comment markers.
@@ -3944,4 +2173,4 @@ declare function escapeDiagnosticText(value: string): string;
3944
2173
  */
3945
2174
  declare function validateSqlExpression(sql: string, context: string): void;
3946
2175
 
3947
- export { ADD_CHECK_RULE_ID, ALTER_AUTHORITY_OBSERVATION, ALTER_COLUMN_SET_NOT_NULL_OPERATION_KIND, ALTER_TYPE_ADD_VALUE_OPERATION_KIND, ATTACH_LOGICAL_IDENTITY_OPERATION_KIND, type AddedEnumValue, type AlterColumnSetNotNullPayload, type AlterTypeAddValuePayload, type AttachLogicalIdentityPayload, type BatchValuesJoinDecision, COLUMN_EXISTS_OBSERVATION, CamelCaseNamingPlugin, type CanonicalizeCheckConstraintsOptions, ChangeKind, CheckConstraintCanonicalizationError, type CheckConstraintCanonicalizationWarning, CheckConstraintNewEnumValueError, ColumnDefaultCanonicalizationError, type ColumnDefaultCanonicalizationWarning, type ComparePgsqlDatabaseSchemaOptions, CompareSchemataOptions, type CompiledResult, type CompilerContext, type CompilerOptions, type CompilerState, type ConflictAction, type ConflictTarget, type CursorHoldOption, type CursorOptions, type CursorScrollOption, DATABASE_READ_ONLY_OUTCOME, DBSP_LEDGER_EVENT_TABLE, DBSP_LEDGER_IDENTITY_TABLE, DBSP_LEDGER_MARKER_TABLE, DBSP_LEDGER_RESERVATION_TABLE, DBSP_LOGICAL_IDENTITY_TABLE, DBSP_META_SCHEMA, DBSP_TRANSITION_AUTHORIZATION_TABLE, DBSP_TRANSITION_JOURNAL_TABLE, DBSP_TRANSITION_RUN_PLAN_TABLE, DBSP_TRANSITION_RUN_TABLE, DEFAULT_PK_COLUMN, DEFAULT_REDACTION_PATTERNS, type Decision, type DeleteConfig, type DetectedHierarchy, ENGINE_VERSION_OBSERVATION, ENUM_ADD_VALUE_RULE_ID, ENUM_LABEL_VISIBLE_OBSERVATION, ENUM_TYPE_EXISTS_OBSERVATION, type EnumAddValueMatch, type EnumAddValueRuleOptions, type ExplainFormat, type ExplainOptions, type ExplainPlan, type ExpressionCanonicalizationWarning, type ExpressionHandler, ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError, type FetchDirection, type FetchOptions, type FkColumnDerivation, type GenerateDDLOptions, type GeneratedMutationClassification, type IdentityAdoptionAsserter, IdentityNamingPlugin, type IncludeHandler, type IncludeResult, type IndexCapabilityContext, IndexFeatureUnsupportedError, IndexPredicateCanonicalizationError, type IndexRenderSpec, type InsertConfig, type IntrospectedModelIR, type IntrospectionOptions, InvalidIdentifierError, type JoinDecision, LOGICAL_IDENTITY_ADOPTION_RULE_ID, LOGICAL_IDENTITY_CARRIER_OBSERVATION, type LeafCompileFn, type LogicalIdentityAdoptionMatch, type LogicalIdentityAdoptionRuleOptions, MANUAL_SQL_OPERATION_KIND, type ManualSqlPayload, type MigrationSQLOptions, NO_NULLS_GUARD, type NamingPlugin, NonConvergentSchemaDiffError, type NonConvergentSchemaDiffSurface, PG_INTROSPECTION_ARTIFACT, PG_OPERATION_PACK_ARTIFACT, PG_RULE_PACK_ARTIFACT, type ParamRefValidationResult, PartialIndexPredicateNewEnumValueError, type PgAdoptionPreflightResult, type PgAdoptionResult, type PgAdvisoryLockKey, type PgAdvisoryLockResult, PgDatabaseReadOnlyError, type PgDatabaseWritability, type PgDeclaredAdoptionInput, PgExecutionContractDerivationError, type PgLedgerAddressChain, PgLockedRun, PgOutcomeCheckpointObserver, type PgPersistedDeclaredAdoptionInput, type PgPersistedReaddressInput, type PgReaddressPairRecoveryResult, type PgReleaseResult, type PgRemovalEffectAddress, type PgRemovalEffectsClosure, type PgTransitionClientLease, type PgTransitionPackOptions, PgsqlAdapter, type PgsqlAdapterOptions, PgsqlAdvisoryLockOptionsError, type PgsqlBorrowedClientAdapterOptions, type PgsqlCompileOnlyAdapterOptions, PgsqlPinnedConnectionAbortSignalError, type PgsqlPoolAdapterOptions, PgsqlPreparedStatementReplayError, type PgsqlPreparedStatementsOptions, PgsqlRawSqlTransactionControlError, PgsqlTransactionAbortSignalError, PgsqlTransactionAbortedCommitError, PgsqlTransactionAbortedError, PgsqlTransactionOptionsError, PgsqlTransactionTimeoutError, PlanCompiler, type PlanDecision, type PrecompiledJoinDecision, RawIndexPredicateFallbackError, type RedactionConfig, type RedactionPattern, type RollbackOnlyPgsqlScope, SET_NOT_NULL_RULE_ID, SchemaDiff, type SchemaScopeOptions, type SetNotNullMatch, type SetNotNullRuleOptions, type SetOperationResult, type SimplifiedPlanReport, type StreamConfig, type UpdateConfig, type UpsertConfig, type WhereDispatcher, type WhereHandler, acquirePgTransitionClient, assertCreateIndexSupported, assertCreateIndexesSupported, assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid, assertNoRepeatedExpressionSurfaceDrift, assertPgDatabaseWritable, bm25Search, booleanSearch, boost, buildCloseCursor, buildDeclareCursor, buildExplain, buildExplainAnalyzeJson, buildExplainPlan, buildExplainVerbose, buildFetch, buildFetchAll, buildFetchFirst, buildFetchForward, buildFetchNext, buildOnConflictClause, buildStreamingStatements, camelCaseNaming, canGenerateCreateIndex, canonicalizeCheckConstraints, classifyGeneratedMutation, classifyPgDatabaseWritability, classifyPgReaddressRecovery, classifyPgReaddressSupport, classifyPgWrite, classifyRemovalEffectsClosure, collectAndValidateParamRefs, comparePgsqlDatabaseSchema, compileDelete, compileInsert, compileMutation, compilePlan, compileSetOperation, compileUpdate, compileUpsert, conditionalUpdate, containmentAuthorityOutcome, cosineDistance, createAlterColumnSetNotNullOperationRuntime, createAlterTypeAddValueOperationRuntime, createAnyExpr, createAttachLogicalIdentityOperationRuntime, createEnumAddValueRule, createEqualityExpr, createLeafCompileFn, createLogicalIdentityAdoptionRule, createManualSqlOperationRuntime, createParamRef, createPgExecutionContract, createPgObservationIssuer, createPgTransitionLessor, createPgTransitionPack, createPgsqlAdapter, createPgsqlCompileOnlyAdapter, createSetNotNullRule, createTypeCastParamRef, dbTypesEqual, defaultFkDerivation, derivePostgresqlCapabilitiesForVersion, escapeDiagnosticText, evaluatePgExecutionContract, excludedRef, executePgDeclaredAdoption, executePgObservationFromLessor, executePgPersistedTableReaddress, findPgLedgerTerminalMember, generateCreateIndex, generateCursorName, generateDDL, generateDownSQL, generateMigrationSQL, generateSeries, getNamingPluginForDbCasing, getRowEstimates, getTotalExecutionTime, identityNaming, innerProduct, introspect, isBatchValuesJoinDecision, isGeneratedMutationDestructive, isJoinDecision, isPgDatabaseReadOnlyError, isPrecompiledJoinDecision, isReservedKeyword, l2Distance, mapColumnType, mapOnDeleteAction, nextval, normalizeManualSqlPayload, parse, parseExplainJson, pgTargetIdentityMismatch, preflightPgDeclaredAdoption, preparePgExecutionSession, preparePgRecoveryAdmission, rawDistance, readPgExecutionTargetFromClient, readPgLedgerAddressChain, readPgLedgerControllerOid, readPgObservationContextFromClient, readPgObservationContextFromLessor, readPgRemovalEffectsClosure, recoverPgReaddressPair, redactParams, refusesRecordedPlanRemoval, releasePgManagedAddress, renderAlterColumnSetNotNullSql, renderAlterTypeAddValueSql, renderAttachLogicalIdentityLockSql, renderCreateIndex, renderCreateLogicalIdentityIndexesSql, renderCreateLogicalIdentitySideTableSql, renderInsertLogicalIdentitySql, renderNoNullsCheckSql, renderPgTableReaddressStatements, renderSetNotNullLockSql, reservationsForRemovalClosure, resolveLogicalName, sanitizeForDisplay, score, validateIdentifier, validateIdentifiers, validateParamRef, validatePgManagedLedgerCurrency, validateQualifiedIdentifier, validateSqlExpression, vectorDims, withPgTransitionRunLock };
2176
+ export { ADD_CHECK_RULE_ID, ALTER_AUTHORITY_OBSERVATION, ALTER_COLUMN_SET_NOT_NULL_OPERATION_KIND, ALTER_TYPE_ADD_VALUE_OPERATION_KIND, ATTACH_LOGICAL_IDENTITY_OPERATION_KIND, type AlterColumnSetNotNullPayload, type AlterTypeAddValuePayload, type AttachLogicalIdentityPayload, COLUMN_EXISTS_OBSERVATION, ChangeKind, CompilerContext, CompilerState, type ConflictAction, type ConflictTarget, type ConvergePgBaseOptions, type ConvergePgCheckOptions, type ConvergePgOptions, type CursorHoldOption, type CursorOptions, type CursorScrollOption, DATABASE_READ_ONLY_OUTCOME, DBSP_LEDGER_EVENT_TABLE, DBSP_LEDGER_IDENTITY_TABLE, DBSP_LEDGER_MARKER_TABLE, DBSP_LEDGER_RESERVATION_TABLE, DBSP_LOGICAL_IDENTITY_TABLE, DBSP_META_SCHEMA, DBSP_TRANSITION_AUTHORIZATION_TABLE, DBSP_TRANSITION_JOURNAL_TABLE, DBSP_TRANSITION_RUN_PLAN_TABLE, DBSP_TRANSITION_RUN_TABLE, DEFAULT_REDACTION_PATTERNS, Decision, type DeleteConfig, ENGINE_VERSION_OBSERVATION, ENUM_ADD_VALUE_RULE_ID, ENUM_LABEL_VISIBLE_OBSERVATION, ENUM_TYPE_EXISTS_OBSERVATION, type EnumAddValueMatch, type EnumAddValueRuleOptions, type ExplainFormat, type ExplainOptions, type ExplainPlan, type FetchDirection, type FetchOptions, type GeneratedIdentityObservation, type GeneratedMutationClassification, type GeneratedPostconditionObservation, type GeneratedPostconditionReadBack, GeneratedPostconditionSession, type GeneratedStructuralObservation, type IdentityAdoptionAsserter, type InsertConfig, InvalidIdentifierError, LOGICAL_IDENTITY_ADOPTION_RULE_ID, LOGICAL_IDENTITY_CARRIER_OBSERVATION, type LeafCompileFn, type LogicalIdentityAdoptionMatch, type LogicalIdentityAdoptionRuleOptions, MANUAL_SQL_OPERATION_KIND, type ManualSqlPayload, NO_NULLS_GUARD, PG_INTROSPECTION_ARTIFACT, PG_OPERATION_PACK_ARTIFACT, PG_RULE_PACK_ARTIFACT, type ParamRefValidationResult, type PgAdoptionPreflightResult, type PgAdoptionResult, PgConvergeCheckResult, PgConvergeResult, PgDatabaseReadOnlyError, type PgDatabaseWritability, type PgDeclaredAdoptionInput, PgExecutionContractDerivationError, type PgLedgerAddressChain, PgLedgerScopeCurrency, PgLockedRun, PgOutcomeCheckpointObserver, type PgPersistedDeclaredAdoptionInput, type PgPersistedReaddressInput, PgPhysicalModel, type PgReaddressPairRecoveryResult, type PgReconcileFailureStage, type PgReconcileRecoveryFailureCause, type PgReconcileRecoveryOutcome, type PgReconcileRecoveryReport, type PgReconcileSelectedIssue, PgReconcileTransitionRunError, type PgReconcileTransitionRunResult, type PgReleaseResult, type PgRemovalEffectAddress, type PgRemovalEffectsClosure, type PgTransitionClientLease, type PgTransitionPackOptions, type RedactionConfig, type RedactionPattern, SET_NOT_NULL_RULE_ID, type SetNotNullMatch, type SetOperationResult, type StreamConfig, type UpdateConfig, type UpsertConfig, acquirePgTransitionClient, assertCreateUniqueIndexConcurrentlyRecoveryNotInvalid, assertPgDatabaseWritable, bm25Search, booleanSearch, boost, buildCloseCursor, buildDeclareCursor, buildExplain, buildExplainAnalyzeJson, buildExplainPlan, buildExplainVerbose, buildFetch, buildFetchAll, buildFetchFirst, buildFetchForward, buildFetchNext, buildOnConflictClause, buildStreamingStatements, classifyGeneratedMutation, classifyPgDatabaseWritability, classifyPgReaddressRecovery, classifyPgReaddressSupport, classifyPgWrite, classifyRemovalEffectsClosure, collectAndValidateParamRefs, compileDelete, compileInsert, compileMutation, compileSetOperation, compileUpdate, compileUpsert, conditionalUpdate, containmentAuthorityOutcome, convergePg, cosineDistance, createAlterColumnSetNotNullOperationRuntime, createAlterTypeAddValueOperationRuntime, createAnyExpr, createAttachLogicalIdentityOperationRuntime, createEnumAddValueRule, createEqualityExpr, createLeafCompileFn, createLogicalIdentityAdoptionRule, createManualSqlOperationRuntime, createParamRef, createPgExecutionContract, createPgObservationIssuer, createPgTransitionLessor, createPgTransitionPack, createSetNotNullRule, createTypeCastParamRef, dbTypesEqual, derivePgCapabilitiesForVersion, evaluatePgExecutionContract, excludedRef, executePgDeclaredAdoption, executePgObservationFromLessor, executePgPersistedTableReaddress, executionIdsForRun, findPgLedgerTerminalMember, generateCursorName, generateSeries, getRowEstimates, getTotalExecutionTime, innerProduct, isGeneratedMutationDestructive, isPgDatabaseReadOnlyError, isReservedKeyword, l2Distance, mapColumnType, mapOnDeleteAction, nextval, normalizeManualSqlPayload, parse, parseExplainJson, pgTargetIdentityMismatch, preflightPgDeclaredAdoption, preparePgExecutionSession, preparePgRecoveryAdmission, rawDistance, readGeneratedPostcondition, readGeneratedPostconditionReadBack, readPgExecutionTargetFromClient, readPgLedgerAddressChain, readPgLedgerControllerOid, readPgObservationContextFromClient, readPgObservationContextFromLessor, readPgRemovalEffectsClosure, readTransitionJournal, reconcilePgTransitionRun, recoverPgReaddressPair, redactParams, refusesRecordedPlanRemoval, releasePgManagedAddress, renderAlterColumnSetNotNullSql, renderAlterTypeAddValueSql, renderAttachLogicalIdentityLockSql, renderCreateLogicalIdentityIndexesSql, renderCreateLogicalIdentitySideTableSql, renderInsertLogicalIdentitySql, renderNoNullsCheckSql, renderPgTableReaddressStatements, renderSetNotNullLockSql, reservationsForRemovalClosure, sanitizeForDisplay, score, validateIdentifier, validateIdentifiers, validateParamRef, validatePgManagedLedgerCurrency, validateQualifiedIdentifier, validateSqlExpression, vectorDims, withPgTransitionRunLock };