forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresDatabase+SimpleQuery.swift
71 lines (63 loc) · 2.22 KB
/
PostgresDatabase+SimpleQuery.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
import NIO
import Logging
extension PostgresDatabase {
public func simpleQuery(_ string: String) -> EventLoopFuture<[PostgresRow]> {
var rows: [PostgresRow] = []
return simpleQuery(string) { rows.append($0) }.map { rows }
}
public func simpleQuery(_ string: String, _ onRow: @escaping (PostgresRow) throws -> ()) -> EventLoopFuture<Void> {
let query = PostgresSimpleQuery(query: string, onRow: onRow)
return self.send(query, logger: self.logger)
}
}
// MARK: Private
private final class PostgresSimpleQuery: PostgresRequest {
var query: String
var onRow: (PostgresRow) throws -> ()
var rowLookupTable: PostgresRow.LookupTable?
init(query: String, onRow: @escaping (PostgresRow) throws -> ()) {
self.query = query
self.onRow = onRow
}
func log(to logger: Logger) {
logger.debug("\(self.query)")
}
func respond(to message: PostgresMessage) throws -> [PostgresMessage]? {
if case .error = message.identifier {
// we should continue after errors
return []
}
switch message.identifier {
case .dataRow:
let data = try PostgresMessage.DataRow(message: message)
guard let rowLookupTable = self.rowLookupTable else { fatalError() }
let row = PostgresRow(dataRow: data, lookupTable: rowLookupTable)
try onRow(row)
return []
case .rowDescription:
let row = try PostgresMessage.RowDescription(message: message)
self.rowLookupTable = PostgresRow.LookupTable(
rowDescription: row,
resultFormat: []
)
return []
case .commandComplete:
return []
case .readyForQuery:
return nil
case .notice:
return []
case .notificationResponse:
return []
case .parameterStatus:
return []
default:
throw PostgresError.protocol("Unexpected message during simple query: \(message)")
}
}
func start() throws -> [PostgresMessage] {
return try [
PostgresMessage.SimpleQuery(string: self.query).message()
]
}
}