stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.73k stars 1.57k forks source link

database update with nil on a Codable type does not change the column to null #838

Closed alexzielenski closed 2 years ago

alexzielenski commented 6 years ago

Build Information

General guidelines

If you run try db.run(table.filter(id == desiredID).update(modelObject)) where modelObject is a Codable struct containing an optional value where the corresponding column is defined as nullable, the SQL generated will not include the set to null as expected.

Example:

struct DBAllocation: Codable {
        let amount: Double
        let note: String
        let strategy: AllocationInterval.Datatype
        let tag_id: Int?
        let start_date: Date.Datatype
        let end_date: Date.Datatype?
}

Executing the update with the above struct where end_date is nil produces the following SQL UPDATE "allocations" SET "amount" = 60.0, "note" = 'Electric', "strategy" = 'Monthly', "tag_id" = 4, "start_date" = '2018-08-01T07:00:00.000' WHERE ("id" = 5)

which excludes the end_date column set to NULL as I'd expect.

alexzielenski commented 6 years ago

It seems like in Coding.swift the methods of KeyedEncodingContainerProtocol for encoding optional values were excluded. To be honest, they are kind of non-intuitive. I don't understand why there is a separate encodeNil if it is not going to be used when optional types are indeed nil. Either way, adding the following into that file solved the issue for me:

        ...
        func encodeIfPresent(_ value: Int?, forKey key: MyKey) throws {
            guard let value = value else {
                try encodeNil(forKey: key)
                return
            }
            try encode(value, forKey: key)
        }

        func encodeIfPresent(_ value: String?, forKey key: MyKey) throws {
            guard let value = value else {
                try encodeNil(forKey: key)
                return
            }
            try encode(value, forKey: key)
        }
        ...
jberkel commented 6 years ago

would you mind submitting a PR with these changes?