1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
11 * Written by Craig Edwards, Craig McLure, and others.
12 * This program is free but copyrighted software; see
13 * the file COPYING for details.
15 * ---------------------------------------------------
28 #include "helperfuncs.h"
30 #include "configreader.h"
34 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
35 /* $CompileFlags: -I`pg_config --includedir` `perl extra/pgsql_config.pl` */
36 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
38 /* UGH, UGH, UGH, UGH, UGH, UGH
39 * I'm having trouble seeing how I
40 * can avoid this. The core-defined
41 * constructors for InspSocket just
42 * aren't suitable...and if I'm
43 * reimplementing them I need this so
44 * I can access the socket engine :\
46 extern InspIRCd* ServerInstance;
49 /* Forward declare, so we can have the typedef neatly at the top */
51 /* Also needs forward declaration, as it's used inside SQLconn */
54 typedef std::map<std::string, SQLConn*> ConnMap;
56 /* CREAD, Connecting and wants read event
57 * CWRITE, Connecting and wants write event
58 * WREAD, Connected/Working and wants read event
59 * WWRITE, Connected/Working and wants write event
60 * RREAD, Resetting and wants read event
61 * RWRITE, Resetting and wants write event
63 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
65 /** SQLhost, simple structure to store information about a SQL-connection-to-be
66 * We use this struct simply to make it neater passing around host information
67 * when we're creating connections and resolving hosts.
68 * Rather than giving SQLresolver a parameter for every field here so it can in
69 * turn call SQLConn's constructor with them all, both can simply use a SQLhost.
74 std::string id; /* Database handle id */
75 std::string host; /* Database server hostname */
76 unsigned int port; /* Database server port */
77 std::string name; /* Database name */
78 std::string user; /* Database username */
79 std::string pass; /* Database password */
80 bool ssl; /* If we should require SSL */
86 SQLhost(const std::string& i, const std::string& h, unsigned int p, const std::string& n, const std::string& u, const std::string& pa, bool s)
87 : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s)
92 class SQLresolver : public Resolver
98 SQLresolver(ModulePgSQL* m, Server* srv, const SQLhost& hi)
99 : Resolver(ServerInstance, hi.host, DNS_QUERY_FORWARD), host(hi), mod(m)
103 virtual void OnLookupComplete(const std::string &result);
105 virtual void OnError(ResolverError e, const std::string &errormessage)
107 log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
110 virtual ~SQLresolver()
115 /** QueryQueue, a queue of queries waiting to be executed.
116 * This maintains two queues internally, one for 'priority'
117 * queries and one for less important ones. Each queue has
118 * new queries appended to it and ones to execute are popped
119 * off the front. This keeps them flowing round nicely and no
120 * query should ever get 'stuck' for too long. If there are
121 * queries in the priority queue they will be executed first,
122 * 'unimportant' queries will only be executed when the
123 * priority queue is empty.
125 * We store lists of SQLrequest's here, by value as we want to avoid storing
126 * any data allocated inside the client module (in case that module is unloaded
127 * while the query is in progress).
129 * Because we want to work on the current SQLrequest in-situ, we need a way
130 * of accessing the request we are currently processing, QueryQueue::front(),
131 * but that call needs to always return the same request until that request
132 * is removed from the queue, this is what the 'which' variable is. New queries are
133 * always added to the back of one of the two queues, but if when front()
134 * is first called then the priority queue is empty then front() will return
135 * a query from the normal queue, but if a query is then added to the priority
136 * queue then front() must continue to return the front of the *normal* queue
137 * until pop() is called.
140 class QueryQueue : public classbase
143 typedef std::deque<SQLrequest> ReqDeque;
145 ReqDeque priority; /* The priority queue */
146 ReqDeque normal; /* The 'normal' queue */
147 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
155 void push(const SQLrequest &q)
157 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
160 priority.push_back(q);
167 if((which == PRI) && priority.size())
169 priority.pop_front();
171 else if((which == NOR) && normal.size())
179 /* Silently do nothing if there was no element to pop() */
187 return priority.front();
189 return normal.front();
194 return priority.front();
200 return normal.front();
203 /* This will probably result in a segfault,
204 * but the caller should have checked totalsize()
205 * first so..meh - moron :p
208 return priority.front();
212 std::pair<int, int> size()
214 return std::make_pair(priority.size(), normal.size());
219 return priority.size() + normal.size();
222 void PurgeModule(Module* mod)
224 DoPurgeModule(mod, priority);
225 DoPurgeModule(mod, normal);
229 void DoPurgeModule(Module* mod, ReqDeque& q)
231 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
233 if(iter->GetSource() == mod)
235 if(iter->id == front().id)
237 /* It's the currently active query.. :x */
238 iter->SetSource(NULL);
242 /* It hasn't been executed yet..just remove it */
243 iter = q.erase(iter);
250 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
251 * All SQL providers must create their own subclass and define it's methods using that
252 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
253 * of converting all data to a common format before it reaches the result structure. This way
254 * data is passes to the module nearly as directly as if it was using the API directly itself.
257 class PgSQLresult : public SQLresult
264 SQLfieldList* fieldlist;
265 SQLfieldMap* fieldmap;
267 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
268 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
270 rows = PQntuples(res);
271 cols = PQnfields(res);
273 log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
278 /* If we allocated these, free them... */
292 return atoi(PQcmdTuples(res));
302 return PQnfields(res);
305 virtual std::string ColName(int column)
307 char* name = PQfname(res, column);
309 return (name) ? name : "";
312 virtual int ColNum(const std::string &column)
314 int n = PQfnumber(res, column.c_str());
318 throw SQLbadColName();
326 virtual SQLfield GetValue(int row, int column)
328 char* v = PQgetvalue(res, row, column);
332 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
336 log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
337 throw SQLbadColName();
341 virtual SQLfieldList& GetRow()
343 /* In an effort to reduce overhead we don't actually allocate the list
344 * until the first time it's needed...so...
352 fieldlist = new SQLfieldList;
355 if(currentrow < PQntuples(res))
357 int cols = PQnfields(res);
359 for(int i = 0; i < cols; i++)
361 fieldlist->push_back(GetValue(currentrow, i));
370 virtual SQLfieldMap& GetRowMap()
372 /* In an effort to reduce overhead we don't actually allocate the map
373 * until the first time it's needed...so...
381 fieldmap = new SQLfieldMap;
384 if(currentrow < PQntuples(res))
386 int cols = PQnfields(res);
388 for(int i = 0; i < cols; i++)
390 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
399 virtual SQLfieldList* GetRowPtr()
401 SQLfieldList* fl = new SQLfieldList;
403 if(currentrow < PQntuples(res))
405 int cols = PQnfields(res);
407 for(int i = 0; i < cols; i++)
409 fl->push_back(GetValue(currentrow, i));
418 virtual SQLfieldMap* GetRowMapPtr()
420 SQLfieldMap* fm = new SQLfieldMap;
422 if(currentrow < PQntuples(res))
424 int cols = PQnfields(res);
426 for(int i = 0; i < cols; i++)
428 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
437 virtual void Free(SQLfieldMap* fm)
442 virtual void Free(SQLfieldList* fl)
448 /** SQLConn represents one SQL session.
449 * Each session has its own persistent connection to the database.
450 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
451 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
455 class SQLConn : public InspSocket
458 ModulePgSQL* us; /* Pointer to the SQL provider itself */
459 Server* Srv; /* Server* for..uhm..something, maybe */
460 std::string dbhost; /* Database server hostname */
461 unsigned int dbport; /* Database server port */
462 std::string dbname; /* Database name */
463 std::string dbuser; /* Database username */
464 std::string dbpass; /* Database password */
465 bool ssl; /* If we should require SSL */
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 */
474 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
476 SQLConn(InspIRCd* SI, ModulePgSQL* self, Server* srv, const SQLhost& hostinfo);
482 virtual void Close();
486 bool DoConnectedPoll();
492 virtual bool OnDataReady();
494 virtual bool OnWriteReady();
496 virtual bool OnConnected();
502 std::string MkInfoStr();
504 const char* StatusStr();
506 SQLerror DoQuery(SQLrequest &req);
508 SQLerror Query(const SQLrequest &req);
510 void OnUnloadModule(Module* mod);
513 class ModulePgSQL : public Module
518 unsigned long currid;
522 ModulePgSQL(Server* Me)
523 : Module::Module(Me), Srv(Me), currid(0)
525 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
527 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
529 strcpy(sqlsuccess, SQLSUCCESS);
534 void Implements(char* List)
536 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
539 virtual void OnRehash(const std::string ¶meter)
543 /* Delete all the SQLConn objects in the connection lists,
544 * this will call their destructors where they can handle
545 * closing connections and such.
547 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
549 DELETE(iter->second);
552 /* Empty out our list of connections */
555 for(int i = 0; i < conf.Enumerate("database"); i++)
561 host.id = conf.ReadValue("database", "id", i);
562 host.host = conf.ReadValue("database", "hostname", i);
563 host.port = conf.ReadInteger("database", "port", i, true);
564 host.name = conf.ReadValue("database", "name", i);
565 host.user = conf.ReadValue("database", "username", i);
566 host.pass = conf.ReadValue("database", "password", i);
567 host.ssl = conf.ReadFlag("database", "ssl", i);
569 ipvalid = insp_aton(host.host.c_str(), &blargle);
573 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
576 else if(ipvalid == 0)
578 /* Conversion failed, assume it's a host */
579 SQLresolver* resolver;
581 resolver = new SQLresolver(this, Srv, host);
583 Srv->AddResolver(resolver);
587 /* Invalid address family, die horribly. */
588 log(DEBUG, "insp_aton failed returning -1, oh noes.");
593 void AddConn(const SQLhost& hi)
597 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
598 newconn = new SQLConn(ServerInstance, this, Srv, hi);
600 connections.insert(std::make_pair(hi.id, newconn));
603 virtual char* OnRequest(Request* request)
605 if(strcmp(SQLREQID, request->GetId()) == 0)
607 SQLrequest* req = (SQLrequest*)request;
608 ConnMap::iterator iter;
610 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());
612 if((iter = connections.find(req->dbid)) != connections.end())
616 req->error = iter->second->Query(*req);
618 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
622 req->error.Id(BAD_DBID);
627 log(DEBUG, "Got unsupported API version string: %s", request->GetId());
632 virtual void OnUnloadModule(Module* mod, const std::string& name)
634 /* When a module unloads we have to check all the pending queries for all our connections
635 * and set the Module* specifying where the query came from to NULL. If the query has already
636 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
638 * If the queries we find are not already being executed then we can simply remove them immediately.
640 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
642 iter->second->OnUnloadModule(mod);
646 unsigned long NewID()
654 virtual Version GetVersion()
656 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
659 virtual ~ModulePgSQL()
665 SQLConn::SQLConn(InspIRCd* SI, ModulePgSQL* self, Server* srv, const SQLhost& hi)
666 : InspSocket::InspSocket(SI), us(self), Srv(srv), dbhost(hi.host), dbport(hi.port), dbname(hi.name), dbuser(hi.user), dbpass(hi.pass), ssl(hi.ssl), sql(NULL), status(CWRITE), qinprog(false)
668 log(DEBUG, "Creating new PgSQL connection to database %s on %s:%u (%s/%s)", dbname.c_str(), dbhost.c_str(), dbport, dbuser.c_str(), dbpass.c_str());
670 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
671 * just copied this over from the InspSocket constructor.
673 strlcpy(this->host, dbhost.c_str(), MAXBUF);
674 strlcpy(this->IP, dbhost.c_str(), MAXBUF);
678 this->ClosePending = false;
680 log(DEBUG,"No need to resolve %s", this->host);
683 if(!this->DoConnect())
685 throw ModuleException("Connect failed");
694 bool SQLConn::DoConnect()
696 log(DEBUG, "SQLConn::DoConnect()");
698 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
700 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
705 if(PQstatus(sql) == CONNECTION_BAD)
707 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
714 if(PQsetnonblocking(sql, 1) == -1)
716 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
721 /* OK, we've initalised the connection, now to get it hooked into the socket engine
722 * and then start polling it.
725 log(DEBUG, "Old DNS socket: %d", this->fd);
726 this->fd = PQsocket(sql);
727 log(DEBUG, "New SQL socket: %d", this->fd);
731 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
736 this->state = I_CONNECTING;
737 if (!ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
739 log(DEBUG, "A PQsocket cant be added to the socket engine!");
743 Instance->socket_ref[this->fd] = this;
745 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
750 void SQLConn::Close()
752 log(DEBUG,"SQLConn::Close");
755 Instance->socket_ref[this->fd] = NULL;
757 this->state = I_ERROR;
758 this->OnError(I_ERR_SOCKET);
759 this->ClosePending = true;
770 bool SQLConn::DoPoll()
772 switch(PQconnectPoll(sql))
774 case PGRES_POLLING_WRITING:
775 log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
779 case PGRES_POLLING_READING:
780 log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
783 case PGRES_POLLING_FAILED:
784 log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
786 case PGRES_POLLING_OK:
787 log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
789 return DoConnectedPoll();
791 log(DEBUG, "PGconnectPoll: wtf?");
796 bool SQLConn::DoConnectedPoll()
798 if(!qinprog && queue.totalsize())
800 /* There's no query currently in progress, and there's queries in the queue. */
801 SQLrequest& query = queue.front();
805 if(PQconsumeInput(sql))
807 log(DEBUG, "PQconsumeInput succeeded");
809 /* We just read stuff from the server, that counts as it being alive
810 * so update the idle-since time :p
816 log(DEBUG, "Still busy processing command though");
820 log(DEBUG, "Looks like we have a result to process!");
822 /* Grab the request we're processing */
823 SQLrequest& query = queue.front();
825 log(DEBUG, "ID is %lu", query.id);
827 /* Get a pointer to the module we're about to return the result to */
828 Module* to = query.GetSource();
830 /* Fetch the result.. */
831 PGresult* result = PQgetResult(sql);
833 /* PgSQL would allow a query string to be sent which has multiple
834 * queries in it, this isn't portable across database backends and
835 * we don't want modules doing it. But just in case we make sure we
836 * drain any results there are and just use the last one.
837 * If the module devs are behaving there will only be one result.
839 while (PGresult* temp = PQgetResult(sql))
847 /* ..and the result */
848 PgSQLresult reply(us, to, query.id, result);
850 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
852 switch(PQresultStatus(result))
854 case PGRES_EMPTY_QUERY:
855 case PGRES_BAD_RESPONSE:
856 case PGRES_FATAL_ERROR:
857 reply.error.Id(QREPLY_FAIL);
858 reply.error.Str(PQresultErrorMessage(result));
860 /* No action, other values are not errors */
865 /* PgSQLresult's destructor will free the PGresult */
869 /* If the client module is unloaded partway through a query then the provider will set
870 * the pointer to NULL. We cannot just cancel the query as the result will still come
871 * through at some point...and it could get messy if we play with invalid pointers...
873 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);
883 log(DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
890 /* I think we'll assume this means the server died...it might not,
891 * but I think that any error serious enough we actually get here
892 * deserves to reconnect [/excuse]
893 * Returning true so the core doesn't try and close the connection.
895 log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
901 bool SQLConn::DoResetPoll()
903 switch(PQresetPoll(sql))
905 case PGRES_POLLING_WRITING:
906 log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
910 case PGRES_POLLING_READING:
911 log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
914 case PGRES_POLLING_FAILED:
915 log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
917 case PGRES_POLLING_OK:
918 log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
920 return DoConnectedPoll();
922 log(DEBUG, "PGresetPoll: wtf?");
927 void SQLConn::ShowStatus()
929 switch(PQstatus(sql))
931 case CONNECTION_STARTED:
932 log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
935 case CONNECTION_MADE:
936 log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
939 case CONNECTION_AWAITING_RESPONSE:
940 log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
943 case CONNECTION_AUTH_OK:
944 log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
947 case CONNECTION_SSL_STARTUP:
948 log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
951 case CONNECTION_SETENV:
952 log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
956 log(DEBUG, "PQstatus: ???");
960 bool SQLConn::OnDataReady()
962 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
963 log(DEBUG, "OnDataReady(): status = %s", StatusStr());
968 bool SQLConn::OnWriteReady()
970 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
971 log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
976 bool SQLConn::OnConnected()
978 log(DEBUG, "OnConnected(): status = %s", StatusStr());
983 bool SQLConn::Reconnect()
985 log(DEBUG, "Initiating reconnect");
987 if(PQresetStart(sql))
989 /* Successfully initiatied database reconnect,
990 * set flags so PQresetPoll() will be called appropriately
998 log(DEBUG, "Failed to initiate reconnect...fun");
1003 bool SQLConn::DoEvent()
1007 if((status == CREAD) || (status == CWRITE))
1011 else if((status == RREAD) || (status == RWRITE))
1013 ret = DoResetPoll();
1017 ret = DoConnectedPoll();
1020 switch(PQflush(sql))
1023 log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
1026 log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
1029 log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
1037 std::string SQLConn::MkInfoStr()
1039 std::ostringstream conninfo("connect_timeout = '2'");
1042 conninfo << " hostaddr = '" << dbhost << "'";
1045 conninfo << " port = '" << dbport << "'";
1048 conninfo << " dbname = '" << dbname << "'";
1051 conninfo << " user = '" << dbuser << "'";
1054 conninfo << " password = '" << dbpass << "'";
1057 conninfo << " sslmode = 'require'";
1059 return conninfo.str();
1062 const char* SQLConn::StatusStr()
1064 if(status == CREAD) return "CREAD";
1065 if(status == CWRITE) return "CWRITE";
1066 if(status == WREAD) return "WREAD";
1067 if(status == WWRITE) return "WWRITE";
1068 return "Err...what, erm..BUG!";
1071 SQLerror SQLConn::DoQuery(SQLrequest &req)
1073 if((status == WREAD) || (status == WWRITE))
1077 /* Parse the command string and dispatch it */
1079 /* Pointer to the buffer we screw around with substitution in */
1081 /* Pointer to the current end of query, where we append new stuff */
1083 /* Total length of the unescaped parameters */
1084 unsigned int paramlen;
1088 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
1090 paramlen += i->size();
1093 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
1094 * sizeofquery + (totalparamlength*2) + 1
1096 * The +1 is for null-terminating the string for PQsendQuery()
1099 query = new char[req.query.q.length() + (paramlen*2)];
1102 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
1103 * the parameters into it...
1106 for(unsigned int i = 0; i < req.query.q.length(); i++)
1108 if(req.query.q[i] == '?')
1110 /* We found a place to substitute..what fun.
1111 * Use the PgSQL calls to escape and write the
1112 * escaped string onto the end of our query buffer,
1113 * then we "just" need to make sure queryend is
1114 * pointing at the right place.
1117 if(req.query.p.size())
1122 #ifdef PGSQL_HAS_ESCAPECONN
1123 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
1125 len = PQescapeStringConn(queryend, req.query.p.front().c_str(), req.query.p.front().length());
1131 log(DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
1134 log(DEBUG, "Appended %d bytes of escaped string onto the query", len);
1136 /* Incremenet queryend to the end of the newly escaped parameter */
1139 /* Remove the parameter we just substituted in */
1140 req.query.p.pop_front();
1144 log(DEBUG, "Found a substitution location but no parameter to substitute :|");
1150 *queryend = req.query.q[i];
1155 /* Null-terminate the query */
1158 log(DEBUG, "Attempting to dispatch query: %s", query);
1160 req.query.q = query;
1162 if(PQsendQuery(sql, query))
1164 log(DEBUG, "Dispatched query successfully");
1171 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1173 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1178 log(DEBUG, "Can't query until connection is complete");
1179 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1182 SQLerror SQLConn::Query(const SQLrequest &req)
1186 if(!qinprog && queue.totalsize())
1188 /* There's no query currently in progress, and there's queries in the queue. */
1189 SQLrequest& query = queue.front();
1190 return DoQuery(query);
1198 void SQLConn::OnUnloadModule(Module* mod)
1200 queue.PurgeModule(mod);
1203 void SQLresolver::OnLookupComplete(const std::string &result)
1209 class ModulePgSQLFactory : public ModuleFactory
1212 ModulePgSQLFactory()
1216 ~ModulePgSQLFactory()
1220 virtual Module * CreateModule(Server* Me)
1222 return new ModulePgSQL(Me);
1227 extern "C" void * init_module( void )
1229 return new ModulePgSQLFactory;