Additional layer of protection for unsafe saves

* Attempt to restore database, if that fails retain the temporary file and tell the user where it is located
This commit is contained in:
Jonathan White 2019-04-07 09:21:58 -04:00
parent 3b0b5d85e9
commit 791b796c23

View File

@ -251,11 +251,15 @@ bool Database::save(const QString& filePath, QString* error, bool atomic, bool b
tempFile.setAutoRemove(false); tempFile.setAutoRemove(false);
setFilePath(filePath); setFilePath(filePath);
return true; return true;
} else { } else if (!backup || !restoreDatabase(filePath)) {
// restore the database from the backup // Failed to copy new database in place, and
if (backup) { // failed to restore from backup or backups disabled
restoreDatabase(filePath); tempFile.setAutoRemove(false);
if (error) {
*error = tr("%1\nBackup database located at %2").arg(tempFile.errorString(), tempFile.fileName());
} }
markAsModified();
return false;
} }
} }
@ -338,8 +342,12 @@ bool Database::restoreDatabase(const QString& filePath)
auto match = re.match(filePath); auto match = re.match(filePath);
auto backupFilePath = match.captured(1) + ".old" + match.captured(2); auto backupFilePath = match.captured(1) + ".old" + match.captured(2);
QFile::remove(filePath); // Only try to restore if the backup file actually exists
return QFile::copy(backupFilePath, filePath); if (QFile::exists(backupFilePath)) {
QFile::remove(filePath);
return QFile::copy(backupFilePath, filePath);
}
return false;
} }
bool Database::isReadOnly() const bool Database::isReadOnly() const