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: -I`pg_config --includedir` `perl extra/pgsql_config.pl` */
32 /* $LinkerFlags: -L`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
96 ReconnectTimer(InspIRCd* SI, SQLConn* c, Module* m)
97 : InspTimer(5, SI->Time(), false), conn(c), mod(m)
100 virtual void Tick(time_t TIME);
104 /** Used to resolve sql server hostnames
106 class SQLresolver : public Resolver
112 SQLresolver(Module* m, InspIRCd* Instance, const SQLhost& hi, bool &cached)
113 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD, cached, (Module*)m), host(hi), mod(m)
117 virtual void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached);
119 virtual void OnError(ResolverError e, const std::string &errormessage)
121 ServerInstance->Log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
125 /** QueryQueue, a queue of queries waiting to be executed.
126 * This maintains two queues internally, one for 'priority'
127 * queries and one for less important ones. Each queue has
128 * new queries appended to it and ones to execute are popped
129 * off the front. This keeps them flowing round nicely and no
130 * query should ever get 'stuck' for too long. If there are
131 * queries in the priority queue they will be executed first,
132 * 'unimportant' queries will only be executed when the
133 * priority queue is empty.
135 * We store lists of SQLrequest's here, by value as we want to avoid storing
136 * any data allocated inside the client module (in case that module is unloaded
137 * while the query is in progress).
139 * Because we want to work on the current SQLrequest in-situ, we need a way
140 * of accessing the request we are currently processing, QueryQueue::front(),
141 * but that call needs to always return the same request until that request
142 * is removed from the queue, this is what the 'which' variable is. New queries are
143 * always added to the back of one of the two queues, but if when front()
144 * is first called then the priority queue is empty then front() will return
145 * a query from the normal queue, but if a query is then added to the priority
146 * queue then front() must continue to return the front of the *normal* queue
147 * until pop() is called.
150 class QueryQueue : public classbase
153 typedef std::deque<SQLrequest> ReqDeque;
155 ReqDeque priority; /* The priority queue */
156 ReqDeque normal; /* The 'normal' queue */
157 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
165 void push(const SQLrequest &q)
167 //ServerInstance->Log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
170 priority.push_back(q);
177 if((which == PRI) && priority.size())
179 priority.pop_front();
181 else if((which == NOR) && normal.size())
189 /* Silently do nothing if there was no element to pop() */
197 return priority.front();
199 return normal.front();
204 return priority.front();
210 return normal.front();
213 /* This will probably result in a segfault,
214 * but the caller should have checked totalsize()
215 * first so..meh - moron :p
218 return priority.front();
222 std::pair<int, int> size()
224 return std::make_pair(priority.size(), normal.size());
229 return priority.size() + normal.size();
232 void PurgeModule(Module* mod)
234 DoPurgeModule(mod, priority);
235 DoPurgeModule(mod, normal);
239 void DoPurgeModule(Module* mod, ReqDeque& q)
241 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
243 if(iter->GetSource() == mod)
245 if(iter->id == front().id)
247 /* It's the currently active query.. :x */
248 iter->SetSource(NULL);
252 /* It hasn't been executed yet..just remove it */
253 iter = q.erase(iter);
260 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
261 * All SQL providers must create their own subclass and define it's methods using that
262 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
263 * of converting all data to a common format before it reaches the result structure. This way
264 * data is passes to the module nearly as directly as if it was using the API directly itself.
267 class PgSQLresult : public SQLresult
274 SQLfieldList* fieldlist;
275 SQLfieldMap* fieldmap;
277 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
278 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
280 rows = PQntuples(res);
281 cols = PQnfields(res);
283 //ServerInstance->Log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
288 /* If we allocated these, free them... */
302 return atoi(PQcmdTuples(res));
312 return PQnfields(res);
315 virtual std::string ColName(int column)
317 char* name = PQfname(res, column);
319 return (name) ? name : "";
322 virtual int ColNum(const std::string &column)
324 int n = PQfnumber(res, column.c_str());
328 throw SQLbadColName();
336 virtual SQLfield GetValue(int row, int column)
338 char* v = PQgetvalue(res, row, column);
342 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
346 //ServerInstance->Log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
347 throw SQLbadColName();
351 virtual SQLfieldList& GetRow()
353 /* In an effort to reduce overhead we don't actually allocate the list
354 * until the first time it's needed...so...
362 fieldlist = new SQLfieldList;
365 if(currentrow < PQntuples(res))
367 int cols = PQnfields(res);
369 for(int i = 0; i < cols; i++)
371 fieldlist->push_back(GetValue(currentrow, i));
380 virtual SQLfieldMap& GetRowMap()
382 /* In an effort to reduce overhead we don't actually allocate the map
383 * until the first time it's needed...so...
391 fieldmap = new SQLfieldMap;
394 if(currentrow < PQntuples(res))
396 int cols = PQnfields(res);
398 for(int i = 0; i < cols; i++)
400 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
409 virtual SQLfieldList* GetRowPtr()
411 SQLfieldList* fl = new SQLfieldList;
413 if(currentrow < PQntuples(res))
415 int cols = PQnfields(res);
417 for(int i = 0; i < cols; i++)
419 fl->push_back(GetValue(currentrow, i));
428 virtual SQLfieldMap* GetRowMapPtr()
430 SQLfieldMap* fm = new SQLfieldMap;
432 if(currentrow < PQntuples(res))
434 int cols = PQnfields(res);
436 for(int i = 0; i < cols; i++)
438 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
447 virtual void Free(SQLfieldMap* fm)
452 virtual void Free(SQLfieldList* fl)
458 /** SQLConn represents one SQL session.
460 class SQLConn : public EventHandler
464 SQLhost confhost; /* The <database> entry */
465 Module* us; /* Pointer to the SQL provider itself */
466 PGconn* sql; /* PgSQL database connection handle */
467 SQLstatus status; /* PgSQL database connection status */
468 bool qinprog; /* If there is currently a query in progress */
469 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
470 time_t idle; /* Time we last heard from the database */
473 SQLConn(InspIRCd* SI, Module* self, const SQLhost& hi)
474 : EventHandler(), Instance(SI), confhost(hi), us(self), sql(NULL), status(CWRITE), qinprog(false)
476 idle = this->Instance->Time();
479 Instance->Log(DEFAULT, "WARNING: Could not connect to database with id: " + ConvToStr(hi.id));
490 virtual void HandleEvent(EventType et, int errornum)
514 if(!(sql = PQconnectStart(confhost.GetDSN().c_str())))
516 Instance->Log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
520 if(PQstatus(sql) == CONNECTION_BAD)
522 Instance->Log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
528 if(PQsetnonblocking(sql, 1) == -1)
530 Instance->Log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
534 /* OK, we've initalised the connection, now to get it hooked into the socket engine
535 * and then start polling it.
537 this->fd = PQsocket(sql);
538 Instance->Log(DEBUG, "New SQL socket: %d", this->fd);
542 Instance->Log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
546 if (!this->Instance->SE->AddFd(this))
548 Instance->Log(DEBUG, "A PQsocket cant be added to the socket engine!");
552 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
559 switch(PQconnectPoll(sql))
561 case PGRES_POLLING_WRITING:
562 Instance->SE->WantWrite(this);
565 case PGRES_POLLING_READING:
568 case PGRES_POLLING_FAILED:
570 case PGRES_POLLING_OK:
572 return DoConnectedPoll();
578 bool DoConnectedPoll()
580 if(!qinprog && queue.totalsize())
582 /* There's no query currently in progress, and there's queries in the queue. */
583 SQLrequest& query = queue.front();
587 if(PQconsumeInput(sql))
589 Instance->Log(DEBUG, "PQconsumeInput succeeded");
591 /* We just read stuff from the server, that counts as it being alive
592 * so update the idle-since time :p
594 idle = this->Instance->Time();
598 //Instance->Log(DEBUG, "Still busy processing command though");
602 //ServerInstance->Log(DEBUG, "Looks like we have a result to process!");
604 /* Grab the request we're processing */
605 SQLrequest& query = queue.front();
607 Instance->Log(DEBUG, "ID is %lu", query.id);
609 /* Get a pointer to the module we're about to return the result to */
610 Module* to = query.GetSource();
612 /* Fetch the result.. */
613 PGresult* result = PQgetResult(sql);
615 /* PgSQL would allow a query string to be sent which has multiple
616 * queries in it, this isn't portable across database backends and
617 * we don't want modules doing it. But just in case we make sure we
618 * drain any results there are and just use the last one.
619 * If the module devs are behaving there will only be one result.
621 while (PGresult* temp = PQgetResult(sql))
629 /* ..and the result */
630 PgSQLresult reply(us, to, query.id, result);
632 /* Fix by brain, make sure the original query gets sent back in the reply */
633 reply.query = query.query.q;
635 Instance->Log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
637 switch(PQresultStatus(result))
639 case PGRES_EMPTY_QUERY:
640 case PGRES_BAD_RESPONSE:
641 case PGRES_FATAL_ERROR:
642 reply.error.Id(QREPLY_FAIL);
643 reply.error.Str(PQresultErrorMessage(result));
645 /* No action, other values are not errors */
650 /* PgSQLresult's destructor will free the PGresult */
654 /* If the client module is unloaded partway through a query then the provider will set
655 * the pointer to NULL. We cannot just cancel the query as the result will still come
656 * through at some point...and it could get messy if we play with invalid pointers...
658 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);
667 Instance->Log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
673 /* I think we'll assume this means the server died...it might not,
674 * but I think that any error serious enough we actually get here
675 * deserves to reconnect [/excuse]
676 * Returning true so the core doesn't try and close the connection.
678 Instance->Log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
687 switch(PQresetPoll(sql))
689 case PGRES_POLLING_WRITING:
690 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
691 Instance->SE->WantWrite(this);
694 case PGRES_POLLING_READING:
695 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
698 case PGRES_POLLING_FAILED:
699 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
701 case PGRES_POLLING_OK:
702 //ServerInstance->Log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
704 return DoConnectedPoll();
706 //ServerInstance->Log(DEBUG, "PGresetPoll: wtf?");
713 switch(PQstatus(sql))
716 Instance->Log(DEBUG, "PQstatus: CONNECTION_OK: Can proceed to connect.");
720 Instance->Log(DEBUG, "PQstatus: CONNECTION_BAD: Connection is closed.");
723 case CONNECTION_STARTED:
724 Instance->Log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
727 case CONNECTION_MADE:
728 Instance->Log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
731 case CONNECTION_AWAITING_RESPONSE:
732 Instance->Log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
735 case CONNECTION_AUTH_OK:
736 Instance->Log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
739 case CONNECTION_SSL_STARTUP:
740 Instance->Log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
743 case CONNECTION_SETENV:
744 Instance->Log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
748 Instance->Log(DEBUG, "PQstatus: ???");
754 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
755 Instance->Log(DEBUG, "OnDataReady(): status = %s", StatusStr());
761 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
762 Instance->Log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
768 Instance->Log(DEBUG, "OnConnected(): status = %s", StatusStr());
772 void DelayReconnect()
774 ReconnectTimer* timer = new ReconnectTimer(Instance, this, us);
775 Instance->Timers->AddTimer(timer);
782 if((status == CREAD) || (status == CWRITE))
786 else if((status == RREAD) || (status == RWRITE))
792 ret = DoConnectedPoll();
797 const char* StatusStr()
799 if(status == CREAD) return "CREAD";
800 if(status == CWRITE) return "CWRITE";
801 if(status == WREAD) return "WREAD";
802 if(status == WWRITE) return "WWRITE";
803 return "Err...what, erm..BUG!";
806 SQLerror DoQuery(SQLrequest &req)
808 if((status == WREAD) || (status == WWRITE))
812 /* Parse the command string and dispatch it */
814 /* Pointer to the buffer we screw around with substitution in */
816 /* Pointer to the current end of query, where we append new stuff */
818 /* Total length of the unescaped parameters */
819 unsigned int paramlen;
823 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
825 paramlen += i->size();
828 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
829 * sizeofquery + (totalparamlength*2) + 1
831 * The +1 is for null-terminating the string for PQsendQuery()
834 query = new char[req.query.q.length() + (paramlen*2) + 1];
837 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
838 * the parameters into it...
841 for(unsigned int i = 0; i < req.query.q.length(); i++)
843 if(req.query.q[i] == '?')
845 /* We found a place to substitute..what fun.
846 * Use the PgSQL calls to escape and write the
847 * escaped string onto the end of our query buffer,
848 * then we "just" need to make sure queryend is
849 * pointing at the right place.
852 if(req.query.p.size())
857 #ifdef PGSQL_HAS_ESCAPECONN
858 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
860 len = PQescapeString (queryend, req.query.p.front().c_str(), req.query.p.front().length());
864 Instance->Log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
867 Instance->Log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
869 /* Incremenet queryend to the end of the newly escaped parameter */
872 /* Remove the parameter we just substituted in */
873 req.query.p.pop_front();
877 Instance->Log(DEBUG, "Found a substitution location but no parameter to substitute :|");
883 *queryend = req.query.q[i];
888 /* Null-terminate the query */
891 Instance->Log(DEBUG, "Attempting to dispatch query: %s", query);
895 if(PQsendQuery(sql, query))
897 Instance->Log(DEBUG, "Dispatched query successfully");
904 Instance->Log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
906 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
910 return SQLerror(BAD_CONN, "Can't query until connection is complete");
913 SQLerror Query(const SQLrequest &req)
917 if(!qinprog && queue.totalsize())
919 /* There's no query currently in progress, and there's queries in the queue. */
920 SQLrequest& query = queue.front();
921 return DoQuery(query);
929 void OnUnloadModule(Module* mod)
931 queue.PurgeModule(mod);
934 const SQLhost GetConfHost()
940 Instance->Log(DEBUG, "SQLConn::Close - socket: %d", this->fd);
942 if (!this->Instance->SE->DelFd(this))
944 if (sql && PQstatus(sql) == CONNECTION_BAD)
946 Instance->Log(DEBUG, "PQsocket was already removed. Forcing removal from socket engine!");
947 this->Instance->SE->DelFd(this, true);
951 Instance->Log(DEBUG, "PQsocket cant be removed from socket engine!");
955 Instance->Log(DEBUG, "PQsocket cant be removed from socket engine!");
967 class ModulePgSQL : public Module
971 unsigned long currid;
975 ModulePgSQL(InspIRCd* Me)
976 : Module::Module(Me), currid(0)
978 ServerInstance->UseInterface("SQLutils");
980 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
982 strlcpy(sqlsuccess, SQLSUCCESS, strlen(SQLSUCCESS));
984 if (!ServerInstance->PublishFeature("SQL", this))
986 throw ModuleException("m_pgsql: Unable to publish feature 'SQL'");
991 ServerInstance->PublishInterface("SQL", this);
994 virtual ~ModulePgSQL()
996 ClearAllConnections();
998 ServerInstance->UnpublishInterface("SQL", this);
999 ServerInstance->UnpublishFeature("SQL");
1000 ServerInstance->DoneWithInterface("SQLutils");
1003 void Implements(char* List)
1005 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
1008 virtual void OnRehash(userrec* user, const std::string ¶meter)
1013 bool HasHost(const SQLhost &host)
1015 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1017 if (host == iter->second->GetConfHost())
1023 bool HostInConf(const SQLhost &h)
1025 ConfigReader conf(ServerInstance);
1026 for(int i = 0; i < conf.Enumerate("database"); i++)
1029 host.id = conf.ReadValue("database", "id", i);
1030 host.host = conf.ReadValue("database", "hostname", i);
1031 host.port = conf.ReadInteger("database", "port", i, true);
1032 host.name = conf.ReadValue("database", "name", i);
1033 host.user = conf.ReadValue("database", "username", i);
1034 host.pass = conf.ReadValue("database", "password", i);
1035 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
1044 ClearOldConnections();
1046 ConfigReader conf(ServerInstance);
1047 for(int i = 0; i < conf.Enumerate("database"); i++)
1051 insp_inaddr blargle;
1053 host.id = conf.ReadValue("database", "id", i);
1054 host.host = conf.ReadValue("database", "hostname", i);
1055 host.port = conf.ReadInteger("database", "port", i, true);
1056 host.name = conf.ReadValue("database", "name", i);
1057 host.user = conf.ReadValue("database", "username", i);
1058 host.pass = conf.ReadValue("database", "password", i);
1059 host.ssl = conf.ReadFlag("database", "ssl", "0", i);
1064 ipvalid = insp_aton(host.host.c_str(), &blargle);
1068 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1069 host.ip = host.host;
1070 this->AddConn(host);
1072 else if(ipvalid == 0)
1074 /* Conversion failed, assume it's a host */
1075 SQLresolver* resolver;
1080 resolver = new SQLresolver(this, ServerInstance, host, cached);
1081 ServerInstance->AddResolver(resolver, cached);
1085 /* THE WORLD IS COMING TO AN END! */
1086 ServerInstance->Log(DEBUG, "Couldn't make a SQLresolver..this connection is gonna diiiiiie...actually we just won't create it");
1091 /* Invalid address family, die horribly. */
1092 ServerInstance->Log(DEBUG, "insp_aton failed returning -1, oh noes.");
1097 void ClearOldConnections()
1099 ConnMap::iterator iter,safei;
1100 for (iter = connections.begin(); iter != connections.end(); iter++)
1102 if (!HostInConf(iter->second->GetConfHost()))
1104 DELETE(iter->second);
1107 connections.erase(safei);
1112 void ClearAllConnections()
1114 ConnMap::iterator i;
1115 while ((i = connections.begin()) != connections.end())
1117 connections.erase(i);
1122 void AddConn(const SQLhost& hi)
1126 ServerInstance->Log(DEFAULT, "WARNING: A pgsql connection with id: %s already exists, possibly due to DNS delay. Aborting connection attempt.", hi.id.c_str());
1132 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
1133 newconn = new SQLConn(ServerInstance, this, hi);
1135 connections.insert(std::make_pair(hi.id, newconn));
1138 void ReconnectConn(SQLConn* conn)
1140 for (ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1142 if (conn == iter->second)
1144 DELETE(iter->second);
1145 connections.erase(iter);
1152 virtual char* OnRequest(Request* request)
1154 if(strcmp(SQLREQID, request->GetId()) == 0)
1156 SQLrequest* req = (SQLrequest*)request;
1157 ConnMap::iterator iter;
1159 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());
1161 if((iter = connections.find(req->dbid)) != connections.end())
1165 req->error = iter->second->Query(*req);
1167 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
1171 req->error.Id(BAD_DBID);
1176 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
1181 virtual void OnUnloadModule(Module* mod, const std::string& name)
1183 /* When a module unloads we have to check all the pending queries for all our connections
1184 * and set the Module* specifying where the query came from to NULL. If the query has already
1185 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
1187 * If the queries we find are not already being executed then we can simply remove them immediately.
1189 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
1191 iter->second->OnUnloadModule(mod);
1195 unsigned long NewID()
1203 virtual Version GetVersion()
1205 return Version(1, 1, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER, API_VERSION);
1209 /* move this here to use AddConn, rather that than having the whole
1210 * module above SQLConn, since this is buggin me right now :/
1212 void SQLresolver::OnLookupComplete(const std::string &result, unsigned int ttl, bool cached)
1215 ((ModulePgSQL*)mod)->AddConn(host);
1216 ((ModulePgSQL*)mod)->ClearOldConnections();
1219 void ReconnectTimer::Tick(time_t time)
1221 ((ModulePgSQL*)mod)->ReconnectConn(conn);
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;