dbman.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. * Aircraft Database Related Functions
  801. */
  802. static QVector<QString> retreiveSetting(QString setting_id)
  803. {
  804. QSqlQuery query;
  805. query.prepare("SELECT * FROM settings WHERE setting_id = ?");
  806. query.addBindValue(setting_id);
  807. query.exec();
  808. QVector<QString> setting;
  809. while(query.next()){
  810. setting.append(query.value(0).toString());
  811. setting.append(query.value(1).toString());
  812. setting.append(query.value(2).toString());
  813. }
  814. return setting;
  815. }
  816. static void storesetting(int setting_id, QString setting_value)
  817. {
  818. QSqlQuery query;
  819. query.prepare("UPDATE settings "
  820. "SET setting = ? "
  821. "WHERE setting_id = ?");
  822. query.addBindValue(setting_value);
  823. query.addBindValue(setting_id);
  824. query.exec();
  825. }
  826. /*
  827. * Obsolete Functions
  828. */
  829. /*!
  830. * \brief SelectFlightDate Retreives Flights from the database currently not in use.
  831. * \param doft Date of flight for filtering result set. "ALL" means no filter.
  832. * \return Flight(s) for selected date.
  833. */
  834. static QVector<QString> SelectFlightDate(QString doft)
  835. {
  836. QSqlQuery query;
  837. if (doft == "ALL") // Special Selector
  838. {
  839. query.prepare("SELECT * FROM flights ORDER BY doft DESC, tofb ASC");
  840. qDebug() << "All flights selected";
  841. }else
  842. {
  843. query.prepare("SELECT * FROM flights WHERE doft = ? ORDER BY tofb ASC");
  844. query.addBindValue(doft);
  845. qDebug() << "Searching flights for " << doft;
  846. }
  847. query.exec();
  848. if(query.first());
  849. else
  850. {
  851. qDebug() << ("No flight with this date found");
  852. QVector<QString> flight; //return empty
  853. return flight;
  854. }
  855. query.previous();// To go back to index 0
  856. query.last(); // this can be very slow, used to determine query size since .size is not supported by sqlite
  857. int numRows = query.at() + 1; // Number of rows (flights) in the query
  858. query.first();
  859. query.previous();// Go back to index 0
  860. QVector<QString> flight(numRows * 9); // Every flight has 9 fields in the database
  861. int index = 0; // counter for output vector
  862. while (query.next()) {
  863. QString id = query.value(0).toString();
  864. QString doft = query.value(1).toString();
  865. QString dept = query.value(2).toString();
  866. QString tofb = calc::minutes_to_string((query.value(3).toString()));
  867. QString dest = query.value(4).toString();
  868. QString tonb = calc::minutes_to_string((query.value(5).toString()));
  869. QString tblk = calc::minutes_to_string((query.value(6).toString()));
  870. QString pic = db::RetreivePilotNameFromID(query.value(7).toString());
  871. QString acft = db::RetreiveRegistration(query.value(8).toString());
  872. //qDebug() << id << doft << dept << tofb << dest << tonb << tblk << pic << acft << endl;
  873. flight[index] = id;
  874. ++index;
  875. flight[index] = doft;
  876. ++index;
  877. flight[index] = dept;
  878. ++index;
  879. flight[index] = tofb;
  880. ++index;
  881. flight[index] = dest;
  882. ++index;
  883. flight[index] = tonb;
  884. ++index;
  885. flight[index] = tblk;
  886. ++index;
  887. flight[index] = pic;
  888. ++index;
  889. flight[index] = acft;
  890. ++index;
  891. }
  892. return flight;
  893. }
  894. };