/
mythdbcon.cpp
997 lines (829 loc) · 26.4 KB
/
mythdbcon.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
#include <unistd.h>
// ANSI C
#include <cstdlib>
// Qt
#include <QVector>
#include <QSqlDriver>
#include <QSemaphore>
#include <QSqlError>
#include <QSqlField>
#include <QSqlRecord>
#include <QElapsedTimer>
#include <QCoreApplication>
// MythTV
#include "compat.h"
#include "mythdbcon.h"
#include "mythdb.h"
#include "mythcorecontext.h"
#include "mythlogging.h"
#include "mythsystemlegacy.h"
#include "exitcodes.h"
#include "mthread.h"
#include "mythdate.h"
#include "portchecker.h"
#define DEBUG_RECONNECT 0
#if DEBUG_RECONNECT
#include <stdlib.h>
#endif
static const uint kPurgeTimeout = 60 * 60;
bool TestDatabase(QString dbHostName,
QString dbUserName,
QString dbPassword,
QString dbName,
int dbPort)
{
bool ret = false;
if (dbHostName.isEmpty() || dbUserName.isEmpty())
return ret;
MSqlDatabase *db = new MSqlDatabase("dbtest");
if (!db)
return ret;
DatabaseParams dbparms;
dbparms.dbName = dbName;
dbparms.dbUserName = dbUserName;
dbparms.dbPassword = dbPassword;
dbparms.dbHostName = dbHostName;
dbparms.dbPort = dbPort;
// Just use some sane defaults for these values
dbparms.wolEnabled = false;
dbparms.wolReconnect = 1;
dbparms.wolRetry = 3;
dbparms.wolCommand = QString();
db->SetDBParams(dbparms);
ret = db->OpenDatabase(true);
delete db;
db = NULL;
return ret;
}
MSqlDatabase::MSqlDatabase(const QString &name)
{
m_name = name;
m_name.detach();
if (!QSqlDatabase::isDriverAvailable("QMYSQL"))
{
LOG(VB_FLUSH, LOG_CRIT, "FATAL: Unable to load the QT mysql driver, is it installed?");
exit(GENERIC_EXIT_DB_ERROR); // Exits before we can process the log queue
//return;
}
m_db = QSqlDatabase::addDatabase("QMYSQL", m_name);
LOG(VB_DATABASE, LOG_INFO, "Database object created: " + m_name);
if (!m_db.isValid() || m_db.isOpenError())
{
LOG(VB_FLUSH, LOG_CRIT, MythDB::DBErrorMessage(m_db.lastError()));
LOG(VB_FLUSH, LOG_CRIT, QString("FATAL: Unable to create database object (%1), the installed QT driver may be invalid.").arg(m_name));
exit(GENERIC_EXIT_DB_ERROR); // Exits before we can process the log queue
//return;
}
m_lastDBKick = MythDate::current().addSecs(-60);
}
MSqlDatabase::~MSqlDatabase()
{
if (m_db.isOpen())
{
m_db.close();
m_db = QSqlDatabase(); // forces a destroy and must be done before
// removeDatabase() so that connections
// and queries are cleaned up correctly
QSqlDatabase::removeDatabase(m_name);
LOG(VB_DATABASE, LOG_INFO, "Database object deleted: " + m_name);
}
}
bool MSqlDatabase::isOpen()
{
if (m_db.isValid())
{
if (m_db.isOpen())
return true;
}
return false;
}
bool MSqlDatabase::OpenDatabase(bool skipdb)
{
if (!m_db.isValid())
{
LOG(VB_GENERAL, LOG_ERR,
"MSqlDatabase::OpenDatabase(), db object is not valid!");
return false;
}
bool connected = true;
if (!m_db.isOpen())
{
if (!skipdb)
m_dbparms = GetMythDB()->GetDatabaseParams();
m_db.setDatabaseName(m_dbparms.dbName);
m_db.setUserName(m_dbparms.dbUserName);
m_db.setPassword(m_dbparms.dbPassword);
if (m_dbparms.dbHostName.isEmpty()) // Bootstrapping without a database?
{
connected = true; // Pretend to be connected
return true; // to reduce errors
}
else
{
// code to ensure that a link-local ip address has the scope
int port = 3306;
if (m_dbparms.dbPort)
port = m_dbparms.dbPort;
PortChecker::resolveLinkLocal(m_dbparms.dbHostName, port);
m_db.setHostName(m_dbparms.dbHostName);
}
if (m_dbparms.dbPort)
m_db.setPort(m_dbparms.dbPort);
// Prefer using the faster localhost connection if using standard
// ports, even if the user specified a DBHostName of 127.0.0.1. This
// will cause MySQL to use a Unix socket (on *nix) or shared memory (on
// Windows) connection.
if ((m_dbparms.dbPort == 0 || m_dbparms.dbPort == 3306) &&
m_dbparms.dbHostName == "127.0.0.1")
m_db.setHostName("localhost");
// Default read timeout is 10 mins - set a better value 30 seconds
m_db.setConnectOptions(QString("MYSQL_OPT_READ_TIMEOUT=30"));
connected = m_db.open();
if (!connected && m_dbparms.wolEnabled
&& gCoreContext->IsWOLAllowed())
{
int trycount = 0;
while (!connected && trycount++ < m_dbparms.wolRetry)
{
LOG(VB_GENERAL, LOG_INFO,
QString("Using WOL to wakeup database server (Try %1 of "
"%2)")
.arg(trycount).arg(m_dbparms.wolRetry));
if (myth_system(m_dbparms.wolCommand) != GENERIC_EXIT_OK)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Failed to run WOL command '%1'")
.arg(m_dbparms.wolCommand));
}
sleep(m_dbparms.wolReconnect);
connected = m_db.open();
}
if (!connected)
{
LOG(VB_GENERAL, LOG_ERR,
"WOL failed, unable to connect to database!");
}
}
if (connected)
{
LOG(VB_DATABASE, LOG_INFO,
QString("[%1] Connected to database '%2' at host: %3")
.arg(m_name)
.arg(m_db.databaseName()).arg(m_db.hostName()));
InitSessionVars();
// WriteDelayed depends on SetHaveDBConnection() and SetHaveSchema()
// both being called with true, so order is important here.
GetMythDB()->SetHaveDBConnection(true);
if (!GetMythDB()->HaveSchema())
{
// We can't just check the count of QSqlDatabase::tables()
// because it returns all tables visible to the user in *all*
// databases (not just the current DB).
bool have_schema = false;
QString sql = "SELECT COUNT( "
" INFORMATION_SCHEMA.TABLES.TABLE_NAME "
" ) "
" FROM INFORMATION_SCHEMA.TABLES "
" WHERE INFORMATION_SCHEMA.TABLES.TABLE_SCHEMA "
" = DATABASE() "
" AND INFORMATION_SCHEMA.TABLES.TABLE_TYPE = "
" 'BASE TABLE';";
// We can't use MSqlQuery to determine if we have a schema,
// since it will open a new connection, which will try to check
// if we have a schema
QSqlQuery query = m_db.exec(sql); // don't convert to MSqlQuery
if (query.next())
have_schema = query.value(0).toInt() > 1;
GetMythDB()->SetHaveSchema(have_schema);
}
GetMythDB()->WriteDelayedSettings();
}
}
if (!connected)
{
GetMythDB()->SetHaveDBConnection(false);
LOG(VB_GENERAL, LOG_ERR, QString("[%1] Unable to connect to database!").arg(m_name));
LOG(VB_GENERAL, LOG_ERR, MythDB::DBErrorMessage(m_db.lastError()));
}
return connected;
}
bool MSqlDatabase::KickDatabase(void)
{
m_lastDBKick = MythDate::current().addSecs(-60);
if (!m_db.isOpen())
m_db.open();
return m_db.isOpen();
}
bool MSqlDatabase::Reconnect()
{
m_db.close();
m_db.open();
bool open = m_db.isOpen();
if (open)
{
LOG(VB_GENERAL, LOG_INFO, "MySQL reconnected successfully");
InitSessionVars();
}
return open;
}
void MSqlDatabase::InitSessionVars()
{
// Make sure NOW() returns time in UTC...
m_db.exec("SET @@session.time_zone='+00:00'");
// Disable strict mode
m_db.exec("SET @@session.sql_mode=''");
}
// -----------------------------------------------------------------------
MDBManager::MDBManager()
{
m_nextConnID = 0;
m_connCount = 0;
m_schedCon = NULL;
m_DDCon = NULL;
}
MDBManager::~MDBManager()
{
CloseDatabases();
if (m_connCount != 0 || m_schedCon || m_DDCon)
{
LOG(VB_GENERAL, LOG_CRIT,
"MDBManager exiting with connections still open");
}
#if 0 /* some post logStop() debugging... */
cout<<"m_connCount: "<<m_connCount<<endl;
cout<<"m_schedCon: "<<m_schedCon<<endl;
cout<<"m_DDCon: "<<m_DDCon<<endl;
#endif
}
MSqlDatabase *MDBManager::popConnection(bool reuse)
{
PurgeIdleConnections(true);
m_lock.lock();
MSqlDatabase *db;
#if REUSE_CONNECTION
if (reuse)
{
db = m_inuse[QThread::currentThread()];
if (db != NULL)
{
m_inuse_count[QThread::currentThread()]++;
m_lock.unlock();
return db;
}
}
#endif
DBList &list = m_pool[QThread::currentThread()];
if (list.isEmpty())
{
db = new MSqlDatabase("DBManager" + QString::number(m_nextConnID++));
++m_connCount;
LOG(VB_DATABASE, LOG_INFO,
QString("New DB connection, total: %1").arg(m_connCount));
}
else
{
db = list.back();
list.pop_back();
}
#if REUSE_CONNECTION
if (reuse)
{
m_inuse_count[QThread::currentThread()]=1;
m_inuse[QThread::currentThread()] = db;
}
#endif
m_lock.unlock();
db->OpenDatabase();
return db;
}
void MDBManager::pushConnection(MSqlDatabase *db)
{
m_lock.lock();
#if REUSE_CONNECTION
if (db == m_inuse[QThread::currentThread()])
{
int cnt = --m_inuse_count[QThread::currentThread()];
if (cnt > 0)
{
m_lock.unlock();
return;
}
m_inuse[QThread::currentThread()] = NULL;
}
#endif
if (db)
{
db->m_lastDBKick = MythDate::current();
m_pool[QThread::currentThread()].push_front(db);
}
m_lock.unlock();
PurgeIdleConnections(true);
}
void MDBManager::PurgeIdleConnections(bool leaveOne)
{
QMutexLocker locker(&m_lock);
leaveOne = leaveOne || (gCoreContext && gCoreContext->IsUIThread());
QDateTime now = MythDate::current();
DBList &list = m_pool[QThread::currentThread()];
DBList::iterator it = list.begin();
uint purgedConnections = 0, totalConnections = 0;
MSqlDatabase *newDb = NULL;
while (it != list.end())
{
totalConnections++;
if ((*it)->m_lastDBKick.secsTo(now) <= (int)kPurgeTimeout)
{
++it;
continue;
}
// This connection has not been used in the kPurgeTimeout
// seconds close it.
MSqlDatabase *entry = *it;
it = list.erase(it);
--m_connCount;
purgedConnections++;
// Qt's MySQL driver apparently keeps track of the number of
// open DB connections, and when it hits 0, calls
// my_thread_global_end(). The mysql library then assumes the
// application is ending and that all threads that created DB
// connections have already exited. This is rarely true, and
// may result in the mysql library pausing 5 seconds and
// printing a message like "Error in my_thread_global_end(): 1
// threads didn't exit". This workaround simply creates an
// extra DB connection before all pooled connections are
// purged so that my_thread_global_end() won't be called.
if (leaveOne && it == list.end() &&
purgedConnections > 0 &&
totalConnections == purgedConnections)
{
newDb = new MSqlDatabase("DBManager" +
QString::number(m_nextConnID++));
++m_connCount;
LOG(VB_GENERAL, LOG_INFO,
QString("New DB connection, total: %1").arg(m_connCount));
newDb->m_lastDBKick = MythDate::current();
}
LOG(VB_DATABASE, LOG_INFO, "Deleting idle DB connection...");
delete entry;
LOG(VB_DATABASE, LOG_INFO, "Done deleting idle DB connection.");
}
if (newDb)
list.push_front(newDb);
if (purgedConnections)
{
LOG(VB_DATABASE, LOG_INFO,
QString("Purged %1 idle of %2 total DB connections.")
.arg(purgedConnections).arg(totalConnections));
}
}
MSqlDatabase *MDBManager::getStaticCon(MSqlDatabase **dbcon, QString name)
{
if (!dbcon)
return NULL;
if (!*dbcon)
{
*dbcon = new MSqlDatabase(name);
LOG(VB_GENERAL, LOG_INFO, "New static DB connection" + name);
}
(*dbcon)->OpenDatabase();
if (!m_static_pool[QThread::currentThread()].contains(*dbcon))
m_static_pool[QThread::currentThread()].push_back(*dbcon);
return *dbcon;
}
MSqlDatabase *MDBManager::getSchedCon()
{
return getStaticCon(&m_schedCon, "SchedCon");
}
MSqlDatabase *MDBManager::getDDCon()
{
return getStaticCon(&m_DDCon, "DataDirectCon");
}
void MDBManager::CloseDatabases()
{
m_lock.lock();
DBList list = m_pool[QThread::currentThread()];
m_pool[QThread::currentThread()].clear();
m_lock.unlock();
for (DBList::iterator it = list.begin(); it != list.end(); ++it)
{
LOG(VB_DATABASE, LOG_INFO,
"Closing DB connection named '" + (*it)->m_name + "'");
(*it)->m_db.close();
delete (*it);
m_connCount--;
}
m_lock.lock();
DBList &slist = m_static_pool[QThread::currentThread()];
while (!slist.isEmpty())
{
MSqlDatabase *db = slist.takeFirst();
LOG(VB_DATABASE, LOG_INFO,
"Closing DB connection named '" + db->m_name + "'");
db->m_db.close();
delete db;
if (db == m_schedCon)
m_schedCon = NULL;
if (db == m_DDCon)
m_DDCon = NULL;
}
m_lock.unlock();
}
// -----------------------------------------------------------------------
static void InitMSqlQueryInfo(MSqlQueryInfo &qi)
{
qi.db = NULL;
qi.qsqldb = QSqlDatabase();
qi.returnConnection = true;
}
MSqlQuery::MSqlQuery(const MSqlQueryInfo &qi)
: QSqlQuery(QString::null, qi.qsqldb)
{
m_isConnected = false;
m_db = qi.db;
m_returnConnection = qi.returnConnection;
m_isConnected = m_db && m_db->isOpen();
#ifdef DEBUG_QT4_PORT
m_testbindings = QRegExp("(:\\w+)\\W.*\\1\\b");
#endif
}
MSqlQuery::~MSqlQuery()
{
if (m_returnConnection)
{
MDBManager *dbmanager = GetMythDB()->GetDBManager();
if (dbmanager && m_db)
{
dbmanager->pushConnection(m_db);
}
}
}
MSqlQueryInfo MSqlQuery::InitCon(ConnectionReuse _reuse)
{
bool reuse = kNormalConnection == _reuse;
MSqlDatabase *db = GetMythDB()->GetDBManager()->popConnection(reuse);
MSqlQueryInfo qi;
InitMSqlQueryInfo(qi);
// Bootstrapping without a database?
//if (db->pretendHaveDB)
if (db->m_db.hostName().isEmpty())
{
// Return an invalid database so that QSqlQuery does nothing.
// Also works around a Qt4 bug where QSqlQuery::~QSqlQuery
// calls QMYSQLResult::cleanup() which uses mysql_next_result()
GetMythDB()->GetDBManager()->pushConnection(db);
qi.returnConnection = false;
return qi;
}
qi.db = db;
qi.qsqldb = db->db();
db->KickDatabase();
return qi;
}
MSqlQueryInfo MSqlQuery::SchedCon()
{
MSqlDatabase *db = GetMythDB()->GetDBManager()->getSchedCon();
MSqlQueryInfo qi;
InitMSqlQueryInfo(qi);
qi.returnConnection = false;
if (db)
{
qi.db = db;
qi.qsqldb = db->db();
db->KickDatabase();
}
return qi;
}
MSqlQueryInfo MSqlQuery::DDCon()
{
MSqlDatabase *db = GetMythDB()->GetDBManager()->getDDCon();
MSqlQueryInfo qi;
InitMSqlQueryInfo(qi);
qi.returnConnection = false;
if (db)
{
qi.db = db;
qi.qsqldb = db->db();
db->KickDatabase();
}
return qi;
}
bool MSqlQuery::exec()
{
if (!m_db)
{
// Database structure's been deleted
return false;
}
if (m_last_prepared_query.isEmpty())
{
LOG(VB_GENERAL, LOG_ERR,
"MSqlQuery::exec(void) called without a prepared query.");
return false;
}
#if DEBUG_RECONNECT
if (random() < RAND_MAX / 50)
{
LOG(VB_GENERAL, LOG_INFO,
"MSqlQuery disconnecting DB to test reconnection logic");
m_db->m_db.close();
}
#endif
// Database connection down. Try to restart it, give up if it's still
// down
if (!m_db->isOpen() && !Reconnect())
{
LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
return false;
}
QElapsedTimer timer;
timer.start();
bool result = QSqlQuery::exec();
qint64 elapsed = timer.elapsed();
// if the query failed with "MySQL server has gone away"
// Close and reopen the database connection and retry the query if it
// connects again
if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect())
result = QSqlQuery::exec();
if (!result)
{
QString err = MythDB::GetError("MSqlQuery", *this);
MSqlBindings tmp = QSqlQuery::boundValues();
bool has_null_strings = false;
for (MSqlBindings::iterator it = tmp.begin(); it != tmp.end(); ++it)
{
if (it->type() != QVariant::String)
continue;
if (it->isNull() || it->toString().isNull())
{
has_null_strings = true;
*it = QVariant(QString(""));
}
}
if (has_null_strings)
{
bindValues(tmp);
timer.restart();
result = QSqlQuery::exec();
elapsed = timer.elapsed();
}
if (result)
{
LOG(VB_GENERAL, LOG_ERR,
QString("Original query failed, but resend with empty "
"strings in place of NULL strings worked. ") +
"\n" + err);
}
}
if (VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_INFO))
{
QString str = lastQuery();
// Database logging will cause an infinite loop here if not filtered
// out
if (!str.startsWith("INSERT INTO logging "))
{
// Sadly, neither executedQuery() nor lastQuery() display
// the values in bound queries against a MySQL5 database.
// So, replace the named placeholders with their values.
QMapIterator<QString, QVariant> b = boundValues();
while (b.hasNext())
{
b.next();
str.replace(b.key(), '\'' + b.value().toString() + '\'');
}
LOG(VB_DATABASE, LOG_INFO,
QString("MSqlQuery::exec(%1) %2%3%4")
.arg(m_db->MSqlDatabase::GetConnectionName()).arg(str)
.arg(QString(" <<<< Took %1ms").arg(QString::number(elapsed)))
.arg(isSelect() ? QString(", Returned %1 row(s)")
.arg(size()) : QString()));
}
}
return result;
}
bool MSqlQuery::exec(const QString &query)
{
if (!m_db)
{
// Database structure's been deleted
return false;
}
// Database connection down. Try to restart it, give up if it's still
// down
if (!m_db->isOpen() && !Reconnect())
{
LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
return false;
}
bool result = QSqlQuery::exec(query);
// if the query failed with "MySQL server has gone away"
// Close and reopen the database connection and retry the query if it
// connects again
if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect())
result = QSqlQuery::exec(query);
LOG(VB_DATABASE, LOG_INFO,
QString("MSqlQuery::exec(%1) %2%3")
.arg(m_db->MSqlDatabase::GetConnectionName()).arg(query)
.arg(isSelect() ? QString(" <<<< Returns %1 row(s)")
.arg(size()) : QString()));
return result;
}
bool MSqlQuery::seekDebug(const char *type, bool result,
int where, bool relative) const
{
if (result && VERBOSE_LEVEL_CHECK(VB_DATABASE, LOG_DEBUG))
{
QString str;
QSqlRecord rec = record();
for (long int i = 0; i < rec.count(); i++)
{
if (!str.isEmpty())
str.append(", ");
str.append(rec.fieldName(i) + " = " +
value(i).toString());
}
if (QString("seek")==type)
{
LOG(VB_DATABASE, LOG_DEBUG,
QString("MSqlQuery::seek(%1,%2,%3) Result: \"%4\"")
.arg(m_db->MSqlDatabase::GetConnectionName())
.arg(where).arg(relative)
.arg(str));
}
else
{
LOG(VB_DATABASE, LOG_DEBUG,
QString("MSqlQuery::%1(%2) Result: \"%3\"")
.arg(type).arg(m_db->MSqlDatabase::GetConnectionName())
.arg(str));
}
}
return result;
}
bool MSqlQuery::next(void)
{
return seekDebug("next", QSqlQuery::next(), 0, false);
}
bool MSqlQuery::previous(void)
{
return seekDebug("previous", QSqlQuery::previous(), 0, false);
}
bool MSqlQuery::first(void)
{
return seekDebug("first", QSqlQuery::first(), 0, false);
}
bool MSqlQuery::last(void)
{
return seekDebug("last", QSqlQuery::last(), 0, false);
}
bool MSqlQuery::seek(int where, bool relative)
{
return seekDebug("seek", QSqlQuery::seek(where, relative), where, relative);
}
bool MSqlQuery::prepare(const QString& query)
{
if (!m_db)
{
// Database structure's been deleted
return false;
}
m_last_prepared_query = query;
#ifdef DEBUG_QT4_PORT
if (query.contains(m_testbindings))
{
LOG(VB_GENERAL, LOG_DEBUG,
QString("\n\nQuery contains bind value \"%1\" twice:\n\n\n")
.arg(m_testbindings.cap(1)) + query);
#if 0
exit(1);
#endif
}
#endif
// Database connection down. Try to restart it, give up if it's still
// down
if (!m_db)
{
// Database structure has been deleted...
return false;
}
if (!m_db->isOpen() && !Reconnect())
{
LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected");
return false;
}
// QT docs indicate that there are significant speed ups and a reduction
// in memory usage by enabling forward-only cursors
//
// Unconditionally enable this since all existing uses of the database
// iterate forward over the result set.
setForwardOnly(true);
bool ok = QSqlQuery::prepare(query);
// if the prepare failed with "MySQL server has gone away"
// Close and reopen the database connection and retry the query if it
// connects again
if (!ok && QSqlQuery::lastError().number() == 2006 && Reconnect())
ok = true;
if (!ok && !(GetMythDB()->SuppressDBMessages()))
{
LOG(VB_GENERAL, LOG_ERR,
QString("Error preparing query: %1").arg(query));
LOG(VB_GENERAL, LOG_ERR,
MythDB::DBErrorMessage(QSqlQuery::lastError()));
}
return ok;
}
bool MSqlQuery::testDBConnection()
{
MSqlDatabase *db = GetMythDB()->GetDBManager()->popConnection(true);
// popConnection() has already called OpenDatabase(),
// so we only have to check if it was successful:
bool isOpen = db->isOpen();
GetMythDB()->GetDBManager()->pushConnection(db);
return isOpen;
}
void MSqlQuery::bindValue(const QString &placeholder, const QVariant &val)
{
#ifdef DEBUG_QT4_PORT
// XXX - HACK BEGIN
// qt4 doesn't like to bind values without occurrence in the prepared query
if (!m_last_prepared_query.contains(placeholder))
{
LOG(VB_GENERAL, LOG_ERR, "Trying to bind a value to placeholder " +
placeholder + " without occurrence in the prepared query."
" Ignoring it.\nQuery was: \"" + m_last_prepared_query + "\"");
return;
}
// XXX - HACK END
#endif
QSqlQuery::bindValue(placeholder, val, QSql::In);
}
void MSqlQuery::bindValues(const MSqlBindings &bindings)
{
MSqlBindings::const_iterator it;
for (it = bindings.begin(); it != bindings.end(); ++it)
{
bindValue(it.key(), it.value());
}
}
QVariant MSqlQuery::lastInsertId()
{
return QSqlQuery::lastInsertId();
}
bool MSqlQuery::Reconnect(void)
{
if (!m_db->Reconnect())
return false;
if (!m_last_prepared_query.isEmpty())
{
MSqlBindings tmp = QSqlQuery::boundValues();
if (!QSqlQuery::prepare(m_last_prepared_query))
return false;
bindValues(tmp);
}
return true;
}
void MSqlAddMoreBindings(MSqlBindings &output, MSqlBindings &addfrom)
{
MSqlBindings::Iterator it;
for (it = addfrom.begin(); it != addfrom.end(); ++it)
{
output.insert(it.key(), it.value());
}
}
struct Holder {
Holder( const QString& hldr = QString::null, int pos = -1 )
: holderName( hldr ), holderPos( pos ) {}
bool operator==( const Holder& h ) const
{ return h.holderPos == holderPos && h.holderName == holderName; }
bool operator!=( const Holder& h ) const
{ return h.holderPos != holderPos || h.holderName != holderName; }
QString holderName;
int holderPos;
};
void MSqlEscapeAsAQuery(QString &query, MSqlBindings &bindings)
{
MSqlQuery result(MSqlQuery::InitCon());
QString q = query;
QRegExp rx(QString::fromLatin1("'[^']*'|:([a-zA-Z0-9_]+)"));
QVector<Holder> holders;
int i = 0;
while ((i = rx.indexIn(q, i)) != -1)
{
if (!rx.cap(1).isEmpty())
holders.append(Holder(rx.cap(0), i));
i += rx.matchedLength();
}
QVariant val;
QString holder;
for (i = (int)holders.count() - 1; i >= 0; --i)
{
holder = holders[(uint)i].holderName;
val = bindings[holder];
QSqlField f("", val.type());
if (val.isNull())
f.clear();
else
f.setValue(val);
query = query.replace((uint)holders[(uint)i].holderPos, holder.length(),
result.driver()->formatValue(f));
}
}