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))))
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.