1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2010 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
18 /* $ModDesc: sqlite3 provider */
19 /* $CompileFlags: pkgconfversion("sqlite3","3.3") pkgconfincludes("sqlite3","/sqlite3.h","") */
20 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
21 /* $ModDep: m_sqlv2.h */
30 typedef std::map<std::string, SQLConn*> ConnMap;
31 typedef std::deque<classbase*> paramlist;
32 typedef std::deque<SQLite3Result*> ResultQueue;
34 static unsigned long count(const char * const str, char a)
37 for (const char *p = str; *p; ++p)
45 class SQLite3Result : public SQLresult
52 std::vector<std::string> colnames;
53 std::vector<SQLfieldList> fieldlists;
54 SQLfieldList emptyfieldlist;
56 SQLfieldList* fieldlist;
57 SQLfieldMap* fieldmap;
60 SQLite3Result(Module* self, Module* to, unsigned int rid)
61 : SQLresult(self, to, rid), currentrow(0), rows(0), cols(0), fieldlist(NULL), fieldmap(NULL)
69 void AddRow(int colsnum, char **dat, char **colname)
73 for (int i = 0; i < colsnum; i++)
75 fieldlists.resize(fieldlists.size()+1);
76 colnames.push_back(colname[i]);
77 SQLfield sf(dat[i] ? dat[i] : "", dat[i] ? false : true);
78 fieldlists[rows].push_back(sf);
83 void UpdateAffectedCount()
98 virtual std::string ColName(int column)
100 if (column < (int)colnames.size())
102 return colnames[column];
106 throw SQLbadColName();
111 virtual int ColNum(const std::string &column)
113 for (unsigned int i = 0; i < colnames.size(); i++)
115 if (column == colnames[i])
118 throw SQLbadColName();
122 virtual SQLfield GetValue(int row, int column)
124 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
126 return fieldlists[row][column];
129 throw SQLbadColName();
131 /* XXX: We never actually get here because of the throw */
132 return SQLfield("",true);
135 virtual SQLfieldList& GetRow()
137 if (currentrow < rows)
138 return fieldlists[currentrow];
140 return emptyfieldlist;
143 virtual SQLfieldMap& GetRowMap()
145 /* In an effort to reduce overhead we don't actually allocate the map
146 * until the first time it's needed...so...
154 fieldmap = new SQLfieldMap;
157 if (currentrow < rows)
159 for (int i = 0; i < Cols(); i++)
161 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
169 virtual SQLfieldList* GetRowPtr()
171 fieldlist = new SQLfieldList();
173 if (currentrow < rows)
175 for (int i = 0; i < Rows(); i++)
177 fieldlist->push_back(fieldlists[currentrow][i]);
184 virtual SQLfieldMap* GetRowMapPtr()
186 fieldmap = new SQLfieldMap();
188 if (currentrow < rows)
190 for (int i = 0; i < Cols(); i++)
192 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
200 virtual void Free(SQLfieldMap* fm)
205 virtual void Free(SQLfieldList* fl)
213 class SQLConn : public classbase
222 SQLConn(Module* m, const SQLhost& hi)
225 if (OpenDB() != SQLITE_OK)
227 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: Could not open DB with id: " + host.id);
237 SQLerror Query(SQLrequest &req)
239 /* Pointer to the buffer we screw around with substitution in */
242 /* Pointer to the current end of query, where we append new stuff */
245 /* Total length of the unescaped parameters */
246 unsigned long maxparamlen, paramcount;
248 /* The length of the longest parameter */
251 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
253 if (i->size() > maxparamlen)
254 maxparamlen = i->size();
257 /* How many params are there in the query? */
258 paramcount = count(req.query.q.c_str(), '?');
260 /* This stores copy of params to be inserted with using numbered params 1;3B*/
261 ParamL paramscopy(req.query.p);
263 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
264 * sizeofquery + (maxtotalparamlength*2) + 1
266 * The +1 is for null-terminating the string
269 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
272 for(unsigned long i = 0; i < req.query.q.length(); i++)
274 if(req.query.q[i] == '?')
276 /* We found a place to substitute..what fun.
277 * use sqlite calls to escape and write the
278 * escaped string onto the end of our query buffer,
279 * then we "just" need to make sure queryend is
280 * pointing at the right place.
283 /* Is it numbered parameter?
289 /* Numbered parameter number :|
291 unsigned int paramnum;
294 /* Let's check if it's a numbered param. And also calculate it's number.
297 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
301 paramnum = paramnum * 10 + req.query.q[i] - '0';
304 if (paramnum > paramscopy.size() - 1)
306 /* index is out of range!
315 escaped = sqlite3_mprintf("%q", paramscopy[paramnum].c_str());
316 for (char* n = escaped; *n; n++)
321 sqlite3_free(escaped);
323 else if (req.query.p.size())
326 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
327 for (char* n = escaped; *n; n++)
332 sqlite3_free(escaped);
333 req.query.p.pop_front();
340 *queryend = req.query.q[i];
347 SQLite3Result* res = new SQLite3Result(mod, req.source, req.id);
349 res->query = req.query.q;
351 params.push_back(this);
352 params.push_back(res);
355 sqlite3_update_hook(conn, QueryUpdateHook, ¶ms);
356 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
358 std::string error(errmsg);
359 sqlite3_free(errmsg);
362 return SQLerror(SQL_QSEND_FAIL, error);
366 results.push_back(res);
371 static int QueryResult(void *params, int argc, char **argv, char **azColName)
373 paramlist* p = (paramlist*)params;
374 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
378 static void QueryUpdateHook(void *params, int eventid, char const * azSQLite, char const * azColName, sqlite_int64 rowid)
380 paramlist* p = (paramlist*)params;
381 ((SQLConn*)(*p)[0])->AffectedReady(((SQLite3Result*)(*p)[1]));
384 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
386 res->AddRow(cols, data, colnames);
389 void AffectedReady(SQLite3Result *res)
391 res->UpdateAffectedCount();
396 return sqlite3_open_v2(host.host.c_str(), &conn, SQLITE_OPEN_READWRITE, 0);
401 sqlite3_interrupt(conn);
405 SQLhost GetConfHost()
412 while (results.size())
414 SQLite3Result* res = results[0];
421 /* If the client module is unloaded partway through a query then the provider will set
422 * the pointer to NULL. We cannot just cancel the query as the result will still come
423 * through at some point...and it could get messy if we play with invalid pointers...
433 while (results.size())
435 SQLite3Result* res = results[0];
444 class ModuleSQLite3 : public Module
448 unsigned long currid;
449 ServiceProvider sqlserv;
453 : currid(0), sqlserv(this, "SQL/sqlite", SERVICE_DATA)
458 Implementation eventlist[] = { I_OnRehash };
459 ServerInstance->Modules->Attach(eventlist, this, 1);
462 virtual ~ModuleSQLite3()
465 ClearAllConnections();
470 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
472 iter->second->ClearResults();
476 bool HasHost(const SQLhost &host)
478 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
480 if (host == iter->second->GetConfHost())
486 bool HostInConf(const SQLhost &h)
489 for(int i = 0; i < conf.Enumerate("database"); i++)
492 host.id = conf.ReadValue("database", "id", i);
493 host.host = conf.ReadValue("database", "hostname", i);
494 host.port = conf.ReadInteger("database", "port", i, true);
495 host.name = conf.ReadValue("database", "name", i);
496 host.user = conf.ReadValue("database", "username", i);
497 host.pass = conf.ReadValue("database", "password", i);
506 ClearOldConnections();
509 for(int i = 0; i < conf.Enumerate("database"); i++)
513 host.id = conf.ReadValue("database", "id", i);
514 host.host = conf.ReadValue("database", "hostname", i);
515 host.port = conf.ReadInteger("database", "port", i, true);
516 host.name = conf.ReadValue("database", "name", i);
517 host.user = conf.ReadValue("database", "username", i);
518 host.pass = conf.ReadValue("database", "password", i);
527 void AddConn(const SQLhost& hi)
531 ServerInstance->Logs->Log("m_sqlite3",DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
537 newconn = new SQLConn(this, hi);
539 connections.insert(std::make_pair(hi.id, newconn));
542 void ClearOldConnections()
544 ConnMap::iterator iter,safei;
545 for (iter = connections.begin(); iter != connections.end(); iter++)
547 if (!HostInConf(iter->second->GetConfHost()))
552 connections.erase(safei);
557 void ClearAllConnections()
560 while ((i = connections.begin()) != connections.end())
562 connections.erase(i);
567 virtual void OnRehash(User* user)
572 void OnRequest(Request& request)
574 if(strcmp(SQLREQID, request.id) == 0)
576 SQLrequest* req = (SQLrequest*)&request;
577 ConnMap::iterator iter;
578 if((iter = connections.find(req->dbid)) != connections.end())
581 req->error = iter->second->Query(*req);
585 req->error.Id(SQL_BAD_DBID);
590 unsigned long NewID()
598 virtual Version GetVersion()
600 return Version("sqlite3 provider", VF_VENDOR);
605 MODULE_INIT(ModuleSQLite3)