swiftdatabase-migrationvaporvapor-fluentserver-side-swift

How to update field from required to optional using vapor (fluent migration)?


I'm use vapor 4

struct MakeRegionOptional: AsyncMigration {
    
    func prepare(on database: Database) async throws {
        try await database.schema("Attraction")
            .updateField("region", .string)
            .update()
    }
    
    func revert(on database: Database) async throws {
        try await database.schema("Attraction")
            .field("region", .sql(.default("")))
            .update()
    }
    
}

also adding migrations in the configuration file update table model.

app.migrations.add(MakeRegionOptional())

// Attraction model for table

final class Attraction: Model, Content {
    static let schema = "Attraction"
    
    @ID(key: .id)
    var id: UUID?
    
    
    //Before
    //@Field(key: "region")
    //var region: String
    
    // after make optional
    @OptionalField(key: "region")
    var region: String?
    
    init() { }
    
    init(id: UUID? = nil, region: String?) {
        self.id = id
        self.region = region
    }
     }

I'm trying to make optional region field using migration. But my code is not working maybe my migration is wrong. Anyone knows how to make working on this migration?


Solution

  • update() enables you to change a column from optional, to .required but not the other way. Something like .notRequired would be useful here, but it doesn't exist!

    The easiest way is to use a raw sql query to alter the column.