Search code examples
swiftdatabase-migrationvapor

Swift Vapor: remove database field via migration and from struct at the same time


I have added a database migration to remove a field:

static func prepare(on conn: PostgreSQLConnection) -> EventLoopFuture<Void> {
    return Database.update(User.self, on: conn) { builder in
        builder.deleteField(for: \.name)
    }
}

Now this works fine except that when I remove the field name from my User struct, this doesn't compile anymore, because obviously, the keypath for name can't be found.
So this requires me to leave the field in the User struct until after the migration has run and then I can delete the field but then I also need to delete the migration.

That doesn't feel like a good practice to me and I'm probably doing something wrong here.
What can I do instead?


Solution

  • What you can do is get the field by name and have it remove that:

    builder.deleteField(User.Database.QueryField.column("users", "name"))
    

    where

    • users is the table name
    • name is the column/field name