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