Allow Codables with nillable columns to encode as nil, if they wish
This patch was authored by @danramteke and released by @siemensikkema.
In #122 , we resurrected support for nillable columns, however, this caused some issues with downstream clients of this repo.
With this release, we allow clients to opt-in to this behavior.
Here is an example:
struct Gas: Codable {
let name: String
let color: String?
}
let db = TestDatabase()
var serializer = SQLSerializer(database: db)
let insertBuilder = try db.insert(into: "gasses").model(Gas(name: "oxygen", color: nil), nilEncodingStrategy: .asNil)
insertBuilder.insert.serialize(to: &serializer)
XCTAssertEqual(serializer.sql, "INSERT INTO `gasses` (`name`, `color`) VALUES (?, NULL)")
XCTAssertEqual(serializer.binds.count, 1)
XCTAssertEqual(serializer.binds[0] as? String, "oxygen")
Details
There is a new NilEncodingStrategy
right next to the existing KeyEncodingStrategy
. It defaults to the pre-existing behavior that works with Fluent. Clients of this library can pass in a nilEncodingStrategy option to opt-in to the nillable column behavior.