1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the test suite of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
43 #include <QtTest/QtTest>
46 #include "../qsqldatabase/tst_databases.h"
56 const QString qtest(qTableName("qtest", __FILE__));
57 // set this define if Oracle is built with threading support
58 //#define QOCI_THREADED
60 class tst_QSqlThread : public QObject
66 virtual ~tst_QSqlThread();
69 void dropTestTables();
70 void createTestTables();
71 void recreateTestTables();
72 void repopulateTestTables();
74 void generic_data(const QString &engine=QString());
79 void cleanupTestCase();
84 void threadFinished() { ++threadFinishedCount; }
87 void simpleThreading_data() { generic_data(); }
88 void simpleThreading();
89 void readWriteThreading_data() { generic_data(); }
90 void readWriteThreading();
91 void readFromSingleConnection_data() { generic_data(); }
92 void readFromSingleConnection();
93 void readWriteFromSingleConnection_data() { generic_data(); }
94 void readWriteFromSingleConnection();
95 void preparedReadWriteFromSingleConnection_data() { generic_data(); }
96 void preparedReadWriteFromSingleConnection();
97 void transactionsFromSingleConnection_data() { generic_data(); }
98 void transactionsFromSingleConnection();
101 int threadFinishedCount;
104 static QBasicAtomicInt counter;
106 class QtTestSqlThread : public QThread
110 QtTestSqlThread(const QSqlDatabase &aDb, QObject *parent = 0)
111 : QThread(parent), sourceDb(aDb) {}
113 void runHelper(const QString &dbName)
115 QSqlDatabase db = QSqlDatabase::cloneDatabase(sourceDb, dbName);
116 QVERIFY_SQL(db, open());
119 QSqlQuery q("select id from " + qtest, db);
120 QVERIFY_SQL(q, isActive());
122 sum += q.value(0).toInt();
129 QString dbName = QString("QThreadDb%1").arg((size_t)currentThreadId());
132 QSqlDatabase::database(dbName).close();
133 QSqlDatabase::removeDatabase(dbName);
137 QSqlDatabase sourceDb;
140 enum { ProdConIterations = 10 };
142 class SqlProducer: public QThread
146 SqlProducer(const QSqlDatabase &aDb, QObject *parent = 0)
147 : QThread(parent), sourceDb(aDb) {}
149 void runHelper(const QString &dbName)
151 QSqlDatabase db = QSqlDatabase::cloneDatabase(sourceDb, dbName);
152 QVERIFY_SQL(db, open());
154 QVERIFY_SQL(q, prepare("insert into " + qtest + " values (?, ?, ?)"));
156 for (int i = 0; i < ProdConIterations; ++i) {
157 q.bindValue(0, ++id);
158 q.bindValue(1, "threaddy");
160 QVERIFY_SQL(q, exec());
169 QString dbName = QString("Producer%1").arg((size_t)currentThreadId());
171 QSqlDatabase::database(dbName).close();
172 QSqlDatabase::removeDatabase(dbName);
175 QSqlDatabase sourceDb;
178 class SqlConsumer: public QThread
183 SqlConsumer(const QSqlDatabase &aDb, QObject *parent = 0)
184 : QThread(parent), sourceDb(aDb) {}
186 void runHelper(const QString &dbName)
188 QSqlDatabase db = QSqlDatabase::cloneDatabase(sourceDb, dbName);
189 QVERIFY_SQL(db, open());
190 QSqlQuery q1(db), q2(db);
191 QVERIFY_SQL(q2, prepare("delete from " + qtest + " where id = :id"));
193 for (int i = 0; i < ProdConIterations; ++i) {
194 QVERIFY_SQL(q1, exec("select max(id) from " + qtest));
196 q2.bindValue("id", q1.value(0));
198 QVERIFY_SQL(q2, exec());
207 QString dbName = QString("Consumer%1").arg((size_t)currentThreadId());
209 QSqlDatabase::database(dbName).close();
210 QSqlDatabase::removeDatabase(dbName);
214 QSqlDatabase sourceDb;
217 class SqlThread: public QThread
222 enum Mode { SimpleReading, PreparedReading, SimpleWriting, PreparedWriting };
224 SqlThread(Mode m, const QSqlDatabase &db, QObject *parent = 0)
225 : QThread(parent), sourceDb(db), mode(m) {}
229 QSqlDatabase &db = sourceDb;
231 case SimpleReading: {
232 // Executes a Query for reading, iterates over the first 4 results
233 QSqlQuery q(sourceDb);
234 for (int j = 0; j < ProdConIterations; ++j) {
235 QVERIFY_SQL(q, exec("select id,name from " + qtest + " order by id"));
236 for (int i = 1; i < 4; ++i) {
237 QVERIFY_SQL(q, next());
238 QCOMPARE(q.value(0).toInt(), i);
242 case SimpleWriting: {
243 // Executes a query for writing (appends a new row)
244 QSqlQuery q(sourceDb);
245 for (int j = 0; j < ProdConIterations; ++j) {
246 QVERIFY_SQL(q, exec(QString("insert into " + qtest
247 + " (id, name) values(%1, '%2')")
248 .arg(counter.fetchAndAddRelaxed(1)).arg("Robert")));
251 case PreparedReading: {
252 // Prepares a query for reading and iterates over the results
253 QSqlQuery q(sourceDb);
254 QVERIFY_SQL(q, prepare("select id, name from " + qtest + " where id = ?"));
255 for (int j = 0; j < ProdConIterations; ++j) {
256 q.addBindValue(j % 3 + 1);
257 QVERIFY_SQL(q, exec());
258 QVERIFY_SQL(q, next());
259 QCOMPARE(q.value(0).toInt(), j % 3 + 1);
262 case PreparedWriting: {
263 QSqlQuery q(sourceDb);
264 QVERIFY_SQL(q, prepare("insert into " + qtest + " (id, name) "
266 for (int i = 0; i < ProdConIterations; ++i) {
267 q.addBindValue(counter.fetchAndAddRelaxed(1));
268 q.addBindValue("Robert");
269 QVERIFY_SQL(q, exec());
276 QSqlDatabase sourceDb;
281 tst_QSqlThread::tst_QSqlThread()
282 : threadFinishedCount(0)
286 tst_QSqlThread::~tst_QSqlThread()
290 void tst_QSqlThread::generic_data(const QString& engine)
292 if ( dbs.fillTestTable(engine) == 0 ) {
294 QSKIP( "No database drivers are available in this Qt configuration");
296 QSKIP( (QString("No database drivers of type %1 are available in this Qt configuration").arg(engine)).toLocal8Bit());
300 void tst_QSqlThread::dropTestTables()
302 for (int i = 0; i < dbs.dbNames.count(); ++i) {
303 QSqlDatabase db = QSqlDatabase::database(dbs.dbNames.at(i));
306 tst_Databases::safeDropTables(db, QStringList() << qtest << qTableName("qtest2", __FILE__) << qTableName("emptytable", __FILE__));
310 void tst_QSqlThread::createTestTables()
312 for (int i = 0; i < dbs.dbNames.count(); ++i) {
313 QSqlDatabase db = QSqlDatabase::database(dbs.dbNames.at(i));
316 QVERIFY_SQL(q, exec("create table " + qtest
317 + "(id int NOT NULL primary key, name varchar(20), title int)"));
319 QVERIFY_SQL(q, exec("create table " + qTableName("qtest2", __FILE__)
320 + "(id int NOT NULL primary key, title varchar(20))"));
322 QVERIFY_SQL(q, exec("create table " + qTableName("emptytable", __FILE__)
323 + "(id int NOT NULL primary key)"));
327 void tst_QSqlThread::repopulateTestTables()
329 for (int i = 0; i < dbs.dbNames.count(); ++i) {
330 QSqlDatabase db = QSqlDatabase::database(dbs.dbNames.at(i));
333 QVERIFY_SQL(q, exec("delete from " + qtest));
334 QVERIFY_SQL(q, exec("insert into " + qtest + " values(1, 'harry', 1)"));
335 QVERIFY_SQL(q, exec("insert into " + qtest + " values(2, 'trond', 2)"));
336 QVERIFY_SQL(q, exec("insert into " + qtest + " values(3, 'vohi', 3)"));
338 QVERIFY_SQL(q, exec("delete from " + qTableName("qtest2", __FILE__)));
339 QVERIFY_SQL(q, exec("insert into " + qTableName("qtest2", __FILE__) + " values(1, 'herr')"));
340 QVERIFY_SQL(q, exec("insert into " + qTableName("qtest2", __FILE__) + " values(2, 'mister')"));
344 void tst_QSqlThread::recreateTestTables()
348 repopulateTestTables();
351 void tst_QSqlThread::initTestCase()
354 recreateTestTables();
357 void tst_QSqlThread::cleanupTestCase()
363 void tst_QSqlThread::init()
365 threadFinishedCount = 0;
369 void tst_QSqlThread::cleanup()
371 // repopulateTestTables();
374 // This test creates two threads that clone their db connection and read
376 void tst_QSqlThread::simpleThreading()
378 QFETCH(QString, dbName);
379 QSqlDatabase db = QSqlDatabase::database(dbName);
382 if (db.databaseName() == ":memory:")
383 QSKIP("does not work with in-memory databases");
385 QtTestSqlThread t1(db);
386 QtTestSqlThread t2(db);
388 connect(&t1, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
389 connect(&t2, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
394 while (threadFinishedCount < 2)
398 // This test creates two threads that clone their db connection and read
400 void tst_QSqlThread::readWriteThreading()
402 QFETCH(QString, dbName);
403 QSqlDatabase db = QSqlDatabase::database(dbName);
406 if (db.databaseName() == ":memory:")
407 QSKIP("does not work with in-memory databases");
408 else if (tst_Databases::isMSAccess(db))
409 QSKIP("does not work with MS Access databases");
411 SqlProducer producer(db);
412 SqlConsumer consumer(db);
414 connect(&producer, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
415 connect(&consumer, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
420 while (threadFinishedCount < 2)
424 // run with n threads in parallel. Change this constant to hammer the poor DB server even more
425 static const int maxThreadCount = 4;
427 void tst_QSqlThread::readFromSingleConnection()
430 QFETCH(QString, dbName);
431 QSqlDatabase db = QSqlDatabase::database(dbName);
434 if (db.databaseName() == ":memory:")
435 QSKIP("does not work with in-memory databases");
437 QObject cleanupHelper; // make sure the threads die when we exit the scope
438 for (int i = 0; i < maxThreadCount; ++i) {
439 SqlThread *reader = new SqlThread(SqlThread::SimpleReading, db, &cleanupHelper);
440 connect(reader, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
444 while (threadFinishedCount < maxThreadCount)
449 void tst_QSqlThread::readWriteFromSingleConnection()
452 QFETCH(QString, dbName);
453 QSqlDatabase db = QSqlDatabase::database(dbName);
456 if (db.databaseName() == ":memory:")
457 QSKIP("does not work with in-memory databases");
459 QObject cleanupHelper;
460 for (int i = 0; i < maxThreadCount; ++i) {
461 SqlThread *reader = new SqlThread(SqlThread::SimpleReading, db, &cleanupHelper);
462 connect(reader, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
465 SqlThread *writer = new SqlThread(SqlThread::SimpleWriting, db, &cleanupHelper);
466 connect(writer, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
470 while (threadFinishedCount < maxThreadCount * 2)
475 void tst_QSqlThread::preparedReadWriteFromSingleConnection()
478 QFETCH(QString, dbName);
479 QSqlDatabase db = QSqlDatabase::database(dbName);
482 if (db.databaseName() == ":memory:")
483 QSKIP("does not work with in-memory databases");
485 QObject cleanupHelper;
486 for (int i = 0; i < maxThreadCount; ++i) {
487 SqlThread *reader = new SqlThread(SqlThread::PreparedReading, db, &cleanupHelper);
488 connect(reader, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
491 SqlThread *writer = new SqlThread(SqlThread::PreparedWriting, db, &cleanupHelper);
492 connect(writer, SIGNAL(finished()), this, SLOT(threadFinished()), Qt::QueuedConnection);
496 while (threadFinishedCount < maxThreadCount * 2)
501 void tst_QSqlThread::transactionsFromSingleConnection()
504 QFETCH(QString, dbName);
505 QSqlDatabase db = QSqlDatabase::database(dbName);
508 if (db.databaseName() == ":memory:")
509 QSKIP("does not work with in-memory databases");
511 // start and commit a transaction
512 QVERIFY_SQL(db, db.transaction());
513 preparedReadWriteFromSingleConnection(); // read and write from multiple threads
514 if (QTest::currentTestFailed())
516 QVERIFY_SQL(db, db.commit());
518 // reset test environment
519 threadFinishedCount = 0;
521 // start and roll back a transaction
522 QVERIFY_SQL(db, db.transaction());
523 preparedReadWriteFromSingleConnection(); // read and write from multiple threads
524 if (QTest::currentTestFailed())
526 QVERIFY_SQL(db, db.rollback());
530 QTEST_MAIN(tst_QSqlThread)
531 #include "tst_qsqlthread.moc"