Database.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // Created by Иван_Архипов on 17.11.2017.
  3. //
  4. #define UNICODE
  5. #define _UNICODE
  6. #include "Database.h"
  7. #include "Common/DatException.h"
  8. #include "BinaryData.h"
  9. #include "Common/CommonFunctions.h"
  10. #include <cstring>
  11. namespace LOTRO_DAT {
  12. Database::Database() {
  13. db_ = nullptr;
  14. }
  15. Database::Database(const std::string &filename) {
  16. InitDatabase(filename.c_str());
  17. }
  18. Database::~Database() {
  19. ExecSql("COMMIT TRANSACTION");
  20. if (db_ != nullptr) {
  21. sqlite3_finalize(insert_request_);
  22. sqlite3_close(db_);
  23. }
  24. }
  25. void Database::InitDatabase(const std::string &filename) {
  26. if (sqlite3_open(filename.c_str(), &db_) != SQLITE_OK) {
  27. sqlite3_close(db_);
  28. throw DatException("Bad Database::InitDatabase() - sqlite3_open returned an error..."
  29. , DATABASE_EXCEPTION);
  30. }
  31. ExecSql("PRAGMA synchronous = OFF");
  32. ExecSql("PRAGMA count_changes = OFF");
  33. ExecSql("PRAGMA journal_mode = MEMORY");
  34. ExecSql("PRAGMA temp_store = MEMORY");
  35. ExecSql("PRAGMA encoding = \"UTF-8\";");
  36. ExecSql(CreateTableCommand_);
  37. sqlite3_prepare_v2(db_, InsertFileCommand_.c_str(), InsertFileCommand_.length(), &insert_request_, nullptr);
  38. ExecSql("BEGIN TRANSACTION");
  39. }
  40. void Database::ExecSql(const std::string &sql) {
  41. char *error;
  42. if (sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &error) != SQLITE_OK) {
  43. fprintf(stderr, "SQLite3 error: %s\n", sqlite3_errmsg(db_));
  44. throw DatException((std::string("Bad Database::ExecSql() - unable to perform request")
  45. + std::string(sql)).c_str(), DATABASE_EXCEPTION);
  46. }
  47. }
  48. void Database::PushFile(const BinaryData &binary_data, const std::u16string &text_data, const std::string &options) {
  49. sqlite3_bind_blob(insert_request_, 1, binary_data.data(), binary_data.size(), SQLITE_TRANSIENT);
  50. sqlite3_bind_text16(insert_request_, 2, text_data.c_str(), -1, SQLITE_TRANSIENT);
  51. sqlite3_bind_text(insert_request_, 3, options.c_str(), -1, SQLITE_TRANSIENT);
  52. if (sqlite3_step(insert_request_) != SQLITE_DONE) {
  53. fprintf(stderr, "SQLite3 error: %s\n", sqlite3_errmsg(db_));
  54. throw DatException((std::string("Bad Database::PushTextFile() - unable to perform push operation")).c_str(),
  55. DATABASE_EXCEPTION);
  56. }
  57. sqlite3_reset(insert_request_);
  58. }
  59. }