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 * ---------------------------------------------------
20 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
21 /* $CompileFlags: -Iexec("pg_config --includedir") eval("my $s = `pg_config --version`;$s =~ /^.*?(\d+)\.(\d+)\.(\d+).*?$/;my $v = hex(sprintf("0x%02x%02x%02x", $1, $2, $3));print "-DPGSQL_HAS_ESCAPECONN" if(($v >= 0x080104) || ($v >= 0x07030F && $v < 0x070400) || ($v >= 0x07040D && $v < 0x080000) || ($v >= 0x080008 && $v < 0x080100));") */
22 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
23 /* $ModDep: m_sqlv2.h */
25 /* SQLConn rewritten by peavey to
26 * use EventHandler instead of
27 * BufferedSocket. This is much neater
28 * and gives total control of destroy
29 * and delete of resources.
32 /* Forward declare, so we can have the typedef neatly at the top */
36 typedef std::map<std::string, SQLConn*> ConnMap;
38 /* CREAD, Connecting and wants read event
39 * CWRITE, Connecting and wants write event
40 * WREAD, Connected/Working and wants read event
41 * WWRITE, Connected/Working and wants write event
42 * RREAD, Resetting and wants read event
43 * RWRITE, Resetting and wants write event
45 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
47 class ReconnectTimer : public Timer
52 ReconnectTimer(ModulePgSQL* m) : Timer(5, ServerInstance->Time(), false), mod(m)
55 virtual void Tick(time_t TIME);
59 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
60 * All SQL providers must create their own subclass and define it's methods using that
61 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
62 * of converting all data to a common format before it reaches the result structure. This way
63 * data is passes to the module nearly as directly as if it was using the API directly itself.
66 class PgSQLresult : public SQLResult
72 PgSQLresult(PGresult* result) : res(result), currentrow(0)
74 rows = PQntuples(res);
76 rows = atoi(PQcmdTuples(res));
89 virtual void GetCols(std::vector<std::string>& result)
91 result.resize(PQnfields(res));
92 for(unsigned int i=0; i < result.size(); i++)
94 result[i] = PQfname(res, i);
98 virtual SQLEntry GetValue(int row, int column)
100 char* v = PQgetvalue(res, row, column);
101 if (!v || PQgetisnull(res, row, column))
104 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
107 virtual bool GetRow(SQLEntries& result)
109 if (currentrow >= PQntuples(res))
111 int ncols = PQnfields(res);
113 for(int i = 0; i < ncols; i++)
115 result.push_back(GetValue(currentrow, i));
123 /** SQLConn represents one SQL session.
125 class SQLConn : public SQLProvider, public EventHandler
128 reference<ConfigTag> conf; /* The <database> entry */
129 std::deque<SQLQuery*> queue;
130 PGconn* sql; /* PgSQL database connection handle */
131 SQLstatus status; /* PgSQL database connection status */
132 SQLQuery* qinprog; /* If there is currently a query in progress */
133 time_t idle; /* Time we last heard from the database */
136 SQLConn(Module* Creator, ConfigTag* tag)
137 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL)
139 idle = ServerInstance->Time();
142 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
149 this->SQLProvider::cull();
150 ServerInstance->Modules->DelService(*this);
151 return this->EventHandler::cull();
156 SQLerror err(SQL_BAD_DBID);
159 qinprog->OnError(err);
162 for(std::deque<SQLQuery*>::iterator i = queue.begin(); i != queue.end(); i++)
170 virtual void HandleEvent(EventType et, int errornum)
186 std::ostringstream conninfo("connect_timeout = '5'");
189 if (conf->readString("host", item))
190 conninfo << " host = '" << item << "'";
192 if (conf->readString("port", item))
193 conninfo << " port = '" << item << "'";
195 if (conf->readString("name", item))
196 conninfo << " dbname = '" << item << "'";
198 if (conf->readString("user", item))
199 conninfo << " user = '" << item << "'";
201 if (conf->readString("pass", item))
202 conninfo << " password = '" << item << "'";
204 if (conf->getBool("ssl"))
205 conninfo << " sslmode = 'require'";
207 conninfo << " sslmode = 'disable'";
209 return conninfo.str();
214 sql = PQconnectStart(GetDSN().c_str());
218 if(PQstatus(sql) == CONNECTION_BAD)
221 if(PQsetnonblocking(sql, 1) == -1)
224 /* OK, we've initalised the connection, now to get it hooked into the socket engine
225 * and then start polling it.
227 this->fd = PQsocket(sql);
232 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
234 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
238 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
244 switch(PQconnectPoll(sql))
246 case PGRES_POLLING_WRITING:
247 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
250 case PGRES_POLLING_READING:
251 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
254 case PGRES_POLLING_FAILED:
256 case PGRES_POLLING_OK:
257 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
265 void DoConnectedPoll()
268 while (!qinprog && !queue.empty())
270 /* There's no query currently in progress, and there's queries in the queue. */
271 DoQuery(queue.front());
275 if (PQconsumeInput(sql))
277 /* We just read stuff from the server, that counts as it being alive
278 * so update the idle-since time :p
280 idle = ServerInstance->Time();
284 /* Nothing happens here */
288 /* Fetch the result.. */
289 PGresult* result = PQgetResult(sql);
291 /* PgSQL would allow a query string to be sent which has multiple
292 * queries in it, this isn't portable across database backends and
293 * we don't want modules doing it. But just in case we make sure we
294 * drain any results there are and just use the last one.
295 * If the module devs are behaving there will only be one result.
297 while (PGresult* temp = PQgetResult(sql))
303 /* ..and the result */
304 PgSQLresult reply(result);
305 switch(PQresultStatus(result))
307 case PGRES_EMPTY_QUERY:
308 case PGRES_BAD_RESPONSE:
309 case PGRES_FATAL_ERROR:
311 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
312 qinprog->OnError(err);
316 /* Other values are not errors */
317 qinprog->OnResult(reply);
327 /* I think we'll assume this means the server died...it might not,
328 * but I think that any error serious enough we actually get here
329 * deserves to reconnect [/excuse]
330 * Returning true so the core doesn't try and close the connection.
338 switch(PQresetPoll(sql))
340 case PGRES_POLLING_WRITING:
341 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
344 case PGRES_POLLING_READING:
345 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
348 case PGRES_POLLING_FAILED:
350 case PGRES_POLLING_OK:
351 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
359 void DelayReconnect();
363 if((status == CREAD) || (status == CWRITE))
367 else if((status == RREAD) || (status == RWRITE))
377 virtual std::string FormatQuery(const std::string& q, const ParamL& p)
380 unsigned int param = 0;
381 for(std::string::size_type i = 0; i < q.length(); i++)
387 // TODO numbered parameter support ('?1')
388 if (param < p.size())
390 std::string parm = p[param++];
392 #ifdef PGSQL_HAS_ESCAPECONN
394 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
396 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
398 PQescapeString (buffer, parm.c_str(), parm.length());
407 std::string FormatQuery(const std::string& q, const ParamM& p)
410 for(std::string::size_type i = 0; i < q.length(); i++)
418 while (i < q.length() && isalpha(q[i]))
419 field.push_back(q[i++]);
422 ParamM::const_iterator it = p.find(field);
425 std::string parm = it->second;
427 #ifdef PGSQL_HAS_ESCAPECONN
429 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
431 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
433 PQescapeString (buffer, parm.c_str(), parm.length());
442 virtual void submit(SQLQuery *req)
447 queue.push_back(req);
455 void DoQuery(SQLQuery* req)
457 if (status != WREAD && status != WWRITE)
459 // whoops, not connected...
460 SQLerror err(SQL_BAD_CONN);
466 if(PQsendQuery(sql, req->query.c_str()))
472 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
480 ServerInstance->SE->DelFd(this);
490 class ModulePgSQL : public Module
494 ReconnectTimer* retimer;
504 Implementation eventlist[] = { I_OnUnloadModule, I_OnRehash };
505 ServerInstance->Modules->Attach(eventlist, this, 2);
508 virtual ~ModulePgSQL()
511 ServerInstance->Timers->DelTimer(retimer);
512 ClearAllConnections();
515 virtual void OnRehash(User* user)
523 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
524 for(ConfigIter i = tags.first; i != tags.second; i++)
526 if (i->second->getString("module", "pgsql") != "pgsql")
528 std::string id = i->second->getString("id");
529 ConnMap::iterator curr = connections.find(id);
530 if (curr == connections.end())
532 SQLConn* conn = new SQLConn(this, i->second);
533 conns.insert(std::make_pair(id, conn));
534 ServerInstance->Modules->AddService(*conn);
539 connections.erase(curr);
542 ClearAllConnections();
543 conns.swap(connections);
546 void ClearAllConnections()
548 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
556 void OnUnloadModule(Module* mod)
558 // TODO cancel queries that will have a bad vtable
563 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
567 void ReconnectTimer::Tick(time_t time)
573 void SQLConn::DelayReconnect()
575 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
576 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
577 if (it != mod->connections.end())
579 mod->connections.erase(it);
580 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
583 mod->retimer = new ReconnectTimer(mod);
584 ServerInstance->Timers->AddTimer(mod->retimer);
589 MODULE_INIT(ModulePgSQL)