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

Last change on this file since 19232 was 19211, checked in by tbretz, 6 years ago
Fixed a typo in the pre-processor directive
File size: 2.0 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 static const boost::regex expr("(([[:word:].-]+)(:(.+))?@)?([[:word:].-]+)(:([[:digit:]]+))?(/([[:word:].-]+))(\\?compress=[01])?");
26
27 boost::smatch what;
28 if (!boost::regex_match(database, what, expr, boost::match_extra))
29 throw std::runtime_error("Couldn't parse database URI '"+database+"'.");
30
31 if (what.size()!=11)
32 throw std::runtime_error("Error parsing database URI '"+database+"'.");
33
34 user = what[2];
35 passwd = what[4];
36 server = what[5];
37 db = what[9];
38
39 compression = std::string(what[10])[10];
40
41 try
42 {
43 port = stoi(std::string(what[7]));
44 }
45 catch (...)
46 {
47 port = 0;
48 }
49 }
50
51 std::string uri() const
52 {
53 std::string rc;
54 if (!user.empty())
55 rc += user+"@";
56 rc += server;
57 if (port)
58 rc += ":"+std::to_string(port);
59 if (!db.empty())
60 rc += "/"+db;
61 return rc;
62 }
63};
64
65class Database : public DatabaseName, public mysqlpp::Connection
66{
67public:
68 Database(const std::string &desc) : DatabaseName(desc),
69 mysqlpp::Connection()
70 {
71 if ((compression!='0' && boost::algorithm::to_lower_copy(server)!="localhost" && server!="127.0.0.1")||
72 compression=='1')
73 set_option(new mysqlpp::CompressOption());
74
75 // Connect to the database
76 connect(db.c_str(), server.c_str(), user.c_str(), passwd.c_str(), port);
77 }
78};
79
80#endif
Note: See TracBrowser for help on using the repository browser.