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