mbdavid/LiteDB

[BUG] Rebuild function never deletes the previous database backup

michelebastione opened this issue · 4 comments

Version
5.0.18, 5.0.19

Describe the bug
Every time the LiteEngine.Rebuild method is called the database's contents are copied in a brand new backup file named with an incremental numerical suffix. The previous backup file is never deleted and all the copies just keep accumulating on disk.

Code to Reproduce
using var db = new LiteDatabase("Filename=TestDB"); db.Rebuild();

Expected behavior
There should always be only one backup copy of the database on disk while the previous one should be deleted during the Rebuild process, otherwise all these redundant copies will end up occupying precious disk storage, especially if the database size is significant.

Screenshots/Stacktrace
Result of running the example snippet a few times.

Additional context
I believe this happens because of the way the backupFilename is assigned in the RebuildService.Rebuild method:
var backupFilename = FileHelper.GetSuffixFile(_settings.Filename, "-backup", true);
The checkIfExists parameter sohuld not be set to true, as it will trigger the suffix to increment. Instead a check on the existence of the backup and its potential deletion could be performed before creating the new one. This, at least for me, seemed to solve the issue:

FileHelper.Exec(5, () =>
{
    if (File.Exists(backupFilename))
    {
        File.Delete(backupFilename);
    }
    File.Move(_settings.Filename, backupFilename);
});