-
Notifications
You must be signed in to change notification settings - Fork 2
Schema Alterations
If you have released your application with SQLiteModel and later decide you want to add a column to a table, you probably want to be able to alter the schema instead of dropping the table and creating a new one. SQLiteModel supplies this functionality through the static alterSchema abstract method.
This method is an optional override, so unlike buildTable, you don't have to implement it if you don't need to.
The SchemaUpdater supplied in the alterSchema method has a public method alterTable which takes a string which is used to tag the alteration (so we don't alter a table more than once). Tags must be unique or they wont work.
The alterTable method also supplies a closure with a Table as a parameter which requires you to return an array of AlterationStatements (which are just strings). You can always return custom statements here, but you are responsible for making sure they work ;)
Say we decide we want to add a Year column to our Movie model. It can be done as follows:
struct Movie: SQLiteModel {
var localID: SQLiteModelID = -1
static let Title = Expression<String>("title")
static let ReleaseDate = Expression<NSDate>("release_date")
static let Gross = Expression<Double>("gross")
// Alteration v0.1
static let Year = Expression<String>("year")
static func buildTable(tableBuilder: TableBuilder) {
tableBuilder.column(Title)
tableBuilder.column(ReleaseDate, defaultValue: NSDate())
tableBuilder.column(Gross, defaultValue: 0)
}
static func alterSchema(schemaUpdater: SchemaUpdater) {
schemaUpdater.alterTable("v0.1") { (table: Table) -> [AlterationStatement]! in
return [
table.addColumn(Year, defaultValue: "unknown")
]
}
}
}SQLiteModel