jsonhelper.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *openPilotLog - A FOSS Pilot Logbook Application
  3. *Copyright (C) 2020-2023 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 "jsonhelper.h"
  19. #include "src/database/database.h"
  20. #include "src/classes/paths.h"
  21. void JsonHelper::exportDatabase()
  22. {
  23. for (const auto &table : TABLES){
  24. QJsonArray array;
  25. const auto rows = DB->getTable(table);
  26. for (const auto &row : rows)
  27. array.append(QJsonObject::fromVariantHash(row));
  28. QJsonDocument doc(array);
  29. writeDocToFile(doc, OPL::GLOBALS->getDbTableName(table) + QLatin1String(".json"));
  30. }
  31. }
  32. void JsonHelper::importDatabase()
  33. {
  34. TODO << "Another function should do some checking here if data exists etc...";
  35. TODO << "Make the function take a list of files/fileinfo as arguments";
  36. // clear tables
  37. QSqlQuery q;
  38. // make sure flights is cleared first due to foreign key contstraints
  39. q.prepare(QStringLiteral("DELETE FROM FLIGHTS"));
  40. q.exec();
  41. for (const auto & table : TABLES) {
  42. const QString table_name = OPL::GLOBALS->getDbTableName(table);
  43. q.prepare(QLatin1String("DELETE FROM ") + table_name);
  44. q.exec();
  45. const auto doc = readFileToDoc(OPL::Paths::filePath(OPL::Paths::Templates,
  46. table_name + QLatin1String(".json")));
  47. DB->commit(doc.array(), table);
  48. }
  49. }
  50. QJsonDocument JsonHelper::readFileToDoc(const QString &file_path)
  51. {
  52. QFile file(file_path);
  53. file.open(QIODevice::ReadOnly | QIODevice::Text);
  54. QString raw = file.readAll();
  55. file.close();
  56. QJsonDocument doc = QJsonDocument::fromJson(raw.toUtf8());
  57. return doc;
  58. }
  59. void JsonHelper::writeDocToFile(const QJsonDocument &doc, const QString &file_name)
  60. {
  61. QFile out(OPL::Paths::filePath(OPL::Paths::Export,file_name));
  62. out.open(QFile::WriteOnly);
  63. out.write(doc.toJson());
  64. out.close();
  65. }