-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathMySQLConnect.swift
More file actions
84 lines (74 loc) · 2.28 KB
/
Copy pathMySQLConnect.swift
File metadata and controls
84 lines (74 loc) · 2.28 KB
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
//
// MySQLConnect.swift
// MySQLStORM
//
// Created by Jonathan Guthrie on 2016-09-23.
//
//
import StORM
import PerfectMySQL
import PerfectLogger
/// Base connector class, inheriting from StORMConnect.
/// Provides connection services for the Database Provider
open class MySQLConnect: StORMConnect {
/// Server connection container
public let server = MySQL()
/// Init with no credentials
override public init() {
super.init()
self.datasource = .MySQL
}
public private(set) var charset: String = "utf8mb4"
/// Init with credentials
public init(
host: String,
username: String = "",
password: String = "",
database: String = "",
port: Int = 0,
charset: String = "utf8mb4",
method: StORMConnectionMethod = .network) {
super.init()
self.database = database
self.datasource = .MySQL
let _ = self.server.setOption(.MYSQL_SET_CHARSET_NAME, charset)
self.charset = charset
self.credentials = StORMDataSourceCredentials(host: host, port: port, user: username, pass: password, method: method)
}
/// Opens the connection
/// If an error is generated, the connection state will be output to console and to ./StORMlog.txt
public func open() {
if self.credentials.method == .socket {
let status = server.connect(
user: self.credentials.username,
password: self.credentials.password,
db: self.database,
socket: self.credentials.host)
guard status else {
// verify connection success
LogFile.error("MySQL network connection error: \(server.errorMessage())", logFile: StORMDebug.location)
resultCode = .error(server.errorMessage())
return
}
} else {
let status = server.connect(
host: self.credentials.host,
user: self.credentials.username,
password: self.credentials.password,
db: self.database,
port: UInt32(self.credentials.port)
)
guard status else {
// verify connection success
LogFile.error("MySQL socket connection error: \(server.errorMessage())", logFile: StORMDebug.location)
resultCode = .error(server.errorMessage())
return
}
}
resultCode = .noError
}
/// Closes the connection
public func close() {
server.close()
}
}