]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_pgsql.cpp
Updates, should be able to safely unload client modules with queries in progress...
[user/henk/code/inspircd.git] / src / modules / extra / m_pgsql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd is copyright (C) 2002-2004 ChatSpike-Dev.
6  *                       E-mail:
7  *                <brain@chatspike.net>
8  *                <Craig@chatspike.net>
9  *                <omster@gmail.com>
10  *     
11  * Written by Craig Edwards, Craig McLure, and others.
12  * This program is free but copyrighted software; see
13  *            the file COPYING for details.
14  *
15  * ---------------------------------------------------
16  */
17
18 #include <sstream>
19 #include <string>
20 #include <deque>
21 #include <map>
22 #include <libpq-fe.h>
23
24 #include "users.h"
25 #include "channels.h"
26 #include "modules.h"
27 #include "helperfuncs.h"
28 #include "inspircd.h"
29 #include "configreader.h"
30
31 #include "m_sqlv2.h"
32
33 /* $ModDesc: PostgreSQL Service Provider module for all other m_sql* modules, uses v2 of the SQL API */
34 /* $CompileFlags: -I`pg_config --includedir` */
35 /* $LinkerFlags: -L`pg_config --libdir` -lpq */
36
37 /* UGH, UGH, UGH, UGH, UGH, UGH
38  * I'm having trouble seeing how I
39  * can avoid this. The core-defined
40  * constructors for InspSocket just
41  * aren't suitable...and if I'm
42  * reimplementing them I need this so
43  * I can access the socket engine :\
44  */
45 extern InspIRCd* ServerInstance;
46 InspSocket* socket_ref[MAX_DESCRIPTORS];
47
48 /* Forward declare, so we can have the typedef neatly at the top */
49 class SQLConn;
50 /* Also needs forward declaration, as it's used inside SQLconn */
51 class ModulePgSQL;
52
53 typedef std::map<std::string, SQLConn*> ConnMap;
54
55 /* CREAD,       Connecting and wants read event
56  * CWRITE,      Connecting and wants write event
57  * WREAD,       Connected/Working and wants read event
58  * WWRITE,      Connected/Working and wants write event
59  */
60 enum SQLstatus { CREAD, CWRITE, WREAD, WWRITE };
61
62 /** QueryQueue, a queue of queries waiting to be executed.
63  * This maintains two queues internally, one for 'priority'
64  * queries and one for less important ones. Each queue has
65  * new queries appended to it and ones to execute are popped
66  * off the front. This keeps them flowing round nicely and no
67  * query should ever get 'stuck' for too long. If there are
68  * queries in the priority queue they will be executed first,
69  * 'unimportant' queries will only be executed when the
70  * priority queue is empty.
71  *
72  * We store lists of SQLrequest's here, by value as we want to avoid storing
73  * any data allocated inside the client module (in case that module is unloaded
74  * while the query is in progress).
75  *
76  * Because we want to work on the current SQLrequest in-situ, we need a way
77  * of accessing the request we are currently processing, QueryQueue::front(),
78  * but that call needs to always return the same request until that request
79  * is removed from the queue, this is what the 'which' variable is. New queries are
80  * always added to the back of one of the two queues, but if when front()
81  * is first called then the priority queue is empty then front() will return
82  * a query from the normal queue, but if a query is then added to the priority
83  * queue then front() must continue to return the front of the *normal* queue
84  * until pop() is called.
85  */
86
87 class QueryQueue : public classbase
88 {
89 private:
90         typedef std::deque<SQLrequest> ReqDeque;        
91
92         ReqDeque priority;      /* The priority queue */
93         ReqDeque normal;        /* The 'normal' queue */
94         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
95
96 public:
97         QueryQueue()
98         : which(NON)
99         {
100         }
101         
102         void push(const SQLrequest &q)
103         {
104                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.c_str());
105                 
106                 if(q.pri)
107                         priority.push_back(q);
108                 else
109                         normal.push_back(q);
110         }
111         
112         void pop()
113         {
114                 if((which == PRI) && priority.size())
115                 {
116                         priority.pop_front();
117                 }
118                 else if((which == NOR) && normal.size())
119                 {
120                         normal.pop_front();
121                 }
122                 
123                 /* Reset this */
124                 which = NON;
125                 
126                 /* Silently do nothing if there was no element to pop() */
127         }
128         
129         SQLrequest& front()
130         {
131                 switch(which)
132                 {
133                         case PRI:
134                                 return priority.front();
135                         case NOR:
136                                 return normal.front();
137                         default:
138                                 if(priority.size())
139                                 {
140                                         which = PRI;
141                                         return priority.front();
142                                 }
143                                 
144                                 if(normal.size())
145                                 {
146                                         which = NOR;
147                                         return normal.front();
148                                 }
149                                 
150                                 /* This will probably result in a segfault,
151                                  * but the caller should have checked totalsize()
152                                  * first so..meh - moron :p
153                                  */
154                                 
155                                 return priority.front();
156                 }
157         }
158         
159         std::pair<int, int> size()
160         {
161                 return std::make_pair(priority.size(), normal.size());
162         }
163         
164         int totalsize()
165         {
166                 return priority.size() + normal.size();
167         }
168         
169         void PurgeModule(Module* mod)
170         {
171                 DoPurgeModule(mod, priority);
172                 DoPurgeModule(mod, normal);
173         }
174         
175 private:
176         void DoPurgeModule(Module* mod, ReqDeque& q)
177         {
178                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
179                 {
180                         if(iter->GetSource() == mod)
181                         {
182                                 if(iter->id == front().id)
183                                 {
184                                         /* It's the currently active query.. :x */
185                                         iter->SetSource(NULL);
186                                 }
187                                 else
188                                 {
189                                         /* It hasn't been executed yet..just remove it */
190                                         iter = q.erase(iter);
191                                 }
192                         }
193                 }
194         }
195 };
196
197 /** PgSQLresult is a subclass of the mostly-pure-virtual class SQLresult.
198  * All SQL providers must create their own subclass and define it's methods using that
199  * database library's data retriveal functions. The aim is to avoid a slow and inefficient process
200  * of converting all data to a common format before it reaches the result structure. This way
201  * data is passes to the module nearly as directly as if it was using the API directly itself.
202  */
203
204 class PgSQLresult : public SQLresult
205 {
206         PGresult* res;
207         int currentrow;
208         
209         SQLfieldList* fieldlist;
210         SQLfieldMap* fieldmap;
211 public:
212         PgSQLresult(Module* self, Module* to, PGresult* result)
213         : SQLresult(self, to), res(result), currentrow(0), fieldlist(NULL), fieldmap(NULL)
214         {
215                 int rows = PQntuples(res);
216                 int cols = PQnfields(res);
217                 
218                 log(DEBUG, "Created new PgSQL result; %d rows, %d columns", rows, cols);
219         }
220         
221         ~PgSQLresult()
222         {
223                 PQclear(res);
224         }
225         
226         virtual int Rows()
227         {
228                 return PQntuples(res);
229         }
230         
231         virtual int Cols()
232         {
233                 return PQnfields(res);
234         }
235         
236         virtual std::string ColName(int column)
237         {
238                 char* name = PQfname(res, column);
239                 
240                 return (name) ? name : "";
241         }
242         
243         virtual int ColNum(const std::string &column)
244         {
245                 int n = PQfnumber(res, column.c_str());
246                 
247                 if(n == -1)
248                 {
249                         throw SQLbadColName();
250                 }
251                 else
252                 {
253                         return n;
254                 }
255         }
256         
257         virtual SQLfield GetValue(int row, int column)
258         {
259                 char* v = PQgetvalue(res, row, column);
260                 
261                 if(v)
262                 {
263                         return SQLfield(std::string(v, PQgetlength(res, row, column)), PQgetisnull(res, row, column));
264                 }
265                 else
266                 {
267                         log(DEBUG, "PQgetvalue returned a null pointer..nobody wants to tell us what this means");
268                         throw SQLbadColName();
269                 }
270         }
271         
272         virtual SQLfieldList& GetRow()
273         {
274                 /* In an effort to reduce overhead we don't actually allocate the list
275                  * until the first time it's needed...so...
276                  */
277                 if(fieldlist)
278                 {
279                         fieldlist->clear();
280                 }
281                 else
282                 {
283                         fieldlist = new SQLfieldList;
284                 }
285                 
286                 if(currentrow < PQntuples(res))
287                 {
288                         int cols = PQnfields(res);
289                         
290                         for(int i = 0; i < cols; i++)
291                         {
292                                 fieldlist->push_back(GetValue(currentrow, i));
293                         }
294                         
295                         currentrow++;
296                 }
297                 
298                 return *fieldlist;
299         }
300         
301         virtual SQLfieldMap& GetRowMap()
302         {
303                 /* In an effort to reduce overhead we don't actually allocate the map
304                  * until the first time it's needed...so...
305                  */
306                 if(fieldmap)
307                 {
308                         fieldmap->clear();
309                 }
310                 else
311                 {
312                         fieldmap = new SQLfieldMap;
313                 }
314                 
315                 if(currentrow < PQntuples(res))
316                 {
317                         int cols = PQnfields(res);
318                         
319                         for(int i = 0; i < cols; i++)
320                         {
321                                 fieldmap->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
322                         }
323                         
324                         currentrow++;
325                 }
326                 
327                 return *fieldmap;
328         }
329         
330         virtual SQLfieldList* GetRowPtr()
331         {
332                 SQLfieldList* fl = new SQLfieldList;
333                 
334                 if(currentrow < PQntuples(res))
335                 {
336                         int cols = PQnfields(res);
337                         
338                         for(int i = 0; i < cols; i++)
339                         {
340                                 fl->push_back(GetValue(currentrow, i));
341                         }
342                         
343                         currentrow++;
344                 }
345                 
346                 return fl;
347         }
348         
349         virtual SQLfieldMap* GetRowMapPtr()
350         {
351                 SQLfieldMap* fm = new SQLfieldMap;
352                 
353                 if(currentrow < PQntuples(res))
354                 {
355                         int cols = PQnfields(res);
356                         
357                         for(int i = 0; i < cols; i++)
358                         {
359                                 fm->insert(std::make_pair(ColName(i), GetValue(currentrow, i)));
360                         }
361                         
362                         currentrow++;
363                 }
364                 
365                 return fm;
366         }
367         
368         virtual void Free(SQLfieldMap* fm)
369         {
370                 DELETE(fm);
371         }
372         
373         virtual void Free(SQLfieldList* fl)
374         {
375                 DELETE(fl);
376         }
377 };
378
379 /** SQLConn represents one SQL session.
380  * Each session has its own persistent connection to the database.
381  * This is a subclass of InspSocket so it can easily recieve read/write events from the core socket
382  * engine, unlike the original MySQL module this module does not block. Ever. It gets a mild stabbing
383  * if it dares to.
384  */
385
386 class SQLConn : public InspSocket
387 {
388 private:
389         ModulePgSQL* us;                /* Pointer to the SQL provider itself */
390         Server* Srv;                    /* Server* for..uhm..something, maybe */
391         std::string     dbhost; /* Database server hostname */
392         unsigned int    dbport; /* Database server port */
393         std::string     dbname; /* Database name */
394         std::string     dbuser; /* Database username */
395         std::string     dbpass; /* Database password */
396         bool                    ssl;    /* If we should require SSL */
397         PGconn*                 sql;    /* PgSQL database connection handle */
398         SQLstatus               status; /* PgSQL database connection status */
399         bool                    qinprog;/* If there is currently a query in progress */
400         QueryQueue              queue;  /* Queue of queries waiting to be executed on this connection */
401
402 public:
403
404         /* This class should only ever be created inside this module, using this constructor, so we don't have to worry about the default ones */
405
406         SQLConn(ModulePgSQL* self, Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s);
407
408         ~SQLConn();
409
410         bool DoResolve();
411
412         bool DoConnect();
413
414         virtual void Close();
415         
416         bool DoPoll();
417         
418         bool DoConnectedPoll();
419         
420         void ShowStatus();      
421         
422         virtual bool OnDataReady();
423
424         virtual bool OnWriteReady();
425         
426         virtual bool OnConnected();
427         
428         bool DoEvent();
429         
430         std::string MkInfoStr();
431         
432         const char* StatusStr();
433         
434         SQLerror DoQuery(const SQLrequest &req);
435         
436         SQLerror Query(const SQLrequest &req);
437         
438         void OnUnloadModule(Module* mod);
439 };
440
441 class ModulePgSQL : public Module
442 {
443 private:
444         Server* Srv;
445         ConnMap connections;
446         unsigned long currid;
447         char* sqlsuccess;
448
449 public:
450         ModulePgSQL(Server* Me)
451         : Module::Module(Me), Srv(Me), currid(0)
452         {
453                 log(DEBUG, "%s 'SQL' feature", Srv->PublishFeature("SQL", this) ? "Published" : "Couldn't publish");
454                 log(DEBUG, "%s 'PgSQL' feature", Srv->PublishFeature("PgSQL", this) ? "Published" : "Couldn't publish");
455                 
456                 sqlsuccess = new char[strlen(SQLSUCCESS)+1];
457                 
458                 strcpy(sqlsuccess, SQLSUCCESS);
459
460                 OnRehash("");
461         }
462
463         void Implements(char* List)
464         {
465                 List[I_OnUnloadModule] = List[I_OnRequest] = List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnUserDisconnect] = 1;
466         }
467
468         virtual void OnRehash(const std::string &parameter)
469         {
470                 ConfigReader conf;
471                 
472                 /* Delete all the SQLConn objects in the connection lists,
473                  * this will call their destructors where they can handle
474                  * closing connections and such.
475                  */
476                 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
477                 {
478                         DELETE(iter->second);
479                 }
480                 
481                 /* Empty out our list of connections */
482                 connections.clear();
483
484                 for(int i = 0; i < conf.Enumerate("database"); i++)
485                 {
486                         std::string id;
487                         SQLConn* newconn;
488                         
489                         id = conf.ReadValue("database", "id", i);
490                         newconn = new SQLConn(this, Srv,
491                                                                                 conf.ReadValue("database", "hostname", i),
492                                                                                 conf.ReadInteger("database", "port", i, true),
493                                                                                 conf.ReadValue("database", "name", i),
494                                                                                 conf.ReadValue("database", "username", i),
495                                                                                 conf.ReadValue("database", "password", i),
496                                                                                 conf.ReadFlag("database", "ssl", i));
497                         
498                         connections.insert(std::make_pair(id, newconn));
499                 }       
500         }
501         
502         virtual char* OnRequest(Request* request)
503         {
504                 if(strcmp(SQLREQID, request->GetData()) == 0)
505                 {
506                         SQLrequest* req = (SQLrequest*)request;
507                         ConnMap::iterator iter;
508                 
509                         log(DEBUG, "Got query: '%s' on id '%s'", req->query.c_str(), req->dbid.c_str());
510
511                         if((iter = connections.find(req->dbid)) != connections.end())
512                         {
513                                 /* Execute query */
514                                 req->error = iter->second->Query(*req);
515                                 req->id = NewID();
516                                 
517                                 return (req->error.Id() == NO_ERROR) ? sqlsuccess : NULL;
518                         }
519                         else
520                         {
521                                 req->error.Id(BAD_DBID);
522                                 return NULL;
523                         }
524                 }
525
526                 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
527                 
528                 return NULL;
529         }
530         
531         virtual void OnUnloadModule(Module* mod, const std::string&     name)
532         {
533                 /* When a module unloads we have to check all the pending queries for all our connections
534                  * and set the Module* specifying where the query came from to NULL. If the query has already
535                  * been dispatched then when it is processed it will be dropped if the pointer is NULL.
536                  *
537                  * If the queries we find are not already being executed then we can simply remove them immediately.
538                  */
539                 for(ConnMap::iterator iter = connections.begin(); iter != connections.end(); iter++)
540                 {
541                         
542                 }
543         }
544
545         unsigned long NewID()
546         {
547                 if (currid+1 == 0)
548                         currid++;
549                 
550                 return ++currid;
551         }
552                 
553         virtual Version GetVersion()
554         {
555                 return Version(1, 0, 0, 0, VF_VENDOR|VF_SERVICEPROVIDER);
556         }
557         
558         virtual ~ModulePgSQL()
559         {
560                 DELETE(sqlsuccess);
561         }       
562 };
563
564 SQLConn::SQLConn(ModulePgSQL* self, Server* srv, const std::string &h, unsigned int p, const std::string &d, const std::string &u, const std::string &pwd, bool s)
565 : InspSocket::InspSocket(), us(self), Srv(srv), dbhost(h), dbport(p), dbname(d), dbuser(u), dbpass(pwd), ssl(s), sql(NULL), status(CWRITE), qinprog(false)
566 {
567         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());
568
569         /* Some of this could be reviewed, unsure if I need to fill 'host' etc...
570          * just copied this over from the InspSocket constructor.
571          */
572         strlcpy(this->host, dbhost.c_str(), MAXBUF);
573         this->port = dbport;
574         
575         this->ClosePending = false;
576         
577         if(!inet_aton(this->host, &this->addy))
578         {
579                 /* Its not an ip, spawn the resolver.
580                  * PgSQL doesn't do nonblocking DNS 
581                  * lookups, so we do it for it.
582                  */
583                 
584                 log(DEBUG,"Attempting to resolve %s", this->host);
585                 
586                 this->dns.SetNS(Srv->GetConfig()->DNSServer);
587                 this->dns.ForwardLookupWithFD(this->host, fd);
588                 
589                 this->state = I_RESOLVING;
590                 socket_ref[this->fd] = this;
591                 
592                 return;
593         }
594         else
595         {
596                 log(DEBUG,"No need to resolve %s", this->host);
597                 strlcpy(this->IP, this->host, MAXBUF);
598                 
599                 if(!this->DoConnect())
600                 {
601                         throw ModuleException("Connect failed");
602                 }
603         }
604 }
605
606 SQLConn::~SQLConn()
607 {
608         Close();
609 }
610
611 bool SQLConn::DoResolve()
612 {       
613         log(DEBUG, "Checking for DNS lookup result");
614         
615         if(this->dns.HasResult())
616         {
617                 std::string res_ip = dns.GetResultIP();
618                 
619                 if(res_ip.length())
620                 {
621                         log(DEBUG, "Got result: %s", res_ip.c_str());
622                         
623                         strlcpy(this->IP, res_ip.c_str(), MAXBUF);
624                         dbhost = res_ip;
625                         
626                         socket_ref[this->fd] = NULL;
627                         
628                         return this->DoConnect();
629                 }
630                 else
631                 {
632                         log(DEBUG, "DNS lookup failed, dying horribly");
633                         Close();
634                         return false;
635                 }
636         }
637         else
638         {
639                 log(DEBUG, "No result for lookup yet!");
640                 return true;
641         }
642 }
643
644 bool SQLConn::DoConnect()
645 {
646         log(DEBUG, "SQLConn::DoConnect()");
647         
648         if(!(sql = PQconnectStart(MkInfoStr().c_str())))
649         {
650                 log(DEBUG, "Couldn't allocate PGconn structure, aborting: %s", PQerrorMessage(sql));
651                 Close();
652                 return false;
653         }
654         
655         if(PQstatus(sql) == CONNECTION_BAD)
656         {
657                 log(DEBUG, "PQconnectStart failed: %s", PQerrorMessage(sql));
658                 Close();
659                 return false;
660         }
661         
662         ShowStatus();
663         
664         if(PQsetnonblocking(sql, 1) == -1)
665         {
666                 log(DEBUG, "Couldn't set connection nonblocking: %s", PQerrorMessage(sql));
667                 Close();
668                 return false;
669         }
670         
671         /* OK, we've initalised the connection, now to get it hooked into the socket engine
672          * and then start polling it.
673          */
674         
675         log(DEBUG, "Old DNS socket: %d", this->fd);
676         this->fd = PQsocket(sql);
677         log(DEBUG, "New SQL socket: %d", this->fd);
678         
679         if(this->fd <= -1)
680         {
681                 log(DEBUG, "PQsocket says we have an invalid FD: %d", this->fd);
682                 Close();
683                 return false;
684         }
685         
686         this->state = I_CONNECTING;
687         ServerInstance->SE->AddFd(this->fd,false,X_ESTAB_MODULE);
688         socket_ref[this->fd] = this;
689         
690         /* Socket all hooked into the engine, now to tell PgSQL to start connecting */
691         
692         return DoPoll();
693 }
694
695 void SQLConn::Close()
696 {
697         log(DEBUG,"SQLConn::Close");
698         
699         if(this->fd > 01)
700                 socket_ref[this->fd] = NULL;
701         this->fd = -1;
702         this->state = I_ERROR;
703         this->OnError(I_ERR_SOCKET);
704         this->ClosePending = true;
705         
706         if(sql)
707         {
708                 PQfinish(sql);
709                 sql = NULL;
710         }
711         
712         return;
713 }
714
715 bool SQLConn::DoPoll()
716 {
717         switch(PQconnectPoll(sql))
718         {
719                 case PGRES_POLLING_WRITING:
720                         log(DEBUG, "PGconnectPoll: PGRES_POLLING_WRITING");
721                         WantWrite();
722                         status = CWRITE;
723                         return DoPoll();
724                 case PGRES_POLLING_READING:
725                         log(DEBUG, "PGconnectPoll: PGRES_POLLING_READING");
726                         status = CREAD;
727                         break;
728                 case PGRES_POLLING_FAILED:
729                         log(DEBUG, "PGconnectPoll: PGRES_POLLING_FAILED: %s", PQerrorMessage(sql));
730                         return false;
731                 case PGRES_POLLING_OK:
732                         log(DEBUG, "PGconnectPoll: PGRES_POLLING_OK");
733                         status = WWRITE;
734                         return DoConnectedPoll();
735                 default:
736                         log(DEBUG, "PGconnectPoll: wtf?");
737                         break;
738         }
739         
740         return true;
741 }
742
743 bool SQLConn::DoConnectedPoll()
744 {
745         if(!qinprog && queue.totalsize())
746         {
747                 /* There's no query currently in progress, and there's queries in the queue. */
748                 SQLrequest& query = queue.front();
749                 DoQuery(query);
750         }
751         
752         if(PQconsumeInput(sql))
753         {
754                 log(DEBUG, "PQconsumeInput succeeded");
755                         
756                 if(PQisBusy(sql))
757                 {
758                         log(DEBUG, "Still busy processing command though");
759                 }
760                 else if(qinprog)
761                 {
762                         log(DEBUG, "Looks like we have a result to process!");
763                         
764                         /* Grab the request we're processing */
765                         SQLrequest& query = queue.front();
766                         
767                         /* Get a pointer to the module we're about to return the result to */
768                         Module* to = query.GetSource();
769                         
770                         /* Fetch the result.. */
771                         PGresult* result = PQgetResult(sql);
772                         
773                         /* PgSQL would allow a query string to be sent which has multiple
774                          * queries in it, this isn't portable across database backends and
775                          * we don't want modules doing it. But just in case we make sure we
776                          * drain any results there are and just use the last one.
777                          * If the module devs are behaving there will only be one result.
778                          */
779                         while (PGresult* temp = PQgetResult(sql))
780                         {
781                                 PQclear(result);
782                                 result = temp;
783                         }
784                         
785                         if(to)
786                         {
787                                 /* ..and the result */
788                                 log(DEBUG, "Got result, status code: %s; error message: %s", PQresStatus(PQresultStatus(result)), PQresultErrorMessage(result));
789                                         
790                                 PgSQLresult reply(us, to, result);
791                                 
792                                 reply.Send();
793                                 
794                                 /* PgSQLresult's destructor will free the PGresult */
795                         }
796                         else
797                         {
798                                 /* If the client module is unloaded partway through a query then the provider will set
799                                  * the pointer to NULL. We cannot just cancel the query as the result will still come
800                                  * through at some point...and it could get messy if we play with invalid pointers...
801                                  */
802                                 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);
803                                 PQclear(result);
804                         }
805                         
806                         qinprog = false;
807                         queue.pop();                            
808                         DoConnectedPoll();
809                 }
810                 
811                 return true;
812         }
813         
814         log(DEBUG, "PQconsumeInput failed: %s", PQerrorMessage(sql));
815         return false;
816 }
817
818 void SQLConn::ShowStatus()
819 {
820         switch(PQstatus(sql))
821         {
822                 case CONNECTION_STARTED:
823                         log(DEBUG, "PQstatus: CONNECTION_STARTED: Waiting for connection to be made.");
824                         break;
825
826                 case CONNECTION_MADE:
827                         log(DEBUG, "PQstatus: CONNECTION_MADE: Connection OK; waiting to send.");
828                         break;
829                 
830                 case CONNECTION_AWAITING_RESPONSE:
831                         log(DEBUG, "PQstatus: CONNECTION_AWAITING_RESPONSE: Waiting for a response from the server.");
832                         break;
833                 
834                 case CONNECTION_AUTH_OK:
835                         log(DEBUG, "PQstatus: CONNECTION_AUTH_OK: Received authentication; waiting for backend start-up to finish.");
836                         break;
837                 
838                 case CONNECTION_SSL_STARTUP:
839                         log(DEBUG, "PQstatus: CONNECTION_SSL_STARTUP: Negotiating SSL encryption.");
840                         break;
841                 
842                 case CONNECTION_SETENV:
843                         log(DEBUG, "PQstatus: CONNECTION_SETENV: Negotiating environment-driven parameter settings.");
844                         break;
845                 
846                 default:
847                         log(DEBUG, "PQstatus: ???");
848         }
849 }
850
851 bool SQLConn::OnDataReady()
852 {
853         /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
854         log(DEBUG, "OnDataReady(): status = %s", StatusStr());
855         
856         return DoEvent();
857 }
858
859 bool SQLConn::OnWriteReady()
860 {
861         /* Always return true here, false would close the socket - we need to do that ourselves with the pgsql API */
862         log(DEBUG, "OnWriteReady(): status = %s", StatusStr());
863         
864         return DoEvent();
865 }
866
867 bool SQLConn::OnConnected()
868 {
869         log(DEBUG, "OnConnected(): status = %s", StatusStr());
870         
871         return DoEvent();
872 }
873
874 bool SQLConn::DoEvent()
875 {
876         bool ret;
877         
878         if((status == CREAD) || (status == CWRITE))
879         {
880                 ret = DoPoll();
881         }
882         else
883         {
884                 ret = DoConnectedPoll();
885         }
886         
887         switch(PQflush(sql))
888         {
889                 case -1:
890                         log(DEBUG, "Error flushing write queue: %s", PQerrorMessage(sql));
891                         break;
892                 case 0:
893                         log(DEBUG, "Successfully flushed write queue (or there was nothing to write)");
894                         break;
895                 case 1:
896                         log(DEBUG, "Not all of the write queue written, triggering write event so we can have another go");
897                         WantWrite();
898                         break;
899         }
900
901         return ret;
902 }
903
904 std::string SQLConn::MkInfoStr()
905 {                       
906         std::ostringstream conninfo("connect_timeout = '2'");
907         
908         if(dbhost.length())
909                 conninfo << " hostaddr = '" << dbhost << "'";
910         
911         if(dbport)
912                 conninfo << " port = '" << dbport << "'";
913         
914         if(dbname.length())
915                 conninfo << " dbname = '" << dbname << "'";
916         
917         if(dbuser.length())
918                 conninfo << " user = '" << dbuser << "'";
919         
920         if(dbpass.length())
921                 conninfo << " password = '" << dbpass << "'";
922         
923         if(ssl)
924                 conninfo << " sslmode = 'require'";
925         
926         return conninfo.str();
927 }
928
929 const char* SQLConn::StatusStr()
930 {
931         if(status == CREAD) return "CREAD";
932         if(status == CWRITE) return "CWRITE";
933         if(status == WREAD) return "WREAD";
934         if(status == WWRITE) return "WWRITE";
935         return "Err...what, erm..BUG!";
936 }
937
938 SQLerror SQLConn::DoQuery(const SQLrequest &req)
939 {
940         if((status == WREAD) || (status == WWRITE))
941         {
942                 if(!qinprog)
943                 {
944                         if(PQsendQuery(sql, req.query.c_str()))
945                         {
946                                 log(DEBUG, "Dispatched query: %s", req.query.c_str());
947                                 qinprog = true;
948                                 return SQLerror();
949                         }
950                         else
951                         {
952                                 log(DEBUG, "Failed to dispatch query: %s", PQerrorMessage(sql));
953                                 return SQLerror(QSEND_FAIL, PQerrorMessage(sql));
954                         }
955                 }
956         }
957
958         log(DEBUG, "Can't query until connection is complete");
959         return SQLerror(BAD_CONN, "Can't query until connection is complete");
960 }
961
962 SQLerror SQLConn::Query(const SQLrequest &req)
963 {
964         queue.push(req);
965         
966         if(!qinprog && queue.totalsize())
967         {
968                 /* There's no query currently in progress, and there's queries in the queue. */
969                 SQLrequest& query = queue.front();
970                 return DoQuery(query);
971         }
972         else
973         {
974                 return SQLerror();
975         }
976 }
977
978 void SQLConn::OnUnloadModule(Module* mod)
979 {
980         queue.PurgeModule(mod);
981 }
982
983 class ModulePgSQLFactory : public ModuleFactory
984 {
985  public:
986         ModulePgSQLFactory()
987         {
988         }
989         
990         ~ModulePgSQLFactory()
991         {
992         }
993         
994         virtual Module * CreateModule(Server* Me)
995         {
996                 return new ModulePgSQL(Me);
997         }
998 };
999
1000
1001 extern "C" void * init_module( void )
1002 {
1003         return new ModulePgSQLFactory;
1004 }