dbman.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 <QCoreApplication>
  19. #include <QDebug>
  20. #include <QSqlDatabase>
  21. #include <QSqlDriver>
  22. #include <QSqlError>
  23. #include <QSqlQuery>
  24. #include "calc.h"
  25. #include "dbpilots.h"
  26. #include <chrono>
  27. #include <QRandomGenerator>
  28. #include <QStandardPaths>
  29. class db
  30. {
  31. public:
  32. static void connect()
  33. {
  34. const QString DRIVER("QSQLITE");
  35. if(QSqlDatabase::isDriverAvailable(DRIVER))
  36. {
  37. QSqlDatabase db = QSqlDatabase::addDatabase(DRIVER);
  38. //QString pathtodb = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
  39. //db.setDatabaseName(pathtodb+"/logbook.db");
  40. //qDebug() << "Database: " << pathtodb+"/logbook.db";
  41. db.setDatabaseName("logbook.db");
  42. if(!db.open())
  43. qWarning() << "MainWindow::DatabaseConnect - ERROR: " << db.lastError().text();
  44. }
  45. else
  46. qWarning() << "MainWindow::DatabaseConnect - ERROR: no driver " << DRIVER << " available";
  47. }
  48. static void initexample()
  49. {
  50. QSqlQuery query("CREATE TABLE flights (id INTEGER PRIMARY KEY, date NUMERIC)");
  51. if(!query.isActive())
  52. qWarning() << "MainWindow::DatabaseInit - ERROR: " << query.lastError().text();
  53. }
  54. static void queryexamplenamedbinding()
  55. {
  56. QSqlQuery query;
  57. //query.prepare("SELECT * FROM people");
  58. //query.prepare("SELECT * FROM people WHERE name LIKE 'Linus' OR id = :id");
  59. query.prepare("SELECT * from people WHERE name LIKE :name");
  60. query.bindValue(":name", "%Linus%");
  61. query.bindValue(":id",2);
  62. query.exec();
  63. /*
  64. * QSqlQuery provides access to the result set one record at a time. After the call to exec(),
  65. * QSqlQuery's internal pointer is located one position before the first record.
  66. * We must call QSqlQuery::next() once to advance to the first record, then next() again
  67. * repeatedly to access the other records, until it returns false. Here's a typical loop that
  68. * iterates over all the records in order:
  69. * After a SELECT query is executed we have to browse the records (result rows) returned to access
  70. * the data. In this case we try to retrieve the first record calling the function first which
  71. * returns true when the query has been successful and false otherwise.
  72. */
  73. if(query.first());
  74. else
  75. qDebug() << ("No entry found");
  76. query.previous();//To go back to index 0
  77. while (query.next()) {
  78. QString name = query.value(1).toString();
  79. int id = query.value(0).toInt();
  80. qDebug() << name << id;
  81. }
  82. /*
  83. *The QSqlQuery::value() function returns the value of a field in the current record. Fields are
  84. * specified as zero-based indexes. QSqlQuery::value() returns a QVariant, a type that can hold
  85. * various C++ and core Qt data types such as int, QString, and QByteArray. The different database
  86. * types are automatically mapped into the closest Qt equivalent. In the code snippet, we call
  87. * QVariant::toString() and QVariant::toInt() to convert variants to QString and int.
  88. */
  89. }
  90. /*
  91. * Airport Database Related Functions
  92. */
  93. /*!
  94. * \brief RetreiveAirportNameFromIcaoOrIata Looks up Airport Name
  95. * \param identifier can be ICAO or IATA airport codes.
  96. * \return The name of the airport associated with the above code
  97. */
  98. static QString RetreiveAirportNameFromIcaoOrIata(QString identifier)
  99. {
  100. QString result = "";
  101. QSqlQuery query;
  102. query.prepare("SELECT name "
  103. "FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  104. identifier.append("%");
  105. identifier.prepend("%");
  106. query.addBindValue(identifier);
  107. query.addBindValue(identifier);
  108. query.exec();
  109. if(query.first())
  110. {
  111. result.append(query.value(0).toString());
  112. return result;
  113. }else
  114. {
  115. result = result.left(result.length()-1);
  116. result.append("No matching airport found.");
  117. return result;
  118. }
  119. }
  120. static QString RetreiveAirportIdFromIcao(QString identifier)
  121. {
  122. QString result;
  123. QSqlQuery query;
  124. query.prepare("SELECT airport_id FROM airports WHERE icao = ?");
  125. query.addBindValue(identifier);
  126. query.exec();
  127. while(query.next())
  128. {
  129. result.append(query.value(0).toString());
  130. //qDebug() << "db::RetreiveAirportIdFromIcao says Airport found! #" << result;
  131. }
  132. return result;
  133. }
  134. static QStringList CompleteIcaoOrIata(QString icaoStub)
  135. {
  136. QStringList result;
  137. QSqlQuery query;
  138. query.prepare("SELECT icao FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  139. icaoStub.prepend("%"); icaoStub.append("%");
  140. query.addBindValue(icaoStub);
  141. query.addBindValue(icaoStub);
  142. query.exec();
  143. while(query.next())
  144. {
  145. result.append(query.value(0).toString());
  146. qDebug() << "db::CompleteIcaoOrIata says... Result:" << result;
  147. }
  148. return result;
  149. }
  150. /*!
  151. * \brief CheckICAOValid Verifies if a user input airport exists in the database
  152. * \param identifier can be ICAO or IATA airport codes.
  153. * \return bool if airport is in database.
  154. */
  155. static bool CheckICAOValid(QString identifier)
  156. {
  157. if(identifier.length() == 4)
  158. {
  159. QString check = RetreiveAirportIdFromIcao(identifier);
  160. if(check.length() > 0)
  161. {
  162. //qDebug() << "db::CheckICAOValid says: Check passed!";
  163. return 1;
  164. }else
  165. {
  166. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Lookup unsuccessful";
  167. return 0;
  168. }
  169. }else
  170. {
  171. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Empty String NOT epico!";
  172. return 0;
  173. }
  174. }
  175. /*!
  176. * \brief retreiveIcaoCoordinates Looks up coordinates (lat,long) for a given airport
  177. * \param icao 4-letter code for the airport
  178. * \return {lat,lon} in decimal degrees
  179. */
  180. static QVector<double> retreiveIcaoCoordinates(QString icao)
  181. {
  182. QSqlQuery query;
  183. query.prepare("SELECT lat, long "
  184. "FROM airports "
  185. "WHERE icao = ?");
  186. query.addBindValue(icao);
  187. query.exec();
  188. QVector<double> result;
  189. while(query.next()) {
  190. result.append(query.value(0).toDouble());
  191. result.append(query.value(1).toDouble());
  192. }
  193. return result;
  194. }
  195. /*
  196. * Aircraft Database Related Functions
  197. */
  198. /*!
  199. * \brief RetreiveRegistration Looks up tail_id from Database
  200. * \param tail_ID Primary Key of tails database
  201. * \return Registration
  202. */
  203. static QString RetreiveRegistration(QString tail_ID)
  204. {
  205. QString acftRegistration("");
  206. QSqlQuery query;
  207. query.prepare("SELECT registration FROM tails WHERE tail_id == ?");
  208. query.addBindValue(tail_ID.toInt());
  209. query.exec();
  210. if(query.first());
  211. else
  212. qDebug() << ("No Aircraft with this ID found");
  213. query.previous();//To go back to index 0
  214. while (query.next()) {
  215. acftRegistration.append(query.value(0).toString());
  216. }
  217. return acftRegistration;
  218. }
  219. /*!
  220. * \brief newAcftGetString Looks up an aircraft Registration in the database
  221. * \param searchstring
  222. * \return Registration, make, model and variant
  223. */
  224. static QStringList newAcftGetString(QString searchstring)
  225. {
  226. QStringList result;
  227. if(searchstring.length()<2){return result;}
  228. QSqlQuery query;
  229. query.prepare("SELECT registration, make, model, variant "
  230. "FROM aircraft "
  231. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  232. "WHERE tails.registration LIKE ?");
  233. searchstring.append("%"); searchstring.prepend("%");
  234. query.addBindValue(searchstring);
  235. query.exec();
  236. while(query.next())
  237. {
  238. result.append(query.value(0).toString() + " (" + query.value(1).toString() + "-" + query.value(2).toString() + "-" + query.value(3).toString() + ")");
  239. }
  240. qDebug() << "newAcftGetString: " << result.length() << result;
  241. return result;
  242. }
  243. static QString newAcftGetId(QString registration)
  244. {
  245. QString result;
  246. QSqlQuery query;
  247. query.prepare("SELECT tail_id "
  248. "FROM tails "
  249. "WHERE registration LIKE ?");
  250. registration.prepend("%"); registration.append("%");
  251. query.addBindValue(registration);
  252. query.exec();
  253. while(query.next())
  254. {
  255. result.append(query.value(0).toString());
  256. }
  257. qDebug() << "newAcftGetId: " << result;
  258. return result;
  259. }
  260. static QVector<QString> RetreiveAircraftTypeFromReg(QString searchstring)
  261. /*
  262. * Searches the tails Database and returns the aircraft Type.
  263. */
  264. {
  265. QSqlQuery query;
  266. query.prepare("SELECT Name, iata, registration, tail_id " //"SELECT Registration, Name, icao, iata "
  267. "FROM aircraft "
  268. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  269. "WHERE tails.registration LIKE ?");
  270. // Returns Registration/Name/icao/iata
  271. searchstring.prepend("%");
  272. searchstring.append("%");
  273. query.addBindValue(searchstring);
  274. query.exec();
  275. QVector<QString> result;
  276. if(query.first())
  277. {
  278. QString acType = query.value(0).toString();
  279. QString iataCode = query.value(1).toString();
  280. QString registration = query.value(2).toString();
  281. QString tail_id = query.value(3).toString();
  282. //QString formatted = acType + " [ " + registration + " | " + iataCode + " ]";
  283. //qDebug() << formatted;
  284. result.append(registration); result.append(acType);
  285. result.append(iataCode); result.append(tail_id);
  286. return result;
  287. }else
  288. {
  289. return result; // empty vector
  290. }
  291. }
  292. static QStringList RetreiveAircraftMake(QString searchstring)
  293. {
  294. QStringList result;
  295. QSqlQuery query;
  296. query.prepare("SELECT make from aircraft WHERE make LIKE ?");
  297. searchstring.prepend("%"); searchstring.append("%");
  298. query.addBindValue(searchstring);
  299. query.exec();
  300. while(query.next())
  301. {
  302. result.append(query.value(0).toString());
  303. }
  304. qDebug() << "db::RetreiveAircraftMake says... Result:" << result;
  305. return result;
  306. }
  307. static QStringList RetreiveAircraftModel(QString make, QString searchstring)
  308. {
  309. QStringList result;
  310. QSqlQuery query;
  311. query.prepare("SELECT model FROM aircraft WHERE make = ? AND model LIKE ?");
  312. query.addBindValue(make);
  313. searchstring.prepend("%"); searchstring.append("%");
  314. query.addBindValue(searchstring);
  315. query.exec();
  316. while(query.next())
  317. {
  318. result.append(query.value(0).toString());
  319. qDebug() << "db::RetreiveAircraftModel says... Result:" << result;
  320. }
  321. return result;
  322. }
  323. static QStringList RetreiveAircraftVariant(QString make, QString model, QString searchstring)
  324. {
  325. QStringList result;
  326. QSqlQuery query;
  327. query.prepare("SELECT variant from aircraft WHERE make = ? AND model = ? AND variant LIKE ?");
  328. query.addBindValue(make);
  329. query.addBindValue(model);
  330. searchstring.prepend("%"); searchstring.append("%");
  331. query.addBindValue(searchstring);
  332. query.exec();
  333. while(query.next())
  334. {
  335. result.append(query.value(0).toString());
  336. qDebug() << "db::RetreiveAircraftVariant says... Result:" << result;
  337. }
  338. return result;
  339. }
  340. static QString RetreiveAircraftIdFromMakeModelVariant(QString make, QString model, QString variant)
  341. {
  342. QString result;
  343. QSqlQuery query;
  344. query.prepare("SELECT aircraft_id FROM aircraft WHERE make = ? AND model = ? AND variant = ?");
  345. query.addBindValue(make);
  346. query.addBindValue(model);
  347. query.addBindValue(variant);
  348. query.exec();
  349. if(query.first())
  350. {
  351. result.append(query.value(0).toString());
  352. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: Aircraft found! ID# " << result;
  353. return result;
  354. }else
  355. {
  356. result = result.left(result.length()-1);
  357. result.append("0");
  358. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: ERROR - no AircraftId found.";
  359. return result;
  360. }
  361. }
  362. static bool CommitTailToDb(QString registration, QString aircraft_id, QString company)
  363. {
  364. QSqlQuery commit;
  365. commit.prepare("INSERT INTO tails (registration, aircraft_id, company) VALUES (?,?,?)");
  366. commit.addBindValue(registration);
  367. commit.addBindValue(aircraft_id);
  368. commit.addBindValue(company);
  369. commit.exec();
  370. QString error = commit.lastError().text();
  371. if(error.length() < 0)
  372. {
  373. qDebug() << "db::CommitAircraftToDb:: SQL error:" << error;
  374. return false;
  375. }else
  376. {
  377. return true;
  378. }
  379. }
  380. /*
  381. * Obsolete Functions
  382. */
  383. /*!
  384. * \brief SelectFlightDate Retreives Flights from the database currently not in use.
  385. * \param doft Date of flight for filtering result set. "ALL" means no filter.
  386. * \return Flight(s) for selected date.
  387. */
  388. static QVector<QString> SelectFlightDate(QString doft)
  389. {
  390. QSqlQuery query;
  391. if (doft == "ALL") // Special Selector
  392. {
  393. query.prepare("SELECT * FROM flights ORDER BY doft DESC, tofb ASC");
  394. qDebug() << "All flights selected";
  395. }else
  396. {
  397. query.prepare("SELECT * FROM flights WHERE doft = ? ORDER BY tofb ASC");
  398. query.addBindValue(doft);
  399. qDebug() << "Searching flights for " << doft;
  400. }
  401. query.exec();
  402. if(query.first());
  403. else
  404. {
  405. qDebug() << ("No flight with this date found");
  406. QVector<QString> flight; //return empty
  407. return flight;
  408. }
  409. query.previous();// To go back to index 0
  410. query.last(); // this can be very slow, used to determine query size since .size is not supported by sqlite
  411. int numRows = query.at() + 1; // Number of rows (flights) in the query
  412. query.first();
  413. query.previous();// Go back to index 0
  414. QVector<QString> flight(numRows * 9); // Every flight has 9 fields in the database
  415. int index = 0; // counter for output vector
  416. while (query.next()) {
  417. QString id = query.value(0).toString();
  418. QString doft = query.value(1).toString();
  419. QString dept = query.value(2).toString();
  420. QString tofb = calc::minutes_to_string((query.value(3).toString()));
  421. QString dest = query.value(4).toString();
  422. QString tonb = calc::minutes_to_string((query.value(5).toString()));
  423. QString tblk = calc::minutes_to_string((query.value(6).toString()));
  424. QString pic = dbPilots::retreivePilotNameFromID(query.value(7).toString());
  425. QString acft = db::RetreiveRegistration(query.value(8).toString());
  426. //qDebug() << id << doft << dept << tofb << dest << tonb << tblk << pic << acft << endl;
  427. flight[index] = id;
  428. ++index;
  429. flight[index] = doft;
  430. ++index;
  431. flight[index] = dept;
  432. ++index;
  433. flight[index] = tofb;
  434. ++index;
  435. flight[index] = dest;
  436. ++index;
  437. flight[index] = tonb;
  438. ++index;
  439. flight[index] = tblk;
  440. ++index;
  441. flight[index] = pic;
  442. ++index;
  443. flight[index] = acft;
  444. ++index;
  445. }
  446. return flight;
  447. }
  448. };