Compare commits

..

No commits in common. 'dev' and 'queue' have entirely different histories.
dev ... queue

  1. 47
      .vscode/settings.json
  2. 73
      LICENSE
  3. 155
      README.md
  4. 265
      lib/mysql.hpp
  5. 347
      src/mysql.cpp
  6. 262
      test/test.cpp
  7. BIN
      test/test.o

@ -16,51 +16,6 @@
"fstream": "cpp", "fstream": "cpp",
"new": "cpp", "new": "cpp",
"thread": "cpp", "thread": "cpp",
"chrono": "cpp", "chrono": "cpp"
"sstream": "cpp",
"map": "cpp",
"cctype": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"atomic": "cpp",
"bit": "cpp",
"compare": "cpp",
"concepts": "cpp",
"condition_variable": "cpp",
"cstdint": "cpp",
"list": "cpp",
"unordered_map": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory": "cpp",
"memory_resource": "cpp",
"numeric": "cpp",
"random": "cpp",
"ratio": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"iosfwd": "cpp",
"istream": "cpp",
"limits": "cpp",
"numbers": "cpp",
"semaphore": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"cinttypes": "cpp",
"typeinfo": "cpp",
"any": "cpp",
"variant": "cpp"
} }
} }

@ -1,73 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [2023] [Marcel Bandić - marcelb96@yahoo.com]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -1,154 +1 @@
A library for MySQL that implements a simpler framework for MySQL Connector++
# A library for MySQL that implements a simpler framework for MySQL Connector++
A small framework for basic MySQL database operations via MySQL/Connector++
## Features
- Object oriented
- Active connection pool
- Retries to connect
- Native C++ containers: vector, tuple
- Response object
- Thread safe
- Exceptions and log error callback
- Can use external time loop for connection management
## Installation
First install dependency MySQL/Connector++
```
sudo apt install libmysqlcppconn-dev
```
Just download the latest release and unzip it into your project. You can turn it on with:
```
#include "mysql/lib/mysql.hpp"
using namespace marcelb;
```
## Usage
### Internal engine
It internally initializes a single thread that periodically checks the states of the connection pool, adds new ones as needed, and cleans up inactive ones.
```c++
#include "../lib/mysql.hpp"
using namespace marcelb::mysql;
/**
* Init
*/
MySQL mydb("tcp://192.168.2.10:3306", "user_nm", "passss", "my_db", 5);
/**
* Use ------------------
*/ | |
------------------ |
try { | | | |
// execute | | | |
auto response = mydb.exec<int,string>("SELECT id,domain FROM records WHERE enabled = 0;");
// response is MySQL_Res<int,string> type
// check is execute
cout << response.affected << " " << response.have_result << endl;
cout << response.rows << " " << response.columns << endl;
for (auto row : response) { // row is tuple<int,string> type
cout << get<0>(row) << " " << get<1>(row) << endl;
}
// access columns name
for (auto column_name : response.columns_name) {
cout << column_name << endl;
}
} catch (const string err) {
cout << err << endl;
}
```
### External engine
As I developed quite a few wrappers that have some internal thread, I realized that it was inefficient and made it possible to call the necessary functions periodically outside (one thread per whole application or timer (ASIO), or my asynco wrapper).
```c++
#include "../lib/mysql.hpp"
using namespace marcelb::mysql;
#include "../../asynco/lib/timers.hpp"
using namespace marcelb::asynco;
/**
* Init
*/
MySQL mydb("tcp://192.168.2.10:3306", "user_nm", "passss", "my_db", 5, time_loop_type::external);
periodic mysql_maintenance ( [&mydb] () {
mydb.periodic_maintenance();
}, MYSQL_PERIODIC_INTERNAL_TIME);
mydb.set_on_error( [](const string& error) {
cout << error << endl; // print or log
});
/**
* You can call multiple queries asynchronously
*/
auto a1 = atask ( [&mydb] () {
try {
auto response = mydb.exec<int,string>("SELECT id,domain FROM records WHERE enabled = 1;");
for (auto row : response) {
cout << get<0>(row) << " " << get<1>(row) << endl;
}
} catch (const string err) {
cout << err << endl;
}
});
auto a2 = atask ( [&mydb] () {
try {
auto response = mydb.exec<string,string>("SELECT zonename,auth_key FROM zones;");
for (auto row : response) {
cout << get<0>(row) << " " << get<1>(row) << endl;
}
} catch (const string err) {
cout << err << endl;
}
});
auto a3 = atask ( [&mydb] () {
try {
auto response = mydb.exec<string,string>("SELECT username,email FROM users WHERE enabled = 1;");
for (auto row : response) {
cout << get<0>(row) << " " << get<1>(row) << endl;
}
} catch (const string err) {
cout << err << endl;
}
});
wait(a1);
wait(a2);
wait(a3);
```
## License
[APACHE 2.0](http://www.apache.org/licenses/LICENSE-2.0/)
## Support & Feedback
For support and any feedback, contact the address: marcelb96@yahoo.com.
## Contributing
Contributions are always welcome!
Feel free to fork and start working with or without a later pull request. Or contact for suggest and request an option.

@ -1,14 +1,15 @@
#ifndef _MYSQL_ #ifndef _MYSQL_
#define _MYSQL_ #define _MYSQL_
#include <queue> #include <string>
#include <sstream>
#include <vector>
#include <deque>
#include <map>
#include <iostream>
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <future> #include <future>
#include <string>
#include <vector>
#include <tuple>
#include "ctime"
#include <mysql_driver.h> #include <mysql_driver.h>
#include <mysql_connection.h> #include <mysql_connection.h>
@ -25,213 +26,67 @@ using namespace std;
using namespace sql; using namespace sql;
using namespace mysql; using namespace mysql;
namespace marcelb { class sqlQA {
namespace mysql {
/**
*
*/
#define MYSQL_PERIODIC_INTERNAL_TIME 1000
/**
* An enumeration of how periodic functions will be run
* internal - run periodic_maintenance() i new thread
* external - expects periodic_maintenance() to be run periodically outside the library
*
*/
enum class time_loop_type {
internal,
external
};
/**
* A class for creating sql responses
*/
template<typename... Types>
class MySQL_Res : public vector<tuple<Types...>> {
public: public:
bool have_result = false; // query
uint16_t affected = 0; string cmd;
uint16_t rows = 0; string table;
uint16_t columns = sizeof...(Types); vector<string> columns;
vector<string> columns_name; bool isUpdate = false;
bool isSelect = false;
// answer
uint updateCatch = 0;
bool executed = false;
map<string, vector<string>> result;
uint num_rows = 0;
uint num_columns = 0;
// query methods
sqlQA& select(const string _select = "*");
sqlQA& from(const string _tablename);
sqlQA& where(const string _condition);
sqlQA& limit(const uint _limit);
sqlQA& insertInTo(const string _tablename, const string _columns = "");
sqlQA& values(const string _values);
sqlQA& update(const string _tablename);
sqlQA& set(const string _column_value_pairs);
sqlQA& deleteFrom(const string _table);
void print(bool withDetail = false);
// answer methods
private:
void parse_columns(const string _cloumns);
}; };
/** class mySQL {
* Type conversion functions private:
*/
template<typename T>
T getValue(ResultSet* res, int column);
template<>
inline int getValue<int>(ResultSet* res, int column) {
return res->getInt(column);
}
template<>
inline uint32_t getValue<uint32_t>(ResultSet* res, int column) {
return res->getUInt(column);
}
template<>
inline int64_t getValue<int64_t>(ResultSet* res, int column) {
return res->getInt64(column);
}
template<>
inline uint64_t getValue<uint64_t>(ResultSet* res, int column) {
return res->getUInt64(column);
}
template<>
inline float getValue<float>(ResultSet* res, int column) {
return res->getDouble(column);
}
template<>
inline double getValue<double>(ResultSet* res, int column) {
return res->getDouble(column);
}
template<>
inline string getValue<string>(ResultSet* res, int column) {
return res->getString(column);
}
template<>
inline bool getValue<bool>(ResultSet* res, int column) {
return res->getBoolean(column);
}
// implementiraj neku c++ kompatibilnu pretvorbu za timestampe, time, date datetime itd.
class MySQL {
mutex io; mutex io;
condition_variable condition;
MySQL_Driver *drv; MySQL_Driver *drv;
queue<Connection*> connection_pool; deque<Connection*> con;
string path, username, password, database; string path, username, password, db;
uint32_t pool_size; uint available;
bool run_tloop = true; uint reconTrys = 3;
future<void> tloop_future;
time_loop_type tloop_type;
time_t last_loop_time;
/**
* Open one database server connection
*/
Connection* create_connection();
/**
* Close one database connection
*/
bool disconnect_connection(Connection* connection);
/**
* Take an pool_size database connection
*/
Connection* occupy_connection();
/**
* Free an database connection
*/
void release_connection(Connection* connection);
/**
* Function parses a parameterized row
*/
template<typename... Types, size_t... Is>
static tuple<Types...> getRow(sql::ResultSet* res, index_sequence<Is...>) {
return make_tuple(getValue<Types>(res, Is + 1)...);
}
/**
* Connect all connections to server
*/
void connect_pool();
/**
* Disconnect all connections to server
*/
void disconnect_pool();
/**
* Internal tloop periodic
*/
void _tloop();
public:
function<void(const string&)> on_error;
uint32_t connect_trys = 3;
/**
* MySQL constructor,
* receive the path to the mysql server,
* username, password, database name,
* and number of active connections (optional)
*/
MySQL(const string _path, const string _username, const string _password, const string _db, const uint32_t _available = 1, const time_loop_type _engine_type = time_loop_type::internal);
/**
* Execute the SQL statement
*/
template<typename... Types>
MySQL_Res<Types...> exec(const string& sql_q) {
Connection* connection = occupy_connection();
MySQL_Res<Types...> result;
try {
Statement *stmt;
stmt = connection->createStatement();
result.have_result = stmt->execute(sql_q);
if (result.have_result) {
ResultSet* res = stmt->getResultSet();
result.rows = res->rowsCount();
ResultSetMetaData *metaData = res->getMetaData();
int columnCount = metaData->getColumnCount();
for (int i = 1; i <= columnCount; ++i) {
result.columns_name.push_back(metaData->getColumnName(i));
}
while (res->next()) {
result.push_back(MySQL::getRow<Types...>(res, make_index_sequence<sizeof...(Types)>{}));
}
res->close();
delete res;
} else {
result.affected = stmt->getUpdateCount();
}
stmt->close();
delete stmt;
release_connection(connection);
} catch (sql::SQLException& e) {
throw runtime_error(e.what());
// std::cerr << "SQLState: " << e.getSQLState() << std::endl;
// std::cerr << "Error code: " << e.getErrorCode() << std::endl;
}
return result;
}
/**
* If you are using an external periodic motor,
* please call this function in it for proper operation at a certain time interval.
* You can use the default MYSQL_PERIODIC_INTERNAL_TIME
*/
void tloop();
/**
* Destruktor
* close all connections
*/
~MySQL();
}; bool runBot = true;
future<void> bot;
void getColumns(const string _table, vector<string> &_columns, Connection *ptr_con); // privatno
bool open_one(Connection* con_ptr);
Connection* create_con();
bool disconnect_one(Connection* con_ptr);
Connection* shift_con();
public:
mySQL(const string _path, const string _username, const string _password, const string _db, const uint _available = 1);
bool disconnect();
void reconnectTrys(const uint _trys);
void exec(sqlQA &sql_qa);
~mySQL();
};
}
}
#endif #endif

@ -1,88 +1,192 @@
#include "../lib/mysql.hpp" #include "../lib/mysql.hpp"
sqlQA& sqlQA::select(const string _columns) {
if (_columns != "*") {
parse_columns(_columns);
}
isSelect = true;
cmd += "SELECT " + _columns + " ";
return *this;
}
sqlQA& sqlQA::from(const string _table) {
table = _table;
cmd += "FROM " + _table + " ";
return *this;
}
sqlQA& sqlQA::where(const string _condition) {
cmd += "WHERE " + _condition + " ";
return *this;
}
sqlQA& sqlQA::limit(const uint _limit) {
cmd += "LIMIT " + to_string(_limit) + " ";
return *this;
}
sqlQA& sqlQA::insertInTo(const string _tablename, const string _columns) {
isUpdate = true;
cmd += "INSERT INTO " + _tablename;
if (_columns.empty()) {
cmd += " ";
}
else {
cmd += " (" + _columns + ") ";
}
return *this;
}
sqlQA& sqlQA::values(const string _values) {
cmd += "VALUES (" + _values + ") ";
return *this;
}
sqlQA& sqlQA::update(const string _table) {
isUpdate = true;
cmd += "UPDATE " + _table + " ";
return *this;
}
sqlQA& sqlQA::set(const string _column_value_pairs) {
cmd += "SET " + _column_value_pairs + " ";
return *this;
}
sqlQA& sqlQA::deleteFrom(const string _table) {
isUpdate = true;
cmd += "DELETE FROM " + _table + " ";
return *this;
}
void sqlQA::print(bool withDetail) {
cout << "============================================" << endl;
marcelb::mysql::MySQL::MySQL(const string _path, const string _username, const string _password, const string _db, const uint32_t _available, const time_loop_type _engine_type) { for (auto i : result) {
for (auto j: i.second) {
cout << i.first << " : " << j << endl;
}
cout << "--------------------------------------------" << endl;
}
if (withDetail) {
cout << "-----------------DETAILS--------------------" << endl;
cout << "Is executed: " << (executed ? "true" : "false") << endl;
cout << "Update catch: " << updateCatch << endl;
cout << "Num of rows: " << num_rows << endl;
cout << "Num of columns: " << num_columns << endl;
}
cout << "============================================" << endl;
}
void sqlQA::parse_columns(const string _columns) {
istringstream iss(_columns);
string columnName;
while (getline(iss, columnName, ',')) {
size_t startPos = columnName.find_first_not_of(" ");
size_t endPos = columnName.find_last_not_of(" ");
if (startPos != string::npos && endPos != string::npos) {
columns.push_back(columnName.substr(startPos, endPos - startPos + 1));
}
}
}
mySQL::mySQL(const string _path, const string _username, const string _password, const string _db, const uint _available) {
path = _path; path = _path;
username = _username; username = _username;
password = _password; password = _password;
database = _db; db = _db;
pool_size = _available > 0 ? _available : 1; available = _available > 0 ? _available : 1;
tloop_type = _engine_type;
drv = get_mysql_driver_instance(); drv = get_mysql_driver_instance();
connect_pool();
if (tloop_type == time_loop_type::internal) { bot = async(launch::async, [&](){
tloop_future = async(launch::async, [&](){ while (runBot) {
while (run_tloop) { sleep(1);
usleep(MYSQL_PERIODIC_INTERNAL_TIME*1000); while (available>con.size() && runBot) {
_tloop(); try {
Connection* new_con_ptr = create_con();
if (!db.empty()) {
if (open_one(new_con_ptr)) {
throw string("[ERROR] Unable to open database " + db);
}
}
io.lock();
con.push_back(new_con_ptr);
io.unlock();
} catch (const SQLException except) {
cout << except.what() << endl;
} catch (const string except) {
cout << except << endl;
}
} }
return;
}); for (int i=0; i<con.size() && runBot; i++) {
} if (!con[i]->isValid()) {
// set on initialization to avoid the error io.lock();
last_loop_time = time(nullptr); con.erase(con.begin()+i);
io.unlock();
i--;
}
}
}
return;
});
} }
Connection* marcelb::mysql::MySQL::create_connection() { Connection* mySQL::create_con() {
uint32_t trys = 0; uint trys = 0;
bool status = true; bool status = true;
Connection* new_con = NULL; Connection* new_con = NULL;
while (connect_trys == unlimited ? status : (trys <= connect_trys && status)) { while (reconTrys == unlimited ? status : (trys <= reconTrys && status)) {
try { try {
Connection* con_can = drv->connect(path, username, password); Connection* con_can = drv->connect(path, username, password);
con_can->setSchema(database);
status = !con_can->isValid(); status = !con_can->isValid();
if (!status) { if (!status) {
new_con = con_can; new_con = con_can;
} }
else if (!con_can->isClosed()) { else if (!con_can->isClosed()) {
disconnect_connection(con_can); disconnect_one(con_can);
} }
} }
catch (const SQLException &error) { catch (const SQLException &error) {
if (on_error) { cout << error.what() << endl;
on_error(error.what() + string(", SQL state: ") + error.getSQLState() + string(", Error code: ") + to_string(error.getErrorCode()));
}
usleep(reconnectSleep); usleep(reconnectSleep);
connect_trys == unlimited ? trys : trys++; reconTrys == unlimited ? trys : trys++;
} }
} }
return new_con; return new_con;
} }
void marcelb::mysql::MySQL::connect_pool() { bool mySQL::disconnect() {
lock_guard<mutex> lock(io); io.lock();
for (uint32_t i=0; i<pool_size; i++) { bool status = true;
Connection* connection = create_connection();
connection_pool.push(connection);
}
}
void marcelb::mysql::MySQL::disconnect_pool() { for (uint i=0; i<con.size(); i++) {
lock_guard<mutex> lock(io); status = disconnect_one(con[i]) ;
for (uint32_t i=0; i<connection_pool.size(); i++) {
Connection* connection = connection_pool.front();
connection_pool.pop();
disconnect_connection(connection) ;
} }
io.unlock();
return status;
} }
bool marcelb::mysql::MySQL::disconnect_connection(Connection* connection) { bool mySQL::disconnect_one(Connection* con_ptr) {
bool status = !connection->isClosed(); bool status = !con_ptr->isClosed();
if (status) { if (status) {
try { try {
connection->close(); con_ptr->close();
status = !connection->isClosed(); status = !con_ptr->isClosed();
} }
catch (const SQLException &error) { catch (const SQLException &error) {
if (on_error) { cout << error.what() << endl;
on_error(error.what() + string(", SQL state: ") + error.getSQLState() + string(", Error code: ") + to_string(error.getErrorCode()));
}
status = true; status = true;
} }
} }
@ -91,77 +195,132 @@ bool marcelb::mysql::MySQL::disconnect_connection(Connection* connection) {
status = false; // već je zatvorena status = false; // već je zatvorena
} }
delete connection; delete con_ptr;
return status; return status;
} }
void marcelb::mysql::MySQL::_tloop() { bool mySQL::open_one(Connection* con_ptr) {
if (!run_tloop) { bool status = true; // ako true greška je
return; uint trys = 0;
}
lock_guard<mutex> lock(io); while (reconTrys == unlimited ? status : (trys <= reconTrys && status)) {
for (size_t i=0; i<connection_pool.size(); i++) {
try { try {
Connection *conn = connection_pool.front(); if (con_ptr->isValid()) {
connection_pool.pop(); con_ptr->setSchema(db);
if (conn->isValid()) { status = false;
connection_pool.push(conn);
} else {
if (!conn->isClosed()){
conn->close();
}
Connection *n_conn = create_connection();
release_connection(n_conn);
} }
} catch (const SQLException &error) { else {
if (on_error) { break;
on_error(error.what() + string(", SQL state: ") + error.getSQLState() + string(", Error code: ") + to_string(error.getErrorCode()));
} }
} }
catch (const SQLException &error) {
cout << error.what() << endl;
usleep(reconnectSleep);
reconTrys == unlimited ? trys : trys++;
}
} }
last_loop_time = time(nullptr); return status;
}
/**
* Broj pokušaja usljed povezivanja s bazom od 1 do unlimited;
*/
void mySQL::reconnectTrys(const uint _trys) {
io.lock();
reconTrys = _trys;
io.unlock();
} }
Connection* marcelb::mysql::MySQL::occupy_connection() {
if (last_loop_time + (MYSQL_PERIODIC_INTERNAL_TIME*3/1000) < time(nullptr)) { void mySQL::exec(sqlQA &sql_qa) {
if (on_error) { Connection* con_ptr = shift_con();
on_error("The time loop is not executing properly");
try {
vector<string> columns = sql_qa.columns;
if (columns.empty() && !sql_qa.table.empty()) {
getColumns(sql_qa.table, columns, con_ptr);
}
Statement *stmt;
stmt = con_ptr->createStatement();
if (sql_qa.isSelect) {
ResultSet *res = stmt->executeQuery(sql_qa.cmd);
sql_qa.executed = true;
uint num_raw_columns = 0;
while (res->next()) {
for (uint i=0; i<columns.size(); i++) {
sql_qa.result[columns[i]].push_back(res->getString(columns[i]));
num_raw_columns++;
}
}
res->close();
delete res;
sql_qa.num_columns = columns.size();
sql_qa.num_rows = num_raw_columns/columns.size();
}
if (sql_qa.isUpdate) {
sql_qa.updateCatch = stmt->executeUpdate(sql_qa.cmd);
sql_qa.executed = true;
}
else {
sql_qa.executed = stmt->execute(sql_qa.cmd);
} }
stmt->close();
delete stmt;
disconnect_one(con_ptr);
} }
unique_lock<mutex> lock(io); catch (const SQLException &error) {
while (connection_pool.empty()) { cout << error.what() << endl;
condition.wait(lock); sql_qa.executed = false;
}
catch (const string error) {
throw error;
} }
Connection *connection = connection_pool.front();
connection_pool.pop();
return connection;
}
void marcelb::mysql::MySQL::release_connection(Connection* connection) {
lock_guard<std::mutex> lock(io);
connection_pool.push(connection);
condition.notify_one();
} }
marcelb::mysql::MySQL::~MySQL() { void mySQL::getColumns(const string _table, vector<string> &_columns, Connection *ptr_con) {
if (tloop_type == time_loop_type::internal) { Statement *stmt;
run_tloop = false; stmt = ptr_con->createStatement();
tloop_future.get();
} else { ResultSet *columnsRes = stmt->executeQuery("SHOW COLUMNS from " + _table);
run_tloop = false;
while (columnsRes->next()) {
_columns.push_back(columnsRes->getString("Field"));
} }
disconnect_pool(); columnsRes->close();
stmt->close();
delete columnsRes;
delete stmt;
} }
Connection* mySQL::shift_con() {
void marcelb::mysql::MySQL::tloop() { while (true) {
if (tloop_type == time_loop_type::internal) { while(con.size()) {
if (on_error) { io.lock();
on_error("Can't start external call tloop, internal is active!"); Connection* con_ptr = con[0];
con.pop_front();
if (con_ptr->isValid()) {
io.unlock();
return con_ptr;
}
io.unlock();
} }
return; usleep(1000);
} }
_tloop(); }
mySQL::~mySQL() {
runBot = false;
bot.get();
disconnect();
} }

@ -1,165 +1,142 @@
#include <iostream> #include <iostream>
#include <thread> #include <thread>
#include <chrono> #include <chrono>
using namespace std;
using namespace chrono;
#include "../lib/mysql.hpp" #include "../lib/mysql.hpp"
using namespace marcelb::mysql;
#include "../../asynco/lib/asynco.hpp" using namespace std;
#include "../../asynco/lib/timers.hpp" using namespace chrono;
using namespace marcelb::asynco;
int main() { int main() {
try { try {
// MySQL mydb("tcp://192.168.2.10:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5, time_loop_type::internal); // mySQL mydb("tcp://192.168.2.10:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 1);
MySQL mydb("tcp://bitelex.ddns.net:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5, time_loop_type::external); mySQL mydb("tcp://192.168.2.10:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5);
// MySQL mydb("tcp://bitelex.ddns.net:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5);
mydb.on_error = [](const string& error) { // sleep(3600*10);
cout << error << endl; sleep(20);
};
periodic mysql_tloop ( [&mydb] () {
cout << "loop---------------------------" << endl;
mydb.tloop();
}, MYSQL_PERIODIC_INTERNAL_TIME);
while (true) {
sleep(5);
auto start = high_resolution_clock::now(); auto start = high_resolution_clock::now();
auto a1 = nonsync ( [&mydb] () {
try { // thread t1([&](){
auto response = mydb.exec<int,string>("SELECT id,domain FROM records WHERE enabled = 1;"); // try {
cout << response.affected << " " << response.have_result << endl; // sqlQA test_qa;
cout << response.rows << " " << response.columns << endl; // test_qa.select().from("records").where("enabled = 1");
// mydb.exec(test_qa);
for (auto row : response) { // test_qa.print(true);
cout << get<0>(row) << " " << get<1>(row) << endl; // } catch (const string err) {
} // cout << err << endl;
// }
for (auto column_name : response.columns_name) { // });
cout << column_name << endl;
} // // sleep(2);
} catch (const SQLException error) { // thread t2([&](){
cout << error.what() << endl; // try {
} // sqlQA test_qa;
}); // test_qa.select().from("zones");
// mydb.exec(test_qa);
auto a2 = nonsync ( [&mydb] () { // test_qa.print(true);
try { // } catch (const string err) {
auto response = mydb.exec<string,string>("SELECT zonename,auth_key FROM zones;"); // cout << err << endl;
cout << response.affected << " " << response.have_result << endl; // }
cout << response.rows << " " << response.columns << endl; // });
for (auto row : response) { // // sleep(3);
cout << get<0>(row) << " " << get<1>(row) << endl;
} // thread t3([&](){
// try {
for (auto column_name : response.columns_name) { // sqlQA test_qa;
cout << column_name << endl; // test_qa.select().from("users");
} // mydb.exec(test_qa);
// test_qa.print(true);
} catch (const SQLException error) { // } catch (const string err) {
cout << error.what() << endl; // cout << err << endl;
} // }
}); // });
auto a3 = nonsync ( [&mydb] () { // // sleep(1);
try {
auto response = mydb.exec<string,string>("SELECT username,email FROM users WHERE enabled = 1;"); // thread t4([&](){
cout << response.affected << " " << response.have_result << endl; // try {
cout << response.rows << " " << response.columns << endl; // sqlQA test_qa;
// test_qa.select().from("records").where("enabled = 1");
for (auto row : response) { // mydb.exec(test_qa);
cout << get<0>(row) << " " << get<1>(row) << endl; // test_qa.print(true);
} // } catch (const string err) {
// cout << err << endl;
for (auto column_name : response.columns_name) { // }
cout << column_name << endl; // });
}
// thread t5([&](){
} catch (const SQLException error) { // try {
cout << error.what() << endl; // sqlQA test_qa;
} // test_qa.select().from("zones");
}); // mydb.exec(test_qa);
// test_qa.print(true);
auto a4 = nonsync ( [&mydb] () { // } catch (const string err) {
try { // cout << err << endl;
auto response = mydb.exec<int,string>("SELECT id,domain FROM records WHERE enabled = 1;"); // }
cout << response.affected << " " << response.have_result << endl; // });
cout << response.rows << " " << response.columns << endl;
// thread t6([&](){
for (auto row : response) { // try {
cout << get<0>(row) << " " << get<1>(row) << endl; // sqlQA test_qa;
} // test_qa.select().from("users");
// mydb.exec(test_qa);
for (auto column_name : response.columns_name) { // test_qa.print(true);
cout << column_name << endl; // } catch (const string err) {
} // cout << err << endl;
// }
} catch (const SQLException error) { // });
cout << error.what() << endl;
} // t1.join();
}); // t2.join();
// t3.join();
auto a5 = nonsync ( [&mydb] () { // t4.join();
try { // t5.join();
auto response = mydb.exec<string,string>("SELECT zonename,auth_key FROM zones;"); // t6.join();
cout << response.affected << " " << response.have_result << endl;
cout << response.rows << " " << response.columns << endl; // one by one
try {
for (auto row : response) { sqlQA test_qa;
cout << get<0>(row) << " " << get<1>(row) << endl; test_qa.select().from("records").where("enabled = 1");
} mydb.exec(test_qa);
test_qa.print(true);
for (auto column_name : response.columns_name) { } catch (const string err) {
cout << column_name << endl; cout << err << endl;
} }
} catch (const SQLException error) { sleep(20);
cout << error.what() << endl;
} try {
}); sqlQA test_qa;
test_qa.select().from("users");
auto a6 = nonsync ( [&mydb] () { mydb.exec(test_qa);
try { test_qa.print(true);
auto response = mydb.exec<string,string>("SELECT username,email FROM users WHERE enabled = 1;"); } catch (const string err) {
cout << response.affected << " " << response.have_result << endl; cout << err << endl;
cout << response.rows << " " << response.columns << endl; }
for (auto row : response) { sleep(20);
cout << get<0>(row) << " " << get<1>(row) << endl;
} try {
sqlQA test_qa;
for (auto column_name : response.columns_name) { test_qa.select("zone_id,record_type,enabled").from("records").where("domain = 'bitelex.test'");
cout << column_name << endl; mydb.exec(test_qa);
} test_qa.print(true);
} catch (const string err) {
} catch (const SQLException error) { cout << err << endl;
cout << error.what() << endl; }
}
});
wait(a1);
wait(a2);
wait(a3);
wait(a4);
wait(a5);
wait(a6);
auto end = high_resolution_clock::now(); auto end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start); auto duration = duration_cast<microseconds>(end - start);
cout << "-------------Izvršilo se za: " << (double)(duration.count() / 1000.0) << " ms"<< endl; cout << "-------------Izvršilo se za: " << (double)(duration.count() / 1000.0) << " ms"<< endl;
// sleep(100);
}
sleep(100);
} catch (const SQLException error) { } catch (const SQLException error) {
cout << error.what() << endl; cout << error.what() << endl;
@ -169,8 +146,7 @@ while (true) {
cout << "Jebi ga" << endl; cout << "Jebi ga" << endl;
} }
// sleep(600); sleep(600);
_asynco_engine.run();
return 0; return 0;
} }

Binary file not shown.
Loading…
Cancel
Save