source: src/orm/ormrecord.h @ 1006c4f

qt5
Last change on this file since 1006c4f was 4bf728f, checked in by Philipp Spitzer <philipp@…>, 11 years ago

Removed one comment and fixed typos.

  • Property mode set to 100644
File size: 5.7 KB
Line 
1/*
2 * Copyright (C) 2010 Ixonos Plc.
3 * Copyright (C) 2011 Philipp Spitzer, gregor herrmann
4 *
5 * This file is part of ConfClerk.
6 *
7 * ConfClerk is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the Free
9 * Software Foundation, either version 2 of the License, or (at your option)
10 * any later version.
11 *
12 * ConfClerk is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15 * more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * ConfClerk.  If not, see <http://www.gnu.org/licenses/>.
19 */
20#ifndef ORMRECORD_H
21#define ORMRECORD_H
22
23#include <QSqlQuery>
24#include <QSqlRecord>
25#include <QSqlField>
26#include <QSqlError>
27#include <QStringList>
28#include <QDateTime>
29#include <QDebug>
30
31class OrmException
32{
33public:
34    OrmException(const QString& text) : mText(text) {}
35    virtual ~OrmException(){}
36    virtual const QString& text() const { return mText; }
37private:
38    QString mText;
39};
40
41class OrmNoObjectException : public OrmException
42{
43public:
44    OrmNoObjectException() : OrmException("No object exception"){}
45    ~OrmNoObjectException(){}
46};
47
48class OrmSqlException : public OrmException
49{
50public:
51    OrmSqlException(const QString& text) : OrmException( QString("Sql error: ") + text ) {}
52    ~OrmSqlException(){}
53};
54
55template <typename T>
56class OrmRecord : protected QSqlRecord
57{
58public:
59    OrmRecord();
60    static T hydrate(const QSqlRecord& record);
61    void update(QString col, QVariant value = QVariant()); // updates specified column 'col'
62
63protected:
64    QVariant value(QString col) const;
65    void setValue(QString col, QVariant value);
66
67    static T loadOne(QSqlQuery query);
68    static QList<T> load(QSqlQuery query);
69
70    // auxiliary methods
71    static QSqlRecord toRecord(const QList<QSqlField> & columnList);
72    // all record items/columns are in one table
73    static QString columnsForSelect(const QString& prefix = QString());
74    static QString selectQuery();
75    static QString updateQuery();
76
77    static QVariant convertToC(QVariant value, QVariant::Type colType);
78    static QVariant convertToDb(QVariant value, QVariant::Type colType);
79};
80
81template <typename T>
82OrmRecord<T>::OrmRecord()
83{
84    QSqlRecord::operator=(T::sColumns);
85}
86
87template <typename T>
88T OrmRecord<T>::hydrate(const QSqlRecord& record)
89{
90    T object;
91    object.QSqlRecord::operator=(record);
92    return object;
93}
94
95// updates specified column 'col'
96// if the value is not specified as an argument,
97// it's taken from the record itself
98// see also: setValue() method for more details
99template <typename T>
100void OrmRecord<T>::update(QString col, QVariant value)
101{
102    QSqlQuery query;
103    query.prepare(QString(updateQuery() + "SET %1 = :col WHERE id = :id").arg(col));
104    if(value.isValid()) // take 'col' value from the method's arguments
105        query.bindValue(":col", value);
106    else // take 'col' value from the record; see setValue()
107        query.bindValue(":col", convertToDb(this->value(col), this->value(col).type()));
108    query.bindValue(":id", this->value("id"));
109    query.exec();
110}
111
112template <typename T>
113QVariant OrmRecord<T>::value(QString col) const
114{
115    return convertToC(QSqlRecord::value(col), T::sColumns.field(col).type());
116}
117
118template <typename T>
119void OrmRecord<T>::setValue(QString col, QVariant value)
120{
121    QSqlRecord::setValue(col, convertToDb(value, T::sColumns.field(col).type()));
122}
123
124template <typename T>
125T OrmRecord<T>::loadOne(QSqlQuery query)
126{
127    if (!query.isActive())
128    {
129        if (!query.exec())
130        {
131            throw OrmSqlException(query.lastError().text());
132        }
133    }
134
135    if (!query.next())
136    {
137        throw OrmNoObjectException();
138    }
139
140    return hydrate(query.record());
141}
142
143template <typename T>
144QList<T> OrmRecord<T>::load(QSqlQuery query)
145{
146    if (!query.isActive())
147    {
148        if (!query.exec())
149        {
150            qDebug() << "Error: " << query.lastError().driverText() << "; Type: " << query.lastError().type();
151            throw OrmSqlException(query.lastError().text());
152        }
153    }
154
155    QList<T> objects;
156    while (query.next())
157    {
158        objects << hydrate(query.record());
159    }
160    return objects;
161}
162
163template <typename T>
164QString OrmRecord<T>::columnsForSelect(const QString& prefix)
165{
166    QStringList prefixedColumns;
167    for (int i=0; i<T::sColumns.count(); i++)
168    {
169        prefixedColumns.append(prefix.isEmpty() ?
170            T::sColumns.field(i).name() :
171            QString("%1.%2").arg(prefix, T::sColumns.field(i).name()));
172    }
173    return prefixedColumns.join(",");
174}
175
176template <typename T>
177QString OrmRecord<T>::selectQuery()
178{
179    return QString("SELECT %1 FROM %2 ").arg(columnsForSelect(), T::sTableName);
180}
181
182template <typename T>
183QString OrmRecord<T>::updateQuery()
184{
185    return QString("UPDATE %1 ").arg(T::sTableName);
186}
187
188template <typename T>
189QSqlRecord OrmRecord<T>::toRecord(const QList<QSqlField> & columnList)
190{
191    QSqlRecord record;
192    for(int i=0; i< columnList.count(); i++)
193    {
194        record.append(columnList[i]);
195    }
196    return record;
197}
198
199template <typename T>
200QVariant OrmRecord<T>::convertToC(QVariant value, QVariant::Type colType)
201{
202    if (colType == QVariant::DateTime && value.canConvert<uint>())
203    {
204        QDateTime date;
205        date.setTimeSpec(Qt::UTC);
206        date.setTime_t(value.toUInt());
207        return date;
208    }
209
210    return value;
211}
212
213template <typename T>
214QVariant OrmRecord<T>::convertToDb(QVariant value, QVariant::Type colType)
215{
216    if (colType == QVariant::DateTime && value.canConvert<QDateTime>())
217    {
218        return value.toDateTime().toTime_t();
219    }
220
221    return value;
222}
223
224#endif // ORMRECORD_H
225
Note: See TracBrowser for help on using the repository browser.