Separe sqlQA and mySQL lib, add namespace, commnets, license and readme file

generic v0.7
marcelb 10 months ago
parent 87088bdaa7
commit 6201fe0225
  1. 4
      .vscode/settings.json
  2. 73
      LICENSE
  3. 77
      README.md
  4. 90
      lib/mysql.hpp
  5. 119
      lib/sqlqa.hpp
  6. 113
      src/mysql.cpp
  7. 97
      src/sqlqa.cpp
  8. 2
      test/test.cpp
  9. BIN
      test/test.o

@ -16,6 +16,8 @@
"fstream": "cpp", "fstream": "cpp",
"new": "cpp", "new": "cpp",
"thread": "cpp", "thread": "cpp",
"chrono": "cpp" "chrono": "cpp",
"sstream": "cpp",
"map": "cpp"
} }
} }

@ -0,0 +1,73 @@
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 +1,76 @@
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: map, vector
- QA object
- Thread safe
- Exceptions
## 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
```c++
/**
* Init
*/
mySQL mydb("tcp://192.168.2.10:3306", "user_nm", "passss", "my_db", 5);
/**
* Use
*/
sqlQA test_qa;
// build qa
test_qa.select().from("records").where("enabled = 1");
try {
// execute
mydb.exec(test_qa);
// check is execute
if (test_qa.executed) {
// print
test_qa.print(true);
// access to first result of column id
cout << test_qa.result["id"][0] << endl;
// num of returned rows and columns
cout << test_qa.num_rows << " " << test_qa.num_columns << endl;
}
} catch (const string err) {
cout << err << endl;
}
```
## 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,16 +1,13 @@
#ifndef _MYSQL_ #ifndef _MYSQL_
#define _MYSQL_ #define _MYSQL_
#include <string>
#include <sstream>
#include <vector>
#include <deque> #include <deque>
#include <map>
#include <iostream>
#include <mutex> #include <mutex>
#include <thread> #include <thread>
#include <future> #include <future>
#include "sqlqa.hpp"
#include <mysql_driver.h> #include <mysql_driver.h>
#include <mysql_connection.h> #include <mysql_connection.h>
#include <cppconn/driver.h> #include <cppconn/driver.h>
@ -26,67 +23,78 @@ using namespace std;
using namespace sql; using namespace sql;
using namespace mysql; using namespace mysql;
class sqlQA { namespace marcelb {
public:
// query
string cmd;
string table;
vector<string> columns;
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 { class mySQL {
private:
mutex io; mutex io;
MySQL_Driver *drv; MySQL_Driver *drv;
deque<Connection*> con; deque<Connection*> con;
string path, username, password, db; string path, username, password, db;
uint available; uint available;
uint reconTrys = 3; uint reconTrys = 3;
bool runBot = true; bool runBot = true;
future<void> bot; future<void> bot;
/**
* Get column names for a table
*/
void getColumns(const string _table, vector<string> &_columns, Connection *ptr_con); // privatno void getColumns(const string _table, vector<string> &_columns, Connection *ptr_con); // privatno
/**
* Open one database
*/
bool open_one(Connection* con_ptr); bool open_one(Connection* con_ptr);
/**
* Open one database server connection
*/
Connection* create_con(); Connection* create_con();
/**
* Close one database connection
*/
bool disconnect_one(Connection* con_ptr); bool disconnect_one(Connection* con_ptr);
/**
* Take an available database connection
*/
Connection* shift_con(); Connection* shift_con();
public: public:
/**
* 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 uint _available = 1); mySQL(const string _path, const string _username, const string _password, const string _db, const uint _available = 1);
/**
* Disconnect all connections to server
*/
bool disconnect(); bool disconnect();
/**
* Define the maximum number of attempts to
* reconnect to the server
*/
void reconnectTrys(const uint _trys); void reconnectTrys(const uint _trys);
/**
* Execute SQLQA
*/
void exec(sqlQA &sql_qa); void exec(sqlQA &sql_qa);
/**
* Destruktor
* close all connections
*/
~mySQL(); ~mySQL();
}; };
}
#endif #endif

@ -0,0 +1,119 @@
#ifndef _SQLQA_
#define _SQLQA_
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
using namespace std;
namespace marcelb {
/**
* A class for creating sql queries and responses
*/
class sqlQA {
public:
// query variable list
// SQL Command
string cmd;
// Table name
string table;
// Columns name list
vector<string> columns;
// Query is update type
bool isUpdate = false;
// Query is select type
bool isSelect = false;
// answer
// Number of updates caught
uint updateCatch = 0;
// Executing status
bool executed = false;
// Answer
map<string, vector<string>> result;
// Number of returned rows
uint num_rows = 0;
// Number of returned columns
uint num_columns = 0;
// query methods
/**
* SELECT
* accept columns names, comma separated
* defualt *
*/
sqlQA& select(const string _select = "*");
/**
* FROM
* accept table name
*/
sqlQA& from(const string _tablename);
/**
* WHERE
* accept string sql condition
*/
sqlQA& where(const string _condition);
/**
* LIMIT
* set limit result
*/
sqlQA& limit(const uint _limit);
/**
* INSERT IN TO
* accept table name, and columns
*/
sqlQA& insertInTo(const string _tablename, const string _columns = "");
/**
* VALUES
* accept values
*/
sqlQA& values(const string _values);
/**
* UPDATE
* accept tablename for update query
*/
sqlQA& update(const string _tablename);
/**
* SET
* accept column and value pairs
*/
sqlQA& set(const string _column_value_pairs);
/**
* DELETE FROM
* accept table name
*/
sqlQA& deleteFrom(const string _table);
/**
* Print SQLQA
*/
void print(bool withDetail = false);
// intern methods
private:
/**
* Parse column names
*/
void parse_columns(const string _cloumns);
};
}
#endif

@ -1,100 +1,7 @@
#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;
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) { marcelb::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;
@ -139,7 +46,7 @@ mySQL::mySQL(const string _path, const string _username, const string _password,
} }
Connection* mySQL::create_con() { Connection* marcelb::mySQL::create_con() {
uint trys = 0; uint trys = 0;
bool status = true; bool status = true;
Connection* new_con = NULL; Connection* new_con = NULL;
@ -165,7 +72,7 @@ Connection* mySQL::create_con() {
return new_con; return new_con;
} }
bool mySQL::disconnect() { bool marcelb::mySQL::disconnect() {
io.lock(); io.lock();
bool status = true; bool status = true;
@ -177,7 +84,7 @@ bool mySQL::disconnect() {
return status; return status;
} }
bool mySQL::disconnect_one(Connection* con_ptr) { bool marcelb::mySQL::disconnect_one(Connection* con_ptr) {
bool status = !con_ptr->isClosed(); bool status = !con_ptr->isClosed();
if (status) { if (status) {
@ -199,7 +106,7 @@ bool mySQL::disconnect_one(Connection* con_ptr) {
return status; return status;
} }
bool mySQL::open_one(Connection* con_ptr) { bool marcelb::mySQL::open_one(Connection* con_ptr) {
bool status = true; // ako true greška je bool status = true; // ako true greška je
uint trys = 0; uint trys = 0;
@ -227,14 +134,14 @@ bool mySQL::open_one(Connection* con_ptr) {
* Broj pokušaja usljed povezivanja s bazom od 1 do unlimited; * Broj pokušaja usljed povezivanja s bazom od 1 do unlimited;
*/ */
void mySQL::reconnectTrys(const uint _trys) { void marcelb::mySQL::reconnectTrys(const uint _trys) {
io.lock(); io.lock();
reconTrys = _trys; reconTrys = _trys;
io.unlock(); io.unlock();
} }
void mySQL::exec(sqlQA &sql_qa) { void marcelb::mySQL::exec(sqlQA &sql_qa) {
Connection* con_ptr = shift_con(); Connection* con_ptr = shift_con();
try { try {
@ -287,7 +194,7 @@ void mySQL::exec(sqlQA &sql_qa) {
} }
void mySQL::getColumns(const string _table, vector<string> &_columns, Connection *ptr_con) { void marcelb::mySQL::getColumns(const string _table, vector<string> &_columns, Connection *ptr_con) {
Statement *stmt; Statement *stmt;
stmt = ptr_con->createStatement(); stmt = ptr_con->createStatement();
@ -303,7 +210,7 @@ void mySQL::getColumns(const string _table, vector<string> &_columns, Connection
delete stmt; delete stmt;
} }
Connection* mySQL::shift_con() { Connection* marcelb::mySQL::shift_con() {
while (true) { while (true) {
while(con.size()) { while(con.size()) {
io.lock(); io.lock();
@ -319,7 +226,7 @@ Connection* mySQL::shift_con() {
} }
} }
mySQL::~mySQL() { marcelb::mySQL::~mySQL() {
runBot = false; runBot = false;
bot.get(); bot.get();
disconnect(); disconnect();

@ -0,0 +1,97 @@
#include "../lib/sqlqa.hpp"
using namespace marcelb;
sqlQA& marcelb::sqlQA::select(const string _columns) {
if (_columns != "*") {
parse_columns(_columns);
}
isSelect = true;
cmd += "SELECT " + _columns + " ";
return *this;
}
sqlQA& marcelb::sqlQA::from(const string _table) {
table = _table;
cmd += "FROM " + _table + " ";
return *this;
}
sqlQA& marcelb::sqlQA::where(const string _condition) {
cmd += "WHERE " + _condition + " ";
return *this;
}
sqlQA& marcelb::sqlQA::limit(const uint _limit) {
cmd += "LIMIT " + to_string(_limit) + " ";
return *this;
}
sqlQA& marcelb::sqlQA::insertInTo(const string _tablename, const string _columns) {
isUpdate = true;
cmd += "INSERT INTO " + _tablename;
if (_columns.empty()) {
cmd += " ";
}
else {
cmd += " (" + _columns + ") ";
}
return *this;
}
sqlQA& marcelb::sqlQA::values(const string _values) {
cmd += "VALUES (" + _values + ") ";
return *this;
}
sqlQA& marcelb::sqlQA::update(const string _table) {
isUpdate = true;
cmd += "UPDATE " + _table + " ";
return *this;
}
sqlQA& marcelb::sqlQA::set(const string _column_value_pairs) {
cmd += "SET " + _column_value_pairs + " ";
return *this;
}
sqlQA& marcelb::sqlQA::deleteFrom(const string _table) {
isUpdate = true;
cmd += "DELETE FROM " + _table + " ";
return *this;
}
void marcelb::sqlQA::print(bool withDetail) {
cout << "============================================" << endl;
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 marcelb::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));
}
}
}

@ -6,6 +6,7 @@
using namespace std; using namespace std;
using namespace chrono; using namespace chrono;
using namespace marcelb;
int main() { int main() {
try { try {
@ -13,7 +14,6 @@ int main() {
mySQL mydb("tcp://192.168.2.10:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5); mySQL mydb("tcp://192.168.2.10:3306", "dinio", "H€r5elfInd1aH@nds", "dinio", 5);
// sleep(3600*10); // sleep(3600*10);
sleep(20);
auto start = high_resolution_clock::now(); auto start = high_resolution_clock::now();

Binary file not shown.
Loading…
Cancel
Save