]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlite3.cpp
Merge pull request #1219 from SaberUK/master+directive
[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("darwin") pkg-config sqlite3
26 /// $PackageInfo: require_system("ubuntu") libsqlite3-dev pkg-config
27
28 #include "inspircd.h"
29 #include "modules/sql.h"
30
31 // Fix warnings about the use of `long long` on C++03.
32 #if defined __clang__
33 # pragma clang diagnostic ignored "-Wc++11-long-long"
34 #elif defined __GNUC__
35 # pragma GCC diagnostic ignored "-Wlong-long"
36 #endif
37
38 #include <sqlite3.h>
39
40 #ifdef _WIN32
41 # pragma comment(lib, "sqlite3.lib")
42 #endif
43
44 class SQLConn;
45 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
46
47 class SQLite3Result : public SQLResult
48 {
49  public:
50         int currentrow;
51         int rows;
52         std::vector<std::string> columns;
53         std::vector<SQLEntries> fieldlists;
54
55         SQLite3Result() : currentrow(0), rows(0)
56         {
57         }
58
59         int Rows()
60         {
61                 return rows;
62         }
63
64         bool GetRow(SQLEntries& result)
65         {
66                 if (currentrow < rows)
67                 {
68                         result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
69                         currentrow++;
70                         return true;
71                 }
72                 else
73                 {
74                         result.clear();
75                         return false;
76                 }
77         }
78
79         void GetCols(std::vector<std::string>& result)
80         {
81                 result.assign(columns.begin(), columns.end());
82         }
83 };
84
85 class SQLConn : public SQLProvider
86 {
87         sqlite3* conn;
88         reference<ConfigTag> config;
89
90  public:
91         SQLConn(Module* Parent, ConfigTag* tag) : SQLProvider(Parent, "SQL/" + tag->getString("id")), config(tag)
92         {
93                 std::string host = tag->getString("hostname");
94                 if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK)
95                 {
96                         // Even in case of an error conn must be closed
97                         sqlite3_close(conn);
98                         conn = NULL;
99                         ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id"));
100                 }
101         }
102
103         ~SQLConn()
104         {
105                 if (conn)
106                 {
107                         sqlite3_interrupt(conn);
108                         sqlite3_close(conn);
109                 }
110         }
111
112         void Query(SQLQuery* query, const std::string& q)
113         {
114                 SQLite3Result res;
115                 sqlite3_stmt *stmt;
116                 int err = sqlite3_prepare_v2(conn, q.c_str(), q.length(), &stmt, NULL);
117                 if (err != SQLITE_OK)
118                 {
119                         SQLerror error(SQL_QSEND_FAIL, sqlite3_errmsg(conn));
120                         query->OnError(error);
121                         return;
122                 }
123                 int cols = sqlite3_column_count(stmt);
124                 res.columns.resize(cols);
125                 for(int i=0; i < cols; i++)
126                 {
127                         res.columns[i] = sqlite3_column_name(stmt, i);
128                 }
129                 while (1)
130                 {
131                         err = sqlite3_step(stmt);
132                         if (err == SQLITE_ROW)
133                         {
134                                 // Add the row
135                                 res.fieldlists.resize(res.rows + 1);
136                                 res.fieldlists[res.rows].resize(cols);
137                                 for(int i=0; i < cols; i++)
138                                 {
139                                         const char* txt = (const char*)sqlite3_column_text(stmt, i);
140                                         if (txt)
141                                                 res.fieldlists[res.rows][i] = SQLEntry(txt);
142                                 }
143                                 res.rows++;
144                         }
145                         else if (err == SQLITE_DONE)
146                         {
147                                 query->OnResult(res);
148                                 break;
149                         }
150                         else
151                         {
152                                 SQLerror error(SQL_QREPLY_FAIL, sqlite3_errmsg(conn));
153                                 query->OnError(error);
154                                 break;
155                         }
156                 }
157                 sqlite3_finalize(stmt);
158         }
159
160         void submit(SQLQuery* query, const std::string& q)
161         {
162                 Query(query, q);
163                 delete query;
164         }
165
166         void submit(SQLQuery* query, const std::string& q, const ParamL& p)
167         {
168                 std::string res;
169                 unsigned int param = 0;
170                 for(std::string::size_type i = 0; i < q.length(); i++)
171                 {
172                         if (q[i] != '?')
173                                 res.push_back(q[i]);
174                         else
175                         {
176                                 if (param < p.size())
177                                 {
178                                         char* escaped = sqlite3_mprintf("%q", p[param++].c_str());
179                                         res.append(escaped);
180                                         sqlite3_free(escaped);
181                                 }
182                         }
183                 }
184                 submit(query, res);
185         }
186
187         void submit(SQLQuery* query, const std::string& q, const ParamM& p)
188         {
189                 std::string res;
190                 for(std::string::size_type i = 0; i < q.length(); i++)
191                 {
192                         if (q[i] != '$')
193                                 res.push_back(q[i]);
194                         else
195                         {
196                                 std::string field;
197                                 i++;
198                                 while (i < q.length() && isalnum(q[i]))
199                                         field.push_back(q[i++]);
200                                 i--;
201
202                                 ParamM::const_iterator it = p.find(field);
203                                 if (it != p.end())
204                                 {
205                                         char* escaped = sqlite3_mprintf("%q", it->second.c_str());
206                                         res.append(escaped);
207                                         sqlite3_free(escaped);
208                                 }
209                         }
210                 }
211                 submit(query, res);
212         }
213 };
214
215 class ModuleSQLite3 : public Module
216 {
217         ConnMap conns;
218
219  public:
220         ~ModuleSQLite3()
221         {
222                 ClearConns();
223         }
224
225         void ClearConns()
226         {
227                 for(ConnMap::iterator i = conns.begin(); i != conns.end(); i++)
228                 {
229                         SQLConn* conn = i->second;
230                         ServerInstance->Modules->DelService(*conn);
231                         delete conn;
232                 }
233                 conns.clear();
234         }
235
236         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
237         {
238                 ClearConns();
239                 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
240                 for(ConfigIter i = tags.first; i != tags.second; i++)
241                 {
242                         if (i->second->getString("module", "sqlite") != "sqlite")
243                                 continue;
244                         SQLConn* conn = new SQLConn(this, i->second);
245                         conns.insert(std::make_pair(i->second->getString("id"), conn));
246                         ServerInstance->Modules->AddService(*conn);
247                 }
248         }
249
250         Version GetVersion() CXX11_OVERRIDE
251         {
252                 return Version("sqlite3 provider", VF_VENDOR);
253         }
254 };
255
256 MODULE_INIT(ModuleSQLite3)