export type QueryType = 'create' | 'alter' | 'drop_table' | 'drop_index' | 'select' | 'insert' | 'insert_many' | 'update' | 'delete' | 'aggregate'; export type AggregateFunction = 'count' | 'sum' | 'avg' | 'min' | 'max'; export interface AggregateField { fn: AggregateFunction; field: keyof T | '*'; alias?: string; } export type ColumnType = "text" | "integer" | "float" | "boolean" | "date" | "json"; export interface Column { type: ColumnType; nullable?: boolean; default?: T; autoIncrement?: boolean; primary?: boolean; unique?: boolean; length?: number; } export type Definition = { [P in keyof T]: Column; }; export interface ModelOptions { /** 启用软删除(需要表中有 deletedAt 字段) */ softDelete?: boolean; /** 软删除字段名,默认 'deletedAt' */ deletedAtField?: string; /** 启用自动时间戳(createdAt, updatedAt) */ timestamps?: boolean; /** createdAt 字段名,默认 'createdAt' */ createdAtField?: string; /** updatedAt 字段名,默认 'updatedAt' */ updatedAtField?: string; } /** * 生命周期钩子上下文 * 包含当前操作的相关信息 */ export interface HookContext { /** 模型名称 */ modelName: string; /** 当前操作的数据(create/update 时) */ data?: Partial; /** 查询条件(find/update/delete 时) */ where?: Condition; /** 操作结果(after 钩子时) */ result?: T | T[] | number; } /** * 钩子函数类型 * 返回 false 可以取消操作(仅 before 钩子) */ export type HookFn = (context: HookContext) => void | boolean | Promise; /** * 生命周期钩子名称 */ export type HookName = 'beforeCreate' | 'afterCreate' | 'beforeUpdate' | 'afterUpdate' | 'beforeDelete' | 'afterDelete' | 'beforeFind' | 'afterFind'; /** * 钩子配置 */ export type HooksConfig = { [K in HookName]?: HookFn | HookFn[]; }; export interface AddDefinition { action: "add"; type: ColumnType; nullable?: boolean; default?: T; primary?: boolean; length?: number; } export interface ModifyDefinition { action: "modify"; type?: ColumnType; nullable?: boolean; default?: T; length?: number; } export interface DropDefinition { action: "drop"; } export type AlterDefinition = { [P in keyof T]?: AddDefinition | ModifyDefinition | DropDefinition; }; /** * 子查询标识接口 * @template T 子查询返回的字段类型 */ export interface Subquery { readonly __isSubquery: true; /** 子查询返回值类型标记(仅用于类型推断,运行时不存在) */ readonly __returnType?: T; toSQL(): { sql: string; params: any[]; }; } export interface ComparisonOperators { $eq?: T; $ne?: T; $gt?: T; $gte?: T; $lt?: T; $lte?: T; /** 值在数组中或子查询结果中 */ $in?: T[] | Subquery; /** 值不在数组中或子查询结果中 */ $nin?: T[] | Subquery; $like?: string; $nlike?: string; } export interface LogicOperators { $and?: Condition[]; $or?: Condition[]; $not?: Condition; } export type Condition = { [P in keyof T]?: T[P] | ComparisonOperators | LogicOperators; } | LogicOperators; export type SortDirection = "ASC" | "DESC"; export interface Ordering { field: keyof T; direction: SortDirection; } export type JoinType = 'INNER' | 'LEFT' | 'RIGHT' | 'FULL'; /** * JOIN 子句定义 * @template S Schema 类型 * @template T 主表 * @template J 关联表 */ export interface JoinClause, T extends keyof S, J extends keyof S> { /** JOIN 类型 */ type: JoinType; /** 关联表名 */ table: J; /** 主表字段 */ leftField: keyof S[T]; /** 关联表字段 */ rightField: keyof S[J]; /** 表别名(可选) */ alias?: string; } export interface BaseQueryParams = Record, T extends keyof S = keyof S> { tableName: T; } export interface CreateQueryParams, T extends keyof S> extends BaseQueryParams { type: 'create'; definition: Definition; } export interface AlterQueryParams, T extends keyof S> extends BaseQueryParams { type: 'alter'; alterations: AlterDefinition; } export interface DropTableQueryParams, T extends keyof S> extends BaseQueryParams { type: 'drop_table'; conditions?: Condition; } export interface DropIndexQueryParams, T extends keyof S> extends BaseQueryParams { type: 'drop_index'; indexName: string; conditions?: Condition; } export interface SelectQueryParams, T extends keyof S> extends BaseQueryParams { type: 'select'; fields?: (keyof S[T])[]; conditions?: Condition; groupings?: (keyof S[T])[]; orderings?: Ordering[]; limitCount?: number; offsetCount?: number; /** JOIN 子句列表 */ joins?: JoinClause[]; } export interface InsertQueryParams, T extends keyof S> extends BaseQueryParams { type: 'insert'; data: S[T]; } export interface InsertManyQueryParams, T extends keyof S> extends BaseQueryParams { type: 'insert_many'; data: S[T][]; } export interface UpdateQueryParams, T extends keyof S> extends BaseQueryParams { type: 'update'; update: Partial; conditions?: Condition; } export interface DeleteQueryParams, T extends keyof S> extends BaseQueryParams { type: 'delete'; conditions?: Condition; } export interface AggregateQueryParams, T extends keyof S> extends BaseQueryParams { type: 'aggregate'; aggregates: AggregateField[]; conditions?: Condition; groupings?: (keyof S[T])[]; havingConditions?: Condition; } export type QueryParams, T extends keyof S> = CreateQueryParams | AlterQueryParams | DropTableQueryParams | DropIndexQueryParams | SelectQueryParams | InsertQueryParams | InsertManyQueryParams | UpdateQueryParams | DeleteQueryParams | AggregateQueryParams; export interface BuildQueryResult { query: R; params: any[]; } /** * 文档查询结果类型 */ export interface DocumentQueryResult { collection: string; filter: Record; sort?: Record; limit?: number; skip?: number; projection?: Record; operation?: 'find' | 'insertOne' | 'insertMany' | 'updateOne' | 'updateMany' | 'deleteOne' | 'deleteMany' | 'createCollection' | 'createIndex' | 'dropIndex' | 'dropCollection'; } /** * 键值查询结果类型 */ export interface KeyValueQueryResult { bucket: string; operation: 'get' | 'set' | 'delete' | 'has' | 'keys' | 'values' | 'entries' | 'clear' | 'size' | 'expire' | 'ttl' | 'persist' | 'cleanup' | 'keysByPattern'; key?: string; value?: any; ttl?: number; pattern?: string; keys?: string[]; } /** * 文档操作结果类型 */ export interface DocumentOperationResult { success: boolean; data?: T | T[]; count?: number; error?: string; } /** * 键值操作结果类型 */ export interface KeyValueOperationResult { success: boolean; data?: T | T[] | number | boolean; error?: string; } /** * 数据库方言信息接口 */ export interface DatabaseDialect { name: string; version: string; features: string[]; dataTypes: Record; identifierQuote: string; parameterPlaceholder: string; supportsTransactions: boolean; supportsIndexes: boolean; supportsForeignKeys: boolean; supportsViews: boolean; supportsStoredProcedures: boolean; } export interface SelectResult { rows: T[]; count?: number; } export interface InsertResult { insertId?: number | string; affectedRows?: number; data?: T; } export interface UpdateResult { affectedRows: number; } export interface DeleteResult { affectedRows: number; } export interface BaseDriverConfig { timeout?: number; retries?: number; } export interface DriverConnection { isConnected(): boolean; connect(): Promise; disconnect(): Promise; healthCheck(): Promise; } export type IsolationLevel = 'READ_UNCOMMITTED' | 'READ_COMMITTED' | 'REPEATABLE_READ' | 'SERIALIZABLE'; export interface TransactionOptions { isolationLevel?: IsolationLevel; timeout?: number; } export interface Transaction { commit(): Promise; rollback(): Promise; query(sql: string, params?: any[]): Promise; } /** * 增强的事务接口,支持链式调用 */ export interface TransactionContext = Record> extends Transaction { /** * 插入单条数据 */ insert(tableName: T, data: S[T]): Promise; /** * 批量插入数据 */ insertMany(tableName: T, data: S[T][]): Promise<{ affectedRows: number; }>; /** * 查询数据 */ select(tableName: T, fields?: (keyof S[T])[]): TransactionSelection; /** * 更新数据 */ update(tableName: T, data: Partial): TransactionUpdation; /** * 删除数据 */ delete(tableName: T): TransactionDeletion; } /** * 事务查询选择器 */ export interface TransactionSelection, T extends keyof S> { where(condition: Condition): this; orderBy(field: keyof S[T], direction?: 'ASC' | 'DESC'): this; limit(count: number): this; offset(count: number): this; then(onfulfilled?: (value: S[T][]) => R | PromiseLike): Promise; } /** * 事务更新器 */ export interface TransactionUpdation, T extends keyof S> { where(condition: Condition): this; then(onfulfilled?: (value: number) => R | PromiseLike): Promise; } /** * 事务删除器 */ export interface TransactionDeletion, T extends keyof S> { where(condition: Condition): this; then(onfulfilled?: (value: number) => R | PromiseLike): Promise; } export interface PoolConfig { min?: number; max?: number; acquireTimeoutMillis?: number; idleTimeoutMillis?: number; } export interface DriverQuery { query(sql: string, params?: any[]): Promise; } export interface DriverSchema { getTables(): Promise; getTableInfo(tableName: string): Promise; } export interface DriverQueryBuilder { buildQuery, T extends keyof S>(params: QueryParams): BuildQueryResult; } export interface DriverLifecycle { dispose(): Promise; } export interface TableInfo { name: string; type: string; nullable: boolean; defaultValue: any; primaryKey: boolean; unique: boolean; length?: number; } export interface ModelField { type: "string" | "integer" | "number" | "float" | "json" | "boolean" | "date" | "object" | "array"; initial?: any; length?: number; primary?: boolean; autoIncrement?: boolean; unique?: boolean; notNull?: boolean; } export interface ModelConfig { driver?: string; timestamps?: boolean; softDelete?: boolean; relations?: ModelRelation[]; } export interface ModelRelation { model: string; type: "belongs-to" | "has-one" | "has-many" | "many-to-many"; foreignKey?: string; through?: string; } export type RequiredKeys = T & Required>; export type OptionalKeys = Omit & Partial>; export type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; export type DeepRequired = { [P in keyof T]-?: T[P] extends object ? DeepRequired : T[P]; }; export declare function isCreateQuery, T extends keyof S>(params: QueryParams): params is CreateQueryParams; export declare function isAlterQuery, T extends keyof S>(params: QueryParams): params is AlterQueryParams; export declare function isSelectQuery, T extends keyof S>(params: QueryParams): params is SelectQueryParams; export declare function isInsertQuery, T extends keyof S>(params: QueryParams): params is InsertQueryParams; export declare function isUpdateQuery, T extends keyof S>(params: QueryParams): params is UpdateQueryParams; export declare function isDeleteQuery, T extends keyof S>(params: QueryParams): params is DeleteQueryParams; export declare function isDropTableQuery, T extends keyof S>(params: QueryParams): params is DropTableQueryParams; export declare function isDropIndexQuery, T extends keyof S>(params: QueryParams): params is DropIndexQueryParams; export declare function isInsertManyQuery, T extends keyof S>(params: QueryParams): params is InsertManyQueryParams; export declare function isAggregateQuery, T extends keyof S>(params: QueryParams): params is AggregateQueryParams; /** * 关联关系类型 */ export type RelationType = 'hasOne' | 'hasMany' | 'belongsTo' | 'belongsToMany'; /** * Schema 中的关系声明 * * @example * ```ts * interface MySchema { * users: { * id: number; * name: string; * $hasMany: { orders: 'userId' }; * $hasOne: { profile: 'userId' }; * }; * orders: { * id: number; * userId: number; * $belongsTo: { users: 'userId' }; * }; * } * ``` */ export interface SchemaRelations> { /** 一对多关系: { 目标表名: '外键字段' } */ $hasMany?: { [K in keyof S]?: string; }; /** 一对一关系: { 目标表名: '外键字段' } */ $hasOne?: { [K in keyof S]?: string; }; /** 多对一关系: { 目标表名: '本表外键字段' } */ $belongsTo?: { [K in keyof S]?: string; }; } /** * 从 Schema 表定义中提取纯数据字段(排除关系声明) */ export type SchemaFields = Omit; /** * 关联关系定义 */ export interface RelationDefinition, From extends keyof S, To extends keyof S> { /** 关联类型 */ type: RelationType; /** 目标表名 */ target: To; /** 本表外键字段 */ foreignKey: keyof S[From] | keyof S[To]; /** 目标表主键字段(默认 'id') */ targetKey?: keyof S[To]; /** 本表主键字段(默认 'id') */ localKey?: keyof S[From]; /** 中间表配置(仅 belongsToMany) */ pivot?: PivotConfig; } /** * 中间表(Pivot Table)配置 * 用于多对多关系 */ export interface PivotConfig { /** 中间表名 */ table: string; /** 中间表中指向源表的外键 */ foreignPivotKey: string; /** 中间表中指向目标表的外键 */ relatedPivotKey: string; /** 中间表额外字段(可选) */ pivotFields?: string[]; /** 是否包含时间戳 */ timestamps?: boolean; } /** * 带关联数据的结果类型 */ export type WithRelation = T & { [K in RelName]: RelType extends ('hasMany' | 'belongsToMany') ? RelData[] : RelData | null; }; /** * 带中间表数据的关联结果 */ export type WithPivot> = T & { pivot: PivotData; }; /** * 关联查询选项 */ export interface RelationQueryOptions, T extends keyof S> { /** 要加载的关联名称 */ relations?: string[]; /** 关联数据的筛选条件 */ where?: Condition; } /** * 关系配置中的外键字段类型 * 表名是强类型的,字段名是 string(运行时验证) */ export type RelationForeignKey = string; /** * hasMany 关系配置:{ 目标表名: 外键字段名 } */ export type HasManyConfig> = { [K in Extract]?: RelationForeignKey; }; /** * hasOne 关系配置:{ 目标表名: 外键字段名 } */ export type HasOneConfig> = { [K in Extract]?: RelationForeignKey; }; /** * belongsTo 关系配置:{ 目标表名: 本表外键字段名 } */ export type BelongsToConfig> = { [K in Extract]?: RelationForeignKey; }; /** * belongsToMany 关系配置 * { 目标表名: { pivot: 中间表名, foreignKey: 源外键, relatedKey: 目标外键, pivotFields?: 额外字段 } } */ export interface BelongsToManyRelationConfig { /** 中间表名 */ pivot: string; /** 中间表中指向源表的外键 */ foreignKey: string; /** 中间表中指向目标表的外键 */ relatedKey: string; /** 要获取的中间表额外字段 */ pivotFields?: string[]; } export type BelongsToManyConfig> = { [K in Extract]?: BelongsToManyRelationConfig; }; /** * 单个表的关系配置 */ export interface TableRelationsConfig> { hasMany?: HasManyConfig; hasOne?: HasOneConfig; belongsTo?: BelongsToConfig; belongsToMany?: BelongsToManyConfig; } /** * 关系配置对象(用于 Database 构造) * * 表名是强类型的(必须是 Schema 中定义的表), * 字段名是字符串(在运行时通过模型方法验证) * * @example * ```ts * interface Schema { * users: { id: number; name: string }; * orders: { id: number; userId: number }; * } * * db.defineRelations({ * users: { * hasMany: { orders: 'userId' } // ✅ 'orders' 是有效表名 * }, * orders: { * belongsTo: { users: 'userId' } // ✅ 'users' 是有效表名 * }, * // wrongTable: {} // ❌ 类型错误:'wrongTable' 不在 Schema 中 * }); * ``` */ export type RelationsConfig> = { [T in Extract]?: TableRelationsConfig; }; /** * 迁移上下文 - 提供迁移操作所需的数据库方法 */ export interface MigrationContext { /** 创建表 */ createTable(tableName: string, columns: Record): Promise; /** 删除表 */ dropTable(tableName: string): Promise; /** 添加列 */ addColumn(tableName: string, columnName: string, column: Column): Promise; /** 删除列 */ dropColumn(tableName: string, columnName: string): Promise; /** 修改列 */ modifyColumn(tableName: string, columnName: string, column: Column): Promise; /** 重命名列 */ renameColumn(tableName: string, oldName: string, newName: string): Promise; /** 添加索引 */ addIndex(tableName: string, indexName: string, columns: string[], unique?: boolean): Promise; /** 删除索引 */ dropIndex(tableName: string, indexName: string): Promise; /** 执行原生 SQL */ query(sql: string, params?: any[]): Promise; } /** * 迁移定义 */ /** * 迁移操作记录(用于自动生成 down) */ export type MigrationOperation = { type: 'createTable'; tableName: string; columns: Record; } | { type: 'dropTable'; tableName: string; } | { type: 'addColumn'; tableName: string; columnName: string; column: Column; } | { type: 'dropColumn'; tableName: string; columnName: string; } | { type: 'addIndex'; tableName: string; indexName: string; columns: string[]; unique?: boolean; } | { type: 'dropIndex'; tableName: string; indexName: string; } | { type: 'renameColumn'; tableName: string; oldName: string; newName: string; } | { type: 'query'; sql: string; params?: any[]; }; export interface Migration { /** 迁移名称(唯一标识) */ name: string; /** 迁移版本(时间戳或序号) */ version?: string | number; /** 升级操作 */ up(context: MigrationContext): Promise; /** * 降级操作(可选) * 如果不提供,将自动根据 up 操作生成反向操作 */ down?(context: MigrationContext): Promise; } /** * 迁移记录(存储在数据库中) */ export interface MigrationRecord { id: number; name: string; batch: number; executedAt: Date; } /** * 迁移状态 */ export interface MigrationStatus { name: string; status: 'pending' | 'executed'; batch?: number; executedAt?: Date; } /** * 迁移运行器配置 */ export interface MigrationRunnerConfig { /** 迁移记录表名 */ tableName?: string; /** 迁移文件目录 */ migrationsPath?: string; } //# sourceMappingURL=types.d.ts.map