2

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?

  • When you say 'not working', what do you mean? What is the original type? Is there an error? – Nick Apr 01 '23 at 19:18
  • Original type is String and not get error but show below debug code [ DEBUG ] ALTER TABLE "Attraction" ALTER COLUMN "region" SET DATA TYPE TEXT [] [database-id: psql] (FluentPostgresDriver/FluentPostgresDatabase.swift:47 – Mitul Pokiya Apr 03 '23 at 03:35

1 Answers1

2

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.

Nick
  • 4,820
  • 18
  • 31
  • 47