2
0

adatabasesetup.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /*
  2. *openPilotLog - A FOSS Pilot Logbook Application
  3. *Copyright (C) 2020-2021 Felix Turowsky
  4. *
  5. *This program is free software: you can redistribute it and/or modify
  6. *it under the terms of the GNU General Public License as published by
  7. *the Free Software Foundation, either version 3 of the License, or
  8. *(at your option) any later version.
  9. *
  10. *This program is distributed in the hope that it will be useful,
  11. *but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. *MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. *GNU General Public License for more details.
  14. *
  15. *You should have received a copy of the GNU General Public License
  16. *along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. #include "adatabasesetup.h"
  19. #include "src/database/adatabase.h"
  20. #include "src/testing/adebug.h"
  21. #include "src/functions/areadcsv.h"
  22. #include "src/classes/astandardpaths.h"
  23. #include "src/classes/adownload.h"
  24. #include "src/oplconstants.h"
  25. #include "src/functions/adatetime.h"
  26. #include "src/functions/alog.h"
  27. const auto createTablePilots = QLatin1String("CREATE TABLE pilots ( "
  28. " pilot_id INTEGER NOT NULL, "
  29. " lastname TEXT NOT NULL, "
  30. " firstname TEXT, "
  31. " alias TEXT, "
  32. " company TEXT, "
  33. " employeeid TEXT, "
  34. " phone TEXT, "
  35. " email TEXT, "
  36. " PRIMARY KEY(pilot_id AUTOINCREMENT)"
  37. ")");
  38. const auto createTableTails = QLatin1String("CREATE TABLE tails ("
  39. " tail_id INTEGER NOT NULL,"
  40. " registration TEXT NOT NULL,"
  41. " company TEXT,"
  42. " make TEXT,"
  43. " model TEXT,"
  44. " variant TEXT,"
  45. " multipilot INTEGER,"
  46. " multiengine INTEGER,"
  47. " engineType INTEGER,"
  48. " weightClass INTEGER,"
  49. " PRIMARY KEY(tail_id AUTOINCREMENT)"
  50. ")");
  51. const auto createTableFlights = QLatin1String("CREATE TABLE flights ("
  52. " flight_id INTEGER NOT NULL, "
  53. " doft NUMERIC NOT NULL, "
  54. " dept TEXT NOT NULL, "
  55. " dest TEXT NOT NULL, "
  56. " tofb INTEGER NOT NULL, "
  57. " tonb INTEGER NOT NULL, "
  58. " pic INTEGER NOT NULL, "
  59. " acft INTEGER NOT NULL, "
  60. " tblk INTEGER NOT NULL, "
  61. " tSPSE INTEGER, "
  62. " tSPME INTEGER, "
  63. " tMP INTEGER, "
  64. " tNIGHT INTEGER, "
  65. " tIFR INTEGER, "
  66. " tPIC INTEGER, "
  67. " tPICUS INTEGER, "
  68. " tSIC INTEGER, "
  69. " tDUAL INTEGER, "
  70. " tFI INTEGER, "
  71. " tSIM INTEGER, "
  72. " pilotFlying INTEGER, "
  73. " toDay INTEGER, "
  74. " toNight INTEGER, "
  75. " ldgDay INTEGER, "
  76. " ldgNight INTEGER, "
  77. " autoland INTEGER, "
  78. " secondPilot INTEGER, "
  79. " thirdPilot INTEGER, "
  80. " approachType TEXT, "
  81. " flightNumber TEXT, "
  82. " remarks TEXT, "
  83. " FOREIGN KEY(pic) REFERENCES pilots(pilot_id) ON DELETE RESTRICT, "
  84. " FOREIGN KEY(acft) REFERENCES tails(tail_id) ON DELETE RESTRICT, "
  85. " PRIMARY KEY(flight_id AUTOINCREMENT) "
  86. ")");
  87. const auto createTableAirports = QLatin1String("CREATE TABLE airports ( "
  88. " airport_id INTEGER NOT NULL, "
  89. " icao TEXT NOT NULL, "
  90. " iata TEXT, "
  91. " name TEXT, "
  92. " lat REAL, "
  93. " long REAL, "
  94. " country TEXT, "
  95. " alt INTEGER, "
  96. " utcoffset INTEGER, "
  97. " tzolson TEXT, "
  98. " PRIMARY KEY(airport_id AUTOINCREMENT) "
  99. ")");
  100. const auto createTableAircraft = QLatin1String("CREATE TABLE aircraft ("
  101. " aircraft_id INTEGER NOT NULL,"
  102. " make TEXT,"
  103. " model TEXT,"
  104. " variant TEXT,"
  105. " name TEXT,"
  106. " iata TEXT,"
  107. " icao TEXT,"
  108. " multipilot INTEGER,"
  109. " multiengine INTEGER,"
  110. " engineType INTEGER,"
  111. " weightClass INTEGER,"
  112. " PRIMARY KEY(aircraft_id AUTOINCREMENT)"
  113. ")");
  114. const auto createTableChangelog = QLatin1String("CREATE TABLE changelog ( "
  115. " revision INTEGER NOT NULL, "
  116. " comment TEXT, "
  117. " date NUMERIC, "
  118. " PRIMARY KEY(revision) "
  119. ")");
  120. const auto createTableCurrencies = QLatin1String("CREATE TABLE currencies ( "
  121. " currency_id INTEGER PRIMARY KEY AUTOINCREMENT, "
  122. " description TEXT, "
  123. " expiryDate NUMERIC "
  124. ")"
  125. );
  126. // Statements for creation of views in the database
  127. const auto createViewDefault = QLatin1String("CREATE VIEW viewDefault AS "
  128. " SELECT flight_id, doft as 'Date', "
  129. " dept AS 'Dept', "
  130. " printf('%02d',(tofb/60))||':'||printf('%02d',(tofb%60)) AS 'Time', "
  131. " dest AS 'Dest', printf('%02d',(tonb/60))||':'||printf('%02d',(tonb%60)) AS 'Time ', "
  132. " printf('%02d',(tblk/60))||':'||printf('%02d',(tblk%60)) AS 'Total', "
  133. " CASE "
  134. " WHEN pilot_id = 1 THEN alias "
  135. " ELSE lastname||', '||substr(firstname, 1, 1)||'.' "
  136. " END "
  137. " AS 'Name PIC', "
  138. " CASE "
  139. " WHEN variant IS NOT NULL THEN make||' '||model||'-'||variant "
  140. " ELSE make||' '||model "
  141. " END "
  142. " AS 'Type', "
  143. " registration AS 'Registration', "
  144. " FlightNumber AS 'Flight #', "
  145. " remarks AS 'Remarks'"
  146. " FROM flights "
  147. " INNER JOIN pilots on flights.pic = pilots.pilot_id "
  148. " INNER JOIN tails on flights.acft = tails.tail_id "
  149. " ORDER BY date DESC ");
  150. const auto createViewEASA = QLatin1String("CREATE VIEW viewEASA AS "
  151. " SELECT "
  152. " flight_id, doft as 'Date', "
  153. " dept AS 'Dept', "
  154. " printf('%02d',(tofb/60))||':'||printf('%02d',(tofb%60)) AS 'Time', "
  155. " dest AS 'Dest', printf('%02d',(tonb/60))||':'||printf('%02d',(tonb%60)) AS 'Time ', "
  156. " CASE "
  157. " WHEN variant IS NOT NULL THEN make||' '||model||'-'||variant "
  158. " ELSE make||' '||model "
  159. " END "
  160. " AS 'Type', "
  161. " registration AS 'Registration', "
  162. " (SELECT printf('%02d',(tSPSE/60))||':'||printf('%02d',(tSPSE%60)) WHERE tSPSE IS NOT NULL) AS 'SP SE', "
  163. " (SELECT printf('%02d',(tSPME/60))||':'||printf('%02d',(tSPME%60)) WHERE tSPME IS NOT NULL) AS 'SP ME', "
  164. " (SELECT printf('%02d',(tMP/60))||':'||printf('%02d',(tMP%60)) WHERE tMP IS NOT NULL) AS 'MP', "
  165. " printf('%02d',(tblk/60))||':'||printf('%02d',(tblk%60)) AS 'Total', "
  166. " CASE "
  167. " WHEN pilot_id = 1 THEN alias "
  168. " ELSE lastname||', '||substr(firstname, 1, 1)||'.' "
  169. " END "
  170. " AS 'Name PIC', "
  171. " ldgDay AS 'L/D', "
  172. " ldgNight AS 'L/N', "
  173. " (SELECT printf('%02d',(tNight/60))||':'||printf('%02d',(tNight%60)) WHERE tNight IS NOT NULL) AS 'Night', "
  174. " (SELECT printf('%02d',(tIFR/60))||':'||printf('%02d',(tIFR%60)) WHERE tIFR IS NOT NULL) AS 'IFR', "
  175. " (SELECT printf('%02d',(tPIC/60))||':'||printf('%02d',(tPIC%60)) WHERE tPIC IS NOT NULL) AS 'PIC', "
  176. " (SELECT printf('%02d',(tSIC/60))||':'||printf('%02d',(tSIC%60)) WHERE tSIC IS NOT NULL) AS 'SIC', "
  177. " (SELECT printf('%02d',(tDual/60))||':'||printf('%02d',(tDual%60)) WHERE tDual IS NOT NULL) AS 'Dual', "
  178. " (SELECT printf('%02d',(tFI/60))||':'||printf('%02d',(tFI%60)) WHERE tFI IS NOT NULL) AS 'FI', "
  179. " remarks AS 'Remarks' "
  180. " FROM flights "
  181. " INNER JOIN pilots on flights.pic = pilots.pilot_id "
  182. " INNER JOIN tails on flights.acft = tails.tail_id "
  183. " ORDER BY date DESC");
  184. const auto createViewTails = QLatin1String("CREATE VIEW viewTails AS "
  185. " SELECT "
  186. " tail_id AS 'ID', "
  187. " registration AS 'Registration', "
  188. " make||' '||model AS 'Type', "
  189. " company AS 'Company' "
  190. " FROM tails WHERE model IS NOT NULL AND variant IS NULL "
  191. " UNION "
  192. " SELECT "
  193. " tail_id AS 'ID', "
  194. " registration AS 'Registration', "
  195. " make||' '||model||'-'||variant AS 'Type', "
  196. " company AS 'Company' "
  197. " FROM tails WHERE variant IS NOT NULL");
  198. const auto createViewPilots = QLatin1String("CREATE VIEW viewPilots AS "
  199. " SELECT "
  200. " pilot_id AS 'ID', "
  201. " lastname AS 'Last Name', "
  202. " firstname AS 'First Name', "
  203. " company AS 'Company' "
  204. " FROM pilots");
  205. const auto createViewQCompleter = QLatin1String("CREATE VIEW viewQCompleter AS "
  206. " SELECT airport_id, icao, iata, tail_id, registration, pilot_id, "
  207. " lastname||', '||firstname AS 'pilot_name', alias "
  208. " FROM airports "
  209. " LEFT JOIN tails ON airports.airport_id = tails.tail_id "
  210. " LEFT JOIN pilots ON airports.airport_id = pilots.pilot_id");
  211. const auto createViewTotals = QLatin1String("CREATE VIEW viewTotals AS "
  212. " SELECT "
  213. " printf(\"%02d\",CAST(SUM(tblk) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tblk) AS INT)%60) AS \"TOTAL\", "
  214. " printf(\"%02d\",CAST(SUM(tSPSE) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tSPSE) AS INT)%60) AS \"SP SE\", "
  215. " printf(\"%02d\",CAST(SUM(tSPME) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tSPME) AS INT)%60) AS \"SP ME\", "
  216. " printf(\"%02d\",CAST(SUM(tNIGHT) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tNIGHT) AS INT)%60) AS \"NIGHT\", "
  217. " printf(\"%02d\",CAST(SUM(tIFR) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tIFR) AS INT)%60) AS \"IFR\", "
  218. " printf(\"%02d\",CAST(SUM(tPIC) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tPIC) AS INT)%60) AS \"PIC\", "
  219. " printf(\"%02d\",CAST(SUM(tPICUS) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tPICUS) AS INT)%60) AS \"PICUS\", "
  220. " printf(\"%02d\",CAST(SUM(tSIC) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tSIC) AS INT)%60) AS \"SIC\", "
  221. " printf(\"%02d\",CAST(SUM(tDual) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tDual) AS INT)%60) AS \"DUAL\", "
  222. " printf(\"%02d\",CAST(SUM(tFI) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tFI) AS INT)%60) AS \"INSTRUCTOR\", "
  223. " printf(\"%02d\",CAST(SUM(tSIM) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tSIM) AS INT)%60) AS \"SIMULATOR\", "
  224. " printf(\"%02d\",CAST(SUM(tMP) AS INT)/60)||\":\"||printf(\"%02d\",CAST(SUM(tMP) AS INT)%60) AS \"MultPilot\", "
  225. " CAST(SUM(toDay) AS INT) AS \"TO Day\", CAST(SUM(toNight) AS INT) AS \"TO Night\", "
  226. " CAST(SUM(ldgDay) AS INT) AS \"LDG Day\", CAST(SUM(ldgNight) AS INT) AS \"LDG Night\" "
  227. " FROM flights");
  228. const QStringList tables = {
  229. createTablePilots,
  230. createTableTails,
  231. createTableFlights,
  232. createTableAircraft,
  233. createTableAirports,
  234. createTableCurrencies,
  235. createTableChangelog
  236. };
  237. const QStringList views = {
  238. createViewDefault,
  239. createViewEASA,
  240. createViewTails,
  241. createViewPilots,
  242. createViewTotals,
  243. createViewQCompleter,
  244. };
  245. const QStringList userTables = {
  246. QStringLiteral("flights"),
  247. QStringLiteral("pilots"),
  248. QStringLiteral("tails")
  249. };
  250. const QStringList templateTables= {
  251. QStringLiteral("aircraft"),
  252. QStringLiteral("airports"),
  253. QStringLiteral("currencies"),
  254. QStringLiteral("changelog")
  255. };
  256. bool ADataBaseSetup::createDatabase()
  257. {
  258. DEB << "Creating tables...";
  259. if (!createSchemata(tables)) {
  260. DEB << "Creating tables has failed.";
  261. return false;
  262. }
  263. DEB << "Creating views...";
  264. if (!createSchemata(views)) {
  265. DEB << "Creating views failed.";
  266. return false;
  267. }
  268. aDB->updateLayout();
  269. LOG << "Database successfully created!\n";
  270. return true;
  271. }
  272. bool ADataBaseSetup::downloadTemplates()
  273. {
  274. QDir template_dir(AStandardPaths::directory(AStandardPaths::Templates));
  275. DEB << template_dir;
  276. for (const auto& table : templateTables) {
  277. QEventLoop loop;
  278. ADownload* dl = new ADownload;
  279. QObject::connect(dl, &ADownload::done, &loop, &QEventLoop::quit );
  280. dl->setTarget(QUrl(TEMPLATE_URL + table + QLatin1String(".csv")));
  281. dl->setFileName(template_dir.absoluteFilePath(table + QLatin1String(".csv")));
  282. dl->download();
  283. dl->deleteLater();
  284. loop.exec(); // event loop waits for download done signal before allowing loop to continue
  285. QFileInfo downloaded_file(template_dir.filePath(table + QLatin1String(".csv")));
  286. if (downloaded_file.size() == 0)
  287. return false; // ssl/network error
  288. }
  289. return true;
  290. }
  291. bool ADataBaseSetup::backupOldData()
  292. {
  293. LOG << "Backing up old database...";
  294. QFileInfo database_file(AStandardPaths::directory(AStandardPaths::Database).
  295. absoluteFilePath(QStringLiteral("logbook.db")));
  296. DEB << "File Info:" << database_file;
  297. if(!database_file.exists()) {
  298. DEB << "No Database to backup, returning.";
  299. return true;
  300. }
  301. auto date_string = ADateTime::toString(QDateTime::currentDateTime(),
  302. Opl::Datetime::Backup);
  303. auto backup_dir = AStandardPaths::directory(AStandardPaths::Backup);
  304. QString backup_name = database_file.baseName() + QLatin1String("_bak_")
  305. + date_string + QLatin1String(".db");
  306. QFile file(database_file.absoluteFilePath());
  307. DEB << "File:" << file;
  308. if (!file.rename(backup_dir.absoluteFilePath(backup_name))) {
  309. LOG << "Unable to backup old database.\n";
  310. return false;
  311. }
  312. LOG << "Backed up old database as: " << backup_name << "\n";
  313. return true;
  314. }
  315. bool ADataBaseSetup::importDefaultData(bool use_ressource_data)
  316. {
  317. QSqlQuery query;
  318. // reset template tables
  319. for (const auto& table_name : templateTables) {
  320. //clear tables
  321. query.prepare("DELETE FROM " + table_name);
  322. if (!query.exec()) {
  323. DEB << "Error: " << query.lastError().text();
  324. return false;
  325. }
  326. // Prepare data
  327. QVector<QStringList> data_to_commit;
  328. QString error_message("Error importing data ");
  329. if (use_ressource_data) {
  330. data_to_commit = aReadCsv(QStringLiteral(":templates/database/templates/")
  331. + table_name + QLatin1String(".csv"));
  332. error_message.append(" (ressource) ");
  333. } else {
  334. data_to_commit = aReadCsv(AStandardPaths::directory(
  335. AStandardPaths::Templates).absoluteFilePath(
  336. table_name + QLatin1String(".csv")));
  337. error_message.append(" (downloaded) ");
  338. }
  339. //fill with data from csv
  340. if (!commitData(data_to_commit, table_name)) {
  341. LOG << error_message;
  342. return false;
  343. }
  344. }
  345. return true;
  346. };
  347. /*!
  348. * \brief DbSetup::resetToDefault Empties all user-generated content in the database.
  349. * \return true on success
  350. */
  351. bool ADataBaseSetup::resetToDefault()
  352. {
  353. QSqlQuery query;
  354. // clear user tables
  355. for (const auto& table : userTables) {
  356. query.prepare("DELETE FROM " + table);
  357. if (!query.exec()) {
  358. DEB << "Error: " << query.lastError().text();
  359. }
  360. }
  361. return true;
  362. }
  363. /*!
  364. * \brief dbSetup::debug prints Database Layout
  365. */
  366. void ADataBaseSetup::debug()
  367. {
  368. DEB << "Database tables and views: ";
  369. QSqlQuery query;
  370. const QVector<QString> types = { "table", "view" };
  371. for (const auto& var : types){
  372. query.prepare("SELECT name FROM sqlite_master WHERE type=" + var);
  373. query.exec();
  374. while (query.next()) {
  375. QString table = query.value(0).toString();
  376. QSqlQuery entries("SELECT COUNT(*) FROM " + table);
  377. entries.next();
  378. DEB << "Element " << query.value(0).toString() << "with"
  379. << entries.value(0).toString() << "rows";
  380. }
  381. }
  382. }
  383. /*!
  384. * \brief dbSetup::createTables Create the required tables for the database
  385. * \return true on success
  386. */
  387. bool ADataBaseSetup::createSchemata(const QStringList &statements)
  388. {
  389. QSqlQuery query;
  390. QStringList errors;
  391. for (const auto& statement : statements) {
  392. query.prepare(statement);
  393. query.exec();
  394. if(!query.isActive()) {
  395. errors << statement.section(QLatin1Char(' '),2,2) + " ERROR - " + query.lastError().text();
  396. DEB << "Query: " << query.lastQuery();
  397. continue;
  398. }
  399. DEB << "Schema added: " << statement.section(QLatin1Char(' '), 2, 2);
  400. }
  401. if (!errors.isEmpty()) {
  402. DEB_SRC << "The following errors have ocurred: ";
  403. for (const auto& error : qAsConst(errors)) {
  404. DEB_RAW << error;
  405. }
  406. return false;
  407. }
  408. LOG << "All database tables created successfully\n";
  409. return true;
  410. }
  411. /*!
  412. * \brief DbSetup::commitData inserts the data parsed from a csv file into the
  413. * database. The first line of the csv file has to contain the column names
  414. * of the corresponding table in the database.
  415. * \param fromCSV input as parsed from CSV::read()
  416. * \param tableName as in the database
  417. * \return
  418. */
  419. bool ADataBaseSetup::commitData(QVector<QStringList> from_csv, const QString &table_name)
  420. {
  421. aDB->updateLayout();
  422. if (!aDB->getTableNames().contains(table_name)){
  423. DEB << table_name << "is not a table in the database. Aborting.";
  424. DEB << "Please check input data.";
  425. return false;
  426. }
  427. // create insert statement
  428. QString statement = "INSERT INTO " + table_name + " (";
  429. QString placeholder = ") VALUES (";
  430. for (auto& csvColumn : from_csv) {
  431. if(aDB->getTableColumns(table_name).contains(csvColumn.first())) {
  432. statement += csvColumn.first() + ',';
  433. csvColumn.removeFirst();
  434. placeholder.append("?,");
  435. } else {
  436. DEB << csvColumn.first() << "is not a column of " << table_name << "Aborting.";
  437. DEB << "Please check input data.";
  438. return false;
  439. }
  440. }
  441. statement.chop(1);
  442. placeholder.chop(1);
  443. placeholder.append(')');
  444. statement.append(placeholder);
  445. /*
  446. * Using exclusive transaction and the loop below is MUCH faster than
  447. * passing the QStringLists to QSqlQuery::addBindValue and using QSqlQuery::execBatch()
  448. */
  449. QSqlQuery query;
  450. query.exec("BEGIN EXCLUSIVE TRANSACTION;");
  451. for (int i = 0; i < from_csv.first().length(); i++){
  452. query.prepare(statement);
  453. for(int j = 0; j < from_csv.length(); j++) {
  454. from_csv[j][i] == QString("") ? // make sure NULL is committed for empty values
  455. query.addBindValue(QVariant(QString()))
  456. : query.addBindValue(from_csv[j][i]);
  457. //query.addBindValue(fromCSV[j][i]);
  458. }
  459. query.exec();
  460. }
  461. query.exec("COMMIT;"); //commit transaction
  462. if (query.lastError().text().length() > 3) {
  463. DEB << "Error:" << query.lastError().text();
  464. return false;
  465. } else {
  466. qDebug() << table_name << "Database successfully updated!";
  467. return true;
  468. }
  469. }