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