< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.MigrateLibraryUserData
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateLibraryUserData.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 58
Coverable lines: 58
Total lines: 123
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 14
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 1/23/2026 - 12:11:06 AM Line coverage: 0% (0/4) Total lines: 1234/19/2026 - 12:14:27 AM Line coverage: 0% (0/58) Branch coverage: 0% (0/14) Total lines: 123 4/19/2026 - 12:14:27 AM Line coverage: 0% (0/58) Branch coverage: 0% (0/14) Total lines: 123

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
PerformAsync()0%210140%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/MigrateLibraryUserData.cs

#LineLine coverage
 1#pragma warning disable RS0030 // Do not use banned APIs
 2
 3using System;
 4using System.Collections.Generic;
 5using System.IO;
 6using System.Linq;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using Emby.Server.Implementations.Data;
 10using Jellyfin.Database.Implementations;
 11using Jellyfin.Database.Implementations.Entities;
 12using Jellyfin.Server.Implementations.Item;
 13using Jellyfin.Server.ServerSetupApp;
 14using MediaBrowser.Controller;
 15using Microsoft.Data.Sqlite;
 16using Microsoft.EntityFrameworkCore;
 17using Microsoft.Extensions.Logging;
 18
 19namespace Jellyfin.Server.Migrations.Routines;
 20
 21[JellyfinMigration("2025-06-18T01:00:00", nameof(MigrateLibraryUserData))]
 22[JellyfinMigrationBackup(JellyfinDb = true)]
 23internal class MigrateLibraryUserData : IAsyncMigrationRoutine
 24{
 25    private const string DbFilename = "library.db.old";
 26
 27    private readonly IStartupLogger _logger;
 28    private readonly IServerApplicationPaths _paths;
 29    private readonly IDbContextFactory<JellyfinDbContext> _provider;
 30
 31    public MigrateLibraryUserData(
 32            IStartupLogger<MigrateLibraryDb> startupLogger,
 33            IDbContextFactory<JellyfinDbContext> provider,
 34            IServerApplicationPaths paths)
 35    {
 036        _logger = startupLogger;
 037        _provider = provider;
 038        _paths = paths;
 039    }
 40
 41    public async Task PerformAsync(CancellationToken cancellationToken)
 42    {
 043        _logger.LogInformation("Migrating the userdata from library.db.old may take a while, do not stop Jellyfin.");
 44
 045        var dataPath = _paths.DataPath;
 046        var libraryDbPath = Path.Combine(dataPath, DbFilename);
 047        if (!File.Exists(libraryDbPath))
 48        {
 049            _logger.LogError("Cannot migrate userdata from {LibraryDb} as it does not exist. This migration expects the 
 050            return;
 51        }
 52
 053        var dbContext = await _provider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
 054        await using (dbContext.ConfigureAwait(false))
 55        {
 056            if (!await dbContext.BaseItems.AnyAsync(e => e.Id == BaseItemRepository.PlaceholderId, cancellationToken).Co
 57            {
 58                // the placeholder baseitem has been deleted by the librarydb migration so we need to readd it.
 059                await dbContext.BaseItems.AddAsync(
 060                    new Database.Implementations.Entities.BaseItemEntity()
 061                    {
 062                        Id = BaseItemRepository.PlaceholderId,
 063                        Type = "PLACEHOLDER",
 064                        Name = "This is a placeholder item for UserData that has been detacted from its original item"
 065                    },
 066                    cancellationToken)
 067                    .ConfigureAwait(false);
 068                await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
 69            }
 70
 071            var users = dbContext.Users.AsNoTracking().ToArray();
 072            var userIdBlacklist = new HashSet<int>();
 073            using var connection = new SqliteConnection($"Filename={libraryDbPath};Mode=ReadOnly");
 074            var retentionDate = DateTime.UtcNow;
 75
 076            var queryResult = connection.Query(
 077"""
 078    SELECT key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, 
 079
 080    WHERE NOT EXISTS(SELECT 1 FROM TypedBaseItems WHERE TypedBaseItems.UserDataKey = UserDatas.key)
 081""");
 82
 083            var importedUserData = new Dictionary<Guid, List<UserData>>();
 084            foreach (var entity in queryResult)
 85            {
 086                var userData = MigrateLibraryDb.GetUserData(users, entity, userIdBlacklist, _logger);
 087                if (userData is null)
 88                {
 089                    var userDataId = entity.GetString(0);
 090                    var internalUserId = entity.GetInt32(1);
 91
 092                    if (!userIdBlacklist.Contains(internalUserId))
 93                    {
 094                        _logger.LogError("Was not able to migrate user data with key {0} because its id {InternalId} doe
 095                        userIdBlacklist.Add(internalUserId);
 96                    }
 97
 098                    continue;
 99                }
 100
 0101                var ogId = userData.ItemId;
 0102                userData.ItemId = BaseItemRepository.PlaceholderId;
 0103                userData.RetentionDate = retentionDate;
 0104                if (!importedUserData.TryGetValue(ogId, out var importUserData))
 105                {
 0106                    importUserData = [];
 0107                    importedUserData[ogId] = importUserData;
 108                }
 109
 0110                importUserData.Add(userData);
 111            }
 112
 0113            foreach (var item in importedUserData)
 114            {
 0115                await dbContext.UserData.Where(e => e.ItemId == item.Key).ExecuteDeleteAsync(cancellationToken).Configur
 0116                dbContext.UserData.AddRange(item.Value.DistinctBy(e => e.CustomDataKey)); // old userdata can have fucke
 0117            }
 118
 0119            _logger.LogInformation("Try saving {NewSaved} UserData entries.", dbContext.UserData.Local.Count);
 0120            await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
 0121        }
 0122    }
 123}