-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathPostgreSQLConnection.swift
58 lines (52 loc) · 1.84 KB
/
PostgreSQLConnection.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
import Fluent
import PostgreSQL
public final class Connection: Fluent.Connection {
public let postgresqlConnection: PostgreSQL.Connection
public var queryLogger: QueryLogger?
public var isClosed: Bool {
return !postgresqlConnection.isConnected
}
public init(_ conn: PostgreSQL.Connection) {
postgresqlConnection = conn
}
// Executes a `Query` from and returns an array of results fetched,
// created, or updated by the action.
//
// Drivers that support raw querying accept string queries and
// parameterized values.
//
// This allows Fluent extensions to be written that can support custom
// querying behavior.
@discardableResult
public func query<E: Entity>(_ query: RawOr<Query<E>>) throws -> Node {
switch query {
case .raw(let raw, let values):
return try postgresql(raw, values)
case .some(let query):
let serializer = PostgreSQLSerializer(query)
let (statement, values) = serializer.serialize()
let results = try postgresql(statement, values)
if query.action == .create {
return results.array?[0].object?[E.idKey] ?? Node.null
}
return results
}
}
@discardableResult
private func postgresql(_ query: String, _ values: [Node] = []) throws -> Node {
queryLogger?.log(query, values)
do {
return try postgresqlConnection.execute(
query,
values as [NodeRepresentable]
)
} catch let error as PostgreSQLError
where
error.code == .connectionException ||
error.code == .connectionDoesNotExist ||
error.code == .connectionFailure
{
throw QueryError.connectionClosed(error)
}
}
}