Search code examples
swiftvaporvapor-fluent

Add a default value in migration in Vapor


How do I add a default value for a non-optional field in a fluent migration? I currently have this error:

⚠️ PostgreSQL Error: column "firstName" contains null values

my only options are

public func field<T>(for key: KeyPath<Self.Model, T>, isIdentifier: Bool? = nil)
public func field<T>(for key: KeyPath<Self.Model, T>, type: Self.Model.Database.SchemaFieldType)

EDIT: Thanks to Tim's answer, the solution is:

static func prepare(on conn: PostgreSQLConnection) -> Future<Void> {
        return Database.update(User.self, on: conn) { builder in
            builder.field(for: \User.firstName, type: .text, .default(.literal("")))
        }
    }

Solution

  • There is another option that you haven't seen:

    static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
      return Database.update(Event.self, on: connection) { builder in
        builder.field(for: \Event.isPrivate, type: .boolean, .default(.literal(.boolean(.false))))
      }
    }