]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Error checking and debug
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.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  *     
10  * Written by Craig Edwards, Craig McLure, and others.
11  * This program is free but copyrighted software; see
12  *          the file COPYING for details.
13  *
14  * ---------------------------------------------------
15  */
16
17 using namespace std;
18
19 #include <stdio.h>
20 #include <string>
21 #include <mysql.h>
22 #include <pthread.h>
23 #include "users.h"
24 #include "channels.h"
25 #include "modules.h"
26 #include "helperfuncs.h"
27 #include "m_sqlv2.h"
28
29 /* VERSION 2 API: With nonblocking (threaded) requests */
30
31 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
32 /* $CompileFlags: `mysql_config --include` */
33 /* $LinkerFlags: `mysql_config --libs_r` `perl ../mysql_rpath.pl` */
34
35
36 class SQLConnection;
37 class Notifier;
38
39 extern InspIRCd* ServerInstance;
40 typedef std::map<std::string, SQLConnection*> ConnMap;
41 bool giveup = false;
42 static Module* SQLModule = NULL;
43 static Notifier* MessagePipe = NULL;
44 int QueueFD = -1;
45
46
47 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
48 #define mysql_field_count mysql_num_fields
49 #endif
50
51 typedef std::deque<SQLresult*> ResultQueue;
52
53 class QueryQueue : public classbase
54 {
55 private:
56         typedef std::deque<SQLrequest> ReqDeque;
57
58         ReqDeque priority;      /* The priority queue */
59         ReqDeque normal;        /* The 'normal' queue */
60         enum { PRI, NOR, NON } which;   /* Which queue the currently active element is at the front of */
61
62 public:
63         QueryQueue()
64         : which(NON)
65         {
66         }
67
68         void push(const SQLrequest &q)
69         {
70                 log(DEBUG, "QueryQueue::push(): Adding %s query to queue: %s", ((q.pri) ? "priority" : "non-priority"), q.query.q.c_str());
71
72                 if(q.pri)
73                         priority.push_back(q);
74                 else
75                         normal.push_back(q);
76         }
77
78         void pop()
79         {
80                 if((which == PRI) && priority.size())
81                 {
82                         priority.pop_front();
83                 }
84                 else if((which == NOR) && normal.size())
85                 {
86                         normal.pop_front();
87                 }
88
89                 /* Reset this */
90                 which = NON;
91
92                 /* Silently do nothing if there was no element to pop() */
93         }
94
95         SQLrequest& front()
96         {
97                 switch(which)
98                 {
99                         case PRI:
100                                 return priority.front();
101                         case NOR:
102                                 return normal.front();
103                         default:
104                                 if(priority.size())
105                                 {
106                                         which = PRI;
107                                         return priority.front();
108                                 }
109
110                                 if(normal.size())
111                                 {
112                                         which = NOR;
113                                         return normal.front();
114                                 }
115
116                                 /* This will probably result in a segfault,
117                                  * but the caller should have checked totalsize()
118                                  * first so..meh - moron :p
119                                  */
120
121                                 return priority.front();
122                 }
123         }
124
125         std::pair<int, int> size()
126         {
127                 return std::make_pair(priority.size(), normal.size());
128         }
129
130         int totalsize()
131         {
132                 return priority.size() + normal.size();
133         }
134
135         void PurgeModule(Module* mod)
136         {
137                 DoPurgeModule(mod, priority);
138                 DoPurgeModule(mod, normal);
139         }
140
141 private:
142         void DoPurgeModule(Module* mod, ReqDeque& q)
143         {
144                 for(ReqDeque::iterator iter = q.begin(); iter != q.end(); iter++)
145                 {
146                         if(iter->GetSource() == mod)
147                         {
148                                 if(iter->id == front().id)
149                                 {
150                                         /* It's the currently active query.. :x */
151                                         iter->SetSource(NULL);
152                                 }
153                                 else
154                                 {
155                                         /* It hasn't been executed yet..just remove it */
156                                         iter = q.erase(iter);
157                                 }
158                         }
159                 }
160         }
161 };
162
163 /* A mutex to wrap around queue accesses */
164 pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
165
166 pthread_mutex_t results_mutex = PTHREAD_MUTEX_INITIALIZER;
167
168 class MySQLresult : public SQLresult
169 {
170         int currentrow;
171         //std::vector<std::map<std::string,std::string> > results;
172         std::vector<std::string> colnames;
173         std::vector<SQLfieldList> fieldlists;
174         SQLfieldMap* fieldmap;
175         int rows;
176         int cols;
177  public:
178
179         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows) : SQLresult(self, to), currentrow(0), fieldmap(NULL)
180         {
181                 /* A number of affected rows from from mysql_affected_rows.
182                  */
183                 log(DEBUG,"Created new MySQLresult of non-error type");
184                 fieldlists.clear();
185                 rows = affected_rows;
186                 fieldlists.resize(rows);
187                 unsigned int field_count;
188                 if (res)
189                 {
190                         MYSQL_ROW row;
191                         int n = 0;
192                         while ((row = mysql_fetch_row(res)))
193                         {
194                                 field_count = 0;
195                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
196                                 if(mysql_num_fields(res) == 0)
197                                         break;
198                                 if (fields && mysql_num_fields(res))
199                                 {
200                                         colnames.clear();
201                                         while (field_count < mysql_num_fields(res))
202                                         {
203                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
204                                                 std::string b = (row[field_count] ? row[field_count] : "");
205                                                 SQLfield sqlf(a, !row[field_count]);
206                                                 colnames.push_back(a);
207                                                 fieldlists[n].push_back(sqlf); 
208                                                 field_count++;
209                                         }
210                                         n++;
211                                 }
212                         }
213                         cols = mysql_num_fields(res);
214                         mysql_free_result(res);
215                 }
216                 cols = field_count;
217                 log(DEBUG, "Created new MySQL result; %d rows, %d columns", rows, cols);
218         }
219
220         MySQLresult(Module* self, Module* to, SQLerror e) : SQLresult(self, to), currentrow(0)
221         {
222                 rows = 0;
223                 cols = 0;
224                 error = e;
225                 log(DEBUG,"Created new MySQLresult of error type");
226         }
227
228         ~MySQLresult()
229         {
230         }
231
232         virtual int Rows()
233         {
234                 return rows;
235         }
236
237         virtual int Cols()
238         {
239                 return cols;
240         }
241
242         virtual std::string ColName(int column)
243         {
244                 if (column < (int)colnames.size())
245                 {
246                         return colnames[column];
247                 }
248                 else
249                 {
250                         throw SQLbadColName();
251                 }
252                 return "";
253         }
254
255         virtual int ColNum(const std::string &column)
256         {
257                 for (unsigned int i = 0; i < colnames.size(); i++)
258                 {
259                         if (column == colnames[i])
260                                 return i;
261                 }
262                 throw SQLbadColName();
263                 return 0;
264         }
265
266         virtual SQLfield GetValue(int row, int column)
267         {
268                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < cols))
269                 {
270                         return fieldlists[row][column];
271                 }
272
273                 log(DEBUG,"Danger will robinson, we don't have row %d, column %d!", row, column);
274                 throw SQLbadColName();
275
276                 /* XXX: We never actually get here because of the throw */
277                 return SQLfield("",true);
278         }
279
280         virtual SQLfieldList& GetRow()
281         {
282                 return fieldlists[currentrow];
283         }
284
285         virtual SQLfieldMap& GetRowMap()
286         {
287                 fieldmap = new SQLfieldMap();
288                 
289                 for (int i = 0; i < cols; i++)
290                 {
291                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
292                 }
293                 currentrow++;
294
295                 return *fieldmap;
296         }
297
298         virtual SQLfieldList* GetRowPtr()
299         {
300                 return &fieldlists[currentrow++];
301         }
302
303         virtual SQLfieldMap* GetRowMapPtr()
304         {
305                 fieldmap = new SQLfieldMap();
306
307                 for (int i = 0; i < cols; i++)
308                 {
309                         fieldmap->insert(std::make_pair(colnames[cols],GetValue(currentrow, i)));
310                 }
311                 currentrow++;
312
313                 return fieldmap;
314         }
315
316         virtual void Free(SQLfieldMap* fm)
317         {
318                 delete fm;
319         }
320
321         virtual void Free(SQLfieldList* fl)
322         {
323                 /* XXX: Yes, this is SUPPOSED to do nothing, we
324                  * dont want to free our fieldlist until we
325                  * destruct the object. Unlike the pgsql module,
326                  * we only have the one.
327                  */
328         }
329 };
330
331 class SQLConnection;
332
333 void NotifyMainThread(SQLConnection* connection_with_new_result);
334
335 class SQLConnection : public classbase
336 {
337  protected:
338
339         MYSQL connection;
340         MYSQL_RES *res;
341         MYSQL_ROW row;
342         std::string host;
343         std::string user;
344         std::string pass;
345         std::string db;
346         std::map<std::string,std::string> thisrow;
347         bool Enabled;
348         std::string id;
349
350  public:
351
352         QueryQueue queue;
353         ResultQueue rq;
354
355         // This constructor creates an SQLConnection object with the given credentials, and creates the underlying
356         // MYSQL struct, but does not connect yet.
357         SQLConnection(std::string thishost, std::string thisuser, std::string thispass, std::string thisdb, const std::string &myid)
358         {
359                 this->Enabled = true;
360                 this->host = thishost;
361                 this->user = thisuser;
362                 this->pass = thispass;
363                 this->db = thisdb;
364                 this->id = myid;
365         }
366
367         // This method connects to the database using the credentials supplied to the constructor, and returns
368         // true upon success.
369         bool Connect()
370         {
371                 unsigned int timeout = 1;
372                 mysql_init(&connection);
373                 mysql_options(&connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
374                 return mysql_real_connect(&connection, host.c_str(), user.c_str(), pass.c_str(), db.c_str(), 0, NULL, 0);
375         }
376
377         void DoLeadingQuery()
378         {
379                 /* Parse the command string and dispatch it to mysql */
380                 SQLrequest& req = queue.front();
381                 log(DEBUG,"DO QUERY: %s",req.query.q.c_str());
382
383                 /* Pointer to the buffer we screw around with substitution in */
384                 char* query;
385
386                 /* Pointer to the current end of query, where we append new stuff */
387                 char* queryend;
388
389                 /* Total length of the unescaped parameters */
390                 unsigned long paramlen;
391
392                 /* Total length of query, used for binary-safety in mysql_real_query */
393                 unsigned long querylength = 0;
394
395                 paramlen = 0;
396
397                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
398                 {
399                         paramlen += i->size();
400                 }
401
402                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
403                  * sizeofquery + (totalparamlength*2) + 1
404                  *
405                  * The +1 is for null-terminating the string for mysql_real_escape_string
406                  */
407
408                 query = new char[req.query.q.length() + (paramlen*2)];
409                 queryend = query;
410
411                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
412                  * the parameters into it...
413                  */
414
415                 for(unsigned long i = 0; i < req.query.q.length(); i++)
416                 {
417                         if(req.query.q[i] == '?')
418                         {
419                                 /* We found a place to substitute..what fun.
420                                  * use mysql calls to escape and write the
421                                  * escaped string onto the end of our query buffer,
422                                  * then we "just" need to make sure queryend is
423                                  * pointing at the right place.
424                                  */
425                                 if(req.query.p.size())
426                                 {
427                                         unsigned long len = mysql_real_escape_string(&connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
428
429                                         queryend += len;
430                                         req.query.p.pop_front();
431                                 }
432                                 else
433                                 {
434                                         log(DEBUG, "Found a substitution location but no parameter to substitute :|");
435                                         break;
436                                 }
437                         }
438                         else
439                         {
440                                 *queryend = req.query.q[i];
441                                 queryend++;
442                         }
443                         querylength++;
444                 }
445
446                 *queryend = 0;
447
448                 log(DEBUG, "Attempting to dispatch query: %s", query);
449
450                 pthread_mutex_lock(&queue_mutex);
451                 req.query.q = std::string(query,querylength);
452                 pthread_mutex_unlock(&queue_mutex);
453
454                 if (!mysql_real_query(&connection, req.query.q.data(), req.query.q.length()))
455                 {
456                         /* Successfull query */
457                         res = mysql_use_result(&connection);
458                         unsigned long rows = mysql_affected_rows(&connection);
459                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), res, rows);
460                         r->dbid = this->GetID();
461                         r->query = req.query.q;
462                         /* Put this new result onto the results queue.
463                          * XXX: Remember to mutex the queue!
464                          */
465                         pthread_mutex_lock(&results_mutex);
466                         rq.push_back(r);
467                         pthread_mutex_unlock(&results_mutex);
468                 }
469                 else
470                 {
471                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
472                          * possible error numbers and error messages */
473                         SQLerror e((SQLerrorNum)mysql_errno(&connection), mysql_error(&connection));
474                         MySQLresult* r = new MySQLresult(SQLModule, req.GetSource(), e);
475                         r->dbid = this->GetID();
476                         r->query = req.query.q;
477
478                         pthread_mutex_lock(&results_mutex);
479                         rq.push_back(r);
480                         pthread_mutex_unlock(&results_mutex);
481                 }
482
483                 /* Now signal the main thread that we've got a result to process.
484                  * Pass them this connection id as what to examine
485                  */
486
487                 NotifyMainThread(this);
488         }
489
490         bool ConnectionLost()
491         {
492                 if (&connection) {
493                         return (mysql_ping(&connection) != 0);
494                 }
495                 else return false;
496         }
497
498         bool CheckConnection()
499         {
500                 if (ConnectionLost()) {
501                         return Connect();
502                 }
503                 else return true;
504         }
505
506         std::string GetError()
507         {
508                 return mysql_error(&connection);
509         }
510
511         const std::string& GetID()
512         {
513                 return id;
514         }
515
516         std::string GetHost()
517         {
518                 return host;
519         }
520
521         void SetEnable(bool Enable)
522         {
523                 Enabled = Enable;
524         }
525
526         bool IsEnabled()
527         {
528                 return Enabled;
529         }
530
531 };
532
533 ConnMap Connections;
534
535 void ConnectDatabases(Server* Srv)
536 {
537         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
538         {
539                 i->second->SetEnable(true);
540                 if (i->second->Connect())
541                 {
542                         Srv->Log(DEFAULT,"SQL: Successfully connected database "+i->second->GetHost());
543                 }
544                 else
545                 {
546                         Srv->Log(DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
547                         i->second->SetEnable(false);
548                 }
549         }
550 }
551
552
553 void LoadDatabases(ConfigReader* ThisConf, Server* Srv)
554 {
555         Srv->Log(DEFAULT,"SQL: Loading database settings");
556         Connections.clear();
557         Srv->Log(DEBUG,"Cleared connections");
558         for (int j =0; j < ThisConf->Enumerate("database"); j++)
559         {
560                 std::string db = ThisConf->ReadValue("database","name",j);
561                 std::string user = ThisConf->ReadValue("database","username",j);
562                 std::string pass = ThisConf->ReadValue("database","password",j);
563                 std::string host = ThisConf->ReadValue("database","hostname",j);
564                 std::string id = ThisConf->ReadValue("database","id",j);
565                 Srv->Log(DEBUG,"Read database settings");
566                 if ((db != "") && (host != "") && (user != "") && (id != "") && (pass != ""))
567                 {
568                         SQLConnection* ThisSQL = new SQLConnection(host,user,pass,db,id);
569                         Srv->Log(DEFAULT,"Loaded database: "+ThisSQL->GetHost());
570                         Connections[id] = ThisSQL;
571                         Srv->Log(DEBUG,"Pushed back connection");
572                 }
573         }
574         ConnectDatabases(Srv);
575 }
576
577 void NotifyMainThread(SQLConnection* connection_with_new_result)
578 {
579         /* Here we write() to the socket the main thread has open
580          * and we connect()ed back to before our thread became active.
581          * The main thread is using a nonblocking socket tied into
582          * the socket engine, so they wont block and they'll receive
583          * nearly instant notification. Because we're in a seperate
584          * thread, we can just use standard connect(), and we can
585          * block if we like. We just send the connection id of the
586          * connection back.
587          */
588         log(DEBUG,"Notify of result on connection: %s",connection_with_new_result->GetID().c_str());
589         if (send(QueueFD, connection_with_new_result->GetID().c_str(), connection_with_new_result->GetID().length()+1, 0) < 1) // add one for null terminator
590         {
591                 log(DEBUG,"Error writing to QueueFD: %s",strerror(errno));
592         }
593         log(DEBUG,"Sent it on its way via fd=%d",QueueFD);
594 }
595
596 void* DispatcherThread(void* arg);
597
598 class Notifier : public InspSocket
599 {
600         sockaddr_in sock_us;
601         socklen_t uslen;
602         Server* Srv;
603
604  public:
605
606         /* Create a socket on a random port. Let the tcp stack allocate us an available port */
607         Notifier(Server* S) : InspSocket("127.0.0.1", 0, true, 3000), Srv(S)
608         {
609                 uslen = sizeof(sock_us);
610                 if (getsockname(this->fd,(sockaddr*)&sock_us,&uslen))
611                 {
612                         throw ModuleException("Could not create random listening port on localhost");
613                 }
614         }
615
616         Notifier(int newfd, char* ip, Server* S) : InspSocket(newfd, ip), Srv(S)
617         {
618                 log(DEBUG,"Constructor of new socket");
619         }
620
621         /* Using getsockname and ntohs, we can determine which port number we were allocated */
622         int GetPort()
623         {
624                 return ntohs(sock_us.sin_port);
625         }
626
627         virtual int OnIncomingConnection(int newsock, char* ip)
628         {
629                 log(DEBUG,"Inbound connection on fd %d!",newsock);
630                 Notifier* n = new Notifier(newsock, ip, Srv);
631                 Srv->AddSocket(n);
632                 return true;
633         }
634
635         virtual bool OnDataReady()
636         {
637                 log(DEBUG,"Inbound data!");
638                 char* data = this->Read();
639                 ConnMap::iterator iter;
640
641                 if (data && *data)
642                 {
643                         log(DEBUG,"Looking for connection %s",data);
644                         /* We expect to be sent a null terminated string */
645                         if((iter = Connections.find(data)) != Connections.end())
646                         {
647                                 log(DEBUG,"Found it!");
648
649                                 /* Lock the mutex, send back the data */
650                                 pthread_mutex_lock(&results_mutex);
651                                 ResultQueue::iterator n = iter->second->rq.begin();
652                                 (*n)->Send();
653                                 iter->second->rq.pop_front();
654                                 pthread_mutex_unlock(&results_mutex);
655                                 return true;
656                         }
657                 }
658
659                 return false;
660         }
661 };
662
663 class ModuleSQL : public Module
664 {
665  public:
666         Server *Srv;
667         ConfigReader *Conf;
668         pthread_t Dispatcher;
669         int currid;
670
671         void Implements(char* List)
672         {
673                 List[I_OnRehash] = List[I_OnRequest] = 1;
674         }
675
676         unsigned long NewID()
677         {
678                 if (currid+1 == 0)
679                         currid++;
680                 return ++currid;
681         }
682
683         char* OnRequest(Request* request)
684         {
685                 if(strcmp(SQLREQID, request->GetData()) == 0)
686                 {
687                         SQLrequest* req = (SQLrequest*)request;
688
689                         /* XXX: Lock */
690                         pthread_mutex_lock(&queue_mutex);
691
692                         ConnMap::iterator iter;
693
694                         char* returnval = NULL;
695
696                         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());
697
698                         if((iter = Connections.find(req->dbid)) != Connections.end())
699                         {
700                                 iter->second->queue.push(*req);
701                                 req->id = NewID();
702                                 returnval = SQLSUCCESS;
703                         }
704                         else
705                         {
706                                 req->error.Id(BAD_DBID);
707                         }
708
709                         pthread_mutex_unlock(&queue_mutex);
710                         /* XXX: Unlock */
711
712                         return returnval;
713                 }
714
715                 log(DEBUG, "Got unsupported API version string: %s", request->GetData());
716
717                 return NULL;
718         }
719
720         ModuleSQL(Server* Me)
721                 : Module::Module(Me)
722         {
723                 Srv = Me;
724                 Conf = new ConfigReader();
725                 currid = 0;
726                 SQLModule = this;
727
728                 MessagePipe = new Notifier(Srv);
729                 Srv->AddSocket(MessagePipe);
730                 log(DEBUG,"Bound notifier to 127.0.0.1:%d",MessagePipe->GetPort());
731                 
732                 pthread_attr_t attribs;
733                 pthread_attr_init(&attribs);
734                 pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_DETACHED);
735                 if (pthread_create(&this->Dispatcher, &attribs, DispatcherThread, (void *)this) != 0)
736                 {
737                         throw ModuleException("m_mysql: Failed to create dispatcher thread: " + std::string(strerror(errno)));
738                 }
739                 Srv->PublishFeature("SQL", this);
740                 Srv->PublishFeature("MySQL", this);
741         }
742         
743         virtual ~ModuleSQL()
744         {
745                 DELETE(Conf);
746         }
747         
748         virtual void OnRehash(const std::string &parameter)
749         {
750                 /* TODO: set rehash bool here, which makes the dispatcher thread rehash at next opportunity */
751         }
752         
753         virtual Version GetVersion()
754         {
755                 return Version(1,1,0,0,VF_VENDOR|VF_SERVICEPROVIDER);
756         }
757         
758 };
759
760 void* DispatcherThread(void* arg)
761 {
762         ModuleSQL* thismodule = (ModuleSQL*)arg;
763         LoadDatabases(thismodule->Conf, thismodule->Srv);
764
765         /* Connect back to the Notifier */
766
767         if ((QueueFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
768         {
769                 /* crap, we're out of sockets... */
770                 log(DEBUG,"QueueFD cant be created");
771                 return NULL;
772         }
773
774         log(DEBUG,"Initialize QueueFD to %d",QueueFD);
775
776         sockaddr_in addr;
777         in_addr ia;
778         inet_aton("127.0.0.1", &ia);
779         addr.sin_family = AF_INET;
780         addr.sin_addr = ia;
781         addr.sin_port = htons(MessagePipe->GetPort());
782
783         if (connect(QueueFD, (sockaddr*)&addr,sizeof(addr)) == -1)
784         {
785                 /* wtf, we cant connect to it, but we just created it! */
786                 log(DEBUG,"QueueFD cant connect!");
787                 return NULL;
788         }
789
790         log(DEBUG,"Connect QUEUE FD");
791
792         while (!giveup)
793         {
794                 SQLConnection* conn = NULL;
795                 /* XXX: Lock here for safety */
796                 pthread_mutex_lock(&queue_mutex);
797                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
798                 {
799                         if (i->second->queue.totalsize())
800                         {
801                                 conn = i->second;
802                                 break;
803                         }
804                 }
805                 pthread_mutex_unlock(&queue_mutex);
806                 /* XXX: Unlock */
807
808                 /* Theres an item! */
809                 if (conn)
810                 {
811                         log(DEBUG,"Process Leading query");
812                         conn->DoLeadingQuery();
813
814                         /* XXX: Lock */
815                         pthread_mutex_lock(&queue_mutex);
816                         conn->queue.pop();
817                         pthread_mutex_unlock(&queue_mutex);
818                         /* XXX: Unlock */
819                 }
820
821                 usleep(50);
822         }
823
824         return NULL;
825 }
826
827
828 // stuff down here is the module-factory stuff. For basic modules you can ignore this.
829
830 class ModuleSQLFactory : public ModuleFactory
831 {
832  public:
833         ModuleSQLFactory()
834         {
835         }
836         
837         ~ModuleSQLFactory()
838         {
839         }
840         
841         virtual Module * CreateModule(Server* Me)
842         {
843                 return new ModuleSQL(Me);
844         }
845         
846 };
847
848
849 extern "C" void * init_module( void )
850 {
851         return new ModuleSQLFactory;
852 }
853