9

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("")))
        }
    }
Dani Pralea
  • 4,545
  • 2
  • 31
  • 49

2 Answers2

12

Just in case someone get here and is trying to do it in Vapor 4:

func prepare(on database: Database) -> EventLoopFuture<Void> {
    let defaultValue = SQLColumnConstraintAlgorithm.default(false)
    return database.schema(“event”)
        .field(“is_private”, .bool, .sql(defaultValue))
        .update()
}
ggrana
  • 2,335
  • 2
  • 21
  • 31
7

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))))
  }
}
0xTim
  • 5,146
  • 11
  • 23
  • I'm getting an error `PostgreSQL Error: column "created_at" of relation "experiments" already exists` when using this to add a default value. – Ryan Poolos Jan 08 '20 at 21:37