ctkPluginDatabase.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkPluginDatabase_p.h"
  16. #include "ctkPluginDatabaseException.h"
  17. #include "ctkPlugin.h"
  18. #include "ctkPluginConstants.h"
  19. #include "ctkPluginException.h"
  20. #include "ctkPluginArchive_p.h"
  21. #include "ctkPluginStorage_p.h"
  22. #include "ctkPluginFrameworkUtil_p.h"
  23. #include "ctkServiceException.h"
  24. #include <QApplication>
  25. #include <QFileInfo>
  26. #include <QUrl>
  27. #include <QDebug>
  28. //database table names
  29. #define PLUGINS_TABLE "Plugins"
  30. #define PLUGIN_RESOURCES_TABLE "PluginResources"
  31. //----------------------------------------------------------------------------
  32. enum TBindIndexes
  33. {
  34. EBindIndex=0,
  35. EBindIndex1,
  36. EBindIndex2,
  37. EBindIndex3,
  38. EBindIndex4,
  39. EBindIndex5,
  40. EBindIndex6,
  41. EBindIndex7
  42. };
  43. //----------------------------------------------------------------------------
  44. ctkPluginDatabase::ctkPluginDatabase(ctkPluginStorage* storage)
  45. :m_isDatabaseOpen(false), m_inTransaction(false), m_PluginStorage(storage)
  46. {
  47. }
  48. //----------------------------------------------------------------------------
  49. ctkPluginDatabase::~ctkPluginDatabase()
  50. {
  51. close();
  52. }
  53. //----------------------------------------------------------------------------
  54. void ctkPluginDatabase::open()
  55. {
  56. if (m_isDatabaseOpen)
  57. return;
  58. QString path;
  59. //Create full path to database
  60. if(m_databasePath.isEmpty ())
  61. m_databasePath = getDatabasePath();
  62. path = m_databasePath;
  63. QFileInfo dbFileInfo(path);
  64. if (!dbFileInfo.dir().exists())
  65. {
  66. if(!QDir::root().mkpath(dbFileInfo.path()))
  67. {
  68. close();
  69. QString errorText("Could not create database directory: %1");
  70. throw ctkPluginDatabaseException(errorText.arg(dbFileInfo.path()), ctkPluginDatabaseException::DB_CREATE_DIR_ERROR);
  71. }
  72. }
  73. m_connectionName = dbFileInfo.completeBaseName();
  74. QSqlDatabase database;
  75. if (QSqlDatabase::contains(m_connectionName))
  76. {
  77. database = QSqlDatabase::database(m_connectionName);
  78. }
  79. else
  80. {
  81. database = QSqlDatabase::addDatabase("QSQLITE", m_connectionName);
  82. database.setDatabaseName(path);
  83. }
  84. if (!database.isValid())
  85. {
  86. close();
  87. throw ctkPluginDatabaseException(QString("Invalid database connection: %1").arg(m_connectionName),
  88. ctkPluginDatabaseException::DB_CONNECTION_INVALID);
  89. }
  90. //Create or open database
  91. if (!database.isOpen())
  92. {
  93. if (!database.open())
  94. {
  95. close();
  96. throw ctkPluginDatabaseException(QString("Could not open database. ") + database.lastError().text(),
  97. ctkPluginDatabaseException::DB_SQL_ERROR);
  98. }
  99. }
  100. m_isDatabaseOpen = true;
  101. //Check if the sqlite version supports foreign key constraints
  102. QSqlQuery query(database);
  103. if (!query.exec("PRAGMA foreign_keys"))
  104. {
  105. close();
  106. throw ctkPluginDatabaseException(QString("Check for foreign key support failed."),
  107. ctkPluginDatabaseException::DB_SQL_ERROR);
  108. }
  109. if (!query.next())
  110. {
  111. close();
  112. throw ctkPluginDatabaseException(QString("SQLite db does not support foreign keys. It is either older than 3.6.19 or was compiled with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER"),
  113. ctkPluginDatabaseException::DB_SQL_ERROR);
  114. }
  115. query.finish();
  116. query.clear();
  117. //Enable foreign key support
  118. if (!query.exec("PRAGMA foreign_keys = ON"))
  119. {
  120. close();
  121. throw ctkPluginDatabaseException(QString("Enabling foreign key support failed."),
  122. ctkPluginDatabaseException::DB_SQL_ERROR);
  123. }
  124. query.finish();
  125. //Check database structure (tables) and recreate tables if neccessary
  126. //If one of the tables is missing remove all tables and recreate them
  127. //This operation is required in order to avoid data coruption
  128. if (!checkTables())
  129. {
  130. if (dropTables())
  131. {
  132. createTables();
  133. }
  134. else
  135. {
  136. //dropTables() should've handled error message
  137. //and warning
  138. close();
  139. }
  140. }
  141. removeUninstalledPlugins();
  142. //Update database based on the recorded timestamps
  143. updateDB();
  144. }
  145. //----------------------------------------------------------------------------
  146. void ctkPluginDatabase::removeUninstalledPlugins()
  147. {
  148. checkConnection();
  149. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  150. QSqlQuery query(database);
  151. beginTransaction(&query, Write);
  152. try
  153. {
  154. QString statement = "DELETE FROM Plugins WHERE StartLevel==-2";
  155. executeQuery(&query, statement);
  156. }
  157. catch (...)
  158. {
  159. rollbackTransaction(&query);
  160. throw;
  161. }
  162. commitTransaction(&query);
  163. }
  164. //----------------------------------------------------------------------------
  165. void ctkPluginDatabase::updateDB()
  166. {
  167. checkConnection();
  168. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  169. QSqlQuery query(database);
  170. beginTransaction(&query, Write);
  171. QString statement = "SELECT ID, Location, LocalPath, Timestamp, SymbolicName, Version FROM Plugins WHERE State != ?";
  172. QList<QVariant> bindValues;
  173. bindValues.append(ctkPlugin::UNINSTALLED);
  174. QList<qlonglong> outdatedIds;
  175. QList<QPair<QString,QString> > outdatedPlugins;
  176. QStringList outdatedServiceNames;
  177. try
  178. {
  179. executeQuery(&query, statement, bindValues);
  180. while (query.next())
  181. {
  182. QFileInfo pluginInfo(query.value(EBindIndex2).toString());
  183. if (pluginInfo.lastModified() > getQDateTimeFromString(query.value(EBindIndex3).toString()))
  184. {
  185. outdatedIds.append(query.value(EBindIndex).toLongLong());
  186. outdatedPlugins.append(qMakePair(query.value(EBindIndex1).toString(), query.value(EBindIndex2).toString()));
  187. }
  188. }
  189. }
  190. catch (...)
  191. {
  192. rollbackTransaction(&query);
  193. throw;
  194. }
  195. query.finish();
  196. query.clear();
  197. try
  198. {
  199. statement = "DELETE FROM Plugins WHERE ID=?";
  200. QListIterator<qlonglong> idIter(outdatedIds);
  201. while (idIter.hasNext())
  202. {
  203. bindValues.clear();
  204. bindValues.append(idIter.next());
  205. executeQuery(&query, statement, bindValues);
  206. }
  207. }
  208. catch (...)
  209. {
  210. rollbackTransaction(&query);
  211. throw;
  212. }
  213. commitTransaction(&query);
  214. QListIterator<QPair<QString,QString> > locationIter(outdatedPlugins);
  215. while (locationIter.hasNext())
  216. {
  217. const QPair<QString,QString>& locations = locationIter.next();
  218. insertPlugin(QUrl(locations.first), locations.second, false);
  219. }
  220. }
  221. //----------------------------------------------------------------------------
  222. ctkPluginArchive* ctkPluginDatabase::insertPlugin(const QUrl& location, const QString& localPath, bool createArchive)
  223. {
  224. checkConnection();
  225. // Assemble the data for the sql record
  226. QFileInfo fileInfo(localPath);
  227. if (!fileInfo.exists())
  228. {
  229. throw std::invalid_argument((localPath + " does not exist").toStdString());
  230. }
  231. const QString libTimestamp = getStringFromQDateTime(fileInfo.lastModified());
  232. QString resourcePrefix = fileInfo.baseName();
  233. if (resourcePrefix.startsWith("lib"))
  234. {
  235. resourcePrefix = resourcePrefix.mid(3);
  236. }
  237. resourcePrefix.replace("_", ".");
  238. resourcePrefix = QString(":/") + resourcePrefix + "/";
  239. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  240. QSqlQuery query(database);
  241. beginTransaction(&query, Write);
  242. QString statement = "INSERT INTO Plugins(Location,LocalPath,SymbolicName,Version,State,LastModified,Timestamp,StartLevel,AutoStart)"
  243. "VALUES(?,?,?,?,?,'',?,-1,-1)";
  244. QList<QVariant> bindValues;
  245. bindValues.append(location.toString());
  246. bindValues.append(localPath);
  247. bindValues.append(QString("na"));
  248. bindValues.append(QString("na"));
  249. bindValues.append(ctkPlugin::INSTALLED);
  250. bindValues.append(libTimestamp);
  251. qlonglong pluginId = -1;
  252. try
  253. {
  254. executeQuery(&query, statement, bindValues);
  255. QVariant lastId = query.lastInsertId();
  256. if (lastId.isValid())
  257. {
  258. pluginId = lastId.toLongLong();
  259. }
  260. }
  261. catch (...)
  262. {
  263. rollbackTransaction(&query);
  264. throw;
  265. }
  266. // Load the plugin and cache the resources
  267. QPluginLoader pluginLoader;
  268. pluginLoader.setFileName(localPath);
  269. if (!pluginLoader.load())
  270. {
  271. rollbackTransaction(&query);
  272. ctkPluginException exc(QString("The plugin could not be loaded: %1").arg(localPath));
  273. exc.setCause(pluginLoader.errorString());
  274. throw exc;
  275. }
  276. QDirIterator dirIter(resourcePrefix, QDirIterator::Subdirectories);
  277. while (dirIter.hasNext())
  278. {
  279. QString resourcePath = dirIter.next();
  280. if (QFileInfo(resourcePath).isDir()) continue;
  281. QFile resourceFile(resourcePath);
  282. resourceFile.open(QIODevice::ReadOnly);
  283. QByteArray resourceData = resourceFile.readAll();
  284. resourceFile.close();
  285. statement = "INSERT INTO PluginResources(PluginID, ResourcePath, Resource) VALUES(?,?,?)";
  286. bindValues.clear();
  287. bindValues.append(QVariant::fromValue<qlonglong>(pluginId));
  288. bindValues.append(resourcePath.mid(resourcePrefix.size()-1));
  289. bindValues.append(resourceData);
  290. try
  291. {
  292. executeQuery(&query, statement, bindValues);
  293. }
  294. catch (...)
  295. {
  296. rollbackTransaction(&query);
  297. throw;
  298. }
  299. }
  300. pluginLoader.unload();
  301. try
  302. {
  303. ctkPluginArchive* archive = new ctkPluginArchive(m_PluginStorage, location, localPath,
  304. pluginId);;
  305. statement = "UPDATE Plugins SET SymbolicName=?,Version=? WHERE ID=?";
  306. QString versionString = archive->getAttribute(ctkPluginConstants::PLUGIN_VERSION);
  307. bindValues.clear();
  308. bindValues.append(archive->getAttribute(ctkPluginConstants::PLUGIN_SYMBOLICNAME));
  309. bindValues.append(versionString.isEmpty() ? "0.0.0" : versionString);
  310. bindValues.append(pluginId);
  311. if (!createArchive)
  312. {
  313. delete archive;
  314. archive = 0;
  315. }
  316. executeQuery(&query, statement, bindValues);
  317. commitTransaction(&query);
  318. return archive;
  319. }
  320. catch (...)
  321. {
  322. rollbackTransaction(&query);
  323. throw;
  324. }
  325. }
  326. //----------------------------------------------------------------------------
  327. void ctkPluginDatabase::setStartLevel(long pluginId, int startLevel)
  328. {
  329. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  330. QSqlQuery query(database);
  331. QString statement = "UPDATE Plugins SET StartLevel=? WHERE ID=?";
  332. QList<QVariant> bindValues;
  333. bindValues.append(startLevel);
  334. bindValues.append(QVariant::fromValue(pluginId));
  335. executeQuery(&query, statement, bindValues);
  336. }
  337. //----------------------------------------------------------------------------
  338. void ctkPluginDatabase::setLastModified(long pluginId, const QDateTime& lastModified)
  339. {
  340. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  341. QSqlQuery query(database);
  342. QString statement = "UPDATE Plugins SET LastModified=? WHERE ID=?";
  343. QList<QVariant> bindValues;
  344. bindValues.append(getStringFromQDateTime(lastModified));
  345. bindValues.append(QVariant::fromValue(pluginId));
  346. executeQuery(&query, statement, bindValues);
  347. }
  348. //----------------------------------------------------------------------------
  349. void ctkPluginDatabase::setAutostartSetting(long pluginId, int autostart)
  350. {
  351. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  352. QSqlQuery query(database);
  353. QString statement = "UPDATE Plugins SET AutoStart=? WHERE ID=?";
  354. QList<QVariant> bindValues;
  355. bindValues.append(autostart);
  356. bindValues.append(QVariant::fromValue(pluginId));
  357. executeQuery(&query, statement, bindValues);
  358. }
  359. //----------------------------------------------------------------------------
  360. QStringList ctkPluginDatabase::findResourcesPath(long pluginId, const QString& path) const
  361. {
  362. checkConnection();
  363. QString statement = "SELECT SUBSTR(ResourcePath,?) FROM PluginResources WHERE PluginID=? AND SUBSTR(ResourcePath,1,?)=?";
  364. QString resourcePath = path.startsWith('/') ? path : QString("/") + path;
  365. if (!resourcePath.endsWith('/'))
  366. resourcePath += "/";
  367. QList<QVariant> bindValues;
  368. bindValues.append(resourcePath.size()+1);
  369. bindValues.append(qlonglong(pluginId));
  370. bindValues.append(resourcePath.size());
  371. bindValues.append(resourcePath);
  372. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  373. QSqlQuery query(database);
  374. executeQuery(&query, statement, bindValues);
  375. QStringList paths;
  376. while (query.next())
  377. {
  378. QString currPath = query.value(EBindIndex).toString();
  379. int slashIndex = currPath.indexOf('/');
  380. if (slashIndex > 0)
  381. {
  382. currPath = currPath.left(slashIndex+1);
  383. }
  384. paths << currPath;
  385. }
  386. return paths;
  387. }
  388. //----------------------------------------------------------------------------
  389. void ctkPluginDatabase::removeArchive(const ctkPluginArchive *pa)
  390. {
  391. checkConnection();
  392. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  393. QSqlQuery query(database);
  394. QString statement = "DELETE FROM Plugins WHERE ID=?";
  395. QList<QVariant> bindValues;
  396. bindValues.append(pa->getPluginId());
  397. executeQuery(&query, statement, bindValues);
  398. }
  399. //----------------------------------------------------------------------------
  400. void ctkPluginDatabase::executeQuery(QSqlQuery *query, const QString &statement, const QList<QVariant> &bindValues) const
  401. {
  402. Q_ASSERT(query != 0);
  403. bool success = false;
  404. enum {Prepare =0 , Execute=1};
  405. for (int stage=Prepare; stage <= Execute; ++stage)
  406. {
  407. if ( stage == Prepare)
  408. success = query->prepare(statement);
  409. else // stage == Execute
  410. success = query->exec();
  411. if (!success)
  412. {
  413. QString errorText = "Problem: Could not %1 statement: %2\n"
  414. "Reason: %3\n"
  415. "Parameters: %4\n";
  416. QString parameters;
  417. if (bindValues.count() > 0)
  418. {
  419. for (int i = 0; i < bindValues.count(); ++i)
  420. {
  421. parameters.append(QString("\n\t[") + QString::number(i) + "]: " + bindValues.at(i).toString());
  422. }
  423. }
  424. else
  425. {
  426. parameters = "None";
  427. }
  428. ctkPluginDatabaseException::Type errorType;
  429. int result = query->lastError().number();
  430. if (result == 26 || result == 11) //SQLILTE_NOTADB || SQLITE_CORRUPT
  431. {
  432. qWarning() << "ctkPluginFramework:- Database file is corrupt or invalid:" << getDatabasePath();
  433. errorType = ctkPluginDatabaseException::DB_FILE_INVALID;
  434. }
  435. else if (result == 8) //SQLITE_READONLY
  436. errorType = ctkPluginDatabaseException::DB_WRITE_ERROR;
  437. else
  438. errorType = ctkPluginDatabaseException::DB_SQL_ERROR;
  439. query->finish();
  440. query->clear();
  441. throw ctkPluginDatabaseException(errorText.arg(stage == Prepare ? "prepare":"execute")
  442. .arg(statement).arg(query->lastError().text()).arg(parameters), errorType);
  443. }
  444. if (stage == Prepare)
  445. {
  446. foreach(const QVariant &bindValue, bindValues)
  447. query->addBindValue(bindValue);
  448. }
  449. }
  450. }
  451. //----------------------------------------------------------------------------
  452. void ctkPluginDatabase::close()
  453. {
  454. if (m_isDatabaseOpen)
  455. {
  456. QSqlDatabase database = QSqlDatabase::database(m_connectionName, false);
  457. if (database.isValid())
  458. {
  459. if(database.isOpen())
  460. {
  461. database.close();
  462. m_isDatabaseOpen = false;
  463. return;
  464. }
  465. }
  466. else
  467. {
  468. throw ctkPluginDatabaseException(QString("Problem closing database: Invalid connection %1").arg(m_connectionName));
  469. }
  470. }
  471. }
  472. //----------------------------------------------------------------------------
  473. void ctkPluginDatabase::setDatabasePath(const QString &databasePath)
  474. {
  475. m_databasePath = QDir::toNativeSeparators(databasePath);
  476. }
  477. //----------------------------------------------------------------------------
  478. QString ctkPluginDatabase::getDatabasePath() const
  479. {
  480. QString path = m_databasePath;
  481. if(path.isEmpty())
  482. {
  483. path = QDir::homePath() + "/ctkpluginfw/plugins.db";
  484. qWarning() << "No database path set. Using default:" << path;
  485. }
  486. path = QDir::toNativeSeparators(path);
  487. qDebug() << "Using database:" << path;
  488. return path;
  489. }
  490. //----------------------------------------------------------------------------
  491. QByteArray ctkPluginDatabase::getPluginResource(long pluginId, const QString& res) const
  492. {
  493. checkConnection();
  494. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  495. QSqlQuery query(database);
  496. QString statement = "SELECT Resource FROM PluginResources WHERE PluginID=? AND ResourcePath=?";
  497. QString resourcePath = res.startsWith('/') ? res : QString("/") + res;
  498. QList<QVariant> bindValues;
  499. bindValues.append(qlonglong(pluginId));
  500. bindValues.append(resourcePath);
  501. executeQuery(&query, statement, bindValues);
  502. if (query.next())
  503. {
  504. return query.value(EBindIndex).toByteArray();
  505. }
  506. return QByteArray();
  507. }
  508. //----------------------------------------------------------------------------
  509. void ctkPluginDatabase::createTables()
  510. {
  511. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  512. QSqlQuery query(database);
  513. //Begin Transaction
  514. beginTransaction(&query, Write);
  515. QString statement("CREATE TABLE Plugins("
  516. "ID INTEGER PRIMARY KEY,"
  517. "Location TEXT NOT NULL UNIQUE,"
  518. "LocalPath TEXT NOT NULL UNIQUE,"
  519. "SymbolicName TEXT NOT NULL,"
  520. "Version TEXT NOT NULL,"
  521. "State INTEGER NOT NULL,"
  522. "LastModified TEXT NOT NULL,"
  523. "Timestamp TEXT NOT NULL,"
  524. "StartLevel INTEGER NOT NULL,"
  525. "AutoStart INTEGER NOT NULL)");
  526. try
  527. {
  528. executeQuery(&query, statement);
  529. }
  530. catch (...)
  531. {
  532. rollbackTransaction(&query);
  533. throw;
  534. }
  535. statement = "CREATE TABLE PluginResources("
  536. "PluginID INTEGER NOT NULL,"
  537. "ResourcePath TEXT NOT NULL, "
  538. "Resource BLOB NOT NULL,"
  539. "FOREIGN KEY(PluginID) REFERENCES Plugins(ID) ON DELETE CASCADE)";
  540. try
  541. {
  542. executeQuery(&query, statement);
  543. }
  544. catch (...)
  545. {
  546. rollbackTransaction(&query);
  547. throw;
  548. }
  549. try
  550. {
  551. commitTransaction(&query);
  552. }
  553. catch (...)
  554. {
  555. rollbackTransaction(&query);
  556. throw;
  557. }
  558. }
  559. //----------------------------------------------------------------------------
  560. bool ctkPluginDatabase::checkTables() const
  561. {
  562. bool bTables(false);
  563. QStringList tables = QSqlDatabase::database(m_connectionName).tables();
  564. if (tables.contains(PLUGINS_TABLE)
  565. && tables.contains(PLUGIN_RESOURCES_TABLE))
  566. {
  567. bTables = true;
  568. }
  569. return bTables;
  570. }
  571. //----------------------------------------------------------------------------
  572. bool ctkPluginDatabase::dropTables()
  573. {
  574. //Execute transaction for deleting the database tables
  575. QSqlDatabase database = QSqlDatabase::database(m_connectionName);
  576. QSqlQuery query(database);
  577. QStringList expectedTables;
  578. expectedTables << PLUGINS_TABLE << PLUGIN_RESOURCES_TABLE;
  579. if (database.tables().count() > 0)
  580. {
  581. beginTransaction(&query, Write);
  582. QStringList actualTables = database.tables();
  583. foreach(const QString expectedTable, expectedTables)
  584. {
  585. if (actualTables.contains(expectedTable))
  586. {
  587. try
  588. {
  589. executeQuery(&query, QString("DROP TABLE ") + expectedTable);
  590. }
  591. catch (...)
  592. {
  593. rollbackTransaction(&query);
  594. throw;
  595. }
  596. }
  597. try
  598. {
  599. commitTransaction(&query);
  600. }
  601. catch (...)
  602. {
  603. rollbackTransaction(&query);
  604. throw;
  605. }
  606. }
  607. }
  608. return true;
  609. }
  610. //----------------------------------------------------------------------------
  611. bool ctkPluginDatabase::isOpen() const
  612. {
  613. return m_isDatabaseOpen;
  614. }
  615. //----------------------------------------------------------------------------
  616. void ctkPluginDatabase::checkConnection() const
  617. {
  618. if(!m_isDatabaseOpen)
  619. {
  620. throw ctkPluginDatabaseException("Database not open.", ctkPluginDatabaseException::DB_NOT_OPEN_ERROR);
  621. }
  622. if (!QSqlDatabase::database(m_connectionName).isValid())
  623. {
  624. throw ctkPluginDatabaseException(QString("Database connection invalid: %1").arg(m_connectionName),
  625. ctkPluginDatabaseException::DB_CONNECTION_INVALID);
  626. }
  627. }
  628. //----------------------------------------------------------------------------
  629. void ctkPluginDatabase::beginTransaction(QSqlQuery *query, TransactionType type)
  630. {
  631. bool success;
  632. if (type == Read)
  633. success = query->exec(QLatin1String("BEGIN"));
  634. else
  635. success = query->exec(QLatin1String("BEGIN IMMEDIATE"));
  636. if (!success) {
  637. int result = query->lastError().number();
  638. if (result == 26 || result == 11) //SQLITE_NOTADB || SQLITE_CORRUPT
  639. {
  640. throw ctkPluginDatabaseException(QString("ctkPluginFramework: Database file is corrupt or invalid: %1").arg(getDatabasePath()),
  641. ctkPluginDatabaseException::DB_FILE_INVALID);
  642. }
  643. else if (result == 8) //SQLITE_READONLY
  644. {
  645. throw ctkPluginDatabaseException(QString("ctkPluginFramework: Insufficient permissions to write to database: %1").arg(getDatabasePath()),
  646. ctkPluginDatabaseException::DB_WRITE_ERROR);
  647. }
  648. else
  649. throw ctkPluginDatabaseException(QString("ctkPluginFramework: ") + query->lastError().text(),
  650. ctkPluginDatabaseException::DB_SQL_ERROR);
  651. }
  652. }
  653. //----------------------------------------------------------------------------
  654. void ctkPluginDatabase::commitTransaction(QSqlQuery *query)
  655. {
  656. Q_ASSERT(query != 0);
  657. query->finish();
  658. query->clear();
  659. if (!query->exec(QLatin1String("COMMIT")))
  660. {
  661. throw ctkPluginDatabaseException(QString("ctkPluginFramework: ") + query->lastError().text(),
  662. ctkPluginDatabaseException::DB_SQL_ERROR);
  663. }
  664. }
  665. //----------------------------------------------------------------------------
  666. void ctkPluginDatabase::rollbackTransaction(QSqlQuery *query)
  667. {
  668. Q_ASSERT(query !=0);
  669. query->finish();
  670. query->clear();
  671. if (!query->exec(QLatin1String("ROLLBACK")))
  672. {
  673. throw ctkPluginDatabaseException(QString("ctkPluginFramework: ") + query->lastError().text(),
  674. ctkPluginDatabaseException::DB_SQL_ERROR);
  675. }
  676. }
  677. //----------------------------------------------------------------------------
  678. QList<ctkPluginArchive*> ctkPluginDatabase::getPluginArchives() const
  679. {
  680. checkConnection();
  681. QSqlQuery query(QSqlDatabase::database(m_connectionName));
  682. QString statement("SELECT ID, Location, LocalPath FROM Plugins WHERE State != ?");
  683. QList<QVariant> bindValues;
  684. bindValues.append(ctkPlugin::UNINSTALLED);
  685. executeQuery(&query, statement, bindValues);
  686. QList<ctkPluginArchive*> archives;
  687. while (query.next())
  688. {
  689. const long id = query.value(EBindIndex).toLongLong();
  690. const QUrl location(query.value(EBindIndex1).toString());
  691. const QString localPath(query.value(EBindIndex2).toString());
  692. if (id <= 0 || location.isEmpty() || localPath.isEmpty())
  693. {
  694. throw ctkPluginDatabaseException(QString("Database integrity corrupted, row %1 contains empty values.").arg(id),
  695. ctkPluginDatabaseException::DB_FILE_INVALID);
  696. }
  697. try
  698. {
  699. ctkPluginArchive* pa = new ctkPluginArchive(m_PluginStorage, location, localPath, id);
  700. archives.append(pa);
  701. }
  702. catch (const ctkPluginException& exc)
  703. {
  704. qWarning() << exc;
  705. }
  706. }
  707. return archives;
  708. }
  709. //----------------------------------------------------------------------------
  710. QString ctkPluginDatabase::getStringFromQDateTime(const QDateTime& dateTime) const
  711. {
  712. return dateTime.toString(Qt::ISODate);
  713. }
  714. //----------------------------------------------------------------------------
  715. QDateTime ctkPluginDatabase::getQDateTimeFromString(const QString& dateTimeString) const
  716. {
  717. return QDateTime::fromString(dateTimeString, Qt::ISODate);
  718. }