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

Last change on this file since 19779 was 19435, checked in by tbretz, 6 years ago
Allow to create a pending connection and call reconnect instead.
File size: 2.2 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) : 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
54 std::string uri() const
55 {
56 std::string rc;
57 if (!user.empty())
58 rc += user+"@";
59 rc += server;
60 if (port)
61 rc += ":"+std::to_string(port);
62 if (!db.empty())
63 rc += "/"+db;
64 return rc;
65 }
66};
67
68class Database : public DatabaseName, public mysqlpp::Connection
69{
70public:
71 Database(const std::string &desc) : DatabaseName(desc),
72 mysqlpp::Connection()
73 {
74 if ((compression!='0' && boost::algorithm::to_lower_copy(server)!="localhost" && server!="127.0.0.1")||
75 compression=='1')
76 set_option(new mysqlpp::CompressOption());
77
78 set_option(new mysqlpp::ReconnectOption(true));
79
80 // Connect to the database
81 if (!server.empty())
82 reconnect();
83 }
84
85 void reconnect()
86 {
87 connect(db.c_str(), server.c_str(), user.c_str(), passwd.c_str(), port);
88 }
89};
90
91#endif
Note: See TracBrowser for help on using the repository browser.