如何使用https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md
在SQLite.swift中升级数据库版本并在表中快速添加新列//migration of db version
extension Connection {
public var userVersion: Int32 {
get { return Int32(try! scalar("PRAGMA user_version") as! Int64)}
set { try! run("PRAGMA user_version = \(newValue)") }
}
}
//in viewdidLoad of viewcontroller
if db.userVersion == 0 {
// handle first migration
db.userVersion = 1
}
if db.userVersion == 1 {
// handle second migration
db.userVersion = 2
}
//my table and want to upgrade with some new columns
do
{
let offlineLocationTable = sqliteOfflineLocationTable.offlineLocationTable.create(ifNotExists: true) { (table) in
table.column(sqliteOfflineLocationTable.id, primaryKey: true)
table.column(sqliteOfflineLocationTable.status)
table.column(sqliteOfflineLocationTable.loadid)
table.column(sqliteOfflineLocationTable.jobid)
table.column(sqliteOfflineLocationTable.lat)
table.column(sqliteOfflineLocationTable.lng)
// this is new columns which i want to add in new version of db
table.column(sqliteOfflineLocationTable.t)
print("offline location table created")
}
try self.db.run(offlineLocationTable)
} catch {
print(error)
}
// this code run successfully but when i try to get the column value it carsh due to No such column "t" in columns [........]
答案 0 :(得分:2)
我还没有尝试过,但是您可以尝试一下。 在Swift中,您可以为连接类创建一个新的扩展文件。
extension Connection {
public var userVersion: Int32 {
get { return Int32(try! scalar("PRAGMA user_version") as! Int64)}
set { try! run("PRAGMA user_version = \(newValue)") }
}
}
警告:由于我无法判断您的变量,请检查以下代码的语法
如果表不存在,则会根据您的代码创建表。
//in viewdidLoad of viewcontroller
if db.userVersion == 0 {
// handle first migration
do
{
let offlineLocationTable = sqliteOfflineLocationTable.offlineLocationTable.create(ifNotExists: true) { (table) in
table.column(sqliteOfflineLocationTable.id, primaryKey: true)
table.column(sqliteOfflineLocationTable.status)
table.column(sqliteOfflineLocationTable.loadid)
table.column(sqliteOfflineLocationTable.jobid)
table.column(sqliteOfflineLocationTable.lat)
table.column(sqliteOfflineLocationTable.lng)
// any other table entries
}
try self.db.run(offlineLocationTable)
// on complete of first table creation change the version
db.userVersion = 1
} catch {
print(error)
}
}
if db.userVersion == 1 {
// handle second migration
// Here we add New Column in table
do
{
try self.db.run(offlineLocationTable.addColumn(t, defaultValue: ""))
// any other modifications
db.userVersion = 2
} catch {
print(error)
}
}
现在编写您的任何其他代码。