通常,如果要向现有表添加新列,您将需要一个迁移路径。您可以使用userVersion
管理数据库架构版本的属性:
if db.userVersion < 1 {
db.create(table: users) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
db.userVersion = 1
}
if db.userVersion < 2 {
db.alter(table: users, add: name)
db.alter(table: users, add: age)
db.userVersion = 2
}
您还可以按照 Max 的建议,使用ifNotExists:
at the create(table:…)
level:
db.create(table: users, ifNotExists: true) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
但要添加新列,您必须解析一个笨拙的 PRAGMA 语句:
let tableInfo = Array(db.prepare("PRAGMA table_info(users)"))
if tableInfo.filter { col in col[1] == "name" } == nil {
db.alter(table: users, add: name)
}
if tableInfo.filter { col in col[1] == "age" } == nil {
db.alter(table: users, add: age)
}
几乎不具有可读性(或推荐),但如果您正在处理遗留数据库,则可能有必要。
请务必阅读ALTER TABLE 文档用于更复杂的更改。