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 | struct DatabaseName
|
---|
11 | {
|
---|
12 | std::string user;
|
---|
13 | std::string passwd;
|
---|
14 | std::string server;
|
---|
15 | std::string db;
|
---|
16 | int port;
|
---|
17 | char compression;
|
---|
18 |
|
---|
19 | DatabaseName(const std::string &database) : compression(0)
|
---|
20 | {
|
---|
21 | static const boost::regex expr("(([[:word:].-]+)(:(.+))?@)?([[:word:].-]+)(:([[:digit:]]+))?(/([[:word:].-]+))(/[+-])?");
|
---|
22 |
|
---|
23 | boost::smatch what;
|
---|
24 | if (!boost::regex_match(database, what, expr, boost::match_extra))
|
---|
25 | throw std::runtime_error("Couldn't parse database URI '"+database+"'.");
|
---|
26 |
|
---|
27 | if (what.size()!=11)
|
---|
28 | throw std::runtime_error("Error parsing database URI '"+database+"'.");
|
---|
29 |
|
---|
30 | user = what[2];
|
---|
31 | passwd = what[4];
|
---|
32 | server = what[5];
|
---|
33 | db = what[9];
|
---|
34 |
|
---|
35 | compression = std::string(what[10])[1];
|
---|
36 |
|
---|
37 | try
|
---|
38 | {
|
---|
39 | port = stoi(std::string(what[7]));
|
---|
40 | }
|
---|
41 | catch (...)
|
---|
42 | {
|
---|
43 | port = 0;
|
---|
44 | }
|
---|
45 | }
|
---|
46 |
|
---|
47 | std::string uri() const
|
---|
48 | {
|
---|
49 | std::string rc;
|
---|
50 | if (!user.empty())
|
---|
51 | rc += user+"@";
|
---|
52 | rc += server;
|
---|
53 | if (port)
|
---|
54 | rc += ":"+std::to_string(port);
|
---|
55 | if (!db.empty())
|
---|
56 | rc += "/"+db;
|
---|
57 | return rc;
|
---|
58 | }
|
---|
59 | };
|
---|
60 |
|
---|
61 | class Database : public DatabaseName, public mysqlpp::Connection
|
---|
62 | {
|
---|
63 | public:
|
---|
64 | Database(const std::string &desc) : DatabaseName(desc),
|
---|
65 | mysqlpp::Connection()
|
---|
66 | {
|
---|
67 | if ((compression!='-' && boost::algorithm::to_lower_copy(server)!="localhost" && server!="127.0.0.1")||
|
---|
68 | compression=='+')
|
---|
69 | set_option(new mysqlpp::CompressOption());
|
---|
70 |
|
---|
71 | // Connect to the database
|
---|
72 | connect(db.c_str(), server.c_str(), user.c_str(), passwd.c_str(), port);
|
---|
73 | }
|
---|
74 | };
|
---|
75 |
|
---|
76 | #endif
|
---|
Note:
See
TracBrowser
for help on using the repository browser.