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