dbman.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. static bool DeleteFlightById(QString flight_id)
  264. {
  265. QSqlQuery query;
  266. query.prepare("DELETE FROM flights WHERE id = ?");
  267. query.addBindValue(flight_id);
  268. query.exec();
  269. QString error = query.lastError().text();
  270. qDebug() << "db::DeleteFlightById: Removing flight with ID#: " << flight_id << "Query Error: " << error;
  271. if(error.length() > 0)
  272. {
  273. return false;
  274. }else
  275. {
  276. return true;
  277. }
  278. }
  279. /*
  280. * Pilots Database Related Functions
  281. */
  282. /*!
  283. * \brief RetreivePilotNameFromID Looks up pilot ID in database
  284. * \param pilotID pilot_id in database
  285. * \return Pilot Name
  286. */
  287. static QString RetreivePilotNameFromID(QString pilotID)
  288. {
  289. QString pilotName("");
  290. if (pilotID == "1")
  291. {
  292. pilotName = "self";
  293. return pilotName;
  294. }
  295. QSqlQuery query;
  296. query.prepare("SELECT piclastname, picfirstname, alias FROM pilots WHERE pilot_id == ?");
  297. query.addBindValue(pilotID.toInt());
  298. query.exec();
  299. while (query.next()) {
  300. pilotName.append(query.value(0).toString());
  301. pilotName.append(", ");
  302. pilotName.append(query.value(1).toString());//.left(1));
  303. }
  304. if(pilotName.length() == 0)
  305. {
  306. qDebug() << ("No Pilot with this ID found");
  307. }
  308. return pilotName;
  309. }
  310. static QString RetreivePilotIdFromString(QString lastname, QString firstname)
  311. {
  312. QSqlQuery query;
  313. query.prepare("SELECT pilot_id from pilots "
  314. "WHERE piclastname = ? AND picfirstname LIKE ?");
  315. query.addBindValue(lastname);
  316. firstname.prepend("%"); firstname.append("%");
  317. query.addBindValue(firstname);
  318. query.exec();
  319. QString id;
  320. if(query.first()){id.append(query.value(0).toString());}
  321. return id;
  322. }
  323. static QStringList RetreivePilotNameFromString(QString searchstring)
  324. /* Searches the pilot Name in the Database and returns the name as a vector of results
  325. * unless the pilot in command is the logbook owner.
  326. */
  327. {
  328. QString firstname = searchstring; //To Do: Two control paths, one for single word, query as before with only searchstring
  329. QString lastname = searchstring; // second control path with comma, lastname like AND firstname like
  330. if(searchstring.contains(QLatin1Char(',')))
  331. {
  332. QStringList namelist = searchstring.split(QLatin1Char(','));
  333. QString lastname = namelist[0].trimmed();
  334. lastname = lastname.toLower();
  335. lastname[0] = lastname[0].toUpper();
  336. lastname.prepend("%"), lastname.append("%");
  337. QString firstname = namelist[1].trimmed();
  338. if(firstname.length()>1)
  339. {
  340. firstname = firstname.toLower();
  341. firstname[0] = firstname[0].toUpper();
  342. firstname.prepend("%"), firstname.append("%");
  343. }
  344. qDebug() << "db::RetreivePilotNameFromString: first last after comma";
  345. qDebug() << firstname << lastname;
  346. }
  347. QSqlQuery query;
  348. query.prepare("SELECT piclastname, picfirstname, alias "
  349. "FROM pilots WHERE "
  350. "picfirstname LIKE ? OR piclastname LIKE ? OR alias LIKE ?");
  351. searchstring.prepend("%");
  352. searchstring.append("%");
  353. query.addBindValue(firstname);
  354. query.addBindValue(lastname);
  355. query.addBindValue(searchstring);
  356. query.exec();
  357. QStringList result;
  358. while (query.next()) {
  359. QString piclastname = query.value(0).toString();
  360. QString picfirstname = query.value(1).toString();
  361. QString alias = query.value(2).toString();
  362. QString name = piclastname + ", " + picfirstname;
  363. result.append(name);
  364. }
  365. qDebug() << "db::RetreivePilotNameFromString Result: " << result;
  366. //qDebug() << query.lastError();
  367. if(result.size() == 0)
  368. {
  369. qDebug() << ("db::RetreivePilotNameFromString: No Pilot found");
  370. return result;
  371. }
  372. return result;
  373. }
  374. /*!
  375. * \brief newPicGetString This function is returning a QStringList for the QCompleter in the NewFlight::newPic line edit
  376. * A regular expression limits the input possibilities to only characters,
  377. * followed by an optional ',' and 1 whitespace, e.g.:
  378. * Miller, Jim ->valid / Miller, Jim -> invalid / Miller,, Jim -> invalid
  379. * Miller Jim -> valid / Miller Jim ->invalid
  380. * Jim Miller-> valid
  381. * \param searchstring
  382. * \return
  383. */
  384. static QStringList newPicGetString(QString searchstring)
  385. {
  386. QStringList result;
  387. QStringList searchlist;
  388. if(searchstring == "self")
  389. {
  390. result.append("self");
  391. qDebug() << "Pilot is self";
  392. return result;
  393. }
  394. //Fall 1) Nachname, Vorname
  395. if(searchstring.contains(QLatin1Char(',')))
  396. {
  397. QStringList namelist = searchstring.split(QLatin1Char(','));
  398. QString name1 = namelist[0].trimmed();
  399. name1 = name1.toLower();
  400. name1[0] = name1[0].toUpper();
  401. searchlist.append(name1);
  402. if(namelist[1].length() > 1)
  403. {
  404. QString name2 = namelist[1].trimmed();
  405. name2 = name2.toLower();
  406. name2[0] = name2[0].toUpper();
  407. searchlist.append(name2);
  408. }
  409. }
  410. //Fall 2) Vorname Nachname
  411. if(searchstring.contains(" ") && !searchstring.contains(QLatin1Char(',')))
  412. {
  413. QStringList namelist = searchstring.split(" ");
  414. QString name1 = namelist[0].trimmed();
  415. name1 = name1.toLower();
  416. name1[0] = name1[0].toUpper();
  417. searchlist.append(name1);
  418. if(namelist[1].length() > 1) //To avoid index out of range if the searchstring is one word followed by only one whitespace
  419. {
  420. QString name2 = namelist[1].trimmed();
  421. name2 = name2.toLower();
  422. name2[0] = name2[0].toUpper();
  423. searchlist.append(name2);
  424. }
  425. }
  426. //Fall 3) Name
  427. if(!searchstring.contains(" ") && !searchstring.contains(QLatin1Char(',')))
  428. {
  429. QString name1 = searchstring.toLower();
  430. name1[0] = name1[0].toUpper();
  431. searchlist.append(name1);
  432. }
  433. if(searchlist.length() == 1)
  434. {
  435. QSqlQuery query;
  436. query.prepare("SELECT piclastname, picfirstname FROM pilots "
  437. "WHERE piclastname LIKE ?");
  438. query.addBindValue(searchlist[0] + '%');
  439. query.exec();
  440. while(query.next())
  441. {
  442. result.append(query.value(0).toString() + ", " + query.value(1).toString());
  443. }
  444. QSqlQuery query2;
  445. query2.prepare("SELECT piclastname, picfirstname FROM pilots "
  446. "WHERE picfirstname LIKE ?");
  447. query2.addBindValue(searchlist[0] + '%');
  448. query2.exec();
  449. while(query2.next())
  450. {
  451. result.append(query2.value(0).toString() + ", " + query2.value(1).toString());
  452. }
  453. }else
  454. {
  455. QSqlQuery query;
  456. query.prepare("SELECT piclastname, picfirstname FROM pilots "
  457. "WHERE piclastname LIKE ? AND picfirstname LIKE ?");
  458. query.addBindValue(searchlist[0] + '%');
  459. query.addBindValue(searchlist[1] + '%');
  460. query.exec();
  461. while(query.next())
  462. {
  463. result.append(query.value(0).toString() + ", " + query.value(1).toString());
  464. }
  465. QSqlQuery query2;
  466. query2.prepare("SELECT piclastname, picfirstname FROM pilots "
  467. "WHERE picfirstname LIKE ? AND piclastname LIKE ?");
  468. query2.addBindValue(searchlist[0] + '%');
  469. query2.addBindValue(searchlist[1] + '%');
  470. query2.exec();
  471. while(query2.next())
  472. {
  473. result.append(query2.value(0).toString() + ", " + query2.value(1).toString());
  474. }
  475. }
  476. qDebug() << "db::newPic Result" << result.length() << result;
  477. if(result.length() == 0)
  478. {
  479. //try first name search
  480. qDebug() << "No Pilot with this last name found. trying first name search.";
  481. return result;
  482. }else
  483. {
  484. return result;
  485. }
  486. }
  487. static QString newPicGetId(QString name)
  488. {
  489. QString result;
  490. QStringList nameparts = name.split(QLatin1Char(','));
  491. QString lastname = nameparts[0].trimmed();
  492. lastname = lastname.toLower(); lastname[0] = lastname[0].toUpper();
  493. QString firstname = nameparts[1].trimmed();
  494. firstname = firstname.toLower(); firstname[0] = firstname[0].toUpper();
  495. firstname.prepend("%"); firstname.append("%");
  496. QSqlQuery query;
  497. query.prepare("SELECT pilot_id FROM pilots "
  498. "WHERE piclastname = ? AND picfirstname LIKE ?");
  499. query.addBindValue(lastname);
  500. query.addBindValue(firstname);
  501. query.exec();
  502. while (query.next())
  503. {
  504. result.append(query.value(0).toString());
  505. }
  506. qDebug() << "newPicGetId: result = " << result;
  507. return result;
  508. }
  509. /*
  510. * Airport Database Related Functions
  511. */
  512. /*!
  513. * \brief RetreiveAirportNameFromIcaoOrIata Looks up Airport Name
  514. * \param identifier can be ICAO or IATA airport codes.
  515. * \return The name of the airport associated with the above code
  516. */
  517. static QString RetreiveAirportNameFromIcaoOrIata(QString identifier)
  518. {
  519. QString result = "";
  520. QSqlQuery query;
  521. query.prepare("SELECT name "
  522. "FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  523. identifier.append("%");
  524. identifier.prepend("%");
  525. query.addBindValue(identifier);
  526. query.addBindValue(identifier);
  527. query.exec();
  528. if(query.first())
  529. {
  530. result.append(query.value(0).toString());
  531. return result;
  532. }else
  533. {
  534. result = result.left(result.length()-1);
  535. result.append("No matching airport found.");
  536. return result;
  537. }
  538. }
  539. static QString RetreiveAirportIdFromIcao(QString identifier)
  540. {
  541. QString result;
  542. QSqlQuery query;
  543. query.prepare("SELECT airport_id FROM airports WHERE icao = ?");
  544. query.addBindValue(identifier);
  545. query.exec();
  546. while(query.next())
  547. {
  548. result.append(query.value(0).toString());
  549. //qDebug() << "db::RetreiveAirportIdFromIcao says Airport found! #" << result;
  550. }
  551. return result;
  552. }
  553. static QStringList CompleteIcaoOrIata(QString icaoStub)
  554. {
  555. QStringList result;
  556. QSqlQuery query;
  557. query.prepare("SELECT icao FROM airports WHERE icao LIKE ? OR iata LIKE ?");
  558. icaoStub.prepend("%"); icaoStub.append("%");
  559. query.addBindValue(icaoStub);
  560. query.addBindValue(icaoStub);
  561. query.exec();
  562. while(query.next())
  563. {
  564. result.append(query.value(0).toString());
  565. qDebug() << "db::CompleteIcaoOrIata says... Result:" << result;
  566. }
  567. return result;
  568. }
  569. /*!
  570. * \brief CheckICAOValid Verifies if a user input airport exists in the database
  571. * \param identifier can be ICAO or IATA airport codes.
  572. * \return bool if airport is in database.
  573. */
  574. static bool CheckICAOValid(QString identifier)
  575. {
  576. if(identifier.length() == 4)
  577. {
  578. QString check = RetreiveAirportIdFromIcao(identifier);
  579. if(check.length() > 0)
  580. {
  581. //qDebug() << "db::CheckICAOValid says: Check passed!";
  582. return 1;
  583. }else
  584. {
  585. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Lookup unsuccessful";
  586. return 0;
  587. }
  588. }else
  589. {
  590. //qDebug() << "db::CheckICAOValid says: Check NOT passed! Empty String NOT epico!";
  591. return 0;
  592. }
  593. }
  594. /*!
  595. * \brief retreiveIcaoCoordinates Looks up coordinates (lat,long) for a given airport
  596. * \param icao 4-letter code for the airport
  597. * \return {lat,lon} in decimal degrees
  598. */
  599. static QVector<double> retreiveIcaoCoordinates(QString icao)
  600. {
  601. QSqlQuery query;
  602. query.prepare("SELECT lat, long "
  603. "FROM airports "
  604. "WHERE icao = ?");
  605. query.addBindValue(icao);
  606. query.exec();
  607. QVector<double> result;
  608. while(query.next()) {
  609. result.append(query.value(0).toDouble());
  610. result.append(query.value(1).toDouble());
  611. }
  612. return result;
  613. }
  614. /*
  615. * Aircraft Database Related Functions
  616. */
  617. /*!
  618. * \brief RetreiveRegistration Looks up tail_id from Database
  619. * \param tail_ID Primary Key of tails database
  620. * \return Registration
  621. */
  622. static QString RetreiveRegistration(QString tail_ID)
  623. {
  624. QString acftRegistration("");
  625. QSqlQuery query;
  626. query.prepare("SELECT registration FROM tails WHERE tail_id == ?");
  627. query.addBindValue(tail_ID.toInt());
  628. query.exec();
  629. if(query.first());
  630. else
  631. qDebug() << ("No Aircraft with this ID found");
  632. query.previous();//To go back to index 0
  633. while (query.next()) {
  634. acftRegistration.append(query.value(0).toString());
  635. }
  636. return acftRegistration;
  637. }
  638. /*!
  639. * \brief newAcftGetString Looks up an aircraft Registration in the database
  640. * \param searchstring
  641. * \return Registration, make, model and variant
  642. */
  643. static QStringList newAcftGetString(QString searchstring)
  644. {
  645. QStringList result;
  646. if(searchstring.length()<2){return result;}
  647. QSqlQuery query;
  648. query.prepare("SELECT registration, make, model, variant "
  649. "FROM aircraft "
  650. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  651. "WHERE tails.registration LIKE ?");
  652. searchstring.append("%"); searchstring.prepend("%");
  653. query.addBindValue(searchstring);
  654. query.exec();
  655. while(query.next())
  656. {
  657. result.append(query.value(0).toString() + " (" + query.value(1).toString() + "-" + query.value(2).toString() + "-" + query.value(3).toString() + ")");
  658. }
  659. qDebug() << "newAcftGetString: " << result.length() << result;
  660. return result;
  661. }
  662. static QString newAcftGetId(QString registration)
  663. {
  664. QString result;
  665. QSqlQuery query;
  666. query.prepare("SELECT tail_id "
  667. "FROM tails "
  668. "WHERE registration LIKE ?");
  669. registration.prepend("%"); registration.append("%");
  670. query.addBindValue(registration);
  671. query.exec();
  672. while(query.next())
  673. {
  674. result.append(query.value(0).toString());
  675. }
  676. qDebug() << "newAcftGetId: " << result;
  677. return result;
  678. }
  679. static QVector<QString> RetreiveAircraftTypeFromReg(QString searchstring)
  680. /*
  681. * Searches the tails Database and returns the aircraft Type.
  682. */
  683. {
  684. QSqlQuery query;
  685. query.prepare("SELECT Name, iata, registration, tail_id " //"SELECT Registration, Name, icao, iata "
  686. "FROM aircraft "
  687. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  688. "WHERE tails.registration LIKE ?");
  689. // Returns Registration/Name/icao/iata
  690. searchstring.prepend("%");
  691. searchstring.append("%");
  692. query.addBindValue(searchstring);
  693. query.exec();
  694. QVector<QString> result;
  695. if(query.first())
  696. {
  697. QString acType = query.value(0).toString();
  698. QString iataCode = query.value(1).toString();
  699. QString registration = query.value(2).toString();
  700. QString tail_id = query.value(3).toString();
  701. //QString formatted = acType + " [ " + registration + " | " + iataCode + " ]";
  702. //qDebug() << formatted;
  703. result.append(registration); result.append(acType);
  704. result.append(iataCode); result.append(tail_id);
  705. return result;
  706. }else
  707. {
  708. return result; // empty vector
  709. }
  710. }
  711. static QStringList RetreiveAircraftMake(QString searchstring)
  712. {
  713. QStringList result;
  714. QSqlQuery query;
  715. query.prepare("SELECT make from aircraft WHERE make LIKE ?");
  716. searchstring.prepend("%"); searchstring.append("%");
  717. query.addBindValue(searchstring);
  718. query.exec();
  719. while(query.next())
  720. {
  721. result.append(query.value(0).toString());
  722. }
  723. qDebug() << "db::RetreiveAircraftMake says... Result:" << result;
  724. return result;
  725. }
  726. static QStringList RetreiveAircraftModel(QString make, QString searchstring)
  727. {
  728. QStringList result;
  729. QSqlQuery query;
  730. query.prepare("SELECT model FROM aircraft WHERE make = ? AND model LIKE ?");
  731. query.addBindValue(make);
  732. searchstring.prepend("%"); searchstring.append("%");
  733. query.addBindValue(searchstring);
  734. query.exec();
  735. while(query.next())
  736. {
  737. result.append(query.value(0).toString());
  738. qDebug() << "db::RetreiveAircraftModel says... Result:" << result;
  739. }
  740. return result;
  741. }
  742. static QStringList RetreiveAircraftVariant(QString make, QString model, QString searchstring)
  743. {
  744. QStringList result;
  745. QSqlQuery query;
  746. query.prepare("SELECT variant from aircraft WHERE make = ? AND model = ? AND variant LIKE ?");
  747. query.addBindValue(make);
  748. query.addBindValue(model);
  749. searchstring.prepend("%"); searchstring.append("%");
  750. query.addBindValue(searchstring);
  751. query.exec();
  752. while(query.next())
  753. {
  754. result.append(query.value(0).toString());
  755. qDebug() << "db::RetreiveAircraftVariant says... Result:" << result;
  756. }
  757. return result;
  758. }
  759. static QString RetreiveAircraftIdFromMakeModelVariant(QString make, QString model, QString variant)
  760. {
  761. QString result;
  762. QSqlQuery query;
  763. query.prepare("SELECT aircraft_id FROM aircraft WHERE make = ? AND model = ? AND variant = ?");
  764. query.addBindValue(make);
  765. query.addBindValue(model);
  766. query.addBindValue(variant);
  767. query.exec();
  768. if(query.first())
  769. {
  770. result.append(query.value(0).toString());
  771. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: Aircraft found! ID# " << result;
  772. return result;
  773. }else
  774. {
  775. result = result.left(result.length()-1);
  776. result.append("0");
  777. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: ERROR - no AircraftId found.";
  778. return result;
  779. }
  780. }
  781. static bool CommitTailToDb(QString registration, QString aircraft_id, QString company)
  782. {
  783. QSqlQuery commit;
  784. commit.prepare("INSERT INTO tails (registration, aircraft_id, company) VALUES (?,?,?)");
  785. commit.addBindValue(registration);
  786. commit.addBindValue(aircraft_id);
  787. commit.addBindValue(company);
  788. commit.exec();
  789. QString error = commit.lastError().text();
  790. if(error.length() < 0)
  791. {
  792. qDebug() << "db::CommitAircraftToDb:: SQL error:" << error;
  793. return false;
  794. }else
  795. {
  796. return true;
  797. }
  798. }
  799. /*
  800. * Settings Database Related Functions
  801. */
  802. /*!
  803. * \brief retreiveSetting Looks up a setting in the database and returns its value
  804. * \param setting_id
  805. * \return setting value
  806. */
  807. static QString retreiveSetting(QString setting_id)
  808. {
  809. QSqlQuery query;
  810. query.prepare("SELECT setting FROM settings WHERE setting_id = ?");
  811. query.addBindValue(setting_id);
  812. query.exec();
  813. QString setting = "-1";
  814. while(query.next()){
  815. setting = query.value(0).toString();
  816. }
  817. return setting;
  818. }
  819. /*!
  820. * \brief retreiveSettingInfo Looks up a setting in the database and returns its value and description
  821. * \param setting_id
  822. * \return {setting_id, setting, description}
  823. */
  824. static QVector<QString> retreiveSettingInfo(QString setting_id)
  825. {
  826. QSqlQuery query;
  827. query.prepare("SELECT * FROM settings WHERE setting_id = ?");
  828. query.addBindValue(setting_id);
  829. query.exec();
  830. QVector<QString> setting;
  831. while(query.next()){
  832. setting.append(query.value(0).toString());
  833. setting.append(query.value(1).toString());
  834. setting.append(query.value(2).toString());
  835. }
  836. return setting;
  837. }
  838. /*!
  839. * \brief storesetting Updates a stored setting in the database
  840. * \param setting_id
  841. * \param setting_value
  842. */
  843. static void storesetting(int setting_id, QString setting_value)
  844. {
  845. QSqlQuery query;
  846. query.prepare("UPDATE settings "
  847. "SET setting = ? "
  848. "WHERE setting_id = ?");
  849. query.addBindValue(setting_value);
  850. query.addBindValue(setting_id);
  851. query.exec();
  852. }
  853. /*
  854. * Obsolete Functions
  855. */
  856. /*!
  857. * \brief SelectFlightDate Retreives Flights from the database currently not in use.
  858. * \param doft Date of flight for filtering result set. "ALL" means no filter.
  859. * \return Flight(s) for selected date.
  860. */
  861. static QVector<QString> SelectFlightDate(QString doft)
  862. {
  863. QSqlQuery query;
  864. if (doft == "ALL") // Special Selector
  865. {
  866. query.prepare("SELECT * FROM flights ORDER BY doft DESC, tofb ASC");
  867. qDebug() << "All flights selected";
  868. }else
  869. {
  870. query.prepare("SELECT * FROM flights WHERE doft = ? ORDER BY tofb ASC");
  871. query.addBindValue(doft);
  872. qDebug() << "Searching flights for " << doft;
  873. }
  874. query.exec();
  875. if(query.first());
  876. else
  877. {
  878. qDebug() << ("No flight with this date found");
  879. QVector<QString> flight; //return empty
  880. return flight;
  881. }
  882. query.previous();// To go back to index 0
  883. query.last(); // this can be very slow, used to determine query size since .size is not supported by sqlite
  884. int numRows = query.at() + 1; // Number of rows (flights) in the query
  885. query.first();
  886. query.previous();// Go back to index 0
  887. QVector<QString> flight(numRows * 9); // Every flight has 9 fields in the database
  888. int index = 0; // counter for output vector
  889. while (query.next()) {
  890. QString id = query.value(0).toString();
  891. QString doft = query.value(1).toString();
  892. QString dept = query.value(2).toString();
  893. QString tofb = calc::minutes_to_string((query.value(3).toString()));
  894. QString dest = query.value(4).toString();
  895. QString tonb = calc::minutes_to_string((query.value(5).toString()));
  896. QString tblk = calc::minutes_to_string((query.value(6).toString()));
  897. QString pic = db::RetreivePilotNameFromID(query.value(7).toString());
  898. QString acft = db::RetreiveRegistration(query.value(8).toString());
  899. //qDebug() << id << doft << dept << tofb << dest << tonb << tblk << pic << acft << endl;
  900. flight[index] = id;
  901. ++index;
  902. flight[index] = doft;
  903. ++index;
  904. flight[index] = dept;
  905. ++index;
  906. flight[index] = tofb;
  907. ++index;
  908. flight[index] = dest;
  909. ++index;
  910. flight[index] = tonb;
  911. ++index;
  912. flight[index] = tblk;
  913. ++index;
  914. flight[index] = pic;
  915. ++index;
  916. flight[index] = acft;
  917. ++index;
  918. }
  919. return flight;
  920. }
  921. };