1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
26 #include "configreader.h"
30 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
31 /* $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) or (($v >= 0x07030F) and ($v < 0x080000)));") */
32 /* $LinkerFlags: -Lexec("pg_config --libdir") -lpq */
33 /* $ModDep: m_sqlv2.h */
36 /* SQLConn rewritten by peavey to
37 * use EventHandler instead of
38 * InspSocket. 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 */
46 typedef std::map<std::string, SQLConn*> ConnMap;
48 /* CREAD, Connecting and wants read event
49 * CWRITE, Connecting and wants write event
50 * WREAD, Connected/Working and wants read event
51 * WWRITE, Connected/Working and wants write event
52 * RREAD, Resetting and wants read event
53 * RWRITE, Resetting and wants write event
55 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
57 /** SQLhost::GetDSN() - Overload to return correct DSN for PostgreSQL
59 std::string SQLhost::GetDSN()
61 std::ostringstream conninfo("connect_timeout = '2'");
64 conninfo << " hostaddr = '" << ip << "'";
67 conninfo << " port = '" << port << "'";
70 conninfo << " dbname = '" << name << "'";
73 conninfo << " user = '" << user << "'";
76 conninfo << " password = '" << pass << "'";
80 conninfo << " sslmode = 'require'";
84 conninfo << " sslmode = 'disable'";
87 return conninfo.str();
90 class ReconnectTimer : public InspTimer
95 ReconnectTimer(InspIRCd* SI, Module* m)
96 : InspTimer(5, SI->Time(), false), mod(m)
99 virtual void Tick(time_t TIME);
103 /** Used to resolve sql server hostnames
105 class SQLresolver : public Resolver
111 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
112 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
116 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached);
118 virtual void OnError(ResolverError e, const std::string &errormessage)
120 ServerInstance->Log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
124 /** QueryQueue, a queue of queries waiting to be executed.
125 * This maintains two queues internally, one for 'priority'
126 * queries and one for less important ones. Each queue has
127 * new queries appended to it and ones to execute are popped
128 * off the front. This keeps them flowing round nicely and no
129 * query should ever get 'stuck' for too long. If there are
130 * queries in the priority queue they will be executed first,
131 * 'unimportant' queries will only be executed when the
132 * priority queue is empty.
134 * We store lists of SQLrequest's here, by value as we want to avoid storing
135 * any data allocated inside the client module (in case that module is unloaded
136 * while the query is in progress).
138 * Because we want to work on the current SQLrequest in-situ, we need a way
139 * of accessing the request we are currently processing, QueryQueue::front(),
140 * but that call needs to always return the same request until that request
141 * is removed from the queue, this is what the 'which' variable is. New queries are
142 * always added to the back of one of the two queues, but if when front()
143 * is first called then the priority queue is empty then front() will return
144 * a query from the normal queue, but if a query is then added to the priority
145 * queue then front() must continue to return the front of the *normal* queue
146 * until pop() is called.
149 class QueryQueue : public classbase
152 typedef std::deque<SQLrequest> ReqDeque;
154 ReqDeque priority; /* The priority queue */
155 ReqDeque normal; /* The 'normal' queue */
156 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
164 void push(const SQLrequest &q)
166 //ServerInstance->Log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
169 priority.push_back(q);
176 if((which == PRI) && priority.size())
178 priority.pop_front();
180 else if((which == NOR) && normal.size())
188 /* Silently do nothing if there was no element to pop() */
196 return priority.front();
198 return normal.front();
203 return priority.front();
209 return normal.front();
212 /* This will probably result in a segfault,
213 * but the caller should have checked totalsize()
214 * first so..meh - moron :p
217 return priority.front();
221 std::pair<int, int> size()
223 return std::make_pair(priority.size(), normal.size());
228 return priority.size() + normal.size();
231 void PurgeModule(Module* mod)
233 DoPurgeModule(mod, priority);
234 DoPurgeModule(mod, normal);
238 void DoPurgeModule(Module* mod, ReqDeque& q)
240 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
242 if(iter->GetSource() == mod)
244 if(iter->id == front().id)
246 /* It's the currently active query.. :x */
247 iter->SetSource(NULL);
251 /* It hasn't been executed yet..just remove it */
252 iter = q.erase(iter);
259 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
260 * All SQL providers must create their own subclass and define it's methods using that
261 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
262 * of converting all data to a common format before it reaches the result structure. This way
263 * data is passes to the module nearly as directly as if it was using the API directly itself.
266 class PgSQLresult : public SQLresult
273 SQLfieldList* fieldlist;
274 SQLfieldMap* fieldmap;
276 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
277 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
279 rows = PQntuples(res);
280 cols = PQnfields(res);
282 //ServerInstance->Log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
287 /* If we allocated these, free them... */
301 return atoi(PQcmdTuples(res));
311 return PQnfields(res);
314 virtual std::string ColName(int column)
316 char* name = PQfname(res, column);
318 return (name) ? name : "";
321 virtual int ColNum(const std::string &column)
323 int n = PQfnumber(res, column.c_str());
327 throw SQLbadColName();
335 virtual SQLfield GetValue(int row, int column)
337 char* v = PQgetvalue(res, row, column);
341 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
345 //ServerInstance->Log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
346 throw SQLbadColName();
350 virtual SQLfieldList& GetRow()
352 /* In an effort to reduce overhead we don't actually allocate the list
353 * until the first time it's needed...so...
361 fieldlist = new SQLfieldList;
364 if(currentrow < PQntuples(res))
366 int cols = PQnfields(res);
368 for(int i = 0; i < cols; i++)
370 fieldlist->push_back(GetValue(currentrow, i));
379 virtual SQLfieldMap& GetRowMap()
381 /* In an effort to reduce overhead we don't actually allocate the map
382 * until the first time it's needed...so...
390 fieldmap = new SQLfieldMap;
393 if(currentrow < PQntuples(res))
395 int cols = PQnfields(res);
397 for(int i = 0; i < cols; i++)
399 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
408 virtual SQLfieldList* GetRowPtr()
410 SQLfieldList* fl = new SQLfieldList;
412 if(currentrow < PQntuples(res))
414 int cols = PQnfields(res);
416 for(int i = 0; i < cols; i++)
418 fl->push_back(GetValue(currentrow, i));
427 virtual SQLfieldMap* GetRowMapPtr()
429 SQLfieldMap* fm = new SQLfieldMap;
431 if(currentrow < PQntuples(res))
433 int cols = PQnfields(res);
435 for(int i = 0; i < cols; i++)
437 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
446 virtual void Free(SQLfieldMap* fm)
451 virtual void Free(SQLfieldList* fl)
457 /** SQLConn represents one SQL session.
459 class SQLConn : public EventHandler
463 SQLhost confhost; /* The <database> entry */
464 Module* us; /* Pointer to the SQL provider itself */
465 PGconn* sql; /* PgSQL database connection handle */
466 SQLstatus status; /* PgSQL database connection status */
467 bool qinprog; /* If there is currently a query in progress */
468 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
469 time_t idle; /* Time we last heard from the database */
472 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
473 : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
475 idle = this->Instance->Time();
478 Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
488 virtual void HandleEvent(EventType et, int errornum)
511 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
513 Instance->Log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
517 if(PQstatus(sql) == CONNECTION_BAD)
519 Instance->Log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
525 if(PQsetnonblocking(sql, 1) == -1)
527 Instance->Log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
531 /* OK, we've initalised the connection, now to get it hooked into the socket engine
532 * and then start polling it.
534 this->fd = PQsocket(sql);
535 Instance->Log(DEBUG, "New SQL socket: %d", this->fd);
539 Instance->Log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
543 if (!this->Instance->SE->AddFd(this))
545 Instance->Log(DEBUG, "A PQsocket cant be added to the socket engine!");
549 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
555 switch(PQconnectPoll(sql))
557 case PGRES_POLLING_WRITING:
558 Instance->SE->WantWrite(this);
561 case PGRES_POLLING_READING:
564 case PGRES_POLLING_FAILED:
566 case PGRES_POLLING_OK:
568 return DoConnectedPoll();
574 bool DoConnectedPoll()
576 if(!qinprog && queue.totalsize())
578 /* There's no query currently in progress, and there's queries in the queue. */
579 SQLrequest& query = queue.front();
583 if(PQconsumeInput(sql))
585 Instance->Log(DEBUG, "PQconsumeInput succeeded");
587 /* We just read stuff from the server, that counts as it being alive
588 * so update the idle-since time :p
590 idle = this->Instance->Time();
594 //Instance->Log(DEBUG, "Still busy processing command though");
598 //ServerInstance->Log(DEBUG, "Looks like we have a result to process!");
600 /* Grab the request we're processing */
601 SQLrequest& query = queue.front();
603 Instance->Log(DEBUG, "ID is %lu", query.id);
605 /* Get a pointer to the module we're about to return the result to */
606 Module* to = query.GetSource();
608 /* Fetch the result.. */
609 PGresult* result = PQgetResult(sql);
611 /* PgSQL would allow a query string to be sent which has multiple
612 * queries in it, this isn't portable across database backends and
613 * we don't want modules doing it. But just in case we make sure we
614 * drain any results there are and just use the last one.
615 * If the module devs are behaving there will only be one result.
617 while (PGresult* temp = PQgetResult(sql))
625 /* ..and the result */
626 PgSQLresult reply(us, to, query.id, result);
628 /* Fix by brain, make sure the original query gets sent back in the reply */
629 reply.query = query.query.q;
631 Instance->Log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
633 switch(PQresultStatus(result))
635 case PGRES_EMPTY_QUERY:
636 case PGRES_BAD_RESPONSE:
637 case PGRES_FATAL_ERROR:
638 reply.error.Id(QREPLY_FAIL);
639 reply.error.Str(PQresultErrorMessage(result));
641 /* No action, other values are not errors */
646 /* PgSQLresult's destructor will free the PGresult */
650 /* If the client module is unloaded partway through a query then the provider will set
651 * the pointer to NULL. We cannot just cancel the query as the result will still come
652 * through at some point...and it could get messy if we play with invalid pointers...
654 Instance->Log(DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: %lu", query.id);
663 Instance->Log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
669 /* I think we'll assume this means the server died...it might not,
670 * but I think that any error serious enough we actually get here
671 * deserves to reconnect [/excuse]
672 * Returning true so the core doesn't try and close the connection.
674 Instance->Log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
682 switch(PQresetPoll(sql))
684 case PGRES_POLLING_WRITING:
685 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
686 Instance->SE->WantWrite(this);
689 case PGRES_POLLING_READING:
690 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
693 case PGRES_POLLING_FAILED:
694 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
696 case PGRES_POLLING_OK:
697 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
699 return DoConnectedPoll();
701 //ServerInstance->Log(DEBUG, "PGresetPoll: wtf?");
708 switch(PQstatus(sql))
711 Instance->Log(DEBUG, "PQstatus: CONNECTION_OK: Can proceed to connect.");
715 Instance->Log(DEBUG, "PQstatus: CONNECTION_BAD: Connection is closed.");
718 case CONNECTION_STARTED:
719 Instance->Log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
722 case CONNECTION_MADE:
723 Instance->Log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
726 case CONNECTION_AWAITING_RESPONSE:
727 Instance->Log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
730 case CONNECTION_AUTH_OK:
731 Instance->Log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
734 case CONNECTION_SSL_STARTUP:
735 Instance->Log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
738 case CONNECTION_SETENV:
739 Instance->Log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
743 Instance->Log(DEBUG, "PQstatus: ???");
749 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
750 Instance->Log(DEBUG, "OnDataReady(): status = %s", StatusStr());
756 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
757 Instance->Log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
763 Instance->Log(DEBUG, "OnConnected(): status = %s", StatusStr());
767 void DelayReconnect();
773 if((status == CREAD) || (status == CWRITE))
777 else if((status == RREAD) || (status == RWRITE))
783 ret = DoConnectedPoll();
788 const char* StatusStr()
790 if(status == CREAD) return "CREAD";
791 if(status == CWRITE) return "CWRITE";
792 if(status == WREAD) return "WREAD";
793 if(status == WWRITE) return "WWRITE";
794 return "Err...what, erm..BUG!";
797 SQLerror DoQuery(SQLrequest &req)
799 if((status == WREAD) || (status == WWRITE))
803 /* Parse the command string and dispatch it */
805 /* Pointer to the buffer we screw around with substitution in */
807 /* Pointer to the current end of query, where we append new stuff */
809 /* Total length of the unescaped parameters */
810 unsigned int paramlen;
814 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
816 paramlen += i->size();
819 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
820 * sizeofquery + (totalparamlength*2) + 1
822 * The +1 is for null-terminating the string for PQsendQuery()
825 query = new char[req.query.q.length() + (paramlen*2) + 1];
828 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
829 * the parameters into it...
832 for(unsigned int i = 0; i < req.query.q.length(); i++)
834 if(req.query.q[i] == '?')
836 /* We found a place to substitute..what fun.
837 * Use the PgSQL calls to escape and write the
838 * escaped string onto the end of our query buffer,
839 * then we "just" need to make sure queryend is
840 * pointing at the right place.
843 if(req.query.p.size())
848 #ifdef PGSQL_HAS_ESCAPECONN
849 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
851 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
855 Instance->Log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
858 Instance->Log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
860 /* Incremenet queryend to the end of the newly escaped parameter */
863 /* Remove the parameter we just substituted in */
864 req.query.p.pop_front();
868 Instance->Log(DEBUG, "Found a substitution location but no parameter to substitute :|");
874 *queryend = req.query.q[i];
879 /* Null-terminate the query */
882 Instance->Log(DEBUG, "Attempting to dispatch query: %s", query);
886 if(PQsendQuery(sql, query))
888 Instance->Log(DEBUG, "Dispatched query successfully");
895 Instance->Log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
897 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
901 return SQLerror(BAD_CONN, "Can't query until connection is complete");
904 SQLerror Query(const SQLrequest &req)
908 if(!qinprog && queue.totalsize())
910 /* There's no query currently in progress, and there's queries in the queue. */
911 SQLrequest& query = queue.front();
912 return DoQuery(query);
920 void OnUnloadModule(Module* mod)
922 queue.PurgeModule(mod);
925 const SQLhost GetConfHost()
931 Instance->Log(DEBUG, "SQLConn::Close - socket: %d", this->fd);
933 if (!this->Instance->SE->DelFd(this))
935 if (sql && PQstatus(sql) == CONNECTION_BAD)
937 Instance->Log(DEBUG, "PQsocket was already removed. Forcing removal from socket engine!");
938 this->Instance->SE->DelFd(this, true);
942 Instance->Log(DEBUG, "PQsocket cant be removed from socket engine!");
946 Instance->Log(DEBUG, "PQsocket removed from socket engine!");
958 class ModulePgSQL : public Module
962 unsigned long currid;
964 ReconnectTimer* retimer;
967 ModulePgSQL(InspIRCd* Me)
968 : Module::Module(Me), currid(0)
970 ServerInstance->UseInterface("SQLutils");
972 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
974 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
976 if (!ServerInstance->PublishFeature("SQL", this))
978 throw ModuleException("m_pgsql: Unable to publish feature 'SQL'");
983 ServerInstance->PublishInterface("SQL", this);
986 virtual ~ModulePgSQL()
989 ServerInstance->Timers->DelTimer(retimer);
990 ClearAllConnections();
992 ServerInstance->UnpublishInterface("SQL", this);
993 ServerInstance->UnpublishFeature("SQL");
994 ServerInstance->DoneWithInterface("SQLutils");
997 void Implements(char* List)
999 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
1002 virtual void OnRehash(userrec* user, const std::string ¶meter)
1007 bool HasHost(const SQLhost &host)
1009 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1011 if (host == iter->second->GetConfHost())
1017 bool HostInConf(const SQLhost &h)
1019 ConfigReader conf(ServerInstance);
1020 for(int i = 0; i < conf.Enumerate("database"); i++)
1023 host.id = conf.ReadValue("database", "id", i);
1024 host.host = conf.ReadValue("database", "hostname", i);
1025 host.port = conf.ReadInteger("database", "port", i, true);
1026 host.name = conf.ReadValue("database", "name", i);
1027 host.user = conf.ReadValue("database", "username", i);
1028 host.pass = conf.ReadValue("database", "password", i);
1029 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
1038 ClearOldConnections();
1040 ConfigReader conf(ServerInstance);
1041 for(int i = 0; i < conf.Enumerate("database"); i++)
1045 insp_inaddr blargle;
1047 host.id = conf.ReadValue("database", "id", i);
1048 host.host = conf.ReadValue("database", "hostname", i);
1049 host.port = conf.ReadInteger("database", "port", i, true);
1050 host.name = conf.ReadValue("database", "name", i);
1051 host.user = conf.ReadValue("database", "username", i);
1052 host.pass = conf.ReadValue("database", "password", i);
1053 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
1058 ipvalid = insp_aton(host.host.c_str(), &blargle);
1062 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1063 host.ip = host.host;
1064 this->AddConn(host);
1066 else if(ipvalid == 0)
1068 /* Conversion failed, assume it's a host */
1069 SQLresolver* resolver;
1074 resolver = new SQLresolver(this, ServerInstance, host, cached);
1075 ServerInstance->AddResolver(resolver, cached);
1079 /* THE WORLD IS COMING TO AN END! */
1080 ServerInstance->Log(DEBUG, "Couldn't make a SQLresolver..this connection is gonna diiiiiie...actually we just won't create it");
1085 /* Invalid address family, die horribly. */
1086 ServerInstance->Log(DEBUG, "insp_aton failed returning -1, oh noes.");
1091 void ClearOldConnections()
1093 ConnMap::iterator iter,safei;
1094 for (iter = connections.begin(); iter != connections.end(); iter++)
1096 if (!HostInConf(iter->second->GetConfHost()))
1098 DELETE(iter->second);
1101 connections.erase(safei);
1106 void ClearAllConnections()
1108 ConnMap::iterator i;
1109 while ((i = connections.begin()) != connections.end())
1111 connections.erase(i);
1116 void AddConn(const SQLhost& hi)
1120 ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
1126 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1127 newconn = new SQLConn(ServerInstance, this, hi);
1129 connections.insert(std::make_pair(hi.id, newconn));
1132 void ReconnectConn(SQLConn* conn)
1134 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1136 if (conn == iter->second)
1138 DELETE(iter->second);
1139 connections.erase(iter);
1143 retimer = new ReconnectTimer(ServerInstance, this);
1144 ServerInstance->Timers->AddTimer(retimer);
1147 virtual char* OnRequest(Request* request)
1149 if(strcmp(SQLREQID, request->GetId()) == 0)
1151 SQLrequest* req = (SQLrequest*)request;
1152 ConnMap::iterator iter;
1154 ServerInstance->Log(DEBUG, "Got query: '%s' with %d replacement parameters on id '%s'", req->query.q.c_str(), req->query.p.size(), req->dbid.c_str());
1156 if((iter = connections.find(req->dbid)) != connections.end())
1160 req->error = iter->second->Query(*req);
1162 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1166 req->error.Id(BAD_DBID);
1171 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
1176 virtual void OnUnloadModule(Module* mod, const std::string& name)
1178 /* When a module unloads we have to check all the pending queries for all our connections
1179 * and set the Module* specifying where the query came from to NULL. If the query has already
1180 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1182 * If the queries we find are not already being executed then we can simply remove them immediately.
1184 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1186 iter->second->OnUnloadModule(mod);
1190 unsigned long NewID()
1198 virtual Version GetVersion()
1200 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1204 /* move this here to use AddConn, rather that than having the whole
1205 * module above SQLConn, since this is buggin me right now :/
1207 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
1210 ((ModulePgSQL*)mod)->AddConn(host);
1211 ((ModulePgSQL*)mod)->ClearOldConnections();
1214 void ReconnectTimer::Tick(time_t time)
1216 ((ModulePgSQL*)mod)->ReadConf();
1219 void SQLConn::DelayReconnect()
1221 ((ModulePgSQL*)us)->ReconnectConn(this);
1225 class ModulePgSQLFactory : public ModuleFactory
1228 ModulePgSQLFactory()
1232 ~ModulePgSQLFactory()
1236 virtual Module * CreateModule(InspIRCd* Me)
1238 return new ModulePgSQL(Me);
1243 extern "C" void * init_module( void )
1245 return new ModulePgSQLFactory;