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, tag->getString("id"))
187 ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "WARNING: Could not connect to database " + tag->getString("id"));
192 CullResult cull() CXX11_OVERRIDE
194 this->SQL::Provider::cull();
195 ServerInstance->Modules->DelService(*this);
196 return this->EventHandler::cull();
201 SQL::Error err(SQL::BAD_DBID);
204 qinprog.c->OnError(err);
207 for(std::deque<QueueItem>::iterator i = queue.begin(); i != queue.end(); i++)
209 SQL::Query* q = i->c;
215 void OnEventHandlerRead() CXX11_OVERRIDE
220 void OnEventHandlerWrite() CXX11_OVERRIDE
225 void OnEventHandlerError(int errornum) CXX11_OVERRIDE
232 std::ostringstream conninfo("connect_timeout = '5'");
235 if (conf->readString("host", item))
236 conninfo << " host = '" << item << "'";
238 if (conf->readString("port", item))
239 conninfo << " port = '" << item << "'";
241 if (conf->readString("name", item))
242 conninfo << " dbname = '" << item << "'";
244 if (conf->readString("user", item))
245 conninfo << " user = '" << item << "'";
247 if (conf->readString("pass", item))
248 conninfo << " password = '" << item << "'";
250 if (conf->getBool("ssl"))
251 conninfo << " sslmode = 'require'";
253 conninfo << " sslmode = 'disable'";
255 return conninfo.str();
260 sql = PQconnectStart(GetDSN().c_str());
264 if(PQstatus(sql) == CONNECTION_BAD)
267 if(PQsetnonblocking(sql, 1) == -1)
270 /* OK, we've initalised the connection, now to get it hooked into the socket engine
271 * and then start polling it.
273 this->fd = PQsocket(sql);
278 if (!SocketEngine::AddFd(this, FD_WANT_NO_WRITE | FD_WANT_NO_READ))
280 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Couldn't add pgsql socket to socket engine");
284 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
290 switch(PQconnectPoll(sql))
292 case PGRES_POLLING_WRITING:
293 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
296 case PGRES_POLLING_READING:
297 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
300 case PGRES_POLLING_FAILED:
302 case PGRES_POLLING_OK:
303 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
312 void DoConnectedPoll()
315 while (qinprog.q.empty() && !queue.empty())
317 /* There's no query currently in progress, and there's queries in the queue. */
318 DoQuery(queue.front());
322 if (PQconsumeInput(sql))
326 /* Nothing happens here */
330 /* Fetch the result.. */
331 PGresult* result = PQgetResult(sql);
333 /* PgSQL would allow a query string to be sent which has multiple
334 * queries in it, this isn't portable across database backends and
335 * we don't want modules doing it. But just in case we make sure we
336 * drain any results there are and just use the last one.
337 * If the module devs are behaving there will only be one result.
339 while (PGresult* temp = PQgetResult(sql))
345 /* ..and the result */
346 PgSQLresult reply(result);
347 switch(PQresultStatus(result))
349 case PGRES_EMPTY_QUERY:
350 case PGRES_BAD_RESPONSE:
351 case PGRES_FATAL_ERROR:
353 SQL::Error err(SQL::QREPLY_FAIL, PQresultErrorMessage(result));
354 qinprog.c->OnError(err);
358 /* Other values are not errors */
359 qinprog.c->OnResult(reply);
363 qinprog = QueueItem(NULL, "");
373 /* I think we'll assume this means the server died...it might not,
374 * but I think that any error serious enough we actually get here
375 * deserves to reconnect [/excuse]
376 * Returning true so the core doesn't try and close the connection.
384 switch(PQresetPoll(sql))
386 case PGRES_POLLING_WRITING:
387 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_WRITE | FD_WANT_NO_READ);
390 case PGRES_POLLING_READING:
391 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
394 case PGRES_POLLING_FAILED:
396 case PGRES_POLLING_OK:
397 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
406 void DelayReconnect();
410 if((status == CREAD) || (status == CWRITE))
414 else if((status == RREAD) || (status == RWRITE))
424 void Submit(SQL::Query *req, const std::string& q) CXX11_OVERRIDE
426 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Executing PostgreSQL query: " + q);
427 if (qinprog.q.empty())
429 DoQuery(QueueItem(req,q));
434 queue.push_back(QueueItem(req,q));
438 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamList& p) CXX11_OVERRIDE
441 unsigned int param = 0;
442 for(std::string::size_type i = 0; i < q.length(); i++)
448 if (param < p.size())
450 std::string parm = p[param++];
451 std::vector<char> buffer(parm.length() * 2 + 1);
453 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
455 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
456 res.append(&buffer[0], escapedsize);
463 void Submit(SQL::Query *req, const std::string& q, const SQL::ParamMap& p) CXX11_OVERRIDE
466 for(std::string::size_type i = 0; i < q.length(); i++)
474 while (i < q.length() && isalnum(q[i]))
475 field.push_back(q[i++]);
478 SQL::ParamMap::const_iterator it = p.find(field);
481 std::string parm = it->second;
482 std::vector<char> buffer(parm.length() * 2 + 1);
484 size_t escapedsize = PQescapeStringConn(sql, &buffer[0], parm.data(), parm.length(), &error);
486 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "BUG: Apparently PQescapeStringConn() failed");
487 res.append(&buffer[0], escapedsize);
494 void DoQuery(const QueueItem& req)
496 if (status != WREAD && status != WWRITE)
498 // whoops, not connected...
499 SQL::Error err(SQL::BAD_CONN);
505 if(PQsendQuery(sql, req.q.c_str()))
511 SQL::Error err(SQL::QSEND_FAIL, PQerrorMessage(sql));
519 SocketEngine::DelFd(this);
529 class ModulePgSQL : public Module
533 ReconnectTimer* retimer;
543 ClearAllConnections();
546 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
554 ConfigTagList tags = ServerInstance->Config->ConfTags("database");
555 for(ConfigIter i = tags.first; i != tags.second; i++)
557 if (!stdalgo::string::equalsci(i->second->getString("module"), "pgsql"))
559 std::string id = i->second->getString("id");
560 ConnMap::iterator curr = connections.find(id);
561 if (curr == connections.end())
563 SQLConn* conn = new SQLConn(this, i->second);
564 conns.insert(std::make_pair(id, conn));
565 ServerInstance->Modules->AddService(*conn);
570 connections.erase(curr);
573 ClearAllConnections();
574 conns.swap(connections);
577 void ClearAllConnections()
579 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
587 void OnUnloadModule(Module* mod) CXX11_OVERRIDE
589 SQL::Error err(SQL::BAD_DBID);
590 for(ConnMap::iterator i = connections.begin(); i != connections.end(); i++)
592 SQLConn* conn = i->second;
593 if (conn->qinprog.c && conn->qinprog.c->creator == mod)
595 conn->qinprog.c->OnError(err);
596 delete conn->qinprog.c;
597 conn->qinprog.c = NULL;
599 std::deque<QueueItem>::iterator j = conn->queue.begin();
600 while (j != conn->queue.end())
602 SQL::Query* q = j->c;
603 if (q->creator == mod)
607 j = conn->queue.erase(j);
615 Version GetVersion() CXX11_OVERRIDE
617 return Version("PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API", VF_VENDOR);
621 bool ReconnectTimer::Tick(time_t time)
629 void SQLConn::DelayReconnect()
631 ModulePgSQL* mod = (ModulePgSQL*)(Module*)creator;
632 ConnMap::iterator it = mod->connections.find(conf->getString("id"));
633 if (it != mod->connections.end())
635 mod->connections.erase(it);
636 ServerInstance->GlobalCulls.AddItem((EventHandler*)this);
639 mod->retimer = new ReconnectTimer(mod);
640 ServerInstance->Timers.AddTimer(mod->retimer);
645 MODULE_INIT(ModulePgSQL)