Repository navigation
Expand file tree
/
Copy patheasy_mysql.h
More file actions
173 lines (143 loc) · 5.54 KB
/
Copy patheasy_mysql.h
File metadata and controls
173 lines (143 loc) · 5.54 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
// Copyright (c) 2026 Yang Zhengguo. All Rights Reserved.
//
// A modern, lightweight C++17 wrapper for MySQL Connector/C++.
// Features: RAII transactions, custom logging, and type-safe parameter binding.
#ifndef EASY_MYSQL_H_
#define EASY_MYSQL_H_
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <string_view>
#include <sstream>
// MySQL Connector/C++ headers
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
namespace easymysql {
// Configuration structure for database connection
struct DbConfig {
std::string host;
int port = 3306;
std::string user;
std::string password;
std::string database;
int connect_timeout = 3; // Seconds
bool auto_reconnect = true;
};
// Log levels for the injected logger
enum class LogLevel {
kDebug,
kInfo,
kWarning,
kError
};
// Logger callback type definition
using LoggerCallback = std::function<void(LogLevel, const std::string&)>;
class EasyMySQL {
public:
// RAII Helper class for managing transactions automatically.
// If this object goes out of scope without Commit() being called,
// it triggers a Rollback().
class Transaction {
public:
explicit Transaction(EasyMySQL* db);
~Transaction();
// Disable copying
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
// Allow moving
Transaction(Transaction&&) = default;
Transaction& operator=(Transaction&&) = default;
bool Commit();
private:
EasyMySQL* db_;
bool committed_;
bool valid_;
};
EasyMySQL();
~EasyMySQL();
// Sets a custom logger. If not set, logs to stderr by default.
void SetLogger(LoggerCallback logger);
// Establishes the database connection.
bool Connect(const DbConfig& config);
// Checks if connection is alive.
bool Ping();
// Executes a non-query SQL (INSERT, UPDATE, DELETE).
// Returns the number of affected rows, or -1 on error.
template <typename... Args>
int64_t Execute(std::string_view sql, Args&&... args) {
std::lock_guard<std::mutex> lock(conn_mutex_);
if (!CheckConnection()) return -1;
try {
std::unique_ptr<sql::PreparedStatement> pstmt(conn_->prepareStatement(sql.data()));
int index = 1;
// C++17 Fold Expression for parameter binding
(BindParam(pstmt.get(), index++, std::forward<Args>(args)), ...);
return pstmt->executeUpdate();
} catch (const sql::SQLException& e) {
LogSqlError(e, sql);
return -1;
}
}
// Executes a query SQL (SELECT).
// Uses a callback to handle the ResultSet to ensure safety.
// Callback should return true to continue, false to stop.
template <typename... Args>
bool Query(std::string_view sql,
std::function<bool(sql::ResultSet*)> result_handler,
Args&&... args) {
std::lock_guard<std::mutex> lock(conn_mutex_);
if (!CheckConnection()) return false;
try {
std::unique_ptr<sql::PreparedStatement> pstmt(conn_->prepareStatement(sql.data()));
int index = 1;
// C++17 Fold Expression
(BindParam(pstmt.get(), index++, std::forward<Args>(args)), ...);
std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery());
if (result_handler) {
return result_handler(res.get());
}
return true;
} catch (const sql::SQLException& e) {
LogSqlError(e, sql);
return false;
}
}
// Transaction primitives (Internal usage or manual control)
bool BeginTransaction();
bool Commit();
bool Rollback();
// Factory method to create a RAII transaction guard
[[nodiscard]] Transaction CreateTransaction() {
return Transaction(this);
}
private:
// Internal method to maintain connection health
bool CheckConnection();
// Logging helper
void Log(LogLevel level, const std::string& msg);
void LogSqlError(const sql::SQLException& e, std::string_view sql);
// --- Parameter Binding Overloads ---
void BindParam(sql::PreparedStatement* pstmt, int index, int32_t val) { pstmt->setInt(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, uint32_t val) { pstmt->setUInt(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, int64_t val) { pstmt->setInt64(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, uint64_t val) { pstmt->setUInt64(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, bool val) { pstmt->setBoolean(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, double val) { pstmt->setDouble(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, const std::string& val) { pstmt->setString(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, const char* val) { pstmt->setString(index, val); }
void BindParam(sql::PreparedStatement* pstmt, int index, std::string_view val) { pstmt->setString(index, std::string(val)); }
// Members
sql::Driver* driver_;
std::unique_ptr<sql::Connection> conn_;
DbConfig config_;
LoggerCallback logger_;
std::mutex conn_mutex_;
bool in_transaction_;
};
} // namespace easymysql
#endif // EASY_MYSQL_H_