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("arch") postgresql-libs
28 /// $PackageInfo: require_system("centos") postgresql-devel
29 /// $PackageInfo: require_system("darwin") postgresql
30 /// $PackageInfo: require_system("debian") libpq-dev
31 /// $PackageInfo: require_system("ubuntu") libpq-dev
37 #include "modules/sql.h"
39 /* SQLConn rewritten by peavey to
40 * use EventHandler instead of
41 * BufferedSocket. This is much neater
42 * and gives total control of destroy
43 * and delete of resources.
46 /* Forward declare, so we can have the typedef neatly at the top */
50 typedef insp::flat_map<std::string, SQLConn*> ConnMap;
52 /* CREAD, Connecting and wants read event
53 * CWRITE, Connecting and wants write event
54 * WREAD, Connected/Working and wants read event
55 * WWRITE, Connected/Working and wants write event
56 * RREAD, Resetting and wants read event
57 * RWRITE, Resetting and wants write event
59 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
61 class ReconnectTimer : public Timer
66 ReconnectTimer(ModulePgSQL* m) : Timer(5, false), mod(m)
69 bool Tick(time_t TIME) CXX11_OVERRIDE;
76 QueueItem(SQL::Query* C, const std::string& Q) : c(C), q(Q) {}
79 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
80 * All SQL providers must create their own subclass and define it's methods using that
81 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
82 * of converting all data to a common format before it reaches the result structure. This way
83 * data is passes to the module nearly as directly as if it was using the API directly itself.
86 class PgSQLresult : public SQL::Result
91 std::vector<std::string> colnames;
95 colnames.resize(PQnfields(res));
96 for(unsigned int i=0; i < colnames.size(); i++)
98 colnames[i] = PQfname(res, i);
102 PgSQLresult(PGresult* result) : res(result), currentrow(0)
104 rows = PQntuples(res);
106 rows = ConvToNum<int>(PQcmdTuples(res));
114 int Rows() CXX11_OVERRIDE
119 void GetCols(std::vector<std::string>& result) CXX11_OVERRIDE
121 if (colnames.empty())
126 bool HasColumn(const std::string& column, size_t& index) CXX11_OVERRIDE
128 if (colnames.empty())
131 for (size_t i = 0; i < colnames.size(); ++i)
133 if (colnames[i] == column)
142 SQL::Field GetValue(int row, int column)
144 char* v = PQgetvalue(res, row, column);
145 if (!v || PQgetisnull(res, row, column))
148 return SQL::Field(std::string(v, PQgetlength(res, row, column)));
151 bool GetRow(SQL::Row& result) CXX11_OVERRIDE
153 if (currentrow >= PQntuples(res))
155 int ncols = PQnfields(res);
157 for(int i = 0; i < ncols; i++)
159 result.push_back(GetValue(currentrow, i));
167 /** SQLConn represents one SQL session.
169 class SQLConn : public SQL::Provider, public EventHandler
172 reference<ConfigTag> conf; /* The <database> entry */
173 std::deque<QueueItem> queue;
174 PGconn* sql; /* PgSQL database connection handle */
175 SQLstatus status; /* PgSQL database connection status */
176 QueueItem qinprog; /* If there is currently a query in progress */
178 SQLConn(Module* Creator, ConfigTag* tag)
179 : SQL::Provider(Creator, "SQL/" + tag->getString("id")), conf(tag), sql(NULL), status(CWRITE), qinprog(NULL, "")
183 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
188 CullResult cull() CXX11_OVERRIDE
190 this->SQL::Provider::cull();
191 ServerInstance->Modules->DelService(*this);
192 return this->EventHandler::cull();
197 SQL::Error err(SQL::BAD_DBID);
200 qinprog.c->OnError(err);
203 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
205 SQL::Query* q = i->c;
211 void OnEventHandlerRead() CXX11_OVERRIDE
216 void OnEventHandlerWrite() CXX11_OVERRIDE
221 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
228 std::ostringstream conninfo("connect_timeout = '5'");
231 if (conf->readString("host", item))
232 conninfo << " host = '" << item << "'";
234 if (conf->readString("port", item))
235 conninfo << " port = '" << item << "'";
237 if (conf->readString("name", item))
238 conninfo << " dbname = '" << item << "'";
240 if (conf->readString("user", item))
241 conninfo << " user = '" << item << "'";
243 if (conf->readString("pass", item))
244 conninfo << " password = '" << item << "'";
246 if (conf->getBool("ssl"))
247 conninfo << " sslmode = 'require'";
249 conninfo << " sslmode = 'disable'";
251 return conninfo.str();
256 sql = PQconnectStart(GetDSN().c_str());
260 if(PQstatus(sql) == CONNECTION_BAD)
263 if(PQsetnonblocking(sql, 1) == -1)
266 /* OK, we've initalised the connection, now to get it hooked into the socket engine
267 * and then start polling it.
269 this->fd = PQsocket(sql);
274 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
276 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
280 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
286 switch(PQconnectPoll(sql))
288 case PGRES_POLLING_WRITING:
289 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
292 case PGRES_POLLING_READING:
293 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
296 case PGRES_POLLING_FAILED:
298 case PGRES_POLLING_OK:
299 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
308 void DoConnectedPoll()
311 while (qinprog.q.empty() && !queue.empty())
313 /* There's no query currently in progress, and there's queries in the queue. */
314 DoQuery(queue.front());
318 if (PQconsumeInput(sql))
322 /* Nothing happens here */
326 /* Fetch the result.. */
327 PGresult* result = PQgetResult(sql);
329 /* PgSQL would allow a query string to be sent which has multiple
330 * queries in it, this isn't portable across database backends and
331 * we don't want modules doing it. But just in case we make sure we
332 * drain any results there are and just use the last one.
333 * If the module devs are behaving there will only be one result.
335 while (PGresult* temp = PQgetResult(sql))
341 /* ..and the result */
342 PgSQLresult reply(result);
343 switch(PQresultStatus(result))
345 case PGRES_EMPTY_QUERY:
346 case PGRES_BAD_RESPONSE:
347 case PGRES_FATAL_ERROR:
349 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
350 qinprog.c->OnError(err);
354 /* Other values are not errors */
355 qinprog.c->OnResult(reply);
359 qinprog = QueueItem(NULL, "");
369 /* I think we'll assume this means the server died...it might not,
370 * but I think that any error serious enough we actually get here
371 * deserves to reconnect [/excuse]
372 * Returning true so the core doesn't try and close the connection.
380 switch(PQresetPoll(sql))
382 case PGRES_POLLING_WRITING:
383 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
386 case PGRES_POLLING_READING:
387 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
390 case PGRES_POLLING_FAILED:
392 case PGRES_POLLING_OK:
393 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
402 void DelayReconnect();
406 if((status == CREAD) || (status == CWRITE))
410 else if((status == RREAD) || (status == RWRITE))
420 void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
422 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing PostgreSQL query: " + q);
423 if (qinprog.q.empty())
425 DoQuery(QueueItem(req,q));
430 queue.push_back(QueueItem(req,q));
434 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
437 unsigned int param = 0;
438 for(std::string::size_type i = 0; i < q.length(); i++)
444 if (param < p.size())
446 std::string parm = p[param++];
447 std::vector<char> buffer(parm.length() * 2 + 1);
449 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
451 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
452 res.append(&buffer[0], escapedsize);
459 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
462 for(std::string::size_type i = 0; i < q.length(); i++)
470 while (i < q.length() && isalnum(q[i]))
471 field.push_back(q[i++]);
474 SQL::ParamMap::const_iterator it = p.find(field);
477 std::string parm = it->second;
478 std::vector<char> buffer(parm.length() * 2 + 1);
480 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
482 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
483 res.append(&buffer[0], escapedsize);
490 void DoQuery(const QueueItem& req)
492 if (status != WREAD && status != WWRITE)
494 // whoops, not connected...
495 SQL::Error err(SQL::BAD_CONN);
501 if(PQsendQuery(sql, req.q.c_str()))
507 SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
515 SocketEngine::DelFd(this);
525 class ModulePgSQL : public Module
529 ReconnectTimer* retimer;
539 ClearAllConnections();
542 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
550 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
551 for(ConfigIter i = tags.first; i != tags.second; i++)
553 if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
555 std::string id = i->second->getString("id");
556 ConnMap::iterator curr = connections.find(id);
557 if (curr == connections.end())
559 SQLConn* conn = new SQLConn(this, i->second);
560 conns.insert(std::make_pair(id, conn));
561 ServerInstance->Modules->AddService(*conn);
566 connections.erase(curr);
569 ClearAllConnections();
570 conns.swap(connections);
573 void ClearAllConnections()
575 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
583 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
585 SQL::Error err(SQL::BAD_DBID);
586 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
588 SQLConn* conn = i->second;
589 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
591 conn->qinprog.c->OnError(err);
592 delete conn->qinprog.c;
593 conn->qinprog.c = NULL;
595 std::deque<QueueItem>::iterator j = conn->queue.begin();
596 while (j != conn->queue.end())
598 SQL::Query* q = j->c;
599 if (q->creator == mod)
603 j = conn->queue.erase(j);
611 Version GetVersion() CXX11_OVERRIDE
613 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
617 bool ReconnectTimer::Tick(time_t time)
625 void SQLConn::DelayReconnect()
627 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
628 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
629 if (it != mod->connections.end())
631 mod->connections.erase(it);
632 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
635 mod->retimer = new ReconnectTimer(mod);
636 ServerInstance->Timers.AddTimer(mod->retimer);
641 MODULE_INIT(ModulePgSQL)