forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgreSQLDatabaseConfig.swift
69 lines (60 loc) · 2.49 KB
/
PostgreSQLDatabaseConfig.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
import Foundation
import NIOOpenSSL
/// Config options for a `PostgreSQLConnection`
public struct PostgreSQLDatabaseConfig {
/// Creates a `PostgreSQLDatabaseConfig` with default settings.
public static func `default`() -> PostgreSQLDatabaseConfig {
return .init(hostname: "localhost", port: 5432, username: "postgres")
}
/// Destination hostname.
public let hostname: String
/// Destination port.
public let port: Int
/// Username to authenticate.
public let username: String
/// Optional database name to use during authentication.
/// Defaults to the username.
public let database: String?
/// Optional password to use for authentication.
public let password: String?
/// Optional TLSConfiguration. Set this if your PostgreSQL server requires an SSL connection
/// For paid Heroku Postgres plans, set this to `.forClient(certificateVerification: .none)`
public let tlsConfiguration: TLSConfiguration?
/// Creates a new `PostgreSQLDatabaseConfig`.
public init(hostname: String, port: Int = 5432, username: String, database: String? = nil, password: String? = nil, tlsConfiguration: TLSConfiguration? = nil) {
self.hostname = hostname
self.port = port
self.username = username
self.database = database
self.password = password
self.tlsConfiguration = tlsConfiguration
}
/// Creates a `PostgreSQLDatabaseConfig` frome a connection string.
public init(url urlString: String, tlsConfiguration: TLSConfiguration? = nil) throws {
guard let url = URL(string: urlString),
let hostname = url.host,
let port = url.port,
let username = url.user,
url.path.count > 0
else {
throw PostgreSQLError(
identifier: "Bad Connection String",
reason: "Host could not be parsed",
possibleCauses: ["Foundation URL is unable to parse the provided connection string"],
suggestedFixes: ["Check the connection string being passed"],
source: .capture()
)
}
self.hostname = hostname
self.port = port
self.username = username
let database = url.path
if database.hasPrefix("/") {
self.database = database.dropFirst().description
} else {
self.database = database
}
self.password = url.password
self.tlsConfiguration = tlsConfiguration
}
}