forked from vapor/postgres-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresConfiguration.swift
89 lines (79 loc) · 2.63 KB
/
PostgresConfiguration.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@_exported import struct Foundation.URL
public struct PostgresConfiguration {
public var address: () throws -> SocketAddress
public var username: String
public var password: String?
public var database: String?
public var tlsConfiguration: TLSConfiguration?
/// Optional `search_path` to set on new connections.
public var searchPath: [String]?
/// IANA-assigned port number for PostgreSQL
/// `UInt16(getservbyname("postgresql", "tcp").pointee.s_port).byteSwapped`
public static var ianaPortNumber: Int { 5432 }
internal var _hostname: String?
public init?(url: String) {
guard let url = URL(string: url) else {
return nil
}
self.init(url: url)
}
public init?(url: URL) {
guard url.scheme?.hasPrefix("postgres") == true else {
return nil
}
guard let username = url.user else {
return nil
}
let password = url.password
guard let hostname = url.host else {
return nil
}
let port = url.port ?? Self.ianaPortNumber
let tlsConfiguration: TLSConfiguration?
if url.query?.contains("ssl=true") == true || url.query?.contains("sslmode=require") == true {
tlsConfiguration = TLSConfiguration.makeClientConfiguration()
} else {
tlsConfiguration = nil
}
self.init(
hostname: hostname,
port: port,
username: username,
password: password,
database: url.path.split(separator: "/").last.flatMap(String.init),
tlsConfiguration: tlsConfiguration
)
}
public init(
unixDomainSocketPath: String,
username: String,
password: String? = nil,
database: String? = nil
) {
self.address = {
return try SocketAddress.init(unixDomainSocketPath: unixDomainSocketPath)
}
self.username = username
self.password = password
self.database = database
self.tlsConfiguration = nil
self._hostname = nil
}
public init(
hostname: String,
port: Int = Self.ianaPortNumber,
username: String,
password: String? = nil,
database: String? = nil,
tlsConfiguration: TLSConfiguration? = nil
) {
self.address = {
return try SocketAddress.makeAddressResolvingHost(hostname, port: port)
}
self.username = username
self.database = database
self.password = password
self.tlsConfiguration = tlsConfiguration
self._hostname = hostname
}
}