2015-04-23 81 views

回答

6

通常,如果要將新列添加到現有表中,您將希望具有遷移路徑。您可以使用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 
} 

還可以,麥克斯認爲,在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以瞭解更多複雜的更改。

+0

我知道這是一年前,但如何從sqlite.swift得到userVersion?我試圖添加列可能或可能不存在的表,但我不太清楚如何做到這一點..如何檢查表是否存在?因爲使用'table.create(ifNotExists:true)'我不能做一個else存在,檢查列是否存在。另外我該如何檢查列是否存在? – apikurious

2

爲2.0迅速正確的做法是以下幾點:

let tableInfo = Array(db.prepare("PRAGMA table_info(users)")) 

let foundColumn = tableInfo.filter { 
    col in col[1] as! String == "name" 
} 

if(foundColumn.count == 0){ 
    try! db.run(users.addColumn(name)) 
} 
相關問題