dbsetup.cpp 13 KB

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