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