dbman.cpp 34 KB

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