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 :\
47 /* Forward declare, so we can have the typedef neatly at the top */
49 /* Also needs forward declaration, as it's used inside SQLconn */
52 typedef std::map<std::string, SQLConn*> ConnMap;
54 /* CREAD, Connecting and wants read event
55 * CWRITE, Connecting and wants write event
56 * WREAD, Connected/Working and wants read event
57 * WWRITE, Connected/Working and wants write event
58 * RREAD, Resetting and wants read event
59 * RWRITE, Resetting and wants write event
61 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE, RREAD, RWRITE };
63 /** SQLhost, simple structure to store information about a SQL-connection-to-be
64 * We use this struct simply to make it neater passing around host information
65 * when we're creating connections and resolving hosts.
66 * Rather than giving SQLresolver a parameter for every field here so it can in
67 * turn call SQLConn's constructor with them all, both can simply use a SQLhost.
72 std::string id; /* Database handle id */
73 std::string host; /* Database server hostname */
74 unsigned int port; /* Database server port */
75 std::string name; /* Database name */
76 std::string user; /* Database username */
77 std::string pass; /* Database password */
78 bool ssl; /* If we should require SSL */
84 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)
85 : id(i), host(h), port(p), name(n), user(u), pass(pa), ssl(s)
90 class SQLresolver : public Resolver
96 SQLresolver(ModulePgSQL* m, InspIRCd* Instance, const SQLhost& hi)
97 : Resolver(Instance, hi.host, DNS_QUERY_FORWARD), host(hi), mod(m)
101 virtual void OnLookupComplete(const std::string &result);
103 virtual void OnError(ResolverError e, const std::string &errormessage)
105 log(DEBUG, "DNS lookup failed (%s), dying horribly", errormessage.c_str());
108 virtual ~SQLresolver()
113 /** QueryQueue, a queue of queries waiting to be executed.
114 * This maintains two queues internally, one for 'priority'
115 * queries and one for less important ones. Each queue has
116 * new queries appended to it and ones to execute are popped
117 * off the front. This keeps them flowing round nicely and no
118 * query should ever get 'stuck' for too long. If there are
119 * queries in the priority queue they will be executed first,
120 * 'unimportant' queries will only be executed when the
121 * priority queue is empty.
123 * We store lists of SQLrequest's here, by value as we want to avoid storing
124 * any data allocated inside the client module (in case that module is unloaded
125 * while the query is in progress).
127 * Because we want to work on the current SQLrequest in-situ, we need a way
128 * of accessing the request we are currently processing, QueryQueue::front(),
129 * but that call needs to always return the same request until that request
130 * is removed from the queue, this is what the 'which' variable is. New queries are
131 * always added to the back of one of the two queues, but if when front()
132 * is first called then the priority queue is empty then front() will return
133 * a query from the normal queue, but if a query is then added to the priority
134 * queue then front() must continue to return the front of the *normal* queue
135 * until pop() is called.
138 class QueryQueue : public classbase
141 typedef std::deque<SQLrequest> ReqDeque;
143 ReqDeque priority; /* The priority queue */
144 ReqDeque normal; /* The 'normal' queue */
145 enum { PRI, NOR, NON } which; /* Which queue the currently active element is at the front of */
153 void push(const SQLrequest &q)
155 //log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
158 priority.push_back(q);
165 if((which == PRI) && priority.size())
167 priority.pop_front();
169 else if((which == NOR) && normal.size())
177 /* Silently do nothing if there was no element to pop() */
185 return priority.front();
187 return normal.front();
192 return priority.front();
198 return normal.front();
201 /* This will probably result in a segfault,
202 * but the caller should have checked totalsize()
203 * first so..meh - moron :p
206 return priority.front();
210 std::pair<int, int> size()
212 return std::make_pair(priority.size(), normal.size());
217 return priority.size() + normal.size();
220 void PurgeModule(Module* mod)
222 DoPurgeModule(mod, priority);
223 DoPurgeModule(mod, normal);
227 void DoPurgeModule(Module* mod, ReqDeque& q)
229 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
231 if(iter->GetSource() == mod)
233 if(iter->id == front().id)
235 /* It's the currently active query.. :x */
236 iter->SetSource(NULL);
240 /* It hasn't been executed yet..just remove it */
241 iter = q.erase(iter);
248 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
249 * All SQL providers must create their own subclass and define it's methods using that
250 * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
251 * of converting all data to a common format before it reaches the result structure. This way
252 * data is passes to the module nearly as directly as if it was using the API directly itself.
255 class PgSQLresult : public SQLresult
262 SQLfieldList* fieldlist;
263 SQLfieldMap* fieldmap;
265 PgSQLresult(Module* self, Module* to, unsigned long id, PGresult* result)
266 : SQLresult(self, to, id), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
268 rows = PQntuples(res);
269 cols = PQnfields(res);
271 //log(DEBUG, "Created new PgSQL result; %d rows, %d columns, %s affected", rows, cols, PQcmdTuples(res));
276 /* If we allocated these, free them... */
290 return atoi(PQcmdTuples(res));
300 return PQnfields(res);
303 virtual std::string ColName(int column)
305 char* name = PQfname(res, column);
307 return (name) ? name : "";
310 virtual int ColNum(const std::string &column)
312 int n = PQfnumber(res, column.c_str());
316 throw SQLbadColName();
324 virtual SQLfield GetValue(int row, int column)
326 char* v = PQgetvalue(res, row, column);
330 return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
334 //log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
335 throw SQLbadColName();
339 virtual SQLfieldList& GetRow()
341 /* In an effort to reduce overhead we don't actually allocate the list
342 * until the first time it's needed...so...
350 fieldlist = new SQLfieldList;
353 if(currentrow < PQntuples(res))
355 int cols = PQnfields(res);
357 for(int i = 0; i < cols; i++)
359 fieldlist->push_back(GetValue(currentrow, i));
368 virtual SQLfieldMap& GetRowMap()
370 /* In an effort to reduce overhead we don't actually allocate the map
371 * until the first time it's needed...so...
379 fieldmap = new SQLfieldMap;
382 if(currentrow < PQntuples(res))
384 int cols = PQnfields(res);
386 for(int i = 0; i < cols; i++)
388 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
397 virtual SQLfieldList* GetRowPtr()
399 SQLfieldList* fl = new SQLfieldList;
401 if(currentrow < PQntuples(res))
403 int cols = PQnfields(res);
405 for(int i = 0; i < cols; i++)
407 fl->push_back(GetValue(currentrow, i));
416 virtual SQLfieldMap* GetRowMapPtr()
418 SQLfieldMap* fm = new SQLfieldMap;
420 if(currentrow < PQntuples(res))
422 int cols = PQnfields(res);
424 for(int i = 0; i < cols; i++)
426 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
435 virtual void Free(SQLfieldMap* fm)
440 virtual void Free(SQLfieldList* fl)
446 /** SQLConn represents one SQL session.
447 * Each session has its own persistent connection to the database.
448 * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
449 * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
453 class SQLConn : public InspSocket
456 ModulePgSQL* us; /* Pointer to the SQL provider itself */
457 std::string dbhost; /* Database server hostname */
458 unsigned int dbport; /* Database server port */
459 std::string dbname; /* Database name */
460 std::string dbuser; /* Database username */
461 std::string dbpass; /* Database password */
462 bool ssl; /* If we should require SSL */
463 PGconn* sql; /* PgSQL database connection handle */
464 SQLstatus status; /* PgSQL database connection status */
465 bool qinprog;/* If there is currently a query in progress */
466 QueryQueue queue; /* Queue of queries waiting to be executed on this connection */
467 time_t idle; /* Time we last heard from the database */
471 /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
473 SQLConn(InspIRCd* SI, ModulePgSQL* self, const SQLhost& hostinfo);
479 virtual void Close();
483 bool DoConnectedPoll();
489 virtual bool OnDataReady();
491 virtual bool OnWriteReady();
493 virtual bool OnConnected();
499 std::string MkInfoStr();
501 const char* StatusStr();
503 SQLerror DoQuery(SQLrequest &req);
505 SQLerror Query(const SQLrequest &req);
507 void OnUnloadModule(Module* mod);
510 class ModulePgSQL : public Module
515 unsigned long currid;
519 ModulePgSQL(InspIRCd* Me)
520 : Module::Module(Me), currid(0)
522 log(DEBUG, "%s 'SQL' feature", ServerInstance->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
524 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
526 strcpy(sqlsuccess, SQLSUCCESS);
531 void Implements(char* List)
533 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
536 virtual void OnRehash(const std::string ¶meter)
538 ConfigReader conf(ServerInstance);
540 /* Delete all the SQLConn objects in the connection lists,
541 * this will call their destructors where they can handle
542 * closing connections and such.
544 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
546 DELETE(iter->second);
549 /* Empty out our list of connections */
552 for(int i = 0; i < conf.Enumerate("database"); i++)
558 host.id = conf.ReadValue("database", "id", i);
559 host.host = conf.ReadValue("database", "hostname", i);
560 host.port = conf.ReadInteger("database", "port", i, true);
561 host.name = conf.ReadValue("database", "name", i);
562 host.user = conf.ReadValue("database", "username", i);
563 host.pass = conf.ReadValue("database", "password", i);
564 host.ssl = conf.ReadFlag("database", "ssl", i);
566 ipvalid = insp_aton(host.host.c_str(), &blargle);
570 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
573 else if(ipvalid == 0)
575 /* Conversion failed, assume it's a host */
576 SQLresolver* resolver;
578 resolver = new SQLresolver(this, ServerInstance, host);
580 ServerInstance->AddResolver(resolver);
584 /* Invalid address family, die horribly. */
585 log(DEBUG, "insp_aton failed returning -1, oh noes.");
590 void AddConn(const SQLhost& hi)
594 /* The conversion succeeded, we were given an IP and we can give it straight to SQLConn */
595 newconn = new SQLConn(ServerInstance, this, hi);
597 connections.insert(std::make_pair(hi.id, newconn));
600 virtual char* OnRequest(Request* request)
602 if(strcmp(SQLREQID, request->GetId()) == 0)
604 SQLrequest* req = (SQLrequest*)request;
605 ConnMap::iterator iter;
607 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());
609 if((iter = connections.find(req->dbid)) != connections.end())
613 req->error = iter->second->Query(*req);
615 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
619 req->error.Id(BAD_DBID);
624 log(DEBUG, "Got unsupported API version string: %s", request->GetId());
629 virtual void OnUnloadModule(Module* mod, const std::string& name)
631 /* When a module unloads we have to check all the pending queries for all our connections
632 * and set the Module* specifying where the query came from to NULL. If the query has already
633 * been dispatched then when it is processed it will be dropped if the pointer is NULL.
635 * If the queries we find are not already being executed then we can simply remove them immediately.
637 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
639 iter->second->OnUnloadModule(mod);
643 unsigned long NewID()
651 virtual Version GetVersion()
653 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
656 virtual ~ModulePgSQL()
662 SQLConn::SQLConn(InspIRCd* SI, ModulePgSQL* self, const SQLhost& hi)
663 : InspSocket::InspSocket(SI), us(self), dbhost(hi.host), dbport(hi.port), dbname(hi.name), dbuser(hi.user), dbpass(hi.pass), ssl(hi.ssl), sql(NULL), status(CWRITE), qinprog(false)
665 //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());
667 /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
668 * just copied this over from the InspSocket constructor.
670 strlcpy(this->host, dbhost.c_str(), MAXBUF);
671 strlcpy(this->IP, dbhost.c_str(), MAXBUF);
673 idle = this->Instance->Time();
675 this->ClosePending = false;
677 ilog(Instance,DEBUG,"No need to resolve %s", this->host);
680 if(!this->DoConnect())
682 throw ModuleException("Connect failed");
691 bool SQLConn::DoConnect()
693 //log(DEBUG, "SQLConn::DoConnect()");
695 if(!(sql = PQconnectStart(MkInfoStr().c_str())))
697 ilog(Instance,DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
702 if(PQstatus(sql) == CONNECTION_BAD)
704 ilog(Instance,DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
711 if(PQsetnonblocking(sql, 1) == -1)
713 ilog(Instance,DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
718 /* OK, we've initalised the connection, now to get it hooked into the socket engine
719 * and then start polling it.
722 //log(DEBUG, "Old DNS socket: %d", this->fd);
723 this->fd = PQsocket(sql);
724 ilog(Instance,DEBUG, "New SQL socket: %d", this->fd);
728 ilog(Instance,DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
733 this->state = I_CONNECTING;
734 if (!this->Instance->SE->AddFd(this->fd,false,X_ESTAB_MODULE))
736 ilog(Instance,DEBUG, "A PQsocket cant be added to the socket engine!");
740 this->Instance->socket_ref[this->fd] = this;
742 /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
747 void SQLConn::Close()
749 ilog(Instance,DEBUG,"SQLConn::Close");
752 Instance->socket_ref[this->fd] = NULL;
754 this->state = I_ERROR;
755 this->OnError(I_ERR_SOCKET);
756 this->ClosePending = true;
767 bool SQLConn::DoPoll()
769 switch(PQconnectPoll(sql))
771 case PGRES_POLLING_WRITING:
772 //log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
776 case PGRES_POLLING_READING:
777 //log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
780 case PGRES_POLLING_FAILED:
781 //log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
783 case PGRES_POLLING_OK:
784 //log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
786 return DoConnectedPoll();
788 //log(DEBUG, "PGconnectPoll: wtf?");
793 bool SQLConn::DoConnectedPoll()
795 if(!qinprog && queue.totalsize())
797 /* There's no query currently in progress, and there's queries in the queue. */
798 SQLrequest& query = queue.front();
802 if(PQconsumeInput(sql))
804 ilog(Instance,DEBUG, "PQconsumeInput succeeded");
806 /* We just read stuff from the server, that counts as it being alive
807 * so update the idle-since time :p
809 idle = this->Instance->Time();
813 //log(DEBUG, "Still busy processing command though");
817 //log(DEBUG, "Looks like we have a result to process!");
819 /* Grab the request we're processing */
820 SQLrequest& query = queue.front();
822 ilog(Instance,DEBUG, "ID is %lu", query.id);
824 /* Get a pointer to the module we're about to return the result to */
825 Module* to = query.GetSource();
827 /* Fetch the result.. */
828 PGresult* result = PQgetResult(sql);
830 /* PgSQL would allow a query string to be sent which has multiple
831 * queries in it, this isn't portable across database backends and
832 * we don't want modules doing it. But just in case we make sure we
833 * drain any results there are and just use the last one.
834 * If the module devs are behaving there will only be one result.
836 while (PGresult* temp = PQgetResult(sql))
844 /* ..and the result */
845 PgSQLresult reply(us, to, query.id, result);
847 ilog(Instance,DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
849 switch(PQresultStatus(result))
851 case PGRES_EMPTY_QUERY:
852 case PGRES_BAD_RESPONSE:
853 case PGRES_FATAL_ERROR:
854 reply.error.Id(QREPLY_FAIL);
855 reply.error.Str(PQresultErrorMessage(result));
857 /* No action, other values are not errors */
862 /* PgSQLresult's destructor will free the PGresult */
866 /* If the client module is unloaded partway through a query then the provider will set
867 * the pointer to NULL. We cannot just cancel the query as the result will still come
868 * through at some point...and it could get messy if we play with invalid pointers...
870 ilog(Instance,DEBUG, "Looks like we're handling a zombie query from a module which unloaded before it got a result..fun. ID: %lu", query.id);
880 ilog(Instance,DEBUG, "Eh!? We just got a read event, and connection isn't busy..but no result :(");
887 /* I think we'll assume this means the server died...it might not,
888 * but I think that any error serious enough we actually get here
889 * deserves to reconnect [/excuse]
890 * Returning true so the core doesn't try and close the connection.
892 ilog(Instance,DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
898 bool SQLConn::DoResetPoll()
900 switch(PQresetPoll(sql))
902 case PGRES_POLLING_WRITING:
903 //log(DEBUG, "PGresetPoll: PGRES_POLLING_WRITING");
907 case PGRES_POLLING_READING:
908 //log(DEBUG, "PGresetPoll: PGRES_POLLING_READING");
911 case PGRES_POLLING_FAILED:
912 //log(DEBUG, "PGresetPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
914 case PGRES_POLLING_OK:
915 //log(DEBUG, "PGresetPoll: PGRES_POLLING_OK");
917 return DoConnectedPoll();
919 //log(DEBUG, "PGresetPoll: wtf?");
924 void SQLConn::ShowStatus()
926 switch(PQstatus(sql))
928 case CONNECTION_STARTED:
929 ilog(Instance,DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
932 case CONNECTION_MADE:
933 ilog(Instance,DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
936 case CONNECTION_AWAITING_RESPONSE:
937 ilog(Instance,DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
940 case CONNECTION_AUTH_OK:
941 ilog(Instance,DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
944 case CONNECTION_SSL_STARTUP:
945 ilog(Instance,DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
948 case CONNECTION_SETENV:
949 ilog(Instance,DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
953 ilog(Instance,DEBUG, "PQstatus: ???");
957 bool SQLConn::OnDataReady()
959 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
960 ilog(Instance,DEBUG, "OnDataReady(): status = %s", StatusStr());
965 bool SQLConn::OnWriteReady()
967 /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
968 ilog(Instance,DEBUG, "OnWriteReady(): status = %s", StatusStr());
973 bool SQLConn::OnConnected()
975 ilog(Instance,DEBUG, "OnConnected(): status = %s", StatusStr());
980 bool SQLConn::Reconnect()
982 ilog(Instance,DEBUG, "Initiating reconnect");
984 if(PQresetStart(sql))
986 /* Successfully initiatied database reconnect,
987 * set flags so PQresetPoll() will be called appropriately
995 ilog(Instance,DEBUG, "Failed to initiate reconnect...fun");
1000 bool SQLConn::DoEvent()
1004 if((status == CREAD) || (status == CWRITE))
1008 else if((status == RREAD) || (status == RWRITE))
1010 ret = DoResetPoll();
1014 ret = DoConnectedPoll();
1017 switch(PQflush(sql))
1020 ilog(Instance,DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
1023 ilog(Instance,DEBUG, "Successfully flushed write queue (or there was nothing to write)");
1026 ilog(Instance,DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
1034 std::string SQLConn::MkInfoStr()
1036 std::ostringstream conninfo("connect_timeout = '2'");
1039 conninfo << " hostaddr = '" << dbhost << "'";
1042 conninfo << " port = '" << dbport << "'";
1045 conninfo << " dbname = '" << dbname << "'";
1048 conninfo << " user = '" << dbuser << "'";
1051 conninfo << " password = '" << dbpass << "'";
1054 conninfo << " sslmode = 'require'";
1056 return conninfo.str();
1059 const char* SQLConn::StatusStr()
1061 if(status == CREAD) return "CREAD";
1062 if(status == CWRITE) return "CWRITE";
1063 if(status == WREAD) return "WREAD";
1064 if(status == WWRITE) return "WWRITE";
1065 return "Err...what, erm..BUG!";
1068 SQLerror SQLConn::DoQuery(SQLrequest &req)
1070 if((status == WREAD) || (status == WWRITE))
1074 /* Parse the command string and dispatch it */
1076 /* Pointer to the buffer we screw around with substitution in */
1078 /* Pointer to the current end of query, where we append new stuff */
1080 /* Total length of the unescaped parameters */
1081 unsigned int paramlen;
1085 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
1087 paramlen += i->size();
1090 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
1091 * sizeofquery + (totalparamlength*2) + 1
1093 * The +1 is for null-terminating the string for PQsendQuery()
1096 query = new char[req.query.q.length() + (paramlen*2)];
1099 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
1100 * the parameters into it...
1103 for(unsigned int i = 0; i < req.query.q.length(); i++)
1105 if(req.query.q[i] == '?')
1107 /* We found a place to substitute..what fun.
1108 * Use the PgSQL calls to escape and write the
1109 * escaped string onto the end of our query buffer,
1110 * then we "just" need to make sure queryend is
1111 * pointing at the right place.
1114 if(req.query.p.size())
1119 #ifdef PGSQL_HAS_ESCAPECONN
1120 len = PQescapeStringConn(sql, queryend, req.query.p.front().c_str(), req.query.p.front().length(), &error);
1122 len = PQescapeStringConn(queryend, req.query.p.front().c_str(), req.query.p.front().length());
1127 ilog(Instance,DEBUG, "Apparently PQescapeStringConn() failed somehow...don't know how or what to do...");
1130 ilog(Instance,DEBUG, "Appended %d bytes of escaped string onto the query", len);
1132 /* Incremenet queryend to the end of the newly escaped parameter */
1135 /* Remove the parameter we just substituted in */
1136 req.query.p.pop_front();
1140 ilog(Instance,DEBUG, "Found a substitution location but no parameter to substitute :|");
1146 *queryend = req.query.q[i];
1151 /* Null-terminate the query */
1154 ilog(Instance,DEBUG, "Attempting to dispatch query: %s", query);
1156 req.query.q = query;
1158 if(PQsendQuery(sql, query))
1160 ilog(Instance,DEBUG, "Dispatched query successfully");
1167 ilog(Instance,DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
1169 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
1174 ilog(Instance,DEBUG, "Can't query until connection is complete");
1175 return SQLerror(BAD_CONN, "Can't query until connection is complete");
1178 SQLerror SQLConn::Query(const SQLrequest &req)
1182 if(!qinprog && queue.totalsize())
1184 /* There's no query currently in progress, and there's queries in the queue. */
1185 SQLrequest& query = queue.front();
1186 return DoQuery(query);
1194 void SQLConn::OnUnloadModule(Module* mod)
1196 queue.PurgeModule(mod);
1199 void SQLresolver::OnLookupComplete(const std::string &result)
1205 class ModulePgSQLFactory : public ModuleFactory
1208 ModulePgSQLFactory()
1212 ~ModulePgSQLFactory()
1216 virtual Module * CreateModule(InspIRCd* Me)
1218 return new ModulePgSQL(Me);
1223 extern "C" void * init_module( void )
1225 return new ModulePgSQLFactory;