2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2007, 2009 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2006-2007, 2009 Craig Edwards <craigedwards@brainbox.cc>
7 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 /// $CompilerFlags: -Iexecute("pg_config --includedir" "POSTGRESQL_INCLUDE_DIR")
25 /// $LinkerFlags: -Lexecute("pg_config --libdir" "POSTGRESQL_LIBRARY_DIR") -lpq
27 /// $PackageInfo: require_system("darwin") postgresql
28 /// $PackageInfo: require_system("ubuntu") libpq-dev
34 #include "modules/sql.h"
36 /* SQLConn rewritten by peavey to
37 * use EventHandler instead of
38 * BufferedSocket. This is much neater
39 * and gives total control of destroy
40 * and delete of resources.
43 /* Forward declare, so we can have the typedef neatly at the top */
47 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
49 /* CREAD, Connecting and wants read event
50 * CWRITE, Connecting and wants write event
51 * WREAD, Connected/Working and wants read event
52 * WWRITE, Connected/Working and wants write event
53 * RREAD, Resetting and wants read event
54 * RWRITE, Resetting and wants write event
56 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
58 class ReconnectTimer : public Timer
63 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
66 bool Tick(time_t TIME);
73 QueueItem(SQLQuery* C, const std::string& Q) : c(C), q(Q) {}
76 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
77 * All SQL providers must create their own subclass and define it's methods using that
78 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
79 * of converting all data to a common format before it reaches the result structure. This way
80 * data is passes to the module nearly as directly as if it was using the API directly itself.
83 class PgSQLresult : public SQLResult
89 PgSQLresult(PGresult* result) : res(result), currentrow(0)
91 rows = PQntuples(res);
93 rows = atoi(PQcmdTuples(res));
106 void GetCols(std::vector<std::string>& result)
108 result.resize(PQnfields(res));
109 for(unsigned int i=0; i < result.size(); i++)
111 result[i] = PQfname(res, i);
115 SQLEntry GetValue(int row, int column)
117 char* v = PQgetvalue(res, row, column);
118 if (!v || PQgetisnull(res, row, column))
121 return SQLEntry(std::string(v, PQgetlength(res, row, column)));
124 bool GetRow(SQLEntries& result)
126 if (currentrow >= PQntuples(res))
128 int ncols = PQnfields(res);
130 for(int i = 0; i < ncols; i++)
132 result.push_back(GetValue(currentrow, i));
140 /** SQLConn represents one SQL session.
142 class SQLConn : public SQLProvider, public EventHandler
145 reference<ConfigTag> conf; /* The <database> entry */
146 std::deque<QueueItem> queue;
147 PGconn* sql; /* PgSQL database connection handle */
148 SQLstatus status; /* PgSQL database connection status */
149 QueueItem qinprog; /* If there is currently a query in progress */
151 SQLConn(Module* Creator, ConfigTag* tag)
152 : SQLProvider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
156 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
163 this->SQLProvider::cull();
164 ServerInstance->Modules->DelService(*this);
165 return this->EventHandler::cull();
170 SQLerror err(SQL_BAD_DBID);
173 qinprog.c->OnError(err);
176 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
184 void OnEventHandlerRead() CXX11_OVERRIDE
189 void OnEventHandlerWrite() CXX11_OVERRIDE
194 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
201 std::ostringstream conninfo("connect_timeout = '5'");
204 if (conf->readString("host", item))
205 conninfo << " host = '" << item << "'";
207 if (conf->readString("port", item))
208 conninfo << " port = '" << item << "'";
210 if (conf->readString("name", item))
211 conninfo << " dbname = '" << item << "'";
213 if (conf->readString("user", item))
214 conninfo << " user = '" << item << "'";
216 if (conf->readString("pass", item))
217 conninfo << " password = '" << item << "'";
219 if (conf->getBool("ssl"))
220 conninfo << " sslmode = 'require'";
222 conninfo << " sslmode = 'disable'";
224 return conninfo.str();
229 sql = PQconnectStart(GetDSN().c_str());
233 if(PQstatus(sql) == CONNECTION_BAD)
236 if(PQsetnonblocking(sql, 1) == -1)
239 /* OK, we've initalised the connection, now to get it hooked into the socket engine
240 * and then start polling it.
242 this->fd = PQsocket(sql);
247 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
249 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
253 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
259 switch(PQconnectPoll(sql))
261 case PGRES_POLLING_WRITING:
262 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
265 case PGRES_POLLING_READING:
266 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
269 case PGRES_POLLING_FAILED:
271 case PGRES_POLLING_OK:
272 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
280 void DoConnectedPoll()
283 while (qinprog.q.empty() && !queue.empty())
285 /* There's no query currently in progress, and there's queries in the queue. */
286 DoQuery(queue.front());
290 if (PQconsumeInput(sql))
294 /* Nothing happens here */
298 /* Fetch the result.. */
299 PGresult* result = PQgetResult(sql);
301 /* PgSQL would allow a query string to be sent which has multiple
302 * queries in it, this isn't portable across database backends and
303 * we don't want modules doing it. But just in case we make sure we
304 * drain any results there are and just use the last one.
305 * If the module devs are behaving there will only be one result.
307 while (PGresult* temp = PQgetResult(sql))
313 /* ..and the result */
314 PgSQLresult reply(result);
315 switch(PQresultStatus(result))
317 case PGRES_EMPTY_QUERY:
318 case PGRES_BAD_RESPONSE:
319 case PGRES_FATAL_ERROR:
321 SQLerror err(SQL_QREPLY_FAIL, PQresultErrorMessage(result));
322 qinprog.c->OnError(err);
326 /* Other values are not errors */
327 qinprog.c->OnResult(reply);
331 qinprog = QueueItem(NULL, "");
341 /* I think we'll assume this means the server died...it might not,
342 * but I think that any error serious enough we actually get here
343 * deserves to reconnect [/excuse]
344 * Returning true so the core doesn't try and close the connection.
352 switch(PQresetPoll(sql))
354 case PGRES_POLLING_WRITING:
355 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
358 case PGRES_POLLING_READING:
359 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
362 case PGRES_POLLING_FAILED:
364 case PGRES_POLLING_OK:
365 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
373 void DelayReconnect();
377 if((status == CREAD) || (status == CWRITE))
381 else if((status == RREAD) || (status == RWRITE))
391 void submit(SQLQuery *req, const std::string& q)
393 if (qinprog.q.empty())
395 DoQuery(QueueItem(req,q));
400 queue.push_back(QueueItem(req,q));
404 void submit(SQLQuery *req, const std::string& q, const ParamL& p)
407 unsigned int param = 0;
408 for(std::string::size_type i = 0; i < q.length(); i++)
414 if (param < p.size())
416 std::string parm = p[param++];
417 std::vector<char> buffer(parm.length() * 2 + 1);
419 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
421 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
422 res.append(&buffer[0], escapedsize);
429 void submit(SQLQuery *req, const std::string& q, const ParamM& p)
432 for(std::string::size_type i = 0; i < q.length(); i++)
440 while (i < q.length() && isalnum(q[i]))
441 field.push_back(q[i++]);
444 ParamM::const_iterator it = p.find(field);
447 std::string parm = it->second;
448 std::vector<char> buffer(parm.length() * 2 + 1);
450 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
452 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
453 res.append(&buffer[0], escapedsize);
460 void DoQuery(const QueueItem& req)
462 if (status != WREAD && status != WWRITE)
464 // whoops, not connected...
465 SQLerror err(SQL_BAD_CONN);
471 if(PQsendQuery(sql, req.q.c_str()))
477 SQLerror err(SQL_QSEND_FAIL, PQerrorMessage(sql));
485 SocketEngine::DelFd(this);
495 class ModulePgSQL : public Module
499 ReconnectTimer* retimer;
509 ClearAllConnections();
512 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
520 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
521 for(ConfigIter i = tags.first; i != tags.second; i++)
523 if (i->second->getString("module", "pgsql") != "pgsql")
525 std::string id = i->second->getString("id");
526 ConnMap::iterator curr = connections.find(id);
527 if (curr == connections.end())
529 SQLConn* conn = new SQLConn(this, i->second);
530 conns.insert(std::make_pair(id, conn));
531 ServerInstance->Modules->AddService(*conn);
536 connections.erase(curr);
539 ClearAllConnections();
540 conns.swap(connections);
543 void ClearAllConnections()
545 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
553 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
555 SQLerror err(SQL_BAD_DBID);
556 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
558 SQLConn* conn = i->second;
559 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
561 conn->qinprog.c->OnError(err);
562 delete conn->qinprog.c;
563 conn->qinprog.c = NULL;
565 std::deque<QueueItem>::iterator j = conn->queue.begin();
566 while (j != conn->queue.end())
569 if (q->creator == mod)
573 j = conn->queue.erase(j);
581 Version GetVersion() CXX11_OVERRIDE
583 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
587 bool 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)