forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLConnection+Query.swift
75 lines (72 loc) · 3.01 KB
/
PostgreSQLConnection+Query.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
import Async
extension PostgreSQLConnection {
/// Sends a parameterized PostgreSQL query command, collecting the parsed results.
public func query(
_ string: String,
_ parameters: [PostgreSQLDataCustomConvertible] = []
) throws -> Future<[[String: PostgreSQLData]]> {
var rows: [[String: PostgreSQLData]] = []
return try query(string, parameters) { row in
rows.append(row)
}.map(to: [[String: PostgreSQLData]].self) {
return rows
}
}
/// Sends a parameterized PostgreSQL query command, returning the parsed results to
/// the supplied closure.
public func query(
_ string: String,
_ parameters: [PostgreSQLDataCustomConvertible] = [],
resultFormat: PostgreSQLResultFormat = .binary(),
onRow: @escaping ([String: PostgreSQLData]) -> ()
) throws -> Future<Void> {
let parameters = try parameters.map { try $0.convertToPostgreSQLData() }
logger?.log(query: string, parameters: parameters)
let parse = PostgreSQLParseRequest(
statementName: "",
query: string,
parameterTypes: parameters.map { $0.type }
)
let describe = PostgreSQLDescribeRequest(type: .statement, name: "")
var currentRow: PostgreSQLRowDescription?
return send([
.parse(parse), .describe(describe), .sync
]) { message in
switch message {
case .parseComplete: break
case .rowDescription(let row): currentRow = row
case .parameterDescription: break
case .noData: break
default: fatalError("Unexpected message during PostgreSQLParseRequest: \(message)")
}
}.flatMap(to: Void.self) {
let resultFormats = resultFormat.formatCodeFactory(currentRow?.fields.map { $0.dataType } ?? [])
// cache so we don't compute twice
let bind = PostgreSQLBindRequest(
portalName: "",
statementName: "",
parameterFormatCodes: parameters.map { $0.format },
parameters: parameters.map { .init(data: $0.data) },
resultFormatCodes: resultFormats
)
let execute = PostgreSQLExecuteRequest(
portalName: "",
maxRows: 0
)
return self.send([
.bind(bind), .execute(execute), .sync
]) { message in
switch message {
case .bindComplete: break
case .dataRow(let data):
let row = currentRow !! "Unexpected PostgreSQLDataRow without preceding PostgreSQLRowDescription."
let parsed = try row.parse(data: data, formatCodes: resultFormats)
onRow(parsed)
case .close: break
case .noData: break
default: fatalError("Unexpected message during PostgreSQLParseRequest: \(message)")
}
}
}
}
}