1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
23 #include "configreader.h"
27 /* $ModDesc: sqlite3 provider */
28 /* $CompileFlags: pkgconfincludes("sqlite3","/sqlite3.h","") */
29 /* $LinkerFlags: pkgconflibs("sqlite3","/libsqlite3.so","-lsqlite3") */
30 /* $ModDep: m_sqlv2.h */
36 typedef std::map<std::string, SQLConn*> ConnMap;
37 typedef std::deque<classbase*> paramlist;
38 typedef std::deque<SQLite3Result*> ResultQueue;
40 class SQLite3Result : public SQLresult
47 std::vector<std::string> colnames;
48 std::vector<SQLfieldList> fieldlists;
49 SQLfieldList emptyfieldlist;
51 SQLfieldList* fieldlist;
52 SQLfieldMap* fieldmap;
55 SQLite3Result(Module* self, Module* to, unsigned int id)
56 : SQLresult(self, to, id), currentrow(0), rows(0), cols(0)
64 void AddRow(int colsnum, char **data, char **colname)
68 for (int i = 0; i < colsnum; i++)
70 fieldlists.resize(fieldlists.size()+1);
71 colnames.push_back(colname[i]);
72 SQLfield sf(data[i] ? data[i] : "", data[i] ? false : true);
73 fieldlists[rows].push_back(sf);
\r
88 virtual std::string ColName(int column)
90 if (column < (int)colnames.size())
92 return colnames[column];
96 throw SQLbadColName();
101 virtual int ColNum(const std::string &column)
103 for (unsigned int i = 0; i < colnames.size(); i++)
105 if (column == colnames[i])
108 throw SQLbadColName();
112 virtual SQLfield GetValue(int row, int column)
114 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
116 return fieldlists[row][column];
119 throw SQLbadColName();
121 /* XXX: We never actually get here because of the throw */
122 return SQLfield("",true);
125 virtual SQLfieldList& GetRow()
127 if (currentrow < rows)
128 return fieldlists[currentrow];
130 return emptyfieldlist;
133 virtual SQLfieldMap& GetRowMap()
135 /* In an effort to reduce overhead we don't actually allocate the map
136 * until the first time it's needed...so...
144 fieldmap = new SQLfieldMap;
147 if (currentrow < rows)
149 for (int i = 0; i < Cols(); i++)
151 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
159 virtual SQLfieldList* GetRowPtr()
161 fieldlist = new SQLfieldList();
163 if (currentrow < rows)
165 for (int i = 0; i < Rows(); i++)
167 fieldlist->push_back(fieldlists[currentrow][i]);
174 virtual SQLfieldMap* GetRowMapPtr()
176 fieldmap = new SQLfieldMap();
178 if (currentrow < rows)
180 for (int i = 0; i < Cols(); i++)
182 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
190 virtual void Free(SQLfieldMap* fm)
195 virtual void Free(SQLfieldList* fl)
203 class SQLConn : public classbase
213 SQLConn(InspIRCd* SI, Module* m, const SQLhost& hi)
214 : Instance(SI), mod(m), host(hi)
217 if ((result = OpenDB()) == SQLITE_OK)
219 Instance->Log(DEBUG, "Opened sqlite DB: " + host.host);
223 Instance->Log(DEFAULT, "WARNING: Could not open DB with id: " + host.id);
228 SQLerror Query(SQLrequest &req)
230 /* Pointer to the buffer we screw around with substitution in */
233 /* Pointer to the current end of query, where we append new stuff */
236 /* Total length of the unescaped parameters */
237 unsigned long paramlen;
239 /* Total length of query, used for binary-safety in mysql_real_query */
240 unsigned long querylength = 0;
243 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
245 paramlen += i->size();
248 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
249 * sizeofquery + (totalparamlength*2) + 1
251 * The +1 is for null-terminating the string for mysql_real_escape_string
254 query = new char[req.query.q.length() + (paramlen*2) + 1];
257 for(unsigned long i = 0; i < req.query.q.length(); i++)
259 if(req.query.q[i] == '?')
261 if(req.query.p.size())
264 escaped = sqlite3_mprintf("%q", req.query.p.front().c_str());
265 for (char* n = escaped; *n; n++)
270 sqlite3_free(escaped);
271 req.query.p.pop_front();
278 *queryend = req.query.q[i];
286 // Instance->Log(DEBUG, "<******> Doing query: " + ConvToStr(req.query.q.data()));
288 SQLite3Result* res = new SQLite3Result(mod, req.GetSource(), req.id);
289 res->query = req.query.q;
291 params.push_back(this);
292 params.push_back(res);
295 if (sqlite3_exec(conn, req.query.q.data(), QueryResult, ¶ms, &errmsg) != SQLITE_OK)
297 Instance->Log(DEBUG, "Query failed: " + ConvToStr(errmsg));
298 sqlite3_free(errmsg);
301 return SQLerror(QSEND_FAIL, ConvToStr(errmsg));
303 Instance->Log(DEBUG, "Dispatched query successfully. ID: %d resulting rows %d", req.id, res->Rows());
306 results.push_back(res);
311 static int QueryResult(void *params, int argc, char **argv, char **azColName)
313 paramlist* p = (paramlist*)params;
314 ((SQLConn*)(*p)[0])->ResultReady(((SQLite3Result*)(*p)[1]), argc, argv, azColName);
318 void ResultReady(SQLite3Result *res, int cols, char **data, char **colnames)
320 res->AddRow(cols, data, colnames);
323 void QueryDone(SQLrequest* req, int rows)
325 SQLite3Result* r = new SQLite3Result(mod, req->GetSource(), req->id);
327 r->query = req->query.q;
332 return sqlite3_open(host.host.c_str(), &conn);
337 sqlite3_interrupt(conn);
341 SQLhost GetConfHost()
350 SQLite3Result* res = results[0];
357 /* If the client module is unloaded partway through a query then the provider will set
358 * the pointer to NULL. We cannot just cancel the query as the result will still come
359 * through at some point...and it could get messy if we play with invalid pointers...
361 Instance->Log(DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: " + ConvToStr(res->GetId()));
371 class ModuleSQLite3 : public Module
375 unsigned long currid;
378 ModuleSQLite3(InspIRCd* Me)
379 : Module::Module(Me), currid(0)
381 ServerInstance->UseInterface("SQLutils");
383 if (!ServerInstance->PublishFeature("SQL", this))
385 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
390 ServerInstance->PublishInterface("SQL", this);
393 virtual ~ModuleSQLite3()
395 ServerInstance->UnpublishInterface("SQL", this);
396 ServerInstance->UnpublishFeature("SQL");
397 ServerInstance->DoneWithInterface("SQLutils");
400 void Implements(char* List)
402 List[I_OnRequest] = 1;
405 bool HasHost(const SQLhost &host)
407 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
409 if (host == iter->second->GetConfHost())
415 bool HostInConf(const SQLhost &h)
417 ConfigReader conf(ServerInstance);
418 for(int i = 0; i < conf.Enumerate("database"); i++)
421 host.id = conf.ReadValue("database", "id", i);
422 host.host = conf.ReadValue("database", "hostname", i);
423 host.port = conf.ReadInteger("database", "port", i, true);
424 host.name = conf.ReadValue("database", "name", i);
425 host.user = conf.ReadValue("database", "username", i);
426 host.pass = conf.ReadValue("database", "password", i);
427 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
436 //ClearOldConnections();
438 ConfigReader conf(ServerInstance);
439 for(int i = 0; i < conf.Enumerate("database"); i++)
443 host.id = conf.ReadValue("database", "id", i);
444 host.host = conf.ReadValue("database", "hostname", i);
445 host.port = conf.ReadInteger("database", "port", i, true);
446 host.name = conf.ReadValue("database", "name", i);
447 host.user = conf.ReadValue("database", "username", i);
448 host.pass = conf.ReadValue("database", "password", i);
449 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
458 void AddConn(const SQLhost& hi)
462 ServerInstance->Log(DEFAULT, "WARNING: A sqlite connection with id: %s already exists. Aborting database open attempt.", hi.id.c_str());
468 newconn = new SQLConn(ServerInstance, this, hi);
470 connections.insert(std::make_pair(hi.id, newconn));
473 virtual char* OnRequest(Request* request)
475 if(strcmp(SQLREQID, request->GetId()) == 0)
477 SQLrequest* req = (SQLrequest*)request;
478 ConnMap::iterator iter;
479 ServerInstance->Log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
480 if((iter = connections.find(req->dbid)) != connections.end())
483 req->error = iter->second->Query(*req);
488 req->error.Id(BAD_DBID);
492 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
496 unsigned long NewID()
504 virtual Version GetVersion()
506 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER,API_VERSION);
512 class ModuleSQLite3Factory : public ModuleFactory
515 ModuleSQLite3Factory()
519 ~ModuleSQLite3Factory()
523 virtual Module * CreateModule(InspIRCd* Me)
525 return new ModuleSQLite3(Me);
529 extern "C" void * init_module( void )
531 return new ModuleSQLite3Factory;