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