summaryrefslogtreecommitdiff
path: root/src/modules/extra/m_sqlite3.cpp
blob: 4a0538bc8e3d4ad8d8f92836706c9cc6567547e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*		 +------------------------------------+
 *		 | Inspire Internet Relay Chat Daemon |
 *		 +------------------------------------+
 *
 *	InspIRCd: (C) 2002-2010 InspIRCd Development Team
 * See: http://wiki.inspircd.org/Credits
 *
 * This program is free but copyrighted software; see
 *			  the file COPYING for details.
 *
 * ---------------------------------------------------
 */

#include "inspircd.h"
#include <sqlite3.h>
#include "sql.h"

/* $ModDesc: sqlite3 provider */
/* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
/* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
/* $NoPedantic */

class SQLConn;
typedef std::map<std::string, reference<SQLConn> > ConnMap;

class SQLite3Result : public SQLResult
{
 public:
	int currentrow;
	int rows;
	std::vector<std::vector<std::string> > fieldlists;

	SQLite3Result() : currentrow(0), rows(0)
	{
	}

	~SQLite3Result()
	{
	}

	virtual int Rows()
	{
		return rows;
	}

	virtual bool GetRow(std::vector<std::string>& result)
	{
		if (currentrow < rows)
		{
			result.assign(fieldlists[currentrow].begin(), fieldlists[currentrow].end());
			currentrow++;
			return true;
		}
		else
		{
			result.clear();
			return false;
		}
	}
};

class SQLConn : public refcountbase
{
 private:
	sqlite3* conn;
	reference<ConfigTag> config;

 public:
	SQLConn(ConfigTag* tag) : config(tag)
	{
		std::string host = tag->getString("hostname");
		if (sqlite3_open_v2(host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0) != SQLITE_OK)
		{
			ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + tag->getString("id"));
			conn = NULL;
		}
	}

	~SQLConn()
	{
		sqlite3_interrupt(conn);
		sqlite3_close(conn);
	}

	void Query(SQLQuery* query)
	{
		SQLite3Result res;
		sqlite3_stmt *stmt;
		int err = sqlite3_prepare_v2(conn, query->query.c_str(), query->query.length(), &stmt, NULL);
		if (err != SQLITE_OK)
		{
			SQLerror error(SQL_QSEND_FAIL, sqlite3_errmsg(conn));
			query->OnError(error);
			return;
		}
		int cols = sqlite3_column_count(stmt);
		while (1)
		{
			err = sqlite3_step(stmt);
			if (err == SQLITE_ROW)
			{
				// Add the row
				res.fieldlists.resize(res.rows + 1);
				res.fieldlists[res.rows].resize(cols);
				for(int i=0; i < cols; i++)
				{
					const char* txt = (const char*)sqlite3_column_text(stmt, i);
					res.fieldlists[res.rows][i] = txt ? txt : "";
				}
				res.rows++;
			}
			else if (err == SQLITE_DONE)
			{
				query->OnResult(res);
				break;
			}
			else
			{
				SQLerror error(SQL_QREPLY_FAIL, sqlite3_errmsg(conn));
				query->OnError(error);
				break;
			}
		}
		sqlite3_finalize(stmt);
	}
};

class SQLiteProvider : public SQLProvider
{
 public:
	ConnMap hosts;

	SQLiteProvider(Module* Parent) : SQLProvider(Parent, "SQL/SQLite") {}

	std::string FormatQuery(std::string q, ParamL p)
	{
		std::string res;
		unsigned int param = 0;
		for(std::string::size_type i = 0; i < q.length(); i++)
		{
			if (q[i] != '?')
				res.push_back(q[i]);
			else
			{
				// TODO numbered parameter support ('?1')
				if (param < p.size())
				{
					char* escaped = sqlite3_mprintf("%q", p[param++].c_str());
					res.append(escaped);
					sqlite3_free(escaped);
				}
			}
		}
		return res;
	}

	std::string FormatQuery(std::string q, ParamM p)
	{
		std::string res;
		for(std::string::size_type i = 0; i < q.length(); i++)
		{
			if (q[i] != '$')
				res.push_back(q[i]);
			else
			{
				std::string field;
				i++;
				while (i < q.length() && isalpha(q[i]))
					field.push_back(q[i++]);
				i--;

				char* escaped = sqlite3_mprintf("%q", p[field].c_str());
				res.append(escaped);
				sqlite3_free(escaped);
			}
		}
		return res;
	}
	
	void submit(SQLQuery* query)
	{
		ConnMap::iterator iter = hosts.find(query->dbid);
		if (iter == hosts.end())
		{
			SQLerror err(SQL_BAD_DBID);
			query->OnError(err);
		}
		else
		{
			iter->second->Query(query);
		}
		delete query;
	}
};

class ModuleSQLite3 : public Module
{
 private:
	SQLiteProvider sqlserv;

 public:
	ModuleSQLite3()
	: sqlserv(this)
	{
	}

	void init()
	{
		ServerInstance->Modules->AddService(sqlserv);

		ReadConf();

		Implementation eventlist[] = { I_OnRehash };
		ServerInstance->Modules->Attach(eventlist, this, 1);
	}

	virtual ~ModuleSQLite3()
	{
	}

	void ReadConf()
	{
		sqlserv.hosts.clear();
		ConfigTagList tags = ServerInstance->Config->ConfTags("database");
		for(ConfigIter i = tags.first; i != tags.second; i++)
		{
			sqlserv.hosts.insert(std::make_pair(i->second->getString("id"), new SQLConn(i->second)));
		}
	}

	void OnRehash(User* user)
	{
		ReadConf();
	}

	Version GetVersion()
	{
		return Version("sqlite3 provider", VF_VENDOR);
	}
};

MODULE_INIT(ModuleSQLite3)