I have a db, and I want to add a column to it if it doesn't exist. How do I do that with sqlite.swift API?
The easiest and straightforward way to check for the column in a table is to use the information schema for column system view. Wright a select query for INFORMATION_SCHEMA. COLUMNS as shown below. If the query returns record, then the column is available in the table.
If you can say the column is the last change to the table then sys. tables(modify_date) is workable.
Generally you'll want to have a migration path if you're adding new columns to existing tables. You can use the userVersion
attribute to manage versions of your database schema:
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
}
You can also, as Max suggested, use ifNotExists:
at the create(table:…)
level:
db.create(table: users, ifNotExists: true) { t in
t.column(id, primaryKey: true)
t.column(email, unique: true)
}
But for adding new columns, you have to parse an unwieldy PRAGMA statement:
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)
}
Not nearly as readable (or recommended), but if you're dealing with a legacy database, maybe necessary.
Be sure to read the ALTER TABLE documentation for more complicated alterations.
The correct way for swift 2.0 is following:
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With