]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Fix compile error due to mismerge
[user/henk/code/inspircd.git] / src / modules / extra / m_mysql.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* Stop mysql wanting to use long long */
15 #define NO_CLIENT_LONG_LONG
16
17 #include "inspircd.h"
18 #include <mysql.h>
19 #include "m_sqlv2.h"
20
21 #ifdef WINDOWS
22 #pragma comment(lib, "mysqlclient.lib")
23 #endif
24
25 /* VERSION 2 API: With nonblocking (threaded) requests */
26
27 /* $ModDesc: SQL Service Provider module for all other m_sql* modules */
28 /* $CompileFlags: exec("mysql_config --include") */
29 /* $LinkerFlags: exec("mysql_config --libs_r") rpath("mysql_config --libs_r") */
30 /* $ModDep: m_sqlv2.h */
31
32 /* THE NONBLOCKING MYSQL API!
33  *
34  * MySQL provides no nonblocking (asyncronous) API of its own, and its developers recommend
35  * that instead, you should thread your program. This is what i've done here to allow for
36  * asyncronous SQL requests via mysql. The way this works is as follows:
37  *
38  * The module spawns a thread via class Thread, and performs its mysql queries in this thread,
39  * using a queue with priorities. There is a mutex on either end which prevents two threads
40  * adjusting the queue at the same time, and crashing the ircd. Every 50 milliseconds, the
41  * worker thread wakes up, and checks if there is a request at the head of its queue.
42  * If there is, it processes this request, blocking the worker thread but leaving the ircd
43  * thread to go about its business as usual. During this period, the ircd thread is able
44  * to insert futher pending requests into the queue.
45  *
46  * Once the processing of a request is complete, it is removed from the incoming queue to
47  * an outgoing queue, and initialized as a 'response'. The worker thread then signals the
48  * ircd thread (via a loopback socket) of the fact a result is available, by sending the
49  * connection ID through the connection.
50  *
51  * The ircd thread then mutexes the queue once more, reads the outbound response off the head
52  * of the queue, and sends it on its way to the original calling module.
53  *
54  * XXX: You might be asking "why doesnt he just send the response from within the worker thread?"
55  * The answer to this is simple. The majority of InspIRCd, and in fact most ircd's are not
56  * threadsafe. This module is designed to be threadsafe and is careful with its use of threads,
57  * however, if we were to call a module's OnRequest even from within a thread which was not the
58  * one the module was originally instantiated upon, there is a chance of all hell breaking loose
59  * if a module is ever put in a re-enterant state (stack corruption could occur, crashes, data
60  * corruption, and worse, so DONT think about it until the day comes when InspIRCd is 100%
61  * gauranteed threadsafe!)
62  *
63  * For a diagram of this system please see http://wiki.inspircd.org/Mysql2
64  */
65
66
67 class SQLConnection;
68 class DispatcherThread;
69
70 typedef std::map<std::string, SQLConnection*> ConnMap;
71 typedef std::deque<SQLresult*> ResultQueue;
72
73 unsigned long count(const char * const str, char a)
74 {
75         unsigned long n = 0;
76         for (const char *p = reinterpret_cast<const char *>(str); *p; ++p)
77         {
78                 if (*p == '?')
79                         ++n;
80         }
81         return n;
82 }
83
84
85 /** MySQL module
86  *  */
87 class ModuleSQL : public Module
88 {
89  public:
90
91          ConfigReader *Conf;
92          InspIRCd* PublicServerInstance;
93          int currid;
94          bool rehashing;
95          DispatcherThread* Dispatcher;
96          Mutex ResultsMutex;
97          Mutex LoggingMutex;
98          Mutex ConnMutex;
99
100          ModuleSQL(InspIRCd* Me);
101          ~ModuleSQL();
102          unsigned long NewID();
103          const char* OnRequest(Request* request);
104          void OnRehash(User* user, const std::string &parameter);
105          Version GetVersion();
106 };
107
108
109 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
110 #define mysql_field_count mysql_num_fields
111 #endif
112
113 /** Represents a mysql result set
114  */
115 class MySQLresult : public SQLresult
116 {
117         int currentrow;
118         std::vector<std::string> colnames;
119         std::vector<SQLfieldList> fieldlists;
120         SQLfieldMap* fieldmap;
121         SQLfieldMap fieldmap2;
122         SQLfieldList emptyfieldlist;
123         int rows;
124  public:
125
126         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
127         {
128                 /* A number of affected rows from from mysql_affected_rows.
129                  */
130                 fieldlists.clear();
131                 rows = 0;
132                 if (affected_rows >= 1)
133                 {
134                         rows = affected_rows;
135                         fieldlists.resize(rows);
136                 }
137                 unsigned int field_count = 0;
138                 if (res)
139                 {
140                         MYSQL_ROW row;
141                         int n = 0;
142                         while ((row = mysql_fetch_row(res)))
143                         {
144                                 if (fieldlists.size() < (unsigned int)rows+1)
145                                 {
146                                         fieldlists.resize(fieldlists.size()+1);
147                                 }
148                                 field_count = 0;
149                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
150                                 if(mysql_num_fields(res) == 0)
151                                         break;
152                                 if (fields && mysql_num_fields(res))
153                                 {
154                                         colnames.clear();
155                                         while (field_count < mysql_num_fields(res))
156                                         {
157                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
158                                                 std::string b = (row[field_count] ? row[field_count] : "");
159                                                 SQLfield sqlf(b, !row[field_count]);
160                                                 colnames.push_back(a);
161                                                 fieldlists[n].push_back(sqlf);
162                                                 field_count++;
163                                         }
164                                         n++;
165                                 }
166                                 rows++;
167                         }
168                         mysql_free_result(res);
169                         res = NULL;
170                 }
171         }
172
173         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
174         {
175                 rows = 0;
176                 error = e;
177         }
178
179         ~MySQLresult()
180         {
181         }
182
183         virtual int Rows()
184         {
185                 return rows;
186         }
187
188         virtual int Cols()
189         {
190                 return colnames.size();
191         }
192
193         virtual std::string ColName(int column)
194         {
195                 if (column < (int)colnames.size())
196                 {
197                         return colnames[column];
198                 }
199                 else
200                 {
201                         throw SQLbadColName();
202                 }
203                 return "";
204         }
205
206         virtual int ColNum(const std::string &column)
207         {
208                 for (unsigned int i = 0; i < colnames.size(); i++)
209                 {
210                         if (column == colnames[i])
211                                 return i;
212                 }
213                 throw SQLbadColName();
214                 return 0;
215         }
216
217         virtual SQLfield GetValue(int row, int column)
218         {
219                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
220                 {
221                         return fieldlists[row][column];
222                 }
223
224                 throw SQLbadColName();
225
226                 /* XXX: We never actually get here because of the throw */
227                 return SQLfield("",true);
228         }
229
230         virtual SQLfieldList& GetRow()
231         {
232                 if (currentrow < rows)
233                         return fieldlists[currentrow++];
234                 else
235                         return emptyfieldlist;
236         }
237
238         virtual SQLfieldMap& GetRowMap()
239         {
240                 fieldmap2.clear();
241
242                 if (currentrow < rows)
243                 {
244                         for (int i = 0; i < Cols(); i++)
245                         {
246                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
247                         }
248                         currentrow++;
249                 }
250
251                 return fieldmap2;
252         }
253
254         virtual SQLfieldList* GetRowPtr()
255         {
256                 SQLfieldList* fieldlist = new SQLfieldList();
257
258                 if (currentrow < rows)
259                 {
260                         for (int i = 0; i < Rows(); i++)
261                         {
262                                 fieldlist->push_back(fieldlists[currentrow][i]);
263                         }
264                         currentrow++;
265                 }
266                 return fieldlist;
267         }
268
269         virtual SQLfieldMap* GetRowMapPtr()
270         {
271                 fieldmap = new SQLfieldMap();
272
273                 if (currentrow < rows)
274                 {
275                         for (int i = 0; i < Cols(); i++)
276                         {
277                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
278                         }
279                         currentrow++;
280                 }
281
282                 return fieldmap;
283         }
284
285         virtual void Free(SQLfieldMap* fm)
286         {
287                 delete fm;
288         }
289
290         virtual void Free(SQLfieldList* fl)
291         {
292                 delete fl;
293         }
294 };
295
296 /** Represents a connection to a mysql database
297  */
298 class SQLConnection : public classbase
299 {
300  protected:
301         MYSQL *connection;
302         MYSQL_RES *res;
303         MYSQL_ROW *row;
304         SQLhost host;
305         std::map<std::string,std::string> thisrow;
306         bool Enabled;
307         ModuleSQL* Parent;
308
309  public:
310
311         QueryQueue queue;
312         ResultQueue rq;
313
314         // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
315         SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : connection(NULL), host(hi), Enabled(false), Parent(Creator)
316         {
317         }
318
319         ~SQLConnection()
320         {
321                 Close();
322         }
323
324         // This method connects to the database using the credentials supplied to the constructor, and returns
325         // true upon success.
326         bool Connect()
327         {
328                 unsigned int timeout = 1;
329                 connection = mysql_init(connection);
330                 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
331                 return mysql_real_connect(connection, host.host.c_str(), host.user.c_str(), host.pass.c_str(), host.name.c_str(), host.port, NULL, 0);
332         }
333
334         void DoLeadingQuery()
335         {
336                 if (!CheckConnection())
337                         return;
338
339                 /* Parse the command string and dispatch it to mysql */
340                 SQLrequest& req = queue.front();
341
342                 /* Pointer to the buffer we screw around with substitution in */
343                 char* query;
344
345                 /* Pointer to the current end of query, where we append new stuff */
346                 char* queryend;
347
348                 /* Total length of the unescaped parameters */
349                 unsigned long maxparamlen, paramcount;
350
351                 /* The length of the longest parameter */
352                 maxparamlen = 0;
353
354                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
355                 {
356                         if (i->size() > maxparamlen)
357                                 maxparamlen = i->size();
358                 }
359
360                 /* How many params are there in the query? */
361                 paramcount = count(req.query.q.c_str(), '?');
362
363                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
364                 ParamL paramscopy(req.query.p);
365
366                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
367                  * sizeofquery + (maxtotalparamlength*2) + 1
368                  *
369                  * The +1 is for null-terminating the string for mysql_real_escape_string
370                  */
371
372                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
373                 queryend = query;
374
375                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
376                  * the parameters into it...
377                  */
378
379                 for(unsigned long i = 0; i < req.query.q.length(); i++)
380                 {
381                         if(req.query.q[i] == '?')
382                         {
383                                 /* We found a place to substitute..what fun.
384                                  * use mysql calls to escape and write the
385                                  * escaped string onto the end of our query buffer,
386                                  * then we "just" need to make sure queryend is
387                                  * pointing at the right place.
388                                  */
389
390                                 /* Is it numbered parameter?
391                                  */
392
393                                 bool numbered;
394                                 numbered = false;
395
396                                 /* Numbered parameter number :|
397                                  */
398                                 unsigned int paramnum;
399                                 paramnum = 0;
400
401                                 /* Let's check if it's a numbered param. And also calculate it's number.
402                                  */
403
404                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
405                                 {
406                                         numbered = true;
407                                         ++i;
408                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
409                                 }
410
411                                 if (paramnum > paramscopy.size() - 1)
412                                 {
413                                         /* index is out of range!
414                                          */
415                                         numbered = false;
416                                 }
417
418                                 if (numbered)
419                                 {
420                                         unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
421
422                                         queryend += len;
423                                 }
424                                 else if (req.query.p.size())
425                                 {
426                                         unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
427
428                                         queryend += len;
429                                         req.query.p.pop_front();
430                                 }
431                                 else
432                                         break;
433                         }
434                         else
435                         {
436                                 *queryend = req.query.q[i];
437                                 queryend++;
438                         }
439                 }
440
441                 *queryend = 0;
442
443                 req.query.q = query;
444
445                 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
446                 {
447                         /* Successfull query */
448                         res = mysql_use_result(connection);
449                         unsigned long rows = mysql_affected_rows(connection);
450                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
451                         r->dbid = this->GetID();
452                         r->query = req.query.q;
453                         /* Put this new result onto the results queue.
454                          * XXX: Remember to mutex the queue!
455                          */
456                         Parent->ResultsMutex.Lock();
457                         rq.push_back(r);
458                         Parent->ResultsMutex.Unlock();
459                 }
460                 else
461                 {
462                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
463                          * possible error numbers and error messages */
464                         SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
465                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
466                         r->dbid = this->GetID();
467                         r->query = req.query.q;
468
469                         Parent->ResultsMutex.Lock();
470                         rq.push_back(r);
471                         Parent->ResultsMutex.Unlock();
472                 }
473
474                 delete[] query;
475         }
476
477         bool ConnectionLost()
478         {
479                 if (&connection)
480                 {
481                         return (mysql_ping(connection) != 0);
482                 }
483                 else return false;
484         }
485
486         bool CheckConnection()
487         {
488                 if (ConnectionLost())
489                 {
490                         return Connect();
491                 }
492                 else return true;
493         }
494
495         std::string GetError()
496         {
497                 return mysql_error(connection);
498         }
499
500         const std::string& GetID()
501         {
502                 return host.id;
503         }
504
505         std::string GetHost()
506         {
507                 return host.host;
508         }
509
510         void SetEnable(bool Enable)
511         {
512                 Enabled = Enable;
513         }
514
515         bool IsEnabled()
516         {
517                 return Enabled;
518         }
519
520         void Close()
521         {
522                 mysql_close(connection);
523         }
524
525         const SQLhost& GetConfHost()
526         {
527                 return host;
528         }
529
530 };
531
532 ConnMap Connections;
533
534 bool HasHost(const SQLhost &host)
535 {
536         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
537         {
538                 if (host == iter->second->GetConfHost())
539                         return true;
540         }
541         return false;
542 }
543
544 bool HostInConf(ConfigReader* conf, const SQLhost &h)
545 {
546         for(int i = 0; i < conf->Enumerate("database"); i++)
547         {
548                 SQLhost host;
549                 host.id         = conf->ReadValue("database", "id", i);
550                 host.host       = conf->ReadValue("database", "hostname", i);
551                 host.port       = conf->ReadInteger("database", "port", i, true);
552                 host.name       = conf->ReadValue("database", "name", i);
553                 host.user       = conf->ReadValue("database", "username", i);
554                 host.pass       = conf->ReadValue("database", "password", i);
555                 host.ssl        = conf->ReadFlag("database", "ssl", i);
556                 if (h == host)
557                         return true;
558         }
559         return false;
560 }
561
562 void ClearOldConnections(ConfigReader* conf)
563 {
564         ConnMap::iterator i,safei;
565         for (i = Connections.begin(); i != Connections.end(); i++)
566         {
567                 if (!HostInConf(conf, i->second->GetConfHost()))
568                 {
569                         delete i->second;
570                         safei = i;
571                         --i;
572                         Connections.erase(safei);
573                 }
574         }
575 }
576
577 void ClearAllConnections()
578 {
579         ConnMap::iterator i;
580         while ((i = Connections.begin()) != Connections.end())
581         {
582                 Connections.erase(i);
583                 delete i->second;
584         }
585 }
586
587 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
588 {
589         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
590         {
591                 if (i->second->IsEnabled())
592                         continue;
593
594                 i->second->SetEnable(true);
595                 if (!i->second->Connect())
596                 {
597                         /* XXX: MUTEX */
598                         Parent->LoggingMutex.Lock();
599                         ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
600                         i->second->SetEnable(false);
601                         Parent->LoggingMutex.Unlock();
602                 }
603         }
604 }
605
606 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
607 {
608         Parent->ConnMutex.Lock();
609         ClearOldConnections(conf);
610         for (int j =0; j < conf->Enumerate("database"); j++)
611         {
612                 SQLhost host;
613                 host.id         = conf->ReadValue("database", "id", j);
614                 host.host       = conf->ReadValue("database", "hostname", j);
615                 host.port       = conf->ReadInteger("database", "port", j, true);
616                 host.name       = conf->ReadValue("database", "name", j);
617                 host.user       = conf->ReadValue("database", "username", j);
618                 host.pass       = conf->ReadValue("database", "password", j);
619                 host.ssl        = conf->ReadFlag("database", "ssl", j);
620
621                 if (HasHost(host))
622                         continue;
623
624                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
625                 {
626                         SQLConnection* ThisSQL = new SQLConnection(host, Parent);
627                         Connections[host.id] = ThisSQL;
628                 }
629         }
630         ConnectDatabases(ServerInstance, Parent);
631         Parent->ConnMutex.Unlock();
632 }
633
634 char FindCharId(const std::string &id)
635 {
636         char i = 1;
637         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
638         {
639                 if (iter->first == id)
640                 {
641                         return i;
642                 }
643         }
644         return 0;
645 }
646
647 ConnMap::iterator GetCharId(char id)
648 {
649         char i = 1;
650         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
651         {
652                 if (i == id)
653                         return iter;
654         }
655         return Connections.end();
656 }
657
658 class ModuleSQL;
659
660 class DispatcherThread : public SocketThread
661 {
662  private:
663         ModuleSQL* Parent;
664         InspIRCd* ServerInstance;
665  public:
666         DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : SocketThread(Instance), Parent(CreatorModule), ServerInstance(Instance) { }
667         ~DispatcherThread() { }
668         virtual void Run();
669         virtual void OnNotify();
670 };
671
672 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
673 {
674         ServerInstance->Modules->UseInterface("SQLutils");
675
676         Conf = new ConfigReader(ServerInstance);
677         PublicServerInstance = ServerInstance;
678         currid = 0;
679
680         Dispatcher = new DispatcherThread(ServerInstance, this);
681         ServerInstance->Threads->Start(Dispatcher);
682
683         if (!ServerInstance->Modules->PublishFeature("SQL", this))
684         {
685                 /* Tell worker thread to exit NOW,
686                  * Automatically joins */
687                 delete Dispatcher;
688                 ServerInstance->Modules->DoneWithInterface("SQLutils");
689                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
690         }
691
692         ServerInstance->Modules->PublishInterface("SQL", this);
693         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
694         ServerInstance->Modules->Attach(eventlist, this, 2);
695 }
696
697 ModuleSQL::~ModuleSQL()
698 {
699         delete Dispatcher;
700         ClearAllConnections();
701         delete Conf;
702         ServerInstance->Modules->UnpublishInterface("SQL", this);
703         ServerInstance->Modules->UnpublishFeature("SQL");
704         ServerInstance->Modules->DoneWithInterface("SQLutils");
705 }
706
707 unsigned long ModuleSQL::NewID()
708 {
709         if (currid+1 == 0)
710                 currid++;
711         return ++currid;
712 }
713
714 const char* ModuleSQL::OnRequest(Request* request)
715 {
716         if(strcmp(SQLREQID, request->GetId()) == 0)
717         {
718                 SQLrequest* req = (SQLrequest*)request;
719
720                 ConnMap::iterator iter;
721
722                 const char* returnval = NULL;
723
724                 Dispatcher->LockQueue();
725                 ConnMutex.Lock();
726                 if((iter = Connections.find(req->dbid)) != Connections.end())
727                 {
728                         req->id = NewID();
729                         iter->second->queue.push(*req);
730                         returnval = SQLSUCCESS;
731                 }
732                 else
733                 {
734                         req->error.Id(SQL_BAD_DBID);
735                 }
736
737                 ConnMutex.Unlock();
738                 Dispatcher->UnlockQueueWakeup();
739                 /* Yes, it's possible this will generate a spurious wakeup.
740                  * That's fine, it'll just get ignored.
741                  */
742
743                 return returnval;
744         }
745
746         return NULL;
747 }
748
749 void ModuleSQL::OnRehash(User* user, const std::string &parameter)
750 {
751         Dispatcher->LockQueue();
752         rehashing = true;
753         Dispatcher->UnlockQueueWakeup();
754 }
755
756 Version ModuleSQL::GetVersion()
757 {
758         return Version("$Id$", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
759 }
760
761 void DispatcherThread::Run()
762 {
763         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
764
765         SQLConnection* conn = NULL;
766
767         this->LockQueue();
768         while (!this->GetExitFlag())
769         {
770                 if (Parent->rehashing)
771                 {
772                         Parent->rehashing = false;
773                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
774                 }
775
776                 Parent->ConnMutex.Lock();
777                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
778                 {
779                         if (i->second->queue.totalsize())
780                         {
781                                 conn = i->second;
782                                 break;
783                         }
784                 }
785                 Parent->ConnMutex.Unlock();
786
787                 if (conn)
788                 {
789                         /* There's an item! */
790                         this->UnlockQueue();
791                         conn->DoLeadingQuery();
792                         this->NotifyParent();
793                         this->LockQueue();
794                         conn->queue.pop();
795                 }
796                 else
797                 {
798                         /* We know the queue is empty, we can safely hang this thread until
799                          * something happens
800                          */
801                         this->WaitForQueue();
802                 }
803         }
804         this->UnlockQueue();
805 }
806
807 void DispatcherThread::OnNotify()
808 {
809         while (1)
810         {
811                 SQLConnection* conn = NULL;
812                 Parent->ConnMutex.Lock();
813                 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
814                 {
815                         if (!iter->second->rq.empty())
816                         {
817                                 conn = iter->second;
818                                 break;
819                         }
820                 }
821                 Parent->ConnMutex.Unlock();
822
823                 if (!conn)
824                         break;
825
826                 Parent->ResultsMutex.Lock();
827                 ResultQueue::iterator n = conn->rq.begin();
828                 Parent->ResultsMutex.Unlock();
829
830                 (*n)->Send();
831                 delete (*n);
832
833                 Parent->ResultsMutex.Lock();
834                 conn->rq.pop_front();
835                 Parent->ResultsMutex.Unlock();
836         }
837 }
838
839 MODULE_INIT(ModuleSQL)