source: src/orm/ormrecord.h @ 72cd3af

qt5
Last change on this file since 72cd3af was 72cd3af, checked in by korrco <korrco@…>, 12 years ago

activities tab implemented

  • Property mode set to 100644
File size: 6.6 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 OrmSqlException(query.lastError().text());
124        }
125    }
126
127    if (!query.next())
128    {
129        throw 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            qDebug() << "Error: " << query.lastError().driverText() << "; Type: " << query.lastError().type();
143            throw OrmSqlException(query.lastError().text());
144        }
145        else
146        {
147            qDebug() << "SQL OK";
148        }
149    }
150
151    QList<T> objects;
152    while (query.next())
153    {
154        objects << hydrate(query.record());
155    }
156    qDebug() << "Fetch done";
157    return objects;
158}
159
160template <typename T>
161QString OrmRecord<T>::columnsForSelect(const QString& prefix)
162{
163    QStringList prefixedColumns;
164    for (int i=0; i<T::sColumns.count(); i++)
165    {
166        prefixedColumns.append(prefix.isEmpty() ?
167            T::sColumns.field(i).name() :
168            QString("%1.%2").arg(prefix, T::sColumns.field(i).name()));
169    }
170    return prefixedColumns.join(",");
171}
172
173template <typename T>
174QString OrmRecord<T>::columnsForSelectJoin2T()
175{
176    Q_ASSERT((T::sTable1ColCount+T::sTable2ColCount) == T::sColumns.count());
177
178    QStringList prefixedColumns;
179    for (int i=0; i<T::sTable1ColCount; i++)
180    {
181        prefixedColumns.append(QString("%1.%2").arg(T::sTable1Name, T::sColumns.field(i).name()));
182    }
183    for (int j=0; j<T::sTable2ColCount; j++)
184    {
185        prefixedColumns.append(QString("%1.%2").arg(T::sTable2Name, T::sColumns.field(T::sTable1ColCount+j).name()));
186    }
187    return prefixedColumns.join(",");
188}
189
190template <typename T>
191QString OrmRecord<T>::selectQuery()
192{
193    return QString("SELECT %1 FROM %2 ").arg(columnsForSelect(), T::sTableName);
194}
195
196
197template <typename T>
198QString OrmRecord<T>::selectQueryJoin2T(const QString &key)
199{
200    return QString("SELECT %1 FROM %2 INNER JOIN %3 ON %4.%5 = %6.%7 ").arg(
201            columnsForSelectJoin2T(),
202            T::sTable1Name,
203            T::sTable2Name,
204            T::sTable1Name,
205            key,
206            T::sTable2Name,
207            key);
208}
209
210template <typename T>
211QString OrmRecord<T>::updateQuery()
212{
213    return QString("UPDATE %1 ").arg(T::sTable1Name);
214}
215
216template <typename T>
217QSqlRecord OrmRecord<T>::toRecord(const QList<QSqlField> & columnList)
218{
219    QSqlRecord record;
220    foreach (const QSqlField & col, columnList)
221    {
222        record.append(col);
223    }
224    return record;
225}
226
227template <typename T>
228QVariant OrmRecord<T>::convertToC(QVariant value, QVariant::Type colType)
229{
230    if (colType == QVariant::DateTime && value.canConvert<uint>())
231    {
232        QDateTime date;
233        date.setTimeSpec(Qt::UTC);
234        date.setTime_t(value.toUInt());
235        return date;
236    }
237
238    return value;
239}
240
241template <typename T>
242QVariant OrmRecord<T>::convertToDb(QVariant value, QVariant::Type colType)
243{
244    if (colType == QVariant::DateTime && value.canConvert<QDateTime>())
245    {
246        return value.toDateTime().toTime_t();
247    }
248
249    return value;
250}
251
252#endif // ORMRECORD_H
253
Note: See TracBrowser for help on using the repository browser.