Any web application will need to have its database modified at some point. Here, I go over how to add and remove columns from a database using Vapor's ORM, Fluent.
prepare
function. Below is the most updated code.migrations.swift
:
struct AddCompletedToTodos: Migration {
// Need to declare which database
typealias Database = PostgreSQLDatabase
static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture {
return Database.update(Todo.self, on: conn) { builder in
builder.field(for: \Todo.completed, type: PostgreSQLQuery.DataType.bool, PostgreSQLQuery.ColumnConstraint.null)
}
}
static func revert(on connection: PostgreSQLConnection) -> EventLoopFuture {
return Future.map(on: connection) {}
}
}
struct RemoveCompletedFromTodos: Migration {
typealias Database = PostgreSQLDatabase
static func prepare(on connection: PostgreSQLConnection) -> EventLoopFuture {
return Database.update(Todo.self, on: connection, closure: { updater in
try updater.removeField(for: \Todo.completed)
})
}
static func revert(on connection: PostgreSQLConnection) -> EventLoopFuture {
return Future.map(on: connection) {}
}
}
configure.swift
migrations.add(migration: AddCompletedToTodos.self, database: .psql)
migrations.add(migration: RemoveCompletedFromTodos.self, database: .psql)