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