数据库实体规范
1. 实体基础结构
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { z } from 'zod';
@Entity('table_name') // 使用小写下划线命名表名
export class EntityName {
// 字段定义...
}
2. 主键定义规范
@PrimaryGeneratedColumn({ unsigned: true }) // 必须使用无符号整数
id!: number; // 使用非空断言(!)和明确类型
3. 列定义规范
@Column({
name: '字段名称', // 必须添加并与数据表字段名称一致
type: 'varchar', // 明确指定数据库类型
length: 255, // 字符串必须指定长度
nullable: true, // 明确是否可为空
default: undefined, // 默认值(可选)
comment: '字段说明' // 必须添加中文注释
})
fieldName!: FieldType; // 类型必须明确
4. 数据类型规范
| 业务类型 |
数据库类型 |
TypeScript 类型 |
| 主键ID |
int unsigned |
number |
| 短文本 |
varchar(length) |
string |
| 长文本 |
text |
string |
| 整数 |
int |
number |
| 小数 |
decimal(precision,scale) |
number |
| 布尔状态 |
tinyint |
number (0/1) |
| 日期时间 |
timestamp |
Date |
5. 状态字段规范
// 禁用状态 (0启用 1禁用)
@Column({ name: 'is_disabled', type: 'tinyint', default: 1 })
isDisabled!: number;
// 删除状态 (0未删除 1已删除)
@Column({ name: 'is_deleted',type: 'tinyint', default: 0 })
isDeleted!: number;
6. 时间字段规范
// 创建时间 (自动设置)
@Column({
name: 'created_at',
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP'
})
createdAt!: Date;
// 更新时间 (自动更新)
@Column({
name: 'updated_at',
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP',
onUpdate: 'CURRENT_TIMESTAMP'
})
updatedAt!: Date;
7. Zod Schema 规范
export const EntitySchema = z.object({
id: z.number().int().positive().openapi({ description: 'ID说明' }),
// 字符串字段
fieldName: z.string()
.max(255)
.nullable()
.openapi({
description: '字段说明',
example: '示例值'
}),
// 数字字段
numberField: z.number()
.default(默认值)
.openapi({...}),
// 日期字段
dateField: z.date().openapi({...})
});
8. 命名规范
- 实体类名:PascalCase (如 RackInfo)
- 表名:snake_case (如 rack_info)
- 字段名:camelCase (如 rackName)
- 数据库列名:snake_case (如 rack_name)
9. 最佳实践
- 所有字段必须添加字段名称(name)及注释(comment)
- 必须明确指定 nullable 属性
- 状态字段使用 tinyint 并注明取值含义
- 必须包含 createdAt/updatedAt 时间字段
- 每个实体必须配套 Zod Schema 定义
- Schema 必须包含 OpenAPI 元数据(description/example)