Fluent Migrations: Adding/Deleting Columns from a Database

498 Views

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.

Code

Edit June 16, 2018: The video is slightly outdated for the 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)


Enjoy this article? Consider supporting VaporForums by following us on Twitter! Get the latest Vapor articles, tutorials, and news.