source: src/orm/ormrecord.h @ 28d9e28

qt5
Last change on this file since 28d9e28 was 27102d5, checked in by fortefr <fortefr@…>, 12 years ago

Temporal virtual_event change

  • Property mode set to 100644
File size: 6.4 KB
Line 
1#ifndef ORMRECORD_H
2#define ORMRECORD_H
3
4#include <QSqlQuery>
5#include <QSqlRecord>
6#include <QSqlField>
7#include <QSqlError>
8#include <QStringList>
9#include <QDateTime>
10#include <QDebug>
11
12// INFO:
13// all record items/columns may be defined in one table (1.), or
14// they can be splitted in two separate tables (2.) (eg. for FTS support)
15// 1.) you have to define "static QString const sTableName"
16// 2.) you have to define two table names:
17//     "static QString const sTable1Name"
18//     "static QString const sTable2Name"
19// and since all record items/columns are handled by one QSqlRecord,
20// you have to also define number of columns that belongs to table 1 (1.), and table 2 (2.)
21// 1.) "static int const sTable1ColCount"
22// 2.) "static int const sTable2ColCount"
23// there are also defined auxiliary methods for 1-Table/2-Tables approach, see bellow
24
25class OrmException
26{
27};
28
29class OrmNoObjectException : OrmException
30{
31};
32
33class OrmSqlException : OrmException
34{
35public:
36    OrmSqlException(const QString& text) : mText(text) {}
37    QString text() const { return mText; }
38
39private:
40    QString mText;
41};
42
43template <typename T>
44class OrmRecord : protected QSqlRecord
45{
46public:
47    OrmRecord();
48    static T hydrate(const QSqlRecord& record);
49    void update(QString col, QVariant value = QVariant()); // updates specified column 'col'
50
51protected:
52    QVariant value(QString col) const;
53    void setValue(QString col, QVariant value);
54
55    static T loadOne(QSqlQuery query);
56    static QList<T> load(QSqlQuery query);
57
58    // auxiliary methods
59    static QSqlRecord toRecord(const QList<QSqlField> & columnList);
60    // all record items/columns are in one table
61    static QString columnsForSelect(const QString& prefix = QString());
62    static QString selectQuery();
63    static QString updateQuery();
64    // record items/columns are stored in two tables
65    static QString columnsForSelectJoin2T(); // for joining two tables
66    static QString selectQueryJoin2T(const QString &key); // for joining two tables
67
68    static QVariant convertToC(QVariant value, QVariant::Type colType);
69    static QVariant convertToDb(QVariant value, QVariant::Type colType);
70};
71
72template <typename T>
73OrmRecord<T>::OrmRecord()
74{
75    QSqlRecord::operator=(T::sColumns);
76}
77
78template <typename T>
79T OrmRecord<T>::hydrate(const QSqlRecord& record)
80{
81    T object;
82    object.QSqlRecord::operator=(record);
83    return object;
84}
85
86// updates specified column 'col'
87// if the value is not specified  as an argument,
88// it's taken from the reford itself
89// see also: setValue() method for more details
90template <typename T>
91void OrmRecord<T>::update(QString col, QVariant value)
92{
93    QSqlQuery query;
94    query.prepare(QString(updateQuery() + "SET %1 = :col WHERE id = :id").arg(col));
95    if(value.isValid()) // take 'col' value from the method's arguments
96        query.bindValue(":col", value);
97    else // take 'col' value from the record; see setValue()
98        query.bindValue(":col", convertToDb(this->value(col), this->value(col).type()));
99    query.bindValue(":id", this->value("id"));
100    //query.bindValue(":id", convertToDb(value("id"), QVariant::Int));
101    query.exec();
102}
103
104template <typename T>
105QVariant OrmRecord<T>::value(QString col) const
106{
107    return convertToC(QSqlRecord::value(col), T::sColumns.field(col).type());
108}
109
110template <typename T>
111void OrmRecord<T>::setValue(QString col, QVariant value)
112{
113    QSqlRecord::setValue(col, convertToDb(value, T::sColumns.field(col).type()));
114}
115
116template <typename T>
117T OrmRecord<T>::loadOne(QSqlQuery query)
118{
119    if (!query.isActive())
120    {
121        if (!query.exec())
122        {
123            throw new OrmSqlException(query.lastError().text());
124        }
125    }
126
127    if (!query.next())
128    {
129        throw new OrmNoObjectException();
130    }
131
132    return hydrate(query.record());
133}
134
135template <typename T>
136QList<T> OrmRecord<T>::load(QSqlQuery query)
137{
138    if (!query.isActive())
139    {
140        if (!query.exec())
141        {
142            throw new OrmSqlException(query.lastError().text());
143        }
144    }
145
146    QList<T> objects;
147    while (query.next())
148    {
149        objects << hydrate(query.record());
150    }
151
152    return objects;
153}
154
155template <typename T>
156QString OrmRecord<T>::columnsForSelect(const QString& prefix)
157{
158    QStringList prefixedColumns;
159    for (int i=0; i<T::sColumns.count(); i++)
160    {
161        prefixedColumns.append(prefix.isEmpty() ?
162            T::sColumns.field(i).name() :
163            QString("%1.%2").arg(prefix, T::sColumns.field(i).name()));
164    }
165    return prefixedColumns.join(",");
166}
167
168template <typename T>
169QString OrmRecord<T>::columnsForSelectJoin2T()
170{
171    Q_ASSERT((T::sTable1ColCount+T::sTable2ColCount) == T::sColumns.count());
172
173    QStringList prefixedColumns;
174    for (int i=0; i<T::sTable1ColCount; i++)
175    {
176        prefixedColumns.append(QString("%1.%2").arg(T::sTable1Name, T::sColumns.field(i).name()));
177    }
178    for (int j=0; j<T::sTable2ColCount; j++)
179    {
180        prefixedColumns.append(QString("%1.%2").arg(T::sTable2Name, T::sColumns.field(T::sTable1ColCount+j).name()));
181    }
182    return prefixedColumns.join(",");
183}
184
185template <typename T>
186QString OrmRecord<T>::selectQuery()
187{
188    return QString("SELECT %1 FROM %2 ").arg(columnsForSelect(), T::sTableName);
189}
190
191
192template <typename T>
193QString OrmRecord<T>::selectQueryJoin2T(const QString &key)
194{
195    return QString("SELECT %1 FROM %2 INNER JOIN %3 ON %4.%5 = %6.%7 ").arg(
196            columnsForSelectJoin2T(),
197            T::sTable1Name,
198            T::sTable2Name,
199            T::sTable1Name,
200            key,
201            T::sTable2Name,
202            key);
203}
204
205template <typename T>
206QString OrmRecord<T>::updateQuery()
207{
208    return QString("UPDATE %1 ").arg(T::sTable1Name);
209}
210
211template <typename T>
212QSqlRecord OrmRecord<T>::toRecord(const QList<QSqlField> & columnList)
213{
214    QSqlRecord record;
215    foreach (const QSqlField & col, columnList)
216    {
217        record.append(col);
218    }
219    return record;
220}
221
222template <typename T>
223QVariant OrmRecord<T>::convertToC(QVariant value, QVariant::Type colType)
224{
225    if (colType == QVariant::DateTime && value.canConvert<uint>())
226    {
227        QDateTime date;
228        date.setTimeSpec(Qt::UTC);
229        date.setTime_t(value.toUInt());
230        return date;
231    }
232
233    return value;
234}
235
236template <typename T>
237QVariant OrmRecord<T>::convertToDb(QVariant value, QVariant::Type colType)
238{
239    if (colType == QVariant::DateTime && value.canConvert<QDateTime>())
240    {
241        return value.toDateTime().toTime_t();
242    }
243
244    return value;
245}
246
247#endif // ORMRECORD_H
248
Note: See TracBrowser for help on using the repository browser.