@dbsp/core 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
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, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, TableReaddressDeclaration, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, ObservationContext, TransitionSessionClient, TransitionRunMetadata, IssuedObservation, RecoveryArtefact, ManagedStepClaimMaterial, LedgerPayload, FingerprintManifest, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, DurableIntentRecord, OperationEffectAssessment, ObservationIssuer, ApplyGuard, OperationExecutionOutcome, TransactionalCompletionRecord, StepJournal, TransitionRule, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, TransitionRunJournal, ProvenPlanShape, ApplyPolicy, CheckConstraintIR, Comparator, ResourceAddress, JsonValue as JsonValue$1, DeclarationSet, EnumIR, ObservationRequest, EvidenceView, ProofObligation, ExecutionContract, ExecutionRequirement, AdvisoryObservationId, AssumptionId, ClaimId, EvidenceId, SemanticArtifactId, IndexIR, LedgerClaimKind, LedgerLifecycleGrammarColumn, LedgerHome, LedgerAddress, LedgerChainMember, LedgerStableState, LedgerOpenClaim, LedgerChainProjection, Assumption, ResourceSelector, TransitionLessor, ApplyResult, TransitionCandidate, TransitionFragmentComposition, PlanAssessment, CompareOutcome, TransitionFragment, ProofClaim, NormalizedManagedStep, ApplicableAssessment, ExclusiveTransitionTarget, DurableApplyOutcome, 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, StandaloneWhereExpressionIntent, AggOrderByArg, PredicateOperator, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, RangeOperand, 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, ConnectionAvailability, CreateIndexOptions, CustomTraversal, DDLGeneratingAdapter, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, DurableIntentRecord, EdgeTableTraversal, EmitJoinClause, ExclusiveTransitionTarget, 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, PredicateOperator, 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, TableReaddressAddress, TableReaddressDeclaration, TransactionOptions, TransactionalAdapter, TransactionalCompletionRecord, TransitionCandidate, TransitionLessor, TransitionQueryClient, TransitionRule, TransitionRunMetadata, TransitionSessionClient, 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
- import { D as DurablyLoadedRun, T as TransitionReadTarget } from './internal-CNjWzMNe.js';
5
- export { A as AdmittedDestructiveOutcomeClaim, a as TRANSITION_LESSOR_REJECTION, b as TransitionLeaseFailure, c as acquireExclusiveTransitionLease, d as acquireTransitionLease, e as acquireTransitionTargetLease, f as classifyOutcomeRecovery, g as createExclusiveTransitionTarget, h as createTransitionLessor, i as findUniqueLedgerTerminal, j as isExclusiveTransitionTarget, k as isTransitionLessor, o as outcomeClaimEventId, l as outcomeClaimId, p as planOperationSession } from './internal-CNjWzMNe.js';
2
+ import { PseudoColumnMetadata, RecursiveMetadata, RelationIR, RelationKind, AdapterCapabilities, Adapter, BaseAdapter, ExecutingAdapter, IntrospectingAdapter, RawSqlAdapter, StreamingAdapter, TransactionalAdapter, ColumnType, ColumnJsReadType as ColumnJsReadType$1, WhereIntent, OnDeleteAction, TableReaddressDeclaration, ModelIR, DbCasing, QueryIntent, PlanOptions, PlanReport, RecursiveIntent, RecursivePlanOptions, RecursivePlanReport, ObservationContext, TransitionSessionClient, TransitionRunMetadata, IssuedObservation, RecoveryArtefact, ManagedStepClaimMaterial, LedgerPayload, FingerprintManifest, OperationSemantics, OperationKindRef, PhysicalOperation, EvidenceObservation, DurableIntentRecord, OperationEffectAssessment, ObservationIssuer, ApplyGuard, OperationExecutionOutcome, TransactionalCompletionRecord, StepJournal, TransitionRule, EquivalenceCapability, CapabilityDescriptor, TransitionCompositionFact, RuleRef, SemanticArtifactRef, TransitionRunJournal, ProvenPlanShape, ApplyPolicy, CheckConstraintIR, Comparator, ResourceAddress, JsonValue as JsonValue$1, DeclarationSet, EnumIR, ObservationRequest, EvidenceView, ProofObligation, ExecutionContract, ExecutionRequirement, AdvisoryObservationId, AssumptionId, ClaimId, EvidenceId, SemanticArtifactId, IndexIR, LedgerClaimKind, LedgerLifecycleGrammarColumn, LedgerHome, LedgerAddress, LedgerChainMember, LedgerStableState, LedgerOpenClaim, LedgerChainProjection, Assumption, ResourceSelector, TransitionLessor, ApplyResult, TransitionCandidate, TransitionFragmentComposition, PlanAssessment, CompareOutcome, TransitionFragment, ProofClaim, NormalizedManagedStep, ApplicableAssessment, ExclusiveTransitionTarget, DurableApplyOutcome, 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, StandaloneWhereExpressionIntent, AggOrderByArg, PredicateOperator, RelationType as RelationType$1, Cardinality, FeatureWarning, UnsupportedFeatureBehavior, FeatureBehaviorConfig, RangeValue, WhereRangeIntent, RangeOperand, 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, ConnectionAvailability, CreateIndexOptions, CustomTraversal, DbCasing, DecisionType, DeleteIntent, DialectCapabilities, DialectName, DropIndexOptions, DuckDBColumnType, Dump, DumpMeta, DurableIntentRecord, EdgeTableTraversal, EmitJoinClause, ExclusiveTransitionTarget, 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, PredicateOperator, 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, TableReaddressAddress, TableReaddressDeclaration, TransactionOptions, TransactionalAdapter, TransactionalCompletionRecord, TransitionCandidate, TransitionLessor, TransitionQueryClient, TransitionRule, TransitionRunMetadata, TransitionSessionClient, 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
+ import { D as DurablyLoadedRun, T as TransitionReadTarget } from './outcome-protocol-CNjWzMNe.js';
5
+ export { A as AdmittedDestructiveOutcomeClaim, a as TRANSITION_LESSOR_REJECTION, b as TransitionLeaseFailure, c as acquireExclusiveTransitionLease, d as acquireTransitionLease, e as acquireTransitionTargetLease, f as classifyOutcomeRecovery, g as createExclusiveTransitionTarget, h as createTransitionLessor, i as findUniqueLedgerTerminal, j as isExclusiveTransitionTarget, k as isTransitionLessor, o as outcomeClaimEventId, l as outcomeClaimId, p as planOperationSession } from './outcome-protocol-CNjWzMNe.js';
6
6
  import { NqlCompilerOptions } from '@dbsp/nql';
7
7
 
8
8
  /**
@@ -76,10 +76,6 @@ declare function supportsTransactions<DB>(adapter: BaseAdapter): adapter is Tran
76
76
  * Check if adapter supports raw SQL execution.
77
77
  */
78
78
  declare function supportsRawSql(adapter: BaseAdapter): adapter is RawSqlAdapter;
79
- /**
80
- * Check if adapter supports DDL generation.
81
- */
82
- declare function supportsDDLGeneration(adapter: BaseAdapter): adapter is DDLGeneratingAdapter;
83
79
  /**
84
80
  * Error thrown when an operation requires an adapter but none was provided.
85
81
  */
@@ -946,13 +942,18 @@ type SchemaConstraints = Record<string, SchemaTableOptions>;
946
942
  interface SchemaExtras {
947
943
  /** PostgreSQL extensions to ensure (CREATE EXTENSION IF NOT EXISTS "name") */
948
944
  extensions?: string[];
949
- /** Sequences to create (CREATE SEQUENCE). Key = sequence name */
945
+ /**
946
+ * Sequences to create (CREATE SEQUENCE), or, with `adopt: true`, an existing standalone
947
+ * sequence for `convergePg` to take into management. Key = sequence name
948
+ */
950
949
  sequences?: Record<string, {
951
950
  startWith?: number | string;
952
951
  incrementBy?: number | string;
953
952
  minValue?: number | string;
954
953
  maxValue?: number | string;
955
954
  cycle?: boolean;
955
+ /** Explicitly bring an existing standalone sequence under managed state. */
956
+ adopt?: true;
956
957
  }>;
957
958
  }
958
959
  /**
@@ -1465,7 +1466,9 @@ interface OperationObservation {
1465
1466
  interface ComparatorNameNormalizer {
1466
1467
  /**
1467
1468
  * Normalize identifiers from the observed/current model into the namespace
1468
- * used by authored desired models before comparator matching runs.
1469
+ * used by authored desired models before comparator matching runs. Enum
1470
+ * names are not normalized: a declared enum name is the physical catalog type
1471
+ * name that columns reference in `originalDbType` (#825).
1469
1472
  */
1470
1473
  normalizeCurrentIdentifier(identifier: string): string;
1471
1474
  }
@@ -1704,14 +1707,6 @@ interface DeclarationAddressContext {
1704
1707
  readonly database: string;
1705
1708
  readonly schema: string;
1706
1709
  }
1707
- /**
1708
- * The declaration layer deliberately depends on this small structural naming
1709
- * boundary rather than an adapter package. Callers pass the same strategy that
1710
- * comparison and proof use for the target database.
1711
- */
1712
- interface DeclarationNamingStrategy {
1713
- toDatabase(identifier: string): string;
1714
- }
1715
1710
  /**
1716
1711
  * Reject every JavaScript value whose JSON representation is lossy or
1717
1712
  * host-dependent. JSON.stringify alone is unsuitable because it silently drops
@@ -1722,8 +1717,10 @@ declare function assertCanonicalizableJson(value: unknown, path?: string, seen?:
1722
1717
  * Slice only the declarable part of ModelIR. Deliberately absent are
1723
1718
  * logicalIdentity, pseudoColumns, comment, partition, rlsEnabled and policies;
1724
1719
  * their omission is encoded here once, rather than re-checked at every caller.
1720
+ * The supplied model is already physical: declaration binding never derives an
1721
+ * identifier spelling.
1725
1722
  */
1726
- declare function declarationSetFromModel(model: ModelIR, context: DeclarationAddressContext, naming?: DeclarationNamingStrategy): DeclarationSet;
1723
+ declare function declarationSetFromModel(model: ModelIR, context: DeclarationAddressContext): DeclarationSet;
1727
1724
  /** Validate the complete declarable surface before comparison can short-circuit plan time. */
1728
1725
  declare function validateDeclarationModel(model: ModelIR): void;
1729
1726
  /** Compare only the recorded/live identity and retain the precise mismatch reason. */
@@ -4488,9 +4485,9 @@ interface NqlBuilder<T> {
4488
4485
  run(): Promise<void>;
4489
4486
  /** Execute query and return first result or null */
4490
4487
  first(): Promise<T | null>;
4491
- /** Get the IntentIR for debugging */
4488
+ /** Get the IntentIR for debugging. Throws for CTE and set-operation queries. */
4492
4489
  toIntentIR(): QueryIntent | MutationIntent$1;
4493
- /** Get the execution plan */
4490
+ /** Get the execution plan. Throws for mutations and CTE and set-operation queries. */
4494
4491
  plan(): PlanReport;
4495
4492
  /** Get full dump. Mutations return MutationDump without a plan. */
4496
4493
  dump(meta?: DumpMetaInput): Dump | MutationDump;
@@ -6366,10 +6363,14 @@ declare function raw(sqlFragment: string, as: string): ExpressionSpec;
6366
6363
  declare function col(column: string, alias: string): ExpressionSpec;
6367
6364
  /**
6368
6365
  * Creates a relation column expression for selecting a column from a related table.
6369
- * Auto-creates JOINs via the include mechanism and selects with custom alias.
6370
6366
  *
6371
- * Uses structured relation-column intent - no raw SQL. The compiler resolves the
6372
- * relation to its join alias and renders a dialect-specific aliased column.
6367
+ * Names a relation whose JOIN the query has already emitted. The compiler resolves
6368
+ * that relation to its emitted SQL alias and renders a dialect-specific aliased
6369
+ * column. Without an emitted alias, it reports
6370
+ * `relation column "<relation>"."<column>" has no emitted alias in this query`.
6371
+ *
6372
+ * It does not derive a join: choosing its type, null behavior, and row
6373
+ * multiplication is a separate caller-owned query decision.
6373
6374
  *
6374
6375
  * @param relation - Relation path to traverse (dot-separated for multi-level)
6375
6376
  * @param column - Column name to select from the target relation
@@ -6378,19 +6379,17 @@ declare function col(column: string, alias: string): ExpressionSpec;
6378
6379
  *
6379
6380
  * @example
6380
6381
  * ```typescript
6381
- * // Select from direct relation
6382
- * relationColumn('category', 'name', 'categoryName')
6383
- * // → SELECT t1."name" AS "categoryName" (with JOIN to categories)
6384
- *
6385
- * // Select from nested relation (multi-level path)
6386
- * relationColumn('category.parent', 'name', 'parentName')
6387
- * // → SELECT t2."name" AS "parentName" (with JOINs through category to parent)
6388
- *
6389
- * // In a query
6390
- * orm.select('products').columns([
6391
- * 'name',
6392
- * relationColumn('category', 'name', 'categoryName'),
6393
- * ])
6382
+ * // A relation join supplies the emitted alias.
6383
+ * orm.select('products')
6384
+ * .join('category')
6385
+ * .columns(['name', relationColumn('category', 'name', 'categoryName')])
6386
+ *
6387
+ * // An include with an explicit outer join supplies the alias too. A bare
6388
+ * // include aggregates the relation instead, so the column lands inside
6389
+ * // `<relation>_json` rather than at the top level under its own alias (#793).
6390
+ * orm.select('products')
6391
+ * .include('category', { join: 'left' })
6392
+ * .columns(['name', relationColumn('category', 'name', 'categoryName')])
6394
6393
  * ```
6395
6394
  */
6396
6395
  declare function relationColumn<A extends string>(relation: string, column: string, as: A): AliasedExprColumn<A>;
@@ -8533,4 +8532,4 @@ declare const assertIntentHasOrderBy: (result: AssertionQueryResult, expected: b
8533
8532
  */
8534
8533
  declare function runAssertions(blocks: AssertionBlock[], results: AssertionQueryResult[], queries: string[], hasDb?: boolean): AssertionSummary;
8535
8534
 
8536
- export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterMutationObserver, type AfterQueryHook, type AfterQueryObserver, 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, CanonicalJsonError, 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 DeclarationNamingStrategy, 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, type Insertable, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, LEDGER_LIFECYCLE_GRAMMAR, LEDGER_PROJECTION_CODE_VERSION, type LedgerChainProjectionInput, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, type ManagedOutcomeExecutionRequest, type ManagedOutcomePreflightRequest, 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 ObserverErrorHandler, 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, PREDICATE_REF_DISCRIMINATOR, PackRegistry, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PredicateExpressionRef, type PredicateRef, 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, TransitionReadTarget, type TransitionRelationalValidationInput, type TransitionRelationalValidationResult, type TransitionRunPersister, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, type Updateable, UpsertBuilder, type ValidatedManagedStepManifest, type ValidatedManagedStepManifestResult, type WarningCategory, type WhereFilter, WindowBuilder, admitRecordedIdentity, advisoryObservationId, aggOrderBy, and, any, array, arrayAgg, assertCanonicalizableJson, assertCapability, assertConnectionAvailable, 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, assumptionAccepted, assumptionId, batchValues, bindDeclarationSet, bindExecutionContract, boolFn, canonicalJson, canonicalJsonDigest, capitalize, caseWhen, cast, checkDelta, chooseReadyCandidate, claimId, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, concludeEvidenceForObligation, countDistinctRelationPathsByName, createApplier, createComparator, createDialectCapabilities, createEvidenceView, createExecutionContract, createHookManager, createNqlTag, createOrm, createPackRegistry, createProver, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, createStagedTransitionOrchestrator, createTransitionRunMetadata, decapitalize, declarationSetFromModel, 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, interpretLedgerLifecycle, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOperationRuntime, isOverallSuccess, isPredicateRef, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, loadVerifiedRecoveryJournal, lt, lte, markGeneratorRemovalNonReplayable, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizedIndex, not, notExists, nqlRaw, objectToWhereIntent, observationContextDigest, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, preflightStagedComposition, projectCompareToSingleCandidate, projectLedgerChain, 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, transitionPlanDigest, unary, unsafeAsPredicate, validateAssertionBlocks, validateDeclarationModel, validateExecutionContract, validateNormalizedManagedStepManifest, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTransitionRelationalInvariants, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };
8535
+ export { ASSERTION_TYPES, AdapterRequiredError, type AdjacencyOptions, type AfterMutationHook, type AfterMutationObserver, type AfterQueryHook, type AfterQueryObserver, 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, CanonicalJsonError, 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, type Insertable, IntentBuilder, type IntentBuilderState, type IntentSummary, InvalidOperationError, InvalidRelationDefinitionError, type JoinOptions, type JsonValue, LEDGER_LIFECYCLE_GRAMMAR, LEDGER_PROJECTION_CODE_VERSION, type LedgerChainProjectionInput, type LightweightRelationsDef, type ListHierarchyOptions, type ListIndexOptions, type Logger, MSSQL_CAPABILITIES, MYSQL_CAPABILITIES, type ManagedOutcomeExecutionRequest, type ManagedOutcomePreflightRequest, 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 ObserverErrorHandler, 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, PREDICATE_REF_DISCRIMINATOR, PackRegistry, type PaginateOptions, type PaginatedResult, type ParseError, type ParseResult, type ParsedRelationDef, type ParsedRelationKey, type PathOptions, type PredicateExpressionRef, type PredicateRef, 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, TransitionReadTarget, type TransitionRelationalValidationInput, type TransitionRelationalValidationResult, type TransitionRunPersister, type TraversalDirection, UnhandledTypeInDialect, UnknownDialectError, UnsafeOperationError, UnsupportedCapabilityError, UnsupportedFeatureError, UnsupportedStrategyError, UpdateBuilder, type Updateable, UpsertBuilder, type ValidatedManagedStepManifest, type ValidatedManagedStepManifestResult, type WarningCategory, type WhereFilter, WindowBuilder, admitRecordedIdentity, advisoryObservationId, aggOrderBy, and, any, array, arrayAgg, assertCanonicalizableJson, assertCapability, assertConnectionAvailable, 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, assumptionAccepted, assumptionId, batchValues, bindDeclarationSet, bindExecutionContract, boolFn, canonicalJson, canonicalJsonDigest, capitalize, caseWhen, cast, checkDelta, chooseReadyCandidate, claimId, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, concludeEvidenceForObligation, countDistinctRelationPathsByName, createApplier, createComparator, createDialectCapabilities, createEvidenceView, createExecutionContract, createHookManager, createNqlTag, createOrm, createPackRegistry, createProver, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, createStagedTransitionOrchestrator, createTransitionRunMetadata, decapitalize, declarationSetFromModel, 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, interpretLedgerLifecycle, isAliasedColumn, isAllColumns, isBatchValuesRef, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isKnownDialect, isNotNull, isNull, isOperationRuntime, isOverallSuccess, isPredicateRef, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, loadVerifiedRecoveryJournal, lt, lte, markGeneratorRemovalNonReplayable, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizedIndex, not, notExists, nqlRaw, objectToWhereIntent, observationContextDigest, op, or, outerRef, param, parseAssertionFile, parseRelationDef, parseRelationKey, pipeAfterMutationHooks, pipeAfterQueryHooks, pipeBeforeMutationHooks, pipeBeforeQueryHooks, pipeOnErrorHooks, plan, planRecursive, pluralize, preflightStagedComposition, projectCompareToSingleCandidate, projectLedgerChain, 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, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, transitionPlanDigest, unary, unsafeAsPredicate, validateAssertionBlocks, validateDeclarationModel, validateExecutionContract, validateNormalizedManagedStepManifest, validateRecursiveInclude, validateRecursiveShape, validateSchemaIndexOptions, validateTransitionRelationalInvariants, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  acquireTransitionTargetLease,
10
10
  admitRecordedIdentity,
11
11
  assertCanonicalizableJson,
12
+ assertDeclaredEnumMapIdentity,
12
13
  bindDeclarationSet,
13
14
  canonicalJson,
14
15
  canonicalJsonDigest,
@@ -33,7 +34,7 @@ import {
33
34
  transitionLessorRejectionAssessment,
34
35
  transitionLessorRejectionDetail,
35
36
  validateDeclarationModel
36
- } from "./chunk-AQN7HBYD.js";
37
+ } from "./chunk-XBGQXVXC.js";
37
38
 
38
39
  // src/model-ir.ts
39
40
  function createPseudoColumnMetadata(table, foreignKeyColumn, targetColumn, parentRole, childRole) {
@@ -801,10 +802,17 @@ function schemaToModelIR(definition, constraints, extras, options) {
801
802
  }
802
803
  const extensions = extras?.extensions;
803
804
  const sequenceMap = extras?.sequences ? new Map(
804
- Object.entries(extras.sequences).map(([name, seq]) => [
805
- name,
806
- { name, ...seq }
807
- ])
805
+ Object.entries(extras.sequences).map(([name, seq]) => {
806
+ const { adopt, ...shape } = seq;
807
+ return [
808
+ name,
809
+ {
810
+ name,
811
+ ...shape,
812
+ ...adopt === true ? { adopt: true } : {}
813
+ }
814
+ ];
815
+ })
808
816
  ) : void 0;
809
817
  return new ModelIRImpl(
810
818
  tableMap,
@@ -3454,6 +3462,11 @@ function lifecycle(value, detail) {
3454
3462
  kind: "adoption",
3455
3463
  shape: canonicalJson2(source.shape, detail)
3456
3464
  };
3465
+ if (source.kind === "sequence-adoption")
3466
+ return {
3467
+ kind: "sequence-adoption",
3468
+ shape: sequenceShape(source.shape, detail)
3469
+ };
3457
3470
  if (source.kind === "adoption-refused") return { kind: "adoption-refused" };
3458
3471
  if (source.kind === "readdress") {
3459
3472
  const declaration = record(source.declaration, detail);
@@ -3467,6 +3480,27 @@ function lifecycle(value, detail) {
3467
3480
  }
3468
3481
  return parseError(detail);
3469
3482
  }
3483
+ function sequenceShape(value, detail) {
3484
+ const source = record(value, detail);
3485
+ const sequenceInteger = (item) => {
3486
+ if (typeof item === "string") return item;
3487
+ if (typeof item === "number" && Number.isFinite(item)) return item;
3488
+ return parseError(detail);
3489
+ };
3490
+ const sequenceBoolean = (item) => {
3491
+ if (typeof item === "boolean") return item;
3492
+ return parseError(detail);
3493
+ };
3494
+ return {
3495
+ name: nonEmptyString(source.name, detail),
3496
+ ...source.startWith === void 0 ? {} : { startWith: sequenceInteger(source.startWith) },
3497
+ ...source.incrementBy === void 0 ? {} : { incrementBy: sequenceInteger(source.incrementBy) },
3498
+ ...source.minValue === void 0 ? {} : { minValue: sequenceInteger(source.minValue) },
3499
+ ...source.maxValue === void 0 ? {} : { maxValue: sequenceInteger(source.maxValue) },
3500
+ ...source.cycle === void 0 ? {} : { cycle: sequenceBoolean(source.cycle) },
3501
+ ...source.schema === void 0 ? {} : { schema: nonEmptyString(source.schema, detail) }
3502
+ };
3503
+ }
3470
3504
  function deepFreeze(value) {
3471
3505
  if (value !== null && typeof value === "object") {
3472
3506
  for (const child of Object.values(value)) deepFreeze(child);
@@ -3595,6 +3629,8 @@ function parseStep(value, index) {
3595
3629
  }
3596
3630
  function validateLifecycleCoupling(step) {
3597
3631
  const lifecycle2 = step.lifecycle;
3632
+ if (step.selection?.kind === "adoption" && (!lifecycle2 || step.address?.kind === "table" && lifecycle2.kind !== "adoption" || step.address?.kind === "sequence" && lifecycle2.kind !== "sequence-adoption" || step.address?.kind !== "table" && step.address?.kind !== "sequence"))
3633
+ return `adoption step ${step.stepKey} has invalid lifecycle coupling`;
3598
3634
  if (step.selection?.kind === "replacement") {
3599
3635
  if (lifecycle2)
3600
3636
  return `replacement step ${step.stepKey} has invalid lifecycle coupling`;
@@ -3610,10 +3646,15 @@ function validateLifecycleCoupling(step) {
3610
3646
  return `readdress step ${step.stepKey} has invalid lifecycle coupling`;
3611
3647
  if (!lifecycle2) return void 0;
3612
3648
  if (lifecycle2.kind === "adoption") {
3613
- if (step.claimKind !== "adopt-intent" || step.classification !== "non-destructive" || step.requiresVacancy || step.selection?.kind !== "adoption" || !step.address || !step.expectedDeclaration || !step.expectedCatalogueIdentity || step.statementBundle.statements.length !== 0)
3649
+ if (step.claimKind !== "adopt-intent" || step.classification !== "non-destructive" || step.requiresVacancy || step.selection?.kind !== "adoption" || !step.address || step.address.kind !== "table" || !step.expectedDeclaration || !step.expectedCatalogueIdentity || step.statementBundle.statements.length !== 0)
3614
3650
  return `adoption step ${step.stepKey} has invalid lifecycle coupling`;
3615
3651
  return void 0;
3616
3652
  }
3653
+ if (lifecycle2.kind === "sequence-adoption") {
3654
+ if (step.claimKind !== "adopt-intent" || step.classification !== "non-destructive" || step.requiresVacancy || step.selection?.kind !== "adoption" || !step.address || step.address.kind !== "sequence" || step.selection.selector !== `sequence:${step.address.name}` || lifecycle2.shape.name !== step.address.name || lifecycle2.shape.schema !== void 0 && lifecycle2.shape.schema !== step.address.schema || !step.expectedDeclaration || !step.expectedCatalogueIdentity || step.statementBundle.statements.length !== 0)
3655
+ return `sequence adoption step ${step.stepKey} has invalid lifecycle coupling`;
3656
+ return void 0;
3657
+ }
3617
3658
  if (lifecycle2.kind === "readdress") {
3618
3659
  if (step.claimKind !== "readdress-intent" || step.classification !== "paired-readdress" || step.requiresVacancy || step.selection?.kind !== "readdress" || !step.address || step.address.kind !== "table")
3619
3660
  return `readdress step ${step.stepKey} has invalid lifecycle coupling`;
@@ -8337,7 +8378,7 @@ function normalizeCurrentModelForComparison(model, normalize) {
8337
8378
  relations.set(key, normalized);
8338
8379
  }
8339
8380
  const externalTables = model.externalTables ? new Set([...model.externalTables].map((table) => normalize(table))) : void 0;
8340
- const enums = normalizeNamedMap(model.enums, normalize, "enum");
8381
+ const enums = normalizeNamedMap(model.enums, (name) => name, "enum");
8341
8382
  const sequences = normalizeNamedMap(
8342
8383
  model.sequences,
8343
8384
  normalize,
@@ -8493,7 +8534,11 @@ function modelLevelCollectionsForComparison(model, externalTables, managedCollec
8493
8534
  ),
8494
8535
  sequences: projectManagedMapEntries(
8495
8536
  model.sequences,
8496
- managedCollections.sequences
8537
+ managedCollections.sequences,
8538
+ (_name, sequence) => {
8539
+ const { adopt: _adopt, ...shape } = sequence;
8540
+ return shape;
8541
+ }
8497
8542
  )
8498
8543
  };
8499
8544
  }
@@ -8990,6 +9035,7 @@ function createComparator(registry) {
8990
9035
  return {
8991
9036
  artifact: COMPARATOR_ARTIFACT,
8992
9037
  compare(desired, current, context) {
9038
+ assertDeclaredEnumMapIdentity(desired.enums);
8993
9039
  const engine = context?.engine ?? registry.allRules()[0]?.support.engine ?? "unknown-transition-engine";
8994
9040
  const recognitionContextFor = (rule) => {
8995
9041
  const equivalence = registry.resolveEquivalence(rule.artifact);
@@ -13251,9 +13297,6 @@ function supportsTransactions(adapter) {
13251
13297
  function supportsRawSql(adapter) {
13252
13298
  return "executeRaw" in adapter && typeof adapter.executeRaw === "function";
13253
13299
  }
13254
- function supportsDDLGeneration(adapter) {
13255
- return "generateDDL" in adapter && typeof adapter.generateDDL === "function";
13256
- }
13257
13300
  var AdapterRequiredError = class extends Error {
13258
13301
  constructor(operation) {
13259
13302
  super(
@@ -16870,7 +16913,7 @@ function readJsonAggColumnKeyMap(context) {
16870
16913
  return entries.length > 0 ? new Map(entries) : void 0;
16871
16914
  }
16872
16915
  function isNestedOutputReadHandling(value) {
16873
- return isRecord2(value) && value.kind === "nestedTransform" && typeof value.table === "string" && typeof value.column === "string" && (value.js === "bigint" || value.js === "number" || value.js === "string");
16916
+ return isRecord2(value) && value.kind === "nestedTransform" && typeof value.table === "string" && typeof value.column === "string" && (value.outputKey === void 0 || typeof value.outputKey === "string") && (value.js === "bigint" || value.js === "number" || value.js === "string");
16874
16917
  }
16875
16918
  function readJsonAggNestedReadTransforms(context) {
16876
16919
  const raw2 = context.jsonAggNestedReadTransforms;
@@ -16878,7 +16921,10 @@ function readJsonAggNestedReadTransforms(context) {
16878
16921
  const entries = [];
16879
16922
  for (const item of raw2) {
16880
16923
  if (isNestedOutputReadHandling(item)) {
16881
- entries.push([item.column, item]);
16924
+ entries.push([
16925
+ item.outputKey !== void 0 && item.outputKey !== item.column ? item.outputKey : item.column,
16926
+ item
16927
+ ]);
16882
16928
  }
16883
16929
  }
16884
16930
  return entries.length > 0 ? new Map(entries) : void 0;
@@ -16957,12 +17003,21 @@ function convertJsonAggPayload(value, tableName, model, lookup, columnKeyMap, ne
16957
17003
  if (!isRecord2(value)) return value;
16958
17004
  const table = model.getTable(tableName);
16959
17005
  if (table) {
17006
+ for (const [key, transform] of nestedReadTransforms ?? []) {
17007
+ if (transform.outputKey !== void 0 && transform.outputKey !== transform.column && Object.hasOwn(value, key) && transform.table === tableName) {
17008
+ value[key] = convertBigintJsReadValue(value[key], transform.js, {
17009
+ table: transform.table,
17010
+ column: transform.column,
17011
+ outputKey: key
17012
+ });
17013
+ }
17014
+ }
16960
17015
  for (const column of table.columns) {
16961
17016
  const key = findExistingKey(value, column.name, columnKeyMap);
16962
17017
  if (key === void 0) continue;
16963
17018
  const outputKey = renameExistingKey(value, key, column.name);
16964
- const transform = nestedReadTransforms?.get(column.name);
16965
- if (transform?.kind === "nestedTransform" && transform.table === tableName && transform.column === column.name) {
17019
+ const transform = nestedReadTransforms?.get(outputKey);
17020
+ if (transform?.kind === "nestedTransform" && (transform.outputKey === void 0 || transform.outputKey === transform.column) && transform.table === tableName && transform.column === column.name) {
16966
17021
  value[outputKey] = convertBigintJsReadValue(
16967
17022
  value[outputKey],
16968
17023
  transform.js,
@@ -17101,6 +17156,9 @@ function hydrateJsonAggIncludes(results, planReport, model) {
17101
17156
 
17102
17157
  // src/dx/nql.ts
17103
17158
  var NQL_RAW_FRAGMENT = /* @__PURE__ */ Symbol("NqlRawFragment");
17159
+ var UNPLANNED_NQL_READ_PLAN_ERROR = "NQL CTE and set-operation queries do not have execution plans.";
17160
+ var UNPLANNED_NQL_READ_INTENT_ERROR = "NQL CTE and set-operation queries do not have IntentIR.";
17161
+ var UNPLANNED_NQL_READ_PROGRAM_ERROR = "NQL CTE and set-operation queries are not supported after mutation or snapshot bindings.";
17104
17162
  function hasNqlBindings(bundle) {
17105
17163
  return (bundle.bindings?.size ?? 0) > 0;
17106
17164
  }
@@ -17673,7 +17731,7 @@ function bindingEntryIsFinal(compiledIntent, bindName, boundQuery, sourceBundle)
17673
17731
  if (compiledIntent.kind === "query") {
17674
17732
  return boundQuery === compiledIntent.intent;
17675
17733
  }
17676
- return sourceBundle.mutationBindings?.get(bindName) === compiledIntent.intent;
17734
+ return compiledIntent.kind === "mutation" && sourceBundle.mutationBindings?.get(bindName) === compiledIntent.intent;
17677
17735
  }
17678
17736
  function orderedSequenceStepToProgramStep(step) {
17679
17737
  const dependencyStep = step;
@@ -17817,12 +17875,14 @@ function createNqlProgramSteps(compiledIntent) {
17817
17875
  intent: compiledIntent.intent,
17818
17876
  final: true
17819
17877
  });
17820
- } else {
17878
+ } else if (compiledIntent.kind === "mutation") {
17821
17879
  steps.push({
17822
17880
  kind: "mutation",
17823
17881
  intent: compiledIntent.intent,
17824
17882
  final: true
17825
17883
  });
17884
+ } else {
17885
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
17826
17886
  }
17827
17887
  assertNqlProgramSteps(compiledIntent, steps);
17828
17888
  return steps;
@@ -17984,10 +18044,30 @@ var NqlBuilderImpl = class {
17984
18044
  };
17985
18045
  return this._compiled;
17986
18046
  }
18047
+ if (bundle.cteQuery !== void 0) {
18048
+ this._compiled = {
18049
+ kind: "unplannedRead",
18050
+ bundle,
18051
+ intent: bundle.cteQuery
18052
+ };
18053
+ return this._compiled;
18054
+ }
18055
+ if (bundle.setOperation !== void 0) {
18056
+ this._compiled = {
18057
+ kind: "unplannedRead",
18058
+ bundle,
18059
+ intent: bundle.setOperation
18060
+ };
18061
+ return this._compiled;
18062
+ }
17987
18063
  throw new Error("NQL compilation failed: no query AST produced");
17988
18064
  }
17989
18065
  toIntentIR() {
17990
- return this.compile().intent;
18066
+ const compiled = this.compile();
18067
+ if (compiled.kind === "unplannedRead") {
18068
+ throw new Error(UNPLANNED_NQL_READ_INTENT_ERROR);
18069
+ }
18070
+ return compiled.intent;
17991
18071
  }
17992
18072
  planInternal() {
17993
18073
  const compiled = this.compile();
@@ -17996,6 +18076,9 @@ var NqlBuilderImpl = class {
17996
18076
  "NQL mutations do not have execution plans; use dump() for SQL and parameters."
17997
18077
  );
17998
18078
  }
18079
+ if (compiled.kind === "unplannedRead") {
18080
+ throw new Error(UNPLANNED_NQL_READ_PLAN_ERROR);
18081
+ }
17999
18082
  return plan(compiled.intent, this.model);
18000
18083
  }
18001
18084
  plan() {
@@ -18005,6 +18088,9 @@ var NqlBuilderImpl = class {
18005
18088
  "NQL mutations do not have execution plans; use dump() for SQL and parameters."
18006
18089
  );
18007
18090
  }
18091
+ if (compiled.kind === "unplannedRead") {
18092
+ throw new Error(UNPLANNED_NQL_READ_PLAN_ERROR);
18093
+ }
18008
18094
  return isBindingFinalQuery(compiled.bundle) ? createBindingFinalPlan(
18009
18095
  compiled.intent,
18010
18096
  compiled.bundle,
@@ -18014,6 +18100,12 @@ var NqlBuilderImpl = class {
18014
18100
  }
18015
18101
  dump(meta) {
18016
18102
  const compiledIntent = this.compile();
18103
+ if (compiledIntent.kind === "unplannedRead" && hasExecutableNqlProgramSequence(compiledIntent.bundle)) {
18104
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
18105
+ }
18106
+ if (compiledIntent.kind === "unplannedRead") {
18107
+ return this.dumpUnplannedNqlRead(compiledIntent.bundle, meta);
18108
+ }
18017
18109
  if (hasExecutableNqlProgramSequence(compiledIntent.bundle)) {
18018
18110
  return this.dumpNqlProgramSequence(compiledIntent, meta);
18019
18111
  }
@@ -18071,6 +18163,28 @@ var NqlBuilderImpl = class {
18071
18163
  throw err;
18072
18164
  }
18073
18165
  }
18166
+ dumpUnplannedNqlRead(bundle, meta) {
18167
+ if (!this.adapter) {
18168
+ return {
18169
+ sql: "[No adapter - SQL not available]",
18170
+ params: [],
18171
+ ...meta !== void 0 && { meta }
18172
+ };
18173
+ }
18174
+ const compiled = this.adapter.compile(
18175
+ bundle,
18176
+ this.nqlBundleCompileOptions()
18177
+ );
18178
+ return {
18179
+ sql: compiled.sql,
18180
+ params: compiled.parameters,
18181
+ meta: {
18182
+ ...this._schemaName !== void 0 && { schema: this._schemaName },
18183
+ compiledAt: /* @__PURE__ */ new Date(),
18184
+ ...meta
18185
+ }
18186
+ };
18187
+ }
18074
18188
  requireAdapter(operation) {
18075
18189
  if (!this.adapter) {
18076
18190
  throw new ExecutionError({
@@ -18132,6 +18246,9 @@ var NqlBuilderImpl = class {
18132
18246
  };
18133
18247
  }
18134
18248
  createFinalNqlStatementBundle(compiledIntent, planReport) {
18249
+ if (compiledIntent.kind === "unplannedRead") {
18250
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
18251
+ }
18135
18252
  const finalStep = createNqlProgramSteps(compiledIntent).at(-1);
18136
18253
  if (compiledIntent.kind === "query") {
18137
18254
  return this.createNqlStatementBundle(
@@ -18214,6 +18331,9 @@ var NqlBuilderImpl = class {
18214
18331
  });
18215
18332
  }
18216
18333
  async executeNqlProgramSequence(compiledIntent, adapter) {
18334
+ if (compiledIntent.kind === "unplannedRead") {
18335
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
18336
+ }
18217
18337
  assertConnectionAvailable(adapter, "nql().all()");
18218
18338
  if (!supportsTransactions(adapter)) {
18219
18339
  throw new ExecutionError({
@@ -18323,6 +18443,9 @@ var NqlBuilderImpl = class {
18323
18443
  });
18324
18444
  }
18325
18445
  dumpNqlProgramSequence(compiledIntent, meta) {
18446
+ if (compiledIntent.kind === "unplannedRead") {
18447
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
18448
+ }
18326
18449
  const adapter = this.requireAdapter("dump");
18327
18450
  const sourceBundle = compiledIntent.bundle;
18328
18451
  const priorBindings = /* @__PURE__ */ new Map();
@@ -18469,16 +18592,26 @@ var NqlBuilderImpl = class {
18469
18592
  }
18470
18593
  async all() {
18471
18594
  const adapter = this.adapter;
18595
+ const compiledIntent = this.compile();
18472
18596
  if (!adapter) {
18473
18597
  throw new Error(
18474
- "Cannot execute query: no adapter configured. Pass an adapter to createOrm() or use .toIntentIR() / .plan() for debugging."
18598
+ "Cannot execute query: no adapter configured. " + (compiledIntent.kind === "unplannedRead" ? "Pass an adapter to createOrm()." : "Pass an adapter to createOrm() or use .toIntentIR() / .plan() for debugging.")
18475
18599
  );
18476
18600
  }
18477
- const compiledIntent = this.compile();
18601
+ if (compiledIntent.kind === "unplannedRead" && hasExecutableNqlProgramSequence(compiledIntent.bundle)) {
18602
+ throw new Error(UNPLANNED_NQL_READ_PROGRAM_ERROR);
18603
+ }
18478
18604
  if (hasExecutableNqlProgramSequence(compiledIntent.bundle)) {
18479
18605
  return this.executeNqlProgramSequence(compiledIntent, adapter);
18480
18606
  }
18481
18607
  assertConnectionAvailable(adapter, "nql().all()");
18608
+ if (compiledIntent.kind === "unplannedRead") {
18609
+ const compiled2 = adapter.compile(
18610
+ compiledIntent.bundle,
18611
+ this.nqlBundleCompileOptions()
18612
+ );
18613
+ return executeCompiledQuery(adapter, compiled2, "nql().all()");
18614
+ }
18482
18615
  if (compiledIntent.kind === "mutation") {
18483
18616
  return (await this.runMutationStatement(
18484
18617
  adapter,
@@ -20073,8 +20206,9 @@ var QueryBuilderImpl = class _QueryBuilderImpl {
20073
20206
  plan() {
20074
20207
  const intent = this.buildIntent();
20075
20208
  if (intent.lock && !this.ctx.inTransaction) {
20076
- console.warn(
20077
- "[dbsp] Row-level lock (FOR UPDATE/SHARE) used outside a transaction. Locks are only effective within a transaction."
20209
+ emitWarning(
20210
+ "[dbsp] Row-level lock (FOR UPDATE/SHARE) used outside a transaction. Locks are only effective within a transaction.",
20211
+ "runtime"
20078
20212
  );
20079
20213
  }
20080
20214
  const intentWithHints = this.applyRelationHints(intent);
@@ -23666,7 +23800,6 @@ export {
23666
23800
  star,
23667
23801
  stringAgg,
23668
23802
  subquery,
23669
- supportsDDLGeneration,
23670
23803
  supportsExecution,
23671
23804
  supportsIntrospection,
23672
23805
  supportsRawSql,