在 Vapor 的迁移中添加默认值

Dan*_*lea 4 swift vapor vapor-fluent

如何在流畅迁移中为非可选字段添加默认值?我目前有这个错误:

?? PostgreSQL Error: column "firstName" contains null values
Run Code Online (Sandbox Code Playgroud)

我唯一的选择是

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)
Run Code Online (Sandbox Code Playgroud)

编辑:感谢蒂姆的回答,解决方案是:

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("")))
        }
    }
Run Code Online (Sandbox Code Playgroud)

ggr*_*ana 6

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()
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是 `.sql(.default(false))` (4认同)

0xT*_*Tim 5

还有一个你没见过的选项:

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))))
  }
}
Run Code Online (Sandbox Code Playgroud)