vapor/fluent-mysql-driver

MySQL Error duplicate column in Migration

clbaeza opened this issue · 4 comments

I have this MySQL Model in my project, get this error when run "Thread 1: Fatal error: Error raised at top level: ⚠️ MySQL Error: Duplicate column name 'content'"

import Vapor
import FluentMySQL
import MySQL


final class Post: MySQLModel {
    static var createdAtKey: TimestampKey? {
        return \.createdAt
    }
    static var updatedAtKey: TimestampKey? {
        return \.updatedAt
    }
    static var deletedAtKey: TimestampKey? {
        return \.deletedAt
    }
    
    var id: Int?
    var userID: User.ID
    var title: String
    var content: String
    var createdAt: Date?
    var updatedAt: Date?
    var deletedAt: Date?
    
    init(id: Int?, userID: User.ID, title: String, content: String){
        self.id = id
        self.userID = userID
        self.title = title
        self.content = content
    }
}

extension Post: Migration {
    static func prepare(on conn: MySQLConnection) -> Future<Void> {
        return Database.create(self, on: conn) { (builder) in
            try addProperties(to: builder)
            builder.reference(from: \.userID, to: \User.id)
            builder.field(for: \.content, type: MySQLDataType.longtext)
        }
    }
}

extension Post: Content { }

extension Post: Parameter { }

extension Post {
    var user: Parent<Post, User> {	
        return parent(\.userID)
    }
}

Screen capture
captura de pantalla 2019-02-20 a la s 3 26 45 p m

vzsg commented

The problem is with your code: calling try addProperties(to: builder) already defines a column for the content field.

Using custom column types is an all-or-nothing deal. You must not call addProperties if you want to customize any of the fields, or if you plan on making your database future-proof with migrations.

I see, I'll have to put each column in the builder inside Migrations.
Doing that, Fluent does the automatic encode and decode between, for example, String and MySQLDataType.longtext?

Thanks for your help!

vzsg commented

Yes, fortunately Fluent will be able to handle that automatically.

Great, thanks for all.