Skip to content

Commit f479a97

Browse files
authored
Merge pull request #220 from vapor/zero-length-arr
add support for encoding zero-length arrays
2 parents 355fdc8 + 67fa1a0 commit f479a97

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

Sources/MySQL/Codable/MySQLDataEncoder.swift

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,13 @@ struct MySQLDataEncoder {
88
let encoder = _Encoder()
99
do {
1010
try value.encode(to: encoder)
11-
return encoder.data!
12-
} catch is _DoJSONError {
13-
struct AnyEncodable: Encodable {
14-
let encodable: Encodable
15-
init(_ encodable: Encodable) {
16-
self.encodable = encodable
17-
}
18-
func encode(to encoder: Encoder) throws {
19-
try encodable.encode(to: encoder)
20-
}
11+
if let data = encoder.data {
12+
return data
13+
} else {
14+
return self.encode(json: value)
2115
}
22-
return .init(json: AnyEncodable(value))
16+
} catch is _DoJSONError {
17+
return self.encode(json: value)
2318
} catch {
2419
ERROR("Could not encode \(type(of: value)) to MySQLData: \(error)")
2520
return .null
@@ -28,6 +23,19 @@ struct MySQLDataEncoder {
2823
}
2924

3025
// MARK: Private
26+
27+
private func encode(json value: Encodable) -> MySQLData {
28+
struct AnyEncodable: Encodable {
29+
let encodable: Encodable
30+
init(_ encodable: Encodable) {
31+
self.encodable = encodable
32+
}
33+
func encode(to encoder: Encoder) throws {
34+
try encodable.encode(to: encoder)
35+
}
36+
}
37+
return .init(json: AnyEncodable(value))
38+
}
3139

3240
private final class _Encoder: Encoder {
3341
let codingPath: [CodingKey] = []

Tests/MySQLTests/MySQLTests.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,13 @@ class MySQLTests: XCTestCase {
331331
XCTAssertEqual(res2.count, 0)
332332
}
333333

334+
// https://github.com/vapor/mysql/issues/221
335+
func testZeroLengthArray() throws {
336+
let arr: [Int] = []
337+
let data = MySQLDataEncoder().encode(arr)
338+
print(data)
339+
}
340+
334341
static let allTests = [
335342
("testBenchmark", testBenchmark),
336343
("testSimpleQuery", testSimpleQuery),
@@ -349,6 +356,7 @@ class MySQLTests: XCTestCase {
349356
("testColumnAfter", testColumnAfter),
350357
("testDecimalPrecision", testDecimalPrecision),
351358
("testZeroRowSelect", testZeroRowSelect),
359+
("testZeroLengthArray", testZeroLengthArray),
352360
]
353361
}
354362

0 commit comments

Comments
 (0)