summaryrefslogtreecommitdiff
path: root/src/components/utils/include/utils/sql_qt_wrapper/sql_database.h
blob: d12c4381d4968d6835ebbdbaa594c885e93f23d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQL_QT_WRAPPER_SQL_DATABASE
#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQL_QT_WRAPPER_SQL_DATABASE

#include <string>

#include <QtSql/QSqlDatabase>

#include "utils/lock.h"
#include "utils/sql_qt_wrapper/sql_error.h"

namespace utils {
namespace dbms {

/**
 * Represents a connection to a database.
 */
class SQLDatabase {
 public:
  SQLDatabase();
  SQLDatabase(const std::string& database_path,
              const std::string& connection_name);
  ~SQLDatabase();

  /**
   * Opens connection to the temporary in-memory database
   * @return true if successfully
   */
  bool Open();

  /**
   * Closes connection to the database
   */
  void Close();

  /**
   * Begins a transaction on the database
   * @return true if successfully
   */
  bool BeginTransaction();

  /**
   * Commits a transaction to the database
   * @return true if successfully
   */
  bool CommitTransaction();

  /**
   * Rolls back a transaction on the database
   * @return true if successfully
   */
  bool RollbackTransaction();

  /**
   * Gets information about the last error that occurred on the database
   * @return last error
   */
  SQLError LastError() const;

  /**
   * @brief HasErrors Indicate the status of the last executed operation.
   *
   * @return true in case last operation has any errors, false otherwise.
   */
  bool HasErrors() const;

  /**
   * @brief get_path databse location path.
   *
   * @return the path to the database location
   */
  std::string get_path() const;

  /**
   * Checks if database is read/write
   * @return true if database is read/write
   */
  bool IsReadWrite();

  /**
   * Call backup for opened DB
   */
  bool Backup();

  operator QSqlDatabase() const;

 private:
  QSqlDatabase db_;

  /**
   * The filename of database
   */
  const QString database_path_;

  /**
   * The database connection name
   */
  const QString connection_name_;

  /**
   * Lock for guarding connection to database
   */
  mutable sync_primitives::Lock conn_lock_;
};

}  // namespace dbms
}  // namespace utils

#endif  // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQL_QT_WRAPPER_SQL_DATABASE