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