forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresRow.swift
77 lines (68 loc) · 2.39 KB
/
PostgresRow.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
77
public struct PostgresRow: CustomStringConvertible {
final class LookupTable {
let rowDescription: PostgresMessage.RowDescription
let resultFormat: [PostgresFormatCode]
struct Value {
let index: Int
let field: PostgresMessage.RowDescription.Field
}
private var _storage: [String: Value]?
var storage: [String: Value] {
if let existing = self._storage {
return existing
} else {
let all = self.rowDescription.fields.enumerated().map { (index, field) in
return (field.name, Value(index: index, field: field))
}
let storage = [String: Value](all) { a, b in
// take the first value
return a
}
self._storage = storage
return storage
}
}
init(
rowDescription: PostgresMessage.RowDescription,
resultFormat: [PostgresFormatCode]
) {
self.rowDescription = rowDescription
self.resultFormat = resultFormat
}
func lookup(column: String) -> Value? {
if let value = self.storage[column] {
return value
} else {
return nil
}
}
}
public let dataRow: PostgresMessage.DataRow
public var rowDescription: PostgresMessage.RowDescription {
self.lookupTable.rowDescription
}
let lookupTable: LookupTable
public func column(_ column: String) -> PostgresData? {
guard let entry = self.lookupTable.lookup(column: column) else {
return nil
}
let formatCode: PostgresFormatCode
switch self.lookupTable.resultFormat.count {
case 1: formatCode = self.lookupTable.resultFormat[0]
default: formatCode = entry.field.formatCode
}
return PostgresData(
type: entry.field.dataType,
typeModifier: entry.field.dataTypeModifier,
formatCode: formatCode,
value: self.dataRow.columns[entry.index].value
)
}
public var description: String {
var row: [String: PostgresData] = [:]
for field in self.lookupTable.rowDescription.fields {
row[field.name] = self.column(field.name)
}
return row.description
}
}