dbman.cpp 39 KB

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