@dbsp/adapter-pgsql 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3057 @@
1
+ import * as _pgsql_types from '@pgsql/types';
2
+ import { Node } from '@pgsql/types';
3
+ import * as _dbsp_types from '@dbsp/types';
4
+ import { ModelIR, DbCasing, DialectCapabilities, IndexIR, NormalizedManagedStep, DeclarableResourceAddress, TableIR, CatalogueIdentity, SequenceIR, LedgerPayload, ResourceAddress, LedgerAddress, Adapter, AdapterLogger, AdapterCapabilities, PlanReport, CompiledNqlQuery, CompileOptions, CompiledQuery, ExpressionIntent, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, RecursivePlanReport, CteQueryIntent, SetOperationIntent, DumpMeta, Dump, AdapterStreamOptions, PinnedConnectionOptions, TransactionOptions, OutputDescriptor, ColumnListInput, ParamIntent, LedgerHome, DurableIntentRecord, TransitionRunJournal, ProvenPlanShape, LedgerChainMember, DeclarationSet, OutcomeClaimPlan, DestructiveDecision, LedgerEventKind, OutcomeProtocolRefusal, ClaimBundleStatement, ControllerIdentity, AdmittedOutcomeClaim, ClaimToken, OutcomeRecoveryClassification, OutcomeRecoveryReadBack, OutcomeClaimAdmission } from '@dbsp/types';
5
+ import * as _dbsp_types_internal from '@dbsp/types/internal';
6
+ import { PhysicalNameInventory, NamingPlugin, HierarchyIR, ConnectionAvailability, JsonAggOrderByEntry, TransitionRunAuthorization, LedgerReservationRow, LedgerIdentity, LedgerMarkerState, ReinitializePreflightReport, OutcomeVacancy, OutcomeIndeterminateRecoveryEvidence, OutcomeRecoveryEffect, ScopedApprovalSet } from '@dbsp/types/internal';
7
+ import { Pool, PoolClient } from 'pg';
8
+ import { IndexInfo, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions } from '@dbsp/core';
9
+ import { TransitionRunPersister, AdmittedDestructiveOutcomeClaim, ValidatedManagedStepManifest, DurablyLoadedRun } from '@dbsp/core/internal';
10
+
11
+ /**
12
+ * Default primary key column name used as convention fallback
13
+ * when schema metadata doesn't provide an explicit PK.
14
+ *
15
+ * Consumers (handlers, compiler) must NOT use this directly —
16
+ * they use `requiredColumn()` to throw on missing data.
17
+ * Only convention mappers (extractors, introspection) should reference this.
18
+ */
19
+ declare const DEFAULT_PK_COLUMN = "id";
20
+ /**
21
+ * Derive a foreign key column name from a table name and the PK column it references.
22
+ *
23
+ * Convention: `${singularTableName}_${pkColumnName}`
24
+ * e.g. (authors, id) → author_id, (categories, id) → category_id
25
+ *
26
+ * Consumers should use `deriveFkColumnName` from CompilerContext or options
27
+ * for configurable behavior.
28
+ */
29
+ type FkColumnDerivation = (tableName: string, pkColumnName: string) => string;
30
+ declare const defaultFkDerivation: FkColumnDerivation;
31
+
32
+ type PgPhysicalModelInput = {
33
+ readonly mode: 'logical';
34
+ readonly model: ModelIR;
35
+ readonly schema: string;
36
+ readonly dbCasing?: DbCasing;
37
+ readonly naming?: NamingPlugin;
38
+ readonly fkAutoIndex?: boolean;
39
+ } | {
40
+ readonly mode: 'physical';
41
+ readonly model: ModelIR;
42
+ readonly schema: string;
43
+ readonly fkAutoIndex?: boolean;
44
+ };
45
+ type PgPhysicalNamespace = 'pg_class' | 'pg_type' | 'column' | 'constraint' | 'policy';
46
+ interface PgPhysicalNameClaim {
47
+ readonly namespace: PgPhysicalNamespace;
48
+ readonly schema: string;
49
+ readonly table?: string;
50
+ readonly physicalName: string;
51
+ readonly logicalOrigin: string;
52
+ }
53
+ interface PgPhysicalNameCollision {
54
+ readonly namespace: PgPhysicalNamespace;
55
+ readonly schema: string;
56
+ readonly table?: string;
57
+ readonly physicalName: string;
58
+ readonly first: PgPhysicalNameClaim;
59
+ readonly second: PgPhysicalNameClaim;
60
+ }
61
+ declare class PgPhysicalNameCollisionError extends Error {
62
+ readonly collision: PgPhysicalNameCollision;
63
+ constructor(collision: PgPhysicalNameCollision);
64
+ get namespace(): PgPhysicalNamespace;
65
+ get schema(): string;
66
+ get table(): string | undefined;
67
+ get physicalName(): string;
68
+ get first(): PgPhysicalNameClaim;
69
+ get second(): PgPhysicalNameClaim;
70
+ }
71
+ /** Refusal raised before a physical model starts inspecting its input model. */
72
+ declare class PgPhysicalModelInputError extends Error {
73
+ readonly reason: 'schema' | 'mode-options';
74
+ constructor(reason: 'schema' | 'mode-options');
75
+ }
76
+ interface PgPhysicalModel {
77
+ readonly mode: 'logical' | 'physical';
78
+ readonly schema: string;
79
+ readonly fkAutoIndex: boolean;
80
+ readonly model: ModelIR;
81
+ readonly inventory: PhysicalNameInventory;
82
+ readonly claims: readonly PgPhysicalNameClaim[];
83
+ }
84
+ /** Builds the sole PostgreSQL physical spelling of one model without rendering SQL. */
85
+ declare function createPgPhysicalModel(input: PgPhysicalModelInput): PgPhysicalModel;
86
+
87
+ interface DeclaredNameResolver {
88
+ readonly physicalModel: PgPhysicalModel;
89
+ table(name: string): string | undefined;
90
+ column(table: string, name: string): string | undefined;
91
+ /** Restores the declared logical column key for one emitted physical column. */
92
+ logicalColumn(table: string, physicalName: string): string | undefined;
93
+ index(table: string, name: string): string | undefined;
94
+ constraint(table: string, name: string): string | undefined;
95
+ enum(name: string): string | undefined;
96
+ /** Resolve an index only when its logical name is unique across the model. */
97
+ uniqueIndex(name: string): string | undefined;
98
+ }
99
+
100
+ declare const sqlIdentifierBrand: unique symbol;
101
+ /**
102
+ * A SQL identifier whose authority has been established by the adapter.
103
+ *
104
+ * The brand is intentionally private: this module is the only place that can
105
+ * cross an untyped spelling into the SQL-identifier vocabulary.
106
+ */
107
+ type SqlIdentifier = string & {
108
+ readonly [sqlIdentifierBrand]: 'SqlIdentifier';
109
+ };
110
+
111
+ type IndexRenderKey = {
112
+ readonly column?: string | undefined;
113
+ readonly expression?: string | undefined;
114
+ readonly opclass?: string | undefined;
115
+ };
116
+ type IndexRenderSpec = {
117
+ readonly name: string;
118
+ readonly table: string;
119
+ readonly schema?: string | undefined;
120
+ readonly unique: boolean;
121
+ readonly method?: string | undefined;
122
+ readonly keys: readonly IndexRenderKey[];
123
+ readonly include?: readonly string[] | undefined;
124
+ readonly nullsNotDistinct?: boolean | undefined;
125
+ readonly with?: Readonly<Record<string, unknown>> | undefined;
126
+ readonly where?: string | undefined;
127
+ /** The in-process index value that owns a deparsed `where` predicate. */
128
+ readonly whereSource?: IndexIR | undefined;
129
+ readonly concurrently?: boolean | undefined;
130
+ readonly ifNotExists?: boolean | undefined;
131
+ };
132
+ type IndexCapabilityContext = {
133
+ readonly caps: DialectCapabilities;
134
+ readonly targetVersion?: string | undefined;
135
+ };
136
+ type IndexFeature = 'INCLUDE' | 'PARTIAL INDEX' | 'EXPRESSION INDEX' | 'INDEX METHOD' | 'OPCLASS' | 'NULLS NOT DISTINCT';
137
+ declare class IndexFeatureUnsupportedError extends Error {
138
+ readonly indexName: string;
139
+ readonly unsupportedFeatures: readonly IndexFeature[];
140
+ constructor(indexName: string, unsupportedFeatures: readonly IndexFeature[], message: string);
141
+ }
142
+ declare class AutoIncrementTransitionUnsupportedError extends Error {
143
+ readonly table: string;
144
+ readonly column: string;
145
+ readonly direction: 'enable' | 'disable' | 'retype' | 'unknown';
146
+ constructor(table: string, column: string, direction: 'enable' | 'disable' | 'retype' | 'unknown');
147
+ }
148
+ declare function assertCreateIndexSupported(spec: IndexRenderSpec, ctx?: IndexCapabilityContext): void;
149
+ declare function assertCreateIndexesSupported(specs: readonly IndexRenderSpec[], ctx?: IndexCapabilityContext): void;
150
+ declare function renderCreateIndex(spec: IndexRenderSpec, ctx?: IndexCapabilityContext): string;
151
+
152
+ /**
153
+ * DDL Generator - Generates PostgreSQL DDL statements from ModelIR
154
+ *
155
+ * Generates SQL strings directly for better compatibility and control.
156
+ * Two-pass strategy handles circular FK dependencies.
157
+ *
158
+ * @module ddl/ddl-generator
159
+ */
160
+
161
+ interface GenerateDDLOptions$1 {
162
+ /** Include DROP TABLE IF EXISTS statements before CREATE TABLE */
163
+ readonly includeDropStatements?: boolean;
164
+ /**
165
+ * Database schema name (e.g., 'public', 'tenant_123').
166
+ * Required when emitted DDL would otherwise mix non-default target-scoped
167
+ * custom types/enums with unqualified table SQL.
168
+ */
169
+ readonly schemaName?: string;
170
+ /**
171
+ * Automatically create indexes on foreign key columns.
172
+ * FK columns are frequently used in JOINs, so indexing is a best practice.
173
+ * @default true
174
+ */
175
+ readonly fkAutoIndex?: boolean;
176
+ /** Naming plugin for logical-model callers. Physical models omit this option. */
177
+ readonly naming?: NamingPlugin;
178
+ /** Dialect capabilities — unsupported index features throw during DDL generation */
179
+ readonly dialectCapabilities?: DialectCapabilities;
180
+ }
181
+ /**
182
+ * Generate DDL statements from a ModelIR schema.
183
+ *
184
+ * Uses a two-pass approach to handle circular FK dependencies:
185
+ * 1. CREATE TABLE (without FK constraints)
186
+ * 2. ALTER TABLE ADD CONSTRAINT for foreign keys
187
+ * 3. CREATE INDEX (explicit + auto-generated for FKs)
188
+ *
189
+ * @param schema - The ModelIR schema to generate DDL from
190
+ * @param options - Optional configuration
191
+ * @returns Array of DDL statements in dependency order
192
+ */
193
+ declare function generateDDL$1(schema: ModelIR, options?: GenerateDDLOptions$1): string[];
194
+ declare function generateCreateIndex(tableName: string, idx: IndexIR, schemaName: string | undefined, context?: IndexCapabilityContext, ifNotExists?: boolean): string;
195
+ /**
196
+ * Returns whether the PostgreSQL DDL generator can emit this IndexIR.
197
+ *
198
+ * Keep this as the single representability predicate for generated schema
199
+ * omission and destructive-drop classification: both sides must agree on the
200
+ * exact validation surface used by generateCreateIndex().
201
+ */
202
+ declare function canGenerateCreateIndex(tableName: string, idx: IndexIR, schemaName?: string | undefined): boolean;
203
+
204
+ /**
205
+ * Schema Comparison Engine (DDL-PROV Block 1)
206
+ *
207
+ * Compares two ModelIRs (schema definition vs database state)
208
+ * and produces a structured diff of changes needed.
209
+ *
210
+ * @module schema-diff
211
+ */
212
+
213
+ type ChangeKind = 'create_table' | 'drop_table' | 'readdress_table' | 'add_column' | 'drop_column' | 'alter_column_type' | 'alter_column_nullable' | 'alter_column_default' | 'alter_column_unique' | 'alter_column_auto_increment' | 'add_primary_key' | 'drop_primary_key' | 'add_foreign_key' | 'drop_foreign_key' | 'alter_foreign_key' | 'validate_constraint' | 'create_index' | 'drop_index' | 'add_check_constraint' | 'drop_check_constraint' | 'create_enum' | 'alter_enum_add_value' | 'drop_enum' | 'alter_column_collation' | 'alter_column_identity' | 'add_comment' | 'drop_comment' | 'create_extension' | 'drop_extension' | 'create_sequence' | 'alter_sequence' | 'drop_sequence' | 'enable_rls' | 'disable_rls' | 'create_policy' | 'drop_policy';
214
+ interface SchemaChange {
215
+ readonly kind: ChangeKind;
216
+ readonly table: string;
217
+ readonly column?: string;
218
+ readonly destructive: boolean;
219
+ readonly details: string;
220
+ /** Additional metadata for SQL generation */
221
+ readonly meta?: Readonly<Record<string, unknown>>;
222
+ }
223
+ interface DiffSummary {
224
+ readonly tables: {
225
+ readonly added: number;
226
+ readonly dropped: number;
227
+ };
228
+ readonly columns: {
229
+ readonly added: number;
230
+ readonly dropped: number;
231
+ readonly altered: number;
232
+ };
233
+ readonly indexes: {
234
+ readonly added: number;
235
+ readonly dropped: number;
236
+ };
237
+ readonly constraints: {
238
+ readonly added: number;
239
+ readonly dropped: number;
240
+ readonly altered: number;
241
+ };
242
+ }
243
+ interface SchemaDiff {
244
+ readonly changes: readonly SchemaChange[];
245
+ readonly hasDestructive: boolean;
246
+ readonly summary: DiffSummary;
247
+ }
248
+ interface CompareSchemataOptions$1 {
249
+ /** Internal compatibility metadata; public physical-model comparison owns schema. */
250
+ readonly schema?: string;
251
+ /** Internal callers must already pass physical names; this value is ignored. */
252
+ dbCasing?: DbCasing;
253
+ /** Authored standalone-sequence names retained by the physical-model boundary. */
254
+ readonly declaredSequenceNames?: ReadonlyMap<string, string>;
255
+ /** Dialect capabilities — comparisons for unsupported features will be skipped */
256
+ readonly dialectCapabilities?: DialectCapabilities;
257
+ /**
258
+ * When `true`, extensions present in the live DB but absent from the model
259
+ * schema are silently ignored — no `drop_extension` change is emitted for them.
260
+ * Only extensions explicitly declared in the model are managed (created if missing).
261
+ *
262
+ * Use this when the database image pre-installs extensions that the application
263
+ * schema does not own (e.g. pgvector, pg_search bundled in a custom Postgres image).
264
+ * Default: `false` (full-sync behaviour — unmanaged DB extensions produce a
265
+ * `drop_extension` entry).
266
+ */
267
+ readonly ignoreUnmanagedExtensions?: boolean;
268
+ /**
269
+ * Strict compile-only mode for callers that require convergence guarantees.
270
+ *
271
+ * `compareSchemata()` is intentionally pure and cannot ask PostgreSQL to
272
+ * canonicalise raw-SQL expression surfaces. By default it keeps the historic
273
+ * best-effort verbatim comparison for column defaults, CHECK expressions,
274
+ * partial-index predicates, and index expressions. Set this flag to throw when either model
275
+ * contains one of those surfaces so a caller cannot accidentally rely on a
276
+ * compile-only diff for a convergence-sensitive check.
277
+ *
278
+ * Live PostgreSQL callers should use `comparePgDatabaseSchema()`, which
279
+ * canonicalises CHECK constraint expressions, column defaults, and partial-index predicates before calling this function.
280
+ * Under that live mode, each side is canonicalised independently; rejected
281
+ * predicates refuse the migration and infrastructure fallback uses both raw
282
+ * models. This does not prove
283
+ * that the resulting migration is executable.
284
+ * Index expressions are not canonicalised by the live helper and are rejected
285
+ * there when this strict flag is set.
286
+ */
287
+ readonly requireExpressionCanonicalization?: boolean;
288
+ }
289
+ declare class ExpressionCanonicalizationUnavailableError extends Error {
290
+ readonly surfaces: readonly string[];
291
+ constructor(surfaces: readonly string[]);
292
+ }
293
+ type ReferencedKeyKind = 'unique_index' | 'primary_key' | 'column_unique';
294
+ interface ReferencedKeyRemovalConflict {
295
+ readonly keyKind: ReferencedKeyKind;
296
+ readonly table: string;
297
+ readonly keyColumns: readonly string[];
298
+ readonly keyName?: string;
299
+ readonly referencingTable: string;
300
+ readonly foreignKeyColumns: readonly string[];
301
+ }
302
+ /**
303
+ * Refusal raised when executable UP SQL would remove a key a foreign key may
304
+ * depend on. Only foreign keys visible in the compared model are detected, so
305
+ * a single-schema comparison cannot see a foreign key whose source table is in
306
+ * another schema. A hand-built `SchemaDiff` without the comparison annotation
307
+ * is not covered.
308
+ */
309
+ declare class ReferencedKeyRemovalError extends Error {
310
+ readonly conflicts: readonly ReferencedKeyRemovalConflict[];
311
+ constructor(conflicts: readonly ReferencedKeyRemovalConflict[]);
312
+ }
313
+ /**
314
+ * Compare two ModelIRs and produce a structured diff.
315
+ *
316
+ * @param schema - The desired schema (from definition)
317
+ * @param db - The current database state (from introspection)
318
+ * @param options - Optional comparison settings (e.g. dbCasing)
319
+ * @returns SchemaDiff with all changes needed to bring DB in sync with schema
320
+ */
321
+ declare function compareSchemata$1(schema: ModelIR, db: ModelIR, options?: CompareSchemataOptions$1): SchemaDiff;
322
+ /** Collect comparison annotations from the changes an executable path selected. */
323
+ declare function collectReferencedKeyRemovalConflicts(changes: readonly SchemaChange[]): readonly ReferencedKeyRemovalConflict[];
324
+
325
+ type Address = DeclarableResourceAddress & {
326
+ readonly scope: 'schema' | 'database';
327
+ };
328
+ type GeneratedConstraintPostcondition = {
329
+ readonly type: 'p' | 'u';
330
+ readonly columns: readonly string[];
331
+ readonly deferrable: boolean;
332
+ readonly initiallyDeferred: boolean;
333
+ readonly enforced: boolean;
334
+ } | {
335
+ readonly type: 'f';
336
+ readonly columns: readonly string[];
337
+ readonly references: {
338
+ readonly schema: string;
339
+ readonly table: string;
340
+ readonly columns: readonly string[];
341
+ };
342
+ readonly onDelete: GeneratedForeignKeyAction;
343
+ readonly onUpdate: GeneratedForeignKeyAction;
344
+ readonly deferrable: boolean;
345
+ readonly initiallyDeferred: boolean;
346
+ readonly enforced: boolean;
347
+ readonly notValid: boolean;
348
+ } | {
349
+ readonly type: 'c';
350
+ /** The ModelIR CHECK expression, never a rendered constraint definition. */
351
+ readonly expression: string;
352
+ readonly notValid: boolean;
353
+ };
354
+ /** The semantic FK actions PostgreSQL can represent in pg_constraint. */
355
+ type GeneratedForeignKeyAction = 'NO ACTION' | 'RESTRICT' | 'CASCADE' | 'SET NULL' | 'SET DEFAULT';
356
+ type GeneratedIndexPostcondition = {
357
+ /** The identity is persisted separately from the rendered CREATE INDEX SQL. */
358
+ readonly schema: string;
359
+ readonly table: string;
360
+ readonly name: string;
361
+ /** PostgreSQL exposes an omitted method as btree; make that expectation explicit. */
362
+ readonly method: string;
363
+ readonly unique: boolean;
364
+ readonly valid: true;
365
+ readonly ready: true;
366
+ readonly live: true;
367
+ readonly columns: readonly string[];
368
+ readonly expressions?: readonly string[];
369
+ readonly include?: readonly string[];
370
+ readonly nullsNotDistinct: boolean;
371
+ readonly opclass?: Readonly<Record<string, string>>;
372
+ readonly with?: Readonly<Record<string, string>>;
373
+ readonly where?: string;
374
+ };
375
+ /** A canonical SQL fact, never an unversioned deparse string. */
376
+ type CanonicalSqlFact = {
377
+ readonly canonicalFormVersion: 1;
378
+ readonly sql: string;
379
+ };
380
+ /**
381
+ * The default, identity, and expression facts are one discriminated state.
382
+ * In particular, an identity cannot also claim an authored/default sequence
383
+ * expression, and a missing default cannot carry an expression.
384
+ */
385
+ type GeneratedColumnDefaultState = {
386
+ readonly defaultKind: 'none';
387
+ readonly hasDefault: false;
388
+ readonly identity: null;
389
+ readonly defaultExpression?: never;
390
+ } | {
391
+ readonly defaultKind: 'authored';
392
+ readonly hasDefault: true;
393
+ readonly identity: null;
394
+ readonly defaultExpression: CanonicalSqlFact;
395
+ } | {
396
+ readonly defaultKind: 'generated-sequence';
397
+ readonly hasDefault: true;
398
+ readonly identity: null;
399
+ readonly defaultExpression?: never;
400
+ } | {
401
+ readonly defaultKind: 'identity';
402
+ readonly hasDefault: false;
403
+ readonly identity: 'always' | 'byDefault';
404
+ readonly defaultExpression?: never;
405
+ };
406
+ type GeneratedColumnDeclaration = {
407
+ readonly type?: string;
408
+ readonly nullable?: boolean;
409
+ /** null means no COLLATE clause was authored; it is not an effective default. */
410
+ readonly authoredCollation?: string | null;
411
+ readonly default?: GeneratedColumnDefaultState;
412
+ };
413
+ type GeneratedTableColumnDeclaration = GeneratedColumnDeclaration & {
414
+ /** A table-shape member name, not the table target binding. */
415
+ readonly name: string;
416
+ };
417
+ type GeneratedIndexDeclaration = Omit<GeneratedIndexPostcondition, 'schema' | 'table' | 'name' | 'expressions' | 'where'> & {
418
+ readonly expressions?: readonly CanonicalSqlFact[];
419
+ readonly where?: CanonicalSqlFact;
420
+ };
421
+ type GeneratedConstraintDeclaration = Extract<GeneratedConstraintPostcondition, {
422
+ readonly type: 'p' | 'u';
423
+ }> | Extract<GeneratedConstraintPostcondition, {
424
+ readonly type: 'f';
425
+ }>;
426
+ /** Table names live only in TargetBinding; columns describe table structure. */
427
+ type V3TableDeclaration = {
428
+ readonly kind: 'table';
429
+ readonly columns: readonly GeneratedTableColumnDeclaration[];
430
+ };
431
+ /** Column names live only in TargetBinding; this is the column's shape. */
432
+ type V3ColumnDeclaration = {
433
+ readonly kind: 'column';
434
+ readonly column: GeneratedColumnDeclaration;
435
+ };
436
+ /** Constraint names live only in TargetBinding; this is a non-CHECK constraint fact. */
437
+ type V3ConstraintDeclaration = {
438
+ readonly kind: 'constraint';
439
+ readonly constraint: GeneratedConstraintDeclaration;
440
+ };
441
+ /** CHECK names live only in TargetBinding; expression is canonical and versioned. */
442
+ type V3CheckDeclaration = {
443
+ readonly kind: 'check';
444
+ readonly check: {
445
+ readonly expression: CanonicalSqlFact;
446
+ readonly notValid: boolean;
447
+ };
448
+ };
449
+ /** Index schema, table, and name live only in TargetBinding; options are structured facts. */
450
+ type V3IndexDeclaration = {
451
+ readonly kind: 'index';
452
+ readonly index: GeneratedIndexDeclaration;
453
+ };
454
+ /** Enum names live only in TargetBinding; labels are the declaration. */
455
+ type V3EnumDeclaration = {
456
+ readonly kind: 'enum';
457
+ readonly labels: readonly string[];
458
+ };
459
+ /** Sequence names live only in TargetBinding; options are the declaration. */
460
+ type V3SequenceDeclaration = {
461
+ readonly kind: 'sequence';
462
+ readonly startValue?: string;
463
+ readonly incrementBy?: string;
464
+ readonly minValue?: string;
465
+ readonly maxValue?: string;
466
+ readonly cycle?: boolean;
467
+ };
468
+ /** Extension names live only in TargetBinding; requested version is the declaration. */
469
+ type V3ExtensionDeclaration = {
470
+ readonly kind: 'extension';
471
+ readonly version?: string;
472
+ };
473
+ /** Address-free v3 declaration variants. */
474
+ type GeneratedPostconditionDeclarationV3 = {
475
+ readonly canonicalFormVersion: 1;
476
+ } & (V3TableDeclaration | V3ColumnDeclaration | V3ConstraintDeclaration | V3CheckDeclaration | V3IndexDeclaration | V3EnumDeclaration | V3SequenceDeclaration | V3ExtensionDeclaration | {
477
+ readonly kind: 'absent';
478
+ });
479
+ /**
480
+ * The separate binding selects the surrounding managed step's canonical
481
+ * address. It is versioned independently so later verifiers can resolve it
482
+ * without teaching any declaration variant about physical addresses.
483
+ */
484
+ type TargetBinding = {
485
+ readonly bindingVersion: 1;
486
+ readonly bindingKind: 'managed-step-address';
487
+ };
488
+ /** Version 3 carries an address-free declaration and a separately decoded binding. */
489
+ type GeneratedPostconditionV3 = {
490
+ readonly postconditionVersion: 3;
491
+ /** v3 kind lives only in the address-free declaration, never beside the binding. */
492
+ readonly kind?: never;
493
+ readonly declaration: GeneratedPostconditionDeclarationV3;
494
+ readonly targetBinding: TargetBinding;
495
+ };
496
+ /** Only v3 is a decodable generated postcondition. Older values replan. */
497
+ type GeneratedPostcondition = GeneratedPostconditionV3;
498
+ /** The version tag is part of the digest domain, never an implicit convention. */
499
+ declare function generatedPostconditionDigest(value: {
500
+ readonly postconditionVersion: number;
501
+ }): string;
502
+ declare function generatedPostconditionForChange(input: {
503
+ readonly change: SchemaChange;
504
+ readonly schema: string;
505
+ }): _dbsp_types.LedgerPayload | undefined;
506
+ /**
507
+ * The only change-kind boundary between diagnostic schema diffing and managed
508
+ * execution. Keep it at manifest construction: diagnostic-only controls must
509
+ * never acquire an address, claim, reservation, or DDL bundle.
510
+ */
511
+ declare function assertDeclarableChangeKind(kind: ChangeKind): asserts kind is Exclude<ChangeKind, 'enable_rls' | 'disable_rls' | 'create_policy' | 'drop_policy' | 'add_comment' | 'drop_comment' | 'alter_column_auto_increment'>;
512
+ /**
513
+ * PostgreSQL's total ChangeKind-to-address producer. The mapping is run at
514
+ * plan time, so no executable generator step can later fall through to a
515
+ * permissive "no managed address" branch.
516
+ */
517
+ declare function createPgGeneratedManagedStep(input: {
518
+ readonly change: SchemaChange;
519
+ readonly database: string;
520
+ readonly schema: string;
521
+ readonly stepKey: string;
522
+ readonly order: number;
523
+ readonly dependencyOrder?: readonly string[];
524
+ readonly statements: readonly string[];
525
+ }): NormalizedManagedStep;
526
+ /**
527
+ * The live differ is the shape comparator. Persist the exact authored table
528
+ * shape, rather than a boolean that could later be reinterpreted.
529
+ */
530
+ declare function pgDeclaredAdoptionDeclaration(table: TableIR): LedgerPayload;
531
+ /**
532
+ * Create the persisted, token-gated declaration that admits an already-live
533
+ * table into the managed ledger. It intentionally mirrors the historical
534
+ * generator lifecycle material so CLI plans retain their byte representation.
535
+ */
536
+ declare function createPgDeclaredAdoptionStep(input: {
537
+ readonly address: Address;
538
+ readonly table: TableIR;
539
+ readonly stepKey: string;
540
+ readonly order: number;
541
+ readonly catalogueIdentity: CatalogueIdentity;
542
+ }): NormalizedManagedStep;
543
+ declare function pgDeclaredSequenceAdoptionDeclaration(sequence: SequenceIR): LedgerPayload;
544
+ /** Creates the token-gated adoption claim for a physical standalone sequence. */
545
+ declare function createPgDeclaredSequenceAdoptionStep(input: {
546
+ readonly address: Address;
547
+ readonly sequence: SequenceIR;
548
+ readonly stepKey: string;
549
+ readonly order: number;
550
+ readonly catalogueIdentity: CatalogueIdentity;
551
+ }): NormalizedManagedStep;
552
+
553
+ type GeneratedPostconditionQuery = {
554
+ query(sql: string, params?: readonly unknown[]): Promise<{
555
+ readonly rows: readonly Record<string, unknown>[];
556
+ }>;
557
+ };
558
+ declare const generatedPostconditionSessionBrand: unique symbol;
559
+ /** An adapter-minted, exclusive PostgreSQL session for rollback-only proof. */
560
+ type GeneratedPostconditionSession = GeneratedPostconditionQuery & {
561
+ readonly [generatedPostconditionSessionBrand]: true;
562
+ };
563
+ /** A retained session capability was used after its owning bracket ended. */
564
+ declare class GeneratedPostconditionSessionDeactivatedError extends Error {
565
+ constructor();
566
+ }
567
+ /** A caller attempted to overlap rollback-only proofs on one capability. */
568
+ declare class GeneratedPostconditionProofInFlightError extends Error {
569
+ constructor();
570
+ }
571
+ /** A session bracket completed while rollback-only proof work was still running. */
572
+ declare class GeneratedPostconditionWorkInFlightError extends Error {
573
+ constructor();
574
+ }
575
+ /**
576
+ * Public verifier checkout bracket. Scratch-backed proofs require the active
577
+ * role to hold database TEMP privilege; callers must preflight that capability
578
+ * before applying managed DDL whose postcondition needs scratch staging.
579
+ */
580
+ declare function withGeneratedPostconditionSession<T>(executor: {
581
+ connect(): Promise<GeneratedPostconditionQuery & {
582
+ release(error?: unknown): void | Promise<void>;
583
+ }>;
584
+ }, work: (session: GeneratedPostconditionSession) => Promise<T>, lockTimeoutMs?: number): Promise<T>;
585
+ type ResolvableGeneratedPostconditionKind = 'table' | 'column' | 'constraint';
586
+ type GeneratedPostconditionBindingKind = ResolvableGeneratedPostconditionKind | 'index' | 'enum' | 'sequence' | 'extension';
587
+ type GeneratedPostconditionSchemaBindingKind = Exclude<GeneratedPostconditionBindingKind, 'extension'>;
588
+ type GeneratedPostconditionTableChildKind = 'column' | 'index' | 'constraint';
589
+ /** The canonical schema-scoped table parent of a managed table child. */
590
+ type GeneratedPostconditionTableParent = {
591
+ readonly scope: 'schema';
592
+ readonly engine: string;
593
+ readonly database: string;
594
+ readonly schema: string;
595
+ readonly kind: 'table';
596
+ readonly name: string;
597
+ readonly parent?: never;
598
+ readonly catalogueIdentity?: never;
599
+ readonly qualifiedBy?: never;
600
+ };
601
+ type GeneratedPostconditionSchemaRootAddress<K extends Exclude<GeneratedPostconditionSchemaBindingKind, GeneratedPostconditionTableChildKind>> = Omit<ResourceAddress, 'engine' | 'schema' | 'parent' | 'kind'> & {
602
+ readonly engine: string;
603
+ readonly scope: 'schema';
604
+ readonly schema: string;
605
+ readonly parent?: never;
606
+ readonly kind: K;
607
+ };
608
+ type GeneratedPostconditionTableChildAddress<K extends GeneratedPostconditionTableChildKind> = Omit<ResourceAddress, 'engine' | 'schema' | 'parent' | 'kind'> & {
609
+ readonly engine: string;
610
+ readonly scope: 'schema';
611
+ readonly schema: string;
612
+ readonly parent: GeneratedPostconditionTableParent;
613
+ readonly kind: K;
614
+ };
615
+ type GeneratedPostconditionExtensionAddress = Omit<ResourceAddress, 'engine' | 'schema' | 'parent' | 'kind'> & {
616
+ readonly engine: string;
617
+ readonly scope: 'database';
618
+ readonly schema?: never;
619
+ readonly parent?: never;
620
+ readonly kind: 'extension';
621
+ };
622
+ /** The complete topology selected by a v3 managed-step binding. */
623
+ type GeneratedPostconditionBindingAddress = GeneratedPostconditionSchemaRootAddress<'table' | 'enum' | 'sequence'> | GeneratedPostconditionTableChildAddress<GeneratedPostconditionTableChildKind> | GeneratedPostconditionExtensionAddress;
624
+ declare class GeneratedPostconditionBindingResolutionError extends Error {
625
+ readonly sought: string;
626
+ readonly found: string;
627
+ constructor(input: {
628
+ readonly sought: string;
629
+ readonly found: string;
630
+ }, options?: ErrorOptions);
631
+ }
632
+ /**
633
+ * Narrows a ledger address into the complete topology that a v3 verifier can
634
+ * bind. Ledger addresses are intentionally broader, so this boundary must
635
+ * reject malformed persisted input before it reaches any verifier dispatch.
636
+ */
637
+ declare function toGeneratedPostconditionBindingAddress(address: LedgerAddress): GeneratedPostconditionBindingAddress;
638
+ type IndexProjection = {
639
+ readonly schema: string;
640
+ readonly table: string;
641
+ readonly name: string;
642
+ readonly method: string;
643
+ readonly unique: boolean;
644
+ readonly valid: boolean;
645
+ readonly ready: boolean;
646
+ readonly live: boolean;
647
+ readonly nullsNotDistinct: boolean;
648
+ readonly primary: boolean;
649
+ readonly exclusion: boolean;
650
+ readonly immediate: boolean;
651
+ readonly constraintOwned: boolean;
652
+ readonly keyColumns: readonly (string | null)[];
653
+ readonly keyDefinitions: readonly string[];
654
+ readonly includeColumns: readonly string[];
655
+ readonly opclasses: readonly string[];
656
+ readonly keyOptions: readonly string[];
657
+ readonly reloptions: readonly string[];
658
+ readonly predicate: string | null;
659
+ };
660
+ type CheckProjection = {
661
+ readonly expression: string;
662
+ readonly validated: boolean;
663
+ readonly noInherit: boolean;
664
+ readonly enforced: boolean;
665
+ readonly isLocal: boolean;
666
+ readonly inheritanceCount: number;
667
+ readonly parentId: number;
668
+ };
669
+ type TableColumnProjection = {
670
+ readonly name: string;
671
+ readonly type: string;
672
+ readonly nullable: boolean;
673
+ readonly default: string | undefined;
674
+ /** Ownership and canonical nextval shape read in the same catalogue snapshot. */
675
+ readonly generatedSequenceDefault: boolean;
676
+ readonly collation: string | null;
677
+ readonly identity: 'always' | 'byDefault' | null;
678
+ };
679
+ type TableProjection = {
680
+ readonly columns: readonly TableColumnProjection[];
681
+ };
682
+ type GeneratedColumnProjection = Omit<TableColumnProjection, 'name'>;
683
+ declare class GeneratedPostconditionReplanRequiredError extends Error {
684
+ readonly code = "REPLAN_REQUIRED";
685
+ readonly diagnostic: Readonly<{
686
+ versionSeen: unknown;
687
+ stepIdentity: string | undefined;
688
+ structuralPath: string | undefined;
689
+ }>;
690
+ readonly structuralPath: string | undefined;
691
+ constructor(message: string, versionSeen?: unknown, stepIdentity?: string | undefined, options?: ErrorOptions, structuralPath?: string | undefined);
692
+ }
693
+ /**
694
+ * Decode exactly one postcondition interpretation per version: only v3 is
695
+ * accepted. v1/v2 and every other value are named REPLAN_REQUIRED outcomes.
696
+ */
697
+ declare function decodeGeneratedPostcondition(value: unknown, stepIdentity?: string): GeneratedPostcondition;
698
+ /**
699
+ * The persisted digest is bound to the versioned wire value before decoding.
700
+ * A digest minted for one version cannot authenticate another version body.
701
+ */
702
+ declare function decodeGeneratedPostconditionPayload(payload: {
703
+ readonly value: unknown;
704
+ readonly digest: string;
705
+ }, stepIdentity?: string): GeneratedPostcondition;
706
+ /** Refuse structural lookalikes before any proof or catalogue read. */
707
+ declare function assertGeneratedPostconditionSession(value: unknown): GeneratedPostconditionSession;
708
+ type GeneratedPostconditionCatalogueIdentity = NonNullable<ResourceAddress['catalogueIdentity']>;
709
+ /** Resolves the v3 table binding, then delegates its shared structural proof. */
710
+ declare function verifyGeneratedTablePostcondition(input: {
711
+ readonly session: GeneratedPostconditionSession;
712
+ readonly postcondition: unknown;
713
+ readonly address: GeneratedPostconditionBindingAddress;
714
+ }): Promise<{
715
+ readonly kind: 'table';
716
+ readonly projection: TableProjection;
717
+ readonly catalogueIdentity: GeneratedPostconditionCatalogueIdentity;
718
+ }>;
719
+ /** Resolves the v3 column binding, then delegates its shared structural proof. */
720
+ declare function verifyGeneratedColumnPostcondition(input: {
721
+ readonly session: GeneratedPostconditionSession;
722
+ readonly postcondition: unknown;
723
+ readonly address: GeneratedPostconditionBindingAddress;
724
+ }): Promise<{
725
+ readonly kind: 'column';
726
+ readonly projection: GeneratedColumnProjection;
727
+ readonly catalogueIdentity: GeneratedPostconditionCatalogueIdentity;
728
+ }>;
729
+ /** Resolves the v3 index binding, then delegates its shared structural proof. */
730
+ declare function verifyGeneratedIndexPostcondition(input: {
731
+ readonly session: GeneratedPostconditionSession;
732
+ readonly postcondition: unknown;
733
+ readonly address: GeneratedPostconditionBindingAddress;
734
+ }): Promise<{
735
+ readonly kind: 'index';
736
+ readonly projection: IndexProjection;
737
+ readonly catalogueIdentity: GeneratedPostconditionCatalogueIdentity;
738
+ }>;
739
+ /** Resolves the v3 CHECK binding, then delegates its shared structural proof. */
740
+ declare function verifyGeneratedCheckPostcondition(input: {
741
+ readonly session: GeneratedPostconditionSession;
742
+ readonly postcondition: unknown;
743
+ readonly address: GeneratedPostconditionBindingAddress;
744
+ }): Promise<{
745
+ readonly kind: 'constraint';
746
+ readonly projection: CheckProjection;
747
+ readonly catalogueIdentity: GeneratedPostconditionCatalogueIdentity;
748
+ }>;
749
+ /**
750
+ * Binds the deliberately non-structural v3 kinds under the same rollback-only
751
+ * proof bracket as structural verifiers. The declaration kind is the binding
752
+ * expectation, so a sequence slot can never observe an enum declaration (or
753
+ * vice versa) merely because the address happens to resolve.
754
+ */
755
+ declare function verifyGeneratedIdentityPostcondition(input: {
756
+ readonly session: GeneratedPostconditionSession;
757
+ readonly postcondition: unknown;
758
+ readonly address: GeneratedPostconditionBindingAddress;
759
+ readonly kind: 'constraint' | 'enum' | 'sequence' | 'extension';
760
+ }): Promise<{
761
+ readonly kind: 'constraint' | 'enum' | 'sequence' | 'extension';
762
+ readonly identity: Readonly<{
763
+ readonly relationOid: string;
764
+ readonly objectOid?: string;
765
+ }>;
766
+ readonly catalogueIdentity: GeneratedPostconditionCatalogueIdentity;
767
+ }>;
768
+
769
+ /**
770
+ * PostgreSQL Schema Introspection (ADAPTER-006)
771
+ *
772
+ * Queries information_schema/pg_catalog to build ModelIR
773
+ * from an existing database. Supports:
774
+ * - Table/column/PK discovery
775
+ * - FK → bidirectional relation inference
776
+ * - Hierarchy detection (adjacency + edge-table)
777
+ * - Include/exclude filtering
778
+ *
779
+ * @module introspection
780
+ */
781
+
782
+ /** The minimum every schema-level operation needs: which schema. */
783
+ interface SchemaScopeOptions {
784
+ /** Schema name to operate on (default: 'public') */
785
+ readonly schema?: string;
786
+ }
787
+ /**
788
+ * Introspection additionally chooses WHICH TABLES to read. It is a read-only
789
+ * path, so narrowing it is safe — that is why the table filters live here and
790
+ * nowhere else.
791
+ */
792
+ interface IntrospectionOptions extends SchemaScopeOptions {
793
+ /** Tables to exclude (glob patterns: * matches any chars) */
794
+ readonly exclude?: readonly string[];
795
+ /** Tables to include (default: all). Applied before exclude. */
796
+ readonly include?: readonly string[];
797
+ }
798
+ /** Hierarchy pattern detected during introspection */
799
+ /**
800
+ * Hierarchy pattern detected during introspection.
801
+ * Alias of {@link HierarchyIR} from \@dbsp/types — kept here for
802
+ * public-API backwards compatibility (re-exported from \@dbsp/adapter-pgsql).
803
+ */
804
+ type DetectedHierarchy = HierarchyIR;
805
+ /** Extended ModelIR with hierarchy metadata */
806
+ interface IntrospectedModelIR extends ModelIR {
807
+ readonly hierarchies: readonly DetectedHierarchy[];
808
+ readonly introspectedAt: Date;
809
+ readonly warnings: readonly string[];
810
+ }
811
+ /**
812
+ * Introspect a database through a pool.
813
+ *
814
+ * This does NOT accept a checked-out `PoolClient`, and that is deliberate. A
815
+ * client may be sitting inside a transaction that belongs to its owner, and a
816
+ * catalog query that fails there aborts *their* transaction. Protecting that
817
+ * needs a savepoint, and knowing whether to take one needs the caller to say
818
+ * whose transaction it is — which is what `PgAdapter`'s `borrowedClient`
819
+ * declaration is for. Guessing it from the object's shape is the exact defect
820
+ * this adapter was rewritten to remove.
821
+ *
822
+ * Saying so in a comment is not enough: `CatalogQueryExecutor` is structural, so
823
+ * a `PoolClient` — which has a `query()` — satisfies it, and the prose would have
824
+ * been the only thing standing in the way. It is branded instead, and only the
825
+ * adapter's own protected executor carries the brand. A client cannot be passed
826
+ * here at all.
827
+ *
828
+ * So: hold a client, use `new PgAdapter(client, { borrowedClient: true })`
829
+ * and call `.introspect()` on it.
830
+ */
831
+ declare function introspect(pool: Pool, options?: IntrospectionOptions): Promise<IntrospectedModelIR>;
832
+
833
+ type PgsqlTransactionTimeoutParameter = 'lock_timeout' | 'statement_timeout';
834
+
835
+ declare const rollbackOnlyPgsqlScopeBrand: unique symbol;
836
+ /** A scope minted by withScratchScope and guaranteed to roll back on success. */
837
+ type PgRollbackOnlyScope<DB = unknown> = PgAdapter<DB> & {
838
+ readonly [rollbackOnlyPgsqlScopeBrand]: typeof rollbackOnlyPgsqlScopeBrand;
839
+ };
840
+ type PgAdvisoryLockKey = bigint | {
841
+ readonly classId: number;
842
+ readonly objId: number;
843
+ };
844
+ type PgAdvisoryLockResult<T> = {
845
+ readonly acquired: true;
846
+ readonly value: T;
847
+ } | {
848
+ readonly acquired: false;
849
+ };
850
+ declare class PgRawSqlTransactionControlError extends Error {
851
+ readonly dbspRawSqlTransactionControl = true;
852
+ constructor(cause: unknown);
853
+ }
854
+ declare class PgTransactionAbortedCommitError extends Error {
855
+ readonly dbspTransactionAbortedCommit = true;
856
+ constructor(cause: unknown);
857
+ }
858
+ declare class PgTransactionAbortedError extends Error {
859
+ readonly dbspTransactionAborted = true;
860
+ constructor(cause: unknown);
861
+ }
862
+ /**
863
+ * Raised when a pool-owned top-level transaction is aborted through
864
+ * `TransactionOptions.signal`. If the signal aborts while `pool.connect()` is
865
+ * still pending, dbsp honors it only after a client is acquired.
866
+ */
867
+ declare class PgTransactionAbortSignalError extends Error {
868
+ readonly dbspTransactionAbortSignal = true;
869
+ constructor();
870
+ }
871
+ declare class PgPinnedConnectionAbortSignalError extends Error {
872
+ readonly dbspPinnedConnectionAbortSignal = true;
873
+ constructor();
874
+ }
875
+ declare class PgTransactionOptionsError extends Error {
876
+ readonly dbspTransactionOptions = true;
877
+ constructor(message: string);
878
+ }
879
+ declare class PgAdvisoryLockOptionsError extends Error {
880
+ readonly dbspAdvisoryLockOptions = true;
881
+ constructor(message: string);
882
+ }
883
+ /**
884
+ * Raised when a statement inside a dbsp-managed transaction fails with a SQLSTATE
885
+ * that matches a timeout the caller configured for that transaction: `55P03`
886
+ * (`lock_not_available`) when `lockTimeoutMs` was set, or `57014` (`query_canceled`)
887
+ * when `statementTimeoutMs` was set. The original PostgreSQL error is preserved as
888
+ * `cause`.
889
+ *
890
+ * Classification is by SQLSTATE only. PostgreSQL assigns these codes to the OUTCOME,
891
+ * not the cause: `55P03` is also raised by `FOR UPDATE NOWAIT`, and `57014` is also
892
+ * raised by an external cancel (e.g. `pg_cancel_backend`). There is no locale-stable
893
+ * structured field that separates the timeout from the other cause, so the message
894
+ * text is deliberately NOT parsed. dbsp never emits `NOWAIT` itself, so a `55P03`
895
+ * here is the configured `lock_timeout` unless the caller's own raw SQL used
896
+ * `NOWAIT`; a `57014` is the configured `statement_timeout` unless the backend was
897
+ * cancelled from outside. Inspect `cause` when that distinction matters.
898
+ */
899
+ declare class PgTransactionTimeoutError extends Error {
900
+ readonly timeout: PgsqlTransactionTimeoutParameter;
901
+ readonly dbspTransactionTimeout = true;
902
+ constructor(cause: unknown, timeout: PgsqlTransactionTimeoutParameter);
903
+ }
904
+ /**
905
+ * Raised when the single safe unnamed replay after a prepared-statement
906
+ * infrastructure failure also fails. `message` is always the safe constant
907
+ * `Prepared statement recovery replay failed.`; `cause` is the replay error;
908
+ * `infrastructureError` is the original infrastructure error; and
909
+ * `admissionFingerprint` identifies the admitted statement. DBSP-authored
910
+ * messages carry no parameter values; preserved upstream errors, including the
911
+ * standard Error `cause`, are unsanitized.
912
+ */
913
+ declare class PgPreparedStatementReplayError extends Error {
914
+ readonly admissionFingerprint: string;
915
+ readonly infrastructureError: unknown;
916
+ readonly dbspPreparedStatementReplay = true;
917
+ readonly originalInfrastructureError: unknown;
918
+ readonly originalError: unknown;
919
+ constructor(admissionFingerprint: string, infrastructureError: unknown, cause: unknown);
920
+ }
921
+ /**
922
+ * Options for PgAdapter.
923
+ */
924
+ interface PgPreparedStatementsOptions {
925
+ /** Maximum distinct compiled statements admitted per executor (default: 500). */
926
+ readonly maxStatements?: number;
927
+ }
928
+ interface PgAdapterOptions {
929
+ /** Schema name for multi-tenant queries */
930
+ readonly schemaName?: string;
931
+ /**
932
+ * DB column casing convention (intuitive semantics).
933
+ * - `'snake_case'`: DB columns are snake_case → transform to camelCase for JS
934
+ * - `'camelCase'`: DB columns are camelCase → no transformation
935
+ * - `'preserve'`: No transformation
936
+ */
937
+ readonly dbCasing?: DbCasing;
938
+ /** Optional model for WHERE compilation */
939
+ readonly model?: ModelIR;
940
+ /** Optional logger for debug/error messages */
941
+ readonly logger?: AdapterLogger;
942
+ /** Default primary key column name for convention fallbacks (default: 'id') */
943
+ readonly defaultPkColumnName?: string;
944
+ /** Convention for deriving FK column names: (tableName, pkName) => fkColumnName */
945
+ readonly deriveFkColumnName?: FkColumnDerivation;
946
+ /**
947
+ * Opt in to node-postgres named prepared statements for compiled queries with
948
+ * parameters. `true` uses the default statement cap; an object overrides it.
949
+ */
950
+ readonly preparedStatements?: boolean | PgPreparedStatementsOptions;
951
+ }
952
+ interface PgsqlPoolAdapterOptionsBase extends PgAdapterOptions {
953
+ readonly borrowedClient?: false;
954
+ }
955
+ type PgPoolAdapterOptions = (PgsqlPoolAdapterOptionsBase & {
956
+ readonly replayInvalidatedPlans?: false | undefined;
957
+ }) | (Omit<PgsqlPoolAdapterOptionsBase, 'preparedStatements'> & {
958
+ readonly preparedStatements: true | PgPreparedStatementsOptions;
959
+ /**
960
+ * Enable one unnamed replay after `0A000`/`RevalidateCachedQuery` only when
961
+ * you assert that your statements do not invoke functions performing
962
+ * effectful work before nested prepared-statement operations. This requires
963
+ * `preparedStatements: true` (or a prepared-statements options object).
964
+ *
965
+ * Replay snapshots JSON-like values (finite numbers, strings, booleans,
966
+ * `null`, arrays, plain or null-prototype objects) and clean `Date`/`Buffer`
967
+ * instances. It excludes non-finite numbers, `undefined`, `bigint`, functions,
968
+ * proxies, cycles, sparse arrays, accessors, symbol-valued
969
+ * parameters, symbol keys on plain objects, exotic prototypes, custom built-ins,
970
+ * and values with their own node-postgres
971
+ * `toPostgres` behavior.
972
+ * Serialization-irrelevant symbol metadata on arrays and Buffers is ignored.
973
+ * The detached snapshot covers later mutations to the supplied value graph,
974
+ * not built-in prototypes, timezone state, or node-postgres serialization
975
+ * configuration; a process-global `toPostgres` or `toJSON` installed while
976
+ * the call is in flight is outside the guarantee. Each capture or replay copy
977
+ * is independently limited to 64 Ki visited values, 16 MiB of UTF-8 strings,
978
+ * and 16 MiB of Buffer data. An ineligible or over-budget value still receives
979
+ * the initial named submission, but disables transparent replay.
980
+ * These budgets bound copied nodes and payload bytes; enumerating a plain
981
+ * object's existing property table is proportional to the caller's own object.
982
+ *
983
+ * Replay needs the adapter-owned serialized physical client available from a
984
+ * pool; it is therefore not supported by borrowed or compile-only adapters.
985
+ */
986
+ readonly replayInvalidatedPlans: true;
987
+ });
988
+ interface PgBorrowedClientAdapterOptions extends PgAdapterOptions {
989
+ /** Replay is only available to a pool-owned pinned scope. */
990
+ readonly replayInvalidatedPlans?: never;
991
+ /** This connection belongs to the caller. dbsp never releases it. */
992
+ readonly borrowedClient: true;
993
+ /**
994
+ * Let dbsp run transactions on your connection, through a savepoint.
995
+ *
996
+ * When your connection is already inside a transaction, dbsp creates a
997
+ * savepoint and rolls back dbsp's changes after that savepoint if the callback
998
+ * fails. `RELEASE SAVEPOINT` does not commit; it merges the work into your
999
+ * surrounding transaction, so a callback that succeeded is still undone if you
1000
+ * later roll back. Deferred constraints or triggers can still make your outer
1001
+ * `COMMIT` fail after dbsp has returned. `SET LOCAL` changes inside the callback
1002
+ * remain in effect for the rest of your transaction after the savepoint is
1003
+ * released. `ON COMMIT DROP` and `ON COMMIT DELETE ROWS` fire at your transaction
1004
+ * boundary, not at the savepoint. Sequences are not transactional:
1005
+ * `nextval`/`setval` are not reclaimed by a savepoint rollback. Session-level
1006
+ * advisory locks ignore rollback; transaction-level advisory locks taken by a
1007
+ * successful callback last until your transaction ends.
1008
+ *
1009
+ * Transaction control through raw SQL inside a scope dbsp is managing is
1010
+ * unsupported. `COMMIT`, `ROLLBACK`, and `PREPARE TRANSACTION` end the
1011
+ * transaction dbsp is working inside; dbsp detects that and fails loudly, but
1012
+ * the data is already whatever your statement made it. Raw savepoint control
1013
+ * (`SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`) can alter the
1014
+ * savepoint stack before dbsp sees the command tag; dbsp poisons the scope, but
1015
+ * it cannot make that command un-run. Manage your transaction outside dbsp's
1016
+ * calls.
1017
+ */
1018
+ readonly managedTransactions?: true;
1019
+ }
1020
+ /** Options for a connectionless adapter, which cannot own replay serialization. */
1021
+ interface PgCompileOnlyAdapterOptions extends PgAdapterOptions {
1022
+ readonly replayInvalidatedPlans?: never;
1023
+ }
1024
+ /**
1025
+ * Adapter implementation for PostgreSQL using native pg driver.
1026
+ *
1027
+ * @typeParam DB - Database schema type
1028
+ *
1029
+ * @example
1030
+ * ```typescript
1031
+ * import { Pool } from 'pg';
1032
+ * import { createPgAdapter } from '@dbsp/adapter-pgsql';
1033
+ *
1034
+ * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
1035
+ * const adapter = createPgAdapter(pool);
1036
+ * const orm = createOrm({ model, adapter });
1037
+ * ```
1038
+ */
1039
+ declare class PgAdapter<DB = unknown> implements Adapter<DB> {
1040
+ private readonly pool;
1041
+ private readonly client;
1042
+ private readonly borrowedClient;
1043
+ private readonly managedTransactions;
1044
+ private readonly adapterManagedTransaction;
1045
+ private readonly adapterManagedPinnedConnection;
1046
+ private readonly rollbackOnlyScope;
1047
+ private readonly scopeToken;
1048
+ private readonly scopeState;
1049
+ private readonly schemaName;
1050
+ private readonly _dbCasing;
1051
+ private readonly model;
1052
+ private readonly logger;
1053
+ private readonly replayInvalidatedPlans;
1054
+ private readonly preparedStatements;
1055
+ private readonly preparedStatementRegistry;
1056
+ private readonly _capabilities;
1057
+ private readonly defaultPk;
1058
+ private readonly deriveFk;
1059
+ /**
1060
+ * Create a new PgAdapter.
1061
+ *
1062
+ * Ownership of the connection is **declared**, never inferred. Handing over a
1063
+ * `PoolClient` means nothing on its own — it says the object has a `release()`
1064
+ * method, not that a transaction is open or that the caller owns the lifecycle.
1065
+ * Pass `borrowedClient: true` to say so.
1066
+ *
1067
+ * @param pool - a pg.Pool, a caller-owned pg.PoolClient (with `borrowedClient: true`),
1068
+ * or nothing at all for compile-only mode
1069
+ * @param options - configuration; declares connection ownership
1070
+ */
1071
+ constructor(pool: Pool, options?: PgPoolAdapterOptions);
1072
+ constructor(client: PoolClient, options: PgBorrowedClientAdapterOptions);
1073
+ constructor(pool?: undefined, options?: PgCompileOnlyAdapterOptions);
1074
+ /**
1075
+ * Shared compilation dependencies — built lazily from adapter fields.
1076
+ * Passed to compiler sub-modules instead of `this`.
1077
+ */
1078
+ /**
1079
+ * Return a new PgAdapterOptions that merges current config with overrides.
1080
+ * Ensures that all configuration fields (logger, defaultPkColumnName,
1081
+ * deriveFkColumnName, etc.) are propagated to scoped/transactional adapters.
1082
+ */
1083
+ private cloneOptions;
1084
+ private buildCompileDeps;
1085
+ private requireNqlCompileModel;
1086
+ private compileNqlMutation;
1087
+ private compileNqlBundleLeafEnvelope;
1088
+ private compileNqlBundle;
1089
+ /**
1090
+ * Returns the pool/client executor, or refuses a connectionless adapter.
1091
+ */
1092
+ private requireConnection;
1093
+ /** Adapter capabilities for feature detection */
1094
+ get capabilities(): AdapterCapabilities;
1095
+ /** Per-instance connection state, distinct from PostgreSQL capabilities. */
1096
+ get connectionAvailability(): ConnectionAvailability;
1097
+ /** Side-effect-free execution availability for core feature detection. */
1098
+ executionAvailable(): boolean;
1099
+ /** PostgreSQL dialect capabilities for planner strategy selection */
1100
+ get dialectCapabilities(): DialectCapabilities;
1101
+ /**
1102
+ * DB column casing convention used by this adapter.
1103
+ */
1104
+ get dbCasing(): DbCasing;
1105
+ /**
1106
+ * Get the underlying pg Pool or borrowed PoolClient instance.
1107
+ *
1108
+ * Exposing raw access from a pool-owned dbsp-managed scope permanently taints that
1109
+ * physical client: external callers can queue commands outside dbsp's statement
1110
+ * lock, so replay is disabled and dbsp destroys the client at scope release.
1111
+ * Expect pool churn; session state on that exposed connection does not survive the
1112
+ * release. A borrowed client remains caller-owned: dbsp never releases it, and the
1113
+ * caller decides its fate after raw exposure.
1114
+ */
1115
+ getPoolInstance(): Pool | PoolClient;
1116
+ /**
1117
+ * Compile a plan to executable SQL.
1118
+ *
1119
+ * When passed a direct `CompiledNqlQuery`, the adapter trusts that the bundle
1120
+ * has already been semantically validated by the NQL compiler. This method
1121
+ * still performs adapter-owned SQL safety checks for emitted binding names
1122
+ * before CTE emission.
1123
+ */
1124
+ compile<T = unknown>(plan: PlanReport | CompiledNqlQuery, options?: CompileOptions): CompiledQuery<T>;
1125
+ /**
1126
+ * Compile a FROM-less SELECT expression to SQL.
1127
+ *
1128
+ * Produces: SELECT <expr>
1129
+ * Example: SELECT nextval('my_seq')
1130
+ *
1131
+ * @param expr - ExpressionIntent to evaluate
1132
+ * @returns Compiled SQL and parameters
1133
+ */
1134
+ compileSelectExpression<T = unknown>(expr: ExpressionIntent, options?: CompileOptions): CompiledQuery<T>;
1135
+ /**
1136
+ * Compile an insert intent to executable SQL.
1137
+ *
1138
+ * Strategy switch (per CompileOptions):
1139
+ * - rows <= batchThreshold (default 50): VALUES ($1,$2),($3,$4),...
1140
+ * - rows > batchThreshold OR batchThreshold === 0: SELECT unnest($1::type[]),...
1141
+ */
1142
+ compileInsert(intent: InsertIntent, options?: CompileOptions): CompiledQuery;
1143
+ /**
1144
+ * Compile an insert-from intent to executable SQL (NQL-ALIGN).
1145
+ * INSERT INTO target (cols) SELECT cols FROM source WHERE ... LIMIT ... RETURNING ...
1146
+ */
1147
+ compileInsertFrom(intent: InsertFromIntent, options?: CompileOptions): CompiledQuery;
1148
+ /**
1149
+ * Compile an update intent to executable SQL.
1150
+ */
1151
+ compileUpdate(intent: UpdateIntent, options?: CompileOptions): CompiledQuery;
1152
+ /**
1153
+ * Compile a batch update intent to executable SQL using unnest FROM strategy (BATCH-001).
1154
+ *
1155
+ * Generates:
1156
+ * UPDATE "table" SET "update_col" = t."update_col" [, "scalar_col" = $N]
1157
+ * FROM unnest(CAST($1 AS type[]), CAST($2 AS type[])) AS t("match_col", "update_col")
1158
+ * WHERE "table"."match_col" = t."match_col"
1159
+ * [RETURNING ...]
1160
+ */
1161
+ compileBatchUpdate(intent: BatchUpdateIntent, options?: CompileOptions): CompiledQuery;
1162
+ /**
1163
+ * Compile a delete intent to executable SQL.
1164
+ */
1165
+ compileDelete(intent: DeleteIntent, options?: CompileOptions): CompiledQuery;
1166
+ /**
1167
+ * Compile an upsert intent to executable SQL (DX-026).
1168
+ */
1169
+ compileUpsert(intent: UpsertIntent, options?: CompileOptions): CompiledQuery;
1170
+ /**
1171
+ * Compile an upsert-from intent to executable SQL (NQL-BIND).
1172
+ * INSERT INTO target SELECT ... FROM source ON CONFLICT (cols) DO UPDATE SET ...
1173
+ */
1174
+ compileUpsertFrom(intent: UpsertFromIntent, options?: CompileOptions): CompiledQuery;
1175
+ /**
1176
+ * Compile a recursive CTE plan to executable SQL.
1177
+ * Supports adjacency-list and edge-table traversal modes.
1178
+ */
1179
+ compileRecursive<T = unknown>(report: RecursivePlanReport, model: ModelIR, options?: CompileOptions): CompiledQuery<T>;
1180
+ /**
1181
+ * Compile a CTE query backed by unnest() arrays (BATCH-001 Block 5).
1182
+ *
1183
+ * Strategy: compile CTE nodes to SQL fragments, compile outer query
1184
+ * independently (parameters starting at $1), then renumber outer params
1185
+ * to start after CTE params and prepend WITH clause.
1186
+ */
1187
+ compileCteQuery<T = unknown>(intent: CteQueryIntent, options?: CompileOptions): CompiledQuery<T>;
1188
+ /**
1189
+ * Compile a set operation (UNION / INTERSECT / EXCEPT) to SQL.
1190
+ */
1191
+ compileSetOperation<T = unknown>(intent: SetOperationIntent, model: ModelIR, options?: CompileOptions): CompiledQuery<T>;
1192
+ private compileSetOperationWithBindings;
1193
+ /**
1194
+ * Create a dump for observability.
1195
+ */
1196
+ createDump(plan: PlanReport, query: CompiledQuery, meta?: DumpMeta): Dump;
1197
+ /**
1198
+ * Execute a query and return all results.
1199
+ * Result labels are mapped to their logical projection keys by the compiled query.
1200
+ */
1201
+ execute<T>(query: CompiledQuery<T>): Promise<T[]>;
1202
+ /**
1203
+ * Execute a query and return rows plus PostgreSQL result metadata.
1204
+ * Result labels are mapped to their logical projection keys by the compiled query.
1205
+ */
1206
+ executeWithMeta(query: CompiledQuery): Promise<{
1207
+ readonly rows: readonly unknown[];
1208
+ readonly rowCount: number;
1209
+ readonly command?: string;
1210
+ }>;
1211
+ /**
1212
+ * Transform result rows through the projection's returned-label map.
1213
+ */
1214
+ private transformResultRows;
1215
+ /**
1216
+ * Execute a query and return the first result or null.
1217
+ */
1218
+ executeOne<T>(query: CompiledQuery<T>): Promise<T | null>;
1219
+ /**
1220
+ * Execute a query and return the first result or throw.
1221
+ */
1222
+ executeOneOrThrow<T>(query: CompiledQuery<T>): Promise<T>;
1223
+ /**
1224
+ * Stream query results as an async iterable iterator.
1225
+ * Uses PostgreSQL cursors for efficient streaming.
1226
+ *
1227
+ * Note: The cursor must be used within a transaction. If not already
1228
+ * in a transaction, this method wraps the streaming in one.
1229
+ *
1230
+ * @param query - Compiled query to stream
1231
+ * @param options - Stream options (chunkSize)
1232
+ * @returns AsyncIterableIterator that yields rows one by one
1233
+ */
1234
+ stream<T>(query: CompiledQuery<T>, options?: AdapterStreamOptions): AsyncIterableIterator<T>;
1235
+ /** Stream raw SQL directly using the same cursor machinery as stream(). */
1236
+ streamRaw<T = unknown>(sql: string, parameters?: readonly unknown[], options?: AdapterStreamOptions): AsyncIterableIterator<T>;
1237
+ private streamCursor;
1238
+ /**
1239
+ * Internal: Stream with an existing client using cursors.
1240
+ */
1241
+ private streamWithClient;
1242
+ private streamWithManagedClient;
1243
+ private streamWithManagedClientSavepointScope;
1244
+ private streamWithClientTransaction;
1245
+ /**
1246
+ * Introspect the database schema and return a ModelIR.
1247
+ *
1248
+ * @param options - Optional introspection options (schema, include/exclude filters)
1249
+ * @returns IntrospectedModelIR with tables, relations, and hierarchy metadata
1250
+ *
1251
+ * @example
1252
+ * ```typescript
1253
+ * const model = await adapter.introspect();
1254
+ * const model = await adapter.introspect({ schema: 'tenant_1' });
1255
+ * const model = await adapter.introspect({ exclude: ['_prisma*'] });
1256
+ * ```
1257
+ */
1258
+ introspect(options?: IntrospectionOptions): Promise<IntrospectedModelIR>;
1259
+ /**
1260
+ * Acquire an exclusive session-level PostgreSQL advisory lock for the callback.
1261
+ *
1262
+ * The lock, callback, and unlock run on one `withPinnedConnection()` adapter.
1263
+ * dbsp performs one PostgreSQL acquire and one matching unlock per call. It
1264
+ * does not track reentrant depth in v1; PostgreSQL's session-level stacking
1265
+ * still applies when callers deliberately nest on the same pinned adapter.
1266
+ */
1267
+ withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>): Promise<T>;
1268
+ withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options: {
1269
+ readonly wait?: 'block';
1270
+ readonly signal?: AbortSignal;
1271
+ }): Promise<T>;
1272
+ withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options: {
1273
+ readonly wait: 'try';
1274
+ readonly signal?: AbortSignal;
1275
+ }): Promise<PgAdvisoryLockResult<T>>;
1276
+ withAdvisoryLock<T>(key: PgAdvisoryLockKey, fn: (locked: Adapter<DB>) => Promise<T>, options?: {
1277
+ readonly wait?: 'block' | 'try';
1278
+ readonly signal?: AbortSignal;
1279
+ }): Promise<T | PgAdvisoryLockResult<T>>;
1280
+ private unlockAdvisoryLock;
1281
+ withPinnedConnection<T>(fn: (adapter: Adapter<DB>) => Promise<T>, options?: PinnedConnectionOptions): Promise<T>;
1282
+ private pinnedConnectionReleaseReason;
1283
+ private pinnedConnectionWithClient;
1284
+ /**
1285
+ * Execute a callback within a database transaction.
1286
+ *
1287
+ * ## What this guarantees
1288
+ *
1289
+ * The callback's work commits together or not at all; a statement issued inside
1290
+ * the transaction never executes after its boundary, even if you forget to
1291
+ * `await` it; a nested `transaction()` is a real savepoint; and the connection
1292
+ * never goes back to the pool with a transaction still open on it.
1293
+ *
1294
+ * ## What it cannot guarantee, and you should know before you reach for raw SQL
1295
+ *
1296
+ * **Raw SQL that ends the transaction ends it.** `COMMIT`, `ROLLBACK` and
1297
+ * `PREPARE TRANSACTION` issued through `executeRaw` — or through several commands
1298
+ * in one call — reach PostgreSQL and take effect *before* dbsp is told what they
1299
+ * were: the command tag arrives after the statement has run. dbsp detects it, kills
1300
+ * the scope so nothing else escapes, and throws — but **it cannot un-run what your
1301
+ * statement already did**, and `transaction()` rejecting does not mean nothing was
1302
+ * committed.
1303
+ *
1304
+ * The same holds for session state raw SQL creates: a sequence that advanced stays
1305
+ * advanced, an advisory lock stays held, a `PREPARE` or a `SET` you issued survives
1306
+ * on a pooled connection. dbsp cleans up only what dbsp created.
1307
+ *
1308
+ * This is the contract of an escape hatch, not an oversight — see #327. If you need
1309
+ * transaction control, own the transaction: take a client, `BEGIN` on it yourself,
1310
+ * and hand dbsp a `borrowedClient` **without** `managedTransactions`. dbsp will then
1311
+ * contain its own statements inside *your* transaction instead of the other way round.
1312
+ */
1313
+ transaction<T>(fn: (adapter: Adapter<DB>) => Promise<T>, options?: TransactionOptions): Promise<T>;
1314
+ /**
1315
+ * Execute scratch PostgreSQL work in a scope that always rolls back on success.
1316
+ *
1317
+ * This is intentionally PostgreSQL-adapter-specific. It is used for catalog
1318
+ * shaped scratch DDL such as expression canonicalisation, where the caller
1319
+ * needs PostgreSQL's rendering but must not keep the scratch objects. This
1320
+ * scope has exactly one successful exit: rollback. In a caller transaction,
1321
+ * only this outer savepoint is retained after rollback; nested work releases
1322
+ * normally, so a large canonicalisation run cannot retain one subtransaction
1323
+ * per expression.
1324
+ * Rollback here is cleanup of dbsp-created work, not a sandbox for arbitrary
1325
+ * session effects.
1326
+ */
1327
+ withScratchScope<T>(fn: (adapter: PgRollbackOnlyScope<DB>) => Promise<T>): Promise<T>;
1328
+ private createManagedClientAdapter;
1329
+ private createPinnedConnectionAdapter;
1330
+ private createChildTransactionObserver;
1331
+ private observeChildTransaction;
1332
+ private markChildTransactionObserved;
1333
+ private refreshScopeChildrenFailure;
1334
+ private transactionWithManagedClient;
1335
+ private transactionWithManagedClientSavepointScope;
1336
+ private applyTransactionTimeouts;
1337
+ private captureAndApplySavepointTimeouts;
1338
+ private restoreSavepointTimeouts;
1339
+ private transactionWithClientTransaction;
1340
+ private releaseClient;
1341
+ private rollbackAndReleaseSavepoint;
1342
+ private rollbackSavepoint;
1343
+ private releaseSavepoint;
1344
+ private rollbackTransactionIfOpen;
1345
+ private classifyTransactionStateError;
1346
+ private probeTransactionState;
1347
+ private classifySavepointReleaseFailure;
1348
+ private rollbackSavepointAfterReleaseFailure;
1349
+ private enterTransactionScope;
1350
+ private enterPinnedConnectionScope;
1351
+ private enterSavepointScope;
1352
+ private pushClientScope;
1353
+ private currentClientScope;
1354
+ private managedScopeEndedMessage;
1355
+ private assertCanUseClient;
1356
+ private assertUsableScopeAncestors;
1357
+ private findClientScope;
1358
+ private assertScopeNotPoisoned;
1359
+ private throwIfScopePoisoned;
1360
+ private scopePoisonOutranksError;
1361
+ private poisonScopeState;
1362
+ private poisonClientScope;
1363
+ private poisonClientScopeStack;
1364
+ private runWithScopeStatementLock;
1365
+ private closeScope;
1366
+ private closeScopeAndAssertChildren;
1367
+ private drainScopeStatements;
1368
+ private drainScopeChildren;
1369
+ private assertScopeChildrenSettled;
1370
+ private drainScopeWork;
1371
+ private executeScopeBoundaryStatement;
1372
+ private assertCommitSucceeded;
1373
+ /**
1374
+ * Create a schema-scoped adapter for multi-tenant queries.
1375
+ */
1376
+ getSchemaName(): string | undefined;
1377
+ withSchema(schemaName: string): Adapter<DB>;
1378
+ /**
1379
+ * Execute raw SQL directly.
1380
+ *
1381
+ * ⚠️ WARNING: Use parameter placeholders ($1, $2, etc.) for all values.
1382
+ *
1383
+ * Transaction control through raw SQL inside a scope dbsp is managing is
1384
+ * unsupported. `COMMIT`, `ROLLBACK`, and `PREPARE TRANSACTION` end the
1385
+ * transaction dbsp is working inside; dbsp detects that and fails loudly, but
1386
+ * the data is already whatever your statement made it. Raw savepoint control
1387
+ * (`SAVEPOINT`, `RELEASE SAVEPOINT`, `ROLLBACK TO SAVEPOINT`) can alter the
1388
+ * savepoint stack before dbsp sees the command tag; dbsp poisons the scope, but
1389
+ * it cannot make that command un-run. Manage your transaction outside dbsp's
1390
+ * calls.
1391
+ */
1392
+ executeRaw<T = unknown>(sql: string, parameters?: readonly unknown[]): Promise<T[]>;
1393
+ /**
1394
+ * Generate DDL statements from the PostgreSQL physical model.
1395
+ *
1396
+ * Uses PostgreSQL AST nodes and pgsql-deparser for consistent SQL generation.
1397
+ * Names are already physical: they were mapped once when the model was built
1398
+ * with `createPgPhysicalModel`, and this method maps none again.
1399
+ *
1400
+ * @param physical - The physical model to generate DDL from; its schema and
1401
+ * `fkAutoIndex` apply
1402
+ * @param overrideOptions - Optional rendering overrides (e.g., includeDropStatements)
1403
+ * @returns Array of DDL statements in dependency order
1404
+ */
1405
+ generateDDL(physical: PgPhysicalModel, overrideOptions?: GenerateDDLOptions): string[];
1406
+ /**
1407
+ * Execute a DDL statement directly (e.g. TRUNCATE, VACUUM, ALTER TABLE, CREATE INDEX).
1408
+ *
1409
+ * @throws Error if called on a compile-only adapter (no pool)
1410
+ * @since DDL-TABLE-001
1411
+ */
1412
+ executeDDL(sql: string): Promise<void>;
1413
+ /**
1414
+ * Whether a transaction is open on this adapter's connection.
1415
+ * This is true for dbsp-managed scopes and for borrowed pg clients whose
1416
+ * ReadyForQuery status says the caller has an open transaction.
1417
+ *
1418
+ * @since DDL-TABLE-001
1419
+ */
1420
+ get inTransaction(): boolean;
1421
+ private adapterManagedScopeIsLive;
1422
+ private shouldProtectBorrowedClientTransaction;
1423
+ /**
1424
+ * An idle ReadyForQuery status says nothing about commands another owner has
1425
+ * already queued on a PoolClient. Only a dbsp-created pinned scope both owns
1426
+ * the checked-out physical client and holds its statement lock across the
1427
+ * failed named execution and any unnamed replay.
1428
+ */
1429
+ private ownsSerializedClientForPreparedStatementReplay;
1430
+ private executeQueryProtectingOpenTransaction;
1431
+ private executeConnectionStatement;
1432
+ private executeConnectionStatementUnlocked;
1433
+ private executeConnectionStatementInSavepoint;
1434
+ private issueConnectionQuery;
1435
+ private assertNoMultiCommandRawCall;
1436
+ private assertNoTransactionControlCommand;
1437
+ private assertPrepareDidNotEndTransaction;
1438
+ /**
1439
+ * Resolve the explicit schema for a catalog read: an explicit argument, else
1440
+ * the adapter's configured schema, else `undefined` (resolve in-query). NOT a
1441
+ * hard-coded 'public' — an unresolved schema is handled by the SQL, which
1442
+ * finds the table's schema search_path-aware, in the SAME session, so a
1443
+ * non-public search_path and a pooled connection both stay correct.
1444
+ */
1445
+ private explicitSchema;
1446
+ /**
1447
+ * DDL helpers are invoked by core with declared logical names. Keep the
1448
+ * model-to-physical boundary here: core deliberately does not know about the
1449
+ * PostgreSQL physical model. Direct adapter calls without a configured model
1450
+ * remain catalog-level operations and therefore keep their supplied names.
1451
+ */
1452
+ private helperDeclaredNames;
1453
+ /**
1454
+ * Public compilation APIs receive logical model references. Do the
1455
+ * addressable inventory check at their boundary so forged/stale plans cannot
1456
+ * fall through to a coincidentally named database object. Query-local names
1457
+ * are deliberately not passed to this method.
1458
+ */
1459
+ private assertDeclaredMutationReferences;
1460
+ private assertDeclaredPlanReferences;
1461
+ private helperTableName;
1462
+ private helperColumnName;
1463
+ /**
1464
+ * List all indexes on a table by querying pg_indexes.
1465
+ *
1466
+ * @param table - Table name
1467
+ * @param schema - Schema name (defaults to the search_path-resolved schema)
1468
+ */
1469
+ listIndexes(table: string, schema?: string, options?: {
1470
+ namePattern?: string;
1471
+ }): Promise<IndexInfo[]>;
1472
+ /**
1473
+ * Check whether an index with the given name exists on a table.
1474
+ *
1475
+ * @param name - Index name
1476
+ * @param table - Table name
1477
+ * @param schema - Schema name (defaults to the search_path-resolved schema)
1478
+ */
1479
+ indexExists(name: string, table: string, schema?: string): Promise<boolean>;
1480
+ /**
1481
+ * Return the total storage size of a table in bytes (includes indexes and TOAST).
1482
+ *
1483
+ * The table name is a SQL identifier — it is double-quoted, not parameterized,
1484
+ * because PostgreSQL does not allow parameterized table names in FROM clauses.
1485
+ * With no known schema the table is left unqualified so ::regclass resolves it
1486
+ * through search_path (the same table an unqualified reference would hit).
1487
+ *
1488
+ * @param table - Table name
1489
+ * @param schema - Schema name (defaults to the search_path-resolved schema)
1490
+ */
1491
+ storageSize(table: string, schema?: string): Promise<number>;
1492
+ /**
1493
+ * Generate SQL for TRUNCATE TABLE.
1494
+ * Implements TableDDLGeneratorAdapter.generateTruncate.
1495
+ */
1496
+ generateTruncate(table: string, schemaName: string, options?: TruncateOptions): string;
1497
+ /**
1498
+ * Generate SQL for VACUUM.
1499
+ * Implements TableDDLGeneratorAdapter.generateVacuum.
1500
+ */
1501
+ generateVacuum(table: string, schemaName: string, options?: VacuumOptions): string;
1502
+ /**
1503
+ * Generate SQL for ALTER TABLE ... ALTER COLUMN.
1504
+ * Implements TableDDLGeneratorAdapter.generateAlterColumn.
1505
+ */
1506
+ generateAlterColumn(table: string, schemaName: string, column: string, options: AlterColumnOptions): string;
1507
+ /**
1508
+ * Generate SQL for CREATE INDEX.
1509
+ * Implements TableDDLGeneratorAdapter.generateCreateIndex.
1510
+ */
1511
+ generateCreateIndex(table: string, schemaName: string, options: CreateIndexOptions): string;
1512
+ /**
1513
+ * Generate SQL for DROP INDEX.
1514
+ * Implements TableDDLGeneratorAdapter.generateDropIndex.
1515
+ */
1516
+ generateDropIndex(name: string, schemaName: string, options?: DropIndexOptions): string;
1517
+ generateTableDropIndex(table: string, name: string, schemaName: string, options?: DropIndexOptions): string;
1518
+ /**
1519
+ * Validate an identifier (table name, column name, schema name).
1520
+ */
1521
+ validateIdentifier(value: string, type: string): void;
1522
+ }
1523
+ /**
1524
+ * Create a PgAdapter from a pg Pool instance.
1525
+ *
1526
+ * @param pool - pg Pool instance
1527
+ * @param options - Optional configuration
1528
+ * @returns A new PgAdapter instance
1529
+ *
1530
+ * @example
1531
+ * ```typescript
1532
+ * import { Pool } from 'pg';
1533
+ * import { createPgAdapter } from '@dbsp/adapter-pgsql';
1534
+ *
1535
+ * const pool = new Pool({ connectionString: process.env.DATABASE_URL });
1536
+ * const adapter = createPgAdapter(pool);
1537
+ *
1538
+ * // With naming convention
1539
+ * const adapter = createPgAdapter(pool, { dbCasing: 'snake_case' });
1540
+ * ```
1541
+ */
1542
+ declare function createPgAdapter<DB = unknown>(pool: Pool, options?: PgPoolAdapterOptions): PgAdapter<DB>;
1543
+ declare function createPgAdapter<DB = unknown>(client: PoolClient, options: PgBorrowedClientAdapterOptions): PgAdapter<DB>;
1544
+ /**
1545
+ * Creates a connectionless PgAdapter for SQL generation without a database connection.
1546
+ *
1547
+ * All compilation methods (compile, compileInsert, etc.), createDump(), and generateDDL()
1548
+ * work normally. The adapter has the full PgAdapter surface; database operations refuse
1549
+ * at runtime until it is constructed with a connection via createPgAdapter(pool).
1550
+ *
1551
+ * @example
1552
+ * ```typescript
1553
+ * import { createPgCompileOnlyAdapter } from '@dbsp/adapter-pgsql';
1554
+ * import { createOrm } from '@dbsp/core';
1555
+ *
1556
+ * const adapter = createPgCompileOnlyAdapter();
1557
+ * const orm = createOrm({ model, adapter });
1558
+ * const dump = await orm.select('users').dump();
1559
+ * console.log(dump.sql);
1560
+ * ```
1561
+ */
1562
+ declare function createPgCompileOnlyAdapter<DB = unknown>(options?: PgCompileOnlyAdapterOptions): PgAdapter<DB>;
1563
+
1564
+ interface CheckConstraintCanonicalizationWarning {
1565
+ readonly table: string;
1566
+ readonly kind: 'check_constraint';
1567
+ readonly name: string;
1568
+ readonly constraint: string;
1569
+ readonly message: string;
1570
+ readonly cause: unknown;
1571
+ }
1572
+ interface ColumnDefaultCanonicalizationWarning {
1573
+ readonly table: string;
1574
+ readonly kind: 'column_default';
1575
+ readonly name: string;
1576
+ readonly message: string;
1577
+ readonly cause: unknown;
1578
+ readonly outcome?: 'unavailable' | 'rejected' | 'refused';
1579
+ /** Whether this warning represents a raw fallback or absent counterpart. */
1580
+ readonly comparison: 'raw' | 'unpaired';
1581
+ /** Present when the default could not be paired with the opposite model side. */
1582
+ readonly side?: 'desired' | 'database';
1583
+ }
1584
+ interface IndexPredicateCanonicalizationWarning {
1585
+ readonly table: string;
1586
+ readonly kind: 'index_predicate';
1587
+ readonly name: string;
1588
+ readonly message: string;
1589
+ readonly cause: unknown;
1590
+ readonly outcome: 'unavailable' | 'rejected' | 'refused';
1591
+ /** Predicate fallback always compares both complete models raw. */
1592
+ readonly comparison: 'raw';
1593
+ readonly side?: 'desired' | 'database';
1594
+ }
1595
+ type ExpressionCanonicalizationWarning = CheckConstraintCanonicalizationWarning | ColumnDefaultCanonicalizationWarning | IndexPredicateCanonicalizationWarning;
1596
+ interface CanonicalizeCheckConstraintsOptions {
1597
+ /** Database schema that owns the target tables and target-scoped enum types. */
1598
+ readonly schemaName?: string;
1599
+ /** Called when PostgreSQL CHECK canonicalisation fails and raw comparison is used. */
1600
+ readonly onWarning?: (warning: CheckConstraintCanonicalizationWarning) => void;
1601
+ /** Throw instead of falling back to raw comparison when canonicalisation fails. */
1602
+ readonly requireCanonicalization?: boolean;
1603
+ /** Skip CHECK scratch work when the caller's dialect does not support CHECK DDL. */
1604
+ readonly canonicalizeCheckConstraints?: boolean;
1605
+ /** Capabilities used to generate the migration this scope is staging for. */
1606
+ readonly dialectCapabilities?: DialectCapabilities;
1607
+ }
1608
+ /** The comparison result for one CHECK owned by an application assertion. */
1609
+ type OwnedCheckState = 'healthy' | 'absent' | 'unrenderable' | 'definition-mismatch' | 'unvalidated';
1610
+ declare class CheckConstraintCanonicalizationError extends Error {
1611
+ readonly table: string;
1612
+ readonly constraints: readonly string[];
1613
+ readonly cause: unknown;
1614
+ constructor(table: string, constraints: readonly string[], cause: unknown);
1615
+ }
1616
+ declare class ColumnDefaultCanonicalizationError extends Error {
1617
+ readonly table: string;
1618
+ readonly column: string;
1619
+ readonly cause: unknown;
1620
+ constructor(table: string, column: string, cause: unknown);
1621
+ }
1622
+ /**
1623
+ * Canonicalise PostgreSQL CHECK constraint expressions in a desired model.
1624
+ */
1625
+ declare function canonicalizeCheckConstraints(adapter: PgRollbackOnlyScope, desired: ModelIR, dbModel: ModelIR, options?: CanonicalizeCheckConstraintsOptions): Promise<ModelIR>;
1626
+
1627
+ interface ComparePgDatabaseSchemaOptions$1 extends CompareSchemataOptions$1, SchemaScopeOptions {
1628
+ /**
1629
+ * Whether to canonicalise PostgreSQL CHECK constraint expressions, column defaults, and predicates on column-keyed
1630
+ * partial indexes before comparing. Defaults to `true`. Expression-keyed
1631
+ * partial-index predicates are reported as unavailable. Set to `false` only for compatibility with
1632
+ * legacy raw-string live diffs.
1633
+ *
1634
+ * Live canonicalisation creates temporary scratch tables inside an adapter
1635
+ * scratch scope whose successful cleanup is rollback. The database role needs
1636
+ * permission to create temporary tables and use the scratch column types. If
1637
+ * PostgreSQL refuses that scratch DDL, non-strict mode warns and falls back to
1638
+ * best-effort raw string comparison for the affected expression surfaces.
1639
+ */
1640
+ readonly canonicalizeExpressions?: boolean;
1641
+ /**
1642
+ * Receives live expression canonicalisation warnings. Defaults to the core logger.
1643
+ */
1644
+ readonly onWarning?: (message: string) => void;
1645
+ /** Receives the identity-bearing canonicalisation warning before its string form. */
1646
+ readonly onExpressionCanonicalizationWarning?: (warning: ExpressionCanonicalizationWarning) => void;
1647
+ /**
1648
+ * Diff that the caller just applied before this live re-diff. Used only when
1649
+ * expression surfaces are compared by raw text to fail loudly if the exact same
1650
+ * expression-surface drift appears again after re-introspection.
1651
+ */
1652
+ readonly previouslyAppliedDiff?: SchemaDiff;
1653
+ /** Internal physical-to-authored sequence provenance for legacy-name refusal. */
1654
+ readonly declaredSequenceNames?: ReadonlyMap<string, string>;
1655
+ }
1656
+ /**
1657
+ * Compare the declared shape of an adopted table against its live PostgreSQL
1658
+ * counterpart. The supplied model is deliberately declaration-scoped: the whole
1659
+ * schema is introspected, so an adopted table's foreign keys to any table are
1660
+ * seen, and the comparison then keeps only the declared physical tables (with
1661
+ * the relations between them), so drift on other tables is not reported.
1662
+ */
1663
+ interface ComparePgDeclaredAdoptionSchemaInput {
1664
+ readonly executor: PgAdoptionComparisonExecutor;
1665
+ readonly model: ModelIR;
1666
+ readonly schema: string;
1667
+ readonly dbCasing: DbCasing;
1668
+ /**
1669
+ * Already-physicalized naming authority for `model`. Callers that own a
1670
+ * snapshot pass it here so comparison never re-applies logical naming.
1671
+ */
1672
+ readonly physical?: PgPhysicalModel;
1673
+ /** Physical [table, index] JSON keys whose drop drift is unmanaged. */
1674
+ readonly externalIndexMask?: ReadonlySet<string>;
1675
+ /** Physical [table, surface] JSON keys maintained by application assertions. */
1676
+ readonly ownershipMask?: PgsqlDeclaredAdoptionOwnershipMask;
1677
+ /** Internal physical-to-authored sequence provenance for legacy-name refusal. */
1678
+ readonly declaredSequenceNames?: ReadonlyMap<string, string>;
1679
+ }
1680
+ /** Internal converge-only declaration mask; public database comparison is unchanged. */
1681
+ interface PgsqlDeclaredAdoptionOwnershipMask {
1682
+ readonly checks: ReadonlySet<string>;
1683
+ readonly columnTypes: ReadonlySet<string>;
1684
+ readonly indexes: ReadonlySet<string>;
1685
+ }
1686
+ /** Minimal pool surface retained so callers can keep their executor opaque. */
1687
+ interface PgAdoptionComparisonExecutor {
1688
+ query(sql: string, parameters?: readonly unknown[]): Promise<{
1689
+ readonly rows: readonly Record<string, unknown>[];
1690
+ }>;
1691
+ }
1692
+ /** Builds the declaration-scoped model used by every adoption shape check. */
1693
+ declare function modelForDeclaredAdoption(table: TableIR): ModelIR;
1694
+ /**
1695
+ * PostgreSQL-aware comparison used to admit a declared table adoption. A
1696
+ * claimed session remains pinned by constructing a borrowed, transaction-aware
1697
+ * adapter from that exact executor.
1698
+ */
1699
+ declare function comparePgDeclaredAdoptionSchema(input: ComparePgDeclaredAdoptionSchemaInput): Promise<SchemaDiff>;
1700
+ type NonConvergentSchemaDiffSurface = {
1701
+ readonly kind: 'check_constraint';
1702
+ readonly table: string;
1703
+ readonly constraint: string;
1704
+ } | {
1705
+ readonly kind: 'column_default';
1706
+ readonly table: string;
1707
+ readonly column: string;
1708
+ };
1709
+ declare class NonConvergentSchemaDiffError extends Error {
1710
+ readonly surface: NonConvergentSchemaDiffSurface;
1711
+ readonly desiredExpressionHash: string;
1712
+ readonly databaseExpressionHash: string;
1713
+ constructor(surface: NonConvergentSchemaDiffSurface, desiredExpressionHash: string, databaseExpressionHash: string);
1714
+ }
1715
+ /** An enum value this diff adds, reported as a candidate cause — never asserted. */
1716
+ interface AddedEnumValue {
1717
+ readonly enumName: string;
1718
+ readonly value: string;
1719
+ }
1720
+ declare class CheckConstraintNewEnumValueError extends Error {
1721
+ readonly table: string;
1722
+ readonly constraint: string;
1723
+ readonly addedEnumValues: readonly AddedEnumValue[];
1724
+ constructor(table: string, constraint: string, addedEnumValues: readonly AddedEnumValue[]);
1725
+ }
1726
+ /** A raw partial-index predicate and added enum values cannot share one migration. */
1727
+ declare class PartialIndexPredicateNewEnumValueError extends Error {
1728
+ readonly addedEnumValues: readonly AddedEnumValue[];
1729
+ constructor(addedEnumValues: readonly AddedEnumValue[]);
1730
+ }
1731
+ /** #454: Predicate canonicalization is not implemented for indexes with expression keys. */
1732
+ declare class ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError extends Error {
1733
+ readonly predicates: readonly {
1734
+ readonly side: 'desired' | 'database';
1735
+ readonly table: string;
1736
+ readonly index: string;
1737
+ }[];
1738
+ constructor(predicates: readonly {
1739
+ readonly side: 'desired' | 'database';
1740
+ readonly table: string;
1741
+ readonly index: string;
1742
+ }[]);
1743
+ }
1744
+ /**
1745
+ * A raw partial-index predicate cannot be proven to converge after PostgreSQL
1746
+ * deparses it, so emitting its CREATE statement is unsafe.
1747
+ */
1748
+ declare class RawIndexPredicateFallbackError extends Error {
1749
+ constructor(cause?: unknown);
1750
+ }
1751
+ declare class IndexPredicateCanonicalizationError extends Error {
1752
+ readonly rejectedPredicates: readonly {
1753
+ readonly side: 'desired' | 'database';
1754
+ readonly table: string;
1755
+ readonly index: string;
1756
+ readonly reason?: unknown;
1757
+ }[];
1758
+ /**
1759
+ * Enum values added by this migration are diagnostic candidates only. They
1760
+ * are collected from the schema diff, never matched to a rejected index.
1761
+ */
1762
+ readonly addedEnumValues: readonly AddedEnumValue[];
1763
+ constructor(rejectedPredicates: readonly {
1764
+ readonly side: 'desired' | 'database';
1765
+ readonly table: string;
1766
+ readonly index: string;
1767
+ readonly reason?: unknown;
1768
+ }[],
1769
+ /**
1770
+ * Enum values added by this migration are diagnostic candidates only. They
1771
+ * are collected from the schema diff, never matched to a rejected index.
1772
+ */
1773
+ addedEnumValues?: readonly AddedEnumValue[]);
1774
+ }
1775
+ /**
1776
+ * Live PostgreSQL schema diff: introspect, canonicalise desired CHECK
1777
+ * constraint expressions, column defaults, and predicates on column-keyed
1778
+ * partial indexes through PostgreSQL, then call the pure synchronous
1779
+ * schema comparator.
1780
+ *
1781
+ * If CHECK canonicalisation falls back while the same diff adds a plausibly
1782
+ * referenced enum value, the diff is refused. dbsp currently applies each
1783
+ * migration in one transaction, and PostgreSQL forbids using a newly added enum
1784
+ * value in that same transaction; emitting the CHECK would produce a migration
1785
+ * that cannot run. Apply the enum addition by itself first, then add or update
1786
+ * the CHECK constraint in a later migration.
1787
+ *
1788
+ * Index expressions are intentionally not canonicalised here; partial-index
1789
+ * predicates on expression-keyed indexes are reported as unavailable and are
1790
+ * therefore rejected by strict mode. They need their own key-shape substrate.
1791
+ */
1792
+ declare function comparePgDatabaseSchema$1(adapter: PgAdapter, desired: ModelIR, options?: ComparePgDatabaseSchemaOptions$1): Promise<SchemaDiff>;
1793
+ declare function assertNoRepeatedExpressionSurfaceDrift(previouslyAppliedDiff: SchemaDiff, currentDiff: SchemaDiff, rawExpressionSurfaces?: ReadonlySet<string>): void;
1794
+
1795
+ /**
1796
+ * Migration SQL Generator (DDL-PROV Block 1)
1797
+ *
1798
+ * Generates ordered SQL statements from a SchemaDiff.
1799
+ * Statements are topologically sorted: DROP constraints → DROP objects → CREATE objects → ADD constraints.
1800
+ *
1801
+ * @module migration-sql
1802
+ */
1803
+
1804
+ interface MigrationSQLOptions$1 {
1805
+ /**
1806
+ * Schema namespace (default: none — unqualified).
1807
+ * Required when emitted migration SQL would otherwise mix non-default
1808
+ * target-scoped custom types/enums with unqualified table SQL.
1809
+ */
1810
+ readonly schemaName?: string;
1811
+ /** Whether to include destructive changes (drops) */
1812
+ readonly includeDestructive?: boolean;
1813
+ /** Automatically create indexes on FK columns for new tables (default: true) */
1814
+ readonly fkAutoIndex?: boolean;
1815
+ /**
1816
+ * Declared model whose FK-index coverage controls automatic index emission.
1817
+ * This lets callers mask generated DDL surfaces without changing the
1818
+ * declaration-level decision to emit an automatic FK index.
1819
+ */
1820
+ readonly fkAutoIndexCoverage?: ModelIR;
1821
+ /** Dialect capabilities — unsupported index features throw during migration SQL generation */
1822
+ readonly dialectCapabilities?: DialectCapabilities;
1823
+ }
1824
+ /**
1825
+ * Generate ordered SQL statements from a SchemaDiff.
1826
+ *
1827
+ * Topological order:
1828
+ * 0. DROP FK/CHECK constraints (must drop before referenced tables)
1829
+ * 1. DROP indexes
1830
+ * 2. DROP columns
1831
+ * 3. DROP primary keys
1832
+ * 4. DROP tables, DROP ENUMs
1833
+ * 5. CREATE ENUMs (must exist before tables that use them)
1834
+ * 6. CREATE tables
1835
+ * 7. ADD columns
1836
+ * 8. ALTER columns (type, nullable, default)
1837
+ * 9. ADD primary keys / column UNIQUE constraints
1838
+ * 10. ADD FK constraints (must add after referenced tables exist)
1839
+ * 11. ALTER FK (drop + re-add)
1840
+ * 12. CREATE indexes
1841
+ * 13. ADD CHECK constraints
1842
+ * 14. ALTER ENUM ADD VALUE (must be last — has transaction visibility caveats in PG)
1843
+ * 15. COMMENT ON TABLE / COLUMN (very last)
1844
+ */
1845
+ declare function generateMigrationSQL$1(diff: SchemaDiff, options?: MigrationSQLOptions$1): readonly string[];
1846
+ /**
1847
+ * Generate ordered DOWN SQL statements from a SchemaDiff.
1848
+ *
1849
+ * Reverses the topological order used in UP migrations:
1850
+ * phases run in descending order (18, 17, ..., 0).
1851
+ *
1852
+ * Irreversible drops with missing or unmanaged metadata produce SQL WARNING
1853
+ * comments instead of reconstructing the dropped object.
1854
+ */
1855
+ declare function generateDownSQL$1(diff: SchemaDiff, options?: MigrationSQLOptions$1): readonly string[];
1856
+
1857
+ /** Public physical-model DDL facade. The rendering engines remain ModelIR-only. */
1858
+
1859
+ interface GenerateDDLOptions extends Omit<GenerateDDLOptions$1, 'schemaName' | 'naming' | 'fkAutoIndex'> {
1860
+ }
1861
+ interface CompareSchemataOptions extends Omit<CompareSchemataOptions$1, 'schema' | 'dbCasing' | 'declaredSequenceNames'> {
1862
+ }
1863
+ interface ComparePgDatabaseSchemaOptions extends Omit<ComparePgDatabaseSchemaOptions$1, 'schema' | 'dbCasing' | 'declaredSequenceNames'> {
1864
+ }
1865
+ interface MigrationSQLOptions extends Omit<MigrationSQLOptions$1, 'schemaName' | 'fkAutoIndex' | 'fkAutoIndexCoverage'> {
1866
+ }
1867
+ interface PgSchemaDiff extends SchemaDiff {
1868
+ readonly physical: Pick<PgPhysicalModel, 'schema' | 'fkAutoIndex'>;
1869
+ }
1870
+ declare function generateDDL(physical: PgPhysicalModel, options?: GenerateDDLOptions): string[];
1871
+ declare function compareSchemata(desired: PgPhysicalModel, database: PgPhysicalModel, options?: CompareSchemataOptions): PgSchemaDiff;
1872
+ declare function comparePgDatabaseSchema(adapter: PgAdapter, desired: PgPhysicalModel, options?: ComparePgDatabaseSchemaOptions): Promise<PgSchemaDiff>;
1873
+ declare function generateMigrationSQL(diff: PgSchemaDiff, options?: MigrationSQLOptions): readonly string[];
1874
+ declare function generateDownSQL(diff: PgSchemaDiff, options?: MigrationSQLOptions): readonly string[];
1875
+
1876
+ /**
1877
+ * Query-local relation authority.
1878
+ *
1879
+ * A scope is built as relations enter a query. It deliberately contains the
1880
+ * emitted identifiers, rather than a transformation policy: aliases, CTEs and VALUES
1881
+ * ranges are local SQL vocabulary and must retain their spelling verbatim.
1882
+ */
1883
+
1884
+ type RelationBindingKind = 'declared-table' | 'cte-bind' | 'join-alias' | 'batch-values' | 'generated';
1885
+ /** A local projected output, indexed both by emitted label and logical key. */
1886
+ type RelationBindingOutput = OutputDescriptor & {
1887
+ readonly outputKey: SqlIdentifier;
1888
+ readonly logicalKey: string;
1889
+ };
1890
+ type RelationBinding = {
1891
+ /** The exact identifier emitted as the relation qualifier. */
1892
+ readonly qualifier: SqlIdentifier;
1893
+ readonly kind: RelationBindingKind;
1894
+ /** Present only for a declared physical relation. */
1895
+ readonly logicalTable?: string;
1896
+ /** Present for local relations whose output list is known. */
1897
+ readonly outputs?: ReadonlyMap<SqlIdentifier, RelationBindingOutput>;
1898
+ /** Built together with `outputs`; callers never scan outputs by logical key. */
1899
+ readonly outputsByLogicalKey?: ReadonlyMap<string, RelationBindingOutput>;
1900
+ };
1901
+ type QueryScope = {
1902
+ readonly bindings: ReadonlyMap<string, RelationBinding>;
1903
+ };
1904
+ /**
1905
+ * The pre-lot-3 carrier remains only at compiler boundaries. It is converted
1906
+ * to a QueryScope there; converted lookup functions never accept it.
1907
+ */
1908
+ type BindingNameRegistry = ReadonlySet<string>;
1909
+
1910
+ declare const projectionEnvelopeBrand: unique symbol;
1911
+ type ProjectionEnvelope<T = unknown> = {
1912
+ readonly [projectionEnvelopeBrand]: true;
1913
+ readonly sql: string;
1914
+ readonly parameters: readonly unknown[];
1915
+ readonly ast?: Node;
1916
+ readonly projection: ProjectionState;
1917
+ readonly hydrationPlan?: PlanReport;
1918
+ readonly __resultType?: T;
1919
+ };
1920
+ type ProjectionState = {
1921
+ readonly kind: 'known';
1922
+ readonly outputs: ReadonlyMap<string, OutputProjection>;
1923
+ } | {
1924
+ readonly kind: 'dropped';
1925
+ readonly reason: ProjectionDropReason;
1926
+ readonly hadConvertibleSource: boolean;
1927
+ /** The left positional branch still determines PostgreSQL result labels. */
1928
+ readonly outputKeyMap?: ReadonlyMap<string, string>;
1929
+ };
1930
+ type OutputProjection = OutputDescriptor & {
1931
+ readonly logicalKey: string;
1932
+ };
1933
+
1934
+ type ProjectionDropReason = 'set-operation-positional-merge' | 'raw-recursive-cte-positional-merge' | 'unknown-raw-sql' | 'unsupported-source';
1935
+
1936
+ /** Resolves columns through the relation bindings visible in a query scope. */
1937
+
1938
+ /** Compatibility input accepted only while callers move to QueryScope. */
1939
+ type RelationTargetProjectionRegistry = ReadonlyMap<string, ProjectionEnvelope>;
1940
+ /** A query-scope binding from an emitted SQL alias to the relation it exposes. */
1941
+ type AliasColumnAuthority = ReadonlyMap<string, ResolvedRelationTarget>;
1942
+ type ResolvedRelationTarget = {
1943
+ readonly target: SqlIdentifier;
1944
+ readonly cteName?: SqlIdentifier;
1945
+ readonly logicalTable?: string;
1946
+ readonly outputs?: ReadonlyMap<string, RelationBindingOutput>;
1947
+ /** Built when the local binding enters the scope; no reference path scans outputs. */
1948
+ readonly outputsByLogicalKey?: ReadonlyMap<string, RelationBindingOutput>;
1949
+ };
1950
+
1951
+ /** Built-in include strategies, shared by the runtime registry and public types. */
1952
+ declare const INCLUDE_STRATEGIES: readonly ["join", "lateral", "json_agg", "cte"];
1953
+ /** The four strategies this adapter implements handlers for, distinct from @dbsp/types' five-member IncludeStrategy, which includes auto. */
1954
+ type IncludeHandlerStrategy = (typeof INCLUDE_STRATEGIES)[number];
1955
+ /**
1956
+ * Immutable context passed to all handlers during compilation.
1957
+ */
1958
+ interface CompilerContext {
1959
+ readonly compileCaseCondition?: (intent: _dbsp_types.WhereIntent, ctx: CompilerContext, state: CompilerState) => Node;
1960
+ readonly compileSubqueryCondition?: (intent: _dbsp_types.WhereIntent, ctx: CompilerContext, state: CompilerState) => Node;
1961
+ readonly directRootWhere?: boolean;
1962
+ readonly position?: ConditionPosition;
1963
+ readonly createWhereDispatcher?: () => WhereDispatcher;
1964
+ /** Addressed authority for model-backed identifiers. */
1965
+ readonly declaredNames?: DeclaredNameResolver;
1966
+ /** Casing policy applied when a model is unavailable. */
1967
+ readonly dbCasing?: DbCasing;
1968
+ /** Schema name for table qualification (optional) */
1969
+ readonly schema?: string;
1970
+ /** Dialect capabilities for adapter-layer SQL surface gates */
1971
+ readonly dialectCapabilities?: DialectCapabilities;
1972
+ /** Root table name for the query */
1973
+ readonly rootTable: string;
1974
+ /** Current table alias (for JOINs) */
1975
+ readonly currentAlias?: string;
1976
+ /** Final relation path/name → SQL join alias map for relation-aware expression contexts */
1977
+ readonly aliases?: ReadonlyMap<string, string>;
1978
+ /** Maximum recursive depth (default: 100) */
1979
+ readonly maxRecursiveDepth: number;
1980
+ /** Optional callback for raw SQL audit trail */
1981
+ readonly onRawSQL?: (sql: string) => void;
1982
+ /** Default primary key column name for convention fallbacks (default: 'id') */
1983
+ readonly defaultPkColumnName?: string;
1984
+ /** Convention for deriving FK column names: (tableName, pkName) => fkColumnName */
1985
+ readonly deriveFkColumnName?: FkColumnDerivation;
1986
+ /** Alias of the outer (parent) query — used for FieldRef scope:'outer' resolution in EXISTS subqueries */
1987
+ readonly outerAlias?: string;
1988
+ /** Query-local CTE/binding names that must not be schema-qualified. */
1989
+ readonly bindingNames?: BindingNameRegistry;
1990
+ /** Query-local relation authority; bindings and their outputs never hit the model resolver. */
1991
+ readonly scope?: QueryScope;
1992
+ /** Enclosing query ranges, nearest query first; excludes the current query. */
1993
+ readonly enclosingRanges?: readonly (readonly RelationBinding[])[];
1994
+ /** Ranges emitted by the current query, separate from available CTE bindings. */
1995
+ readonly queryRanges?: readonly RelationBinding[];
1996
+ /**
1997
+ * The binding that owns unqualified expression columns. New callers provide
1998
+ * this directly; the string fields above remain only at pre-lot-4 compiler
1999
+ * boundaries while they are converted to bindings.
2000
+ */
2001
+ readonly currentBinding?: RelationBinding;
2002
+ /** Known projections for visible CTE/binding relation targets. */
2003
+ readonly relationTargetProjections?: RelationTargetProjectionRegistry;
2004
+ /** Lexically visible SQL aliases that expose a known CTE projection. */
2005
+ readonly aliasColumnAuthorities?: AliasColumnAuthority;
2006
+ /**
2007
+ * Optional callback to compile a QueryIntent into an AST Node (SubLink subselect).
2008
+ * Set by PlanCompiler when compiling selectCustomExpression — enables SubqueryExpressionIntent
2009
+ * to embed a fully compiled sub-SELECT into the parent SELECT column list.
2010
+ *
2011
+ * @param query - The inner QueryIntent to compile
2012
+ * @param paramOffset - Current outer paramIndex; inner $N are renumbered by this offset
2013
+ * @returns The compiled SelectStmt AST node and the inner parameters
2014
+ */
2015
+ readonly resolvedConditions?: ReadonlyMap<_dbsp_types.WhereIntent, _dbsp_types.ResolvedCondition>;
2016
+ readonly compileSubquery?: (query: _dbsp_types.QueryIntent, paramOffset: number, parent?: CompilerContext, expression?: _dbsp_types.ExpressionIntent) => {
2017
+ ast: Node;
2018
+ parameters: readonly unknown[];
2019
+ };
2020
+ /**
2021
+ * Optional recursive compiler for NQL-origin SELECT expression values nested
2022
+ * inside handler arguments, such as coalesce(upper(name), :fallback) or
2023
+ * (price + :a) * :b.
2024
+ */
2025
+ readonly compileNqlSelectExpression?: (value: unknown, ctx: CompilerContext, state: CompilerState) => Node;
2026
+ /**
2027
+ * Optional callback to compile a custom fn() FILTER (WHERE ...) condition.
2028
+ * Set by PlanCompiler to keep WHERE-dispatcher dependencies out of expression
2029
+ * handlers while still applying FILTER in every expression position.
2030
+ */
2031
+ readonly compileCustomFnFilter?: (filterIntent: _dbsp_types.WhereIntent, ctx: CompilerContext, state: CompilerState) => Node | undefined;
2032
+ /**
2033
+ * Optional ModelIR for type-aware parameter casting.
2034
+ * When provided, WHERE comparisons emit `$N::type` to eliminate
2035
+ * PostgreSQL type inference ambiguity for nullable columns.
2036
+ */
2037
+ readonly model?: ModelIR;
2038
+ }
2039
+ /**
2040
+ * The expression boundary deliberately excludes the legacy transform policy.
2041
+ * Expressions receive addressed declared names and query scope/bindings instead.
2042
+ */
2043
+ type ExpressionCompilerContext = Omit<CompilerContext, never>;
2044
+ /**
2045
+ * Mutable state maintained during compilation.
2046
+ */
2047
+ interface CompilerState {
2048
+ /** Addressed metadata shared across contexts for this compilation. */
2049
+ addressedColumns?: Map<string, Map<string, _dbsp_types.ColumnIR | undefined>>;
2050
+ /** Collected parameters in order */
2051
+ parameters: unknown[];
2052
+ /** Current parameter index (1-based for PostgreSQL) */
2053
+ paramIndex: number;
2054
+ /** Registered CTEs for the query */
2055
+ ctes: Map<string, Node>;
2056
+ /** Table aliases in use */
2057
+ aliases: Map<string, string>;
2058
+ /** JOIN clauses accumulated */
2059
+ joins: Node[];
2060
+ }
2061
+ /**
2062
+ * Base decision interface matching core's PlanDecision structure.
2063
+ */
2064
+ interface Decision {
2065
+ readonly resolvedInclude?: _dbsp_types.ResolvedIncludeNode;
2066
+ readonly type: string;
2067
+ readonly table?: string;
2068
+ readonly column?: string;
2069
+ readonly alias?: string;
2070
+ readonly operator?: string;
2071
+ readonly value?: unknown;
2072
+ readonly paramIndex?: number;
2073
+ readonly dataType?: string;
2074
+ readonly direction?: 'ASC' | 'DESC';
2075
+ readonly nulls?: 'FIRST' | 'LAST';
2076
+ readonly joinType?: 'inner' | 'left';
2077
+ readonly sourceColumn?: ColumnListInput;
2078
+ readonly targetColumn?: ColumnListInput;
2079
+ readonly targetTable?: string;
2080
+ readonly function?: string;
2081
+ /** Apply DISTINCT to a SELECT-list aggregate (e.g. COUNT(DISTINCT col)). */
2082
+ readonly distinct?: boolean;
2083
+ readonly args?: readonly unknown[];
2084
+ readonly conditions?: readonly Decision[];
2085
+ readonly columns?: readonly string[];
2086
+ /** An include explicitly selected zero fields, distinct from legacy empty columns. */
2087
+ readonly emptyProjection?: boolean;
2088
+ /** Original include select form, retained for strategy validation. */
2089
+ readonly includeSelectForm?: string;
2090
+ readonly values?: readonly unknown[];
2091
+ readonly set?: readonly {
2092
+ column: string;
2093
+ value: unknown;
2094
+ }[];
2095
+ readonly limit?: number | ParamIntent | {
2096
+ paramIndex: number;
2097
+ };
2098
+ readonly offset?: number | ParamIntent | {
2099
+ paramIndex: number;
2100
+ };
2101
+ readonly strategy?: IncludeHandlerStrategy;
2102
+ readonly relation?: string;
2103
+ readonly relationName?: string;
2104
+ readonly relationPath?: string;
2105
+ readonly hydrationPrefix?: string;
2106
+ readonly include?: readonly Decision[];
2107
+ readonly relationType?: 'belongsTo' | 'hasMany' | 'hasOne';
2108
+ readonly foreignKey?: ColumnListInput;
2109
+ readonly parentKey?: ColumnListInput;
2110
+ readonly includeOrderBy?: readonly _dbsp_types.IncludeOrderByIntent[];
2111
+ readonly orderByFallback?: boolean;
2112
+ readonly children?: readonly Decision[];
2113
+ readonly partition?: readonly string[];
2114
+ readonly orderBy?: readonly {
2115
+ column: string;
2116
+ direction?: 'ASC' | 'DESC';
2117
+ }[] | readonly JsonAggOrderByEntry[];
2118
+ readonly frame?: string;
2119
+ readonly recursiveInclude?: _dbsp_types.IncludeRecursiveOptions;
2120
+ readonly maxDepth?: number;
2121
+ readonly pathColumn?: string;
2122
+ readonly cycleDetection?: boolean;
2123
+ readonly selectColumn?: string;
2124
+ readonly aggregate?: string;
2125
+ /**
2126
+ * Apply DISTINCT to a scalar subquery's aggregate (e.g. AVG(DISTINCT price)).
2127
+ * Deliberately NOT named `distinct` — `assertNoDroppedDecisionModifiers`
2128
+ * (subquery-emission.ts) treats a top-level `distinct === true` on ANY
2129
+ * subquery decision as an unsupported query-level DISTINCT modifier and
2130
+ * throws. This field is scoped to the aggregate projection only, so it
2131
+ * must not collide with that generic guard.
2132
+ */
2133
+ readonly aggregateDistinct?: boolean;
2134
+ readonly subqueryOperator?: string;
2135
+ readonly traversal?: string;
2136
+ readonly traversals?: readonly {
2137
+ traversal: string;
2138
+ targetColumn?: string;
2139
+ }[];
2140
+ readonly isRecursive?: boolean;
2141
+ readonly fkColumn?: string;
2142
+ readonly pkColumn?: string;
2143
+ readonly expandRelation?: string;
2144
+ readonly relationColumns?: readonly string[];
2145
+ readonly columnAliases?: Readonly<Record<string, string>>;
2146
+ readonly defaultRelationColumnLabels?: Readonly<Record<string, boolean>>;
2147
+ readonly payloadShape?: _dbsp_types.IncludePayloadShape;
2148
+ readonly jsonPath?: readonly unknown[];
2149
+ readonly jsonMode?: 'json' | 'text';
2150
+ readonly _compiledFilterWhere?: _pgsql_types.Node;
2151
+ readonly filterWhere?: _pgsql_types.Node;
2152
+ readonly expressionIntent?: unknown;
2153
+ readonly escape?: string;
2154
+ /**
2155
+ * Provenance: the ORIGINAL QueryIntent before lowering.
2156
+ * Set by every lowering site (convertIn, convertSubquery, normalizeToDecision,
2157
+ * dispatchWhere, mapInSubqueryCondition) so that `buildPredicateSubquerySelect`
2158
+ * (subquery-emission.ts) can validate the true caller intent rather than the
2159
+ * stripped-down lowered decision fields.
2160
+ *
2161
+ * Required for IN / scalar / inSubquery / notInSubquery decisions.
2162
+ * Optional on other decision types.
2163
+ */
2164
+ readonly subqueryIntent?: _dbsp_types.QueryIntent;
2165
+ }
2166
+ /**
2167
+ * Handler for WHERE clause conditions.
2168
+ * Transforms condition decisions into PostgreSQL AST expressions.
2169
+ */
2170
+ interface WhereHandler {
2171
+ /** Operator(s) this handler supports */
2172
+ readonly operators: readonly string[];
2173
+ /**
2174
+ * Compile a WHERE condition to AST.
2175
+ * @param decision The condition decision
2176
+ * @param ctx Immutable compiler context
2177
+ * @param state Mutable compiler state
2178
+ * @param dispatch Callback to compile nested conditions
2179
+ * @returns PostgreSQL AST node for the condition
2180
+ */
2181
+ compile(decision: Decision, ctx: CompilerContext, state: CompilerState, dispatch: WhereDispatcher): Node;
2182
+ }
2183
+ /**
2184
+ * Dispatcher for recursive WHERE compilation.
2185
+ * The same function object may be passed to every level of a recursive compilation, so it is an opaque callback.
2186
+ * Handlers must not use its identity to distinguish frames or carry frame-local state.
2187
+ */
2188
+ type WhereDispatcher = (decision: Decision, ctx: CompilerContext, state: CompilerState) => Node;
2189
+ /**
2190
+ * Handler for SELECT expressions.
2191
+ * Transforms expression decisions into PostgreSQL AST nodes.
2192
+ */
2193
+ interface ExpressionHandler {
2194
+ /** Expression type(s) this handler supports */
2195
+ readonly types: readonly string[];
2196
+ /**
2197
+ * Safe to use when a function name comes from NQL text.
2198
+ *
2199
+ * Raw/escape-hatch handlers must not set this. NQL-origin function names use
2200
+ * this opt-in surface only, then fall back to generic FuncCall emission.
2201
+ */
2202
+ readonly nqlSafe?: boolean;
2203
+ /**
2204
+ * Compile an expression to AST.
2205
+ * @param decision The expression decision
2206
+ * @param ctx Immutable compiler context
2207
+ * @param state Mutable compiler state
2208
+ * @returns PostgreSQL AST node for the expression
2209
+ */
2210
+ compile(decision: Decision, ctx: ExpressionCompilerContext, state: CompilerState): Node;
2211
+ }
2212
+ /**
2213
+ * Handler for include/relation strategies.
2214
+ * Transforms include decisions into PostgreSQL constructs (JOIN, LATERAL, json_agg, CTE).
2215
+ */
2216
+ interface IncludeHandler {
2217
+ /** Strategy this handler implements */
2218
+ readonly strategy: IncludeHandlerStrategy;
2219
+ /**
2220
+ * Compile an include to AST.
2221
+ * @param decision The include decision
2222
+ * @param ctx Immutable compiler context
2223
+ * @param state Mutable compiler state
2224
+ * @returns Object with modifications to apply
2225
+ */
2226
+ compile(decision: Decision, ctx: CompilerContext, state: CompilerState): IncludeResult;
2227
+ }
2228
+ /**
2229
+ * Result of include compilation.
2230
+ */
2231
+ interface IncludeResult {
2232
+ /** Additional target list items (SELECT columns) */
2233
+ targets?: Node[];
2234
+ /** JOIN to add to FROM clause */
2235
+ join?: Node;
2236
+ /** Additional JOINs for cascaded includes (e.g., flat deep nesting) */
2237
+ additionalJoins?: Node[];
2238
+ /** CTE to add to WITH clause */
2239
+ cte?: Node;
2240
+ /** Subquery for LATERAL */
2241
+ lateral?: Node;
2242
+ }
2243
+
2244
+ /** Compilation position selects the migrated root WHERE, FILTER and recursive-anchor paths; other callers retain their lowering. */
2245
+ type ConditionPosition = 'where' | 'having' | 'filter' | 'join-on' | 'recursive-anchor' | 'subquery' | 'case-when' | 'update-where' | 'delete-where' | 'upsert-guard';
2246
+
2247
+ /** The intentionally narrow query facade passed to application callbacks. */
2248
+ interface PgApplicationStepTx {
2249
+ query<Row extends Record<string, unknown> = Record<string, unknown>>(text: string, values?: readonly unknown[]): Promise<{
2250
+ readonly rows: readonly Row[];
2251
+ }>;
2252
+ }
2253
+ interface PgConvergeApplicationStepBase {
2254
+ readonly id: string;
2255
+ readonly digest: string;
2256
+ readonly scope?: 'schema';
2257
+ readonly phase: 'before-generated-ddl' | 'after-generated-ddl';
2258
+ readonly lockTimeoutMs?: number;
2259
+ readonly statementTimeoutMs?: number;
2260
+ }
2261
+ interface PgConvergeOnceStep extends PgConvergeApplicationStepBase {
2262
+ readonly kind: 'once';
2263
+ readonly apply: (tx: PgApplicationStepTx) => Promise<void> | void;
2264
+ }
2265
+ interface PgConvergeAssertOwnership {
2266
+ readonly checks?: readonly {
2267
+ readonly table: string;
2268
+ readonly name: string;
2269
+ }[];
2270
+ readonly columnTypes?: readonly {
2271
+ readonly table: string;
2272
+ readonly column: string;
2273
+ }[];
2274
+ readonly indexes?: readonly {
2275
+ readonly table: string;
2276
+ readonly name: string;
2277
+ }[];
2278
+ }
2279
+ type PgOwnedCheckState = OwnedCheckState;
2280
+ interface PgApplicationStepOwnedState {
2281
+ readonly checks: readonly {
2282
+ readonly table: string;
2283
+ readonly name: string;
2284
+ readonly physicalTable: string;
2285
+ readonly physicalName: string;
2286
+ readonly state: PgOwnedCheckState;
2287
+ }[];
2288
+ }
2289
+ interface PgConvergeAssertStep extends PgConvergeApplicationStepBase {
2290
+ readonly kind: 'assert';
2291
+ /** Declaration surfaces maintained by this assertion rather than converge. */
2292
+ readonly owns?: PgConvergeAssertOwnership;
2293
+ readonly inspect: (tx: PgApplicationStepTx, owned: PgApplicationStepOwnedState) => Promise<'healthy' | 'unhealthy'> | 'healthy' | 'unhealthy';
2294
+ readonly apply: (tx: PgApplicationStepTx, owned: PgApplicationStepOwnedState) => Promise<void> | void;
2295
+ }
2296
+ type PgConvergeApplicationStep = PgConvergeOnceStep | PgConvergeAssertStep;
2297
+
2298
+ type PgConvergeRefusal = 'invalid-options' | 'unsupported-change' | 'unmanaged-object' | 'unmanaged-parent' | 'concurrent-drift' | 'ledger-absent' | 'incompatible-ledger' | 'unsupported-server' | 'busy' | 'recovery-required' | 'database-read-only' | 'execution-refused' | 'adoption-refused' | 'application-step-changed' | 'application-step-failed' | 'initialization-refused';
2299
+ interface PgConvergeInitializationFailure {
2300
+ readonly home: LedgerHome;
2301
+ readonly code: string;
2302
+ readonly step: string;
2303
+ readonly detail: string;
2304
+ }
2305
+ type PgConvergeRefusalChange = Pick<SchemaChange, 'kind' | 'table' | 'column' | 'details'> & {
2306
+ /**
2307
+ * Present for create_index and drop_index when the index has a name: always
2308
+ * for a live index and for a logical-mode physical model, which names every
2309
+ * index; a physical-mode snapshot passes its own names through as given.
2310
+ */
2311
+ readonly index?: string;
2312
+ };
2313
+ /**
2314
+ * Unsupported-change, ledger and ownership refusals occur before converge commits
2315
+ * managed DDL. An execution refusal may follow a rolled-back transactional DDL
2316
+ * attempt, and comparison may use rollback-only scratch DDL.
2317
+ */
2318
+ declare class PgConvergeRefusalError extends Error {
2319
+ readonly refusal: PgConvergeRefusal;
2320
+ readonly changes: readonly PgConvergeRefusalChange[];
2321
+ readonly detail?: string | undefined;
2322
+ readonly runIds?: readonly string[] | undefined;
2323
+ readonly executionIds?: readonly string[] | undefined;
2324
+ readonly busyRunIds?: readonly string[] | undefined;
2325
+ readonly initialization?: PgConvergeInitializationFailure | undefined;
2326
+ constructor(refusal: PgConvergeRefusal, changes: readonly PgConvergeRefusalChange[], detail?: string | undefined, runIds?: readonly string[] | undefined, executionIds?: readonly string[] | undefined, busyRunIds?: readonly string[] | undefined, initialization?: PgConvergeInitializationFailure | undefined, options?: ErrorOptions);
2327
+ }
2328
+ type PgConvergeResult = {
2329
+ readonly kind: 'no-drift';
2330
+ readonly applied: readonly string[];
2331
+ } | {
2332
+ readonly kind: 'applied';
2333
+ readonly applied: readonly string[];
2334
+ } | {
2335
+ readonly kind: 'partially-applied';
2336
+ readonly completedStepKeys: readonly string[];
2337
+ readonly notStartedStepKeys: readonly string[];
2338
+ readonly detail: string;
2339
+ } | {
2340
+ readonly kind: 'transport-ambiguous';
2341
+ readonly detail: string;
2342
+ };
2343
+ type PgConvergePlannedStep = {
2344
+ readonly stepKey: string;
2345
+ readonly order: number;
2346
+ readonly dependencyOrder: readonly string[];
2347
+ readonly address: NonNullable<NormalizedManagedStep['address']>;
2348
+ readonly kind: SchemaChange['kind'];
2349
+ readonly table: string;
2350
+ readonly column?: string;
2351
+ readonly details: string;
2352
+ } | {
2353
+ readonly stepKey: string;
2354
+ readonly order: number;
2355
+ readonly dependencyOrder: readonly string[];
2356
+ readonly address: NonNullable<NormalizedManagedStep['address']>;
2357
+ readonly kind: 'adopt_table' | 'adopt_sequence';
2358
+ } | {
2359
+ readonly kind: 'application-step';
2360
+ readonly id: string;
2361
+ readonly step: 'once';
2362
+ readonly inspected?: never;
2363
+ readonly stepKey?: never;
2364
+ readonly order?: never;
2365
+ readonly dependencyOrder?: never;
2366
+ readonly address?: never;
2367
+ } | {
2368
+ readonly kind: 'application-step';
2369
+ readonly id: string;
2370
+ readonly step: 'assert';
2371
+ readonly inspected: boolean;
2372
+ readonly stepKey?: never;
2373
+ readonly order?: never;
2374
+ readonly dependencyOrder?: never;
2375
+ readonly address?: never;
2376
+ };
2377
+ type PgConvergeCheckResult = {
2378
+ readonly kind: 'no-drift';
2379
+ } | {
2380
+ readonly kind: 'would-apply';
2381
+ readonly planDigest: string;
2382
+ readonly steps: readonly PgConvergePlannedStep[];
2383
+ };
2384
+ interface ConvergePgBaseOptions {
2385
+ readonly schema?: string;
2386
+ readonly dbCasing?: DbCasing;
2387
+ /** Internal physical-model rendering choice; public callers cannot override it. */
2388
+ readonly fkAutoIndex?: boolean;
2389
+ /** Internal physical-to-authored sequence provenance for legacy-name refusal. */
2390
+ readonly declaredSequenceNames?: ReadonlyMap<string, string>;
2391
+ /**
2392
+ * In apply mode, create a ledger for an absent schema ledger. `pristine`
2393
+ * refuses declared live tables or standalone sequences; `adopt-existing`
2394
+ * also adopts matching declared relations on every converge call. The schema
2395
+ * itself must already exist. Defaults to `never`.
2396
+ */
2397
+ readonly initialize?: 'never' | 'pristine' | 'adopt-existing';
2398
+ /**
2399
+ * Exact physical PostgreSQL index names that converge must leave alone on
2400
+ * declared model tables. Each table name uses the model's naming, while the
2401
+ * index name is used verbatim. Entries are validated before connecting: they
2402
+ * must be distinct, name declared tables, and must not equal the name of an
2403
+ * index listed in any declared table's `indexes`. Converge never drops a
2404
+ * live index named here. It does not check these names against the other
2405
+ * relations the model creates (tables, sequences, primary-key or UNIQUE
2406
+ * constraint indexes); PostgreSQL rejects such a collision when the step
2407
+ * runs, and converge reports it as that step's failure.
2408
+ */
2409
+ readonly externalIndexes?: readonly {
2410
+ readonly table: string;
2411
+ readonly name: string;
2412
+ }[];
2413
+ /**
2414
+ * Transactional application-owned schema work. Recorded runs append
2415
+ * `application-step:<id>` to `applied`, after generated change kinds.
2416
+ * The transaction facade rejects leading transaction-control keywords; it is
2417
+ * a correctness guard, not a security boundary for code in this process.
2418
+ */
2419
+ readonly steps?: readonly PgConvergeApplicationStep[];
2420
+ }
2421
+ interface ConvergePgOptions extends ConvergePgBaseOptions {
2422
+ readonly mode?: 'apply';
2423
+ }
2424
+ interface ConvergePgCheckOptions extends ConvergePgBaseOptions {
2425
+ readonly mode: 'check';
2426
+ }
2427
+ /**
2428
+ * Converges only startup-safe PostgreSQL additions: it creates tables and
2429
+ * sequences, adds nullable columns without defaults and NOT NULL columns with
2430
+ * boolean, finite-number, or non-function-like string literal defaults of a
2431
+ * a PostgreSQL built-in base type or an enum to managed tables, and creates
2432
+ * indexes, CHECK constraints, and foreign keys when their table parents are
2433
+ * created by this same run (for foreign keys, both tables).
2434
+ * Other defaulted original database types are refused.
2435
+ *
2436
+ * Adding a column still takes an ACCESS EXCLUSIVE lock on its table, bounded by
2437
+ * the executor's five-second lock_timeout and held through read-back and the
2438
+ * ledger terminal. A no-rewrite default is therefore not non-blocking.
2439
+ *
2440
+ * Converge mutates only declared additions whose target and existing parent pass
2441
+ * managed admission. It compares the declared tables, sequences, and enums'
2442
+ * structural shape; it does not audit the provenance of an exact-matching child
2443
+ * already present on a managed table.
2444
+ * An assert may own declared CHECKs, column types, and named indexes; those
2445
+ * surfaces are excluded from comparison and generated DDL. Its read-only
2446
+ * `inspect` receives canonical owned-CHECK state, while its callback is
2447
+ * responsible for maintaining them. `externalIndexes` accepts exact physical
2448
+ * index names on logical model tables;
2449
+ * entries are validated before the ledger lock or any query, and converge
2450
+ * never drops a matching live index. A name that collides with another
2451
+ * relation the model creates fails when that step runs.
2452
+ * Before comparison, converge refuses while its target ledger home has a live
2453
+ * reservation: wait for a run that is still executing, reconcile a run whose
2454
+ * lock is free with reconcilePgTransitionRun or `dbsp reconcile --db
2455
+ * <database> <run-id>`, have the ledger owner resolve an unmapped reservation
2456
+ * and the journal owner one whose journal attribution cannot be read, then call
2457
+ * converge again.
2458
+ * Application steps run on the converge session: session-level effects such as
2459
+ * `SET` without `LOCAL`, `SET ROLE`, `LISTEN`, `PREPARE`, temporary tables and
2460
+ * session advisory locks are not part of a step and can affect the rest of the
2461
+ * call. Steps should use `SET LOCAL`.
2462
+ * A declared table with `adopt: true` is taken into management when it exists,
2463
+ * the ledger projects its address as unknown (the only state an adoption claim
2464
+ * opens from), and it matches the declaration exactly after `externalIndexes`
2465
+ * and application ownership masking. A mismatch found while planning refuses
2466
+ * `adoption-refused` before anything is written. A table that changes while
2467
+ * its adoption runs is refused under its claim and the ledger records that
2468
+ * refused adoption; tables adopted earlier in the same call stay adopted.
2469
+ * Tables a run creates and every change on those tables commit together or not
2470
+ * at all. A sequence created by the same run commits on its own and can remain
2471
+ * after a failure. After a transport-ambiguous outcome, the next call observes
2472
+ * whichever state PostgreSQL holds. Converge runs are not journaled. Check mode
2473
+ * returns a point-in-time plan without executing it; it is not a guarantee that
2474
+ * a later apply will succeed, because other sessions can change the database
2475
+ * and execution-time ledger physical-shape integrity, claim-time adoption
2476
+ * re-verification, vacancy, and lock-timeout checks are not reproduced.
2477
+ * `initialize` defaults to `never`. `pristine` creates an absent ledger only
2478
+ * when declared tables and standalone sequences are absent, while
2479
+ * `adopt-existing` creates an absent ledger and adopts matching declared
2480
+ * relations on every call. The target schema must already exist. Application
2481
+ * steps run with `search_path` set to the target schema, `pg_temp`, then the
2482
+ * connection's entries, so `current_schema()` is the target. Lookup goes through
2483
+ * `pg_catalog` first unless those entries name it explicitly, then the target,
2484
+ * `pg_temp` and those entries.
2485
+ */
2486
+ declare function convergePg(pool: Pool, model: ModelIR, options?: ConvergePgOptions): Promise<PgConvergeResult>;
2487
+ declare function convergePg(pool: Pool, model: ModelIR, options: ConvergePgCheckOptions): Promise<PgConvergeCheckResult>;
2488
+
2489
+ type QueryResultLike = {
2490
+ readonly rows: readonly Record<string, unknown>[];
2491
+ };
2492
+ type TransitionJournalQueryable = {
2493
+ query(sql: string, params?: readonly unknown[]): Promise<QueryResultLike>;
2494
+ };
2495
+ /** A copied plan row is not authority for a differently named run. */
2496
+ declare class TransitionRunIdentityMismatchError extends Error {
2497
+ constructor();
2498
+ }
2499
+ declare function renderCreateDbspMetaSchemaSql(): string;
2500
+ declare function renderCreateTransitionRunTableSql(exclusive?: boolean): string;
2501
+ declare function renderCreateTransitionJournalTableSql(exclusive?: boolean): string;
2502
+ declare function renderCreateTransitionRunPlanTableSql(exclusive?: boolean): string;
2503
+ declare function renderCreateTransitionAuthorizationTableSql(exclusive?: boolean): string;
2504
+ declare function ensureTransitionJournal(executor: TransitionJournalQueryable): Promise<void>;
2505
+ declare function createPgTransitionRunPersister(executor: TransitionJournalQueryable): TransitionRunPersister;
2506
+ declare function appendIntentJournal(executor: TransitionJournalQueryable, record: DurableIntentRecord): Promise<void>;
2507
+ /** Append-only run approval, intentionally separate from step attempts. */
2508
+ declare function appendTransitionAuthorization(executor: TransitionJournalQueryable, record: TransitionRunAuthorization): Promise<void>;
2509
+ declare function readTransitionJournal(executor: TransitionJournalQueryable, runId: string, options?: {
2510
+ readonly ensure?: boolean;
2511
+ }): Promise<TransitionRunJournal & {
2512
+ readonly plan: ProvenPlanShape;
2513
+ }>;
2514
+
2515
+ interface PgCatalogueIdentityQueryable {
2516
+ query(sql: string, params?: readonly unknown[]): Promise<{
2517
+ readonly rows: readonly Record<string, unknown>[];
2518
+ }>;
2519
+ }
2520
+ /**
2521
+ * Re-read the PostgreSQL catalogue identity for one managed address. The
2522
+ * adapter deliberately returns absence as undefined; callers decide whether an
2523
+ * absent object is legal for the lifecycle state they are admitting.
2524
+ */
2525
+ declare function readPgCatalogueIdentity(executor: PgCatalogueIdentityQueryable, address: ResourceAddress): Promise<ResourceAddress | undefined>;
2526
+
2527
+ declare const PG_LEDGER_SHAPE_VERSION = 1;
2528
+ declare const ledgerShapeAllowanceBrand: unique symbol;
2529
+ /**
2530
+ * An in-process allowance for one non-ledger trigger observed immediately
2531
+ * after trusted harness setup. Its contents are deliberately not structural:
2532
+ * only the internal factory can register a value in the WeakSet below.
2533
+ */
2534
+ interface PgLedgerShapeAllowance {
2535
+ readonly [ledgerShapeAllowanceBrand]: 'dbsp-ledger-shape-allowance';
2536
+ }
2537
+ type PgLedgerPhysicalShapeOutcome = {
2538
+ readonly kind: 'verified';
2539
+ } | {
2540
+ readonly kind: 'shape-wrong';
2541
+ readonly artefact: string;
2542
+ } | {
2543
+ readonly kind: 'unverifiable';
2544
+ readonly cause: string;
2545
+ } | {
2546
+ readonly kind: 'unsupported-major';
2547
+ readonly major: number | undefined;
2548
+ } | {
2549
+ readonly kind: 'validator-abi-failure';
2550
+ readonly sqlstate: string;
2551
+ };
2552
+ /**
2553
+ * Read-only admission of an existing ledger. A fixture is deliberately a
2554
+ * prerequisite: deparse text is not portable across PostgreSQL majors.
2555
+ */
2556
+ declare function classifyPgLedgerPhysicalShape(executor: TransitionJournalQueryable, target: PgLedgerTarget, allowance?: PgLedgerShapeAllowance): Promise<PgLedgerPhysicalShapeOutcome>;
2557
+ /**
2558
+ * Throwing compatibility façade. Existing mutating callers intentionally keep
2559
+ * their historical contract; outcome-aware consumers use `classify…`.
2560
+ */
2561
+ declare function validatePgLedgerPhysicalShape(executor: TransitionJournalQueryable, target: PgLedgerTarget, allowance?: PgLedgerShapeAllowance): Promise<void>;
2562
+ /**
2563
+ * Mint a one-request allowance for one exact live trigger. This is exported
2564
+ * only from the adapter's `/internal` surface: consumers cannot forge the
2565
+ * WeakMap registration or serialize it into an ordinary recovery request.
2566
+ */
2567
+ declare function createPgLedgerShapeAllowance(executor: TransitionJournalQueryable, target: PgLedgerTarget, triggerName: string): Promise<PgLedgerShapeAllowance>;
2568
+ declare class PgLedgerStorageUnsupportedError extends Error {
2569
+ constructor(observed: unknown);
2570
+ }
2571
+ declare const pgOrderedLedgerLocksBrand: unique symbol;
2572
+ /** Proof returned only after this transaction acquired every home in order. */
2573
+ interface PgOrderedLedgerLocks {
2574
+ readonly homes: readonly PgLedgerTarget[];
2575
+ readonly [pgOrderedLedgerLocksBrand]: 'dbsp-pg-ordered-ledger-locks';
2576
+ }
2577
+ type PgLedgerLockResult = {
2578
+ readonly kind: 'acquired';
2579
+ readonly proof: PgOrderedLedgerLocks;
2580
+ } | {
2581
+ readonly kind: 'busy';
2582
+ readonly ledger: LedgerHome;
2583
+ } | {
2584
+ readonly kind: 'refused';
2585
+ readonly ledger: LedgerHome;
2586
+ readonly error: unknown;
2587
+ };
2588
+ type PgLedgerTarget = LedgerHome;
2589
+ /** Read only reservations explicitly linked to one durable execution/run. */
2590
+ declare function readPgLedgerReservationsForExecution(executor: TransitionJournalQueryable, target: PgLedgerTarget, executionId: string): Promise<readonly LedgerReservationRow[]>;
2591
+ /**
2592
+ * A re-address pair can cross ledger homes. Discover every existing reservation
2593
+ * table before reading the pair so recovery cannot accidentally treat one side
2594
+ * of a cross-schema closure as the entire operation.
2595
+ */
2596
+ type PgLedgerReservationCandidateOutcome = {
2597
+ readonly target: PgLedgerTarget;
2598
+ readonly kind: 'verified';
2599
+ } | {
2600
+ readonly target: PgLedgerTarget;
2601
+ readonly kind: 'not-ledger-shape';
2602
+ } | {
2603
+ readonly target: PgLedgerTarget;
2604
+ readonly kind: 'unverifiable';
2605
+ readonly cause: string;
2606
+ };
2607
+ type PgLedgerReservationsForPair = readonly LedgerReservationRow[] & {
2608
+ readonly candidates: readonly PgLedgerReservationCandidateOutcome[];
2609
+ };
2610
+ declare function readPgLedgerReservationsForPair(executor: TransitionJournalQueryable, pairId: string): Promise<PgLedgerReservationsForPair>;
2611
+ type LedgerWriteMember = Omit<LedgerChainMember, 'controller' | 'recordedAt'>;
2612
+ declare function renderCreateLedgerEventTableSql(target: PgLedgerTarget): string;
2613
+ declare function renderCreateLedgerTerminalMemberIndexSql(target: PgLedgerTarget): string;
2614
+ declare function renderCreateLedgerReservationTableSql(target: PgLedgerTarget): string;
2615
+ declare function renderCreateLedgerIdentityTableSql(target: PgLedgerTarget): string;
2616
+ declare function renderCreateLedgerMarkerTableSql(target: PgLedgerTarget): string;
2617
+ declare function renderCreateLedgerImmutabilityFunctionSql(target: PgLedgerTarget): string;
2618
+ declare function renderCreateLedgerImmutabilityTriggerSql(target: PgLedgerTarget): string;
2619
+ /** Proves the PG 15 requirement before emitting a NULLS NOT DISTINCT table. */
2620
+ declare function ensurePgLedgerStorageVersion(executor: TransitionJournalQueryable): Promise<void>;
2621
+ declare function ensurePgLedger(executor: TransitionJournalQueryable, target: PgLedgerTarget, options?: {
2622
+ readonly writeMarker?: boolean;
2623
+ }): Promise<void>;
2624
+ declare function ensureDbspMetaLedger(executor: TransitionJournalQueryable, options?: {
2625
+ readonly writeMarker?: boolean;
2626
+ }): Promise<void>;
2627
+ /** Records lineage once; a mismatching identity is an admission concern of unit 5. */
2628
+ declare function recordPgLedgerIdentity(executor: TransitionJournalQueryable, target: PgLedgerTarget, identity: LedgerIdentity): Promise<void>;
2629
+ declare function appendPgLedgerProgress(executor: TransitionJournalQueryable, target: PgLedgerTarget, member: LedgerWriteMember): Promise<void>;
2630
+ /**
2631
+ * Appends the root claim and every reservation in one PostgreSQL statement.
2632
+ * Callers can include this statement in a larger DDL transaction, but cannot
2633
+ * accidentally split this claim's append from its durable reservation rows.
2634
+ */
2635
+ declare function appendPgLedgerClaim(executor: TransitionJournalQueryable, target: PgLedgerTarget, member: LedgerWriteMember, reservations: readonly LedgerReservationRow[], reservationRootClaimId?: string): Promise<void>;
2636
+ /**
2637
+ * Appends an entire destructive closure as one ledger group. The caller owns
2638
+ * the surrounding locked transaction; consequently a failed member insert
2639
+ * rolls back the root, every member and every reservation together.
2640
+ */
2641
+ declare function appendPgLedgerClaimGroup(executor: TransitionJournalQueryable, root: LedgerWriteMember, members: readonly LedgerWriteMember[], reservations: readonly LedgerReservationRow[]): Promise<void>;
2642
+ /** Resolves every closure terminal in the caller's one locked transaction. */
2643
+ declare function appendPgLedgerResolutionGroup(executor: TransitionJournalQueryable, rootClaimId: string, members: readonly LedgerWriteMember[], reservations: readonly Pick<LedgerReservationRow, 'address'>[]): Promise<void>;
2644
+ /**
2645
+ * Appends a terminal member and releases the reservations owned by this
2646
+ * append atomically. A group-owned contained member has an intentionally
2647
+ * empty closure because its group's root append already released it.
2648
+ */
2649
+ declare function appendPgLedgerResolution(executor: TransitionJournalQueryable, target: PgLedgerTarget, member: LedgerWriteMember, rootClaimId: string, reservations: readonly Pick<LedgerReservationRow, 'address'>[]): Promise<void>;
2650
+ /**
2651
+ * `released` has no claim spelling in the closed event grammar. It is the
2652
+ * deliberate atomic managed-to-unknown transition, so it must not invent an
2653
+ * empty reservation closure merely to reuse ordinary claim resolution.
2654
+ */
2655
+ declare function appendPgLedgerRelease(executor: TransitionJournalQueryable, target: PgLedgerTarget, member: LedgerWriteMember): Promise<void>;
2656
+ /**
2657
+ * Transaction-scoped, non-waiting locks for one effects closure. The ordering
2658
+ * is dbsp_meta first and then schema name, so opposing closures cannot deadlock.
2659
+ */
2660
+ declare function acquirePgLedgerLocks(executor: TransitionJournalQueryable, homes: readonly LedgerHome[]): Promise<PgLedgerLockResult>;
2661
+
2662
+ type ReinitializePreflightCheckpoint = 'archive' | 'create' | 'grants' | 'journal-create' | 'marker' | 'output';
2663
+ /** Test-only callers can observe real engine progress without changing production flow. */
2664
+ type ReinitializePreflightObserver = (checkpoint: ReinitializePreflightCheckpoint, ledger?: LedgerHome) => Promise<void>;
2665
+ interface PgReinitializePreflightClient extends TransitionJournalQueryable {
2666
+ release?(error?: unknown): void;
2667
+ }
2668
+ interface PgReinitializePreflightPool {
2669
+ connect(): Promise<PgReinitializePreflightClient>;
2670
+ }
2671
+ interface PgReinitializePreflightOptions {
2672
+ readonly pool: PgReinitializePreflightPool;
2673
+ /** Schema names only. `dbsp_meta` is always added as the database ledger. */
2674
+ readonly schemas: readonly string[];
2675
+ readonly declarations: DeclarationSet;
2676
+ readonly writeAdoptionFile: (report: ReinitializePreflightReport) => Promise<void>;
2677
+ readonly observer?: ReinitializePreflightObserver;
2678
+ }
2679
+ /**
2680
+ * Read exactly one ledger shape marker without creating or repairing anything.
2681
+ * Ordinary command surfaces use this to refuse a non-current mutating scope;
2682
+ * inspect deliberately reports the returned value instead.
2683
+ */
2684
+ declare function readPgLedgerMarker(executor: TransitionJournalQueryable, home: LedgerHome): Promise<LedgerMarkerState>;
2685
+ /**
2686
+ * Ordinary mutating commands consume this read-only admission result. It
2687
+ * intentionally delegates equality to the preflight's recorded-vs-live
2688
+ * comparison, keeping that pair as the only ledger lineage comparison.
2689
+ */
2690
+ type PgLedgerScopeCurrency = {
2691
+ readonly kind: 'absent';
2692
+ readonly marker: LedgerMarkerState;
2693
+ } | {
2694
+ readonly kind: 'current';
2695
+ readonly marker: LedgerMarkerState;
2696
+ } | {
2697
+ readonly kind: 'not-current';
2698
+ readonly marker: LedgerMarkerState;
2699
+ readonly reason: 'marker' | 'lineage';
2700
+ };
2701
+ declare function readPgLedgerScopeCurrency(executor: TransitionJournalQueryable, home: LedgerHome): Promise<PgLedgerScopeCurrency>;
2702
+ /**
2703
+ * Pair recovery reads only homes already selected by the durable run. A
2704
+ * same-named user table in another schema is never discovery evidence for a
2705
+ * pair; callers must first establish the finite candidate homes from reviewed
2706
+ * material and then each home is admitted here.
2707
+ */
2708
+ declare function readVerifiedPgLedgerReservationsForPair(executor: TransitionJournalQueryable, pairId: string, homes: readonly LedgerHome[]): Promise<readonly _dbsp_types_internal.LedgerReservationRow[]>;
2709
+ /**
2710
+ * Runs the separately privileged reinitialize-preflight. It never invokes a
2711
+ * ledger append primitive: the only durable writes are additive structure,
2712
+ * archived structure, identity, grants, marker, and the caller-owned output.
2713
+ */
2714
+ declare function runPgReinitializePreflight(options: PgReinitializePreflightOptions): Promise<ReinitializePreflightReport>;
2715
+
2716
+ declare const pgLockedRunBrand: unique symbol;
2717
+ /**
2718
+ * A run identity that was loaded while the caller owns its run lock. This is
2719
+ * deliberately not a structural `{ runId, planDigest }`: callers cannot bind
2720
+ * the digest check to two independently supplied strings.
2721
+ */
2722
+ interface PgLockedRun {
2723
+ readonly runId: string;
2724
+ readonly planDigest: string;
2725
+ readonly [pgLockedRunBrand]: 'dbsp-pg-locked-journal-run';
2726
+ }
2727
+ /**
2728
+ * Adapter-only bridge from the journal-load/run-lock boundary. Keep this
2729
+ * beside the admitted facade; ordinary callers receive a `PgLockedRun`, never
2730
+ * manufacture one from string fields.
2731
+ */
2732
+ declare function lockPgJournalRun(run: DurablyLoadedRun): PgLockedRun;
2733
+ /** A COMMIT write may have reached PostgreSQL even when its acknowledgement did not. */
2734
+ declare class PgCommitAcknowledgementAmbiguousError extends Error {
2735
+ constructor(cause: unknown);
2736
+ }
2737
+ /**
2738
+ * Test-only observation points on the admitted path. Production callers do
2739
+ * not supply an observer, so the helper is inert: it performs no IPC, I/O, or
2740
+ * scheduling work in an ordinary run.
2741
+ */
2742
+ type PgOutcomeCheckpoint = 'post-lock-integrity-before-append' | 'commit-acknowledged' | 'ddl-completed-before-read-back';
2743
+ type PgOutcomeCheckpointObserver = (checkpoint: PgOutcomeCheckpoint) => Promise<void> | void;
2744
+ interface PgOutcomeClaimRequest {
2745
+ readonly plan: OutcomeClaimPlan;
2746
+ readonly reservations: readonly LedgerReservationRow[];
2747
+ readonly lockTimeoutMs?: number;
2748
+ /** Destructive authority is evaluated under these same ledger locks. */
2749
+ readonly destructiveDecision?: (executor: TransitionJournalQueryable, plan: OutcomeClaimPlan) => Promise<DestructiveDecision>;
2750
+ /** Optional E2E observer; absent in all production command paths. */
2751
+ readonly observer?: PgOutcomeCheckpointObserver;
2752
+ }
2753
+ /** One root claim plus its token-free destructive-closure members. */
2754
+ interface PgOutcomeClaimGroupRequest extends PgOutcomeClaimRequest {
2755
+ readonly members: readonly Omit<PgOutcomeClaimRequest, 'destructiveDecision'>[];
2756
+ }
2757
+ interface PgOutcomeClaimGroupAdmission {
2758
+ readonly root: OutcomeClaimAdmission;
2759
+ readonly members: readonly OutcomeClaimAdmission[];
2760
+ }
2761
+ interface PgOutcomeClaimGroupResolution {
2762
+ readonly rootClaimId: string;
2763
+ readonly members: readonly {
2764
+ readonly target: PgLedgerTarget;
2765
+ readonly member: Omit<LedgerChainMember, 'controller' | 'recordedAt'>;
2766
+ }[];
2767
+ readonly reservations: readonly Pick<LedgerReservationRow, 'address'>[];
2768
+ readonly lockTimeoutMs?: number;
2769
+ /** Durable run witness carried from destructive admission to its terminal. */
2770
+ readonly runtimeIntegrityRun?: PgLockedRun;
2771
+ /** Optional E2E observer for this terminal-appending transaction. */
2772
+ readonly observer?: PgOutcomeCheckpointObserver;
2773
+ }
2774
+ interface PgOutcomeResolution {
2775
+ readonly eventId: string;
2776
+ readonly eventKind: Exclude<LedgerEventKind, 'intent' | 'retire-intent' | 'readdress-intent' | 'adopt-intent' | 'executing'>;
2777
+ readonly observed?: LedgerChainMember['observed'];
2778
+ /** Required by the ledger writer when this resolution is `refused`. */
2779
+ readonly refusal?: LedgerChainMember['refusal'];
2780
+ }
2781
+ interface PgOutcomeExecutionRequest {
2782
+ readonly token: ClaimToken;
2783
+ readonly claim: AdmittedOutcomeClaim;
2784
+ readonly statements: readonly ClaimBundleStatement[];
2785
+ }
2786
+ /**
2787
+ * The first admitted-operation shape. Later waves add single and paired
2788
+ * operation variants without reopening the facade's authority boundary.
2789
+ */
2790
+ interface PgSingleAdmittedOperation {
2791
+ readonly kind: 'single-outcome';
2792
+ readonly request: PgOutcomeTransactionalRequest | PgOutcomeNonTransactionalRequest;
2793
+ }
2794
+ /**
2795
+ * The three generated payload roles are intentionally disjoint at the type
2796
+ * boundary. Their runtime serialization remains the ledger's `{ value,
2797
+ * digest }` pair; the discriminant prevents a generic identity observation
2798
+ * from being wired into a declaration or a structural-proof slot.
2799
+ */
2800
+ type GeneratedDeclarationPayload = LedgerPayload & {
2801
+ readonly payloadKind: 'generated-declaration';
2802
+ };
2803
+ type GeneratedIdentityObservation = LedgerPayload & {
2804
+ readonly payloadKind: 'generated-identity-observation';
2805
+ };
2806
+ type GeneratedStructuralObservation = LedgerPayload & {
2807
+ readonly payloadKind: 'generated-structural-observation';
2808
+ };
2809
+ /**
2810
+ * Readdress keeps its catalogue closure discovery in readdress.ts, while this
2811
+ * facade owns the only claim/permit/DDL/terminal path for the resulting pair.
2812
+ */
2813
+ interface PgPairedReaddressOperation {
2814
+ readonly kind: 'paired-readdress';
2815
+ readonly request: {
2816
+ readonly pairId: string;
2817
+ readonly executionId: string;
2818
+ readonly members: readonly {
2819
+ readonly source: LedgerAddress;
2820
+ readonly target: LedgerAddress;
2821
+ readonly sourceClaimId: string;
2822
+ readonly targetClaimId: string;
2823
+ readonly sourceDeclared?: LedgerPayload;
2824
+ readonly targetDeclared: GeneratedDeclarationPayload;
2825
+ readonly targetObserved: GeneratedIdentityObservation;
2826
+ /**
2827
+ * Optional structural proof for a typed table declaration. The paired
2828
+ * protocol invokes it after DDL on its pinned transaction session, so
2829
+ * the observed ledger fact is the catalogue projection it just read.
2830
+ */
2831
+ readonly postDdlReadBack?: (executor: GeneratedPostconditionSession) => Promise<GeneratedStructuralObservation>;
2832
+ /** Verifies a physical relationship that identity alone cannot prove. */
2833
+ readonly postDdlVerify?: (executor: TransitionJournalQueryable) => Promise<void>;
2834
+ }[];
2835
+ readonly reservations: readonly LedgerReservationRow[];
2836
+ readonly statements: readonly ClaimBundleStatement[];
2837
+ /** Digest-covered root material for this paired request; it is never empty. */
2838
+ readonly manifestPlan: OutcomeClaimPlan;
2839
+ /** Re-read closure, source controller/identity and target vacancy under lock. */
2840
+ readonly verifyLiveAdmission: (executor: TransitionJournalQueryable, currentController: ControllerIdentity) => Promise<OutcomeProtocolRefusal | readonly {
2841
+ readonly source: LedgerAddress;
2842
+ readonly target: LedgerAddress;
2843
+ readonly catalogueIdentity: NonNullable<NonNullable<Awaited<ReturnType<typeof readPgCatalogueIdentity>>>['catalogueIdentity']>;
2844
+ }[]>;
2845
+ readonly lockTimeoutMs?: number;
2846
+ /** Optional E2E observer; absent in normal execution. */
2847
+ readonly observer?: PgOutcomeCheckpointObserver;
2848
+ };
2849
+ }
2850
+ interface PgDestructiveAdmittedOperation {
2851
+ readonly kind: 'destructive-outcome';
2852
+ readonly request: PgOutcomeClaimGroupRequest;
2853
+ readonly readBackAndResolve: (executor: TransitionJournalQueryable, claim: AdmittedDestructiveOutcomeClaim) => Promise<PgOutcomeClaimGroupResolution>;
2854
+ }
2855
+ type PgAdmittedOperation = PgSingleAdmittedOperation | PgPairedReaddressOperation | PgDestructiveAdmittedOperation;
2856
+ type PgAdmittedOperationResult = PgOutcomeResult | PgDestructiveOutcomeResult | {
2857
+ readonly kind: 'executed-paired-readdress';
2858
+ readonly pairId: string;
2859
+ } | {
2860
+ readonly kind: 'outcome-transport-ambiguous';
2861
+ readonly reason: string;
2862
+ } | {
2863
+ readonly kind: 'outcome-recovery-required';
2864
+ readonly claimId: string;
2865
+ readonly reason: string;
2866
+ };
2867
+ type PgDestructiveOutcomeResult = {
2868
+ readonly kind: 'executed-destructive-outcome';
2869
+ }
2870
+ /**
2871
+ * SQL was admitted and may have run, but its operation-owned read-back could
2872
+ * not establish a terminal fact. Keep the durable claim open for reconcile;
2873
+ * in particular, never turn this post-executing state into `refused`.
2874
+ */
2875
+ | {
2876
+ readonly kind: 'outcome-protocol-pending';
2877
+ readonly reason: string;
2878
+ } | OutcomeProtocolRefusal | {
2879
+ readonly kind: 'outcome-transport-ambiguous';
2880
+ readonly reason: string;
2881
+ } | {
2882
+ readonly kind: 'outcome-recovery-required';
2883
+ readonly claimId: string;
2884
+ readonly reason: string;
2885
+ };
2886
+ /**
2887
+ * Internal compatibility bridge. Callers must bring the durable run and scoped
2888
+ * approvals that the façade consumes; this bridge never invents either.
2889
+ */
2890
+ declare function executePgDestructiveOutcome(executor: TransitionJournalQueryable, input: {
2891
+ readonly run: PgLockedRun;
2892
+ readonly approval: ScopedApprovalSet;
2893
+ readonly request: PgOutcomeClaimGroupRequest;
2894
+ readonly readBackAndResolve: (executor: TransitionJournalQueryable, claim: AdmittedDestructiveOutcomeClaim) => Promise<PgOutcomeClaimGroupResolution>;
2895
+ }): Promise<PgDestructiveOutcomeResult>;
2896
+ /** Keeps terminal appends and reservation release behind the managed facade. */
2897
+ declare function resolvePgDestructiveOutcome(executor: TransitionJournalQueryable, request: PgOutcomeClaimGroupResolution): Promise<undefined | OutcomeProtocolRefusal>;
2898
+ interface PgOutcomeTransactionalRequest extends PgOutcomeClaimRequest {
2899
+ readonly resolution: PgOutcomeResolution;
2900
+ /** Core has already opened the segment transaction; never nest BEGIN. */
2901
+ readonly transactionOpen?: boolean;
2902
+ /**
2903
+ * Operation-owned terminal read-back; generic catalogue identity is not
2904
+ * evidence. It receives the admitted session so transactional DDL is read
2905
+ * before its terminal ledger fact commits.
2906
+ */
2907
+ readonly readBack?: (executor: GeneratedPostconditionSession) => Promise<LedgerPayload>;
2908
+ /** Required for creations; the reader runs after the claim and before SQL. */
2909
+ readonly vacancy?: (executor: TransitionJournalQueryable, plan: OutcomeClaimPlan) => Promise<OutcomeVacancy>;
2910
+ /** Re-check operation-specific live facts after the claim/reservation opens. */
2911
+ readonly verifyLiveAdmission?: (executor: TransitionJournalQueryable, plan: OutcomeClaimPlan) => Promise<OutcomeProtocolRefusal | undefined>;
2912
+ /** Record the post-DDL catalogue identity on a present terminal member. */
2913
+ readonly recordCatalogueIdentity?: boolean;
2914
+ }
2915
+ interface PgOutcomeNonTransactionalRequest extends PgOutcomeTransactionalRequest {
2916
+ readonly executingEventId: string;
2917
+ /** Observable acknowledgement point after executing has committed, before SQL. */
2918
+ readonly onExecutingCommitted?: () => Promise<void> | void;
2919
+ }
2920
+ /** Builds the canonical read-back payload once catalogue presence is proven. */
2921
+ type PgOutcomeReadBackFactory = (executor: GeneratedPostconditionSession, address: LedgerAddress, catalogueIdentity: NonNullable<Awaited<ReturnType<typeof readPgCatalogueIdentity>>>['catalogueIdentity']) => Promise<LedgerPayload>;
2922
+ /**
2923
+ * A postcondition read owned by the operation itself. Catalogue identity is
2924
+ * still retained when present for the ledger, but effect classification comes
2925
+ * from the operation's value-level observation rather than object presence.
2926
+ */
2927
+ type PgOutcomeOperationReadBackFactory = (executor: TransitionJournalQueryable, address: LedgerAddress, catalogueIdentity: NonNullable<Awaited<ReturnType<typeof readPgCatalogueIdentity>>>['catalogueIdentity'] | undefined) => Promise<{
2928
+ readonly observed: LedgerPayload;
2929
+ readonly effect: OutcomeRecoveryEffect;
2930
+ }>;
2931
+ interface PgOutcomeRecoveryRequest {
2932
+ readonly address: LedgerAddress;
2933
+ readonly reservations: readonly Pick<LedgerReservationRow, 'address'>[];
2934
+ readonly resolutionEventId: string;
2935
+ readonly acceptedExternalDdlExclusion: boolean;
2936
+ /** Durable claim-bound evidence re-matched by reconcile under the run lock. */
2937
+ readonly indeterminateEvidence?: OutcomeIndeterminateRecoveryEvidence;
2938
+ readonly resolveIndeterminate?: boolean;
2939
+ readonly readBack: PgOutcomeReadBackFactory;
2940
+ readonly operationReadBack?: PgOutcomeOperationReadBackFactory;
2941
+ readonly lockTimeoutMs?: number;
2942
+ /** Internal-only, in-memory allowance for one harness-installed trigger. */
2943
+ readonly ledgerShapeAllowance?: PgLedgerShapeAllowance;
2944
+ /** Optional E2E observer for recovery's committing transaction. */
2945
+ readonly observer?: PgOutcomeCheckpointObserver;
2946
+ }
2947
+ type PgOutcomeResolutionAppendResult = {
2948
+ readonly kind: 'appended-outcome-resolution';
2949
+ } | {
2950
+ readonly kind: 'already-appended-outcome-resolution';
2951
+ } | {
2952
+ readonly kind: 'malformed-outcome-resolution';
2953
+ readonly reason: string;
2954
+ };
2955
+ type PgOutcomeRecoveryResult = Exclude<OutcomeRecoveryClassification, {
2956
+ readonly kind: 'outcome-recovery-append';
2957
+ }> | {
2958
+ readonly kind: 'outcome-recovery-appended';
2959
+ readonly classification: Extract<OutcomeRecoveryClassification, {
2960
+ readonly kind: 'outcome-recovery-append';
2961
+ }>;
2962
+ readonly append: Exclude<PgOutcomeResolutionAppendResult, {
2963
+ readonly kind: 'malformed-outcome-resolution';
2964
+ }>;
2965
+ } | {
2966
+ readonly kind: 'outcome-transport-ambiguous';
2967
+ readonly reason: string;
2968
+ } | OutcomeProtocolRefusal;
2969
+ type PgOutcomeResult = {
2970
+ readonly kind: 'executed-outcome-claim';
2971
+ readonly claim: AdmittedOutcomeClaim;
2972
+ } | OutcomeProtocolRefusal | {
2973
+ readonly kind: 'outcome-transport-ambiguous';
2974
+ readonly reason: string;
2975
+ } | {
2976
+ readonly kind: 'outcome-recovery-required';
2977
+ readonly claimId: string;
2978
+ readonly reason: string;
2979
+ };
2980
+ type PgPairedReaddressRecoveryDecision = {
2981
+ readonly kind: 'refused';
2982
+ readonly reason: string;
2983
+ } | {
2984
+ readonly kind: 'pending';
2985
+ readonly reason: string;
2986
+ } | {
2987
+ readonly kind: 'indeterminate';
2988
+ readonly reason: string;
2989
+ } | {
2990
+ readonly kind: 'outcome-transport-ambiguous';
2991
+ readonly reason: string;
2992
+ };
2993
+ /**
2994
+ * Recovery owns its reservation set: it re-reads every durable pair row,
2995
+ * checks currency under the same locks, and appends only under a minted paired
2996
+ * permit. A caller's selected rows are evidence to compare, never authority.
2997
+ */
2998
+ declare function recoverPgAdmittedReaddressPair(executor: TransitionJournalQueryable, request: {
2999
+ readonly pairId: string;
3000
+ readonly executionId: string;
3001
+ readonly reservations: readonly LedgerReservationRow[];
3002
+ readonly assess: (executor: TransitionJournalQueryable, reservations: readonly LedgerReservationRow[]) => Promise<PgPairedReaddressRecoveryDecision>;
3003
+ readonly observer?: PgOutcomeCheckpointObserver;
3004
+ }): Promise<PgPairedReaddressRecoveryDecision>;
3005
+ type RuntimeIntegritySeams = {
3006
+ readonly validateShape: typeof validatePgLedgerPhysicalShape;
3007
+ readonly readCurrency: typeof readPgLedgerScopeCurrency;
3008
+ };
3009
+ /**
3010
+ * The façade's runtime gate: validate the physical ledger and its marker /
3011
+ * lineage currency on the same pinned execution session before it admits DDL.
3012
+ * Callers must still take the ledger locks before claiming; this check avoids a
3013
+ * preflight-only trust decision without widening the ledger DDL grammar.
3014
+ */
3015
+ declare function validatePgLedgerRuntimeIntegrity(executor: TransitionJournalQueryable, homes: readonly PgLedgerTarget[], run?: PgLockedRun, seams?: RuntimeIntegritySeams): Promise<OutcomeProtocolRefusal | undefined>;
3016
+ /**
3017
+ * Appends a resolution once, or treats an already-written equal payload as a
3018
+ * successful retry. A different child cannot be written by PostgreSQL's
3019
+ * one-child constraint and is reported as a fail-closed malformed outcome.
3020
+ */
3021
+ declare function appendPgOutcomeResolution(executor: TransitionJournalQueryable, target: PgLedgerTarget, member: Omit<LedgerChainMember, 'controller' | 'recordedAt'>, rootClaimId: string, reservations: readonly Pick<LedgerReservationRow, 'address'>[]): Promise<PgOutcomeResolutionAppendResult>;
3022
+ /**
3023
+ * Standalone PostgreSQL catalogue read-back. This intentionally does not
3024
+ * issue LOCK TABLE: callers may supply a Pool, and protocol atomicity belongs
3025
+ * to the transaction-bound recovery and observed-resolution paths.
3026
+ */
3027
+ declare function readPgOutcomeRecoveryReadBack(executor: TransitionJournalQueryable, address: LedgerAddress, readBack: PgOutcomeReadBackFactory, operationReadBack?: PgOutcomeOperationReadBackFactory, lockTimeoutMs?: number): Promise<OutcomeRecoveryReadBack>;
3028
+ /** Opens a claim on one connection when supplied a PostgreSQL pool. */
3029
+ declare function openPgOutcomeClaim(executor: TransitionJournalQueryable, request: PgOutcomeClaimRequest, run?: PgLockedRun): Promise<OutcomeClaimAdmission>;
3030
+ /**
3031
+ * Opens a root and all closure claims under globally ordered ledger locks in
3032
+ * one transaction. No child is ever durable before its root group commits.
3033
+ */
3034
+ declare function openPgOutcomeClaimGroup(executor: TransitionJournalQueryable, request: PgOutcomeClaimGroupRequest, run?: PgLockedRun): Promise<PgOutcomeClaimGroupAdmission>;
3035
+ /** Resolves every member terminal atomically under the same ordered locks. */
3036
+ declare function resolvePgOutcomeClaimGroup(executor: TransitionJournalQueryable, request: PgOutcomeClaimGroupResolution): Promise<undefined | OutcomeProtocolRefusal>;
3037
+ /**
3038
+ * The public PostgreSQL admitted-execution boundary. It is intentionally not
3039
+ * used by legacy paths yet: later dispatches bind their persisted runs and
3040
+ * operation shapes here without changing this authority surface.
3041
+ */
3042
+ declare function executePgAdmittedOperation(session: TransitionJournalQueryable, input: {
3043
+ readonly run: PgLockedRun;
3044
+ readonly operation: PgAdmittedOperation;
3045
+ readonly approval: ScopedApprovalSet;
3046
+ /** Branded proof that the operation came from the normalized manifest. */
3047
+ readonly manifest?: ValidatedManagedStepManifest;
3048
+ /** Recomputed from the durable plan while the caller owns its run lock. */
3049
+ readonly recomputedPlanDigest?: string;
3050
+ }): Promise<PgAdmittedOperationResult>;
3051
+ /**
3052
+ * Reads an address's chain and live catalogue in one locked transaction before
3053
+ * appending the core classifier's instruction. It never calls the DDL sink.
3054
+ */
3055
+ declare function recoverPgOutcomeClaim(executor: TransitionJournalQueryable, request: PgOutcomeRecoveryRequest): Promise<PgOutcomeRecoveryResult>;
3056
+
3057
+ export { PG_LEDGER_SHAPE_VERSION as $, type AddedEnumValue as A, type GeneratedPostcondition as B, type ChangeKind as C, type Decision as D, ExpressionCanonicalizationUnavailableError as E, type FkColumnDerivation as F, type GeneratedPostconditionSession as G, type GeneratedPostconditionBindingAddress as H, GeneratedPostconditionBindingResolutionError as I, GeneratedPostconditionProofInFlightError as J, GeneratedPostconditionReplanRequiredError as K, GeneratedPostconditionSessionDeactivatedError as L, GeneratedPostconditionWorkInFlightError as M, type IncludeHandler as N, type IncludeResult as O, type ProjectionEnvelope as P, type IndexCapabilityContext as Q, IndexFeatureUnsupportedError as R, type SqlIdentifier as S, type TransitionJournalQueryable as T, IndexPredicateCanonicalizationError as U, type IndexRenderSpec as V, type IntrospectedModelIR as W, type IntrospectionOptions as X, type MigrationSQLOptions as Y, NonConvergentSchemaDiffError as Z, type NonConvergentSchemaDiffSurface as _, type CompilerContext as a, TransitionRunIdentityMismatchError as a$, PartialIndexPredicateNewEnumValueError as a0, PgAdapter as a1, type PgAdapterOptions as a2, type PgAdmittedOperation as a3, type PgAdmittedOperationResult as a4, type PgAdvisoryLockKey as a5, PgAdvisoryLockOptionsError as a6, type PgAdvisoryLockResult as a7, type PgApplicationStepOwnedState as a8, type PgApplicationStepTx as a9, type PgPhysicalModelInput as aA, PgPhysicalModelInputError as aB, type PgPhysicalNameClaim as aC, type PgPhysicalNameCollision as aD, PgPhysicalNameCollisionError as aE, type PgPhysicalNamespace as aF, PgPinnedConnectionAbortSignalError as aG, type PgPoolAdapterOptions as aH, PgPreparedStatementReplayError as aI, type PgPreparedStatementsOptions as aJ, PgRawSqlTransactionControlError as aK, type PgReinitializePreflightOptions as aL, type PgReinitializePreflightPool as aM, type PgRollbackOnlyScope as aN, type PgSchemaDiff as aO, PgTransactionAbortSignalError as aP, PgTransactionAbortedCommitError as aQ, PgTransactionAbortedError as aR, PgTransactionOptionsError as aS, PgTransactionTimeoutError as aT, RawIndexPredicateFallbackError as aU, type ReferencedKeyKind as aV, type ReferencedKeyRemovalConflict as aW, ReferencedKeyRemovalError as aX, type SchemaChange as aY, type SchemaDiff as aZ, type SchemaScopeOptions as a_, type PgBorrowedClientAdapterOptions as aa, type PgCatalogueIdentityQueryable as ab, type PgCompileOnlyAdapterOptions as ac, type PgConvergeApplicationStep as ad, type PgConvergeAssertStep as ae, type PgConvergeInitializationFailure as af, type PgConvergeOnceStep as ag, type PgConvergePlannedStep as ah, type PgConvergeRefusal as ai, type PgConvergeRefusalChange as aj, PgConvergeRefusalError as ak, type PgLedgerLockResult as al, PgLedgerStorageUnsupportedError as am, type PgLedgerTarget as an, type PgOutcomeCheckpoint as ao, type PgOutcomeClaimRequest as ap, type PgOutcomeExecutionRequest as aq, type PgOutcomeNonTransactionalRequest as ar, type PgOutcomeReadBackFactory as as, type PgOutcomeRecoveryRequest as at, type PgOutcomeRecoveryResult as au, type PgOutcomeResolution as av, type PgOutcomeResolutionAppendResult as aw, type PgOutcomeResult as ax, type PgOutcomeTransactionalRequest as ay, type PgOwnedCheckState as az, type CompilerState as b, type PgOrderedLedgerLocks as b$, type WhereDispatcher as b0, type WhereHandler as b1, acquirePgLedgerLocks as b2, appendIntentJournal as b3, appendTransitionAuthorization as b4, assertCreateIndexSupported as b5, assertCreateIndexesSupported as b6, assertDeclarableChangeKind as b7, assertGeneratedPostconditionSession as b8, assertNoRepeatedExpressionSurfaceDrift as b9, readPgLedgerReservationsForExecution as bA, readPgLedgerScopeCurrency as bB, readPgOutcomeRecoveryReadBack as bC, readVerifiedPgLedgerReservationsForPair as bD, recordPgLedgerIdentity as bE, renderCreateDbspMetaSchemaSql as bF, renderCreateIndex as bG, renderCreateLedgerEventTableSql as bH, renderCreateLedgerIdentityTableSql as bI, renderCreateLedgerImmutabilityFunctionSql as bJ, renderCreateLedgerImmutabilityTriggerSql as bK, renderCreateLedgerMarkerTableSql as bL, renderCreateLedgerReservationTableSql as bM, renderCreateLedgerTerminalMemberIndexSql as bN, renderCreateTransitionAuthorizationTableSql as bO, renderCreateTransitionJournalTableSql as bP, renderCreateTransitionRunPlanTableSql as bQ, renderCreateTransitionRunTableSql as bR, runPgReinitializePreflight as bS, toGeneratedPostconditionBindingAddress as bT, validatePgLedgerRuntimeIntegrity as bU, verifyGeneratedCheckPostcondition as bV, verifyGeneratedColumnPostcondition as bW, verifyGeneratedIdentityPostcondition as bX, verifyGeneratedIndexPostcondition as bY, verifyGeneratedTablePostcondition as bZ, withGeneratedPostconditionSession as b_, canGenerateCreateIndex as ba, canonicalizeCheckConstraints as bb, comparePgDatabaseSchema as bc, compareSchemata as bd, createPgAdapter as be, createPgCompileOnlyAdapter as bf, createPgGeneratedManagedStep as bg, createPgPhysicalModel as bh, createPgTransitionRunPersister as bi, decodeGeneratedPostcondition as bj, decodeGeneratedPostconditionPayload as bk, defaultFkDerivation as bl, ensureDbspMetaLedger as bm, ensurePgLedger as bn, ensurePgLedgerStorageVersion as bo, ensureTransitionJournal as bp, executePgAdmittedOperation as bq, generateCreateIndex as br, generateDDL as bs, generateDownSQL as bt, generateMigrationSQL as bu, generatedPostconditionDigest as bv, generatedPostconditionForChange as bw, introspect as bx, readPgCatalogueIdentity as by, readPgLedgerMarker as bz, type PgLockedRun as c, type PgLedgerShapeAllowance as c0, type PgLedgerPhysicalShapeOutcome as c1, type DeclaredNameResolver as c2, type BindingNameRegistry as c3, type QueryScope as c4, type RelationTargetProjectionRegistry as c5, type ComparePgDatabaseSchemaOptions$1 as c6, type ComparePgDeclaredAdoptionSchemaInput as c7, type CompareSchemataOptions$1 as c8, type ConvergePgBaseOptions as c9, modelForDeclaredAdoption as cA, openPgOutcomeClaim as cB, openPgOutcomeClaimGroup as cC, pgDeclaredAdoptionDeclaration as cD, pgDeclaredSequenceAdoptionDeclaration as cE, readPgLedgerReservationsForPair as cF, recoverPgAdmittedReaddressPair as cG, recoverPgOutcomeClaim as cH, resolvePgDestructiveOutcome as cI, resolvePgOutcomeClaimGroup as cJ, type ConvergePgCheckOptions as ca, type GenerateDDLOptions$1 as cb, type MigrationSQLOptions$1 as cc, type PgAdoptionComparisonExecutor as cd, PgCommitAcknowledgementAmbiguousError as ce, appendPgLedgerClaim as cf, appendPgLedgerClaimGroup as cg, appendPgLedgerProgress as ch, appendPgLedgerRelease as ci, appendPgLedgerResolution as cj, appendPgLedgerResolutionGroup as ck, appendPgOutcomeResolution as cl, classifyPgLedgerPhysicalShape as cm, collectReferencedKeyRemovalConflicts as cn, comparePgDatabaseSchema$1 as co, comparePgDeclaredAdoptionSchema as cp, compareSchemata$1 as cq, convergePg as cr, createPgDeclaredAdoptionStep as cs, createPgDeclaredSequenceAdoptionStep as ct, createPgLedgerShapeAllowance as cu, executePgDestructiveOutcome as cv, generateDDL$1 as cw, generateDownSQL$1 as cx, generateMigrationSQL$1 as cy, lockPgJournalRun as cz, type PgOutcomeCheckpointObserver as d, type ConvergePgOptions as e, type PgPhysicalModel as f, type PgConvergeResult as g, type PgConvergeCheckResult as h, type PgLedgerScopeCurrency as i, AutoIncrementTransitionUnsupportedError as j, type CanonicalizeCheckConstraintsOptions as k, CheckConstraintCanonicalizationError as l, type CheckConstraintCanonicalizationWarning as m, CheckConstraintNewEnumValueError as n, ColumnDefaultCanonicalizationError as o, type ColumnDefaultCanonicalizationWarning as p, type ComparePgDatabaseSchemaOptions as q, readTransitionJournal as r, type CompareSchemataOptions as s, DEFAULT_PK_COLUMN as t, type DetectedHierarchy as u, type DiffSummary as v, type ExpressionCanonicalizationWarning as w, type ExpressionHandler as x, ExpressionKeyedIndexPredicateCanonicalizationUnsupportedError as y, type GenerateDDLOptions as z };