2

I'm using Vapor 3 and FluentMySQL for my new project and want to change maximum length of a field (varchar(N)) via migration. How can I do this?

I have a Model named Word in my project and one of its fields is sourceIdentifier that is String and have maximum length of 12. The model is something like this:

final class Word: MySQLModel {
    ...other properties

    var sourceIdentifier: String

    ...other properties
}

At the beginning, I thought 5 is enough for the field and used this code to create Table for this model:

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return MySQLDatabase.create(Word.self, on: conn) { builder in
        ...other fields...

        builder.field(for: \.sourceIdentifier, type: .varchar(5, characterSet: nil, collate: nil))

        ...other fields...
    }
}

As you see above, the table created with field sourceIdentifier and its type is .varchar(5, characterSet: nil, collate: nil).

Now I want to increase maximum length of the field via migration.

I also tried MySQLDatabase.update like this:

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return MySQLDatabase.update(Word.self, on: conn) { builder in
        builder.field(for: \.sourceIdentifier, type: .varchar(12, characterSet: nil, collate: nil))
    }
}

and it didn't work; Nothing happened.

How can I change structure of the table via Vapor, FluentMySQL and migrations?

Omid Golparvar
  • 468
  • 5
  • 12

2 Answers2

2

You could do anything with raw query like this

static func prepare(on conn: MySQLConnection) -> Future<Void> {
    return conn.raw("ALTER TABLE emp MODIFY COLUMN name VARCHAR(100);").run()
}
imike
  • 5,515
  • 2
  • 37
  • 44
0

You could try this.

static func prepare(on conn: MySQLConnection) -> Future<Void> {
  return Database.create(self, on: connection) { builder in
    builder.field(for: \.id, type: .bigint(20), .primaryKey)
    builder.field(for: \.fieldA, type: .varchar(12))
    builder.field(for: \.fieldB, type: .bigint(20))
  }
}

Instead of using addProperties(to:) to add all the fields to the database, you could use field(for:type:_:) to add fields manually.

zvv
  • 33
  • 5