Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a database upgrade system, use it to fix v12 db #107

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Jellyfin.Plugin.KodiSyncQueue/Data/DbRepo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public DbRepo(string dPath, ILogger<DbRepo> logger)
Directory.CreateDirectory(dPath);
_liteDb = new LiteDatabase($"filename={dPath}/kodisyncqueue.db;mode=exclusive;upgrade=true");
_jsonSerializerOptions = JsonDefaults.Options;
UpgradeDatabase();
}

public List<Guid> GetItems(long dtl, ItemStatus status, IReadOnlyCollection<MediaType> filters)
Expand Down Expand Up @@ -211,5 +212,47 @@ protected virtual void Dispose(bool disposing)
_liteDb?.Dispose();
}
}

private void UpgradeDatabase()
{
switch (_liteDb.UserVersion)
{
// v12 changed the UserInfoRec.ItemId from a string to a Guid.
// v13 changed it back to a string. Any media added with v12
// now has the wrong type in the database.
case 0:
UpgradeDatabaseCollection(UserInfoCollection, (document) =>
{
// Since this is the first upgrader, the database could be from v11 or older
// where ItemId is the correct type. If it is, return as-is.
return (document["ItemId"].RawValue is Guid)
? ("ItemId", new BsonValue(document["ItemId"].AsGuid.ToString("N", CultureInfo.InvariantCulture)))
: ("ItemId", document["ItemId"]);
});
break;

default: return;
}

_liteDb.UserVersion++;
UpgradeDatabase();
}

// https://github.com/litedb-org/LiteDB/issues/1901#issuecomment-748449599
private void UpgradeDatabaseCollection(string name, params Func<BsonDocument, (string, BsonValue)>[] migrateFunctions)
{
var collection = _liteDb.GetCollection(name);
var documents = collection.FindAll().ToList();
foreach (var document in documents)
{
foreach (var func in migrateFunctions)
{
var (key, value) = func(document);
collection.Delete(document[key]);
document[key] = value;
collection.Insert(document);
}
}
}
}
}