forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLRowEncoder.swift
76 lines (62 loc) · 2.61 KB
/
PostgreSQLRowEncoder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/// Encodes `Encodable` objects to PostgreSQL row data.
public struct PostgreSQLRowEncoder {
/// Creates a new `PostgreSQLRowEncoder`.
public init() { }
/// Encodes an `Encodable` object to `[PostgreSQLColumn: PostgreSQLData]`.
///
/// - parameters:
/// - encodable: Item to encode.
/// - tableOID: Optional table OID to use when encoding.
public func encode<E>(_ encodable: E, tableOID: UInt32 = 0) throws -> [PostgreSQLColumn: PostgreSQLData]
where E: Encodable
{
let encoder = _Encoder(tableOID: tableOID)
try encodable.encode(to: encoder)
return encoder.row
}
// MARK: Private
private final class _Encoder: Encoder {
let codingPath: [CodingKey] = []
var userInfo: [CodingUserInfoKey: Any] = [:]
var row: [PostgreSQLColumn: PostgreSQLData]
let tableOID: UInt32
init(tableOID: UInt32) {
self.row = [:]
self.tableOID = tableOID
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
return .init(_KeyedEncodingContainer(encoder: self))
}
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError()
}
func singleValueContainer() -> SingleValueEncodingContainer {
fatalError()
}
}
private struct _KeyedEncodingContainer<Key>: KeyedEncodingContainerProtocol where Key: CodingKey {
let codingPath: [CodingKey] = []
let encoder: _Encoder
init(encoder: _Encoder) {
self.encoder = encoder
}
mutating func encodeNil(forKey key: Key) throws {
encoder.row[.init(tableOID: encoder.tableOID, name: key.stringValue)] = PostgreSQLData(null: .null)
}
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
encoder.row[.init(tableOID: encoder.tableOID, name: key.stringValue)] = try PostgreSQLDataEncoder().encode(value)
}
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
fatalError()
}
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
fatalError()
}
mutating func superEncoder() -> Encoder {
fatalError()
}
mutating func superEncoder(forKey key: Key) -> Encoder {
fatalError()
}
}
}