| 363 | } & Record<`varchar(${number})`, string>; |
| 364 | |
| 365 | export class Column<Type extends keyof TypeMap, In = unknown, Out = unknown> { |
| 366 | type: Type; |
| 367 | ormName: string = ""; |
| 368 | isNullable: boolean = false; |
| 369 | isUnique: boolean = false; |
| 370 | default?: |
| 371 | | { value: TypeMap[Type] } |
| 372 | | { |
| 373 | runtime: DefaultFunction<Type>; |
| 374 | }; |
| 375 | |
| 376 | table: AnyTable = undefined as unknown as AnyTable; |
| 377 | |
| 378 | private initNames: (ormName: string) => NameVariants; |
| 379 | |
| 380 | get names(): NameVariants { |
| 381 | return this.initNames(this.ormName); |
| 382 | } |
| 383 | |
| 384 | set names(v: NameVariants) { |
| 385 | this.initNames = () => v; |
| 386 | } |
| 387 | |
| 388 | constructor(type: Type, onInitNames: (ormName: string) => NameVariants) { |
| 389 | this.type = type; |
| 390 | this.initNames = onInitNames; |
| 391 | } |
| 392 | |
| 393 | nullable<T extends boolean = true>(nullable?: T) { |
| 394 | this.isNullable = nullable ?? true; |
| 395 | |
| 396 | return this as Column< |
| 397 | Type, |
| 398 | T extends true ? In | null : Exclude<In, null>, |
| 399 | T extends true ? Out | null : Exclude<Out, null> |
| 400 | >; |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Add unique constraint to the field, for consistency, duplicated null values are allowed. |
| 405 | */ |
| 406 | unique(unique: boolean = true) { |
| 407 | this.isUnique = unique; |
| 408 | return this; |
| 409 | } |
| 410 | |
| 411 | /** |
| 412 | * Generate default value on runtime |
| 413 | */ |
| 414 | defaultTo$(fn: DefaultFunction<Type>): Column<Type, In | null, Out> { |
| 415 | this.default = { runtime: fn }; |
| 416 | return this; |
| 417 | } |
| 418 | |
| 419 | /** |
| 420 | * Set a database-level default value |
| 421 | * |
| 422 | * For schemaless database, it's still generated on runtime |