dbman.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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 "dbpilots.h"
  26. #include <chrono>
  27. #include <QRandomGenerator>
  28. #include <QStandardPaths>
  29. class db
  30. {
  31. public:
  32. static void connect()
  33. {
  34. const QString DRIVER("QSQLITE");
  35. if(QSqlDatabase::isDriverAvailable(DRIVER))
  36. {
  37. QSqlDatabase db = QSqlDatabase::addDatabase(DRIVER);
  38. //QString pathtodb = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
  39. //db.setDatabaseName(pathtodb+"/logbook.db");
  40. //qDebug() << "Database: " << pathtodb+"/logbook.db";
  41. db.setDatabaseName("logbook.db");
  42. if(!db.open())
  43. qWarning() << "MainWindow::DatabaseConnect - ERROR: " << db.lastError().text();
  44. }
  45. else
  46. qWarning() << "MainWindow::DatabaseConnect - ERROR: no driver " << DRIVER << " available";
  47. }
  48. static void initexample()
  49. {
  50. QSqlQuery query("CREATE TABLE flights (id INTEGER PRIMARY KEY, date NUMERIC)");
  51. if(!query.isActive())
  52. qWarning() << "MainWindow::DatabaseInit - ERROR: " << query.lastError().text();
  53. }
  54. static void queryexamplenamedbinding()
  55. {
  56. QSqlQuery query;
  57. //query.prepare("SELECT * FROM people");
  58. //query.prepare("SELECT * FROM people WHERE name LIKE 'Linus' OR id = :id");
  59. query.prepare("SELECT * from people WHERE name LIKE :name");
  60. query.bindValue(":name", "%Linus%");
  61. query.bindValue(":id",2);
  62. query.exec();
  63. /*
  64. * QSqlQuery provides access to the result set one record at a time. After the call to exec(),
  65. * QSqlQuery's internal pointer is located one position before the first record.
  66. * We must call QSqlQuery::next() once to advance to the first record, then next() again
  67. * repeatedly to access the other records, until it returns false. Here's a typical loop that
  68. * iterates over all the records in order:
  69. * After a SELECT query is executed we have to browse the records (result rows) returned to access
  70. * the data. In this case we try to retrieve the first record calling the function first which
  71. * returns true when the query has been successful and false otherwise.
  72. */
  73. if(query.first());
  74. else
  75. qDebug() << ("No entry found");
  76. query.previous();//To go back to index 0
  77. while (query.next()) {
  78. QString name = query.value(1).toString();
  79. int id = query.value(0).toInt();
  80. qDebug() << name << id;
  81. }
  82. /*
  83. *The QSqlQuery::value() function returns the value of a field in the current record. Fields are
  84. * specified as zero-based indexes. QSqlQuery::value() returns a QVariant, a type that can hold
  85. * various C++ and core Qt data types such as int, QString, and QByteArray. The different database
  86. * types are automatically mapped into the closest Qt equivalent. In the code snippet, we call
  87. * QVariant::toString() and QVariant::toInt() to convert variants to QString and int.
  88. */
  89. }
  90. /*
  91. * Aircraft Database Related Functions
  92. */
  93. /*!
  94. * \brief RetreiveRegistration Looks up tail_id from Database
  95. * \param tail_ID Primary Key of tails database
  96. * \return Registration
  97. */
  98. static QString RetreiveRegistration(QString tail_ID)
  99. {
  100. QString acftRegistration("");
  101. QSqlQuery query;
  102. query.prepare("SELECT registration FROM tails WHERE tail_id == ?");
  103. query.addBindValue(tail_ID.toInt());
  104. query.exec();
  105. if(query.first());
  106. else
  107. qDebug() << ("No Aircraft with this ID found");
  108. query.previous();//To go back to index 0
  109. while (query.next()) {
  110. acftRegistration.append(query.value(0).toString());
  111. }
  112. return acftRegistration;
  113. }
  114. /*!
  115. * \brief newAcftGetString Looks up an aircraft Registration in the database
  116. * \param searchstring
  117. * \return Registration, make, model and variant
  118. */
  119. static QStringList newAcftGetString(QString searchstring)
  120. {
  121. QStringList result;
  122. if(searchstring.length()<2){return result;}
  123. QSqlQuery query;
  124. query.prepare("SELECT registration, make, model, variant "
  125. "FROM aircraft "
  126. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  127. "WHERE tails.registration LIKE ?");
  128. searchstring.append("%"); searchstring.prepend("%");
  129. query.addBindValue(searchstring);
  130. query.exec();
  131. while(query.next())
  132. {
  133. result.append(query.value(0).toString() + " (" + query.value(1).toString() + "-" + query.value(2).toString() + "-" + query.value(3).toString() + ")");
  134. }
  135. qDebug() << "newAcftGetString: " << result.length() << result;
  136. return result;
  137. }
  138. static QString newAcftGetId(QString registration)
  139. {
  140. QString result;
  141. QSqlQuery query;
  142. query.prepare("SELECT tail_id "
  143. "FROM tails "
  144. "WHERE registration LIKE ?");
  145. registration.prepend("%"); registration.append("%");
  146. query.addBindValue(registration);
  147. query.exec();
  148. while(query.next())
  149. {
  150. result.append(query.value(0).toString());
  151. }
  152. qDebug() << "newAcftGetId: " << result;
  153. return result;
  154. }
  155. static QVector<QString> RetreiveAircraftTypeFromReg(QString searchstring)
  156. /*
  157. * Searches the tails Database and returns the aircraft Type.
  158. */
  159. {
  160. QSqlQuery query;
  161. query.prepare("SELECT Name, iata, registration, tail_id " //"SELECT Registration, Name, icao, iata "
  162. "FROM aircraft "
  163. "INNER JOIN tails on tails.aircraft_ID = aircraft.aircraft_id "
  164. "WHERE tails.registration LIKE ?");
  165. // Returns Registration/Name/icao/iata
  166. searchstring.prepend("%");
  167. searchstring.append("%");
  168. query.addBindValue(searchstring);
  169. query.exec();
  170. QVector<QString> result;
  171. if(query.first())
  172. {
  173. QString acType = query.value(0).toString();
  174. QString iataCode = query.value(1).toString();
  175. QString registration = query.value(2).toString();
  176. QString tail_id = query.value(3).toString();
  177. //QString formatted = acType + " [ " + registration + " | " + iataCode + " ]";
  178. //qDebug() << formatted;
  179. result.append(registration); result.append(acType);
  180. result.append(iataCode); result.append(tail_id);
  181. return result;
  182. }else
  183. {
  184. return result; // empty vector
  185. }
  186. }
  187. static QStringList RetreiveAircraftMake(QString searchstring)
  188. {
  189. QStringList result;
  190. QSqlQuery query;
  191. query.prepare("SELECT make from aircraft WHERE make LIKE ?");
  192. searchstring.prepend("%"); searchstring.append("%");
  193. query.addBindValue(searchstring);
  194. query.exec();
  195. while(query.next())
  196. {
  197. result.append(query.value(0).toString());
  198. }
  199. qDebug() << "db::RetreiveAircraftMake says... Result:" << result;
  200. return result;
  201. }
  202. static QStringList RetreiveAircraftModel(QString make, QString searchstring)
  203. {
  204. QStringList result;
  205. QSqlQuery query;
  206. query.prepare("SELECT model FROM aircraft WHERE make = ? AND model LIKE ?");
  207. query.addBindValue(make);
  208. searchstring.prepend("%"); searchstring.append("%");
  209. query.addBindValue(searchstring);
  210. query.exec();
  211. while(query.next())
  212. {
  213. result.append(query.value(0).toString());
  214. qDebug() << "db::RetreiveAircraftModel says... Result:" << result;
  215. }
  216. return result;
  217. }
  218. static QStringList RetreiveAircraftVariant(QString make, QString model, QString searchstring)
  219. {
  220. QStringList result;
  221. QSqlQuery query;
  222. query.prepare("SELECT variant from aircraft WHERE make = ? AND model = ? AND variant LIKE ?");
  223. query.addBindValue(make);
  224. query.addBindValue(model);
  225. searchstring.prepend("%"); searchstring.append("%");
  226. query.addBindValue(searchstring);
  227. query.exec();
  228. while(query.next())
  229. {
  230. result.append(query.value(0).toString());
  231. qDebug() << "db::RetreiveAircraftVariant says... Result:" << result;
  232. }
  233. return result;
  234. }
  235. static QString RetreiveAircraftIdFromMakeModelVariant(QString make, QString model, QString variant)
  236. {
  237. QString result;
  238. QSqlQuery query;
  239. query.prepare("SELECT aircraft_id FROM aircraft WHERE make = ? AND model = ? AND variant = ?");
  240. query.addBindValue(make);
  241. query.addBindValue(model);
  242. query.addBindValue(variant);
  243. query.exec();
  244. if(query.first())
  245. {
  246. result.append(query.value(0).toString());
  247. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: Aircraft found! ID# " << result;
  248. return result;
  249. }else
  250. {
  251. result = result.left(result.length()-1);
  252. result.append("0");
  253. qDebug() << "db::RetreiveAircraftIdFromMakeModelVariant: ERROR - no AircraftId found.";
  254. return result;
  255. }
  256. }
  257. static bool CommitTailToDb(QString registration, QString aircraft_id, QString company)
  258. {
  259. QSqlQuery commit;
  260. commit.prepare("INSERT INTO tails (registration, aircraft_id, company) VALUES (?,?,?)");
  261. commit.addBindValue(registration);
  262. commit.addBindValue(aircraft_id);
  263. commit.addBindValue(company);
  264. commit.exec();
  265. QString error = commit.lastError().text();
  266. if(error.length() < 0)
  267. {
  268. qDebug() << "db::CommitAircraftToDb:: SQL error:" << error;
  269. return false;
  270. }else
  271. {
  272. return true;
  273. }
  274. }
  275. /*
  276. * Obsolete Functions
  277. */
  278. /*!
  279. * \brief SelectFlightDate Retreives Flights from the database currently not in use.
  280. * \param doft Date of flight for filtering result set. "ALL" means no filter.
  281. * \return Flight(s) for selected date.
  282. */
  283. static QVector<QString> SelectFlightDate(QString doft)
  284. {
  285. QSqlQuery query;
  286. if (doft == "ALL") // Special Selector
  287. {
  288. query.prepare("SELECT * FROM flights ORDER BY doft DESC, tofb ASC");
  289. qDebug() << "All flights selected";
  290. }else
  291. {
  292. query.prepare("SELECT * FROM flights WHERE doft = ? ORDER BY tofb ASC");
  293. query.addBindValue(doft);
  294. qDebug() << "Searching flights for " << doft;
  295. }
  296. query.exec();
  297. if(query.first());
  298. else
  299. {
  300. qDebug() << ("No flight with this date found");
  301. QVector<QString> flight; //return empty
  302. return flight;
  303. }
  304. query.previous();// To go back to index 0
  305. query.last(); // this can be very slow, used to determine query size since .size is not supported by sqlite
  306. int numRows = query.at() + 1; // Number of rows (flights) in the query
  307. query.first();
  308. query.previous();// Go back to index 0
  309. QVector<QString> flight(numRows * 9); // Every flight has 9 fields in the database
  310. int index = 0; // counter for output vector
  311. while (query.next()) {
  312. QString id = query.value(0).toString();
  313. QString doft = query.value(1).toString();
  314. QString dept = query.value(2).toString();
  315. QString tofb = calc::minutes_to_string((query.value(3).toString()));
  316. QString dest = query.value(4).toString();
  317. QString tonb = calc::minutes_to_string((query.value(5).toString()));
  318. QString tblk = calc::minutes_to_string((query.value(6).toString()));
  319. QString pic = dbPilots::retreivePilotNameFromID(query.value(7).toString());
  320. QString acft = db::RetreiveRegistration(query.value(8).toString());
  321. //qDebug() << id << doft << dept << tofb << dest << tonb << tblk << pic << acft << endl;
  322. flight[index] = id;
  323. ++index;
  324. flight[index] = doft;
  325. ++index;
  326. flight[index] = dept;
  327. ++index;
  328. flight[index] = tofb;
  329. ++index;
  330. flight[index] = dest;
  331. ++index;
  332. flight[index] = tonb;
  333. ++index;
  334. flight[index] = tblk;
  335. ++index;
  336. flight[index] = pic;
  337. ++index;
  338. flight[index] = acft;
  339. ++index;
  340. }
  341. return flight;
  342. }
  343. };