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("")))
}
}
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()
}
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))))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With