@dbsp/core 1.10.1 → 2.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,7 @@
1
1
  import * as _dbsp_types from '@dbsp/types';
2
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, ScalarSubqueryIntent, 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';
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';
4
4
  import { NqlCompilerOptions } from '@dbsp/nql';
5
- import * as v from 'valibot';
6
5
 
7
6
  /**
8
7
  * @module model-ir
@@ -560,12 +559,12 @@ declare function isAliasedColumn(value: unknown): value is AliasedColumn<string,
560
559
  * Supported column types in schema definitions.
561
560
  * Matches SchemaColumnType from schema.ts.
562
561
  */
563
- type SchemaColumnType$2 = 'string' | 'text' | 'uuid' | 'number' | 'integer' | 'decimal' | 'bigint' | 'boolean' | 'date' | 'time' | 'datetime' | 'timestamp' | 'json' | 'jsonb' | 'daterange' | 'tsrange' | 'tstzrange' | 'int4range' | 'int8range' | 'numrange';
562
+ type SchemaColumnType$1 = 'string' | 'text' | 'uuid' | 'number' | 'integer' | 'decimal' | 'bigint' | 'boolean' | 'date' | 'time' | 'datetime' | 'timestamp' | 'json' | 'jsonb' | 'daterange' | 'tsrange' | 'tstzrange' | 'int4range' | 'int8range' | 'numrange';
564
563
  /**
565
564
  * Column definition - short form or long form.
566
565
  */
567
- type ColumnDef$1 = SchemaColumnType$2 | {
568
- type: SchemaColumnType$2;
566
+ type ColumnDef$1 = SchemaColumnType$1 | {
567
+ type: SchemaColumnType$1;
569
568
  nullable?: boolean;
570
569
  unique?: boolean;
571
570
  primaryKey?: boolean;
@@ -609,8 +608,8 @@ type IsRef<T> = T extends {
609
608
  /**
610
609
  * Extract the column type from a ColumnDef.
611
610
  */
612
- type ExtractColumnType$1<C> = C extends SchemaColumnType$2 ? C : C extends {
613
- type: infer T extends SchemaColumnType$2;
611
+ type ExtractColumnType$1<C> = C extends SchemaColumnType$1 ? C : C extends {
612
+ type: infer T extends SchemaColumnType$1;
614
613
  } ? T : never;
615
614
  /**
616
615
  * Check if a column is nullable.
@@ -621,7 +620,7 @@ type IsNullable$1<C> = C extends {
621
620
  /**
622
621
  * Map schema column types to TypeScript types.
623
622
  */
624
- type MapColumnTypeToTS<T extends SchemaColumnType$2> = 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;
623
+ 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;
625
624
  /**
626
625
  * Infer the TypeScript type for a column definition.
627
626
  */
@@ -659,13 +658,13 @@ type GetRefTarget<TRef> = TRef extends {
659
658
  /**
660
659
  * Infer the row type for a table (used for relation target types).
661
660
  */
662
- type InferRowType$1<TTable extends TableDef$1> = {
661
+ type InferRowType<TTable extends TableDef$1> = {
663
662
  [K in keyof ExtractColumns<TTable> as K extends string ? K : never]: InferColumnTSType<TTable[K]>;
664
663
  };
665
664
  /**
666
665
  * Build RelationRef for a local relation (belongsTo - FK in this table).
667
666
  */
668
- type BuildLocalRelation<_TColName extends string, TRef extends RefDefinition$1, TSchema extends SchemaDefinition$1> = GetRefTarget<TRef> extends keyof TSchema ? RelationRef<GetRefTarget<TRef> & string, InferRowType$1<TSchema[GetRefTarget<TRef>]> | null, 'belongsTo', InferRowType$1<TSchema[GetRefTarget<TRef>]>> : never;
667
+ type BuildLocalRelation<_TColName extends string, TRef extends RefDefinition$1, TSchema extends SchemaDefinition$1> = GetRefTarget<TRef> extends keyof TSchema ? RelationRef<GetRefTarget<TRef> & string, InferRowType<TSchema[GetRefTarget<TRef>]> | null, 'belongsTo', InferRowType<TSchema[GetRefTarget<TRef>]>> : never;
669
668
  /**
670
669
  * Build local relations (belongsTo) for a table.
671
670
  */
@@ -682,7 +681,7 @@ type FindInverseRelations<TName extends string, TSchema extends SchemaDefinition
682
681
  inverse: infer I extends string;
683
682
  };
684
683
  } ? I : TTable extends `${string}s` ? TTable : `${TTable & string}s` : never : never;
685
- }[keyof TSchema[TTable]] : never]: TTable extends string ? RelationRef<TTable, Array<InferRowType$1<TSchema[TTable]>>, 'hasMany', InferRowType$1<TSchema[TTable]>> : never;
684
+ }[keyof TSchema[TTable]] : never]: TTable extends string ? RelationRef<TTable, Array<InferRowType<TSchema[TTable]>>, 'hasMany', InferRowType<TSchema[TTable]>> : never;
686
685
  };
687
686
  /**
688
687
  * Combine local and inverse relations for a table.
@@ -717,8 +716,8 @@ type InferTables<TSchema extends SchemaDefinition$1> = {
717
716
  /**
718
717
  * ARCH-005: Unified Schema API
719
718
  *
720
- * Replaces defineSchema(), TypedSchema, and GeneratedSchema with a single
721
- * schema() + ref() API. Relations are auto-inferred from FK declarations.
719
+ * Provides the schema() + ref() API. Relations are auto-inferred from FK
720
+ * declarations.
722
721
  *
723
722
  * @example
724
723
  * ```typescript
@@ -735,12 +734,12 @@ type InferTables<TSchema extends SchemaDefinition$1> = {
735
734
  * Supported column types in schema definitions.
736
735
  * Maps to ColumnType from ModelIR.
737
736
  */
738
- type SchemaColumnType$1 = ColumnType;
737
+ type SchemaColumnType = ColumnType;
739
738
  /**
740
739
  * Column definition - short form (just type) or long form (with options).
741
740
  */
742
- type ColumnDef = SchemaColumnType$1 | {
743
- type: SchemaColumnType$1;
741
+ type ColumnDef = SchemaColumnType | {
742
+ type: SchemaColumnType;
744
743
  dbType?: string;
745
744
  nullable?: boolean;
746
745
  unique?: boolean;
@@ -767,6 +766,8 @@ interface SelfRefRoles {
767
766
  * Options for ref() foreign key declarations.
768
767
  */
769
768
  interface RefOptions {
769
+ /** Target schema name (omit for same-schema references) */
770
+ schema?: string;
770
771
  /** Is this FK nullable? → optional relation */
771
772
  nullable?: boolean;
772
773
  /** Is this FK unique? → 1:1 instead of 1:N */
@@ -774,7 +775,7 @@ interface RefOptions {
774
775
  /** ON DELETE action */
775
776
  onDelete?: OnDeleteAction;
776
777
  /** ON UPDATE action */
777
- onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
778
+ onUpdate?: OnDeleteAction;
778
779
  /** Local relation name (e.g., 'createdBy' for createdById column) */
779
780
  as?: string;
780
781
  /** Inverse relation name on target table (e.g., 'writings' instead of 'author_posts') */
@@ -841,17 +842,36 @@ interface SchemaIndexOptions {
841
842
  columns: string[];
842
843
  /** Whether this is a unique index */
843
844
  unique?: boolean;
845
+ /**
846
+ * PG15+ — for a UNIQUE index, treat NULLs as not distinct
847
+ * (`NULLS NOT DISTINCT`); true is rejected for non-unique indexes. Emitted
848
+ * as declared; coherent server-version capability gating for all index
849
+ * features is tracked together in #245.
850
+ */
851
+ nullsNotDistinct?: boolean;
844
852
  /** Custom index name (auto-generated if not provided) */
845
853
  name?: string;
846
854
  /** Index access method (default: btree). E.g. 'gin', 'gist', 'hnsw', 'bm25' */
847
855
  method?: string;
848
856
  /** Partial index predicate (WHERE clause) */
849
857
  where?: string;
858
+ /**
859
+ * Non-key columns to include (INCLUDE clause, PG11+).
860
+ * Emitted as declared; coherent server-version capability gating for all
861
+ * index features is tracked together in #245.
862
+ */
863
+ include?: string[];
850
864
  /** Per-column operator class overrides. Key = column name, value = opclass name */
851
865
  opclass?: Record<string, string>;
852
866
  /** Index storage parameters (WITH clause). Key = param name, value = param value */
853
867
  with?: Record<string, string>;
854
868
  }
869
+ interface SchemaIndexValidationInput {
870
+ readonly columns: readonly string[];
871
+ readonly unique?: boolean;
872
+ readonly nullsNotDistinct?: boolean;
873
+ readonly name?: string;
874
+ }
855
875
  interface SchemaTableOptions {
856
876
  /** Indexes for this table (simple, composite, partial, GIN, HNSW, BM25, etc.) */
857
877
  indexes?: SchemaIndexOptions[];
@@ -952,6 +972,8 @@ interface SchemaOptions {
952
972
  interface Schema<T extends SchemaDefinition> {
953
973
  /** The raw schema definition */
954
974
  readonly definition: T;
975
+ /** Table-level constraints supplied to schema() or reconstructed from introspection */
976
+ readonly constraints?: SchemaConstraints;
955
977
  /** Converted ModelIR for use with ORM */
956
978
  readonly model: ModelIR;
957
979
  /** Table names */
@@ -1018,12 +1040,12 @@ interface InferredRangeValue<T> {
1018
1040
  /**
1019
1041
  * Maps a ColumnType string to its TypeScript type.
1020
1042
  */
1021
- type InferColumnType<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' ? JsonValue : T extends 'daterange' ? InferredRangeValue<Date> : T extends 'tsrange' | 'tstzrange' ? InferredRangeValue<Date> : T extends 'int4range' | 'int8range' ? InferredRangeValue<number> : T extends 'numrange' ? InferredRangeValue<number> : unknown;
1043
+ type InferColumnType<T extends SchemaColumnType> = 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' ? JsonValue : T extends 'daterange' ? InferredRangeValue<Date> : T extends 'tsrange' | 'tstzrange' ? InferredRangeValue<Date> : T extends 'int4range' | 'int8range' ? InferredRangeValue<number> : T extends 'numrange' ? InferredRangeValue<number> : unknown;
1022
1044
  /**
1023
1045
  * Extracts the type string from a ColumnDef (handles short and long forms).
1024
1046
  */
1025
- type ExtractColumnType<C extends ColumnDef> = C extends SchemaColumnType$1 ? C : C extends {
1026
- type: infer T extends SchemaColumnType$1;
1047
+ type ExtractColumnType<C extends ColumnDef> = C extends SchemaColumnType ? C : C extends {
1048
+ type: infer T extends SchemaColumnType;
1027
1049
  } ? T : never;
1028
1050
  /**
1029
1051
  * Checks if a ColumnDef is nullable.
@@ -1152,11 +1174,12 @@ declare function schema<T extends SchemaDefinition>(definition: T, constraints?:
1152
1174
  /**
1153
1175
  * Validation error during schema conversion.
1154
1176
  */
1155
- declare class SchemaValidationError$1 extends Error {
1177
+ declare class SchemaValidationError extends Error {
1156
1178
  readonly table?: string | undefined;
1157
1179
  readonly column?: string | undefined;
1158
1180
  constructor(message: string, table?: string | undefined, column?: string | undefined);
1159
1181
  }
1182
+ declare function validateSchemaIndexOptions(tableName: string, idx: SchemaIndexValidationInput): void;
1160
1183
  /**
1161
1184
  * Converts a schema definition to ModelIR.
1162
1185
  *
@@ -1208,337 +1231,8 @@ interface IntrospectableAdapter {
1208
1231
  declare function getSchemaFromDb<T extends SchemaDefinition = SchemaDefinition>(adapter: IntrospectableAdapter, options?: GetSchemaFromDbOptions): Promise<Schema<T>>;
1209
1232
 
1210
1233
  /**
1211
- * Schema DSL Types
1212
- *
1213
- * Input types for defineSchema() - the user-facing schema definition DSL.
1214
- * These types are simpler than the IR types and serve as the "source of truth"
1215
- * for schema definitions before they're processed into ModelIR.
1216
- *
1217
- * Migrated from @dbsp/schema/types.ts as part of ARCH-003.
1218
- */
1219
-
1220
- /**
1221
- * Supported column types in the schema DSL.
1222
- * Maps to database types during DDL generation.
1223
- */
1224
- type SchemaColumnType = 'uuid' | 'string' | 'text' | 'integer' | 'bigint' | 'decimal' | 'boolean' | 'timestamp' | 'date' | 'time' | 'json' | 'jsonb' | 'daterange' | 'tsrange' | 'tstzrange' | 'int4range' | 'int8range' | 'numrange';
1225
- /** Foreign key delete behavior */
1226
- type SchemaOnDeleteAction = 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
1227
- /**
1228
- * Foreign key reference definition.
1229
- * When present, takes priority over convention-based FK detection.
1230
- */
1231
- interface SchemaForeignKeyReference {
1232
- /** Target table name */
1233
- table: string;
1234
- /** Target column name (defaults to 'id') */
1235
- column?: string;
1236
- /** Delete behavior (CASCADE, SET NULL, RESTRICT, NO ACTION) */
1237
- onDelete?: SchemaOnDeleteAction;
1238
- /**
1239
- * Custom role name for parent direction in self-referential FKs.
1240
- * Required when table has multiple self-referential FKs.
1241
- * Example: parentRole: 'manager' for managerId FK
1242
- * @default 'parent' (for single self-ref FK)
1243
- */
1244
- parentRole?: string;
1245
- /**
1246
- * Custom role name for child direction in self-referential FKs.
1247
- * Required when table has multiple self-referential FKs.
1248
- * Example: childRole: 'subordinates' for managerId FK
1249
- * @default 'children' or pluralized parentRole (for single self-ref FK)
1250
- */
1251
- childRole?: string;
1252
- }
1253
- /**
1254
- * Column definition in the schema DSL.
1255
- */
1256
- interface SchemaColumnDefinition {
1257
- /** Column data type */
1258
- type: SchemaColumnType;
1259
- /** Whether the column is the primary key */
1260
- primaryKey?: boolean;
1261
- /** Whether the column allows NULL values */
1262
- nullable?: boolean;
1263
- /** Whether the column has a unique constraint */
1264
- unique?: boolean;
1265
- /** Default value (e.g., 'now()', 'gen_random_uuid()', 0, true) */
1266
- default?: string | number | boolean;
1267
- /** Explicit foreign key reference (takes priority over conventions) */
1268
- references?: SchemaForeignKeyReference;
1269
- /** Create an index on this column (true for auto-name, string for custom name) */
1270
- index?: boolean | string;
1271
- }
1272
- /**
1273
- * Table definition: mapping of column names to their definitions.
1274
- */
1275
- type SchemaTableDefinition = Record<string, SchemaColumnDefinition>;
1276
- /**
1277
- * All tables in the schema.
1234
+ * Naming and self-reference convention helpers.
1278
1235
  */
1279
- type SchemaTablesDefinition = Record<string, SchemaTableDefinition>;
1280
- /**
1281
- * Index definition for composite indexes.
1282
- */
1283
- interface SchemaIndexDefinition {
1284
- /** Columns included in the index */
1285
- columns: string[];
1286
- /** Whether this is a unique index */
1287
- unique?: boolean;
1288
- /** Custom index name (auto-generated if not provided) */
1289
- name?: string;
1290
- }
1291
- /**
1292
- * Index configuration by table.
1293
- */
1294
- type SchemaIndexesDefinition = Record<string, SchemaIndexDefinition[]>;
1295
- /**
1296
- * Relation kinds for discriminated union.
1297
- */
1298
- type SchemaRelationKind = 'belongsTo' | 'hasMany' | 'manyToMany';
1299
- /**
1300
- * Strategy for including related data in queries.
1301
- * - 'join': Use SQL JOIN (default for belongsTo)
1302
- * - 'subquery': Execute subquery query
1303
- * - 'cte': Use Common Table Expression
1304
- * - 'lateral': Use LATERAL JOIN
1305
- * - 'json_agg': Use JSON aggregation
1306
- * - 'auto': Let planner decide based on relation type
1307
- */
1308
- type SchemaIncludeStrategy = 'join' | 'subquery' | 'cte' | 'lateral' | 'json_agg' | 'auto';
1309
- /**
1310
- * Base properties shared by all relation types.
1311
- */
1312
- interface SchemaRelationBase {
1313
- /** Target table name */
1314
- target: string;
1315
- /** Include strategy hint for the planner */
1316
- includeStrategy?: SchemaIncludeStrategy;
1317
- }
1318
- /**
1319
- * BelongsTo relation: source table has FK to target table.
1320
- * Example: posts.author → users (posts.authorId references users.id)
1321
- */
1322
- interface SchemaBelongsToRelation extends SchemaRelationBase {
1323
- kind: 'belongsTo';
1324
- /** Foreign key column in the source table */
1325
- foreignKey: string;
1326
- /** Target column (defaults to 'id') */
1327
- targetKey?: string;
1328
- }
1329
- /**
1330
- * HasMany relation: target table has FK to source table.
1331
- * Example: users.posts → posts (posts.authorId references users.id)
1332
- */
1333
- interface SchemaHasManyRelation extends SchemaRelationBase {
1334
- kind: 'hasMany';
1335
- /** Foreign key column in the target table */
1336
- foreignKey: string;
1337
- /** Source column (defaults to 'id') */
1338
- sourceKey?: string;
1339
- }
1340
- /**
1341
- * ManyToMany relation: junction table connects source and target.
1342
- * Example: posts ↔ categories via post_categories
1343
- */
1344
- interface SchemaManyToManyRelation extends SchemaRelationBase {
1345
- kind: 'manyToMany';
1346
- /** Junction table name */
1347
- through: string;
1348
- /** FK column in junction pointing to source */
1349
- sourceFk: string;
1350
- /** FK column in junction pointing to target */
1351
- targetFk: string;
1352
- }
1353
- /**
1354
- * Union of all relation types.
1355
- * Use `kind` field for type narrowing.
1356
- */
1357
- type SchemaRelationDefinition = SchemaBelongsToRelation | SchemaHasManyRelation | SchemaManyToManyRelation;
1358
- /**
1359
- * Explicit relations mapping.
1360
- * Keys are 'sourceTable.relationName' format.
1361
- */
1362
- type SchemaRelationsDefinition = Record<string, SchemaRelationDefinition>;
1363
- /**
1364
- * Strategy hint for filtering on to-many relations.
1365
- */
1366
- type SchemaFilterStrategy = 'exists' | 'join';
1367
- /**
1368
- * Cardinality hint for relation traversal.
1369
- */
1370
- type SchemaCardinality = 'one' | 'many';
1371
- /**
1372
- * Hint definition for a specific relation path.
1373
- */
1374
- interface SchemaHintDefinition {
1375
- /** Preferred filter strategy */
1376
- defaultStrategy?: SchemaFilterStrategy;
1377
- /** Expected cardinality */
1378
- cardinality?: SchemaCardinality;
1379
- }
1380
- /**
1381
- * All hints, keyed by 'table.relation' path.
1382
- */
1383
- type SchemaHintsDefinition = Record<string, SchemaHintDefinition>;
1384
- /**
1385
- * Convention settings for automatic FK detection and naming.
1386
- */
1387
- interface SchemaConventionsDefinition {
1388
- /**
1389
- * Pattern for foreign key column names.
1390
- * {singular} is replaced with singular table name.
1391
- * @default '{singular}Id'
1392
- */
1393
- fkPattern?: string;
1394
- /**
1395
- * Whether to auto-pluralize relation names.
1396
- * @default true
1397
- */
1398
- pluralize?: boolean;
1399
- /**
1400
- * Column names recognized as timestamps.
1401
- * @default ['createdAt', 'updatedAt']
1402
- */
1403
- timestamps?: string[];
1404
- /**
1405
- * Automatically create indexes on foreign key columns.
1406
- * FK columns are frequently used in JOINs, so indexing is a best practice.
1407
- * @default true
1408
- */
1409
- fkAutoIndex?: boolean;
1410
- }
1411
- /**
1412
- * Complete schema definition input for defineSchema() wrapped form.
1413
- * Prefer the new hybrid API: defineSchema(tables, config?)
1414
- */
1415
- interface SchemaDefinitionInput<T extends SchemaTablesDefinition = SchemaTablesDefinition> {
1416
- /** Table definitions */
1417
- tables: T;
1418
- /** Explicit relation definitions (override auto-detected) */
1419
- relations?: SchemaRelationsDefinition;
1420
- /** Planner hints */
1421
- hints?: SchemaHintsDefinition;
1422
- /** Convention configuration */
1423
- conventions?: SchemaConventionsDefinition;
1424
- }
1425
- /**
1426
- * Per-table default filters applied to all queries.
1427
- * Commonly used for soft delete filtering.
1428
- */
1429
- type SchemaDefaultFilters = {
1430
- [tableName: string]: WhereIntent;
1431
- };
1432
- /**
1433
- * Configuration options for defineSchema (new API).
1434
- */
1435
- interface SchemaConfigInput {
1436
- /** Explicit relation definitions (override auto-detected) */
1437
- relations?: SchemaRelationsDefinition;
1438
- /** Planner hints */
1439
- hints?: SchemaHintsDefinition;
1440
- /** Convention configuration */
1441
- conventions?: SchemaConventionsDefinition;
1442
- /** Table-level index definitions (composite indexes) */
1443
- indexes?: SchemaIndexesDefinition;
1444
- /**
1445
- * Default filters applied automatically to all queries on each table.
1446
- * Use for soft delete (`isNull('deletedAt')`), multi-tenant, or active filtering.
1447
- * Override per-query with `.withoutDefaultFilters()`.
1448
- */
1449
- defaultFilters?: SchemaDefaultFilters;
1450
- }
1451
- /**
1452
- * Resolved schema with all relations (explicit + inferred).
1453
- * This is the output of defineSchema().
1454
- */
1455
- interface ResolvedSchema<T extends SchemaTablesDefinition = SchemaTablesDefinition> {
1456
- /** Original table definitions */
1457
- tables: T;
1458
- /** All relations (explicit + auto-detected) */
1459
- relations: SchemaRelationsDefinition;
1460
- /** Planner hints */
1461
- hints: SchemaHintsDefinition;
1462
- /** Resolved conventions with defaults applied */
1463
- conventions: Required<SchemaConventionsDefinition>;
1464
- /** Table-level index definitions */
1465
- indexes: SchemaIndexesDefinition;
1466
- /** Default filters per table (e.g., soft delete) */
1467
- defaultFilters: SchemaDefaultFilters;
1468
- }
1469
- /**
1470
- * Type guard for BelongsTo relation.
1471
- */
1472
- declare function isBelongsTo(rel: SchemaRelationDefinition): rel is SchemaBelongsToRelation;
1473
- /**
1474
- * Type guard for HasMany relation.
1475
- */
1476
- declare function isHasMany(rel: SchemaRelationDefinition): rel is SchemaHasManyRelation;
1477
- /**
1478
- * Type guard for ManyToMany relation.
1479
- */
1480
- declare function isManyToMany(rel: SchemaRelationDefinition): rel is SchemaManyToManyRelation;
1481
-
1482
- /**
1483
- * Schema DSL - defineSchema() function
1484
- *
1485
- * Main entry point for defining the schema Source of Truth.
1486
- * Merges explicit definitions with convention-inferred relations.
1487
- *
1488
- * Migrated from @dbsp/schema/define.ts as part of ARCH-003.
1489
- */
1490
-
1491
- /**
1492
- * Define a schema with tables, relations, hints, and conventions.
1493
- *
1494
- * @example Simple - just tables
1495
- * ```typescript
1496
- * const schema = defineSchema({
1497
- * users: {
1498
- * id: { type: 'uuid', primaryKey: true },
1499
- * name: { type: 'string', nullable: false },
1500
- * },
1501
- * posts: {
1502
- * id: { type: 'uuid', primaryKey: true },
1503
- * authorId: { type: 'uuid', references: { table: 'users' } },
1504
- * },
1505
- * });
1506
- * ```
1507
- *
1508
- * @example With config
1509
- * ```typescript
1510
- * const schema = defineSchema(
1511
- * {
1512
- * users: { id: { type: 'uuid', primaryKey: true } },
1513
- * roles: { id: { type: 'uuid', primaryKey: true } },
1514
- * },
1515
- * {
1516
- * relations: {...}
1517
- * }
1518
- * );
1519
- * ```
1520
- */
1521
- declare function defineSchema<T extends SchemaTablesDefinition>(tables: T, config?: SchemaConfigInput): ResolvedSchema<T>;
1522
- /**
1523
- * Error thrown when schema validation fails.
1524
- */
1525
- declare class SchemaValidationError extends Error {
1526
- constructor(message: string);
1527
- }
1528
-
1529
- /**
1530
- * Schema Convention Inference
1531
- *
1532
- * Detects foreign keys and M:N relations using:
1533
- * 1. Explicit `references` (highest priority)
1534
- * 2. Convention patterns (fallback)
1535
- *
1536
- * M:N auto-detection: tables with exactly 2 FKs and no business columns.
1537
- *
1538
- * Migrated from @dbsp/schema/conventions.ts as part of ARCH-003.
1539
- */
1540
-
1541
- declare const DEFAULT_CONVENTIONS: Required<SchemaConventionsDefinition>;
1542
1236
  /**
1543
1237
  * Convert table name to singular form.
1544
1238
  * Simple heuristic: remove trailing 's' if present.
@@ -1568,49 +1262,6 @@ declare function capitalize(name: string): string;
1568
1262
  * Decapitalize first letter.
1569
1263
  */
1570
1264
  declare function decapitalize(name: string): string;
1571
- interface DetectedFK {
1572
- /** Column name in source table */
1573
- column: string;
1574
- /** Target table name */
1575
- targetTable: string;
1576
- /** Inferred relation name (e.g., 'author' from 'authorId') */
1577
- inferredName: string;
1578
- /** Whether this was explicitly defined via `references` */
1579
- explicit: boolean;
1580
- /** Target column (from references.column or default 'id') */
1581
- targetColumn: string;
1582
- /** Custom parent role for self-ref FKs (from parentRole or inferred) */
1583
- parentRole?: string;
1584
- /** Custom child role for self-ref FKs (from childRole or inferred) */
1585
- childRole?: string;
1586
- }
1587
- /**
1588
- * Detect foreign keys in a table.
1589
- * Priority: explicit `references` > convention pattern.
1590
- */
1591
- declare function detectForeignKeys(tableName: string, table: SchemaTableDefinition, conventions: Required<SchemaConventionsDefinition>, tableNames: Set<string>): DetectedFK[];
1592
- interface DetectedManyToMany {
1593
- /** Junction table name */
1594
- junction: string;
1595
- /** First table in the M:N relation */
1596
- tableA: string;
1597
- /** Second table in the M:N relation */
1598
- tableB: string;
1599
- /** FK column pointing to tableA */
1600
- fkA: string;
1601
- /** FK column pointing to tableB */
1602
- fkB: string;
1603
- }
1604
- /**
1605
- * Detect pure M:N junction tables.
1606
- * Criteria: exactly 2 FK columns, no business columns.
1607
- */
1608
- declare function detectManyToMany(tables: SchemaTablesDefinition, conventions: Required<SchemaConventionsDefinition>, tableNames: Set<string>): DetectedManyToMany[];
1609
- /**
1610
- * Infer all relations from table definitions.
1611
- * Returns a map of 'sourceTable.relationName' → RelationDefinition.
1612
- */
1613
- declare function inferRelationsFromSchema(tables: SchemaTablesDefinition, conventions: Required<SchemaConventionsDefinition>, explicitRelations?: SchemaRelationsDefinition): SchemaRelationsDefinition;
1614
1265
 
1615
1266
  /**
1616
1267
  * @module planner
@@ -4214,396 +3865,6 @@ declare class RawCteQueryBuilder<TResult = unknown> {
4214
3865
  */
4215
3866
  declare function createRawCteBuilder<TResult = unknown>(cteName: string, options: RecursiveOptions, adapter?: Adapter, schemaName?: string): RawCteQueryBuilder<TResult>;
4216
3867
 
4217
- /**
4218
- * ARCH-002 Block 6: Schema Bridge
4219
- *
4220
- * Converts generated schema (from dbsp generate manifest) to ModelIR.
4221
- * This enables sync createOrm usage with codegen-first schemas.
4222
- */
4223
-
4224
- /**
4225
- * Column type in generated schema.
4226
- */
4227
- type GeneratedColumnType = 'string' | 'text' | 'number' | 'integer' | 'bigint' | 'decimal' | 'boolean' | 'date' | 'timestamp' | 'datetime' | 'time' | 'json' | 'jsonb' | 'uuid' | 'daterange' | 'tstzrange' | 'int4range' | 'tsrange' | 'int8range' | 'numrange';
4228
- /**
4229
- * Column definition in generated schema.
4230
- */
4231
- interface GeneratedColumn {
4232
- readonly type: GeneratedColumnType;
4233
- readonly primaryKey?: boolean;
4234
- readonly nullable?: boolean;
4235
- readonly unique?: boolean;
4236
- readonly autoIncrement?: boolean;
4237
- readonly default?: string;
4238
- readonly references?: {
4239
- readonly table: string;
4240
- readonly column?: string;
4241
- readonly onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
4242
- /** Create an index on this FK column (matches ColumnDefinitionSchema index field) */
4243
- readonly index?: boolean;
4244
- /** Role name for parent traversal in self-ref hierarchies (e.g., 'parent') */
4245
- readonly parentRole?: string;
4246
- /** Role name for child traversal in self-ref hierarchies (e.g., 'children') */
4247
- readonly childRole?: string;
4248
- };
4249
- /** Create an index on this column (true for auto-name, string for custom name) */
4250
- readonly index?: boolean | string;
4251
- }
4252
- /**
4253
- * Table definition in generated schema.
4254
- */
4255
- interface GeneratedForeignKey {
4256
- readonly columns: readonly string[];
4257
- readonly references: {
4258
- readonly table: string;
4259
- readonly columns: readonly string[];
4260
- };
4261
- readonly onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
4262
- readonly onUpdate?: 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
4263
- }
4264
- interface GeneratedIndex {
4265
- readonly columns: readonly string[];
4266
- readonly unique?: boolean;
4267
- readonly name?: string;
4268
- }
4269
- interface GeneratedTableWithConfig {
4270
- readonly columns: Record<string, GeneratedColumn>;
4271
- readonly primaryKey?: string | readonly string[];
4272
- readonly foreignKeys?: readonly GeneratedForeignKey[];
4273
- readonly indexes?: readonly GeneratedIndex[];
4274
- }
4275
- type GeneratedFlatTable = Record<string, GeneratedColumn>;
4276
- type GeneratedTable = GeneratedFlatTable | GeneratedTableWithConfig;
4277
- /**
4278
- * Relation kind in generated schema (discriminated union).
4279
- */
4280
- type GeneratedRelationKind = 'belongsTo' | 'hasMany' | 'manyToMany';
4281
- /**
4282
- * Include strategy for relations.
4283
- */
4284
- type GeneratedIncludeStrategy = 'join' | 'subquery' | 'cte' | 'lateral' | 'json_agg' | 'auto';
4285
- /**
4286
- * BelongsTo relation in generated schema.
4287
- */
4288
- interface GeneratedBelongsTo {
4289
- readonly kind: 'belongsTo';
4290
- readonly target: string;
4291
- readonly foreignKey: string | readonly string[];
4292
- readonly targetKey?: string | readonly string[];
4293
- readonly includeStrategy?: GeneratedIncludeStrategy;
4294
- }
4295
- /**
4296
- * HasMany relation in generated schema.
4297
- */
4298
- interface GeneratedHasMany {
4299
- readonly kind: 'hasMany';
4300
- readonly target: string;
4301
- readonly foreignKey: string | readonly string[];
4302
- readonly sourceKey?: string | readonly string[];
4303
- readonly includeStrategy?: GeneratedIncludeStrategy;
4304
- readonly cardinality?: 'one' | 'many';
4305
- }
4306
- /**
4307
- * ManyToMany relation in generated schema.
4308
- */
4309
- interface GeneratedManyToMany {
4310
- readonly kind: 'manyToMany';
4311
- readonly target: string;
4312
- readonly through: string;
4313
- readonly sourceFk: string;
4314
- readonly targetFk: string;
4315
- readonly includeStrategy?: GeneratedIncludeStrategy;
4316
- }
4317
- /**
4318
- * Relation definition in generated schema.
4319
- */
4320
- type GeneratedRelation = GeneratedBelongsTo | GeneratedHasMany | GeneratedManyToMany;
4321
- /**
4322
- * Hint definition in generated schema.
4323
- */
4324
- interface GeneratedHint {
4325
- readonly defaultStrategy?: 'exists' | 'join';
4326
- readonly cardinality?: 'one' | 'many';
4327
- }
4328
- /**
4329
- * Conventions in generated schema.
4330
- */
4331
- interface GeneratedConventions {
4332
- readonly fkPattern: string;
4333
- readonly pluralize: boolean;
4334
- readonly timestamps: readonly string[];
4335
- readonly fkAutoIndex: boolean;
4336
- }
4337
- /**
4338
- * Complete generated schema (output of dbsp generate manifest).
4339
- *
4340
- * @typeParam TTables - The tables type, preserving literal table names for autocomplete.
4341
- * When using `as const` on your schema definition, table names will be preserved.
4342
- *
4343
- * @example
4344
- * ```typescript
4345
- * const schema = {
4346
- * tables: {
4347
- * users: { id: { type: 'uuid', primaryKey: true }, name: { type: 'string' } },
4348
- * posts: { id: { type: 'uuid', primaryKey: true }, title: { type: 'string' } },
4349
- * },
4350
- * relations: {},
4351
- * hints: {},
4352
- * conventions: { fkPattern: '{singular}Id', pluralize: true, timestamps: [], fkAutoIndex: true },
4353
- * } as const satisfies GeneratedSchema;
4354
- *
4355
- * // TypeScript knows: keyof typeof schema.tables = 'users' | 'posts'
4356
- * ```
4357
- */
4358
- interface GeneratedSchema<TTables extends Record<string, GeneratedTable> = Record<string, GeneratedTable>> {
4359
- readonly tables: TTables;
4360
- readonly relations: Record<string, GeneratedRelation>;
4361
- readonly hints: Record<string, GeneratedHint>;
4362
- readonly conventions: GeneratedConventions;
4363
- }
4364
- /**
4365
- * Map a GeneratedColumnType to its TypeScript runtime type.
4366
- */
4367
- type ColumnTypeToTS<T extends GeneratedColumnType> = T extends 'string' | 'text' | 'uuid' ? string : T extends 'number' | 'integer' | 'decimal' ? number : T extends 'bigint' ? bigint : T extends 'boolean' ? boolean : T extends 'date' | 'timestamp' | 'datetime' ? Date : T extends 'time' ? string : T extends 'json' | 'jsonb' ? unknown : T extends 'daterange' | 'tstzrange' | 'int4range' | 'tsrange' | 'int8range' | 'numrange' ? string : never;
4368
- /**
4369
- * Infer the TypeScript row type from a GeneratedTable definition.
4370
- */
4371
- type GeneratedColumnsOf<T extends GeneratedTable> = T extends GeneratedTableWithConfig ? T['columns'] : T;
4372
- type InferRowType<T extends GeneratedTable> = {
4373
- [K in keyof GeneratedColumnsOf<T>]: GeneratedColumnsOf<T>[K] extends GeneratedColumn ? GeneratedColumnsOf<T>[K]['nullable'] extends true ? ColumnTypeToTS<GeneratedColumnsOf<T>[K]['type']> | null : ColumnTypeToTS<GeneratedColumnsOf<T>[K]['type']> : never;
4374
- };
4375
- /**
4376
- * Infer the database type from a GeneratedSchema.
4377
- * Maps each table name to its row type.
4378
- *
4379
- * @example
4380
- * ```typescript
4381
- * const schema = { tables: { users: { id: { type: 'uuid' } } } } as const satisfies GeneratedSchema;
4382
- * type DB = InferDBFromSchema<typeof schema>;
4383
- * // DB = { users: { id: string } }
4384
- * ```
4385
- */
4386
- type InferDBFromSchema<S extends GeneratedSchema> = {
4387
- [TableName in keyof S['tables'] & string]: InferRowType<S['tables'][TableName]>;
4388
- };
4389
- /**
4390
- * Build a ModelIR from a generated schema.
4391
- *
4392
- * This is the main entry point for the schema bridge.
4393
- * It converts the output of `dbsp generate manifest` into a ModelIR
4394
- * that can be used with createOrm.
4395
- *
4396
- * @example
4397
- * ```typescript
4398
- * import { schema } from './generated/dbsp/schema';
4399
- * import { buildModelFromSchema, createOrm } from '@dbsp/core';
4400
- *
4401
- * const model = buildModelFromSchema(schema);
4402
- * const orm = createOrm({ model, adapter });
4403
- * ```
4404
- */
4405
- declare function buildModelFromSchema(schema: GeneratedSchema): ModelIR;
4406
- /**
4407
- * Build ModelIR directly from ResolvedSchema.
4408
- *
4409
- * Combines the conversion steps: ResolvedSchema → GeneratedSchema → ModelIR.
4410
- * This is the canonical path for creating ModelIR from user-defined schemas.
4411
- *
4412
- * @example
4413
- * ```typescript
4414
- * import { defineSchema, buildModelFromResolvedSchema } from '@dbsp/core';
4415
- *
4416
- * const schema = defineSchema({ users: { ... } }, { relations: { ... } });
4417
- * const model = buildModelFromResolvedSchema(schema);
4418
- * ```
4419
- */
4420
- declare function buildModelFromResolvedSchema(schema: ResolvedSchema): ModelIR;
4421
- /**
4422
- * Type guard for GeneratedSchema.
4423
- *
4424
- * Note: Both GeneratedSchema and ResolvedSchema have the same structure,
4425
- * so this check will return true for both. Use `isResolvedSchema()` to
4426
- * specifically detect ResolvedSchema (from @dbsp/schema).
4427
- */
4428
- declare function isGeneratedSchema(value: unknown): value is GeneratedSchema;
4429
- /**
4430
- * Type guard for ResolvedSchema (from @dbsp/schema).
4431
- *
4432
- * Detects ResolvedSchema by checking for PostgreSQL-specific column types
4433
- * like 'time' and 'jsonb' that only exist in ResolvedSchema.
4434
- *
4435
- * Note: If the schema has no such types, this may return false even for
4436
- * a valid ResolvedSchema. In that case, the schema can be used directly
4437
- * as a GeneratedSchema since both have the same structure.
4438
- */
4439
- declare function isResolvedSchema(value: unknown): boolean;
4440
- /**
4441
- * Normalize a schema input to GeneratedSchema.
4442
- *
4443
- * This function accepts either a GeneratedSchema or a ResolvedSchema
4444
- * and returns a GeneratedSchema. If the input is already a GeneratedSchema,
4445
- * it is returned as-is. If it's a ResolvedSchema, it is converted.
4446
- *
4447
- * This is the recommended way to accept schemas in APIs that need to
4448
- * support both schema formats transparently.
4449
- *
4450
- * @param input - Either a GeneratedSchema or ResolvedSchema
4451
- * @returns GeneratedSchema (possibly converted from ResolvedSchema)
4452
- * @throws Error if the input is not a valid schema
4453
- *
4454
- * @example
4455
- * ```typescript
4456
- * import { normalizeSchema } from '@dbsp/core';
4457
- *
4458
- * // Works with GeneratedSchema (from codegen)
4459
- * const schema1 = normalizeSchema(generatedSchema);
4460
- *
4461
- * // Works with ResolvedSchema (from defineSchema())
4462
- * const schema2 = normalizeSchema(resolvedSchema);
4463
- * ```
4464
- */
4465
- declare function normalizeSchema(input: unknown): GeneratedSchema;
4466
- /**
4467
- * Complete ResolvedSchema validation schema
4468
- */
4469
- declare const ResolvedSchemaValidation: v.ObjectSchema<{
4470
- readonly tables: v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.UnionSchema<[v.ObjectSchema<{
4471
- readonly columns: v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
4472
- readonly type: v.PicklistSchema<["uuid", "string", "text", "integer", "bigint", "decimal", "boolean", "timestamp", "date", "time", "json", "jsonb", "daterange", "tstzrange", "int4range", "tsrange", "int8range", "numrange"], undefined>;
4473
- readonly primaryKey: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4474
- readonly nullable: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4475
- readonly unique: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4476
- readonly autoIncrement: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4477
- readonly default: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.NumberSchema<undefined>, v.BooleanSchema<undefined>], undefined>, undefined>;
4478
- readonly references: v.OptionalSchema<v.ObjectSchema<{
4479
- readonly table: v.StringSchema<undefined>;
4480
- readonly column: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4481
- readonly onDelete: v.OptionalSchema<v.PicklistSchema<["CASCADE", "SET NULL", "RESTRICT", "NO ACTION"], undefined>, undefined>;
4482
- readonly index: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4483
- readonly parentRole: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4484
- readonly childRole: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4485
- }, undefined>, undefined>;
4486
- readonly index: v.OptionalSchema<v.UnionSchema<[v.BooleanSchema<undefined>, v.StringSchema<undefined>], undefined>, undefined>;
4487
- }, undefined>, undefined>]>;
4488
- readonly primaryKey: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>, undefined>;
4489
- readonly foreignKeys: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
4490
- readonly columns: v.ArraySchema<v.StringSchema<undefined>, undefined>;
4491
- readonly references: v.ObjectSchema<{
4492
- readonly table: v.StringSchema<undefined>;
4493
- readonly columns: v.ArraySchema<v.StringSchema<undefined>, undefined>;
4494
- }, undefined>;
4495
- readonly onDelete: v.OptionalSchema<v.PicklistSchema<["CASCADE", "SET NULL", "RESTRICT", "NO ACTION"], undefined>, undefined>;
4496
- readonly onUpdate: v.OptionalSchema<v.PicklistSchema<["CASCADE", "SET NULL", "RESTRICT", "NO ACTION"], undefined>, undefined>;
4497
- }, undefined>, undefined>, undefined>;
4498
- readonly indexes: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
4499
- readonly columns: v.ArraySchema<v.StringSchema<undefined>, undefined>;
4500
- readonly unique: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4501
- readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4502
- }, undefined>, undefined>, undefined>;
4503
- }, undefined>, v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
4504
- readonly type: v.PicklistSchema<["uuid", "string", "text", "integer", "bigint", "decimal", "boolean", "timestamp", "date", "time", "json", "jsonb", "daterange", "tstzrange", "int4range", "tsrange", "int8range", "numrange"], undefined>;
4505
- readonly primaryKey: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4506
- readonly nullable: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4507
- readonly unique: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4508
- readonly autoIncrement: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4509
- readonly default: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.NumberSchema<undefined>, v.BooleanSchema<undefined>], undefined>, undefined>;
4510
- readonly references: v.OptionalSchema<v.ObjectSchema<{
4511
- readonly table: v.StringSchema<undefined>;
4512
- readonly column: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4513
- readonly onDelete: v.OptionalSchema<v.PicklistSchema<["CASCADE", "SET NULL", "RESTRICT", "NO ACTION"], undefined>, undefined>;
4514
- readonly index: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4515
- readonly parentRole: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4516
- readonly childRole: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4517
- }, undefined>, undefined>;
4518
- readonly index: v.OptionalSchema<v.UnionSchema<[v.BooleanSchema<undefined>, v.StringSchema<undefined>], undefined>, undefined>;
4519
- }, undefined>, undefined>]>], undefined>, undefined>]>;
4520
- readonly relations: v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.VariantSchema<"kind", [v.ObjectSchema<{
4521
- readonly kind: v.LiteralSchema<"belongsTo", undefined>;
4522
- readonly target: v.StringSchema<undefined>;
4523
- readonly foreignKey: v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>;
4524
- readonly targetKey: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>, undefined>;
4525
- readonly includeStrategy: v.OptionalSchema<v.PicklistSchema<["join", "subquery", "cte", "lateral", "json_agg", "auto"], undefined>, undefined>;
4526
- }, undefined>, v.ObjectSchema<{
4527
- readonly kind: v.LiteralSchema<"hasMany", undefined>;
4528
- readonly target: v.StringSchema<undefined>;
4529
- readonly foreignKey: v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>;
4530
- readonly sourceKey: v.OptionalSchema<v.UnionSchema<[v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>], undefined>, undefined>;
4531
- readonly includeStrategy: v.OptionalSchema<v.PicklistSchema<["join", "subquery", "cte", "lateral", "json_agg", "auto"], undefined>, undefined>;
4532
- }, undefined>, v.ObjectSchema<{
4533
- readonly kind: v.LiteralSchema<"manyToMany", undefined>;
4534
- readonly target: v.StringSchema<undefined>;
4535
- readonly through: v.StringSchema<undefined>;
4536
- readonly sourceFk: v.StringSchema<undefined>;
4537
- readonly targetFk: v.StringSchema<undefined>;
4538
- readonly includeStrategy: v.OptionalSchema<v.PicklistSchema<["join", "subquery", "cte", "lateral", "json_agg", "auto"], undefined>, undefined>;
4539
- }, undefined>], undefined>, undefined>]>;
4540
- readonly hints: v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
4541
- readonly defaultStrategy: v.OptionalSchema<v.PicklistSchema<["exists", "join"], undefined>, undefined>;
4542
- readonly cardinality: v.OptionalSchema<v.PicklistSchema<["one", "many"], undefined>, undefined>;
4543
- }, undefined>, undefined>]>;
4544
- readonly conventions: v.ObjectSchema<{
4545
- readonly fkPattern: v.StringSchema<undefined>;
4546
- readonly pluralize: v.BooleanSchema<undefined>;
4547
- readonly timestamps: v.ArraySchema<v.StringSchema<undefined>, undefined>;
4548
- readonly fkAutoIndex: v.BooleanSchema<undefined>;
4549
- }, undefined>;
4550
- readonly indexes: v.OptionalSchema<v.SchemaWithPipe<readonly [v.UnknownSchema, v.CheckAction<unknown, "Schema keys must not include prototype-pollution names (__proto__, constructor, prototype)">, v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.ObjectSchema<{
4551
- readonly columns: v.ArraySchema<v.StringSchema<undefined>, undefined>;
4552
- readonly unique: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
4553
- readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
4554
- }, undefined>, undefined>, undefined>]>, undefined>;
4555
- }, undefined>;
4556
- /**
4557
- * Type inferred from ResolvedSchemaValidation
4558
- */
4559
- type ValidatedResolvedSchema = v.InferOutput<typeof ResolvedSchemaValidation>;
4560
- /**
4561
- * Result of schema conversion.
4562
- */
4563
- type SchemaConversionResult = {
4564
- success: true;
4565
- schema: GeneratedSchema;
4566
- } | {
4567
- success: false;
4568
- errors: v.BaseIssue<unknown>[];
4569
- };
4570
- /**
4571
- * Convert a ResolvedSchema (from @dbsp/schema) to GeneratedSchema.
4572
- *
4573
- * This function validates the input using Valibot and then converts the
4574
- * schema structure to the format expected by createOrm().
4575
- *
4576
- * @param input - The ResolvedSchema to convert (output of defineSchema())
4577
- * @returns Conversion result with either the converted schema or validation errors
4578
- *
4579
- * @example
4580
- * ```typescript
4581
- * import { defineSchema } from '@dbsp/schema';
4582
- * import { resolvedSchemaToGeneratedSchema, createOrm } from '@dbsp/core';
4583
- *
4584
- * const resolved = defineSchema({ tables: { users: { id: { type: 'uuid' } } } });
4585
- * const result = resolvedSchemaToGeneratedSchema(resolved);
4586
- *
4587
- * if (result.success) {
4588
- * const orm = createOrm({ schema: result.schema, adapter });
4589
- * } else {
4590
- * console.error('Schema validation failed:', result.errors);
4591
- * }
4592
- * ```
4593
- */
4594
- declare function resolvedSchemaToGeneratedSchema(input: unknown): SchemaConversionResult;
4595
- /**
4596
- * Assert and convert a ResolvedSchema to GeneratedSchema.
4597
- *
4598
- * Throws an error if validation fails. Use this when you're confident
4599
- * the input is valid and want cleaner code without result checking.
4600
- *
4601
- * @param input - The ResolvedSchema to convert
4602
- * @returns The converted GeneratedSchema
4603
- * @throws Error if validation fails
4604
- */
4605
- declare function assertResolvedSchemaToGeneratedSchema(input: unknown): GeneratedSchema;
4606
-
4607
3868
  /**
4608
3869
  * Type definitions for table-scoped DDL operations.
4609
3870
  *
@@ -4654,9 +3915,9 @@ type TableDDL = {
4654
3915
  */
4655
3916
  /**
4656
3917
  * Union type for all ORM options.
4657
- * Prefer specific option types (OrmOptionsWithModel, OrmOptionsWithSchema, OrmOptionsWithAdapter).
3918
+ * Prefer specific option types (OrmOptionsWithModel, OrmOptionsWithAdapter).
4658
3919
  */
4659
- type OrmOptions<DB = unknown> = OrmOptionsWithModel<DB> | OrmOptionsWithSchema<GeneratedSchema, DB> | OrmOptionsWithAdapter<DB>;
3920
+ type OrmOptions<DB = unknown> = OrmOptionsWithModel<DB> | OrmOptionsWithAdapter<DB>;
4660
3921
  /**
4661
3922
  * Base options shared by all ORM option variants.
4662
3923
  */
@@ -4711,30 +3972,11 @@ interface OrmOptionsBase<DB = unknown> {
4711
3972
  }
4712
3973
  /**
4713
3974
  * OrmOptions with explicit model (sync creation).
4714
- * Prefer OrmOptionsWithSchema for codegen-first approach.
4715
3975
  */
4716
3976
  interface OrmOptionsWithModel<DB = unknown> extends OrmOptionsBase<DB> {
4717
3977
  readonly model: ModelIR;
4718
3978
  readonly schema?: never;
4719
3979
  }
4720
- /**
4721
- * OrmOptions with generated schema (sync creation, codegen-first).
4722
- * Preferred approach for ARCH-002 codegen-first architecture.
4723
- *
4724
- * @typeParam TSchema - The schema type (inferred from schema value)
4725
- * @typeParam DB - The database type (inferred from TSchema when possible)
4726
- *
4727
- * @example
4728
- * ```typescript
4729
- * const schema = { tables: { users: { id: { type: 'uuid' } } } } as const satisfies GeneratedSchema;
4730
- * const orm = createOrm({ schema, adapter });
4731
- * // DB is inferred as { users: { id: string } }
4732
- * ```
4733
- */
4734
- interface OrmOptionsWithSchema<TSchema extends GeneratedSchema = GeneratedSchema, DB = InferDBFromSchema<TSchema>> extends OrmOptionsBase<DB> {
4735
- readonly schema: TSchema;
4736
- readonly model?: never;
4737
- }
4738
3980
  /**
4739
3981
  * OrmOptions without model, requires adapter for auto-introspection (async creation).
4740
3982
  */
@@ -4746,7 +3988,7 @@ interface OrmOptionsWithAdapter<DB = unknown> extends OrmOptionsBase<DB> {
4746
3988
  /**
4747
3989
  * ORM instance created by createOrm().
4748
3990
  *
4749
- * @typeParam DB - Database schema type (Kysely-like).
3991
+ * @typeParam DB - Database row map type.
4750
3992
  * Keys are table names, values are row types.
4751
3993
  * When provided, query() method provides autocomplete for table names
4752
3994
  * and infers result types automatically.
@@ -4770,18 +4012,17 @@ interface OrmOptionsWithAdapter<DB = unknown> extends OrmOptionsBase<DB> {
4770
4012
  /**
4771
4013
  * PUBLIC ORM instance type — the interface consumers see from createOrm().
4772
4014
  *
4773
- * String-based table entry points (select, insert, update, delete, upsert) are
4774
- * intentionally absent. Use the typed TableRef-based methods instead:
4775
- * - `orm.from(table)` — SELECT
4776
- * - `orm.into(table)` — INSERT
4777
- * - `orm.modify(table)` — UPDATE
4778
- * - `orm.removeFrom(table)` — DELETE
4779
- * - `orm.upsertInto(table)` — UPSERT (INSERT ... ON CONFLICT)
4015
+ * SELECT queries can start from either first-class table entry point:
4016
+ * - `orm.select(name)` - concise table-name form
4017
+ * - `orm.from(table)` - TableRef form with column-level types
4780
4018
  *
4781
- * Internal code (NQL, planner, tests) that needs string-based access should
4782
- * cast to `OrmInstanceInternal<DB>`.
4019
+ * Mutations use the typed TableRef-based methods:
4020
+ * - `orm.into(table)` - INSERT
4021
+ * - `orm.modify(table)` - UPDATE
4022
+ * - `orm.removeFrom(table)` - DELETE
4023
+ * - `orm.upsertInto(table)` - UPSERT (INSERT ... ON CONFLICT)
4783
4024
  *
4784
- * @typeParam DB - Database schema type (Kysely-like).
4025
+ * @typeParam DB - Database row map type.
4785
4026
  * Keys are table names, values are row types.
4786
4027
  *
4787
4028
  * @example
@@ -4799,7 +4040,7 @@ interface OrmOptionsWithAdapter<DB = unknown> extends OrmOptionsBase<DB> {
4799
4040
  *
4800
4041
  * @example
4801
4042
  * ```typescript
4802
- * // With Schema wrapper (from schema() / defineSchema())
4043
+ * // With Schema wrapper from schema()
4803
4044
  * const db = schema({ users: { id: 'integer', name: 'string' } });
4804
4045
  * type MyOrm = OrmOf<typeof db>; // unwraps Schema<T> → InferDB<T>
4805
4046
  *
@@ -4845,19 +4086,43 @@ interface OrmInstance<DB = Record<string, unknown>> {
4845
4086
  * Use destructuring to get individual table references, then pass
4846
4087
  * them to `from()` for type-safe queries.
4847
4088
  *
4089
+ * Each entry also carries the runtime DDL helpers (`.truncate()`,
4090
+ * `.indexes.list()`, `.alterColumn()`, …) via the `TableDDL` mixin, mirroring
4091
+ * what `wrapTablesProxyWithDDL` produces at runtime.
4092
+ *
4848
4093
  * @example
4849
4094
  * ```typescript
4850
4095
  * const { users, posts } = orm.tables;
4851
4096
  * const activeUsers = await orm.from(users).where(eq(users.active, true)).all();
4097
+ * const indexes = await orm.tables.users.indexes.list();
4852
4098
  * ```
4853
4099
  *
4854
4100
  * @since DX-040-SURFACE
4855
4101
  */
4856
4102
  readonly tables: {
4857
- [K in keyof DB & string]: TableRef<K, RowToColumnRefs<K, DB[K]>, any>;
4103
+ [K in keyof DB & string]: TableRef<K, RowToColumnRefs<K, DB[K]>, any> & TableDDL;
4858
4104
  };
4859
4105
  /**
4860
- * Start a type-safe SELECT query from a TableRef.
4106
+ * Start building a SELECT query from a table name (string-based API).
4107
+ *
4108
+ * This is the ordinary table-name API used throughout guides and examples.
4109
+ * Use `orm.from(orm.tables.<table>)` when you want the stricter TableRef-based
4110
+ * form with column-level type information for filters, ordering, and result
4111
+ * inference.
4112
+ *
4113
+ * @typeParam K - Table name (inferred from DB keys when typed)
4114
+ * @typeParam TResult - Override result type (defaults to DB[K])
4115
+ * @param from - The root table name to select from
4116
+ * @returns A QueryBuilder for constructing the select
4117
+ */
4118
+ select<K extends keyof DB & string, TResult = DB[K]>(from: K): QueryBuilder<TResult>;
4119
+ /**
4120
+ * Start building a SELECT query from a typed TableRef.
4121
+ *
4122
+ * This is the stricter table-reference API. Use it when you want column refs
4123
+ * from `orm.tables.<table>` to carry column-level types into filters and other
4124
+ * query clauses. Use `orm.select('<table>')` when the shorter table-name form is
4125
+ * enough.
4861
4126
  *
4862
4127
  * @typeParam TTable - The TableRef type (inferred from the argument)
4863
4128
  * @param table - A TableRef from `orm.tables`
@@ -4871,18 +4136,6 @@ interface OrmInstance<DB = Record<string, unknown>> {
4871
4136
  *
4872
4137
  * @since DX-040-SURFACE
4873
4138
  */
4874
- /**
4875
- * Start building a SELECT query from a table name (string-based API).
4876
- *
4877
- * @deprecated Use `orm.from(orm.tables.<table>)` for type-safe queries.
4878
- * String-based select is kept for backward compatibility and test convenience.
4879
- *
4880
- * @typeParam K - Table name (inferred from DB keys when typed)
4881
- * @typeParam TResult - Override result type (defaults to DB[K])
4882
- * @param from - The root table name to select from
4883
- * @returns A QueryBuilder for constructing the select
4884
- */
4885
- select<K extends keyof DB & string, TResult = DB[K]>(from: K): QueryBuilder<TResult>;
4886
4139
  from<TTable extends TableRef<any, any, any>>(table: TTable): QueryBuilder<InferTableRow<TTable>>;
4887
4140
  /**
4888
4141
  * Start a SELECT query from a BatchValuesRef source (unnest-backed virtual table).
@@ -6251,10 +5504,10 @@ declare function coalesce(fields: readonly string[], as: string): ExpressionSpec
6251
5504
  */
6252
5505
  declare function raw(sqlFragment: string, as: string): ExpressionSpec;
6253
5506
  /**
6254
- * Creates a column alias expression using native Kysely API.
5507
+ * Creates a column alias expression as a typed dbsp expression intent.
6255
5508
  * Preferred over raw() for simple column aliasing as it's type-safe and dialect-portable.
6256
5509
  *
6257
- * Uses Kysely's `eb.ref(column).as(alias)` internally - no raw SQL.
5510
+ * Compilers render the alias from structured column and alias fields - no raw SQL.
6258
5511
  *
6259
5512
  * @param column - Column name to select
6260
5513
  * @param alias - Alias for the result column
@@ -6279,8 +5532,8 @@ declare function col(column: string, alias: string): ExpressionSpec;
6279
5532
  * Creates a relation column expression for selecting a column from a related table.
6280
5533
  * Auto-creates JOINs via the include mechanism and selects with custom alias.
6281
5534
  *
6282
- * Uses native Kysely API internally - no raw SQL. The compiler resolves the relation
6283
- * to its join alias and uses `eb.ref(alias.column).as(as)`.
5535
+ * Uses structured relation-column intent - no raw SQL. The compiler resolves the
5536
+ * relation to its join alias and renders a dialect-specific aliased column.
6284
5537
  *
6285
5538
  * @param relation - Relation path to traverse (dot-separated for multi-level)
6286
5539
  * @param column - Column name to select from the target relation
@@ -7312,7 +6565,7 @@ declare function pipeOnErrorHooks(...hooks: OnErrorHook[]): OnErrorHook;
7312
6565
  /**
7313
6566
  * DX-023: Lightweight ModelIR Definition
7314
6567
  *
7315
- * Provides a simplified API for defining relations when using Kysely's Database type.
6568
+ * Provides a simplified API for defining relations from a database row map type.
7316
6569
  * Instead of verbose column definitions, developers can focus solely on relations
7317
6570
  * using shorthand syntax with automatic FK inference.
7318
6571
  *
@@ -7743,7 +6996,7 @@ interface SimplifiedOrmOptions<T extends SchemaDefinition = SchemaDefinition> {
7743
6996
  /**
7744
6997
  * Create an ORM instance with the specified configuration.
7745
6998
  *
7746
- * @typeParam DB - Database schema type (Kysely-like).
6999
+ * @typeParam DB - Database row map type.
7747
7000
  * Keys are table names, values are row types.
7748
7001
  * When provided, query() provides autocomplete and type inference.
7749
7002
  *
@@ -8366,4 +7619,4 @@ declare const assertIntentHasOrderBy: (result: AssertionQueryResult, expected: b
8366
7619
  */
8367
7620
  declare function runAssertions(blocks: AssertionBlock[], results: AssertionQueryResult[], queries: string[], hasDb?: boolean): AssertionSummary;
8368
7621
 
8369
- 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, type ColumnTypeToTS, CteBuilder, type CteDump, CteQueryBuilder, type CursorPaginateOptions, type CursorPaginatedResult, DEFAULT_CONVENTIONS, 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 GeneratedBelongsTo, type GeneratedColumn, type GeneratedColumnType, type GeneratedConventions, type GeneratedHasMany, type GeneratedHint, type GeneratedManyToMany, type GeneratedRelation, type GeneratedRelationKind, type GeneratedSchema, type GeneratedTable, 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 InferDBFromSchema, type InferRefColumn, type InferRow, type InferRowType, 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$1 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, type OrmOptionsWithSchema, 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, type ResolvedSchema, ResolvedSchemaValidation, ResultHydrator, SQLITE_CAPABILITIES, SQL_RAW_MARKER, type Schema, type SchemaBelongsToRelation, type SchemaCardinality, type SchemaColumnDefinition, type SchemaColumnType, type SchemaConfigInput, type SchemaConstraints, type SchemaConventionsDefinition, type SchemaConversionResult, type SchemaDefinition, type SchemaDefinitionInput, SchemaValidationError$1 as SchemaError, type SchemaExtras, type SchemaFilterStrategy, type SchemaForeignKeyReference, type SchemaHasManyRelation, type SchemaHintDefinition, type SchemaHintsDefinition, type SchemaIndexDefinition, type SchemaIndexOptions, type SchemaIndexesDefinition, type SchemaManyToManyRelation, type SchemaOnDeleteAction, type SchemaOptions, type SchemaRelationDefinition, type SchemaRelationKind, type SchemaRelationsDefinition, type SchemaTableDefinition, type SchemaTableOptions, type SchemaTablesDefinition, 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 ValidatedResolvedSchema, 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, assertResolvedSchemaToGeneratedSchema, assertSQLColumn, assertSQLEquals, assertSQLJoin, assertSQLTable, assertSuccess, assertTypeSupported, batchValues, buildModelFromResolvedSchema, buildModelFromSchema, capitalize, caseWhen, cast, coalesce, col, composeAfterMutationHooks, composeAfterQueryHooks, composeBeforeMutationHooks, composeBeforeQueryHooks, composeOnErrorHooks, countDistinctRelationPathsByName, createDialectCapabilities, createHookManager, createNqlTag, createOrm, createPseudoColumnMetadata, createRawCteBuilder, createRecursiveMetadata, decapitalize, defaultLogger, defineModel, defineSchema, denseRank, deriveRelationPathFromIntentPath, detectForeignKeys, detectManyToMany, distinct, emitWarning, eq, every, exists, ref as exprRef, extendDialect, extractPseudoColumnKeywords, findClosestMatch, fn, fullTextSearch, getAvailableDialects, getDialectCapabilities, getLogger, getRelationKind, getSchemaFromDb, gt, gte, inArray, inSubquery, inferForeignKey, inferRelationsFromSchema, isAliasedColumn, isAllColumns, isBatchValuesRef, isBelongsTo, isCardinalityShorthand, isColumnRef, isDistinctField, isDistinctFrom, isExpressionSpec, isGeneratedSchema, isHasMany, isKnownDialect, isManyToMany, isNotNull, isNull, isOverallSuccess, isRecursiveIncludeOptions, isRecursiveRelation, isRef, isRelationObjectDef, isRelationRef, isRelationTupleDef, isResolvedSchema, isSelfReferential, isSqlRaw, isSubqueryExpression, isTableRef, isWhereIntent, lag, lead, like, literal, lt, lte, namedArg, negotiateFeatures, neq, none, normalizeSQL, normalizeSchema, 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, resolvedSchemaToGeneratedSchema, rowNumber, runAssertions, schema, schemaToModelIR, setLogger, silentLogger, singularize, some, sortByPriority, sql, star, stringAgg, subquery, supportsDDLGeneration, supportsExecution, supportsIntrospection, supportsRawSql, supportsStreaming, supportsTransactions, textScore, unary, validateAssertionBlocks, validateRecursiveInclude, validateRecursiveShape, validateTypeName, wAvg, wCount, wMax, wMin, wSum, withPriority };
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 };