-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasy_mysql.cpp
More file actions
200 lines (170 loc) · 5.76 KB
/
easy_mysql.cpp
File metadata and controls
200 lines (170 loc) · 5.76 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// Copyright (c) 2026 Yang Zhengguo. All Rights Reserved.
#include "easy_mysql.h"
#include <iostream>
namespace easymysql {
// --- EasyMySQL Implementation ---
EasyMySQL::EasyMySQL() : driver_(nullptr), in_transaction_(false) {
try {
driver_ = sql::mysql::get_mysql_driver_instance();
} catch (const sql::SQLException& e) {
// Since logger isn't set yet, output to stderr
std::cerr << "[EasyMySQL][Error] Failed to get driver instance: "
<< e.what() << std::endl;
}
}
EasyMySQL::~EasyMySQL() {
if (conn_) {
try {
conn_->close();
} catch (...) {
// Suppress exceptions in destructor
}
}
}
void EasyMySQL::SetLogger(LoggerCallback logger) {
logger_ = std::move(logger);
}
bool EasyMySQL::Connect(const DbConfig& config) {
std::lock_guard<std::mutex> lock(conn_mutex_);
config_ = config;
if (!driver_) {
Log(LogLevel::kError, "MySQL Driver not initialized.");
return false;
}
try {
sql::ConnectOptionsMap options;
options["hostName"] = config.host;
options["port"] = config.port;
options["userName"] = config.user;
options["password"] = config.password;
options["schema"] = config.database;
options["OPT_CONNECT_TIMEOUT"] = config.connect_timeout;
// Some versions of connector support this, others don't
// options["OPT_RECONNECT"] = config.auto_reconnect;
conn_.reset(driver_->connect(options));
Log(LogLevel::kInfo, "Successfully connected to database: " + config.database);
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, "Connect");
return false;
}
}
bool EasyMySQL::CheckConnection() {
if (!conn_ || conn_->isClosed()) {
if (in_transaction_) {
Log(LogLevel::kError, "Connection lost inside a transaction. Cannot auto-reconnect.");
return false;
}
if (config_.auto_reconnect) {
Log(LogLevel::kWarning, "Connection lost. Attempting to reconnect...");
// Release the lock temporarily if Connect calls public methods,
// but here we are reusing logic. We need to be careful about recursion.
// Since we are inside a locked scope (from public methods),
// we should not call Connect() which locks again (deadlock).
// Instead, we duplicate the connection logic or refactor Connect to an internal _Connect.
// For simplicity here, we assume direct driver call:
try {
sql::ConnectOptionsMap options;
options["hostName"] = config_.host;
options["port"] = config_.port;
options["userName"] = config_.user;
options["password"] = config_.password;
options["schema"] = config_.database;
options["OPT_CONNECT_TIMEOUT"] = config_.connect_timeout;
conn_.reset(driver_->connect(options));
Log(LogLevel::kInfo, "Reconnected successfully.");
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, "AutoReconnect");
return false;
}
}
return false;
}
return true;
}
bool EasyMySQL::Ping() {
std::lock_guard<std::mutex> lock(conn_mutex_);
return CheckConnection();
}
bool EasyMySQL::BeginTransaction() {
std::lock_guard<std::mutex> lock(conn_mutex_);
if (!CheckConnection()) return false;
if (in_transaction_) return true;
try {
conn_->setAutoCommit(false);
in_transaction_ = true;
Log(LogLevel::kDebug, "Transaction Started");
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, "BeginTransaction");
return false;
}
}
bool EasyMySQL::Commit() {
std::lock_guard<std::mutex> lock(conn_mutex_);
if (!in_transaction_) return false;
try {
conn_->commit();
conn_->setAutoCommit(true);
in_transaction_ = false;
Log(LogLevel::kDebug, "Transaction Committed");
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, "Commit");
return false;
}
}
bool EasyMySQL::Rollback() {
std::lock_guard<std::mutex> lock(conn_mutex_);
if (!in_transaction_) return false;
try {
conn_->rollback();
conn_->setAutoCommit(true);
in_transaction_ = false;
Log(LogLevel::kDebug, "Transaction Rolled Back");
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, "Rollback");
return false;
}
}
void EasyMySQL::Log(LogLevel level, const std::string& msg) {
if (logger_) {
logger_(level, msg);
} else {
// Default fallback logging
if (level == LogLevel::kError) {
std::cerr << "[EasyMySQL] " << msg << std::endl;
}
}
}
void EasyMySQL::LogSqlError(const sql::SQLException& e, std::string_view sql) {
std::stringstream ss;
ss << "SQLException: " << e.what()
<< " (Code: " << e.getErrorCode() << ", State: " << e.getSQLState() << ")"
<< " [Context: " << sql << "]";
Log(LogLevel::kError, ss.str());
}
// --- Transaction Guard Implementation ---
EasyMySQL::Transaction::Transaction(EasyMySQL* db)
: db_(db), committed_(false), valid_(false) {
if (db_) {
valid_ = db_->BeginTransaction();
}
}
EasyMySQL::Transaction::~Transaction() {
if (valid_ && !committed_ && db_) {
db_->Rollback();
}
}
bool EasyMySQL::Transaction::Commit() {
if (valid_ && !committed_ && db_) {
if (db_->Commit()) {
committed_ = true;
return true;
}
}
return false;
}
} // namespace easymysql