Merge pull request #449 from groue/feature/fixEmptyContainersJSONEncoding

Fix JSON encoding of empty containers
This commit is contained in:
Gwendal Roué authored and GitHub committed 2018-11-28 12:24:14 +01:00
commit 769b247da9
4 files changed
+138 -10

No files matched your search

+5
View File
@@ -43,6 +43,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
## Next Version
### Fixed
- [#449](https://github.com/groue/GRDB.swift/pull/449): Fix JSON encoding of empty containers
### New
- [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex
@@ -140,6 +140,10 @@ private class RecordEncoder<Record: MutablePersistableRecord>: Encoder {
// error happens, we'll switch to JSON encoding.
let encoder = ColumnEncoder(recordEncoder: self, key: key)
try value.encode(to: encoder)
if encoder.requiresJSON {
// Here we handle empty arrays and dictionaries.
throw JSONRequiredError()
}
} catch is JSONRequiredError {
// Encode to JSON
let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value)
@@ -159,11 +163,12 @@ private class RecordEncoder<Record: MutablePersistableRecord>: Encoder {
// MARK: - ColumnEncoder
/// The encoder that encodes into a database column
private struct ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
private class ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
var recordEncoder: RecordEncoder<Record>
var key: CodingKey
var codingPath: [CodingKey] { return [key] }
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
var requiresJSON = false
init(recordEncoder: RecordEncoder<Record>, key: CodingKey) {
self.recordEncoder = recordEncoder
@@ -174,6 +179,7 @@ private struct ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
// Keyed values require JSON encoding: we need to throw
// JSONRequiredError. Since we can't throw right from here, let's
// delegate the job to a dedicated container.
requiresJSON = true
let container = JSONRequiredEncoder<Record>.KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
@@ -182,6 +188,7 @@ private struct ColumnEncoder<Record: MutablePersistableRecord>: Encoder {
// Keyed values require JSON encoding: we need to throw
// JSONRequiredError. Since we can't throw right from here, let's
// delegate the job to a dedicated container.
requiresJSON = true
return JSONRequiredEncoder<Record>(codingPath: codingPath)
}
@@ -477,24 +477,44 @@ extension FetchableRecordDecodableTests {
try db.create(table: "t1") { t in
t.column("nested", .text)
}
let nested = NestedStruct(firstName: "Bob", lastName: "Dylan")
let value = StructWithNestedType(nested: [nested, nested])
}
try dbQueue.inTransaction { db in
let value = StructWithNestedType(nested: [
NestedStruct(firstName: "Bob", lastName: "Dylan"),
NestedStruct(firstName: "Bob", lastName: "Dylan")])
try value.insert(db)
let parentModel = try StructWithNestedType.fetchAll(db)
let parentModel = try StructWithNestedType.fetchOne(db)
guard let arrayOfNestedModel = parentModel.first?.nested, let firstNestedModelInArray = arrayOfNestedModel.first else {
guard let nested = parentModel?.nested else {
XCTFail()
return
return .rollback
}
// Check there are two models in array
XCTAssertTrue(arrayOfNestedModel.count == 2)
XCTAssertEqual(nested.count, 2)
// Check the nested model contains the expected values of first and last name
XCTAssertEqual(firstNestedModelInArray.firstName, "Bob")
XCTAssertEqual(firstNestedModelInArray.lastName, "Dylan")
XCTAssertEqual(nested[0].firstName, "Bob")
XCTAssertEqual(nested[0].lastName, "Dylan")
return .rollback
}
try dbQueue.inTransaction { db in
let value = StructWithNestedType(nested: [])
try value.insert(db)
let parentModel = try StructWithNestedType.fetchOne(db)
guard let nested = parentModel?.nested else {
XCTFail()
return .rollback
}
XCTAssertTrue(nested.isEmpty)
return .rollback
}
}
@@ -416,6 +416,102 @@ extension MutablePersistableRecordEncodableTests {
}
}
func testArrayJSONEncoding() throws {
struct Record: PersistableRecord, Encodable {
let array: [String]
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "record") { t in
t.autoIncrementedPrimaryKey("id")
t.column("array", .text)
}
try Record(array: []).insert(db)
try Record(array: ["foo"]).insert(db)
try Record(array: ["foo", "bar"]).insert(db)
let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id")
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0]["array"], "[]")
XCTAssertEqual(rows[1]["array"], "[\"foo\"]")
XCTAssertEqual(rows[2]["array"], "[\"foo\",\"bar\"]")
}
}
func testOptionalArrayJSONEncoding() throws {
struct Record: PersistableRecord, Encodable {
let array: [String]?
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "record") { t in
t.autoIncrementedPrimaryKey("id")
t.column("array", .text)
}
try Record(array: nil).insert(db)
try Record(array: []).insert(db)
try Record(array: ["foo"]).insert(db)
try Record(array: ["foo", "bar"]).insert(db)
let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id")
XCTAssertEqual(rows.count, 4)
XCTAssertTrue(rows[0]["array"] == nil)
XCTAssertEqual(rows[1]["array"], "[]")
XCTAssertEqual(rows[2]["array"], "[\"foo\"]")
XCTAssertEqual(rows[3]["array"], "[\"foo\",\"bar\"]")
}
}
func testDictionaryJSONEncoding() throws {
struct Record: PersistableRecord, Encodable {
let dictionary: [String: Int]
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "record") { t in
t.autoIncrementedPrimaryKey("id")
t.column("dictionary", .text)
}
try Record(dictionary: [:]).insert(db)
try Record(dictionary: ["foo": 1]).insert(db)
let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id")
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0]["dictionary"], "{}")
XCTAssertEqual(rows[1]["dictionary"], "{\"foo\":1}")
}
}
func testOptionalDictionaryJSONEncoding() throws {
struct Record: PersistableRecord, Encodable {
let dictionary: [String: Int]?
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "record") { t in
t.autoIncrementedPrimaryKey("id")
t.column("dictionary", .text)
}
try Record(dictionary: nil).insert(db)
try Record(dictionary: [:]).insert(db)
try Record(dictionary: ["foo": 1]).insert(db)
let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id")
XCTAssertEqual(rows.count, 3)
XCTAssertTrue(rows[0]["dictionary"] == nil)
XCTAssertEqual(rows[1]["dictionary"], "{}")
XCTAssertEqual(rows[2]["dictionary"], "{\"foo\":1}")
}
}
func testJSONDataEncodingStrategy() throws {
struct Record: PersistableRecord, Encodable {
let data: Data