]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
4558e087a9a96d63f41a4f95109cd814079b8ad2
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlite3.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2009 Dennis Friis <peavey@inspircd.org>
6  *   Copyright (C) 2007, 2009 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *
9  * This file is part of InspIRCd.  InspIRCd is free software: you can
10  * redistribute it and/or modify it under the terms of the GNU General Public
11  * License as published by the Free Software Foundation, version 2.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16  * details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 /// $CompilerFlags: find_compiler_flags("sqlite3")
23 /// $LinkerFlags: find_linker_flags("sqlite3" "-lsqlite3")
24
25 /// $PackageInfo: require_system("centos") pkgconfig sqlite-devel
26 /// $PackageInfo: require_system("darwin") pkg-config sqlite3
27 /// $PackageInfo: require_system("debian") libsqlite3-dev pkg-config
28 /// $PackageInfo: require_system("ubuntu") libsqlite3-dev pkg-config
29
30 #include "inspircd.h"
31 #include "modules/sql.h"
32
33 // Fix warnings about the use of `long long` on C++03.
34 #if defined __clang__
35 # pragma clang diagnostic ignored "-Wc++11-long-long"
36 #elif defined __GNUC__
37 # pragma GCC diagnostic ignored "-Wlong-long"
38 #endif
39
40 #include <sqlite3.h>
41
42 #ifdef _WIN32
43 # pragma comment(lib, "sqlite3.lib")
44 #endif
45
46 class SQLConn;
47 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
48
49 class SQLite3Result : public SQL::Result
50 {
51  public:
52         int currentrow;
53         int rows;
54         std::vector<std::string> columns;
55         std::vector<SQL::Row> fieldlists;
56
57         SQLite3Result() : currentrow(0), rows(0)
58         {
59         }
60
61         int Rows() CXX11_OVERRIDE
62         {
63                 return rows;
64         }
65
66         bool GetRow(SQL::Row& result) CXX11_OVERRIDE
67         {
68                 if (currentrow < rows)
69                 {
70                         result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
71                         currentrow++;
72                         return true;
73                 }
74                 else
75                 {
76                         result.clear();
77                         return false;
78                 }
79         }
80
81         void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
82         {
83                 result.assign(columns.begin(), columns.end());
84         }
85
86         bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
87         {
88                 for (size_t i = 0; i < columns.size(); ++i)
89                 {
90                         if (columns[i] == column)
91                         {
92                                 index = i;
93                                 return true;
94                         }
95                 }
96                 return false;
97         }
98 };
99
100 class SQLConn : public SQL::Provider
101 {
102         sqlite3* conn;
103         reference<ConfigTag> config;
104
105  public:
106         SQLConn(Module* Parent, ConfigTag* tag) : SQL::Provider(Parent, "SQL/" + tag->getString("id")), config(tag)
107         {
108                 std::string host = tag->getString("hostname");
109                 if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK)
110                 {
111                         // Even in case of an error conn must be closed
112                         sqlite3_close(conn);
113                         conn = NULL;
114                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id"));
115                 }
116         }
117
118         ~SQLConn()
119         {
120                 if (conn)
121                 {
122                         sqlite3_interrupt(conn);
123                         sqlite3_close(conn);
124                 }
125         }
126
127         void Query(SQL::Query* query, const std::string& q)
128         {
129                 SQLite3Result res;
130                 sqlite3_stmt *stmt;
131                 int err = sqlite3_prepare_v2(conn, q.c_str(), q.length(), &stmt, NULL);
132                 if (err != SQLITE_OK)
133                 {
134                         SQL::Error error(SQL::QSEND_FAIL, sqlite3_errmsg(conn));
135                         query->OnError(error);
136                         return;
137                 }
138                 int cols = sqlite3_column_count(stmt);
139                 res.columns.resize(cols);
140                 for(int i=0; i < cols; i++)
141                 {
142                         res.columns[i] = sqlite3_column_name(stmt, i);
143                 }
144                 while (1)
145                 {
146                         err = sqlite3_step(stmt);
147                         if (err == SQLITE_ROW)
148                         {
149                                 // Add the row
150                                 res.fieldlists.resize(res.rows + 1);
151                                 res.fieldlists[res.rows].resize(cols);
152                                 for(int i=0; i < cols; i++)
153                                 {
154                                         const char* txt = (const char*)sqlite3_column_text(stmt, i);
155                                         if (txt)
156                                                 res.fieldlists[res.rows][i] = SQL::Field(txt);
157                                 }
158                                 res.rows++;
159                         }
160                         else if (err == SQLITE_DONE)
161                         {
162                                 query->OnResult(res);
163                                 break;
164                         }
165                         else
166                         {
167                                 SQL::Error error(SQL::QREPLY_FAIL, sqlite3_errmsg(conn));
168                                 query->OnError(error);
169                                 break;
170                         }
171                 }
172                 sqlite3_finalize(stmt);
173         }
174
175         void Submit(SQL::Query* query, const std::string& q) CXX11_OVERRIDE
176         {
177                 Query(query, q);
178                 delete query;
179         }
180
181         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
182         {
183                 std::string res;
184                 unsigned int param = 0;
185                 for(std::string::size_type i = 0; i < q.length(); i++)
186                 {
187                         if (q[i] != '?')
188                                 res.push_back(q[i]);
189                         else
190                         {
191                                 if (param < p.size())
192                                 {
193                                         char* escaped = sqlite3_mprintf("%q", p[param++].c_str());
194                                         res.append(escaped);
195                                         sqlite3_free(escaped);
196                                 }
197                         }
198                 }
199                 Submit(query, res);
200         }
201
202         void Submit(SQL::Query* query, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
203         {
204                 std::string res;
205                 for(std::string::size_type i = 0; i < q.length(); i++)
206                 {
207                         if (q[i] != '$')
208                                 res.push_back(q[i]);
209                         else
210                         {
211                                 std::string field;
212                                 i++;
213                                 while (i < q.length() && isalnum(q[i]))
214                                         field.push_back(q[i++]);
215                                 i--;
216
217                                 SQL::ParamMap::const_iterator it = p.find(field);
218                                 if (it != p.end())
219                                 {
220                                         char* escaped = sqlite3_mprintf("%q", it->second.c_str());
221                                         res.append(escaped);
222                                         sqlite3_free(escaped);
223                                 }
224                         }
225                 }
226                 Submit(query, res);
227         }
228 };
229
230 class ModuleSQLite3 : public Module
231 {
232         ConnMap conns;
233
234  public:
235         ~ModuleSQLite3()
236         {
237                 ClearConns();
238         }
239
240         void ClearConns()
241         {
242                 for(ConnMap::iterator i = conns.begin(); i != conns.end(); i++)
243                 {
244                         SQLConn* conn = i->second;
245                         ServerInstance->Modules->DelService(*conn);
246                         delete conn;
247                 }
248                 conns.clear();
249         }
250
251         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
252         {
253                 ClearConns();
254                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
255                 for(ConfigIter i = tags.first; i != tags.second; i++)
256                 {
257                         if (!stdalgo::string::equalsci(i->second->getString("module"), "sqlite"))
258                                 continue;
259                         SQLConn* conn = new SQLConn(this, i->second);
260                         conns.insert(std::make_pair(i->second->getString("id"), conn));
261                         ServerInstance->Modules->AddService(*conn);
262                 }
263         }
264
265         Version GetVersion() CXX11_OVERRIDE
266         {
267                 return Version("sqlite3 provider", VF_VENDOR);
268         }
269 };
270
271 MODULE_INIT(ModuleSQLite3)