Line data Source code
1 : #ifndef DB_H
2 : #define DB_H
3 :
4 : #include <QObject>
5 : #include <QString>
6 : #include <QDebug>
7 : #include <QSqlDatabase>
8 : #include <QSqlError>
9 : #include <QSqlQuery>
10 : #include <QFile>
11 :
12 : #include "../FangObject.h"
13 :
14 : /*!
15 : \brief Singleton database for DB.
16 : */
17 : class DB : public FangObject
18 : {
19 : Q_OBJECT
20 : public:
21 : explicit DB(QObject *parent = nullptr);
22 :
23 :
24 : signals:
25 :
26 : public slots:
27 :
28 : // Creates/returns singleton instance.
29 : static DB* instance();
30 :
31 118 : inline QSqlDatabase db() { return _db; }
32 :
33 : /*!
34 : \brief Initialize DB with an existing connection for testing.
35 : \param testDb The pre-configured database connection to use.
36 : */
37 : void initForTesting(QSqlDatabase testDb);
38 :
39 : /*!
40 : \brief Executes a simple DB query and logs error to debug.
41 : \param query
42 : \return
43 : */
44 : bool executeSimpleQuery(QString query);
45 :
46 : private:
47 : /*!
48 : \brief Performs DB init. Called by c'tor.
49 : */
50 : void init();
51 :
52 : /*!
53 : \brief Returns the version of our schema.
54 : Called by upgrade()
55 : \return 0 for no schema, 1 or greater for schema version.
56 : */
57 : int getSchemaVersion();
58 :
59 : /*!
60 : \brief Updates the version of the database.
61 : Called by upgrade()
62 : \param version 1..n
63 : */
64 : void setSchemaVersion(int version);
65 :
66 : /*!
67 : Creates and/or upgrades database, if necessary.
68 : Assumes "sql/[1..n].sql" files exist, where 1.sql creates the
69 : initial schema, and each version through n is run sequentially to
70 : update to version n.
71 : */
72 : void upgrade();
73 :
74 : /*!
75 : \brief Runs a SQL file on our database.
76 : \param sqlFile Text file containing SQL code.
77 : */
78 : bool executeSqlFile(QFile& sqlFile);
79 :
80 : // Static instance.
81 : static DB* _instance;
82 :
83 : // Database object.
84 : QSqlDatabase _db;
85 : };
86 :
87 :
88 : #endif // DB_H
|