]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
Remove InspIRCd* parameters and fields
[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 = 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          int currid;
93          bool rehashing;
94          DispatcherThread* Dispatcher;
95          Mutex ResultsMutex;
96          Mutex LoggingMutex;
97          Mutex ConnMutex;
98
99          ModuleSQL();
100          ~ModuleSQL();
101          unsigned long NewID();
102          const char* OnRequest(Request* request);
103          void OnRehash(User* user);
104          Version GetVersion();
105 };
106
107
108 #if !defined(MYSQL_VERSION_ID) || MYSQL_VERSION_ID<32224
109 #define mysql_field_count mysql_num_fields
110 #endif
111
112 /** Represents a mysql result set
113  */
114 class MySQLresult : public SQLresult
115 {
116         int currentrow;
117         std::vector<std::string> colnames;
118         std::vector<SQLfieldList> fieldlists;
119         SQLfieldMap* fieldmap;
120         SQLfieldMap fieldmap2;
121         SQLfieldList emptyfieldlist;
122         int rows;
123  public:
124
125         MySQLresult(Module* self, Module* to, MYSQL_RES* res, int affected_rows, unsigned int rid) : SQLresult(self, to, rid), currentrow(0), fieldmap(NULL)
126         {
127                 /* A number of affected rows from from mysql_affected_rows.
128                  */
129                 fieldlists.clear();
130                 rows = 0;
131                 if (affected_rows >= 1)
132                 {
133                         rows = affected_rows;
134                         fieldlists.resize(rows);
135                 }
136                 unsigned int field_count = 0;
137                 if (res)
138                 {
139                         MYSQL_ROW row;
140                         int n = 0;
141                         while ((row = mysql_fetch_row(res)))
142                         {
143                                 if (fieldlists.size() < (unsigned int)rows+1)
144                                 {
145                                         fieldlists.resize(fieldlists.size()+1);
146                                 }
147                                 field_count = 0;
148                                 MYSQL_FIELD *fields = mysql_fetch_fields(res);
149                                 if(mysql_num_fields(res) == 0)
150                                         break;
151                                 if (fields && mysql_num_fields(res))
152                                 {
153                                         colnames.clear();
154                                         while (field_count < mysql_num_fields(res))
155                                         {
156                                                 std::string a = (fields[field_count].name ? fields[field_count].name : "");
157                                                 std::string b = (row[field_count] ? row[field_count] : "");
158                                                 SQLfield sqlf(b, !row[field_count]);
159                                                 colnames.push_back(a);
160                                                 fieldlists[n].push_back(sqlf);
161                                                 field_count++;
162                                         }
163                                         n++;
164                                 }
165                                 rows++;
166                         }
167                         mysql_free_result(res);
168                         res = NULL;
169                 }
170         }
171
172         MySQLresult(Module* self, Module* to, SQLerror e, unsigned int rid) : SQLresult(self, to, rid), currentrow(0)
173         {
174                 rows = 0;
175                 error = e;
176         }
177
178         ~MySQLresult()
179         {
180         }
181
182         virtual int Rows()
183         {
184                 return rows;
185         }
186
187         virtual int Cols()
188         {
189                 return colnames.size();
190         }
191
192         virtual std::string ColName(int column)
193         {
194                 if (column < (int)colnames.size())
195                 {
196                         return colnames[column];
197                 }
198                 else
199                 {
200                         throw SQLbadColName();
201                 }
202                 return "";
203         }
204
205         virtual int ColNum(const std::string &column)
206         {
207                 for (unsigned int i = 0; i < colnames.size(); i++)
208                 {
209                         if (column == colnames[i])
210                                 return i;
211                 }
212                 throw SQLbadColName();
213                 return 0;
214         }
215
216         virtual SQLfield GetValue(int row, int column)
217         {
218                 if ((row >= 0) && (row < rows) && (column >= 0) && (column < Cols()))
219                 {
220                         return fieldlists[row][column];
221                 }
222
223                 throw SQLbadColName();
224
225                 /* XXX: We never actually get here because of the throw */
226                 return SQLfield("",true);
227         }
228
229         virtual SQLfieldList& GetRow()
230         {
231                 if (currentrow < rows)
232                         return fieldlists[currentrow++];
233                 else
234                         return emptyfieldlist;
235         }
236
237         virtual SQLfieldMap& GetRowMap()
238         {
239                 fieldmap2.clear();
240
241                 if (currentrow < rows)
242                 {
243                         for (int i = 0; i < Cols(); i++)
244                         {
245                                 fieldmap2.insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
246                         }
247                         currentrow++;
248                 }
249
250                 return fieldmap2;
251         }
252
253         virtual SQLfieldList* GetRowPtr()
254         {
255                 SQLfieldList* fieldlist = new SQLfieldList();
256
257                 if (currentrow < rows)
258                 {
259                         for (int i = 0; i < Rows(); i++)
260                         {
261                                 fieldlist->push_back(fieldlists[currentrow][i]);
262                         }
263                         currentrow++;
264                 }
265                 return fieldlist;
266         }
267
268         virtual SQLfieldMap* GetRowMapPtr()
269         {
270                 fieldmap = new SQLfieldMap();
271
272                 if (currentrow < rows)
273                 {
274                         for (int i = 0; i < Cols(); i++)
275                         {
276                                 fieldmap->insert(std::make_pair(colnames[i],GetValue(currentrow, i)));
277                         }
278                         currentrow++;
279                 }
280
281                 return fieldmap;
282         }
283
284         virtual void Free(SQLfieldMap* fm)
285         {
286                 delete fm;
287         }
288
289         virtual void Free(SQLfieldList* fl)
290         {
291                 delete fl;
292         }
293 };
294
295 /** Represents a connection to a mysql database
296  */
297 class SQLConnection : public classbase
298 {
299  protected:
300         MYSQL *connection;
301         MYSQL_RES *res;
302         MYSQL_ROW *row;
303         SQLhost host;
304         std::map<std::string,std::string> thisrow;
305         bool Enabled;
306         ModuleSQL* Parent;
307         std::string initquery;
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                 if( !initquery.empty() )
340                         mysql_query(connection,initquery.c_str());
341
342                 /* Parse the command string and dispatch it to mysql */
343                 SQLrequest& req = queue.front();
344
345                 /* Pointer to the buffer we screw around with substitution in */
346                 char* query;
347
348                 /* Pointer to the current end of query, where we append new stuff */
349                 char* queryend;
350
351                 /* Total length of the unescaped parameters */
352                 unsigned long maxparamlen, paramcount;
353
354                 /* The length of the longest parameter */
355                 maxparamlen = 0;
356
357                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
358                 {
359                         if (i->size() > maxparamlen)
360                                 maxparamlen = i->size();
361                 }
362
363                 /* How many params are there in the query? */
364                 paramcount = count(req.query.q.c_str(), '?');
365
366                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
367                 ParamL paramscopy(req.query.p);
368
369                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
370                  * sizeofquery + (maxtotalparamlength*2) + 1
371                  *
372                  * The +1 is for null-terminating the string for mysql_real_escape_string
373                  */
374
375                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
376                 queryend = query;
377
378                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
379                  * the parameters into it...
380                  */
381
382                 for(unsigned long i = 0; i < req.query.q.length(); i++)
383                 {
384                         if(req.query.q[i] == '?')
385                         {
386                                 /* We found a place to substitute..what fun.
387                                  * use mysql calls to escape and write the
388                                  * escaped string onto the end of our query buffer,
389                                  * then we "just" need to make sure queryend is
390                                  * pointing at the right place.
391                                  */
392
393                                 /* Is it numbered parameter?
394                                  */
395
396                                 bool numbered;
397                                 numbered = false;
398
399                                 /* Numbered parameter number :|
400                                  */
401                                 unsigned int paramnum;
402                                 paramnum = 0;
403
404                                 /* Let's check if it's a numbered param. And also calculate it's number.
405                                  */
406
407                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
408                                 {
409                                         numbered = true;
410                                         ++i;
411                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
412                                 }
413
414                                 if (paramnum > paramscopy.size() - 1)
415                                 {
416                                         /* index is out of range!
417                                          */
418                                         numbered = false;
419                                 }
420
421                                 if (numbered)
422                                 {
423                                         unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
424
425                                         queryend += len;
426                                 }
427                                 else if (req.query.p.size())
428                                 {
429                                         unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
430
431                                         queryend += len;
432                                         req.query.p.pop_front();
433                                 }
434                                 else
435                                         break;
436                         }
437                         else
438                         {
439                                 *queryend = req.query.q[i];
440                                 queryend++;
441                         }
442                 }
443
444                 *queryend = 0;
445
446                 req.query.q = query;
447
448                 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
449                 {
450                         /* Successfull query */
451                         res = mysql_use_result(connection);
452                         unsigned long rows = mysql_affected_rows(connection);
453                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
454                         r->dbid = this->GetID();
455                         r->query = req.query.q;
456                         /* Put this new result onto the results queue.
457                          * XXX: Remember to mutex the queue!
458                          */
459                         Parent->ResultsMutex.Lock();
460                         rq.push_back(r);
461                         Parent->ResultsMutex.Unlock();
462                 }
463                 else
464                 {
465                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
466                          * possible error numbers and error messages */
467                         SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
468                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
469                         r->dbid = this->GetID();
470                         r->query = req.query.q;
471
472                         Parent->ResultsMutex.Lock();
473                         rq.push_back(r);
474                         Parent->ResultsMutex.Unlock();
475                 }
476
477                 delete[] query;
478         }
479
480         bool ConnectionLost()
481         {
482                 if (&connection)
483                 {
484                         return (mysql_ping(connection) != 0);
485                 }
486                 else return false;
487         }
488
489         bool CheckConnection()
490         {
491                 if (ConnectionLost())
492                 {
493                         return Connect();
494                 }
495                 else return true;
496         }
497
498         std::string GetError()
499         {
500                 return mysql_error(connection);
501         }
502
503         const std::string& GetID()
504         {
505                 return host.id;
506         }
507
508         std::string GetHost()
509         {
510                 return host.host;
511         }
512
513         void setInitialQuery(std::string init)
514         {
515                 initquery = init;
516         }
517
518         void SetEnable(bool Enable)
519         {
520                 Enabled = Enable;
521         }
522
523         bool IsEnabled()
524         {
525                 return Enabled;
526         }
527
528         void Close()
529         {
530                 mysql_close(connection);
531         }
532
533         const SQLhost& GetConfHost()
534         {
535                 return host;
536         }
537
538 };
539
540 ConnMap Connections;
541
542 bool HasHost(const SQLhost &host)
543 {
544         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
545         {
546                 if (host == iter->second->GetConfHost())
547                         return true;
548         }
549         return false;
550 }
551
552 bool HostInConf(ConfigReader* conf, const SQLhost &h)
553 {
554         for(int i = 0; i < conf->Enumerate("database"); i++)
555         {
556                 SQLhost host;
557                 host.id         = conf->ReadValue("database", "id", i);
558                 host.host       = conf->ReadValue("database", "hostname", i);
559                 host.port       = conf->ReadInteger("database", "port", i, true);
560                 host.name       = conf->ReadValue("database", "name", i);
561                 host.user       = conf->ReadValue("database", "username", i);
562                 host.pass       = conf->ReadValue("database", "password", i);
563                 host.ssl        = conf->ReadFlag("database", "ssl", i);
564                 if (h == host)
565                         return true;
566         }
567         return false;
568 }
569
570 void ClearOldConnections(ConfigReader* conf)
571 {
572         ConnMap::iterator i,safei;
573         for (i = Connections.begin(); i != Connections.end(); i++)
574         {
575                 if (!HostInConf(conf, i->second->GetConfHost()))
576                 {
577                         delete i->second;
578                         safei = i;
579                         --i;
580                         Connections.erase(safei);
581                 }
582         }
583 }
584
585 void ClearAllConnections()
586 {
587         ConnMap::iterator i;
588         while ((i = Connections.begin()) != Connections.end())
589         {
590                 Connections.erase(i);
591                 delete i->second;
592         }
593 }
594
595 void ConnectDatabases(ModuleSQL* Parent)
596 {
597         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
598         {
599                 if (i->second->IsEnabled())
600                         continue;
601
602                 i->second->SetEnable(true);
603                 if (!i->second->Connect())
604                 {
605                         /* XXX: MUTEX */
606                         Parent->LoggingMutex.Lock();
607                         ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
608                         i->second->SetEnable(false);
609                         Parent->LoggingMutex.Unlock();
610                 }
611         }
612 }
613
614 void LoadDatabases(ConfigReader* conf, ModuleSQL* Parent)
615 {
616         Parent->ConnMutex.Lock();
617         ClearOldConnections(conf);
618         for (int j =0; j < conf->Enumerate("database"); j++)
619         {
620                 SQLhost host;
621                 host.id         = conf->ReadValue("database", "id", j);
622                 host.host       = conf->ReadValue("database", "hostname", j);
623                 host.port       = conf->ReadInteger("database", "port", j, true);
624                 host.name       = conf->ReadValue("database", "name", j);
625                 host.user       = conf->ReadValue("database", "username", j);
626                 host.pass       = conf->ReadValue("database", "password", j);
627                 host.ssl        = conf->ReadFlag("database", "ssl", j);
628                 std::string initquery = conf->ReadValue("database", "initialquery", j);
629
630                 if (HasHost(host))
631                         continue;
632
633                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
634                 {
635                         SQLConnection* ThisSQL = new SQLConnection(host, Parent);
636                         Connections[host.id] = ThisSQL;
637
638                         ThisSQL->setInitialQuery(initquery);
639                 }
640         }
641         ConnectDatabases(Parent);
642         Parent->ConnMutex.Unlock();
643 }
644
645 char FindCharId(const std::string &id)
646 {
647         char i = 1;
648         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
649         {
650                 if (iter->first == id)
651                 {
652                         return i;
653                 }
654         }
655         return 0;
656 }
657
658 ConnMap::iterator GetCharId(char id)
659 {
660         char i = 1;
661         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
662         {
663                 if (i == id)
664                         return iter;
665         }
666         return Connections.end();
667 }
668
669 class ModuleSQL;
670
671 class DispatcherThread : public SocketThread
672 {
673  private:
674         ModuleSQL* Parent;
675  public:
676         DispatcherThread(ModuleSQL* CreatorModule) : SocketThread(Instance), Parent(CreatorModule),{ }
677         ~DispatcherThread() { }
678         virtual void Run();
679         virtual void OnNotify();
680 };
681
682 ModuleSQL::ModuleSQL() : rehashing(false)
683 {
684         ServerInstance->Modules->UseInterface("SQLutils");
685
686         Conf = new ConfigReader;
687         PublicServerInstance = ServerInstance;
688         currid = 0;
689
690         Dispatcher = new DispatcherThread(this);
691         ServerInstance->Threads->Start(Dispatcher);
692
693         if (!ServerInstance->Modules->PublishFeature("SQL", this))
694         {
695                 Dispatcher->join();
696                 delete Dispatcher;
697                 ServerInstance->Modules->DoneWithInterface("SQLutils");
698                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
699         }
700
701         ServerInstance->Modules->PublishInterface("SQL", this);
702         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
703         ServerInstance->Modules->Attach(eventlist, this, 2);
704 }
705
706 ModuleSQL::~ModuleSQL()
707 {
708         delete Dispatcher;
709         ClearAllConnections();
710         delete Conf;
711         ServerInstance->Modules->UnpublishInterface("SQL", this);
712         ServerInstance->Modules->UnpublishFeature("SQL");
713         ServerInstance->Modules->DoneWithInterface("SQLutils");
714 }
715
716 unsigned long ModuleSQL::NewID()
717 {
718         if (currid+1 == 0)
719                 currid++;
720         return ++currid;
721 }
722
723 const char* ModuleSQL::OnRequest(Request* request)
724 {
725         if(strcmp(SQLREQID, request->GetId()) == 0)
726         {
727                 SQLrequest* req = (SQLrequest*)request;
728
729                 ConnMap::iterator iter;
730
731                 const char* returnval = NULL;
732
733                 Dispatcher->LockQueue();
734                 ConnMutex.Lock();
735                 if((iter = Connections.find(req->dbid)) != Connections.end())
736                 {
737                         req->id = NewID();
738                         iter->second->queue.push(*req);
739                         returnval = SQLSUCCESS;
740                 }
741                 else
742                 {
743                         req->error.Id(SQL_BAD_DBID);
744                 }
745
746                 ConnMutex.Unlock();
747                 Dispatcher->UnlockQueueWakeup();
748                 /* Yes, it's possible this will generate a spurious wakeup.
749                  * That's fine, it'll just get ignored.
750                  */
751
752                 return returnval;
753         }
754
755         return NULL;
756 }
757
758 void ModuleSQL::OnRehash(User* user)
759 {
760         Dispatcher->LockQueue();
761         rehashing = true;
762         Dispatcher->UnlockQueueWakeup();
763 }
764
765 Version ModuleSQL::GetVersion()
766 {
767         return Version("SQL Service Provider module for all other m_sql* modules", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
768 }
769
770 void DispatcherThread::Run()
771 {
772         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
773
774         SQLConnection* conn = NULL;
775
776         this->LockQueue();
777         while (!this->GetExitFlag())
778         {
779                 if (Parent->rehashing)
780                 {
781                         Parent->rehashing = false;
782                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
783                 }
784
785                 conn = NULL;
786                 Parent->ConnMutex.Lock();
787                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
788                 {
789                         if (i->second->queue.totalsize())
790                         {
791                                 conn = i->second;
792                                 break;
793                         }
794                 }
795                 Parent->ConnMutex.Unlock();
796
797                 if (conn)
798                 {
799                         /* There's an item! */
800                         this->UnlockQueue();
801                         conn->DoLeadingQuery();
802                         this->NotifyParent();
803                         this->LockQueue();
804                         conn->queue.pop();
805                 }
806                 else
807                 {
808                         /* We know the queue is empty, we can safely hang this thread until
809                          * something happens
810                          */
811                         this->WaitForQueue();
812                 }
813         }
814         this->UnlockQueue();
815 }
816
817 void DispatcherThread::OnNotify()
818 {
819         SQLConnection* conn;
820         while (1)
821         {
822                 conn = NULL;
823                 Parent->ConnMutex.Lock();
824                 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
825                 {
826                         if (!iter->second->rq.empty())
827                         {
828                                 conn = iter->second;
829                                 break;
830                         }
831                 }
832                 Parent->ConnMutex.Unlock();
833
834                 if (!conn)
835                         break;
836
837                 Parent->ResultsMutex.Lock();
838                 ResultQueue::iterator n = conn->rq.begin();
839                 Parent->ResultsMutex.Unlock();
840
841                 (*n)->Send();
842                 delete (*n);
843
844                 Parent->ResultsMutex.Lock();
845                 conn->rq.pop_front();
846                 Parent->ResultsMutex.Unlock();
847         }
848 }
849
850 MODULE_INIT(ModuleSQL)