@dbsp/adapter-pgsql 5.0.0 → 6.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,97 +1,14 @@
1
+ import { N as NamingPlugin, F as FkColumnDerivation, C as ChangeKind, G as GeneratedPostconditionSession, T as TransitionJournalQueryable, P as PgLockedRun, a as PgOutcomeCheckpointObserver, b as ConvergePgOptions$1, c as PgPhysicalModel, d as PgConvergeResult, e as PgConvergeCheckResult, f as PgLedgerScopeCurrency, r as readTransitionJournal } from './outcome-protocol-Dw5DYhnA.js';
2
+ export { A as AddedEnumValue, g as AutoIncrementTransitionUnsupportedError, h as CamelCaseNamingPlugin, i as CanonicalizeCheckConstraintsOptions, j as CheckConstraintCanonicalizationError, k as CheckConstraintCanonicalizationWarning, l as CheckConstraintNewEnumValueError, m as ColumnDefaultCanonicalizationError, n as ColumnDefaultCanonicalizationWarning, o as ComparePgsqlDatabaseSchemaOptions, p as CompareSchemataOptions, D as DEFAULT_PK_COLUMN, q as DetectedHierarchy, s as DiffSummary, E as ExpressionCanonicalizationUnavailableError, t as ExpressionCanonicalizationWarning, u as ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError, v as GenerateDDLOptions, w as GeneratedPostcondition, x as GeneratedPostconditionBindingAddress, y as GeneratedPostconditionBindingResolutionError, z as GeneratedPostconditionProofInFlightError, B as GeneratedPostconditionReplanRequiredError, H as GeneratedPostconditionSessionDeactivatedError, I as GeneratedPostconditionWorkInFlightError, J as IdentityNamingPlugin, K as IndexCapabilityContext, L as IndexFeatureUnsupportedError, M as IndexPredicateCanonicalizationError, O as IndexRenderSpec, Q as IntrospectedModelIR, R as IntrospectionOptions, S as MigrationSQLOptions, U as NonConvergentSchemaDiffError, V as NonConvergentSchemaDiffSurface, W as PG_LEDGER_SHAPE_VERSION, X as PartialIndexPredicateNewEnumValueError, Y as PgAdmittedOperation, Z as PgAdmittedOperationResult, _ as PgAdvisoryLockKey, $ as PgAdvisoryLockResult, a0 as PgApplicationStepOwnedState, a1 as PgApplicationStepTx, a2 as PgCatalogueIdentityQueryable, a3 as PgConvergeApplicationStep, a4 as PgConvergeAssertStep, a5 as PgConvergeInitializationFailure, a6 as PgConvergeOnceStep, a7 as PgConvergePlannedStep, a8 as PgConvergeRefusal, a9 as PgConvergeRefusalChange, aa as PgConvergeRefusalError, ab as PgLedgerLockResult, ac as PgLedgerStorageUnsupportedError, ad as PgLedgerTarget, ae as PgOutcomeCheckpoint, af as PgOutcomeClaimRequest, ag as PgOutcomeExecutionRequest, ah as PgOutcomeNonTransactionalRequest, ai as PgOutcomeReadBackFactory, aj as PgOutcomeRecoveryRequest, ak as PgOutcomeRecoveryResult, al as PgOutcomeResolution, am as PgOutcomeResolutionAppendResult, an as PgOutcomeResult, ao as PgOutcomeTransactionalRequest, ap as PgOwnedCheckState, aq as PgPhysicalModelInput, ar as PgPhysicalModelInputError, as as PgPhysicalNameClaim, at as PgPhysicalNameCollision, au as PgPhysicalNameCollisionError, av as PgPhysicalNamespace, aw as PgReinitializePreflightOptions, ax as PgReinitializePreflightPool, ay as PgSchemaDiff, az as PgsqlAdapter, aA as PgsqlAdapterOptions, aB as PgsqlAdvisoryLockOptionsError, aC as PgsqlBorrowedClientAdapterOptions, aD as PgsqlCompileOnlyAdapterOptions, aE as PgsqlPinnedConnectionAbortSignalError, aF as PgsqlPoolAdapterOptions, aG as PgsqlPreparedStatementReplayError, aH as PgsqlPreparedStatementsOptions, aI as PgsqlRawSqlTransactionControlError, aJ as PgsqlTransactionAbortSignalError, aK as PgsqlTransactionAbortedCommitError, aL as PgsqlTransactionAbortedError, aM as PgsqlTransactionOptionsError, aN as PgsqlTransactionTimeoutError, aO as RawIndexPredicateFallbackError, aP as ReferencedKeyKind, aQ as ReferencedKeyRemovalConflict, aR as ReferencedKeyRemovalError, aS as RollbackOnlyPgsqlScope, aT as SchemaChange, aU as SchemaDiff, aV as SchemaScopeOptions, aW as TransitionRunIdentityMismatchError, aX as acquirePgLedgerLocks, aY as appendIntentJournal, aZ as appendTransitionAuthorization, a_ as assertCreateIndexSupported, a$ as assertCreateIndexesSupported, b0 as assertDeclarableChangeKind, b1 as assertGeneratedPostconditionSession, b2 as assertNoRepeatedExpressionSurfaceDrift, b3 as camelCaseNaming, b4 as canGenerateCreateIndex, b5 as canonicalizeCheckConstraints, b6 as comparePgsqlDatabaseSchema, b7 as compareSchemata, b8 as createPgPhysicalModel, b9 as createPgTransitionRunPersister, ba as createPgsqlAdapter, bb as createPgsqlCompileOnlyAdapter, bc as createPgsqlGeneratedManagedStep, bd as decodeGeneratedPostcondition, be as decodeGeneratedPostconditionPayload, bf as defaultFkDerivation, bg as ensureDbspMetaLedger, bh as ensurePgLedger, bi as ensurePgLedgerStorageVersion, bj as ensureTransitionJournal, bk as executePgAdmittedOperation, bl as generateCreateIndex, bm as generateDDL, bn as generateDownSQL, bo as generateMigrationSQL, bp as generatedPostconditionDigest, bq as generatedPostconditionForChange, br as getNamingPluginForDbCasing, bs as identityNaming, bt as introspect, bu as readPgCatalogueIdentity, bv as readPgLedgerMarker, bw as readPgLedgerReservationsForExecution, bx as readPgLedgerScopeCurrency, by as readPgOutcomeRecoveryReadBack, bz as readVerifiedPgLedgerReservationsForPair, bA as recordPgLedgerIdentity, bB as renderCreateDbspMetaSchemaSql, bC as renderCreateIndex, bD as renderCreateLedgerEventTableSql, bE as renderCreateLedgerIdentityTableSql, bF as renderCreateLedgerImmutabilityFunctionSql, bG as renderCreateLedgerImmutabilityTriggerSql, bH as renderCreateLedgerMarkerTableSql, bI as renderCreateLedgerReservationTableSql, bJ as renderCreateLedgerTerminalMemberIndexSql, bK as renderCreateTransitionAuthorizationTableSql, bL as renderCreateTransitionJournalTableSql, bM as renderCreateTransitionRunPlanTableSql, bN as renderCreateTransitionRunTableSql, bO as runPgReinitializePreflight, bP as toGeneratedPostconditionBindingAddress, bQ as validatePgLedgerRuntimeIntegrity, bR as verifyGeneratedCheckPostcondition, bS as verifyGeneratedColumnPostcondition, bT as verifyGeneratedIdentityPostcondition, bU as verifyGeneratedIndexPostcondition, bV as verifyGeneratedTablePostcondition, bW as withGeneratedPostconditionSession } from './outcome-protocol-Dw5DYhnA.js';
1
3
  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';
4
+ import { ExpressionRef, ModelIR as ModelIR$1, ValidatedManagedStepManifest, ExecutionCoordinator, CapabilityDescriptor } from '@dbsp/core';
3
5
  export { normalizeSQL } from '@dbsp/core';
4
6
  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';
7
+ import { OutputDescriptor, PlanReport, DialectCapabilities, ModelIR, ColumnListInput, ParamIntent, JsonAggOrderByEntry, LedgerPayload, LedgerAddress, NormalizedManagedStep, ColumnIR, MutationReturningItem, WhereIntent, DbCasing, QueryIntent, CompiledQuery, SetOperationIntent, CompileOptions, LedgerHome, ScopedApprovalSet, 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
8
  import * as _pgsql_types from '@pgsql/types';
7
9
  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';
12
-
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;
10
+ import { PoolClient, Pool } from 'pg';
11
+ export { escapeDiagnosticText } from '@dbsp/core/internal';
95
12
 
96
13
  /**
97
14
  * Internal registry of NQL `| bind name` CTE names visible to a compile pass.
@@ -103,6 +20,47 @@ declare function getNamingPluginForDbCasing(casing: 'snake_case' | 'camelCase' |
103
20
 
104
21
  type BindingNameRegistry = ReadonlySet<string>;
105
22
 
23
+ declare const projectionEnvelopeBrand: unique symbol;
24
+ type ProjectionEnvelope<T = unknown> = {
25
+ readonly [projectionEnvelopeBrand]: true;
26
+ readonly sql: string;
27
+ readonly parameters: readonly unknown[];
28
+ readonly ast?: Node;
29
+ readonly projection: ProjectionState;
30
+ readonly hydrationPlan?: PlanReport;
31
+ readonly __resultType?: T;
32
+ };
33
+ type ProjectionState = {
34
+ readonly kind: 'known';
35
+ readonly outputs: ReadonlyMap<string, OutputProjection>;
36
+ } | {
37
+ readonly kind: 'dropped';
38
+ readonly reason: ProjectionDropReason;
39
+ readonly hadConvertibleSource: boolean;
40
+ };
41
+ type OutputProjection = OutputDescriptor;
42
+
43
+ type ProjectionDropReason = 'set-operation-positional-merge' | 'raw-recursive-cte-positional-merge' | 'unknown-raw-sql' | 'unsupported-source';
44
+
45
+ /**
46
+ * Resolves the columns available through a relation target. A query-local
47
+ * binding shadows a physical relation, so its (when known) projection is the
48
+ * authority for every column emitted against that target.
49
+ */
50
+
51
+ type RelationTargetProjectionRegistry = ReadonlyMap<string, ProjectionEnvelope>;
52
+ /** A query-scope binding from an emitted SQL alias to the relation it exposes. */
53
+ type AliasColumnAuthority = ReadonlyMap<string, ResolvedRelationTarget>;
54
+ type ResolvedRelationTarget = {
55
+ readonly target: string;
56
+ readonly cteName?: string;
57
+ readonly outputs?: ReadonlyMap<string, OutputDescriptor>;
58
+ };
59
+
60
+ /** Built-in include strategies, shared by the runtime registry and public types. */
61
+ declare const INCLUDE_STRATEGIES: readonly ["join", "lateral", "json_agg", "cte"];
62
+ /** The four strategies this adapter implements handlers for, distinct from @dbsp/types' six-member IncludeStrategy, which includes the planner's subquery and auto. */
63
+ type IncludeHandlerStrategy = (typeof INCLUDE_STRATEGIES)[number];
106
64
  /**
107
65
  * Immutable context passed to all handlers during compilation.
108
66
  */
@@ -131,6 +89,10 @@ interface CompilerContext {
131
89
  readonly outerAlias?: string;
132
90
  /** Query-local CTE/binding names that must not be schema-qualified. */
133
91
  readonly bindingNames?: BindingNameRegistry;
92
+ /** Known projections for visible CTE/binding relation targets. */
93
+ readonly relationTargetProjections?: RelationTargetProjectionRegistry;
94
+ /** Lexically visible SQL aliases that expose a known CTE projection. */
95
+ readonly aliasColumnAuthorities?: AliasColumnAuthority;
134
96
  /**
135
97
  * Optional callback to compile a QueryIntent into an AST Node (SubLink subselect).
136
98
  * Set by PlanCompiler when compiling selectCustomExpression — enables SubqueryExpressionIntent
@@ -213,7 +175,7 @@ interface Decision {
213
175
  readonly offset?: number | ParamIntent | {
214
176
  paramIndex: number;
215
177
  };
216
- readonly strategy?: 'join' | 'lateral' | 'json_agg' | 'cte';
178
+ readonly strategy?: IncludeHandlerStrategy;
217
179
  readonly relation?: string;
218
180
  readonly relationName?: string;
219
181
  readonly relationPath?: string;
@@ -326,7 +288,7 @@ interface ExpressionHandler {
326
288
  */
327
289
  interface IncludeHandler {
328
290
  /** Strategy this handler implements */
329
- readonly strategy: 'join' | 'lateral' | 'json_agg' | 'cte';
291
+ readonly strategy: IncludeHandlerStrategy;
330
292
  /**
331
293
  * Compile an include to AST.
332
294
  * @param decision The include decision
@@ -534,6 +496,7 @@ interface CompilerOptions {
534
496
  readonly model?: _dbsp_types.ModelIR;
535
497
  /** Query-local CTE/binding names that must not be schema-qualified. */
536
498
  readonly bindingNames?: BindingNameRegistry;
499
+ readonly relationTargetProjections?: RelationTargetProjectionRegistry;
537
500
  }
538
501
  declare class PlanCompiler {
539
502
  private readonly naming;
@@ -543,6 +506,7 @@ declare class PlanCompiler {
543
506
  private readonly model;
544
507
  private readonly dialectCapabilities;
545
508
  private readonly bindingNames;
509
+ private readonly relationTargetProjections;
546
510
  /** Mutable state shared with extracted condition/value compilation functions */
547
511
  private state;
548
512
  /** Track root table for EXISTS FK correlation */
@@ -561,19 +525,35 @@ declare class PlanCompiler {
561
525
  * correct source alias (e.g., 'callee.file' reads parent path 'callee').
562
526
  */
563
527
  private joinAliasMap;
528
+ /**
529
+ * Immutable-before-emission mapping from a public relation qualifier to the
530
+ * SQL alias that is actually emitted for that relation.
531
+ */
532
+ private visibleSqlQualifiers;
564
533
  /**
565
534
  * Tracks all join aliases in use for the current query.
566
535
  * Entries are stored in emitted database-alias space, after naming.toDatabase().
567
536
  * Ensures no two JOINs share the same alias (DOUBLE-ALIAS prevention).
568
537
  */
569
538
  private usedJoinAliases;
539
+ /**
540
+ * Query-local authority for every emitted non-root alias. Root bindings are
541
+ * deliberately absent: an unqualified root reference retains its historical
542
+ * SQL semantics, even when the root happens to be a reduced CTE.
543
+ */
544
+ private aliasColumnAuthorities;
570
545
  constructor(options?: CompilerOptions);
571
546
  private childCompilerOptions;
572
547
  /** Build immutable context for handler-based WHERE compilation */
573
548
  private handlerCtx;
549
+ private relationTargetContext;
550
+ /** Register an emitted alias before any column-reference path can use it. */
551
+ private registerAliasAuthority;
574
552
  private findAliasForLegacySourceTable;
575
553
  private emittedJoinAlias;
576
554
  private resolvedJoinAliases;
555
+ private resolveVisibleSqlQualifier;
556
+ private filterJoinAlias;
577
557
  /**
578
558
  * Dispatch a PlanDecision through the unified WHERE handler system.
579
559
  * Bridges PlanCompiler's state to handler types, calls dispatcher, syncs back.
@@ -637,6 +617,12 @@ declare class PlanCompiler {
637
617
  private registerIncludeCompilationResult;
638
618
  private compileIncludeDecision;
639
619
  private compileJoinIncludeAllocationPass;
620
+ /**
621
+ * Allocate visible SQL qualifiers before compiling a target. Only emitted
622
+ * joins register their public qualifier; strategies without an outer source
623
+ * deliberately leave their relation unavailable to qualified references.
624
+ */
625
+ private allocateVisibleSqlQualifiers;
640
626
  /**
641
627
  * Fold a WHERE-family decision into an existing where expression.
642
628
  * Returns the updated (or new) where node.
@@ -735,93 +721,6 @@ declare function compilePlan(plan: SimplifiedPlanReport, options?: CompilerOptio
735
721
 
736
722
  declare function dbTypesEqual(a: string, b: string): boolean;
737
723
 
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
724
  /** EFF-04's closed generated-mutation result domain. */
826
725
  type GeneratedMutationClassification = 'non-destructive' | 'removal' | 'data-destructive'
827
726
  /** A table rename is executed only by the paired re-address protocol. */
@@ -841,1045 +740,31 @@ declare function refusesRecordedPlanRemoval(kind: ChangeKind | string, change?:
841
740
  readonly destructive?: boolean;
842
741
  }): boolean;
843
742
 
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;
743
+ /** Durable payload roles are disjoint before the outcome protocol serializes them. */
744
+ type GeneratedIdentityObservation = LedgerPayload & {
745
+ readonly payloadKind: 'generated-identity-observation';
923
746
  };
924
- type PgAdvisoryLockKey = bigint | {
925
- readonly classId: number;
926
- readonly objId: number;
747
+ type GeneratedStructuralObservation = LedgerPayload & {
748
+ readonly payloadKind: 'generated-structural-observation';
927
749
  };
928
- type PgAdvisoryLockResult<T> = {
929
- readonly acquired: true;
930
- readonly value: T;
931
- } | {
932
- readonly acquired: false;
750
+ type GeneratedPostconditionObservation = GeneratedIdentityObservation | GeneratedStructuralObservation;
751
+ type GeneratedPostconditionReadBack = {
752
+ readonly observed: GeneratedPostconditionObservation;
753
+ readonly catalogueIdentity?: NonNullable<LedgerAddress['catalogueIdentity']>;
933
754
  };
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
755
  /**
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.
756
+ * Reads a generated declaration's terminal observation and catalogue identity.
757
+ * The decoded declaration remains module-private so every public path enters
758
+ * through the versioned decoder before it can dispatch on a declaration kind.
950
759
  */
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
- }
760
+ declare function readGeneratedPostconditionReadBack(executor: GeneratedPostconditionSession, step: NormalizedManagedStep, address: LedgerAddress): Promise<GeneratedPostconditionReadBack>;
1005
761
  /**
1006
- * Options for PgsqlAdapter.
762
+ * Generated DDL has no operation runtime to supply an observation. Structural
763
+ * declarations read the precise catalogue fields they change; the four #597
764
+ * identity-only declarations prove existence and catalogue identity, not shape.
765
+ * A same-named object is never enough to write an `observed` terminal.
1007
766
  */
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>;
1643
-
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
- }
1702
- /**
1703
- * Canonicalise PostgreSQL CHECK constraint expressions in a desired model.
1704
- */
1705
- declare function canonicalizeCheckConstraints(adapter: RollbackOnlyPgsqlScope, desired: ModelIR, dbModel: ModelIR, options?: CanonicalizeCheckConstraintsOptions): Promise<ModelIR>;
1706
-
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;
1742
- };
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
- /**
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)
1872
- */
1873
- declare function generateMigrationSQL(diff: SchemaDiff, options?: MigrationSQLOptions): readonly string[];
1874
- /**
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.
1881
- */
1882
- declare function generateDownSQL(diff: SchemaDiff, options?: MigrationSQLOptions): readonly string[];
767
+ declare function readGeneratedPostcondition(executor: GeneratedPostconditionSession, step: NormalizedManagedStep, address: LedgerAddress): Promise<GeneratedPostconditionObservation>;
1883
768
 
1884
769
  /**
1885
770
  * Type Mapping - Maps ModelIR ColumnType to PostgreSQL data types
@@ -2512,28 +1397,6 @@ declare const DEFAULT_REDACTION_PATTERNS: ReadonlyArray<RegExp>;
2512
1397
  */
2513
1398
  declare function redactParams(params: readonly unknown[], config: RedactionConfig): readonly unknown[];
2514
1399
 
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
1400
  /**
2538
1401
  * Set operation compiler (UNION / INTERSECT / EXCEPT)
2539
1402
  *
@@ -3294,10 +2157,7 @@ interface SetNotNullMatch {
3294
2157
  readonly expectedColumnShape: SetNotNullColumnShapeExpectation;
3295
2158
  readonly assumptions?: readonly Assumption[];
3296
2159
  }
3297
- interface SetNotNullRuleOptions {
3298
- readonly naming?: NamingPlugin;
3299
- }
3300
- declare function createSetNotNullRule(options?: SetNotNullRuleOptions): TransitionRule<SetNotNullMatch>;
2160
+ declare function createSetNotNullRule(): TransitionRule<SetNotNullMatch>;
3301
2161
 
3302
2162
  interface EnumAddValueMatch {
3303
2163
  readonly schema?: string;
@@ -3310,6 +2170,9 @@ interface EnumAddValueMatch {
3310
2170
  readonly assumptions?: readonly Assumption[];
3311
2171
  }
3312
2172
  interface EnumAddValueRuleOptions {
2173
+ /**
2174
+ * @deprecated Ignored because declared enum names are physical identifiers (#825).
2175
+ */
3313
2176
  readonly naming?: NamingPlugin;
3314
2177
  }
3315
2178
  declare function satisfiesPgEnumLabelVisibleCompositionFact(fact: TransitionCompositionFact, current: ModelIR, _context: ObservationContext): boolean;
@@ -3338,7 +2201,6 @@ interface LogicalIdentityAdoptionMatch {
3338
2201
  readonly selectionBasis: string;
3339
2202
  }
3340
2203
  interface LogicalIdentityAdoptionRuleOptions {
3341
- readonly naming?: NamingPlugin;
3342
2204
  readonly asserter?: IdentityAdoptionAsserter;
3343
2205
  readonly selectionBasis?: string;
3344
2206
  }
@@ -3355,8 +2217,6 @@ interface AddCheckMatch {
3355
2217
  }
3356
2218
 
3357
2219
  interface PgTransitionPackOptions {
3358
- readonly dbCasing?: DbCasing;
3359
- readonly naming?: NamingPlugin;
3360
2220
  readonly identityAdoptionAsserter?: IdentityAdoptionAsserter;
3361
2221
  readonly identityAdoptionSelectionBasis?: string;
3362
2222
  }
@@ -3870,12 +2730,93 @@ declare function readPgRemovalEffectsClosure(input: {
3870
2730
  readonly isManaged: (address: LedgerAddress) => Promise<boolean>;
3871
2731
  }): Promise<PgRemovalEffectsClosure>;
3872
2732
 
2733
+ interface ConvergePgBaseOptions extends Omit<ConvergePgOptions$1, 'schema' | 'dbCasing' | 'mode' | 'declaredSequenceNames' | 'fkAutoIndex'> {
2734
+ }
2735
+ interface ConvergePgOptions extends ConvergePgBaseOptions {
2736
+ readonly mode?: 'apply';
2737
+ }
2738
+ interface ConvergePgCheckOptions extends ConvergePgBaseOptions {
2739
+ readonly mode: 'check';
2740
+ }
2741
+ declare function convergePg(pool: Pool, physical: PgPhysicalModel, options?: ConvergePgOptions): Promise<PgConvergeResult>;
2742
+ declare function convergePg(pool: Pool, physical: PgPhysicalModel, options: ConvergePgCheckOptions): Promise<PgConvergeCheckResult>;
2743
+
2744
+ type PgReconcileRecoveryOutcome = 'appended' | 'already-appended' | 'indeterminate-appended' | 'no-open-claim' | 'pending' | 'blocked' | 'malformed-chain' | 'protocol-refused' | 'transport-ambiguous' | 'refused-pair' | 'indeterminate-pair';
2745
+ type PgReconcileRecoveryFailureCause = 'catalogue' | 'malformed-journal' | 'transport';
2746
+ /** One ordered recovery attempt; diagnostics are raw and presentation-free. */
2747
+ interface PgReconcileRecoveryReport {
2748
+ readonly address: LedgerAddress;
2749
+ readonly outcome: PgReconcileRecoveryOutcome;
2750
+ readonly reason?: string;
2751
+ readonly pairId?: string;
2752
+ readonly failureCause?: PgReconcileRecoveryFailureCause;
2753
+ }
2754
+ /** The selected semantic refusal condition, never a CLI refusal document. */
2755
+ type PgReconcileSelectedIssue = {
2756
+ readonly kind: 'ledger-not-current';
2757
+ readonly currency: Exclude<PgLedgerScopeCurrency, {
2758
+ readonly kind: 'current';
2759
+ }>;
2760
+ readonly affectedAddresses: readonly LedgerAddress[];
2761
+ } | {
2762
+ readonly kind: 'database-read-only';
2763
+ readonly reason: string;
2764
+ readonly affectedAddresses: readonly LedgerAddress[];
2765
+ } | {
2766
+ readonly kind: 'catalogue-unavailable';
2767
+ readonly address: LedgerAddress;
2768
+ } | {
2769
+ readonly kind: 'malformed-chain';
2770
+ readonly address: LedgerAddress;
2771
+ };
2772
+ interface PgReconcileBaseResult {
2773
+ readonly runId: string;
2774
+ readonly addresses: readonly ResourceAddress[];
2775
+ readonly recovery?: readonly PgReconcileRecoveryReport[];
2776
+ readonly selectedIssue?: PgReconcileSelectedIssue;
2777
+ }
2778
+ type PgReconcileTransitionRunResult = (PgReconcileBaseResult & {
2779
+ readonly kind: 'completed';
2780
+ }) | (PgReconcileBaseResult & {
2781
+ readonly kind: 'unresolved';
2782
+ }) | (PgReconcileBaseResult & {
2783
+ readonly kind: 'selection-unavailable';
2784
+ readonly detail?: string;
2785
+ }) | (PgReconcileBaseResult & {
2786
+ readonly kind: 'database-read-only';
2787
+ readonly selectedIssue: Extract<PgReconcileSelectedIssue, {
2788
+ readonly kind: 'database-read-only';
2789
+ }>;
2790
+ }) | {
2791
+ readonly kind: 'busy';
2792
+ readonly runId: string;
2793
+ readonly addresses: readonly ResourceAddress[];
2794
+ };
2795
+ type PgReconcileFailureStage = 'reconcile' | 'journal' | 'catalogue';
2796
+ /** A read/recovery failure whose original cause remains available to callers. */
2797
+ declare class PgReconcileTransitionRunError extends Error {
2798
+ readonly stage: PgReconcileFailureStage;
2799
+ readonly originalCause: unknown;
2800
+ constructor(stage: PgReconcileFailureStage, originalCause: unknown);
2801
+ }
2802
+ /**
2803
+ * Returns recovery decisions for one durable run without reissuing DDL.
2804
+ *
2805
+ * Reconciliation keeps the run-lock session while `recoverPgOutcomeClaim`
2806
+ * acquires its own outcome session. The supplied pool must allow at least two
2807
+ * concurrent connections: a pool with `max: 1` waits forever under the lock.
2808
+ */
2809
+ declare function reconcilePgTransitionRun(pool: Pool, runId: string): Promise<PgReconcileTransitionRunResult>;
2810
+ /** Finds every execution id durably attributable to one transition run. */
2811
+ declare function executionIdsForRun(journal: Awaited<ReturnType<typeof readTransitionJournal>>): readonly string[];
2812
+
3873
2813
  /**
3874
2814
  * Identifier Validation for adapter-pgsql
3875
2815
  *
3876
2816
  * Security layer to prevent SQL injection via identifiers.
3877
2817
  * All table names, column names, schema names, and aliases MUST pass validation.
3878
2818
  */
2819
+
3879
2820
  /**
3880
2821
  * Error thrown when an identifier fails validation.
3881
2822
  */
@@ -3928,11 +2869,6 @@ declare function validateIdentifiers(identifiers: Record<string, 'table' | 'colu
3928
2869
  * NOT for use in SQL - use validateIdentifier + AST helpers for that.
3929
2870
  */
3930
2871
  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
2872
  /**
3937
2873
  * Validate a raw SQL expression used in DDL contexts (defaults, policy USING/CHECK).
3938
2874
  * Rejects injection vectors: semicolons, line-comment markers, block-comment markers.
@@ -3944,4 +2880,4 @@ declare function escapeDiagnosticText(value: string): string;
3944
2880
  */
3945
2881
  declare function validateSqlExpression(sql: string, context: string): void;
3946
2882
 
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 };
2883
+ 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, type BatchValuesJoinDecision, COLUMN_EXISTS_OBSERVATION, ChangeKind, type CompiledResult, type CompilerContext, type CompilerOptions, type 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, type 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 ExpressionHandler, type FetchDirection, type FetchOptions, FkColumnDerivation, type GeneratedIdentityObservation, type GeneratedMutationClassification, type GeneratedPostconditionObservation, type GeneratedPostconditionReadBack, GeneratedPostconditionSession, type GeneratedStructuralObservation, type IdentityAdoptionAsserter, type IncludeHandler, type IncludeResult, type InsertConfig, InvalidIdentifierError, type JoinDecision, LOGICAL_IDENTITY_ADOPTION_RULE_ID, LOGICAL_IDENTITY_CARRIER_OBSERVATION, type LeafCompileFn, type LogicalIdentityAdoptionMatch, type LogicalIdentityAdoptionRuleOptions, MANUAL_SQL_OPERATION_KIND, type ManualSqlPayload, NO_NULLS_GUARD, NamingPlugin, 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, PlanCompiler, type PlanDecision, type PrecompiledJoinDecision, type RedactionConfig, type RedactionPattern, SET_NOT_NULL_RULE_ID, type SetNotNullMatch, type SetOperationResult, type SimplifiedPlanReport, type StreamConfig, type UpdateConfig, type UpsertConfig, type WhereDispatcher, type WhereHandler, 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, compilePlan, compileSetOperation, compileUpdate, compileUpsert, conditionalUpdate, containmentAuthorityOutcome, convergePg, cosineDistance, createAlterColumnSetNotNullOperationRuntime, createAlterTypeAddValueOperationRuntime, createAnyExpr, createAttachLogicalIdentityOperationRuntime, createEnumAddValueRule, createEqualityExpr, createLeafCompileFn, createLogicalIdentityAdoptionRule, createManualSqlOperationRuntime, createParamRef, createPgExecutionContract, createPgObservationIssuer, createPgTransitionLessor, createPgTransitionPack, createSetNotNullRule, createTypeCastParamRef, dbTypesEqual, derivePostgresqlCapabilitiesForVersion, evaluatePgExecutionContract, excludedRef, executePgDeclaredAdoption, executePgObservationFromLessor, executePgPersistedTableReaddress, executionIdsForRun, findPgLedgerTerminalMember, generateCursorName, generateSeries, getRowEstimates, getTotalExecutionTime, innerProduct, isBatchValuesJoinDecision, isGeneratedMutationDestructive, isJoinDecision, isPgDatabaseReadOnlyError, isPrecompiledJoinDecision, 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, resolveLogicalName, sanitizeForDisplay, score, validateIdentifier, validateIdentifiers, validateParamRef, validatePgManagedLedgerCurrency, validateQualifiedIdentifier, validateSqlExpression, vectorDims, withPgTransitionRunLock };