DBManager.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #include <db/DBManager.h>
  2. #include <QSqlDatabase>
  3. #include <QSqlError>
  4. #include <QSqlQuery>
  5. #include <QSqlRecord>
  6. #include <QThreadStorage>
  7. #include <QUuid>
  8. #include <QDir>
  9. #include <QMetaType>
  10. #ifdef _WIN32
  11. #include <stdexcept>
  12. #endif
  13. // not in header because of linking
  14. static QString _rootPath;
  15. static QThreadStorage<QSqlDatabase> _databasePool;
  16. DBManager::DBManager(QObject* parent)
  17. : QObject(parent)
  18. , _log(Logger::getInstance("DB"))
  19. , _readonlyMode (false)
  20. {
  21. }
  22. DBManager::~DBManager()
  23. {
  24. }
  25. void DBManager::setRootPath(const QString& rootPath)
  26. {
  27. _rootPath = rootPath;
  28. // create directory
  29. QDir().mkpath(_rootPath+"/db");
  30. }
  31. void DBManager::setTable(const QString& table)
  32. {
  33. _table = table;
  34. }
  35. QSqlDatabase DBManager::getDB() const
  36. {
  37. if(_databasePool.hasLocalData())
  38. return _databasePool.localData();
  39. else
  40. {
  41. auto db = QSqlDatabase::addDatabase("QSQLITE", QUuid::createUuid().toString());
  42. _databasePool.setLocalData(db);
  43. db.setDatabaseName(_rootPath+"/db/"+_dbn+".db");
  44. if(!db.open())
  45. {
  46. Error(_log, "%s", QSTRING_CSTR(db.lastError().text()));
  47. throw std::runtime_error("Failed to open database connection!");
  48. }
  49. return db;
  50. }
  51. }
  52. bool DBManager::createRecord(const VectorPair& conditions, const QVariantMap& columns) const
  53. {
  54. if ( _readonlyMode )
  55. {
  56. return false;
  57. }
  58. if(recordExists(conditions))
  59. {
  60. // if there is no column data, return
  61. if(columns.isEmpty())
  62. return true;
  63. if(!updateRecord(conditions, columns))
  64. return false;
  65. return true;
  66. }
  67. QSqlDatabase idb = getDB();
  68. QSqlQuery query(idb);
  69. query.setForwardOnly(true);
  70. QVariantList cValues;
  71. QStringList prep;
  72. QStringList placeh;
  73. // prep merge columns & condition
  74. QVariantMap::const_iterator i = columns.constBegin();
  75. while (i != columns.constEnd()) {
  76. prep.append(i.key());
  77. cValues += i.value();
  78. placeh.append("?");
  79. ++i;
  80. }
  81. for(const auto& pair : conditions)
  82. {
  83. // remove the condition statements
  84. QString tmp = pair.first;
  85. prep << tmp.remove("AND");
  86. cValues << pair.second;
  87. placeh.append("?");
  88. }
  89. query.prepare(QString("INSERT INTO %1 ( %2 ) VALUES ( %3 )").arg(_table,prep.join(", ")).arg(placeh.join(", ")));
  90. // add column & condition values
  91. doAddBindValue(query, cValues);
  92. if(!query.exec())
  93. {
  94. Error(_log, "Failed to create record: '%s' in table: '%s' Error: %s", QSTRING_CSTR(prep.join(", ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  95. return false;
  96. }
  97. return true;
  98. }
  99. bool DBManager::recordExists(const VectorPair& conditions) const
  100. {
  101. if(conditions.isEmpty())
  102. return false;
  103. QSqlDatabase idb = getDB();
  104. QSqlQuery query(idb);
  105. query.setForwardOnly(true);
  106. QStringList prepCond;
  107. QVariantList bindVal;
  108. prepCond << "WHERE";
  109. for(const auto& pair : conditions)
  110. {
  111. prepCond << pair.first+"=?";
  112. bindVal << pair.second;
  113. }
  114. query.prepare(QString("SELECT * FROM %1 %2").arg(_table,prepCond.join(" ")));
  115. doAddBindValue(query, bindVal);
  116. if(!query.exec())
  117. {
  118. Error(_log, "Failed recordExists(): '%s' in table: '%s' Error: %s", QSTRING_CSTR(prepCond.join(" ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  119. return false;
  120. }
  121. int entry = 0;
  122. while (query.next()) {
  123. entry++;
  124. }
  125. if(entry)
  126. return true;
  127. return false;
  128. }
  129. bool DBManager::updateRecord(const VectorPair& conditions, const QVariantMap& columns) const
  130. {
  131. if ( _readonlyMode )
  132. {
  133. return false;
  134. }
  135. QSqlDatabase idb = getDB();
  136. QSqlQuery query(idb);
  137. query.setForwardOnly(true);
  138. QVariantList values;
  139. QStringList prep;
  140. // prepare columns valus
  141. QVariantMap::const_iterator i = columns.constBegin();
  142. while (i != columns.constEnd()) {
  143. prep += i.key()+"=?";
  144. values += i.value();
  145. ++i;
  146. }
  147. // prepare condition values
  148. QStringList prepCond;
  149. QVariantList prepBindVal;
  150. if(!conditions.isEmpty())
  151. prepCond << "WHERE";
  152. for(const auto& pair : conditions)
  153. {
  154. prepCond << pair.first+"=?";
  155. prepBindVal << pair.second;
  156. }
  157. query.prepare(QString("UPDATE %1 SET %2 %3").arg(_table,prep.join(", ")).arg(prepCond.join(" ")));
  158. // add column values
  159. doAddBindValue(query, values);
  160. // add condition values
  161. doAddBindValue(query, prepBindVal);
  162. if(!query.exec())
  163. {
  164. Error(_log, "Failed to update record: '%s' in table: '%s' Error: %s", QSTRING_CSTR(prepCond.join(" ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  165. return false;
  166. }
  167. return true;
  168. }
  169. bool DBManager::getRecord(const VectorPair& conditions, QVariantMap& results, const QStringList& tColumns, const QStringList& tOrder) const
  170. {
  171. QSqlDatabase idb = getDB();
  172. QSqlQuery query(idb);
  173. query.setForwardOnly(true);
  174. QString sColumns("*");
  175. if(!tColumns.isEmpty())
  176. sColumns = tColumns.join(", ");
  177. QString sOrder("");
  178. if(!tOrder.isEmpty())
  179. {
  180. sOrder = " ORDER BY ";
  181. sOrder.append(tOrder.join(", "));
  182. }
  183. // prep conditions
  184. QStringList prepCond;
  185. QVariantList bindVal;
  186. if(!conditions.isEmpty())
  187. prepCond << " WHERE";
  188. for(const auto& pair : conditions)
  189. {
  190. prepCond << pair.first+"=?";
  191. bindVal << pair.second;
  192. }
  193. query.prepare(QString("SELECT %1 FROM %2%3%4").arg(sColumns,_table).arg(prepCond.join(" ")).arg(sOrder));
  194. doAddBindValue(query, bindVal);
  195. if(!query.exec())
  196. {
  197. Error(_log, "Failed to get record: '%s' in table: '%s' Error: %s", QSTRING_CSTR(prepCond.join(" ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  198. return false;
  199. }
  200. // go to first row
  201. query.next();
  202. QSqlRecord rec = query.record();
  203. for(int i = 0; i<rec.count(); i++)
  204. {
  205. results[rec.fieldName(i)] = rec.value(i);
  206. }
  207. return true;
  208. }
  209. bool DBManager::getRecords(QVector<QVariantMap>& results, const QStringList& tColumns, const QStringList& tOrder) const
  210. {
  211. QSqlDatabase idb = getDB();
  212. QSqlQuery query(idb);
  213. query.setForwardOnly(true);
  214. QString sColumns("*");
  215. if(!tColumns.isEmpty())
  216. sColumns = tColumns.join(", ");
  217. QString sOrder("");
  218. if(!tOrder.isEmpty())
  219. {
  220. sOrder = " ORDER BY ";
  221. sOrder.append(tOrder.join(", "));
  222. }
  223. query.prepare(QString("SELECT %1 FROM %2%3").arg(sColumns,_table,sOrder));
  224. if(!query.exec())
  225. {
  226. Error(_log, "Failed to get records: '%s' in table: '%s' Error: %s", QSTRING_CSTR(sColumns), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  227. return false;
  228. }
  229. // iterate through all found records
  230. while(query.next())
  231. {
  232. QVariantMap entry;
  233. QSqlRecord rec = query.record();
  234. for(int i = 0; i<rec.count(); i++)
  235. {
  236. entry[rec.fieldName(i)] = rec.value(i);
  237. }
  238. results.append(entry);
  239. }
  240. return true;
  241. }
  242. bool DBManager::deleteRecord(const VectorPair& conditions) const
  243. {
  244. if ( _readonlyMode )
  245. {
  246. return false;
  247. }
  248. if(conditions.isEmpty())
  249. {
  250. Error(_log, "Oops, a deleteRecord() call wants to delete the entire table (%s)! Denied it", QSTRING_CSTR(_table));
  251. return false;
  252. }
  253. if(recordExists(conditions))
  254. {
  255. QSqlDatabase idb = getDB();
  256. QSqlQuery query(idb);
  257. // prep conditions
  258. QStringList prepCond("WHERE");
  259. QVariantList bindValues;
  260. for(const auto& pair : conditions)
  261. {
  262. prepCond << pair.first+"=?";
  263. bindValues << pair.second;
  264. }
  265. query.prepare(QString("DELETE FROM %1 %2").arg(_table,prepCond.join(" ")));
  266. doAddBindValue(query, bindValues);
  267. if(!query.exec())
  268. {
  269. Error(_log, "Failed to delete record: '%s' in table: '%s' Error: %s", QSTRING_CSTR(prepCond.join(" ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  270. return false;
  271. }
  272. return true;
  273. }
  274. return false;
  275. }
  276. bool DBManager::createTable(QStringList& columns) const
  277. {
  278. if ( _readonlyMode )
  279. {
  280. return false;
  281. }
  282. if(columns.isEmpty())
  283. {
  284. Error(_log,"Empty tables aren't supported!");
  285. return false;
  286. }
  287. QSqlDatabase idb = getDB();
  288. // create table if required
  289. QSqlQuery query(idb);
  290. if(!tableExists(_table))
  291. {
  292. // empty tables aren't supported by sqlite, add one column
  293. QString tcolumn = columns.takeFirst();
  294. // default CURRENT_TIMESTAMP is not supported by ALTER TABLE
  295. if(!query.exec(QString("CREATE TABLE %1 ( %2 )").arg(_table,tcolumn)))
  296. {
  297. Error(_log, "Failed to create table: '%s' Error: %s", QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  298. return false;
  299. }
  300. }
  301. // create columns if required
  302. QSqlRecord rec = idb.record(_table);
  303. int err = 0;
  304. for(const auto& column : columns)
  305. {
  306. QStringList id = column.split(' ');
  307. if(rec.indexOf(id.at(0)) == -1)
  308. {
  309. if(!createColumn(column))
  310. {
  311. err++;
  312. }
  313. }
  314. }
  315. if(err)
  316. return false;
  317. return true;
  318. }
  319. bool DBManager::createColumn(const QString& column) const
  320. {
  321. if ( _readonlyMode )
  322. {
  323. return false;
  324. }
  325. QSqlDatabase idb = getDB();
  326. QSqlQuery query(idb);
  327. if(!query.exec(QString("ALTER TABLE %1 ADD COLUMN %2").arg(_table,column)))
  328. {
  329. Error(_log, "Failed to create column: '%s' in table: '%s' Error: %s", QSTRING_CSTR(column), QSTRING_CSTR(_table), QSTRING_CSTR(idb.lastError().text()));
  330. return false;
  331. }
  332. return true;
  333. }
  334. bool DBManager::tableExists(const QString& table) const
  335. {
  336. QSqlDatabase idb = getDB();
  337. QStringList tables = idb.tables();
  338. if(tables.contains(table))
  339. return true;
  340. return false;
  341. }
  342. bool DBManager::deleteTable(const QString& table) const
  343. {
  344. if ( _readonlyMode )
  345. {
  346. return false;
  347. }
  348. if(tableExists(table))
  349. {
  350. QSqlDatabase idb = getDB();
  351. QSqlQuery query(idb);
  352. if(!query.exec(QString("DROP TABLE %1").arg(table)))
  353. {
  354. Error(_log, "Failed to delete table: '%s' Error: %s", QSTRING_CSTR(table), QSTRING_CSTR(idb.lastError().text()));
  355. return false;
  356. }
  357. }
  358. return true;
  359. }
  360. void DBManager::doAddBindValue(QSqlQuery& query, const QVariantList& variants) const
  361. {
  362. for(const auto& variant : variants)
  363. {
  364. auto t = variant.userType();
  365. switch(t)
  366. {
  367. case QMetaType::UInt:
  368. case QMetaType::Int:
  369. case QMetaType::Bool:
  370. query.addBindValue(variant.toInt());
  371. break;
  372. case QMetaType::Double:
  373. query.addBindValue(variant.toFloat());
  374. break;
  375. case QMetaType::QByteArray:
  376. query.addBindValue(variant.toByteArray());
  377. break;
  378. default:
  379. query.addBindValue(variant.toString());
  380. break;
  381. }
  382. }
  383. }