@dbsp/core 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _dbsp_types from '@dbsp/types';
2
- import { PseudoColumnMetadata, RecursiveMetadata, RelationIR, RelationKind, AdapterCapabilities, Adapter, BaseAdapter, DDLGeneratingAdapter, ExecutingAdapter, IntrospectingAdapter, RawSqlAdapter, StreamingAdapter, TransactionalAdapter, ColumnType, WhereIntent, OnDeleteAction, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, TableIR, EnumIR, SequenceIR, AmbiguityCheckResult, DialectCapabilities, DDLFeature, DDLFeatureVersionRange, SelectIntent, IncludeIntent, AggregateIntent, OrderByIntent, SortDirection, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, Dump, SetOperationIntent, LockStrength, LockWaitPolicy, DumpMeta, JoinIntent, UnnestCteIntent, CteQueryIntent, CompileOptions, CompiledQuery, MutationIntent as MutationIntent$1, DumpSequenceStep, UpsertConflictTarget, UpsertConflictAction, RawCteIntent, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions, IndexInfo, ExpressionIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, WhereExpressionIntent, AggOrderByArg, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, SubqueryIncludeInfo } from '@dbsp/types';
3
- export { Adapter, AdapterCapabilities, AdapterLogger, AdapterStreamOptions, AdjacencyTraversal, AggregateExpressionIntent, AggregateFunction, AggregateIntent, AggregateWindowFunction, AliasIncludedColumnsMode, AlterColumnOptions, AmbiguityCheckResult, ArrayOperator, BaseAdapter, CTEDefinition, Cardinality, CaseExpressionIntent, CoalesceExpressionIntent, ColumnAliasIntent, ColumnExpressionIntent, ColumnIR, ColumnType, CommonColumnType, ComparisonExpressionIntent, ComparisonOperator, CompileOnlyAdapter, CompileOptions, CompileResultWithIncludes, CompiledQuery, CompilingAdapter, CreateIndexOptions, CustomTraversal, DDLGeneratingAdapter, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, EdgeTableTraversal, EmitJoinClause, ExecutingAdapter, ExpressionIntent, FilterStrategy, ForeignKeyIR, IncludeIntent, IncludeStrategy, IndexColumnDef, IndexIR, IndexInfo, IndexMethod, InsertFromIntent, InsertIntent, IntrospectingAdapter, IsTypeSupported, JoinDefault, JoinIntent, LiteralExpressionIntent, LogicalOperator, MSSQLColumnType, ModelIR, MutationIntent, MySQLColumnType, NullOperator, NullsPosition, OffsetWindowFunction, OnDeleteAction, Optionality, OrderByIntent, PartitionIR, PlanDecision, PlanOptions, PlanReport, PlanWarning, PlanWarningCode, PostgresColumnType, PostgresOnlyColumnType, PseudoColumnExpressionIntent, PseudoColumnMetadata, PseudoColumnTraversal, QueryIntent, RangeOperator, RangeValue, RankingWindowFunction, RawExpressionIntent, RawSqlAdapter, RecursiveAdvancedOptions, RecursiveDedupe, RecursiveDirection, RecursiveEmitOptions, RecursiveExistsOptions, RecursiveIntent, RecursiveMetadata, RecursiveNodeIdExpr, RecursivePlanOptions, RecursivePlanReport, RecursiveTrackOptions, RecursiveTraversal, RelationColumnIntent, RelationIR, RelationKind, RelationOperator, RelationType, ResolvedIncludeStrategy, SQLiteColumnType, SelectAggregateIntent, SelectAllIntent, SelectFieldsIntent, SelectIntent, SelectWithExpressionsIntent, SortDirection, StreamingAdapter, StringOperator, SubqueryIncludeInfo, SubqueryRefIntent, SupportedColumnTypes, TableIR, TransactionalAdapter, TruncateOptions, UpdateIntent, UpsertConflictAction, UpsertConflictTarget, UpsertFromIntent, UpsertIntent, VacuumOptions, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereExistsIntent, WhereInIntent, WhereIntent, WhereLikeIntent, WhereNotExistsIntent, WhereNotIntent, WhereNullIntent, WhereOrIntent, WhereRangeIntent, WhereRelationFilterIntent, WhereSubqueryIntent, WindowFunction, WindowIntent, WindowOrderBy, getNodeIdAlias, isAdjacencyTraversal, isAggregateWindowFunction, isCoalesceExpression, isColumnAliasExpression, isCustomTraversal, isDeleteIntent, isEdgeTableTraversal, isInsertIntent, isMutationIntent, isRankingWindowFunction, isRawExpression, isRecursiveIntent, isRelationColumnExpression, isSelectAggregate, isSelectAll, isSelectFields, isSelectWithExpressions, isSubqueryRef, isUpdateIntent, isUpsertIntent, isWhereAnd, isWhereAny, isWhereComparison, isWhereExists, isWhereIn, isWhereLike, isWhereLogical, isWhereNot, isWhereNotExists, isWhereNull, isWhereOr, isWhereRange, isWhereRelationBased, isWhereRelationFilter, isWhereSubquery, isWindowIntent } from '@dbsp/types';
2
+ import { PseudoColumnMetadata, RecursiveMetadata, RelationIR, RelationKind, AdapterCapabilities, Adapter, BaseAdapter, DDLGeneratingAdapter, ExecutingAdapter, IntrospectingAdapter, RawSqlAdapter, StreamingAdapter, TransactionalAdapter, ColumnType, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, ObservationContext, TransitionConnectionPool, IssuedObservation, RecoveryArtefact, FingerprintManifest, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, DurableIntentRecord, OperationEffectAssessment, ObservationIssuer, ApplyGuard, OperationExecutionOutcome, TransactionalCompletionRecord, StepJournal, TransitionRule, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, CheckConstraintIR, Comparator, EnumIR, ObservationRequest, EvidenceView, AdvisoryObservationId, AssumptionId, ClaimId, EvidenceId, SemanticArtifactId, IndexIR, ResourceAddress, ResourceSelector, ApplyPolicy, ApplyResult, TransitionCandidate, TransitionFragmentComposition, PlanAssessment, CompareOutcome, TransitionFragment, ProofClaim, Assumption, ProvenPlanShape, ApplicableAssessment, TransitionRunJournal, InapplicableAssessment, TableIR, SequenceIR, AmbiguityCheckResult, DialectCapabilities, DDLFeature, DDLFeatureVersionRange, SelectIntent, IncludeIntent, AggregateIntent, OrderByIntent, SortDirection, InsertIntent, InsertFromIntent, UpdateIntent, BatchUpdateIntent, DeleteIntent, UpsertIntent, UpsertFromIntent, TransactionBeginOptions, Dump, SetOperationIntent, LockStrength, LockWaitPolicy, DumpMeta, JoinIntent, UnnestCteIntent, CteQueryIntent, CompileOptions, CompiledQuery, MutationIntent as MutationIntent$1, DumpSequenceStep, UpsertConflictTarget, UpsertConflictAction, RawCteIntent, TruncateOptions, VacuumOptions, AlterColumnOptions, CreateIndexOptions, DropIndexOptions, IndexInfo, TransactionOptions, PinnedConnectionOptions, ExpressionIntent, ComparisonOperator, WhereSubqueryIntent, SubqueryRefIntent, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereRelationFilterIntent, RecursiveExistsOptions, WhereExistsIntent, WhereInIntent, WhereNullIntent, WhereLikeIntent, WhereNotIntent, WhereNotExistsIntent, WhereOrIntent, WhereRawExistsIntent, WhereRawNotExistsIntent, WhereExpressionIntent, AggOrderByArg, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, SubqueryIncludeInfo } from '@dbsp/types';
3
+ export { Adapter, AdapterCapabilities, AdapterLogger, AdapterStreamOptions, AdjacencyTraversal, AggregateExpressionIntent, AggregateFunction, AggregateIntent, AggregateWindowFunction, AliasIncludedColumnsMode, AlterColumnOptions, AmbiguityCheckResult, ApplicableAssessment, ApplicableEvaluation, ApplyPolicy, ArrayOperator, Assumption, BaseAdapter, CTEDefinition, CapabilityDescriptor, Cardinality, CaseExpressionIntent, CoalesceExpressionIntent, ColumnAliasIntent, ColumnExpressionIntent, ColumnIR, ColumnJsReadType, ColumnType, CommonColumnType, Comparator, CompareOutcome, ComparisonExpressionIntent, ComparisonOperator, CompileOnlyAdapter, CompileOptions, CompileResultWithIncludes, CompiledQuery, CompilingAdapter, CreateIndexOptions, CustomTraversal, DDLGeneratingAdapter, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, DurableIntentRecord, EdgeTableTraversal, EmitJoinClause, ExecutingAdapter, ExpressionIntent, FilterStrategy, FingerprintManifest, ForeignKeyIR, InapplicableAssessment, IncludeIntent, IncludeStrategy, IndexColumnDef, IndexIR, IndexInfo, IndexMethod, InsertFromIntent, InsertIntent, IntrospectingAdapter, IsTypeSupported, JoinDefault, JoinIntent, LiteralExpressionIntent, LogicalIdentity, LogicalIdentityCarrier, LogicalOperator, MSSQLColumnType, ModelIR, MutationIntent, MySQLColumnType, NullOperator, NullsPosition, ObservationContext, ObservationIssuer, ObservationRequest, OffsetWindowFunction, OnDeleteAction, OperationEffectAssessment, OperationSemantics, Optionality, OrderByIntent, PartitionIR, PhysicalOperation, PlanDecision, PlanOptions, PlanReport, PlanWarning, PlanWarningCode, PostgresColumnType, PostgresOnlyColumnType, ProvenApplyGuard, ProvenGuardProtocol, ProvenPlanShape, ProvenPlanStep, PseudoColumnExpressionIntent, PseudoColumnMetadata, PseudoColumnTraversal, QueryIntent, RangeOperator, RangeValue, RankingWindowFunction, RawExpressionIntent, RawSqlAdapter, RecognitionResult, RecursiveAdvancedOptions, RecursiveDedupe, RecursiveDirection, RecursiveEmitOptions, RecursiveExistsOptions, RecursiveIntent, RecursiveMetadata, RecursiveNodeIdExpr, RecursivePlanOptions, RecursivePlanReport, RecursiveTrackOptions, RecursiveTraversal, RelationColumnIntent, RelationIR, RelationKind, RelationOperator, RelationType, RequiredEnumLabelIR, ResolvedIncludeStrategy, ResourceAddress, RuleEvaluation, RuleSupport, SQLiteColumnType, SelectAggregateIntent, SelectAllIntent, SelectFieldsIntent, SelectIntent, SelectWithExpressionsIntent, SerializedProvenPlan, SortDirection, StepJournal, StreamingAdapter, StringOperator, SubqueryIncludeInfo, SubqueryRefIntent, SupportedColumnTypes, TableIR, TransactionOptions, TransactionalAdapter, TransactionalCompletionRecord, TransitionCandidate, TransitionConnectionPool, TransitionQueryClient, TransitionRule, TransitionRunMetadata, TruncateOptions, UpdateIntent, UpsertConflictAction, UpsertConflictTarget, UpsertFromIntent, UpsertIntent, VacuumOptions, WhereAndIntent, WhereAnyIntent, WhereComparisonIntent, WhereExistsIntent, WhereInIntent, WhereIntent, WhereLikeIntent, WhereNotExistsIntent, WhereNotIntent, WhereNullIntent, WhereOrIntent, WhereRangeIntent, WhereRelationFilterIntent, WhereSubqueryIntent, WindowFunction, WindowIntent, WindowOrderBy, getNodeIdAlias, isAdjacencyTraversal, isAggregateWindowFunction, isCoalesceExpression, isColumnAliasExpression, isCustomTraversal, isDeleteIntent, isEdgeTableTraversal, isInsertIntent, isMutationIntent, isRankingWindowFunction, isRawExpression, isRecursiveIntent, isRelationColumnExpression, isSelectAggregate, isSelectAll, isSelectFields, isSelectWithExpressions, isSubqueryRef, isUpdateIntent, isUpsertIntent, isWhereAnd, isWhereAny, isWhereComparison, isWhereExists, isWhereIn, isWhereLike, isWhereLogical, isWhereNot, isWhereNotExists, isWhereNull, isWhereOr, isWhereRange, isWhereRelationBased, isWhereRelationFilter, isWhereSubquery, isWindowIntent } from '@dbsp/types';
4
4
  import { NqlCompilerOptions } from '@dbsp/nql';
5
5
 
6
6
  /**
@@ -560,11 +560,15 @@ declare function isAliasedColumn(value: unknown): value is AliasedColumn<string,
560
560
  * Matches SchemaColumnType from schema.ts.
561
561
  */
562
562
  type SchemaColumnType$1 = 'string' | 'text' | 'uuid' | 'number' | 'integer' | 'decimal' | 'bigint' | 'boolean' | 'date' | 'time' | 'datetime' | 'timestamp' | 'json' | 'jsonb' | 'daterange' | 'tsrange' | 'tstzrange' | 'int4range' | 'int8range' | 'numrange';
563
+ /** JavaScript read-side representation for PostgreSQL bigint/int8 values. */
564
+ type ColumnJsReadType = 'bigint' | 'number' | 'string';
563
565
  /**
564
566
  * Column definition - short form or long form.
565
567
  */
566
568
  type ColumnDef$1 = SchemaColumnType$1 | {
567
569
  type: SchemaColumnType$1;
570
+ dbType?: string;
571
+ js?: ColumnJsReadType;
568
572
  nullable?: boolean;
569
573
  unique?: boolean;
570
574
  primaryKey?: boolean;
@@ -587,6 +591,7 @@ interface RefOptionsShape {
587
591
  inverse?: string;
588
592
  nullable?: boolean;
589
593
  unique?: boolean;
594
+ js?: ColumnJsReadType;
590
595
  onDelete?: string;
591
596
  onUpdate?: string;
592
597
  roles?: unknown;
@@ -609,27 +614,57 @@ type IsRef<T> = T extends {
609
614
  * Extract the column type from a ColumnDef.
610
615
  */
611
616
  type ExtractColumnType$1<C> = C extends SchemaColumnType$1 ? C : C extends {
612
- type: infer T extends SchemaColumnType$1;
617
+ readonly type: infer T extends SchemaColumnType$1;
613
618
  } ? T : never;
614
619
  /**
615
620
  * Check if a column is nullable.
616
621
  */
617
622
  type IsNullable$1<C> = C extends {
618
- nullable: true;
623
+ readonly nullable: true;
619
624
  } ? true : false;
620
625
  /**
621
626
  * Map schema column types to TypeScript types.
622
627
  */
623
628
  type MapColumnTypeToTS<T extends SchemaColumnType$1> = T extends 'string' | 'text' | 'uuid' ? string : T extends 'number' | 'integer' | 'decimal' ? number : T extends 'bigint' ? bigint : T extends 'boolean' ? boolean : T extends 'date' | 'time' | 'datetime' | 'timestamp' ? Date : T extends 'json' | 'jsonb' ? unknown : T extends 'daterange' | 'tsrange' | 'tstzrange' | 'int4range' | 'int8range' | 'numrange' ? unknown : unknown;
624
629
  /**
625
- * Infer the TypeScript type for a column definition.
630
+ * Infer the non-null TypeScript type for a column definition.
631
+ */
632
+ type InferColumnNonNullTSType<C extends ColumnDef$1> = ExtractColumnType$1<C> extends 'bigint' ? C extends {
633
+ readonly js: 'number';
634
+ } ? number : C extends {
635
+ readonly js: 'bigint';
636
+ } ? bigint : C extends {
637
+ readonly js: 'string';
638
+ } ? string : MapColumnTypeToTS<ExtractColumnType$1<C>> : MapColumnTypeToTS<ExtractColumnType$1<C>>;
639
+ /**
640
+ * Infer the non-null TypeScript type for a ref-backed FK column.
641
+ */
642
+ type InferRefColumnNonNullTSType<R extends RefDefinition$1> = R extends {
643
+ readonly options: {
644
+ readonly js: 'number';
645
+ };
646
+ } ? number : R extends {
647
+ readonly options: {
648
+ readonly js: 'bigint';
649
+ };
650
+ } ? bigint : R extends {
651
+ readonly options: {
652
+ readonly js: 'string';
653
+ };
654
+ } ? string : number | string;
655
+ /**
656
+ * Infer the TypeScript type for a column or ref-backed FK definition.
626
657
  */
627
- type InferColumnTSType<C> = IsRef<C> extends true ? never : C extends ColumnDef$1 ? IsNullable$1<C> extends true ? MapColumnTypeToTS<ExtractColumnType$1<C>> | null : MapColumnTypeToTS<ExtractColumnType$1<C>> : never;
658
+ type InferColumnTSType<C> = C extends RefDefinition$1 ? C extends {
659
+ readonly options: {
660
+ readonly nullable: true;
661
+ };
662
+ } ? InferRefColumnNonNullTSType<C> | null : InferRefColumnNonNullTSType<C> : C extends ColumnDef$1 ? IsNullable$1<C> extends true ? InferColumnNonNullTSType<C> | null : InferColumnNonNullTSType<C> : never;
628
663
  /**
629
- * Extract only column definitions (not refs) from a TableDef.
664
+ * Extract user-visible column definitions, including ref-backed FK columns.
630
665
  */
631
666
  type ExtractColumns<T extends TableDef$1> = {
632
- [K in keyof T as IsRef<T[K]> extends true ? never : K]: T[K];
667
+ [K in keyof T as T[K] extends ColumnDef$1 | RefDefinition$1 ? K : never]: T[K];
633
668
  };
634
669
  /**
635
670
  * Extract only ref definitions from a TableDef.
@@ -740,6 +775,7 @@ type SchemaColumnType = ColumnType;
740
775
  */
741
776
  type ColumnDef = SchemaColumnType | {
742
777
  type: SchemaColumnType;
778
+ js?: ColumnJsReadType$1;
743
779
  dbType?: string;
744
780
  nullable?: boolean;
745
781
  unique?: boolean;
@@ -772,6 +808,8 @@ interface RefOptions {
772
808
  nullable?: boolean;
773
809
  /** Is this FK unique? → 1:1 instead of 1:N */
774
810
  unique?: boolean;
811
+ /** Optional read-side JavaScript representation for bigint/int8 FK columns */
812
+ js?: ColumnJsReadType$1;
775
813
  /** ON DELETE action */
776
814
  onDelete?: OnDeleteAction;
777
815
  /** ON UPDATE action */
@@ -1045,19 +1083,30 @@ type InferColumnType<T extends SchemaColumnType> = T extends 'string' | 'text' |
1045
1083
  * Extracts the type string from a ColumnDef (handles short and long forms).
1046
1084
  */
1047
1085
  type ExtractColumnType<C extends ColumnDef> = C extends SchemaColumnType ? C : C extends {
1048
- type: infer T extends SchemaColumnType;
1086
+ readonly type: infer T extends SchemaColumnType;
1049
1087
  } ? T : never;
1050
1088
  /**
1051
1089
  * Checks if a ColumnDef is nullable.
1052
1090
  */
1053
1091
  type IsNullable<C extends ColumnDef> = C extends {
1054
- nullable: true;
1092
+ readonly nullable: true;
1055
1093
  } ? true : false;
1094
+ /**
1095
+ * Infers the non-null TypeScript type for a single column definition.
1096
+ * Bigint keeps its existing default type unless an explicit read-side js type is set.
1097
+ */
1098
+ type InferColumnNonNull<C extends ColumnDef> = ExtractColumnType<C> extends 'bigint' ? C extends {
1099
+ readonly js: 'number';
1100
+ } ? number : C extends {
1101
+ readonly js: 'bigint';
1102
+ } ? bigint : C extends {
1103
+ readonly js: 'string';
1104
+ } ? string : InferColumnType<ExtractColumnType<C>> : InferColumnType<ExtractColumnType<C>>;
1056
1105
  /**
1057
1106
  * Infers the TypeScript type for a single column definition.
1058
1107
  * Handles both short form ('string') and long form ({ type: 'string', nullable: true }).
1059
1108
  */
1060
- type InferColumn<C extends ColumnDef> = IsNullable<C> extends true ? InferColumnType<ExtractColumnType<C>> | null : InferColumnType<ExtractColumnType<C>>;
1109
+ type InferColumn<C extends ColumnDef> = IsNullable<C> extends true ? InferColumnNonNull<C> | null : InferColumnNonNull<C>;
1061
1110
  /**
1062
1111
  * Infers the FK column type from a RefDefinition.
1063
1112
  *
@@ -1079,11 +1128,24 @@ type InferColumn<C extends ColumnDef> = IsNullable<C> extends true ? InferColumn
1079
1128
  * authorId: ref('users') // Type: number | string
1080
1129
  * editorId: ref('users', { nullable: true }) // Type: number | string | null
1081
1130
  */
1131
+ type InferRefColumnNonNull<R extends RefDefinition> = R extends {
1132
+ readonly options: {
1133
+ readonly js: 'number';
1134
+ };
1135
+ } ? number : R extends {
1136
+ readonly options: {
1137
+ readonly js: 'bigint';
1138
+ };
1139
+ } ? bigint : R extends {
1140
+ readonly options: {
1141
+ readonly js: 'string';
1142
+ };
1143
+ } ? string : number | string;
1082
1144
  type InferRefColumn<R extends RefDefinition> = R extends {
1083
- options: {
1084
- nullable: true;
1145
+ readonly options: {
1146
+ readonly nullable: true;
1085
1147
  };
1086
- } ? number | string | null : number | string;
1148
+ } ? InferRefColumnNonNull<R> | null : InferRefColumnNonNull<R>;
1087
1149
  /**
1088
1150
  * Infers the row type for a single table definition.
1089
1151
  * Maps each column to its TypeScript type.
@@ -1141,7 +1203,7 @@ type InferSchemaDB<S extends Schema<SchemaDefinition>> = S extends Schema<infer
1141
1203
  * parentId: ref('categories', { roles: { parent: 'parent', children: 'children' } })
1142
1204
  * ```
1143
1205
  */
1144
- declare function ref$1<TTarget extends string, TOptions extends RefOptions = Record<string, never>>(target: TTarget, options?: TOptions): RefDefinition<TTarget, TOptions>;
1206
+ declare function ref$1<const TTarget extends string, const TOptions extends RefOptions = Record<string, never>>(target: TTarget, options?: TOptions): RefDefinition<TTarget, TOptions>;
1145
1207
  /**
1146
1208
  * Type guard for RefDefinition.
1147
1209
  */
@@ -1170,7 +1232,7 @@ declare function isRef(value: ColumnDef | RefDefinition): value is RefDefinition
1170
1232
  * const orm = createOrm({ model: db.model, adapter });
1171
1233
  * ```
1172
1234
  */
1173
- declare function schema<T extends SchemaDefinition>(definition: T, constraints?: SchemaConstraints, options?: SchemaOptions, extras?: SchemaExtras): Schema<T>;
1235
+ declare function schema<const T extends SchemaDefinition>(definition: T, constraints?: SchemaConstraints, options?: SchemaOptions, extras?: SchemaExtras): Schema<T>;
1174
1236
  /**
1175
1237
  * Validation error during schema conversion.
1176
1238
  */
@@ -1334,6 +1396,337 @@ declare class UnsupportedStrategyError extends Error {
1334
1396
  constructor(message: string);
1335
1397
  }
1336
1398
 
1399
+ type ObservationContextMergeResult = {
1400
+ readonly ok: true;
1401
+ readonly context: ObservationContext;
1402
+ } | {
1403
+ readonly ok: false;
1404
+ readonly detail: string;
1405
+ };
1406
+
1407
+ interface OperationFingerprints {
1408
+ readonly expectedBefore: FingerprintManifest;
1409
+ readonly expectedAfter: FingerprintManifest;
1410
+ }
1411
+ interface RegisteredOperationSemantics extends OperationSemantics {
1412
+ readonly operationKind?: OperationKindRef;
1413
+ supportsOperation?(operation: PhysicalOperation): boolean;
1414
+ buildFingerprints(operation: PhysicalOperation, evidence: readonly EvidenceObservation[], context: ObservationContext): OperationFingerprints;
1415
+ }
1416
+ interface OperationObservation {
1417
+ readonly observations: readonly IssuedObservation[];
1418
+ readonly fingerprint: FingerprintManifest;
1419
+ }
1420
+ interface ComparatorNameNormalizer {
1421
+ /**
1422
+ * Normalize identifiers from the observed/current model into the namespace
1423
+ * used by authored desired models before comparator matching runs.
1424
+ */
1425
+ normalizeCurrentIdentifier(identifier: string): string;
1426
+ }
1427
+ interface CompositionFactSatisfactionOwner {
1428
+ readonly compositionFactKinds: readonly string[];
1429
+ satisfiesCompositionFact(fact: TransitionCompositionFact, current: ModelIR, context: ObservationContext): boolean;
1430
+ }
1431
+ type RulePrecedenceFact = {
1432
+ readonly higher: RuleRef;
1433
+ readonly lower: RuleRef;
1434
+ readonly reason: string;
1435
+ };
1436
+ interface GuardExecutionResult {
1437
+ readonly passed: boolean;
1438
+ readonly observations: readonly IssuedObservation[];
1439
+ readonly recovery: readonly RecoveryArtefact[];
1440
+ }
1441
+ interface TransitionExecutionClient {
1442
+ readonly opaqueClient: unknown;
1443
+ }
1444
+ interface NonRollbackableExecutionTracker {
1445
+ markNonRollbackableOperationExecuted(): void;
1446
+ }
1447
+ interface ExecutionCoordinator {
1448
+ readonly transactionDomain: string;
1449
+ checkout(target: TransitionConnectionPool): Promise<TransitionExecutionClient>;
1450
+ release(client: TransitionExecutionClient, error?: unknown): Promise<void> | void;
1451
+ begin(client: TransitionExecutionClient): Promise<void>;
1452
+ setLockTimeout(client: TransitionExecutionClient, maxWaitMs: number): Promise<void>;
1453
+ commit(client: TransitionExecutionClient): Promise<void>;
1454
+ rollback(client: TransitionExecutionClient): Promise<void>;
1455
+ isLockTimeout(error: unknown): boolean;
1456
+ }
1457
+ interface TransactionCoordinatorBinding {
1458
+ readonly coordinator: ExecutionCoordinator;
1459
+ readonly transactionDomain: string;
1460
+ }
1461
+ interface OperationRuntime extends RegisteredOperationSemantics {
1462
+ checkout(target: TransitionConnectionPool): Promise<TransitionExecutionClient>;
1463
+ release(client: TransitionExecutionClient, error?: unknown): Promise<void> | void;
1464
+ writeIntentJournal(client: TransitionExecutionClient, record: DurableIntentRecord): Promise<void>;
1465
+ begin(client: TransitionExecutionClient): Promise<void>;
1466
+ setLockTimeout(client: TransitionExecutionClient, maxWaitMs: number): Promise<void>;
1467
+ acquireLocks(client: TransitionExecutionClient, operation: PhysicalOperation, effects: OperationEffectAssessment, context: ObservationContext): Promise<void>;
1468
+ observeContext(client: TransitionExecutionClient, operation: PhysicalOperation, proofContext: ObservationContext): Promise<ObservationContext>;
1469
+ observeOperation(client: TransitionExecutionClient, operation: PhysicalOperation, context: ObservationContext, phase: 'before' | 'after', issuer: ObservationIssuer): Promise<OperationObservation>;
1470
+ checkGuard(client: TransitionExecutionClient, operation: PhysicalOperation, guard: ApplyGuard, context: ObservationContext): Promise<GuardExecutionResult>;
1471
+ executeOperation(client: TransitionExecutionClient, operation: PhysicalOperation, context: ObservationContext, duringGuards?: readonly ApplyGuard[], executionTracker?: NonRollbackableExecutionTracker): Promise<OperationExecutionOutcome>;
1472
+ writeCompletionJournal(client: TransitionExecutionClient, operation: PhysicalOperation, record: TransactionalCompletionRecord): Promise<void>;
1473
+ commit(client: TransitionExecutionClient): Promise<void>;
1474
+ rollback(client: TransitionExecutionClient): Promise<void>;
1475
+ writeObservedJournal(client: TransitionExecutionClient, journal: StepJournal): Promise<void>;
1476
+ isLockTimeout(error: unknown): boolean;
1477
+ }
1478
+ interface TransitionPack {
1479
+ readonly rules: readonly TransitionRule[];
1480
+ readonly operationSemantics: readonly RegisteredOperationSemantics[];
1481
+ readonly issuer: ObservationIssuer;
1482
+ readonly executionCoordinator?: ExecutionCoordinator;
1483
+ readonly transactionDomain?: string;
1484
+ readonly equivalence?: EquivalenceCapability;
1485
+ readonly capabilityDescriptors?: readonly CapabilityDescriptor[];
1486
+ readonly comparatorNameNormalizer?: ComparatorNameNormalizer;
1487
+ readonly compositionFactKinds?: CompositionFactSatisfactionOwner['compositionFactKinds'];
1488
+ readonly satisfiesCompositionFact?: CompositionFactSatisfactionOwner['satisfiesCompositionFact'];
1489
+ readonly rulePrecedence?: readonly RulePrecedenceFact[];
1490
+ }
1491
+ type OperationResolution = {
1492
+ readonly ok: true;
1493
+ readonly semantics: RegisteredOperationSemantics;
1494
+ } | {
1495
+ readonly ok: false;
1496
+ readonly detail: string;
1497
+ };
1498
+ declare function serverVersionNum(engineVersion: string): number | undefined;
1499
+ declare function isOperationRuntime(semantics: RegisteredOperationSemantics): semantics is OperationRuntime;
1500
+ type RulePrecedenceResolution = {
1501
+ readonly ok: true;
1502
+ readonly rule: TransitionRule;
1503
+ readonly facts: readonly RulePrecedenceFact[];
1504
+ readonly reason: string;
1505
+ } | {
1506
+ readonly ok: false;
1507
+ readonly detail: string;
1508
+ };
1509
+ declare class PackRegistry {
1510
+ private readonly rules;
1511
+ private readonly operationSemantics;
1512
+ private readonly issuers;
1513
+ private readonly rulePrecedence;
1514
+ private readonly issuerByArtifact;
1515
+ private readonly equivalenceByArtifact;
1516
+ private readonly compositionFactOwnerByKind;
1517
+ private readonly capabilityDescriptors;
1518
+ private readonly nameNormalizer;
1519
+ private readonly privilegeMergers;
1520
+ private readonly transactionCoordinatorBySemantics;
1521
+ constructor(packs: readonly TransitionPack[]);
1522
+ allRules(): readonly TransitionRule[];
1523
+ defaultIssuer(): ObservationIssuer | undefined;
1524
+ comparatorNameNormalizer(): ComparatorNameNormalizer | undefined;
1525
+ resolveRule(ref: RuleRef): TransitionRule | undefined;
1526
+ resolveRulePrecedence(rules: readonly TransitionRule[]): RulePrecedenceResolution;
1527
+ resolveIssuer(ref?: SemanticArtifactRef): ObservationIssuer | undefined;
1528
+ resolveEquivalence(ref?: SemanticArtifactRef): EquivalenceCapability | undefined;
1529
+ contextWithDerivedCapabilities(context: ObservationContext): ObservationContext;
1530
+ mergeObservationContexts(left: ObservationContext, right: ObservationContext): ObservationContextMergeResult;
1531
+ satisfiesCompositionFact(fact: Parameters<CompositionFactSatisfactionOwner['satisfiesCompositionFact']>[0], current: ModelIR, context: ObservationContext): boolean;
1532
+ resolveOperation(operation: PhysicalOperation): OperationResolution;
1533
+ transactionCoordinatorFor(semantics: RegisteredOperationSemantics): TransactionCoordinatorBinding | undefined;
1534
+ }
1535
+ declare function createPackRegistry(packs: readonly TransitionPack[]): PackRegistry;
1536
+
1537
+ declare function createApplier(registry: PackRegistry): Applier;
1538
+
1539
+ type CheckSetEntry = Pick<CheckConstraintIR, 'name' | 'expression' | 'notValid'>;
1540
+ type CheckDelta = {
1541
+ readonly kind: 'none';
1542
+ } | {
1543
+ readonly kind: 'add-check';
1544
+ readonly check: CheckSetEntry;
1545
+ readonly expectedBefore: readonly CheckSetEntry[];
1546
+ readonly expectedAfter: readonly CheckSetEntry[];
1547
+ } | {
1548
+ readonly kind: 'expression-mismatch';
1549
+ readonly desired: CheckSetEntry;
1550
+ readonly current: CheckSetEntry;
1551
+ readonly expectedBefore: readonly CheckSetEntry[];
1552
+ readonly expectedAfter: readonly CheckSetEntry[];
1553
+ } | {
1554
+ readonly kind: 'unsupported';
1555
+ };
1556
+ declare function checkDelta(desiredChecks: readonly CheckConstraintIR[] | undefined, currentChecks: readonly CheckConstraintIR[] | undefined): CheckDelta;
1557
+
1558
+ declare function createComparator(registry: PackRegistry): Comparator;
1559
+
1560
+ type EnumAddDelta = {
1561
+ readonly kind: 'none';
1562
+ } | {
1563
+ readonly kind: 'add-label';
1564
+ readonly label: string;
1565
+ readonly after?: string;
1566
+ } | {
1567
+ readonly kind: 'unsupported';
1568
+ };
1569
+ interface EnumAddDeltaOptions {
1570
+ readonly targetSchema?: string;
1571
+ }
1572
+ declare function resolveEnumSchemaForComparison(enumDef: EnumIR, targetSchema?: string): EnumIR;
1573
+ declare function enumAddDelta(desired: EnumIR, current: EnumIR, options?: EnumAddDeltaOptions): EnumAddDelta;
1574
+
1575
+ declare function createEvidenceView(params: {
1576
+ readonly evidence: readonly EvidenceObservation[];
1577
+ readonly context: ObservationContext;
1578
+ readonly requests?: readonly ObservationRequest[];
1579
+ }): EvidenceView;
1580
+
1581
+ declare function semanticArtifactId(value: string): SemanticArtifactId;
1582
+ declare function assumptionId(value: string): AssumptionId;
1583
+ declare function claimId(value: string): ClaimId;
1584
+ declare function evidenceId(value: string): EvidenceId;
1585
+ declare function advisoryObservationId(value: string): AdvisoryObservationId;
1586
+
1587
+ type IndexSetEntry = {
1588
+ readonly name: string;
1589
+ readonly columns: readonly string[];
1590
+ readonly unique?: boolean;
1591
+ readonly valid?: boolean;
1592
+ readonly ready?: boolean;
1593
+ readonly method?: string;
1594
+ readonly where?: string;
1595
+ readonly expressions?: readonly string[];
1596
+ readonly include?: readonly string[];
1597
+ readonly opclass?: Readonly<Record<string, string>>;
1598
+ readonly with?: Readonly<Record<string, string>>;
1599
+ readonly nullsNotDistinct?: boolean;
1600
+ };
1601
+ type IndexDelta = {
1602
+ readonly kind: 'none';
1603
+ } | {
1604
+ readonly kind: 'add-unique-index';
1605
+ readonly index: IndexSetEntry;
1606
+ readonly expectedBefore: readonly IndexSetEntry[];
1607
+ readonly expectedAfter: readonly IndexSetEntry[];
1608
+ } | {
1609
+ readonly kind: 'unsupported';
1610
+ };
1611
+ declare function defaultIndexName(tableName: string, index: Pick<IndexIR, 'name' | 'columns'>): string;
1612
+ type IndexPerspective = 'desired' | 'current';
1613
+ declare function normalizedIndex(tableName: string, index: IndexIR, perspective?: IndexPerspective): IndexSetEntry;
1614
+ declare function indexDelta(tableName: string, desiredIndexes: readonly IndexIR[], currentIndexes: readonly IndexIR[]): IndexDelta;
1615
+
1616
+ declare function createProver(registry: PackRegistry): Prover;
1617
+
1618
+ declare function resourceIsWithin(resource: ResourceAddress, parent: ResourceAddress): boolean;
1619
+ declare function selectorMatchesResource(selector: ResourceSelector, resource: ResourceAddress): boolean;
1620
+ declare function resourceScopeCovers(scope: readonly ResourceAddress[], required: readonly ResourceAddress[]): boolean;
1621
+
1622
+ interface StagedTransitionInput {
1623
+ readonly desired: ModelIR;
1624
+ readonly loadCurrent: () => Promise<ModelIR>;
1625
+ readonly readContext: () => Promise<ObservationContext>;
1626
+ readonly target: TransitionConnectionPool;
1627
+ readonly policy: ApplyPolicy;
1628
+ readonly maxIterations?: number;
1629
+ }
1630
+ interface StagedTransitionOrchestrator {
1631
+ applyStagedTransition(input: StagedTransitionInput): Promise<ApplyResult>;
1632
+ }
1633
+ declare function createStagedTransitionOrchestrator(registry: PackRegistry): StagedTransitionOrchestrator;
1634
+
1635
+ type TransitionCompare = Extract<CompareOutcome, {
1636
+ readonly kind: 'transitions';
1637
+ }>;
1638
+ interface StagedCompositionCandidate {
1639
+ readonly candidate: TransitionCandidate;
1640
+ readonly index: number;
1641
+ readonly composition?: TransitionFragmentComposition;
1642
+ readonly opRefs: readonly string[];
1643
+ }
1644
+ type StagedCompositionPreflight = {
1645
+ readonly kind: 'provable-in-stages';
1646
+ readonly ready: readonly StagedCompositionCandidate[];
1647
+ readonly pending: readonly StagedCompositionCandidate[];
1648
+ readonly detail?: string;
1649
+ } | {
1650
+ readonly kind: 'unsupported-transition';
1651
+ readonly assessment: PlanAssessment;
1652
+ };
1653
+ interface StagedCompositionPreflightInput {
1654
+ readonly compare: TransitionCompare;
1655
+ readonly current: ModelIR;
1656
+ readonly context: ObservationContext;
1657
+ }
1658
+ declare function preflightStagedComposition(registry: PackRegistry, input: StagedCompositionPreflightInput): StagedCompositionPreflight;
1659
+ declare function chooseReadyCandidate(preflight: Extract<StagedCompositionPreflight, {
1660
+ readonly kind: 'provable-in-stages';
1661
+ }>): StagedCompositionCandidate;
1662
+ declare function projectCompareToSingleCandidate(compare: TransitionCompare, entry: StagedCompositionCandidate): TransitionCompare;
1663
+
1664
+ type TransitionRelationalValidationInput = {
1665
+ readonly kind: 'fragment';
1666
+ readonly fragment: TransitionFragment;
1667
+ readonly claims: readonly ProofClaim[];
1668
+ readonly assumptions: readonly Assumption[];
1669
+ } | {
1670
+ readonly kind: 'plan';
1671
+ readonly plan: ProvenPlanShape;
1672
+ readonly operationEffectsByRef?: ReadonlyMap<string, OperationEffectAssessment>;
1673
+ };
1674
+ type TransitionRelationalValidationResult = {
1675
+ readonly ok: true;
1676
+ } | {
1677
+ readonly ok: false;
1678
+ readonly detail: string;
1679
+ };
1680
+ /**
1681
+ * Diagnostic consistency check for transition fragments and already-trusted,
1682
+ * in-process plans. For plan inputs this is not an untrusted serialized-plan
1683
+ * validator; apply() first requires the module-private minting capability, and
1684
+ * any later plan failure is a prover bug.
1685
+ */
1686
+ declare function validateTransitionRelationalInvariants(input: TransitionRelationalValidationInput): TransitionRelationalValidationResult;
1687
+
1688
+ type InProcessProvenPlan = ProvenPlanShape & {
1689
+ readonly __inProcessProvenPlan: unique symbol;
1690
+ };
1691
+ type EstablishedProofClaim = ProofClaim & {
1692
+ readonly assumes: readonly [];
1693
+ readonly derivedBy: {
1694
+ readonly conclusion: 'established';
1695
+ };
1696
+ };
1697
+ type ProveOutcome = {
1698
+ readonly kind: 'proven';
1699
+ readonly plan: InProcessProvenPlan;
1700
+ readonly assessment: ApplicableAssessment;
1701
+ } | {
1702
+ readonly kind: 'no-drift';
1703
+ readonly claim: EstablishedProofClaim;
1704
+ readonly assessment: ApplicableAssessment;
1705
+ } | {
1706
+ readonly kind: 'blocked';
1707
+ readonly assessment: PlanAssessment;
1708
+ } | {
1709
+ readonly kind: 'inapplicable';
1710
+ readonly assessment: InapplicableAssessment;
1711
+ readonly claim?: ProofClaim;
1712
+ };
1713
+ interface Prover {
1714
+ readonly artifact: SemanticArtifactRef;
1715
+ prove(compare: CompareOutcome, target: TransitionConnectionPool, context: ObservationContext): Promise<ProveOutcome>;
1716
+ }
1717
+ interface Applier {
1718
+ readonly artifact: SemanticArtifactRef;
1719
+ apply(proven: {
1720
+ readonly plan: InProcessProvenPlan;
1721
+ readonly assessment: ApplicableAssessment;
1722
+ }, policy: ApplyPolicy, target: TransitionConnectionPool): Promise<ApplyResult>;
1723
+ resume(runId: string, loadCurrent: TransitionResumeJournalLoader, readContext: TransitionResumeContextReader, policy: ApplyPolicy, target: TransitionConnectionPool): Promise<ApplyResult>;
1724
+ }
1725
+ type TransitionResumeJournalLoader = (runId: string) => Promise<TransitionRunJournal & {
1726
+ readonly plan: ProvenPlanShape;
1727
+ }>;
1728
+ type TransitionResumeContextReader = (target: TransitionConnectionPool, run: TransitionRunJournal['run']) => Promise<ObservationContext>;
1729
+
1337
1730
  /**
1338
1731
  * @module model-impl
1339
1732
  * ModelIR implementation with Map-based storage and helper methods.
@@ -2033,7 +2426,7 @@ interface QueryBuilderContext {
2033
2426
  * Options for streaming query execution.
2034
2427
  * Options for configuring streaming behavior.
2035
2428
  */
2036
- interface StreamOptions {
2429
+ interface StreamOptions extends TransactionBeginOptions {
2037
2430
  /**
2038
2431
  * Number of rows to fetch per batch from the database.
2039
2432
  * Only affects PostgreSQL with pg-cursor configured.
@@ -2045,6 +2438,8 @@ interface StreamOptions {
2045
2438
  * Receives the query dump for observability/logging.
2046
2439
  */
2047
2440
  readonly onStart?: (dump: Dump) => void;
2441
+ /** AbortSignal is intentionally unsupported by stream-owned transactions. */
2442
+ readonly signal?: never;
2048
2443
  }
2049
2444
  /**
2050
2445
  * Options for offset-based pagination.
@@ -3330,9 +3725,10 @@ declare class CteBuilder {
3330
3725
  private readonly cteName;
3331
3726
  private readonly adapter;
3332
3727
  private readonly schemaName;
3728
+ private readonly model;
3333
3729
  private unnestColumns;
3334
3730
  private indexColumnName;
3335
- constructor(name: string, adapter?: Adapter, schemaName?: string);
3731
+ constructor(name: string, adapter?: Adapter, schemaName?: string, model?: ModelIR);
3336
3732
  /**
3337
3733
  * Provide the column arrays for the unnest() CTE.
3338
3734
  * All arrays must have the same length.
@@ -3371,12 +3767,14 @@ declare class CteQueryBuilder<TResult = unknown> {
3371
3767
  private readonly outerBuilder;
3372
3768
  private readonly adapter;
3373
3769
  private readonly schemaName;
3374
- constructor(cteIntent: UnnestCteIntent, outerBuilder: QueryBuilderImpl<TResult>, adapter?: Adapter, schemaName?: string);
3770
+ private readonly model;
3771
+ constructor(cteIntent: UnnestCteIntent, outerBuilder: QueryBuilderImpl<TResult>, adapter?: Adapter, schemaName?: string, model?: ModelIR);
3375
3772
  /**
3376
3773
  * Build the CteQueryIntent AST.
3377
3774
  */
3378
3775
  buildIntent(): CteQueryIntent;
3379
3776
  private requireAdapter;
3777
+ private compileOptions;
3380
3778
  /**
3381
3779
  * Compile to SQL and return an observability dump.
3382
3780
  */
@@ -3455,6 +3853,7 @@ declare abstract class MutationBuilderBase<T, TIntent extends InsertIntent | Upd
3455
3853
  protected requireAdapter(operation: string): Adapter;
3456
3854
  dump(extraOptions?: CompileOptions): MutationDump;
3457
3855
  execute(): Promise<T>;
3856
+ affectedRows(): Promise<number>;
3458
3857
  private prepareMutationExecution;
3459
3858
  }
3460
3859
  /**
@@ -3816,12 +4215,13 @@ declare class RawCteQueryBuilder<TResult = unknown> {
3816
4215
  private readonly rawCteIntent;
3817
4216
  private readonly adapter;
3818
4217
  private readonly schemaName;
4218
+ private readonly model;
3819
4219
  private outerSelect;
3820
4220
  private outerWhere;
3821
4221
  private outerOrderBy;
3822
4222
  private outerLimit;
3823
4223
  private outerOffset;
3824
- constructor(cteName: string, rawCteIntent: RawCteIntent, adapter?: Adapter, schemaName?: string);
4224
+ constructor(cteName: string, rawCteIntent: RawCteIntent, adapter?: Adapter, schemaName?: string, model?: ModelIR);
3825
4225
  /**
3826
4226
  * Select specific columns from the CTE result.
3827
4227
  */
@@ -3863,7 +4263,7 @@ declare class RawCteQueryBuilder<TResult = unknown> {
3863
4263
  /**
3864
4264
  * Create a RawCteQueryBuilder from named builder instances.
3865
4265
  */
3866
- declare function createRawCteBuilder<TResult = unknown>(cteName: string, options: RecursiveOptions, adapter?: Adapter, schemaName?: string): RawCteQueryBuilder<TResult>;
4266
+ declare function createRawCteBuilder<TResult = unknown>(cteName: string, options: RecursiveOptions, adapter?: Adapter, schemaName?: string, model?: ModelIR): RawCteQueryBuilder<TResult>;
3867
4267
 
3868
4268
  /**
3869
4269
  * Type definitions for table-scoped DDL operations.
@@ -4078,6 +4478,13 @@ interface SelectExpressionResult {
4078
4478
  */
4079
4479
  execute<T = Record<string, unknown>>(): Promise<T[]>;
4080
4480
  }
4481
+ interface RawReadOptions {
4482
+ /**
4483
+ * Map of output-key -> JS read type, applied to bigint columns read via raw SQL.
4484
+ * The caller declares provenance explicitly; dbsp does not infer it for arbitrary SQL.
4485
+ */
4486
+ readonly bigintReads?: Readonly<Record<string, ColumnJsReadType$1>>;
4487
+ }
4081
4488
  interface OrmInstance<DB = Record<string, unknown>> {
4082
4489
  /**
4083
4490
  * Type-safe table references for query building.
@@ -4227,6 +4634,26 @@ interface OrmInstance<DB = Record<string, unknown>> {
4227
4634
  * The strict mode setting for this ORM instance.
4228
4635
  */
4229
4636
  readonly strictMode: boolean;
4637
+ /**
4638
+ * Whether the connection backing this ORM instance is inside a transaction.
4639
+ *
4640
+ * Reflects the backing adapter's real transaction state: `true` inside a
4641
+ * {@link OrmInstance.transaction} callback, and also `true` for a top-level
4642
+ * instance built on an adapter that is ALREADY inside a caller-owned
4643
+ * transaction (e.g. a borrowed pg client mid-`BEGIN`); `false` otherwise.
4644
+ *
4645
+ * Callers use this to enforce a top-level precondition: an operation whose
4646
+ * effects a caller's outer rollback must not silently undo — DDL that cannot
4647
+ * be nested, or a process-level cache that would go stale if the surrounding
4648
+ * transaction rolls back — can fail closed when the connection is already in a
4649
+ * transaction instead of assuming it owns the top-level transaction.
4650
+ *
4651
+ * Optional for backward compatibility: instances produced by `createOrm`
4652
+ * always populate it, but a pre-existing hand-built `OrmInstance` double may
4653
+ * omit it (reads as `undefined`), so a fail-closed caller should treat a
4654
+ * non-`true` value it cannot confirm accordingly.
4655
+ */
4656
+ readonly inTransaction?: boolean;
4230
4657
  /**
4231
4658
  * Create a schema-scoped ORM instance.
4232
4659
  * All queries from the returned instance will include the schema prefix.
@@ -4334,7 +4761,17 @@ interface OrmInstance<DB = Record<string, unknown>> {
4334
4761
  * });
4335
4762
  * ```
4336
4763
  */
4337
- transaction<T>(fn: (tx: OrmInstance<DB>) => Promise<T>): Promise<T>;
4764
+ transaction<T>(fn: (tx: OrmInstance<DB>) => Promise<T>, options?: TransactionOptions): Promise<T>;
4765
+ /**
4766
+ * Execute a callback with all ORM work pinned to one physical database
4767
+ * connection for the callback lifetime, without opening a transaction.
4768
+ *
4769
+ * @typeParam T - The return type of the callback
4770
+ * @param fn - Async callback that receives a connection-pinned ORM instance
4771
+ * @param options - Optional pinned connection controls
4772
+ * @returns Promise resolving to the callback's return value
4773
+ */
4774
+ withPinnedConnection<T>(fn: (pinned: OrmInstance<DB>) => Promise<T>, options?: PinnedConnectionOptions): Promise<T>;
4338
4775
  /**
4339
4776
  * NQL template tag for writing queries in Natural Query Language.
4340
4777
  *
@@ -4358,9 +4795,10 @@ interface OrmInstance<DB = Record<string, unknown>> {
4358
4795
  * @typeParam T - Expected result type (defaults to unknown)
4359
4796
  * @param sql - Raw SQL string with parameter placeholders
4360
4797
  * @param parameters - Parameter values for placeholders
4798
+ * @param options - Explicit raw read coercion options
4361
4799
  * @returns Promise resolving to array of results
4362
4800
  */
4363
- raw<T = unknown>(sql: string, parameters?: readonly unknown[]): Promise<T[]>;
4801
+ raw<T = unknown>(sql: string, parameters?: readonly unknown[], options?: RawReadOptions): Promise<T[]>;
4364
4802
  /**
4365
4803
  * Create a CTE (Common Table Expression) backed by unnest() arrays.
4366
4804
  *
@@ -6348,7 +6786,7 @@ interface FeatureUsage {
6348
6786
  readonly detail: string;
6349
6787
  }
6350
6788
  /**
6351
- * Default feature checkers -- mirrors the 16 supportsDDL* flags that
6789
+ * Default feature checkers -- mirrors the 17 supportsDDL* flags that
6352
6790
  * negotiateFeatures() previously checked inline.
6353
6791
  *
6354
6792
  * Each checker preserves exactly the same detection logic (same guards,
@@ -7275,7 +7713,7 @@ declare class ResultHydrator<TResult = unknown> {
7275
7713
  * E2E-004: json_agg strategy returns data as JSON string in *_json columns.
7276
7714
  * STRAT-SIMPLIFY: For to-one relations (belongsTo/hasOne), unwrap array to single object.
7277
7715
  */
7278
- hydrateJsonAggIncludes(results: TResult[], planReport: PlanReport): void;
7716
+ hydrateJsonAggIncludes(results: TResult[], planReport: PlanReport, query?: CompiledQuery): void;
7279
7717
  /**
7280
7718
  * Process recursive includes via CTEs.
7281
7719
  */
@@ -7619,4 +8057,4 @@ declare const assertIntentHasOrderBy: (result: AssertionQueryResult, expected: b
7619
8057
  */
7620
8058
  declare function runAssertions(blocks: AssertionBlock[], results: AssertionQueryResult[], queries: string[], hasDb?: boolean): AssertionSummary;
7621
8059
 
7622
- export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterQueryHook, type AggregateOptions, type AliasedColumn, type AliasedExprColumn, type AllColumns, AmbiguousPlanError, AmbiguousRelationError, type Assertion, type AssertionBlock, type AssertionOutcome, type AssertionQueryResult, type AssertionSummary, type AssertionType, BRAND, type BatchValuesOptions, type BatchValuesRef, type BeforeMutationHook, type BeforeQueryHook, type BrandKey, COLUMN_META, type CardinalityShorthand, CaseBuilder, type CaseValue, type ColumnDef, type ColumnMetaKey, ColumnNotFoundError, type ColumnRef, type ColumnSpec, CteBuilder, type CteDump, CteQueryBuilder, type CursorPaginateOptions, type CursorPaginatedResult, DEFAULT_FEATURE_CHECKERS, DUCKDB_CAPABILITIES, type DefaultFilters, type DefineModelOptions, DeleteBuilder, type DistinctField, type DumpMetaInput, type EdgeTableOptions, type EmitWarningOptions, ErrorCode, type ErrorHookContext, Errors, ExecutionError, type ExprInput, ExpressionRef, type ExpressionSpec, type FeatureChecker, type FeatureUsage, type FilterOperators, type FilterValue, type FullTextSearchField, type FullTextSearchOptions, type GetSchemaFromDbOptions, type HierarchyOptions, type HookErrorHandler, type HookManager, type HookPriority, type HydrateOptions, IRREGULAR_PLURALS, type IncludeOptions, type IncludeOptionsWithRecursive, type InferColumn, type InferColumnType, type InferColumnTypes, type InferDB, type InferRefColumn, type InferRow, type InferSchemaDB, type InferTableRow, type InferTables, type InferredRangeValue, InsertBuilder, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, ModelIRImpl, type MutationDump, type MutationHookContext, type MutationOperation, NamingConventionMismatchError, type NegotiationResult, type NestedInclude, type SchemaColumnType as NewSchemaColumnType, NotFoundError, type NqlBuilder, type NqlRawFragment, type NqlTag, type OnErrorHook, type OrderByInput, type OrderByRecord, type OrderBySpec, type OrmInstance, type OrmOf, type OrmOptions, type OrmOptionsWithAdapter, type OrmOptionsWithModel, POSTGRESQL_CAPABILITIES, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PrioritizedHook, type QueryAssertionResult, type QueryBuilder, type QueryHookContext, type QueryResultType, RELATION_META, type RangeType, RawCteQueryBuilder, type RecursiveDump, type RecursiveIncludeConfig, type RecursiveOptions, RecursiveShapeMismatchError, type RefDefinition, type RefOptions, type RelationHints, type RelationKey, type RelationMetaKey, RelationNotFoundError, type RelationObjectDef, type RelationPathIncludeNode, type RelationPathUsage, type RelationRef, type RelationShorthand, type RelationTupleDef, ResultHydrator, SQLITE_CAPABILITIES, SQL_RAW_MARKER, type Schema, type SchemaColumnType, type SchemaConstraints, type SchemaDefinition, SchemaValidationError as SchemaError, type SchemaExtras, type SchemaIndexOptions, type SchemaIndexValidationInput, type SchemaOptions, type SchemaTableOptions, SchemaValidationError, type SelectField, type SelfRefRoles, type SetOperationBuilder, type SimplifiedOrmOptions, type SqlRawExpression, type StreamOptions, SubqueryBuilder, SubqueryExpression, TABLE_META, type TableAssertionData, type TableDDL, type TableDef, type TableIndexes, type TableMetaKey, TableNotFoundError, type TableRef, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, UpsertBuilder, type WarningCategory, type WhereFilter, WindowBuilder, aggOrderBy, and, any, array, arrayAgg, assertCapability, assertContains, assertDbColumnExists, assertDbOutput, assertDbRowsEquals, assertDbRowsMax, assertDbRowsMin, assertDbValueEquals, assertEquals, assertIntentHasGroupBy, assertIntentHasOrderBy, assertIntentHasWhere, assertIntentTable, assertIntentType, assertIntentWith, assertMatches, assertParamsEquals, assertParamsLength, assertParamsType, assertParamsValue, assertSQLColumn, assertSQLEquals, assertSQLJoin, assertSQLTable, assertSuccess, assertTypeSupported, batchValues, capitalize, caseWhen, cast, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, countDistinctRelationPathsByName, createDialectCapabilities, createHookManager, createNqlTag, createOrm, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, decapitalize, defaultLogger, defineModel, denseRank, deriveRelationPathFromIntentPath, distinct, emitWarning, eq, every, exists, ref as exprRef, extendDialect, extractPseudoColumnKeywords, findClosestMatch, fn, fullTextSearch, getAvailableDialects, getDialectCapabilities, getLogger, getRelationKind, getSchemaFromDb, gt, gte, inArray, inSubquery, inferForeignKey, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOverallSuccess, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, lt, lte, namedArg, negotiateFeatures, neq, none, normalizeSQL, not, notExists, nqlRaw, objectToWhereIntent, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, rangeContainedBy, rangeContains, rangeOverlaps, rank, raw, rawExists, rawNotExists, ref$1 as ref, registerDialect, relationColumn, requiresDatabase, resetLogger, resolveQueryIndex, rowNumber, runAssertions, schema, schemaToModelIR, setLogger, silentLogger, singularize, some, sortByPriority, sql, star, stringAgg, subquery, supportsDDLGeneration, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, unary, validateAssertionBlocks, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };
8060
+ export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterQueryHook, type AggregateOptions, type AliasedColumn, type AliasedExprColumn, type AllColumns, AmbiguousPlanError, AmbiguousRelationError, type Applier, type Assertion, type AssertionBlock, type AssertionOutcome, type AssertionQueryResult, type AssertionSummary, type AssertionType, BRAND, type BatchValuesOptions, type BatchValuesRef, type BeforeMutationHook, type BeforeQueryHook, type BrandKey, COLUMN_META, type CardinalityShorthand, CaseBuilder, type CaseValue, type CheckDelta, type ColumnDef, type ColumnMetaKey, ColumnNotFoundError, type ColumnRef, type ColumnSpec, CteBuilder, type CteDump, CteQueryBuilder, type CursorPaginateOptions, type CursorPaginatedResult, DEFAULT_FEATURE_CHECKERS, DUCKDB_CAPABILITIES, type DefaultFilters, type DefineModelOptions, DeleteBuilder, type DistinctField, type DumpMetaInput, type EdgeTableOptions, type EmitWarningOptions, type EnumAddDelta, ErrorCode, type ErrorHookContext, Errors, type EstablishedProofClaim, type ExecutionCoordinator, ExecutionError, type ExprInput, ExpressionRef, type ExpressionSpec, type FeatureChecker, type FeatureUsage, type FilterOperators, type FilterValue, type FullTextSearchField, type FullTextSearchOptions, type GetSchemaFromDbOptions, type GuardExecutionResult, type HierarchyOptions, type HookErrorHandler, type HookManager, type HookPriority, type HydrateOptions, IRREGULAR_PLURALS, type InProcessProvenPlan, type IncludeOptions, type IncludeOptionsWithRecursive, type IndexDelta, type IndexSetEntry, type InferColumn, type InferColumnNonNull, type InferColumnType, type InferColumnTypes, type InferDB, type InferRefColumn, type InferRow, type InferSchemaDB, type InferTableRow, type InferTables, type InferredRangeValue, InsertBuilder, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, ModelIRImpl, type MutationDump, type MutationHookContext, type MutationOperation, NamingConventionMismatchError, type NegotiationResult, type NestedInclude, type SchemaColumnType as NewSchemaColumnType, type NonRollbackableExecutionTracker, NotFoundError, type NqlBuilder, type NqlRawFragment, type NqlTag, type OnErrorHook, type OperationFingerprints, type OperationObservation, type OperationRuntime, type OrderByInput, type OrderByRecord, type OrderBySpec, type OrmInstance, type OrmOf, type OrmOptions, type OrmOptionsWithAdapter, type OrmOptionsWithModel, POSTGRESQL_CAPABILITIES, PackRegistry, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PrioritizedHook, type ProveOutcome, type Prover, type QueryAssertionResult, type QueryBuilder, type QueryHookContext, type QueryResultType, RELATION_META, type RangeType, RawCteQueryBuilder, type RecursiveDump, type RecursiveIncludeConfig, type RecursiveOptions, RecursiveShapeMismatchError, type RefDefinition, type RefOptions, type RegisteredOperationSemantics, type RelationHints, type RelationKey, type RelationMetaKey, RelationNotFoundError, type RelationObjectDef, type RelationPathIncludeNode, type RelationPathUsage, type RelationRef, type RelationShorthand, type RelationTupleDef, ResultHydrator, type RulePrecedenceFact, SQLITE_CAPABILITIES, SQL_RAW_MARKER, type Schema, type SchemaColumnType, type SchemaConstraints, type SchemaDefinition, SchemaValidationError as SchemaError, type SchemaExtras, type SchemaIndexOptions, type SchemaIndexValidationInput, type SchemaOptions, type SchemaTableOptions, SchemaValidationError, type SelectField, type SelfRefRoles, type SetOperationBuilder, type SimplifiedOrmOptions, type SqlRawExpression, type StagedCompositionCandidate, type StagedCompositionPreflight, type StagedCompositionPreflightInput, type StagedTransitionInput, type StagedTransitionOrchestrator, type StreamOptions, SubqueryBuilder, SubqueryExpression, TABLE_META, type TableAssertionData, type TableDDL, type TableDef, type TableIndexes, type TableMetaKey, TableNotFoundError, type TableRef, type TransactionCoordinatorBinding, type TransitionExecutionClient, type TransitionPack, type TransitionRelationalValidationInput, type TransitionRelationalValidationResult, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, UpsertBuilder, type WarningCategory, type WhereFilter, WindowBuilder, advisoryObservationId, aggOrderBy, and, any, array, arrayAgg, assertCapability, assertContains, assertDbColumnExists, assertDbOutput, assertDbRowsEquals, assertDbRowsMax, assertDbRowsMin, assertDbValueEquals, assertEquals, assertIntentHasGroupBy, assertIntentHasOrderBy, assertIntentHasWhere, assertIntentTable, assertIntentType, assertIntentWith, assertMatches, assertParamsEquals, assertParamsLength, assertParamsType, assertParamsValue, assertSQLColumn, assertSQLEquals, assertSQLJoin, assertSQLTable, assertSuccess, assertTypeSupported, assumptionId, batchValues, capitalize, caseWhen, cast, checkDelta, chooseReadyCandidate, claimId, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, countDistinctRelationPathsByName, createApplier, createComparator, createDialectCapabilities, createEvidenceView, createHookManager, createNqlTag, createOrm, createPackRegistry, createProver, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, createStagedTransitionOrchestrator, decapitalize, defaultIndexName, defaultLogger, defineModel, denseRank, deriveRelationPathFromIntentPath, distinct, emitWarning, enumAddDelta, eq, every, evidenceId, exists, ref as exprRef, extendDialect, extractPseudoColumnKeywords, findClosestMatch, fn, fullTextSearch, getAvailableDialects, getDialectCapabilities, getLogger, getRelationKind, getSchemaFromDb, gt, gte, inArray, inSubquery, indexDelta, inferForeignKey, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOperationRuntime, isOverallSuccess, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, lt, lte, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizedIndex, not, notExists, nqlRaw, objectToWhereIntent, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, preflightStagedComposition, projectCompareToSingleCandidate, rangeContainedBy, rangeContains, rangeOverlaps, rank, raw, rawExists, rawNotExists, ref$1 as ref, registerDialect, relationColumn, requiresDatabase, resetLogger, resolveEnumSchemaForComparison, resolveQueryIndex, resourceIsWithin, resourceScopeCovers, rowNumber, runAssertions, schema, schemaToModelIR, selectorMatchesResource, semanticArtifactId, serverVersionNum, setLogger, silentLogger, singularize, some, sortByPriority, sql, star, stringAgg, subquery, supportsDDLGeneration, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, unary, validateAssertionBlocks, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTransitionRelationalInvariants, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };