1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
25 #include "helperfuncs.h"
28 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
29 /* $CompileFlags: `mysql_config --include` */
30 /* $LinkerFlags: `mysql_config --libs` `perl ../mysql_rpath.pl` */
32 /** SQLConnection represents one mysql session.
33 * Each session has its own persistent connection to the database.
36 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
37 #define mysql_field_count mysql_num_fields
40 class SQLConnection : public classbase
51 std::map<std::string,std::string> thisrow;
57 // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
58 // MYSQL struct, but does not connect yet.
59 SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, long myid)
62 this->host = thishost;
63 this->user = thisuser;
64 this->pass = thispass;
69 // This method connects to the database using the credentials supplied to the constructor, and returns
73 unsigned int timeout = 1;
74 mysql_init(&connection);
75 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
76 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
79 // This method issues a query that expects multiple rows of results. Use GetRow() and QueryDone() to retrieve
81 bool QueryResult(std::string query)
83 if (!CheckConnection()) return false;
85 int r = mysql_query(&connection, query.c_str());
88 res = mysql_use_result(&connection);
93 // This method issues a query that just expects a number of 'effected' rows (e.g. UPDATE or DELETE FROM).
94 // the number of effected rows is returned in the return value.
95 long QueryCount(std::string query)
97 /* If the connection is down, we return a negative value - New to 1.1 */
98 if (!CheckConnection()) return -1;
100 int r = mysql_query(&connection, query.c_str());
103 res = mysql_store_result(&connection);
104 unsigned long rows = mysql_affected_rows(&connection);
105 mysql_free_result(res);
111 // This method fetches a row, if available from the database. You must issue a query
112 // using QueryResult() first! The row's values are returned as a map of std::string
113 // where each item is keyed by the column name.
114 std::map<std::string,std::string> GetRow()
119 row = mysql_fetch_row(res);
122 unsigned int field_count = 0;
123 MYSQL_FIELD *fields = mysql_fetch_fields(res);
124 if(mysql_field_count(&connection) == 0)
126 if (fields && mysql_field_count(&connection))
128 while (field_count < mysql_field_count(&connection))
130 std::string a = (fields[field_count].name ? fields[field_count].name : "");
131 std::string b = (row[field_count] ? row[field_count] : "");
146 mysql_free_result(res);
153 bool ConnectionLost()
156 return (mysql_ping(&connection) != 0);
161 bool CheckConnection()
163 if (ConnectionLost()) {
169 std::string GetError()
171 return mysql_error(&connection);
179 std::string GetHost()
201 typedef std::vector<SQLConnection> ConnectionList;
203 class ModuleSQL : public Module
207 ConnectionList Connections;
210 void ConnectDatabases()
212 for (ConnectionList::iterator i = Connections.begin(); i != Connections.end(); i++)
217 Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->GetHost());
221 Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->GetHost()+": Error: "+i->GetError());
227 void LoadDatabases(ConfigReader* ThisConf)
229 Srv->Log(DEFAULT,"SQL: Loading database settings");
231 Srv->Log(DEBUG,"Cleared connections");
232 for (int j =0; j < ThisConf->Enumerate("database"); j++)
234 std::string db = ThisConf->ReadValue("database","name",j);
235 std::string user = ThisConf->ReadValue("database","username",j);
236 std::string pass = ThisConf->ReadValue("database","password",j);
237 std::string host = ThisConf->ReadValue("database","hostname",j);
238 std::string id = ThisConf->ReadValue("database","id",j);
239 Srv->Log(DEBUG,"Read database settings");
240 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
242 SQLConnection ThisSQL(host,user,pass,db,atoi(id.c_str()));
243 Srv->Log(DEFAULT,"Loaded database: "+ThisSQL.GetHost());
244 Connections.push_back(ThisSQL);
245 Srv->Log(DEBUG,"Pushed back connection");
251 void ResultType(SQLRequest *r, SQLResult *res)
253 for (ConnectionList::iterator i = Connections.begin(); i != Connections.end(); i++)
255 if ((i->GetID() == r->GetConnID()) && (i->IsEnabled()))
257 bool xr = i->QueryResult(r->GetQuery());
260 res->SetType(SQL_ERROR);
261 res->SetError(i->GetError());
264 res->SetType(SQL_OK);
270 void CountType(SQLRequest *r, SQLResult* res)
272 for (ConnectionList::iterator i = Connections.begin(); i != Connections.end(); i++)
274 if ((i->GetID() == r->GetConnID()) && (i->IsEnabled()))
276 res->SetType(SQL_COUNT);
277 res->SetCount(i->QueryCount(r->GetQuery()));
283 void DoneType(SQLRequest *r, SQLResult* res)
285 for (ConnectionList::iterator i = Connections.begin(); i != Connections.end(); i++)
287 if ((i->GetID() == r->GetConnID()) && (i->IsEnabled()))
289 res->SetType(SQL_DONE);
291 res->SetType(SQL_ERROR);
296 void RowType(SQLRequest *r, SQLResult* res)
298 for (ConnectionList::iterator i = Connections.begin(); i != Connections.end(); i++)
300 if ((i->GetID() == r->GetConnID()) && (i->IsEnabled()))
302 log(DEBUG,"*** FOUND MATCHING ROW");
303 std::map<std::string,std::string> row = i->GetRow();
305 res->SetType(SQL_ROW);
308 log(DEBUG,"ROW SIZE IS 0");
309 res->SetType(SQL_END);
316 void Implements(char* List)
318 List[I_OnRehash] = List[I_OnRequest] = 1;
321 char* OnRequest(Request* request)
325 SQLResult* Result = new SQLResult();
326 SQLRequest *r = (SQLRequest*)request->GetData();
327 switch (r->GetQueryType())
330 ResultType(r,Result);
342 return (char*)Result;
347 ModuleSQL(Server* Me)
351 Conf = new ConfigReader();
361 virtual void OnRehash(const std::string ¶meter)
364 Conf = new ConfigReader();
368 virtual Version GetVersion()
370 return Version(1,0,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
375 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
377 class ModuleSQLFactory : public ModuleFactory
388 virtual Module * CreateModule(Server* Me)
390 return new ModuleSQL(Me);
396 extern "C" void * init_module( void )
398 return new ModuleSQLFactory;