m8labs
m8labs

Reputation: 3721

Avoiding Vapor migrations on a new database

I've created migration for adding a field to the Postgres table, it works as expected on the existing database. But when I want to run the same vapor server with a new database it crashes on the migration with the "field already exists" message, which is, of course, understandable. But how to maintain the server code so it could work both with existing and new databases?

Fatal error: Error raised at top level: PostgreSQL Error: column "the_coloumn" of relation "User" already exists
- id: PostgreSQLError.server.error.check_for_column_name_collision
: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1100.8.280/swift/stdlib/public/core/ErrorType.swift, line 200

Upvotes: 1

Views: 576

Answers (1)

Nick
Nick

Reputation: 5180

Assuming you have deployed the application and have multiple installations then you will need to preserve the two versions of the table. If you haven't then you could always delete the second migration if it does nothing more than add the field. As you have discovered, the field gets created in the first migration on a new installation.

However, if you have to have both then you will need to replace your use of AddProperties in the original migration that builds the table with an explicit list of the fields, less the one you are adding in the second migration. Examples of individual field creations are:

extension User:Migration
{
    static func prepare(on connection:MySQLConnection) -> Future<Void>
    {
        return Database.create(self, on:connection)
        {
            builder in
            builder.field(for:\.id, isIdentifier:true)
            builder.field(for:\.surname, type:.varchar(30, characterSet:nil, collate:nil))
            builder.field(for:\.firstName, type:.varchar(30, characterSet:nil, collate:nil))
        }
    }
}

This will build the table as you had it before when you created the table in the original database. Then your second migration will work as before. See https://docs.vapor.codes/3.0/fluent/migrations/ for more information.

Upvotes: 1

Related Questions