dbsetup.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. *openPilot Log - A FOSS Pilot Logbook Application
  3. *Copyright (C) 2020 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 "dbsetup.h"
  19. /// dummy db connection for debugging
  20. void dbSetup::connect()
  21. {
  22. const QString DRIVER("QSQLITE");
  23. if(QSqlDatabase::isDriverAvailable(DRIVER))
  24. {
  25. QSqlDatabase db = QSqlDatabase::addDatabase(DRIVER);
  26. db.setDatabaseName("debug.db");
  27. if(!db.open())
  28. qWarning() << "DatabaseConnect - ERROR: " << db.lastError().text();
  29. }
  30. else
  31. qWarning() << "DatabaseConnect - ERROR: no driver " << DRIVER << " available";
  32. }
  33. // Pragmas for creation of database table
  34. const QString createTablePilots = "CREATE TABLE pilots ( "
  35. "pilot_id INTEGER, "
  36. "picfirstname TEXT, "
  37. "piclastname TEXT NOT NULL, "
  38. "alias TEXT, "
  39. "phone TEXT, "
  40. "email TEXT, "
  41. "rostername TEXT, "
  42. "PRIMARY KEY(pilot_id) "
  43. ")";
  44. const QString createTableAircraft = "CREATE TABLE aircraft ( "
  45. "aircraft_id integer, "
  46. "make TEXT, "
  47. "model TEXT, "
  48. "variant text, "
  49. "name TEXT, "
  50. "iata TEXT, "
  51. "icao TEXT, "
  52. "singlepilot INTEGER, "
  53. "multipilot INTEGER, "
  54. "singleengine INTEGER, "
  55. "multiengine INTEGER, "
  56. "turboprop INTEGER, "
  57. "jet INTEGER, "
  58. "heavy INTEGER, "
  59. "PRIMARY KEY(aircraft_id) "
  60. ") ";
  61. const QString createTableTails = "CREATE TABLE tails ( "
  62. "tail_id INTEGER, "
  63. "registration TEXT NOT NULL, "
  64. "aircraft_id INTEGER NOT NULL, "
  65. "company TEXT, "
  66. "PRIMARY KEY(tail_id), "
  67. "FOREIGN KEY(aircraft_id) REFERENCES aircraft(aircraft_id) "
  68. ")";
  69. const QString createTableFlights = "CREATE TABLE flights ( "
  70. "id INTEGER, "
  71. "doft NUMERIC NOT NULL, "
  72. "dept TEXT NOT NULL, "
  73. "tofb INTEGER NOT NULL, "
  74. "dest TEXT NOT NULL, "
  75. "tonb INTEGER NOT NULL, "
  76. "tblk INTEGER NOT NULL, "
  77. "pic INTEGER, "
  78. "acft INTEGER, "
  79. "PRIMARY KEY(id), "
  80. "FOREIGN KEY(pic) REFERENCES pilots(pilot_id), "
  81. "FOREIGN KEY(acft) REFERENCES tails(tail_id) "
  82. ")";
  83. //extras table might eventually be merged into flights table.
  84. const QString createTableExtras = "CREATE TABLE extras ( "
  85. "extras_id INTEGER NOT NULL, "
  86. "PilotFlying INTEGER, "
  87. "TOday INTEGER, "
  88. "TOnight INTEGER, "
  89. "LDGday INTEGER, "
  90. "LDGnight INTEGER, "
  91. "autoland INTEGER, "
  92. "tSPSE INTEGER, "
  93. "tSPME INTEGER, "
  94. "tMPME INTEGER, "
  95. "tNight INTEGER, "
  96. "tIFR INTEGER, "
  97. "tPIC INTEGER, "
  98. "tSIC INTEGER, "
  99. "tDual INTEGER, "
  100. "tInstructor INTEGER, "
  101. "tSIM INTEGER, "
  102. "ApproachType TEXT, "
  103. "FlightNumber TEXT, "
  104. "Remarks TEXT, "
  105. "PRIMARY KEY(extras_id) "
  106. ")";
  107. const QString createTableAirports = "CREATE TABLE airports ( "
  108. "airport_id INTEGER primary key, "
  109. "icao TEXT NOT NULL, "
  110. "iata TEXT, "
  111. "name TEXT, "
  112. "lat REAL, "
  113. "long REAL, "
  114. "country TEXT, "
  115. "alt INTEGER, "
  116. "utcoffset INTEGER, "
  117. "tzolson TEXT "
  118. ")";
  119. const QString createTableScratchpad = "CREATE TABLE scratchpad ( "
  120. "id INTEGER, "
  121. "doft NUMERIC, "
  122. "dept TEXT, "
  123. "tofb INTEGER, "
  124. "dest TEXT, "
  125. "tonb INTEGER, "
  126. "tblk INTEGER, "
  127. "pic INTEGER, "
  128. "acft INTEGER, "
  129. "PRIMARY KEY(id) "
  130. ") ";
  131. const QString createTableSettings = "CREATE TABLE settings ( "
  132. "setting_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
  133. "setting TEXT, "
  134. "description TEXT "
  135. ")";
  136. // Pragmas for creation of views in the database
  137. const QString createViewQCompleterView = "CREATE VIEW QCompleterView AS "
  138. "SELECT airport_id, icao, iata, "
  139. "tail_id, registration, "
  140. "pilot_id, "
  141. "piclastname||', '||picfirstname AS 'pilot_name', "
  142. "alias "
  143. "FROM airports "
  144. "LEFT JOIN tails ON airports.airport_id = tails.tail_id "
  145. "LEFT JOIN pilots ON airports.airport_id = pilots.pilot_id";
  146. const QString createViewAircraftList = "CREATE VIEW AircraftListView AS "
  147. "SELECT make AS 'Make', "
  148. "model AS 'Model', "
  149. "variant AS 'Variant' "
  150. "FROM aircraft "
  151. "WHERE variant IS NOT NULL";
  152. const QString createViewLogbook = "CREATE VIEW Logbook AS "
  153. "SELECT id, doft as 'Date', dept AS 'Dept', "
  154. "printf('%02d',(tofb/60))||':'||printf('%02d',(tofb%60)) AS 'Time', "
  155. "dest AS 'Dest', "
  156. "printf('%02d',(tonb/60))||':'||printf('%02d',(tonb%60)) AS 'Time ', "
  157. "printf('%02d',(tblk/60))||':'||printf('%02d',(tblk%60)) AS 'Total', "
  158. "piclastname||', '||substr(picfirstname,1,1)||'.' AS 'Name PIC', "
  159. "make||' '||model||'-'||variant AS 'Type', Registration, "
  160. "FlightNumber AS 'Flight #', Remarks "
  161. "FROM flights "
  162. "INNER JOIN pilots on flights.pic = pilots.pilot_id "
  163. "INNER JOIN tails on flights.acft = tails.tail_id "
  164. "INNER JOIN aircraft on tails.aircraft_id = aircraft.aircraft_id "
  165. "INNER JOIN extras on extras.extras_id = flights.id "
  166. "ORDER BY date DESC ";
  167. //Displays Single Engine, Multi Engine and Multi Pilot Time
  168. const QString createViewTimes = "CREATE VIEW ViewPilotTimes AS "
  169. "SELECT id, "
  170. "tblk*singlepilot*singleengine AS 'SPSE', "
  171. "tblk*singlepilot*multiengine AS 'SPME', "
  172. "tblk*multipilot AS 'MP' "
  173. "FROM flights "
  174. "INNER JOIN tails on flights.acft = tails.tail_id "
  175. "INNER JOIN aircraft on tails.aircraft_id = aircraft.aircraft_id ";
  176. QStringList tables = {
  177. createTablePilots,
  178. createTableAircraft,
  179. createTableTails,
  180. createTableFlights,
  181. createTableExtras,
  182. createTableScratchpad,
  183. createTableAirports,
  184. createTableSettings
  185. };
  186. QStringList views = {
  187. createViewQCompleterView,
  188. createViewAircraftList,
  189. createViewLogbook,
  190. createViewTimes
  191. };
  192. /*!
  193. * \brief dbSetup::showDatabase Outputs database information to Console
  194. */
  195. void dbSetup::showDatabase()
  196. {
  197. QSqlQuery query;
  198. query.prepare("SELECT name FROM sqlite_master WHERE type='table'");
  199. query.exec();
  200. while (query.next()) {
  201. qDebug() << "Tables: " << query.value(0).toString();
  202. }
  203. query.prepare("SELECT name FROM sqlite_master WHERE type='view'");
  204. query.exec();
  205. while (query.next()) {
  206. qDebug() << "Views: " << query.value(0).toString();
  207. }
  208. }
  209. /*!
  210. * \brief dbSetup::createTables Create the required tables for the database
  211. */
  212. void dbSetup::createTables()
  213. {
  214. QSqlQuery query;
  215. for(int i = 0; i<tables.length() ; i++) {
  216. query.prepare(tables[i]);
  217. query.exec();
  218. if(!query.isActive()) {
  219. qWarning() << "DatabaseInit - ERROR: " << query.lastError().text();
  220. }else
  221. qDebug() << "Adding table " << tables[i].section(QLatin1Char(' '),2,2);
  222. }
  223. }
  224. /*!
  225. * \brief dbSetup::createViews Create the required views for the database
  226. */
  227. void dbSetup::createViews()
  228. {
  229. QSqlQuery query;
  230. for(int i = 0; i<views.length() ; i++) {
  231. query.prepare(views[i]);
  232. query.exec();
  233. if(!query.isActive()){
  234. qWarning() << "DatabaseInit - ERROR: " << query.lastError().text();
  235. }else{
  236. qDebug() << "Adding View " << views[i].section(QLatin1Char(' '),2,2);
  237. }
  238. }
  239. }
  240. /*!
  241. * \brief dbSetup::importCSV reads from a CSV file
  242. * \param filename - QString to csv file.
  243. * \return QVector<QStringList> of the CSV data, where each QStringList is one column of the input file
  244. */
  245. QVector<QStringList> dbSetup::importCSV(QString filename)
  246. {
  247. QFile csvfile(filename);
  248. csvfile.open(QIODevice::ReadOnly);
  249. QTextStream stream(&csvfile);
  250. QVector<QStringList> values;
  251. //Read CSV headers and create QStringLists accordingly
  252. QString line = stream.readLine();
  253. auto items = line.split(",");
  254. for (int i = 0; i < items.length(); i++) {
  255. QStringList list;
  256. list.append(items[i]);
  257. values.append(list);
  258. }
  259. //Fill QStringLists with data
  260. while (!stream.atEnd()) {
  261. QString line = stream.readLine();
  262. auto items = line.split(",");
  263. for (int i = 0; i < values.length(); i++) {
  264. values[i].append(items[i]);
  265. }
  266. }
  267. qDebug() << "Values: " << values;
  268. return values;
  269. }
  270. /*QVector<QStringList> dbSetup::importAirportsFromCSV()
  271. {
  272. QStringList icao;
  273. QStringList iata;
  274. QStringList name;
  275. QStringList latitude;
  276. QStringList longitude;
  277. QStringList country;
  278. QStringList altitude;
  279. QStringList utcoffset;
  280. QStringList tzolson;
  281. QFile input("test.csv");
  282. input.open(QIODevice::ReadOnly);
  283. QTextStream inputStream(&input);
  284. while (!inputStream.atEnd()) {
  285. QString line = inputStream.readLine();
  286. auto items = line.split(",");
  287. icao.append(items[0]);
  288. iata.append(items[1]);
  289. name.append(items[2]);
  290. latitude.append(items[3]);
  291. longitude.append(items[4]);
  292. country.append(items[5]);
  293. altitude.append(items[6]);
  294. utcoffset.append(items[7]);
  295. tzolson.append(items[8]);
  296. }
  297. QVector<QStringList> airportData = {
  298. icao,
  299. iata,
  300. name,
  301. latitude,
  302. longitude,
  303. country,
  304. altitude,
  305. utcoffset,
  306. tzolson
  307. };
  308. for(int i=0; i < airportData.length(); i++)
  309. {
  310. airportData[i].removeFirst();
  311. }
  312. qDebug() << "Airport Data: " << airportData;
  313. return airportData;
  314. }*/
  315. void dbSetup::commitAirportData(QVector<QStringList> airportData)
  316. {
  317. //remove header names
  318. for(int i=0; i < airportData.length(); i++)
  319. {
  320. airportData[i].removeFirst();
  321. }
  322. QSqlQuery query;
  323. qDebug() << "Updating Airport Database...";
  324. query.exec("BEGIN EXCLUSIVE TRANSACTION;"); // otherwise execution takes forever
  325. for (int i = 0; i < airportData[0].length(); i++){
  326. query.prepare("INSERT INTO airports ("
  327. "icao, "
  328. "iata, "
  329. "name, "
  330. "lat, "
  331. "long, "
  332. "country, "
  333. "alt, "
  334. "utcoffset, "
  335. "tzolson"
  336. ") "
  337. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
  338. query.addBindValue(airportData[0][i]);
  339. query.addBindValue(airportData[1][i]);
  340. query.addBindValue(airportData[2][i]);
  341. query.addBindValue(airportData[3][i]);
  342. query.addBindValue(airportData[4][i]);
  343. query.addBindValue(airportData[5][i]);
  344. query.addBindValue(airportData[6][i]);
  345. query.addBindValue(airportData[7][i]);
  346. query.addBindValue(airportData[8][i]);
  347. query.exec();
  348. }
  349. query.exec("COMMIT;"); //commit transaction
  350. qDebug() << "Airport Database updated!";
  351. }