source: trunk/FACT++/src/Database.h@ 20056

Last change on this file since 20056 was 20055, checked in by tbretz, 4 years ago
Allow to output interpreted connection information for debugging purposes.
File size: 2.5 KB
Line 
1#ifndef FACT_Database
2#define FACT_Database
3
4#include <exception>
5#include <boost/regex.hpp>
6#include <boost/algorithm/string.hpp>
7
8#include <mysql++/mysql++.h>
9
10#if !defined(__clang_major__) && defined(__GNUC__) && (__GNUC__ <= 4)
11#include "tools.h" // to_string fix for ISDC
12#endif
13
14struct DatabaseName
15{
16 std::string user;
17 std::string passwd;
18 std::string server;
19 std::string db;
20 int port;
21 char compression;
22
23 DatabaseName(const std::string &database, const bool &print=false) : compression(0)
24 {
25 if (database.empty())
26 return;
27
28 static const boost::regex expr("(([[:word:].-]+)(:(.+))?@)?([[:word:].-]+)(:([[:digit:]]+))?(/([[:word:].-]+))(\\?compress=[01])?");
29
30 boost::smatch what;
31 if (!boost::regex_match(database, what, expr, boost::match_extra))
32 throw std::runtime_error("Couldn't parse database URI '"+database+"'.");
33
34 if (what.size()!=11)
35 throw std::runtime_error("Error parsing database URI '"+database+"'.");
36
37 user = what[2];
38 passwd = what[4];
39 server = what[5];
40 db = what[9];
41
42 compression = std::string(what[10])[10];
43
44 try
45 {
46 port = stoi(std::string(what[7]));
47 }
48 catch (...)
49 {
50 port = 0;
51 }
52
53 if (print)
54 std::cerr << "URI=" << user << ":" << passwd << "@" << server << ":" << port << "/" << db << "?compress=" << uint16_t(compression) << std::endl;
55 }
56
57 std::string uri() const
58 {
59 std::string rc;
60 if (!user.empty())
61 rc += user+"@";
62 rc += server;
63 if (port)
64 rc += ":"+std::to_string(port);
65 if (!db.empty())
66 rc += "/"+db;
67 return rc;
68 }
69};
70
71class Database : public DatabaseName, public mysqlpp::Connection
72{
73public:
74 Database(const std::string &desc, const bool &print=false) : DatabaseName(desc, print),
75 mysqlpp::Connection()
76 {
77 if ((compression!='0' && boost::algorithm::to_lower_copy(server)!="localhost" && server!="127.0.0.1")||
78 compression=='1')
79 set_option(new mysqlpp::CompressOption());
80
81 //set_option(new mysqlpp::WriteTimeoutOption(3));
82 //set_option(new mysqlpp::ReadTimeoutOption(28800));
83 set_option(new mysqlpp::ReconnectOption(true));
84
85 // Connect to the database
86 if (!server.empty())
87 reconnect();
88 }
89
90 void reconnect()
91 {
92 connect(db.c_str(), server.c_str(), user.c_str(), passwd.c_str(), port);
93 }
94};
95
96#endif
Note: See TracBrowser for help on using the repository browser.