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 */
134 SQLConn(Module* Creator, ConfigTag* tag)
135 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL)
139 ServerInstance->Logs->Log("m_pgsql",DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
146 this->SQLProvider::cull();
147 ServerInstance->Modules->DelService(*this);
148 return this->EventHandler::cull();
153 SQLerror err(SQL_BAD_DBID);
156 qinprog->OnError(err);
159 for(std::deque<SQLQuery*>::iterator i = queue.begin(); i != queue.end(); i++)
167 virtual void HandleEvent(EventType et, int errornum)
183 std::ostringstream conninfo("connect_timeout = '5'");
186 if (conf->readString("host", item))
187 conninfo << " host = '" << item << "'";
189 if (conf->readString("port", item))
190 conninfo << " port = '" << item << "'";
192 if (conf->readString("name", item))
193 conninfo << " dbname = '" << item << "'";
195 if (conf->readString("user", item))
196 conninfo << " user = '" << item << "'";
198 if (conf->readString("pass", item))
199 conninfo << " password = '" << item << "'";
201 if (conf->getBool("ssl"))
202 conninfo << " sslmode = 'require'";
204 conninfo << " sslmode = 'disable'";
206 return conninfo.str();
211 sql = PQconnectStart(GetDSN().c_str());
215 if(PQstatus(sql) == CONNECTION_BAD)
218 if(PQsetnonblocking(sql, 1) == -1)
221 /* OK, we've initalised the connection, now to get it hooked into the socket engine
222 * and then start polling it.
224 this->fd = PQsocket(sql);
229 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
231 ServerInstance->Logs->Log("m_pgsql",DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
235 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
241 switch(PQconnectPoll(sql))
243 case PGRES_POLLING_WRITING:
244 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
247 case PGRES_POLLING_READING:
248 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
251 case PGRES_POLLING_FAILED:
253 case PGRES_POLLING_OK:
254 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
262 void DoConnectedPoll()
265 while (!qinprog && !queue.empty())
267 /* There's no query currently in progress, and there's queries in the queue. */
268 DoQuery(queue.front());
272 if (PQconsumeInput(sql))
276 /* Nothing happens here */
280 /* Fetch the result.. */
281 PGresult* result = PQgetResult(sql);
283 /* PgSQL would allow a query string to be sent which has multiple
284 * queries in it, this isn't portable across database backends and
285 * we don't want modules doing it. But just in case we make sure we
286 * drain any results there are and just use the last one.
287 * If the module devs are behaving there will only be one result.
289 while (PGresult* temp = PQgetResult(sql))
295 /* ..and the result */
296 PgSQLresult reply(result);
297 switch(PQresultStatus(result))
299 case PGRES_EMPTY_QUERY:
300 case PGRES_BAD_RESPONSE:
301 case PGRES_FATAL_ERROR:
303 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
304 qinprog->OnError(err);
308 /* Other values are not errors */
309 qinprog->OnResult(reply);
319 /* I think we'll assume this means the server died...it might not,
320 * but I think that any error serious enough we actually get here
321 * deserves to reconnect [/excuse]
322 * Returning true so the core doesn't try and close the connection.
330 switch(PQresetPoll(sql))
332 case PGRES_POLLING_WRITING:
333 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
336 case PGRES_POLLING_READING:
337 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
340 case PGRES_POLLING_FAILED:
342 case PGRES_POLLING_OK:
343 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
351 void DelayReconnect();
355 if((status == CREAD) || (status == CWRITE))
359 else if((status == RREAD) || (status == RWRITE))
369 virtual std::string FormatQuery(const std::string& q, const ParamL& p)
372 unsigned int param = 0;
373 for(std::string::size_type i = 0; i < q.length(); i++)
379 // TODO numbered parameter support ('?1')
380 if (param < p.size())
382 std::string parm = p[param++];
384 #ifdef PGSQL_HAS_ESCAPECONN
386 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
388 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
390 PQescapeString (buffer, parm.c_str(), parm.length());
399 std::string FormatQuery(const std::string& q, const ParamM& p)
402 for(std::string::size_type i = 0; i < q.length(); i++)
410 while (i < q.length() && isalpha(q[i]))
411 field.push_back(q[i++]);
414 ParamM::const_iterator it = p.find(field);
417 std::string parm = it->second;
419 #ifdef PGSQL_HAS_ESCAPECONN
421 PQescapeStringConn(sql, buffer, parm.c_str(), parm.length(), &error);
423 ServerInstance->Logs->Log("m_pgsql", DEBUG, "BUG: Apparently PQescapeStringConn() failed");
425 PQescapeString (buffer, parm.c_str(), parm.length());
434 virtual void submit(SQLQuery *req)
439 queue.push_back(req);
447 void DoQuery(SQLQuery* req)
449 if (status != WREAD && status != WWRITE)
451 // whoops, not connected...
452 SQLerror err(SQL_BAD_CONN);
458 if(PQsendQuery(sql, req->query.c_str()))
464 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
472 ServerInstance->SE->DelFd(this);
482 class DummyQuery : public SQLQuery
485 DummyQuery(Module* me) : SQLQuery(me, "") {}
486 void OnResult(SQLResult& result) {}
489 class ModulePgSQL : public Module
493 ReconnectTimer* retimer;
503 Implementation eventlist[] = { I_OnUnloadModule, I_OnRehash };
504 ServerInstance->Modules->Attach(eventlist, this, 2);
507 virtual ~ModulePgSQL()
510 ServerInstance->Timers->DelTimer(retimer);
511 ClearAllConnections();
514 virtual void OnRehash(User* user)
522 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
523 for(ConfigIter i = tags.first; i != tags.second; i++)
525 if (i->second->getString("module", "pgsql") != "pgsql")
527 std::string id = i->second->getString("id");
528 ConnMap::iterator curr = connections.find(id);
529 if (curr == connections.end())
531 SQLConn* conn = new SQLConn(this, i->second);
532 conns.insert(std::make_pair(id, conn));
533 ServerInstance->Modules->AddService(*conn);
538 connections.erase(curr);
541 ClearAllConnections();
542 conns.swap(connections);
545 void ClearAllConnections()
547 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
555 void OnUnloadModule(Module* mod)
557 SQLerror err(SQL_BAD_DBID);
558 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
560 SQLConn* conn = i->second;
561 if (conn->qinprog && conn->qinprog->creator == mod)
563 conn->qinprog->OnError(err);
564 delete conn->qinprog;
565 conn->qinprog = new DummyQuery(this);
567 std::deque<SQLQuery*>::iterator j = conn->queue.begin();
568 while (j != conn->queue.end())
571 if (q->creator == mod)
575 j = conn->queue.erase(j);
585 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
589 void ReconnectTimer::Tick(time_t time)
595 void SQLConn::DelayReconnect()
597 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
598 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
599 if (it != mod->connections.end())
601 mod->connections.erase(it);
602 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
605 mod->retimer = new ReconnectTimer(mod);
606 ServerInstance->Timers->AddTimer(mod->retimer);
611 MODULE_INIT(ModulePgSQL)