Home > Blockchain >  Vapor Fluent How to add a new required field key to existing table
Vapor Fluent How to add a new required field key to existing table

Time:11-24

I have a deployed backend built with Vapor Fluent PostgreSQL.

Now I need to add a new required field key new_field to the table with schema name schema_name in the database. I created a new migration:

struct AddNewFieldToSchema: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        database.schema("schema_name")
            .field("new_field", .string, .required)
            .update()
    }
    
    func revert(on database: Database) -> EventLoopFuture<Void> {
        database.schema("schema_name")
            .deleteField("new_field")
            .update()
    }
}

But after running, it gives me error:

Fatal error: Error raised at top level: server: column "new_field" of relation "schema_name" contains null values (ATRewriteTable)

I am guessing it is because there are existing data created using old data model that does not have values for new_field, because this new migration runs fine if the database is empty.

How do I fix this issue? Thanks.

CodePudding user response:

The .field function takes a list of optional properties where you can pass a default, so for you it would be

func prepare(on database: Database) -> EventLoopFuture<Void> {
  database.schema("schema_name")
    .field("new_field", .string, .required, .sql(.default("Your default value")))
    .update()
}
  • Related