Skip to content

迁移

AutoMigrate

AutoMigrate 用于自动迁移您的 schema,保持您的 schema 是最新的。

注意: AutoMigrate 会创建表、添加字段、修改字段和类型. 出于保护您数据的目的,它不会删除未使用的列。

ts
export class User extends Model {
  /**
   * 名字
   */
  @Field({ type: FieldType.TEXT })
  Name?: string
  /**
   * 年龄
   */
  @Field({ type: FieldType.INTEGER })
  Age?: number
}

this.db.AutoMigrate(User);

Migrator 接口

IBest-ORM 提供了 Migrator 迁移类,该类为每个数据库提供了统一的 API 接口,可用来为您的数据库构建独立迁移,例如:

SQLite 不支持 ALTER COLUMN、DROP COLUMN,当你试图修改表结构,IBest-ORM 将创建一个新表、复制所有数据、删除旧表、重命名新表。

ts
class Migrator {
  // ...

  // Tables
  CreateTable(model: Class) {}
  DropTable(model: Class) {}
  HasTable(model: Class|string): boolean {}
  GetTableInfo(model: Class|string) {}
  RenameTable(oldName: string, newName: string) {}

  // Columns
  HasColumn(model: Class|string, field: string): boolean {}
  AddColumn(model: Class) {}
  DropColumn(model: Class) {}
  AlterColumn(model: Class) {}
}

ts
// 为 `User` 创建表
this.db.Migrator().CreateTable(User)
    
// 删除 `User` 表   
this.db.Migrator().DropTable(User)
    
// 检查 `User` 是否存在                     
this.db.Migrator().HasTable(User)
    
// 获取 `User` 表的信息                 
this.db.Migrator().GetTableInfo(User)
this.db.Migrator().GetTableInfo('user')
    
// 将 `Users` 重命名为 `User`                
this.db.Migrator().RenameTable("Users", "User")

ts
// 检查 `User` 是否含有 `Name` 列
export class User extends Model {
  @Field({ type: FieldType.TEXT })
  Name?: string
}
this.db.Migrator().HasColumn(User, "Name")

// 在 `User` 表中添加 `Age` 列
export class User extends Model {
  @Field({ type: FieldType.TEXT })
  Name?: string
  
  @Field({ type: FieldType.INTEGER })
  Age?: number
}
this.db.Migrator().AddColumn(User)

// 在 `User` 表中删除 `Name` 列
export class User extends Model {
  @Field({ type: FieldType.INTEGER })
  Age?: number
}
this.db.Migrator().DropColumn(User)

// 修改 `User` 表中的 `Age` 列
export class User extends Model {
  @Field({ type: FieldType.TEXT })
  Age?: string
}
this.db.Migrator().AlterColumn(User)