sqlite.swift – 如何在添加列之前检查列是否存在

前端之家收集整理的这篇文章主要介绍了sqlite.swift – 如何在添加列之前检查列是否存在前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数据库,如果它不存在,我想添加一个列.
我如何使用sqlite. swift API做到这一点?

解决方法

通常,如果要向现有表添加新列,则需要具有迁移路径.您可以使用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建议的那样,在create(table:…)级别使用ifNotExists:

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)
 }

不太可读(或推荐),但如果您正在处理遗留数据库,可能是必要的.

请务必阅读the ALTER TABLE documentation以了解更复杂的更改.

猜你在找的Sqlite相关文章