Skip to content

Commit

Permalink
EncodableRecord takes precedence over Encodable when a record is enco…
Browse files Browse the repository at this point in the history
…ded with a SingleValueEncodingContainer.
  • Loading branch information
groue committed Jul 10, 2024
1 parent ba3c938 commit e6d4223
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
6 changes: 5 additions & 1 deletion GRDB/Record/EncodableRecord+Encodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,11 @@ extension RecordEncoder: SingleValueEncodingContainer {
}

func encode<T>(_ value: T) throws where T : Encodable {
try value.encode(to: self)
if let record = value as? EncodableRecord {
try record.encode(to: &_persistenceContainer)
} else {
try value.encode(to: self)
}
}
}

Expand Down
50 changes: 50 additions & 0 deletions Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,56 @@ extension MutablePersistableRecordEncodableTests {
XCTAssertEqual(row[1], "bar")
}
}

// Regression test for <https://github.com/groue/GRDB.swift/issues/1565>
// Here we test that `EncodableRecord` takes precedence over `Encodable`
// when a record is encoded with a `SingleValueEncodingContainer`.
func testSingleValueContainerWithEncodableRecord() throws {
struct Struct: Encodable, EncodableRecord {
let value: String

func encode(to container: inout PersistenceContainer) throws {
container["column1"] = "test"
container["column2"] = 12
}
}

struct Wrapper<Model: Encodable>: MutablePersistableRecord, Encodable {
static var databaseTableName: String { "t1" }
var model: Model
var otherValue: String

enum CodingKeys: String, CodingKey {
case otherValue
}

func encode(to encoder: any Encoder) throws {
var modelContainer = encoder.singleValueContainer()
try modelContainer.encode(model)

var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(otherValue, forKey: .otherValue)
}
}

let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "t1") { t in
t.column("column1", .text)
t.column("column2", .integer)
t.column("otherValue", .text)
}

var value = Wrapper(model: Struct(value: "foo"), otherValue: "bar")
try assert(value, isEncodedIn: ["column1": "test", "column2": 12, "otherValue": "bar"])

try value.insert(db)
let row = try Row.fetchOne(db, sql: "SELECT column1, column2, otherValue FROM t1")!
XCTAssertEqual(row[0], "test")
XCTAssertEqual(row[1], 12)
XCTAssertEqual(row[2], "bar")
}
}
}

// MARK: - Different kinds of single-value properties
Expand Down

0 comments on commit e6d4223

Please sign in to comment.