| 177 | } |
| 178 | |
| 179 | bool DBManager::updateRecord(const VectorPair& conditions, const QVariantMap& columns) const |
| 180 | { |
| 181 | if (_readonlyMode) |
| 182 | { |
| 183 | return false; |
| 184 | } |
| 185 | |
| 186 | SqlDatabase* idb = getDB(); |
| 187 | if (idb->transaction()) |
| 188 | { |
| 189 | |
| 190 | SqlQuery query(idb); |
| 191 | |
| 192 | QVariantList values; |
| 193 | QStringList prep; |
| 194 | |
| 195 | // prepare columns valus |
| 196 | QVariantMap::const_iterator i = columns.constBegin(); |
| 197 | while (i != columns.constEnd()) { |
| 198 | prep += i.key() + "=?"; |
| 199 | values += i.value(); |
| 200 | |
| 201 | ++i; |
| 202 | } |
| 203 | |
| 204 | // prepare condition values |
| 205 | QStringList prepCond; |
| 206 | QVariantList prepBindVal; |
| 207 | if (!conditions.isEmpty()) |
| 208 | prepCond << "WHERE"; |
| 209 | |
| 210 | for (const auto& pair : conditions) |
| 211 | { |
| 212 | prepCond << pair.first + "=?"; |
| 213 | prepBindVal << pair.second; |
| 214 | } |
| 215 | |
| 216 | query.prepare(QString("UPDATE %1 SET %2 %3").arg(_table, prep.join(", ")).arg(prepCond.join(" "))); |
| 217 | // add column values |
| 218 | doAddBindValue(query, values); |
| 219 | // add condition values |
| 220 | doAddBindValue(query, prepBindVal); |
| 221 | if (!query.exec()) |
| 222 | { |
| 223 | Error(_log, "Failed to update record: '%s' in table: '%s' Error: %s", QSTRING_CSTR(prepCond.join(" ")), QSTRING_CSTR(_table), QSTRING_CSTR(idb->error())); |
| 224 | idb->rollback(); |
| 225 | return false; |
| 226 | } |
| 227 | } |
| 228 | else |
| 229 | { |
| 230 | Error(_log, "Could not create a DB transaction. Error: %s", QSTRING_CSTR(idb->error())); |
| 231 | return false; |
| 232 | } |
| 233 | |
| 234 | if (!idb->commit()) |
| 235 | { |
| 236 | Error(_log, "Could not commit the DB transaction. Error: %s", QSTRING_CSTR(idb->error())); |