forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLDatabase.swift
47 lines (40 loc) · 1.7 KB
/
PostgreSQLDatabase.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
import Async
/// Creates connections to an identified PostgreSQL database.
public final class PostgreSQLDatabase: Database {
/// This database's configuration.
public let config: PostgreSQLDatabaseConfig
/// If non-nil, will log queries.
public var logger: PostgreSQLLogger?
/// Caches oid -> table name data.
internal var tableNameCache: PostgreSQLTableNameCache?
/// Creates a new `PostgreSQLDatabase`.
public init(config: PostgreSQLDatabaseConfig, on worker: Worker) {
self.config = config
self.tableNameCache = PostgreSQLTableNameCache(connection: makeConnection(on: worker))
}
/// See `Database.makeConnection()`
public func makeConnection(on worker: Worker) -> Future<PostgreSQLConnection> {
let config = self.config
return Future.flatMap(on: worker) {
return try PostgreSQLConnection.connect(hostname: config.hostname, port: config.port, on: worker) { error in
print("[PostgreSQL] \(error)")
}.flatMap(to: PostgreSQLConnection.self) { client in
client.logger = self.logger
client.tableNameCache = self.tableNameCache
return client.authenticate(
username: config.username,
database: config.database,
password: config.password
).transform(to: client)
}
}
}
}
/// A connection created by a `PostgreSQLDatabase`.
extension PostgreSQLConnection: DatabaseConnection, BasicWorker { }
extension DatabaseIdentifier {
/// Default identifier for `PostgreSQLDatabase`.
public static var psql: DatabaseIdentifier<PostgreSQLDatabase> {
return .init("psql")
}
}