如何在添加列之前检查列是否存在

use*_*373 6 sqlite.swift

我有一个数据库,如果它不存在,我想添加一个列.我如何使用sqlite.swift API做到这一点?

ste*_*lis 8

通常,如果要向现有表添加新列,则需要具有迁移路径.您可以使用该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文档以了解更复杂的更改.