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);
62 QueueItem(SQLQuery* C, const std::string& Q) : c(C), q(Q) {}
65 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
66 * All SQL providers must create their own subclass and define it's methods using that
67 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
68 * of converting all data to a common format before it reaches the result structure. This way
69 * data is passes to the module nearly as directly as if it was using the API directly itself.
72 class PgSQLresult : public SQLResult
78 PgSQLresult(PGresult* result) : res(result), currentrow(0)
80 rows = PQntuples(res);
82 rows = atoi(PQcmdTuples(res));
95 virtual void GetCols(std::vector<std::string>& result)
97 result.resize(PQnfields(res));
98 for(unsigned int i=0; i < result.size(); i++)
100 result[i] = PQfname(res, i);
104 virtual SQLEntry GetValue(int row, int column)
106 char* v = PQgetvalue(res, row, column);
107 if (!v || PQgetisnull(res, row, column))
110 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
113 virtual bool GetRow(SQLEntries& result)
115 if (currentrow >= PQntuples(res))
117 int ncols = PQnfields(res);
119 for(int i = 0; i < ncols; i++)
121 result.push_back(GetValue(currentrow, i));
129 /** SQLConn represents one SQL session.
131 class SQLConn : public SQLProvider, public EventHandler
134 reference<ConfigTag> conf; /* The <database> entry */
135 std::deque<QueueItem> queue;
136 PGconn* sql; /* PgSQL database connection handle */
137 SQLstatus status; /* PgSQL database connection status */
138 QueueItem qinprog; /* If there is currently a query in progress */
140 SQLConn(Module* Creator, ConfigTag* tag)
141 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
145 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
152 this->SQLProvider::cull();
153 ServerInstance->Modules->DelService(*this);
154 return this->EventHandler::cull();
159 SQLerror err(SQL_BAD_DBID);
162 qinprog.c->OnError(err);
165 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
173 virtual void HandleEvent(EventType et, int errornum)
189 std::ostringstream conninfo("connect_timeout = '5'");
192 if (conf->readString("host", item))
193 conninfo << " host = '" << item << "'";
195 if (conf->readString("port", item))
196 conninfo << " port = '" << item << "'";
198 if (conf->readString("name", item))
199 conninfo << " dbname = '" << item << "'";
201 if (conf->readString("user", item))
202 conninfo << " user = '" << item << "'";
204 if (conf->readString("pass", item))
205 conninfo << " password = '" << item << "'";
207 if (conf->getBool("ssl"))
208 conninfo << " sslmode = 'require'";
210 conninfo << " sslmode = 'disable'";
212 return conninfo.str();
217 sql = PQconnectStart(GetDSN().c_str());
221 if(PQstatus(sql) == CONNECTION_BAD)
224 if(PQsetnonblocking(sql, 1) == -1)
227 /* OK, we've initalised the connection, now to get it hooked into the socket engine
228 * and then start polling it.
230 this->fd = PQsocket(sql);
235 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
237 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
241 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
247 switch(PQconnectPoll(sql))
249 case PGRES_POLLING_WRITING:
250 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
253 case PGRES_POLLING_READING:
254 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
257 case PGRES_POLLING_FAILED:
259 case PGRES_POLLING_OK:
260 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
268 void DoConnectedPoll()
271 while (qinprog.q.empty() && !queue.empty())
273 /* There's no query currently in progress, and there's queries in the queue. */
274 DoQuery(queue.front());
278 if (PQconsumeInput(sql))
282 /* Nothing happens here */
286 /* Fetch the result.. */
287 PGresult* result = PQgetResult(sql);
289 /* PgSQL would allow a query string to be sent which has multiple
290 * queries in it, this isn't portable across database backends and
291 * we don't want modules doing it. But just in case we make sure we
292 * drain any results there are and just use the last one.
293 * If the module devs are behaving there will only be one result.
295 while (PGresult* temp = PQgetResult(sql))
301 /* ..and the result */
302 PgSQLresult reply(result);
303 switch(PQresultStatus(result))
305 case PGRES_EMPTY_QUERY:
306 case PGRES_BAD_RESPONSE:
307 case PGRES_FATAL_ERROR:
309 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
310 qinprog.c->OnError(err);
314 /* Other values are not errors */
315 qinprog.c->OnResult(reply);
319 qinprog = QueueItem(NULL, "");
329 /* I think we'll assume this means the server died...it might not,
330 * but I think that any error serious enough we actually get here
331 * deserves to reconnect [/excuse]
332 * Returning true so the core doesn't try and close the connection.
340 switch(PQresetPoll(sql))
342 case PGRES_POLLING_WRITING:
343 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
346 case PGRES_POLLING_READING:
347 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
350 case PGRES_POLLING_FAILED:
352 case PGRES_POLLING_OK:
353 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
361 void DelayReconnect();
365 if((status == CREAD) || (status == CWRITE))
369 else if((status == RREAD) || (status == RWRITE))
379 void submit(SQLQuery *req, const std::string& q)
381 if (qinprog.q.empty())
383 DoQuery(QueueItem(req,q));
388 queue.push_back(QueueItem(req,q));
392 void submit(SQLQuery *req, const std::string& q, const ParamL& p)
395 unsigned int param = 0;
396 for(std::string::size_type i = 0; i < q.length(); i++)
402 if (param < p.size())
404 std::string parm = p[param++];
406 #ifdef PGSQL_HAS_ESCAPECONN
408 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
410 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
412 PQescapeString (buffer, parm.c_str(), parm.length());
421 void submit(SQLQuery *req, const std::string& q, const ParamM& p)
424 for(std::string::size_type i = 0; i < q.length(); i++)
432 while (i < q.length() && isalpha(q[i]))
433 field.push_back(q[i++]);
436 ParamM::const_iterator it = p.find(field);
439 std::string parm = it->second;
441 #ifdef PGSQL_HAS_ESCAPECONN
443 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
445 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
447 PQescapeString (buffer, parm.c_str(), parm.length());
456 void DoQuery(const QueueItem& req)
458 if (status != WREAD && status != WWRITE)
460 // whoops, not connected...
461 SQLerror err(SQL_BAD_CONN);
467 if(PQsendQuery(sql, req.q.c_str()))
473 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
481 ServerInstance->SE->DelFd(this);
491 class ModulePgSQL : public Module
495 ReconnectTimer* retimer;
505 Implementation eventlist[] = { I_OnUnloadModule, I_OnRehash };
506 ServerInstance->Modules->Attach(eventlist, this, 2);
509 virtual ~ModulePgSQL()
512 ServerInstance->Timers->DelTimer(retimer);
513 ClearAllConnections();
516 virtual void OnRehash(User* user)
524 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
525 for(ConfigIter i = tags.first; i != tags.second; i++)
527 if (i->second->getString("module", "pgsql") != "pgsql")
529 std::string id = i->second->getString("id");
530 ConnMap::iterator curr = connections.find(id);
531 if (curr == connections.end())
533 SQLConn* conn = new SQLConn(this, i->second);
534 conns.insert(std::make_pair(id, conn));
535 ServerInstance->Modules->AddService(*conn);
540 connections.erase(curr);
543 ClearAllConnections();
544 conns.swap(connections);
547 void ClearAllConnections()
549 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
557 void OnUnloadModule(Module* mod)
559 SQLerror err(SQL_BAD_DBID);
560 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
562 SQLConn* conn = i->second;
563 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
565 conn->qinprog.c->OnError(err);
566 delete conn->qinprog.c;
567 conn->qinprog.c = NULL;
569 std::deque<QueueItem>::iterator j = conn->queue.begin();
570 while (j != conn->queue.end())
573 if (q->creator == mod)
577 j = conn->queue.erase(j);
587 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
591 void ReconnectTimer::Tick(time_t time)
597 void SQLConn::DelayReconnect()
599 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
600 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
601 if (it != mod->connections.end())
603 mod->connections.erase(it);
604 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
607 mod->retimer = new ReconnectTimer(mod);
608 ServerInstance->Timers->AddTimer(mod->retimer);
613 MODULE_INIT(ModulePgSQL)