Skip to content

Commit 902eb00

Browse files
authored
support encoding arrays other than json (#172)
* support encoding arrays other than json * simplify decoder method * test fluent on 5.2
1 parent 222dcf7 commit 902eb00

File tree

3 files changed

+7
-14
lines changed

3 files changed

+7
-14
lines changed

.github/workflows/test.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ jobs:
3636
- run: swift test --enable-test-discovery --sanitize=thread
3737
fluent:
3838
container:
39-
image: vapor/swift:5.1
39+
image: vapor/swift:5.2
4040
services:
4141
psql:
4242
image: postgres

Sources/PostgresKit/PostgresDataDecoder.swift

+1-10
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ public final class PostgresDataDecoder {
5656
}
5757

5858
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
59-
print(self.data.type)
6059
guard let data = self.data.array else {
6160
throw Error.unexpectedDataType(self.data.type, expected: "array")
6261
}
@@ -108,15 +107,7 @@ public final class PostgresDataDecoder {
108107
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
109108
defer { self.currentIndex += 1 }
110109
let data = self.data[self.currentIndex]
111-
let jsonData: Data
112-
if let jsonb = data.jsonb {
113-
jsonData = jsonb
114-
} else if let json = data.json {
115-
jsonData = json
116-
} else {
117-
throw Error.unexpectedDataType(data.type, expected: "json")
118-
}
119-
return try self.json.decode(T.self, from: jsonData)
110+
return try PostgresDataDecoder(json: self.json).decode(T.self, from: data)
120111
}
121112

122113
mutating func nestedContainer<NestedKey>(

Sources/PostgresKit/PostgresDataEncoder.swift

+5-3
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@ public final class PostgresDataEncoder {
88
}
99

1010
public func encode(_ value: Encodable) throws -> PostgresData {
11-
if let custom = value as? PostgresDataConvertible {
12-
return custom.postgresData!
11+
if let custom = value as? PostgresDataConvertible, let data = custom.postgresData {
12+
return data
1313
} else {
1414
let context = _Context()
1515
try value.encode(to: _Encoder(context: context))
1616
if let value = context.value {
1717
return value
1818
} else if let array = context.array {
19-
return PostgresData(array: array, elementType: .jsonb)
19+
let elementType = array.first?.type ?? .jsonb
20+
assert(array.filter { $0.type != elementType }.isEmpty, "Array does not contain all: \(elementType)")
21+
return PostgresData(array: array, elementType: elementType)
2022
} else {
2123
return try PostgresData(jsonb: self.json.encode(_Wrapper(value)))
2224
}

0 commit comments

Comments
 (0)