bump version after release.
[toast/confclerk.git] / src / orm / ormrecord.h
1 /*
2  * Copyright (C) 2010 Ixonos Plc.
3  * Copyright (C) 2011-2021 Philipp Spitzer, gregor herrmann, Stefan Stahl
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 #include <stdexcept>
31
32 class OrmException: public std::runtime_error
33 {
34 public:
35     OrmException(const QString& text) : std::runtime_error(text.toStdString()), mText(text) {}
36     virtual ~OrmException() throw() {}
37     virtual const QString& text() const { return mText; }
38 private:
39     QString mText;
40 };
41
42 class OrmNoObjectException : public OrmException
43 {
44 public:
45     OrmNoObjectException() : OrmException("SQL query expects one record but found none."){}
46     ~OrmNoObjectException() throw() {}
47 };
48
49 class OrmSqlException : public OrmException
50 {
51 public:
52     OrmSqlException(const QString& text) : OrmException( QString("Sql error: ") + text ) {}
53     ~OrmSqlException() throw() {}
54 };
55
56 template <typename T>
57 class OrmRecord : protected QSqlRecord
58 {
59 public:
60     OrmRecord();
61     static T hydrate(const QSqlRecord& record);
62     void update(QString col, QVariant value = QVariant()); // updates specified column 'col'
63
64 protected:
65     QVariant value(QString col) const;
66     void setValue(QString col, QVariant value);
67
68     static T loadOne(QSqlQuery query);
69     static QList<T> load(QSqlQuery query);
70
71     // auxiliary methods
72     static QSqlRecord toRecord(const QList<QSqlField> & columnList);
73     // all record items/columns are in one table
74     static QString columnsForSelect(const QString& prefix = QString());
75     static QString selectQuery();
76     static QString updateQuery();
77
78     static QVariant convertToC(QVariant value, QVariant::Type colType);
79     static QVariant convertToDb(QVariant value, QVariant::Type colType);
80 };
81
82 template <typename T>
83 OrmRecord<T>::OrmRecord()
84 {
85     QSqlRecord::operator=(T::sColumns);
86 }
87
88 template <typename T>
89 T OrmRecord<T>::hydrate(const QSqlRecord& record)
90 {
91     T object;
92     object.QSqlRecord::operator=(record);
93     return object;
94 }
95
96 // updates specified column 'col'
97 // if the value is not specified as an argument,
98 // it's taken from the record itself
99 // see also: setValue() method for more details
100 template <typename T>
101 void OrmRecord<T>::update(QString col, QVariant value)
102 {
103     QSqlQuery query;
104     query.prepare(QString(updateQuery() + "SET %1 = :col WHERE id = :id").arg(col));
105     if(value.isValid()) // take 'col' value from the method's arguments
106         query.bindValue(":col", value);
107     else // take 'col' value from the record; see setValue()
108         query.bindValue(":col", convertToDb(this->value(col), this->value(col).type()));
109     query.bindValue(":id", this->value("id"));
110     query.exec();
111 }
112
113 template <typename T>
114 QVariant OrmRecord<T>::value(QString col) const
115 {
116     return convertToC(QSqlRecord::value(col), T::sColumns.field(col).type());
117 }
118
119 template <typename T>
120 void OrmRecord<T>::setValue(QString col, QVariant value)
121 {
122     QSqlRecord::setValue(col, convertToDb(value, T::sColumns.field(col).type()));
123 }
124
125 template <typename T>
126 T OrmRecord<T>::loadOne(QSqlQuery query)
127 {
128     if (!query.isActive())
129     {
130         if (!query.exec())
131         {
132             throw OrmSqlException(query.lastError().text());
133         }
134     }
135
136     if (!query.next())
137     {
138         throw OrmNoObjectException();
139     }
140
141     return hydrate(query.record());
142 }
143
144 template <typename T>
145 QList<T> OrmRecord<T>::load(QSqlQuery query)
146 {
147     if (!query.isActive())
148     {
149         if (!query.exec())
150         {
151             qDebug() << "Error: " << query.lastError().driverText() << "; Type: " << query.lastError().type();
152             throw OrmSqlException(query.lastError().text());
153         }
154     }
155
156     QList<T> objects;
157     while (query.next())
158     {
159         objects << hydrate(query.record());
160     }
161     return objects;
162 }
163
164 template <typename T>
165 QString OrmRecord<T>::columnsForSelect(const QString& prefix)
166 {
167     QStringList prefixedColumns;
168     for (int i=0; i<T::sColumns.count(); i++)
169     {
170         prefixedColumns.append(prefix.isEmpty() ?
171             T::sColumns.field(i).name() :
172             QString("%1.%2").arg(prefix, T::sColumns.field(i).name()));
173     }
174     return prefixedColumns.join(",");
175 }
176
177 template <typename T>
178 QString OrmRecord<T>::selectQuery()
179 {
180     return QString("SELECT %1 FROM %2 ").arg(columnsForSelect(), T::sTableName);
181 }
182
183 template <typename T>
184 QString OrmRecord<T>::updateQuery()
185 {
186     return QString("UPDATE %1 ").arg(T::sTableName);
187 }
188
189 template <typename T>
190 QSqlRecord OrmRecord<T>::toRecord(const QList<QSqlField> & columnList)
191 {
192     QSqlRecord record;
193     for(int i=0; i< columnList.count(); i++)
194     {
195         record.append(columnList[i]);
196     }
197     return record;
198 }
199
200 template <typename T>
201 QVariant OrmRecord<T>::convertToC(QVariant value, QVariant::Type colType)
202 {
203     if (colType == QVariant::DateTime && value.canConvert<uint>())
204     {
205         QDateTime date;
206         date.setTimeSpec(Qt::UTC);
207         date.setTime_t(value.toUInt());
208         return date;
209     }
210
211     return value;
212 }
213
214 template <typename T>
215 QVariant OrmRecord<T>::convertToDb(QVariant value, QVariant::Type colType)
216 {
217     if (colType == QVariant::DateTime && value.canConvert<QDateTime>())
218     {
219         QDateTime dateTime = value.toDateTime();
220         dateTime.setTimeSpec(Qt::UTC); // this is to avoid that dateTime.toTime_t changes the time depending on the local time zone
221         return dateTime.toTime_t();
222     }
223
224     return value;
225 }
226
227 #endif // ORMRECORD_H
228