]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_mysql.cpp
3718eecf85284768a0cd08b36cdb7e1f4742cb3f
[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          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);
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         std::string initquery;
309
310  public:
311
312         QueryQueue queue;
313         ResultQueue rq;
314
315         // This constructor creates an SQLConnection object with the given credentials, but does not connect yet.
316         SQLConnection(const SQLhost &hi, ModuleSQL* Creator) : connection(NULL), host(hi), Enabled(false), Parent(Creator)
317         {
318         }
319
320         ~SQLConnection()
321         {
322                 Close();
323         }
324
325         // This method connects to the database using the credentials supplied to the constructor, and returns
326         // true upon success.
327         bool Connect()
328         {
329                 unsigned int timeout = 1;
330                 connection = mysql_init(connection);
331                 mysql_options(connection,MYSQL_OPT_CONNECT_TIMEOUT,(char*)&timeout);
332                 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);
333         }
334
335         void DoLeadingQuery()
336         {
337                 if (!CheckConnection())
338                         return;
339
340                 if( !initquery.empty() )
341                         mysql_query(connection,initquery.c_str());
342
343                 /* Parse the command string and dispatch it to mysql */
344                 SQLrequest& req = queue.front();
345
346                 /* Pointer to the buffer we screw around with substitution in */
347                 char* query;
348
349                 /* Pointer to the current end of query, where we append new stuff */
350                 char* queryend;
351
352                 /* Total length of the unescaped parameters */
353                 unsigned long maxparamlen, paramcount;
354
355                 /* The length of the longest parameter */
356                 maxparamlen = 0;
357
358                 for(ParamL::iterator i = req.query.p.begin(); i != req.query.p.end(); i++)
359                 {
360                         if (i->size() > maxparamlen)
361                                 maxparamlen = i->size();
362                 }
363
364                 /* How many params are there in the query? */
365                 paramcount = count(req.query.q.c_str(), '?');
366
367                 /* This stores copy of params to be inserted with using numbered params 1;3B*/
368                 ParamL paramscopy(req.query.p);
369
370                 /* To avoid a lot of allocations, allocate enough memory for the biggest the escaped query could possibly be.
371                  * sizeofquery + (maxtotalparamlength*2) + 1
372                  *
373                  * The +1 is for null-terminating the string for mysql_real_escape_string
374                  */
375
376                 query = new char[req.query.q.length() + (maxparamlen*paramcount*2) + 1];
377                 queryend = query;
378
379                 /* Okay, now we have a buffer large enough we need to start copying the query into it and escaping and substituting
380                  * the parameters into it...
381                  */
382
383                 for(unsigned long i = 0; i < req.query.q.length(); i++)
384                 {
385                         if(req.query.q[i] == '?')
386                         {
387                                 /* We found a place to substitute..what fun.
388                                  * use mysql calls to escape and write the
389                                  * escaped string onto the end of our query buffer,
390                                  * then we "just" need to make sure queryend is
391                                  * pointing at the right place.
392                                  */
393
394                                 /* Is it numbered parameter?
395                                  */
396
397                                 bool numbered;
398                                 numbered = false;
399
400                                 /* Numbered parameter number :|
401                                  */
402                                 unsigned int paramnum;
403                                 paramnum = 0;
404
405                                 /* Let's check if it's a numbered param. And also calculate it's number.
406                                  */
407
408                                 while ((i < req.query.q.length() - 1) && (req.query.q[i+1] >= '0') && (req.query.q[i+1] <= '9'))
409                                 {
410                                         numbered = true;
411                                         ++i;
412                                         paramnum = paramnum * 10 + req.query.q[i] - '0';
413                                 }
414
415                                 if (paramnum > paramscopy.size() - 1)
416                                 {
417                                         /* index is out of range!
418                                          */
419                                         numbered = false;
420                                 }
421
422                                 if (numbered)
423                                 {
424                                         unsigned long len = mysql_real_escape_string(connection, queryend, paramscopy[paramnum].c_str(), paramscopy[paramnum].length());
425
426                                         queryend += len;
427                                 }
428                                 else if (req.query.p.size())
429                                 {
430                                         unsigned long len = mysql_real_escape_string(connection, queryend, req.query.p.front().c_str(), req.query.p.front().length());
431
432                                         queryend += len;
433                                         req.query.p.pop_front();
434                                 }
435                                 else
436                                         break;
437                         }
438                         else
439                         {
440                                 *queryend = req.query.q[i];
441                                 queryend++;
442                         }
443                 }
444
445                 *queryend = 0;
446
447                 req.query.q = query;
448
449                 if (!mysql_real_query(connection, req.query.q.data(), req.query.q.length()))
450                 {
451                         /* Successfull query */
452                         res = mysql_use_result(connection);
453                         unsigned long rows = mysql_affected_rows(connection);
454                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), res, rows, req.id);
455                         r->dbid = this->GetID();
456                         r->query = req.query.q;
457                         /* Put this new result onto the results queue.
458                          * XXX: Remember to mutex the queue!
459                          */
460                         Parent->ResultsMutex.Lock();
461                         rq.push_back(r);
462                         Parent->ResultsMutex.Unlock();
463                 }
464                 else
465                 {
466                         /* XXX: See /usr/include/mysql/mysqld_error.h for a list of
467                          * possible error numbers and error messages */
468                         SQLerror e(SQL_QREPLY_FAIL, ConvToStr(mysql_errno(connection)) + std::string(": ") + mysql_error(connection));
469                         MySQLresult* r = new MySQLresult(Parent, req.GetSource(), e, req.id);
470                         r->dbid = this->GetID();
471                         r->query = req.query.q;
472
473                         Parent->ResultsMutex.Lock();
474                         rq.push_back(r);
475                         Parent->ResultsMutex.Unlock();
476                 }
477
478                 delete[] query;
479         }
480
481         bool ConnectionLost()
482         {
483                 if (&connection)
484                 {
485                         return (mysql_ping(connection) != 0);
486                 }
487                 else return false;
488         }
489
490         bool CheckConnection()
491         {
492                 if (ConnectionLost())
493                 {
494                         return Connect();
495                 }
496                 else return true;
497         }
498
499         std::string GetError()
500         {
501                 return mysql_error(connection);
502         }
503
504         const std::string& GetID()
505         {
506                 return host.id;
507         }
508
509         std::string GetHost()
510         {
511                 return host.host;
512         }
513
514         void setInitialQuery(std::string init)
515         {
516                 initquery = init;
517         }
518
519         void SetEnable(bool Enable)
520         {
521                 Enabled = Enable;
522         }
523
524         bool IsEnabled()
525         {
526                 return Enabled;
527         }
528
529         void Close()
530         {
531                 mysql_close(connection);
532         }
533
534         const SQLhost& GetConfHost()
535         {
536                 return host;
537         }
538
539 };
540
541 ConnMap Connections;
542
543 bool HasHost(const SQLhost &host)
544 {
545         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
546         {
547                 if (host == iter->second->GetConfHost())
548                         return true;
549         }
550         return false;
551 }
552
553 bool HostInConf(ConfigReader* conf, const SQLhost &h)
554 {
555         for(int i = 0; i < conf->Enumerate("database"); i++)
556         {
557                 SQLhost host;
558                 host.id         = conf->ReadValue("database", "id", i);
559                 host.host       = conf->ReadValue("database", "hostname", i);
560                 host.port       = conf->ReadInteger("database", "port", i, true);
561                 host.name       = conf->ReadValue("database", "name", i);
562                 host.user       = conf->ReadValue("database", "username", i);
563                 host.pass       = conf->ReadValue("database", "password", i);
564                 host.ssl        = conf->ReadFlag("database", "ssl", i);
565                 if (h == host)
566                         return true;
567         }
568         return false;
569 }
570
571 void ClearOldConnections(ConfigReader* conf)
572 {
573         ConnMap::iterator i,safei;
574         for (i = Connections.begin(); i != Connections.end(); i++)
575         {
576                 if (!HostInConf(conf, i->second->GetConfHost()))
577                 {
578                         delete i->second;
579                         safei = i;
580                         --i;
581                         Connections.erase(safei);
582                 }
583         }
584 }
585
586 void ClearAllConnections()
587 {
588         ConnMap::iterator i;
589         while ((i = Connections.begin()) != Connections.end())
590         {
591                 Connections.erase(i);
592                 delete i->second;
593         }
594 }
595
596 void ConnectDatabases(InspIRCd* ServerInstance, ModuleSQL* Parent)
597 {
598         for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
599         {
600                 if (i->second->IsEnabled())
601                         continue;
602
603                 i->second->SetEnable(true);
604                 if (!i->second->Connect())
605                 {
606                         /* XXX: MUTEX */
607                         Parent->LoggingMutex.Lock();
608                         ServerInstance->Logs->Log("m_mysql",DEFAULT,"SQL: Failed to connect database "+i->second->GetHost()+": Error: "+i->second->GetError());
609                         i->second->SetEnable(false);
610                         Parent->LoggingMutex.Unlock();
611                 }
612         }
613 }
614
615 void LoadDatabases(ConfigReader* conf, InspIRCd* ServerInstance, ModuleSQL* Parent)
616 {
617         Parent->ConnMutex.Lock();
618         ClearOldConnections(conf);
619         for (int j =0; j < conf->Enumerate("database"); j++)
620         {
621                 SQLhost host;
622                 host.id         = conf->ReadValue("database", "id", j);
623                 host.host       = conf->ReadValue("database", "hostname", j);
624                 host.port       = conf->ReadInteger("database", "port", j, true);
625                 host.name       = conf->ReadValue("database", "name", j);
626                 host.user       = conf->ReadValue("database", "username", j);
627                 host.pass       = conf->ReadValue("database", "password", j);
628                 host.ssl        = conf->ReadFlag("database", "ssl", j);
629                 std::string initquery = conf->ReadValue("database", "initialquery", j);
630
631                 if (HasHost(host))
632                         continue;
633
634                 if (!host.id.empty() && !host.host.empty() && !host.name.empty() && !host.user.empty() && !host.pass.empty())
635                 {
636                         SQLConnection* ThisSQL = new SQLConnection(host, Parent);
637                         Connections[host.id] = ThisSQL;
638
639                         ThisSQL->setInitialQuery(initquery);
640                 }
641         }
642         ConnectDatabases(ServerInstance, Parent);
643         Parent->ConnMutex.Unlock();
644 }
645
646 char FindCharId(const std::string &id)
647 {
648         char i = 1;
649         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
650         {
651                 if (iter->first == id)
652                 {
653                         return i;
654                 }
655         }
656         return 0;
657 }
658
659 ConnMap::iterator GetCharId(char id)
660 {
661         char i = 1;
662         for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); ++iter, ++i)
663         {
664                 if (i == id)
665                         return iter;
666         }
667         return Connections.end();
668 }
669
670 class ModuleSQL;
671
672 class DispatcherThread : public SocketThread
673 {
674  private:
675         ModuleSQL* Parent;
676         InspIRCd* ServerInstance;
677  public:
678         DispatcherThread(InspIRCd* Instance, ModuleSQL* CreatorModule) : SocketThread(Instance), Parent(CreatorModule), ServerInstance(Instance) { }
679         ~DispatcherThread() { }
680         virtual void Run();
681         virtual void OnNotify();
682 };
683
684 ModuleSQL::ModuleSQL(InspIRCd* Me) : Module(Me), rehashing(false)
685 {
686         ServerInstance->Modules->UseInterface("SQLutils");
687
688         Conf = new ConfigReader(ServerInstance);
689         PublicServerInstance = ServerInstance;
690         currid = 0;
691
692         Dispatcher = new DispatcherThread(ServerInstance, this);
693         ServerInstance->Threads->Start(Dispatcher);
694
695         if (!ServerInstance->Modules->PublishFeature("SQL", this))
696         {
697                 Dispatcher->join();
698                 delete Dispatcher;
699                 ServerInstance->Modules->DoneWithInterface("SQLutils");
700                 throw ModuleException("m_mysql: Unable to publish feature 'SQL'");
701         }
702
703         ServerInstance->Modules->PublishInterface("SQL", this);
704         Implementation eventlist[] = { I_OnRehash, I_OnRequest };
705         ServerInstance->Modules->Attach(eventlist, this, 2);
706 }
707
708 ModuleSQL::~ModuleSQL()
709 {
710         delete Dispatcher;
711         ClearAllConnections();
712         delete Conf;
713         ServerInstance->Modules->UnpublishInterface("SQL", this);
714         ServerInstance->Modules->UnpublishFeature("SQL");
715         ServerInstance->Modules->DoneWithInterface("SQLutils");
716 }
717
718 unsigned long ModuleSQL::NewID()
719 {
720         if (currid+1 == 0)
721                 currid++;
722         return ++currid;
723 }
724
725 const char* ModuleSQL::OnRequest(Request* request)
726 {
727         if(strcmp(SQLREQID, request->GetId()) == 0)
728         {
729                 SQLrequest* req = (SQLrequest*)request;
730
731                 ConnMap::iterator iter;
732
733                 const char* returnval = NULL;
734
735                 Dispatcher->LockQueue();
736                 ConnMutex.Lock();
737                 if((iter = Connections.find(req->dbid)) != Connections.end())
738                 {
739                         req->id = NewID();
740                         iter->second->queue.push(*req);
741                         returnval = SQLSUCCESS;
742                 }
743                 else
744                 {
745                         req->error.Id(SQL_BAD_DBID);
746                 }
747
748                 ConnMutex.Unlock();
749                 Dispatcher->UnlockQueueWakeup();
750                 /* Yes, it's possible this will generate a spurious wakeup.
751                  * That's fine, it'll just get ignored.
752                  */
753
754                 return returnval;
755         }
756
757         return NULL;
758 }
759
760 void ModuleSQL::OnRehash(User* user)
761 {
762         Dispatcher->LockQueue();
763         rehashing = true;
764         Dispatcher->UnlockQueueWakeup();
765 }
766
767 Version ModuleSQL::GetVersion()
768 {
769         return Version("SQL Service Provider module for all other m_sql* modules", VF_VENDOR | VF_SERVICEPROVIDER, API_VERSION);
770 }
771
772 void DispatcherThread::Run()
773 {
774         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
775
776         SQLConnection* conn = NULL;
777
778         this->LockQueue();
779         while (!this->GetExitFlag())
780         {
781                 if (Parent->rehashing)
782                 {
783                         Parent->rehashing = false;
784                         LoadDatabases(Parent->Conf, Parent->PublicServerInstance, Parent);
785                 }
786
787                 conn = NULL;
788                 Parent->ConnMutex.Lock();
789                 for (ConnMap::iterator i = Connections.begin(); i != Connections.end(); i++)
790                 {
791                         if (i->second->queue.totalsize())
792                         {
793                                 conn = i->second;
794                                 break;
795                         }
796                 }
797                 Parent->ConnMutex.Unlock();
798
799                 if (conn)
800                 {
801                         /* There's an item! */
802                         this->UnlockQueue();
803                         conn->DoLeadingQuery();
804                         this->NotifyParent();
805                         this->LockQueue();
806                         conn->queue.pop();
807                 }
808                 else
809                 {
810                         /* We know the queue is empty, we can safely hang this thread until
811                          * something happens
812                          */
813                         this->WaitForQueue();
814                 }
815         }
816         this->UnlockQueue();
817 }
818
819 void DispatcherThread::OnNotify()
820 {
821         SQLConnection* conn;
822         while (1)
823         {
824                 conn = NULL;
825                 Parent->ConnMutex.Lock();
826                 for (ConnMap::iterator iter = Connections.begin(); iter != Connections.end(); iter++)
827                 {
828                         if (!iter->second->rq.empty())
829                         {
830                                 conn = iter->second;
831                                 break;
832                         }
833                 }
834                 Parent->ConnMutex.Unlock();
835
836                 if (!conn)
837                         break;
838
839                 Parent->ResultsMutex.Lock();
840                 ResultQueue::iterator n = conn->rq.begin();
841                 Parent->ResultsMutex.Unlock();
842
843                 (*n)->Send();
844                 delete (*n);
845
846                 Parent->ResultsMutex.Lock();
847                 conn->rq.pop_front();
848                 Parent->ResultsMutex.Unlock();
849         }
850 }
851
852 MODULE_INIT(ModuleSQL)