dbman.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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 <chrono>
  26. #include <QRandomGenerator>
  27. #include <QStandardPaths>
  28. class db
  29. {
  30. public:
  31. static void connect()
  32. {
  33. const QString DRIVER("QSQLITE");
  34. if(QSqlDatabase::isDriverAvailable(DRIVER))
  35. {
  36. QSqlDatabase db = QSqlDatabase::addDatabase(DRIVER);
  37. //QString pathtodb = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
  38. //db.setDatabaseName(pathtodb+"/logbook.db");
  39. //qDebug() << "Database: " << pathtodb+"/logbook.db";
  40. db.setDatabaseName("logbook.db");
  41. if(!db.open())
  42. qWarning() << "MainWindow::DatabaseConnect - ERROR: " << db.lastError().text();
  43. }
  44. else
  45. qWarning() << "MainWindow::DatabaseConnect - ERROR: no driver " << DRIVER << " available";
  46. }
  47. static void initexample()
  48. {
  49. QSqlQuery query("CREATE TABLE flights (id INTEGER PRIMARY KEY, date NUMERIC)");
  50. if(!query.isActive())
  51. qWarning() << "MainWindow::DatabaseInit - ERROR: " << query.lastError().text();
  52. }
  53. static void queryexamplenamedbinding()
  54. {
  55. QSqlQuery query;
  56. //query.prepare("SELECT * FROM people");
  57. //query.prepare("SELECT * FROM people WHERE name LIKE 'Linus' OR id = :id");
  58. query.prepare("SELECT * from people WHERE name LIKE :name");
  59. query.bindValue(":name", "%Linus%");
  60. query.bindValue(":id",2);
  61. query.exec();
  62. /*
  63. * QSqlQuery provides access to the result set one record at a time. After the call to exec(),
  64. * QSqlQuery's internal pointer is located one position before the first record.
  65. * We must call QSqlQuery::next() once to advance to the first record, then next() again
  66. * repeatedly to access the other records, until it returns false. Here's a typical loop that
  67. * iterates over all the records in order:
  68. * After a SELECT query is executed we have to browse the records (result rows) returned to access
  69. * the data. In this case we try to retrieve the first record calling the function first which
  70. * returns true when the query has been successful and false otherwise.
  71. */
  72. if(query.first());
  73. else
  74. qDebug() << ("No entry found");
  75. query.previous();//To go back to index 0
  76. while (query.next()) {
  77. QString name = query.value(1).toString();
  78. int id = query.value(0).toInt();
  79. qDebug() << name << id;
  80. }
  81. /*
  82. *The QSqlQuery::value() function returns the value of a field in the current record. Fields are
  83. * specified as zero-based indexes. QSqlQuery::value() returns a QVariant, a type that can hold
  84. * various C++ and core Qt data types such as int, QString, and QByteArray. The different database
  85. * types are automatically mapped into the closest Qt equivalent. In the code snippet, we call
  86. * QVariant::toString() and QVariant::toInt() to convert variants to QString and int.
  87. */
  88. }
  89. /*
  90. * Flights Database Related Functions
  91. */
  92. /*!
  93. * \brief SelectFlightById Retreives a single flight from the database.
  94. * \param flight_id Primary Key of flights database
  95. * \return Flight details of selected flight.
  96. */
  97. static QVector<QString> SelectFlightById(QString flight_id)
  98. {
  99. QSqlQuery query;
  100. query.prepare("SELECT * FROM flights WHERE id = ?");
  101. query.addBindValue(flight_id);
  102. query.exec();
  103. if(query.first());
  104. else
  105. {
  106. qDebug() << "db::SelectFlightById - No Flight with this ID found";
  107. QVector<QString> flight; //return empty
  108. return flight;
  109. }
  110. QVector<QString> flight;
  111. flight.append(query.value(0).toString());
  112. flight.append(query.value(1).toString());
  113. flight.append(query.value(2).toString());
  114. flight.append(query.value(3).toString());
  115. flight.append(query.value(4).toString());
  116. flight.append(query.value(5).toString());
  117. flight.append(query.value(6).toString());
  118. flight.append(query.value(7).toString());
  119. flight.append(query.value(8).toString());
  120. qDebug() << "db::SelectFlightById - retreived flight: " << flight;
  121. return flight;
  122. }
  123. /*!
  124. * \brief CreateFlightVectorFromInput Converts input from NewFlight Window into database format
  125. * \param doft Date of flight
  126. * \param dept Place of Departure
  127. * \param tofb Time Off Blocks (UTC)
  128. * \param dest Place of Destination
  129. * \param tonb Time On Blocks (UTC)
  130. * \param tblk Total Block Time
  131. * \param pic Pilot in command
  132. * \param acft Aircraft
  133. * \return Vector of values ready for committing
  134. */
  135. static QVector<QString> CreateFlightVectorFromInput(QString doft, QString dept, QTime tofb, QString dest, QTime tonb, QTime tblk, QString pic, QString acft)
  136. {
  137. QVector<QString> flight;
  138. flight.insert(0, ""); // ID, created as primary key during commit
  139. flight.insert(1, doft);
  140. flight.insert(2, dept);
  141. flight.insert(3, QString::number(calc::time_to_minutes(tofb)));
  142. flight.insert(4, dest);
  143. flight.insert(5, QString::number(calc::time_to_minutes(tonb)));
  144. flight.insert(6, QString::number(calc::time_to_minutes(tblk)));
  145. flight.insert(7, pic); // lookup and matching tbd
  146. flight.insert(8, acft);// lookup and matching tbd
  147. //qDebug() << flight;
  148. return flight;
  149. }
  150. /*!
  151. * \brief CommitFlight Inserts prepared flight vector into database. Also creates
  152. * a corresponding entry in the extras database to ensure matching IDs.
  153. * \param flight a Vector of values in database format
  154. */
  155. static void CommitFlight(QVector<QString> flight)// flight vector shall always have length 9
  156. {
  157. QSqlQuery query;
  158. query.prepare("INSERT INTO flights (doft, dept, tofb, dest, tonb, tblk, pic, acft) "
  159. "VALUES (:doft, :dept, :tofb, :dest, :tonb, :tblk, :pic, :acft)");
  160. //flight[0] is primary key, not required for commit
  161. query.bindValue(":doft", flight[1]); //string
  162. query.bindValue(":dept", flight[2]);
  163. query.bindValue(":tofb", flight[3].toInt()); //int
  164. query.bindValue(":dest", flight[4]);
  165. query.bindValue(":tonb", flight[5].toInt());
  166. query.bindValue(":tblk", flight[6].toInt());
  167. query.bindValue(":pic", flight[7].toInt());
  168. query.bindValue(":acft", flight[8].toInt());
  169. query.exec();
  170. qDebug() << "Error message for commiting flight: " << query.lastError().text();
  171. QSqlQuery query2;
  172. query2.prepare("INSERT INTO extras DEFAULT VALUES");
  173. query2.exec();
  174. qDebug() << "Creating extras entry" << query2.lastError().text();
  175. }
  176. /*!
  177. * \brief CommitToScratchpad Commits the inputs of the NewFlight window to a scratchpad
  178. * to make them available for restoring entries when the input fields are being reloaded.
  179. * \param flight The input data, which was not accepted for commiting to the flights table.
  180. */
  181. static void CommitToScratchpad(QVector<QString> flight)// to store input mask
  182. {
  183. //qDebug() << "Saving invalid flight to scratchpad";
  184. QSqlQuery query;
  185. query.prepare("INSERT INTO scratchpad (doft, dept, tofb, dest, tonb, tblk, pic, acft) "
  186. "VALUES (:doft, :dept, :tofb, :dest, :tonb, :tblk, :pic, :acft)");
  187. //flight[0] is primary key, not required for commit
  188. query.bindValue(":doft", flight[1]); //string
  189. query.bindValue(":dept", flight[2]);
  190. query.bindValue(":tofb", flight[3].toInt()); //int
  191. query.bindValue(":dest", flight[4]);
  192. query.bindValue(":tonb", flight[5].toInt());
  193. query.bindValue(":tblk", flight[6].toInt());
  194. query.bindValue(":pic", flight[7].toInt());
  195. query.bindValue(":acft", flight[8].toInt());
  196. query.exec();
  197. qDebug() << query.lastError().text();
  198. }
  199. /*!
  200. * \brief CheckScratchpad Verifies if the scratchpad contains data
  201. * \return true if scratchpad contains data
  202. */
  203. static bool CheckScratchpad() // see if scratchpad is empty
  204. {
  205. //qDebug() << "Checking if scratchpad contains data";
  206. QSqlQuery query;
  207. query.prepare("SELECT * FROM scratchpad");
  208. query.exec();
  209. if(query.first())
  210. {
  211. //qDebug() << "Scratchpad contains data";
  212. return 1;
  213. }
  214. else
  215. {
  216. //qDebug() << ("Scratchpad contains NO data");
  217. return 0;
  218. }
  219. }
  220. /*!
  221. * \brief ClearScratchpad Deletes data contained in the scratchpad
  222. */
  223. static void ClearScratchpad()
  224. {
  225. qDebug() << "Deleting scratchpad";
  226. QSqlQuery query;
  227. query.prepare("DELETE FROM scratchpad;");
  228. query.exec();
  229. }
  230. /*!
  231. * \brief RetreiveScratchpad Selects data from scratchpad
  232. * \return Vector of data contained in scratchpad
  233. */
  234. static QVector<QString> RetreiveScratchpad()
  235. {
  236. //qDebug() << "Retreiving invalid flight from scratchpad";
  237. QSqlQuery query;
  238. query.prepare("SELECT * FROM scratchpad");
  239. query.exec();
  240. if(query.first());
  241. else
  242. {
  243. //qDebug() << ("scratchpad empty");
  244. QVector<QString> flight; //return empty
  245. return flight;
  246. }
  247. query.previous();
  248. QVector<QString> flight;
  249. while (query.next()) {
  250. flight.append(query.value(0).toString());
  251. flight.append(query.value(1).toString());
  252. flight.append(query.value(2).toString());
  253. flight.append(calc::minutes_to_string((query.value(3).toString())));
  254. flight.append(query.value(4).toString());
  255. flight.append(calc::minutes_to_string((query.value(5).toString())));
  256. flight.append(calc::minutes_to_string((query.value(6).toString())));
  257. flight.append(query.value(7).toString());
  258. flight.append(query.value(8).toString());
  259. }
  260. ClearScratchpad();
  261. return flight;
  262. }
  263. /*!
  264. * \brief deleteFlightById Deletes a Flight from the database.
  265. * Entries in the basic flights table as well as in the extras table are deleted.
  266. * \param flight_id The primary key of the entry in the database
  267. * \return True if no errors, otherwise false
  268. */
  269. static bool deleteFlightById(QString flight_id)
  270. {
  271. QSqlQuery query;
  272. query.prepare("DELETE FROM flights WHERE id = ?");
  273. query.addBindValue(flight_id);
  274. query.exec();
  275. QString error = query.lastError().text();
  276. QSqlQuery query2;
  277. query2.prepare("DELETE FROM extras WHERE extras_id = ?");
  278. query2.addBindValue(flight_id);
  279. query2.exec();
  280. QString error2 = query2.lastError().text();
  281. qDebug() << "db::deleteFlightById: Removing flight with ID#: " << flight_id;
  282. if(error.length() > 0 || error2.length() > 0)
  283. {
  284. qWarning() << "db::deleteFlightsById: Errors have occured: " << error << " " << error2;
  285. return false;
  286. }else
  287. {
  288. return true;
  289. }
  290. }
  291. /*
  292. * Pilots Database Related Functions
  293. */
  294. /*!
  295. * \brief RetreivePilotNameFromID Looks up pilot ID in database
  296. * \param pilotID pilot_id in database
  297. * \return Pilot Name
  298. */
  299. static QString RetreivePilotNameFromID(QString pilotID)
  300. {
  301. QString pilotName("");
  302. if (pilotID == "1")
  303. {
  304. pilotName = "self";
  305. return pilotName;
  306. }
  307. QSqlQuery query;
  308. query.prepare("SELECT piclastname, picfirstname, alias FROM pilots WHERE pilot_id == ?");
  309. query.addBindValue(pilotID.toInt());
  310. query.exec();
  311. while (query.next()) {
  312. pilotName.append(query.value(0).toString());
  313. pilotName.append(", ");
  314. pilotName.append(query.value(1).toString());//.left(1));
  315. }
  316. if(pilotName.length() == 0)
  317. {
  318. qDebug() << ("No Pilot with this ID found");
  319. }
  320. return pilotName;
  321. }
  322. static QString RetreivePilotIdFromString(QString lastname, QString firstname)
  323. {
  324. QSqlQuery query;
  325. query.prepare("SELECT pilot_id from pilots "
  326. "WHERE piclastname = ? AND picfirstname LIKE ?");
  327. query.addBindValue(lastname);
  328. firstname.prepend("%"); firstname.append("%");
  329. query.addBindValue(firstname);
  330. query.exec();
  331. QString id;
  332. if(query.first()){id.append(query.value(0).toString());}
  333. return id;
  334. }
  335. static QStringList RetreivePilotNameFromString(QString searchstring)
  336. /* Searches the pilot Name in the Database and returns the name as a vector of results
  337. * unless the pilot in command is the logbook owner.
  338. */
  339. {
  340. QString firstname = searchstring; //To Do: Two control paths, one for single word, query as before with only searchstring
  341. QString lastname = searchstring; // second control path with comma, lastname like AND firstname like
  342. if(searchstring.contains(QLatin1Char(',')))
  343. {
  344. QStringList namelist = searchstring.split(QLatin1Char(','));
  345. QString lastname = namelist[0].trimmed();
  346. lastname = lastname.toLower();
  347. lastname[0] = lastname[0].toUpper();
  348. lastname.prepend("%"), lastname.append("%");
  349. QString firstname = namelist[1].trimmed();
  350. if(firstname.length()>1)
  351. {
  352. firstname = firstname.toLower();
  353. firstname[0] = firstname[0].toUpper();
  354. firstname.prepend("%"), firstname.append("%");
  355. }
  356. qDebug() << "db::RetreivePilotNameFromString: first last after comma";
  357. qDebug() << firstname << lastname;
  358. }
  359. QSqlQuery query;
  360. query.prepare("SELECT piclastname, picfirstname, alias "
  361. "FROM pilots WHERE "
  362. "picfirstname LIKE ? OR piclastname LIKE ? OR alias LIKE ?");
  363. searchstring.prepend("%");
  364. searchstring.append("%");
  365. query.addBindValue(firstname);
  366. query.addBindValue(lastname);
  367. query.addBindValue(searchstring);
  368. query.exec();
  369. QStringList result;
  370. while (query.next()) {
  371. QString piclastname = query.value(0).toString();
  372. QString picfirstname = query.value(1).toString();
  373. QString alias = query.value(2).toString();
  374. QString name = piclastname + ", " + picfirstname;
  375. result.append(name);
  376. }
  377. qDebug() << "db::RetreivePilotNameFromString Result: " << result;
  378. //qDebug() << query.lastError();
  379. if(result.size() == 0)
  380. {
  381. qDebug() << ("db::RetreivePilotNameFromString: No Pilot found");
  382. return result;
  383. }
  384. return result;
  385. }
  386. /*!
  387. * \brief newPicGetString This function is returning a QStringList for the QCompleter in the NewFlight::newPic line edit
  388. * A regular expression limits the input possibilities to only characters,
  389. * followed by an optional ',' and 1 whitespace, e.g.:
  390. * Miller, Jim ->valid / Miller, Jim -> invalid / Miller,, Jim -> invalid
  391. * Miller Jim -> valid / Miller Jim ->invalid
  392. * Jim Miller-> valid
  393. * \param searchstring
  394. * \return
  395. */
  396. static QStringList newPicGetString(QString searchstring)
  397. {
  398. QStringList result;
  399. QStringList searchlist;
  400. if(searchstring == "self")
  401. {
  402. result.append("self");
  403. qDebug() << "Pilot is self";
  404. return result;
  405. }
  406. //Fall 1) Nachname, Vorname
  407. if(searchstring.contains(QLatin1Char(',')))
  408. {
  409. QStringList namelist = searchstring.split(QLatin1Char(','));
  410. QString name1 = namelist[0].trimmed();
  411. name1 = name1.toLower();
  412. name1[0] = name1[0].toUpper();
  413. searchlist.append(name1);
  414. if(namelist[1].length() > 1)
  415. {
  416. QString name2 = namelist[1].trimmed();
  417. name2 = name2.toLower();
  418. name2[0] = name2[0].toUpper();
  419. searchlist.append(name2);
  420. }
  421. }
  422. //Fall 2) Vorname Nachname
  423. if(searchstring.contains(" ") && !searchstring.contains(QLatin1Char(',')))
  424. {
  425. QStringList namelist = searchstring.split(" ");
  426. QString name1 = namelist[0].trimmed();
  427. name1 = name1.toLower();
  428. name1[0] = name1[0].toUpper();
  429. searchlist.append(name1);
  430. if(namelist[1].length() > 1) //To avoid index out of range if the searchstring is one word followed by only one whitespace
  431. {
  432. QString name2 = namelist[1].trimmed();
  433. name2 = name2.toLower();
  434. name2[0] = name2[0].toUpper();
  435. searchlist.append(name2);
  436. }
  437. }
  438. //Fall 3) Name
  439. if(!searchstring.contains(" ") && !searchstring.contains(QLatin1Char(',')))
  440. {
  441. QString name1 = searchstring.toLower();
  442. name1[0] = name1[0].toUpper();
  443. searchlist.append(name1);
  444. }
  445. if(searchlist.length() == 1)
  446. {
  447. QSqlQuery query;
  448. query.prepare("SELECT piclastname, picfirstname FROM pilots "
  449. "WHERE piclastname LIKE ?");
  450. query.addBindValue(searchlist[0] + '%');
  451. query.exec();
  452. while(query.next())
  453. {
  454. result.append(query.value(0).toString() + ", " + query.value(1).toString());
  455. }
  456. QSqlQuery query2;
  457. query2.prepare("SELECT piclastname, picfirstname FROM pilots "
  458. "WHERE picfirstname LIKE ?");
  459. query2.addBindValue(searchlist[0] + '%');
  460. query2.exec();
  461. while(query2.next())
  462. {
  463. result.append(query2.value(0).toString() + ", " + query2.value(1).toString());
  464. }
  465. }else
  466. {
  467. QSqlQuery query;
  468. query.prepare("SELECT piclastname, picfirstname FROM pilots "
  469. "WHERE piclastname LIKE ? AND picfirstname LIKE ?");
  470. query.addBindValue(searchlist[0] + '%');
  471. query.addBindValue(searchlist[1] + '%');
  472. query.exec();
  473. while(query.next())
  474. {
  475. result.append(query.value(0).toString() + ", " + query.value(1).toString());
  476. }
  477. QSqlQuery query2;
  478. query2.prepare("SELECT piclastname, picfirstname FROM pilots "
  479. "WHERE picfirstname LIKE ? AND piclastname LIKE ?");
  480. query2.addBindValue(searchlist[0] + '%');
  481. query2.addBindValue(searchlist[1] + '%');
  482. query2.exec();
  483. while(query2.next())
  484. {
  485. result.append(query2.value(0).toString() + ", " + query2.value(1).toString());
  486. }
  487. }
  488. qDebug() << "db::newPic Result" << result.length() << result;
  489. if(result.length() == 0)
  490. {
  491. //try first name search
  492. qDebug() << "No Pilot with this last name found. trying first name search.";
  493. return result;
  494. }else
  495. {
  496. return result;
  497. }
  498. }
  499. static QString newPicGetId(QString name)
  500. {
  501. QString result;
  502. QStringList nameparts = name.split(QLatin1Char(','));
  503. QString lastname = nameparts[0].trimmed();
  504. lastname = lastname.toLower(); lastname[0] = lastname[0].toUpper();
  505. QString firstname = nameparts[1].trimmed();
  506. firstname = firstname.toLower(); firstname[0] = firstname[0].toUpper();
  507. firstname.prepend("%"); firstname.append("%");
  508. QSqlQuery query;
  509. query.prepare("SELECT pilot_id FROM pilots "
  510. "WHERE piclastname = ? AND picfirstname LIKE ?");
  511. query.addBindValue(lastname);
  512. query.addBindValue(firstname);
  513. query.exec();
  514. while (query.next())
  515. {
  516. result.append(query.value(0).toString());
  517. }
  518. qDebug() << "newPicGetId: result = " << result;
  519. return result;
  520. }
  521. /*
  522. * Airport Database Related Functions
  523. */
  524. /*!
  525. * \brief RetreiveAirportNameFromIcaoOrIata Looks up Airport Name
  526. * \param identifier can be ICAO or IATA airport codes.
  527. * \return The name of the airport associated with the above code
  528. */
  529. static QString RetreiveAirportNameFromIcaoOrIata(QString identifier)
  530. {
  531. QString result = "";
  532. QSqlQuery query;
  533. query.prepare("SELECT name "
  534. "FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  535. identifier.append("%");
  536. identifier.prepend("%");
  537. query.addBindValue(identifier);
  538. query.addBindValue(identifier);
  539. query.exec();
  540. if(query.first())
  541. {
  542. result.append(query.value(0).toString());
  543. return result;
  544. }else
  545. {
  546. result = result.left(result.length()-1);
  547. result.append("No matching airport found.");
  548. return result;
  549. }
  550. }
  551. static QString RetreiveAirportIdFromIcao(QString identifier)
  552. {
  553. QString result;
  554. QSqlQuery query;
  555. query.prepare("SELECT airport_id FROM airports WHERE icao = ?");
  556. query.addBindValue(identifier);
  557. query.exec();
  558. while(query.next())
  559. {
  560. result.append(query.value(0).toString());
  561. //qDebug() << "db::RetreiveAirportIdFromIcao says Airport found! #" << result;
  562. }
  563. return result;
  564. }
  565. static QStringList CompleteIcaoOrIata(QString icaoStub)
  566. {
  567. QStringList result;
  568. QSqlQuery query;
  569. query.prepare("SELECT icao FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  570. icaoStub.prepend("%"); icaoStub.append("%");
  571. query.addBindValue(icaoStub);
  572. query.addBindValue(icaoStub);
  573. query.exec();
  574. while(query.next())
  575. {
  576. result.append(query.value(0).toString());
  577. qDebug() << "db::CompleteIcaoOrIata says... Result:" << result;
  578. }
  579. return result;
  580. }
  581. /*!
  582. * \brief CheckICAOValid Verifies if a user input airport exists in the database
  583. * \param identifier can be ICAO or IATA airport codes.
  584. * \return bool if airport is in database.
  585. */
  586. static bool CheckICAOValid(QString identifier)
  587. {
  588. if(identifier.length() == 4)
  589. {
  590. QString check = RetreiveAirportIdFromIcao(identifier);
  591. if(check.length() > 0)
  592. {
  593. //qDebug() << "db::CheckICAOValid says: Check passed!";
  594. return 1;
  595. }else
  596. {
  597. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Lookup unsuccessful";
  598. return 0;
  599. }
  600. }else
  601. {
  602. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Empty String NOT epico!";
  603. return 0;
  604. }
  605. }
  606. /*!
  607. * \brief retreiveIcaoCoordinates Looks up coordinates (lat,long) for a given airport
  608. * \param icao 4-letter code for the airport
  609. * \return {lat,lon} in decimal degrees
  610. */
  611. static QVector<double> retreiveIcaoCoordinates(QString icao)
  612. {
  613. QSqlQuery query;
  614. query.prepare("SELECT lat, long "
  615. "FROM airports "
  616. "WHERE icao = ?");
  617. query.addBindValue(icao);
  618. query.exec();
  619. QVector<double> result;
  620. while(query.next()) {
  621. result.append(query.value(0).toDouble());
  622. result.append(query.value(1).toDouble());
  623. }
  624. return result;
  625. }
  626. /*
  627. * Aircraft Database Related Functions
  628. */
  629. /*!
  630. * \brief RetreiveRegistration Looks up tail_id from Database
  631. * \param tail_ID Primary Key of tails database
  632. * \return Registration
  633. */
  634. static QString RetreiveRegistration(QString tail_ID)
  635. {
  636. QString acftRegistration("");
  637. QSqlQuery query;
  638. query.prepare("SELECT registration FROM tails WHERE tail_id == ?");
  639. query.addBindValue(tail_ID.toInt());
  640. query.exec();
  641. if(query.first());
  642. else
  643. qDebug() << ("No Aircraft with this ID found");
  644. query.previous();//To go back to index 0
  645. while (query.next()) {
  646. acftRegistration.append(query.value(0).toString());
  647. }
  648. return acftRegistration;
  649. }
  650. /*!
  651. * \brief newAcftGetString Looks up an aircraft Registration in the database
  652. * \param searchstring
  653. * \return Registration, make, model and variant
  654. */
  655. static QStringList newAcftGetString(QString searchstring)
  656. {
  657. QStringList result;
  658. if(searchstring.length()<2){return result;}
  659. QSqlQuery query;
  660. query.prepare("SELECT registration, make, model, variant "
  661. "FROM aircraft "
  662. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  663. "WHERE tails.registration LIKE ?");
  664. searchstring.append("%"); searchstring.prepend("%");
  665. query.addBindValue(searchstring);
  666. query.exec();
  667. while(query.next())
  668. {
  669. result.append(query.value(0).toString() + " (" + query.value(1).toString() + "-" + query.value(2).toString() + "-" + query.value(3).toString() + ")");
  670. }
  671. qDebug() << "newAcftGetString: " << result.length() << result;
  672. return result;
  673. }
  674. static QString newAcftGetId(QString registration)
  675. {
  676. QString result;
  677. QSqlQuery query;
  678. query.prepare("SELECT tail_id "
  679. "FROM tails "
  680. "WHERE registration LIKE ?");
  681. registration.prepend("%"); registration.append("%");
  682. query.addBindValue(registration);
  683. query.exec();
  684. while(query.next())
  685. {
  686. result.append(query.value(0).toString());
  687. }
  688. qDebug() << "newAcftGetId: " << result;
  689. return result;
  690. }
  691. static QVector<QString> RetreiveAircraftTypeFromReg(QString searchstring)
  692. /*
  693. * Searches the tails Database and returns the aircraft Type.
  694. */
  695. {
  696. QSqlQuery query;
  697. query.prepare("SELECT Name, iata, registration, tail_id " //"SELECT Registration, Name, icao, iata "
  698. "FROM aircraft "
  699. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  700. "WHERE tails.registration LIKE ?");
  701. // Returns Registration/Name/icao/iata
  702. searchstring.prepend("%");
  703. searchstring.append("%");
  704. query.addBindValue(searchstring);
  705. query.exec();
  706. QVector<QString> result;
  707. if(query.first())
  708. {
  709. QString acType = query.value(0).toString();
  710. QString iataCode = query.value(1).toString();
  711. QString registration = query.value(2).toString();
  712. QString tail_id = query.value(3).toString();
  713. //QString formatted = acType + " [ " + registration + " | " + iataCode + " ]";
  714. //qDebug() << formatted;
  715. result.append(registration); result.append(acType);
  716. result.append(iataCode); result.append(tail_id);
  717. return result;
  718. }else
  719. {
  720. return result; // empty vector
  721. }
  722. }
  723. static QStringList RetreiveAircraftMake(QString searchstring)
  724. {
  725. QStringList result;
  726. QSqlQuery query;
  727. query.prepare("SELECT make from aircraft WHERE make LIKE ?");
  728. searchstring.prepend("%"); searchstring.append("%");
  729. query.addBindValue(searchstring);
  730. query.exec();
  731. while(query.next())
  732. {
  733. result.append(query.value(0).toString());
  734. }
  735. qDebug() << "db::RetreiveAircraftMake says... Result:" << result;
  736. return result;
  737. }
  738. static QStringList RetreiveAircraftModel(QString make, QString searchstring)
  739. {
  740. QStringList result;
  741. QSqlQuery query;
  742. query.prepare("SELECT model FROM aircraft WHERE make = ? AND model LIKE ?");
  743. query.addBindValue(make);
  744. searchstring.prepend("%"); searchstring.append("%");
  745. query.addBindValue(searchstring);
  746. query.exec();
  747. while(query.next())
  748. {
  749. result.append(query.value(0).toString());
  750. qDebug() << "db::RetreiveAircraftModel says... Result:" << result;
  751. }
  752. return result;
  753. }
  754. static QStringList RetreiveAircraftVariant(QString make, QString model, QString searchstring)
  755. {
  756. QStringList result;
  757. QSqlQuery query;
  758. query.prepare("SELECT variant from aircraft WHERE make = ? AND model = ? AND variant LIKE ?");
  759. query.addBindValue(make);
  760. query.addBindValue(model);
  761. searchstring.prepend("%"); searchstring.append("%");
  762. query.addBindValue(searchstring);
  763. query.exec();
  764. while(query.next())
  765. {
  766. result.append(query.value(0).toString());
  767. qDebug() << "db::RetreiveAircraftVariant says... Result:" << result;
  768. }
  769. return result;
  770. }
  771. static QString RetreiveAircraftIdFromMakeModelVariant(QString make, QString model, QString variant)
  772. {
  773. QString result;
  774. QSqlQuery query;
  775. query.prepare("SELECT aircraft_id FROM aircraft WHERE make = ? AND model = ? AND variant = ?");
  776. query.addBindValue(make);
  777. query.addBindValue(model);
  778. query.addBindValue(variant);
  779. query.exec();
  780. if(query.first())
  781. {
  782. result.append(query.value(0).toString());
  783. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: Aircraft found! ID# " << result;
  784. return result;
  785. }else
  786. {
  787. result = result.left(result.length()-1);
  788. result.append("0");
  789. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: ERROR - no AircraftId found.";
  790. return result;
  791. }
  792. }
  793. static bool CommitTailToDb(QString registration, QString aircraft_id, QString company)
  794. {
  795. QSqlQuery commit;
  796. commit.prepare("INSERT INTO tails (registration, aircraft_id, company) VALUES (?,?,?)");
  797. commit.addBindValue(registration);
  798. commit.addBindValue(aircraft_id);
  799. commit.addBindValue(company);
  800. commit.exec();
  801. QString error = commit.lastError().text();
  802. if(error.length() < 0)
  803. {
  804. qDebug() << "db::CommitAircraftToDb:: SQL error:" << error;
  805. return false;
  806. }else
  807. {
  808. return true;
  809. }
  810. }
  811. /*
  812. * Settings Database Related Functions
  813. */
  814. /*!
  815. * \brief retreiveSetting Looks up a setting in the database and returns its value
  816. * \param setting_id
  817. * \return setting value
  818. */
  819. static QString retreiveSetting(QString setting_id)
  820. {
  821. QSqlQuery query;
  822. query.prepare("SELECT setting FROM settings WHERE setting_id = ?");
  823. query.addBindValue(setting_id);
  824. query.exec();
  825. QString setting = "-1";
  826. while(query.next()){
  827. setting = query.value(0).toString();
  828. }
  829. return setting;
  830. }
  831. /*!
  832. * \brief retreiveSettingInfo Looks up a setting in the database and returns its value and description
  833. * \param setting_id
  834. * \return {setting_id, setting, description}
  835. */
  836. static QVector<QString> retreiveSettingInfo(QString setting_id)
  837. {
  838. QSqlQuery query;
  839. query.prepare("SELECT * FROM settings WHERE setting_id = ?");
  840. query.addBindValue(setting_id);
  841. query.exec();
  842. QVector<QString> setting;
  843. while(query.next()){
  844. setting.append(query.value(0).toString());
  845. setting.append(query.value(1).toString());
  846. setting.append(query.value(2).toString());
  847. }
  848. return setting;
  849. }
  850. /*!
  851. * \brief storesetting Updates a stored setting in the database
  852. * \param setting_id
  853. * \param setting_value
  854. */
  855. static void storesetting(int setting_id, QString setting_value)
  856. {
  857. QSqlQuery query;
  858. query.prepare("UPDATE settings "
  859. "SET setting = ? "
  860. "WHERE setting_id = ?");
  861. query.addBindValue(setting_value);
  862. query.addBindValue(setting_id);
  863. query.exec();
  864. }
  865. /*
  866. * Obsolete Functions
  867. */
  868. /*!
  869. * \brief SelectFlightDate Retreives Flights from the database currently not in use.
  870. * \param doft Date of flight for filtering result set. "ALL" means no filter.
  871. * \return Flight(s) for selected date.
  872. */
  873. static QVector<QString> SelectFlightDate(QString doft)
  874. {
  875. QSqlQuery query;
  876. if (doft == "ALL") // Special Selector
  877. {
  878. query.prepare("SELECT * FROM flights ORDER BY doft DESC, tofb ASC");
  879. qDebug() << "All flights selected";
  880. }else
  881. {
  882. query.prepare("SELECT * FROM flights WHERE doft = ? ORDER BY tofb ASC");
  883. query.addBindValue(doft);
  884. qDebug() << "Searching flights for " << doft;
  885. }
  886. query.exec();
  887. if(query.first());
  888. else
  889. {
  890. qDebug() << ("No flight with this date found");
  891. QVector<QString> flight; //return empty
  892. return flight;
  893. }
  894. query.previous();// To go back to index 0
  895. query.last(); // this can be very slow, used to determine query size since .size is not supported by sqlite
  896. int numRows = query.at() + 1; // Number of rows (flights) in the query
  897. query.first();
  898. query.previous();// Go back to index 0
  899. QVector<QString> flight(numRows * 9); // Every flight has 9 fields in the database
  900. int index = 0; // counter for output vector
  901. while (query.next()) {
  902. QString id = query.value(0).toString();
  903. QString doft = query.value(1).toString();
  904. QString dept = query.value(2).toString();
  905. QString tofb = calc::minutes_to_string((query.value(3).toString()));
  906. QString dest = query.value(4).toString();
  907. QString tonb = calc::minutes_to_string((query.value(5).toString()));
  908. QString tblk = calc::minutes_to_string((query.value(6).toString()));
  909. QString pic = db::RetreivePilotNameFromID(query.value(7).toString());
  910. QString acft = db::RetreiveRegistration(query.value(8).toString());
  911. //qDebug() << id << doft << dept << tofb << dest << tonb << tblk << pic << acft << endl;
  912. flight[index] = id;
  913. ++index;
  914. flight[index] = doft;
  915. ++index;
  916. flight[index] = dept;
  917. ++index;
  918. flight[index] = tofb;
  919. ++index;
  920. flight[index] = dest;
  921. ++index;
  922. flight[index] = tonb;
  923. ++index;
  924. flight[index] = tblk;
  925. ++index;
  926. flight[index] = pic;
  927. ++index;
  928. flight[index] = acft;
  929. ++index;
  930. }
  931. return flight;
  932. }
  933. };