通常,如果要向现有表添加新列,则需要具有迁移路径.您可以使用该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
}
Run Code Online (Sandbox Code Playgroud)
正如Max建议的那样,您也可以ifNotExists:在以下create(table:…)级别使用:
db.create(table: users, ifNotExists: true) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
Run Code Online (Sandbox Code Playgroud)
但是要添加新列,您必须解析一个笨拙的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)
}
Run Code Online (Sandbox Code Playgroud)
不太可读(或推荐),但如果您正在处理遗留数据库,可能是必要的.
请务必阅读ALTER TABLE文档以了解更复杂的更改.
| 归档时间: |
|
| 查看次数: |
3052 次 |
| 最近记录: |