dbman.cpp 36 KB

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