< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.JellyfinMigrationService
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/JellyfinMigrationService.cs
Line coverage
51%
Covered lines: 142
Uncovered lines: 136
Coverable lines: 278
Total lines: 547
Line coverage: 51%
Branch coverage
40%
Covered branches: 46
Total branches: 114
Branch coverage: 40.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 41.9% (102/243) Branch coverage: 25.5% (25/98) Total lines: 4646/28/2026 - 12:15:35 AM Line coverage: 42.4% (104/245) Branch coverage: 25.5% (25/98) Total lines: 4678/2/2026 - 12:17:28 AM Line coverage: 43.2% (108/250) Branch coverage: 26% (26/100) Total lines: 48510/29/2026 - 12:17:11 AM Line coverage: 51% (142/278) Branch coverage: 40.3% (46/114) Total lines: 54911/13/2026 - 12:19:51 AM Line coverage: 51% (142/278) Branch coverage: 40.3% (46/114) Total lines: 547 5/31/2026 - 12:15:44 AM Line coverage: 41.9% (102/243) Branch coverage: 25.5% (25/98) Total lines: 4646/28/2026 - 12:15:35 AM Line coverage: 42.4% (104/245) Branch coverage: 25.5% (25/98) Total lines: 4678/2/2026 - 12:17:28 AM Line coverage: 43.2% (108/250) Branch coverage: 26% (26/100) Total lines: 48510/29/2026 - 12:17:11 AM Line coverage: 51% (142/278) Branch coverage: 40.3% (46/114) Total lines: 54911/13/2026 - 12:19:51 AM Line coverage: 51% (142/278) Branch coverage: 40.3% (46/114) Total lines: 547

Coverage delta

Coverage delta 15 -15

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%22100%
CheckFirstTimeRunOrMigration()73.07%812656.71%
EnsureExistingDatabaseAsync()90%1010100%
MigrateStepAsync()47.05%1313456.25%
GetJellyfinVersion()100%11100%
CleanupSystemAfterMigration()0%210140%
PrepareSystemForMigration()0%342180%
MergeBackupAttributes(...)0%110100%
.ctor(...)100%11100%
PerformAsync()100%11100%
.ctor(...)100%11100%
PerformAsync()100%11100%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/JellyfinMigrationService.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.IO;
 5using System.Linq;
 6using System.Reflection;
 7using System.Threading;
 8using System.Threading.Tasks;
 9using Emby.Server.Implementations.Serialization;
 10using Jellyfin.Database.Implementations;
 11using Jellyfin.Server.Implementations.SystemBackupService;
 12using Jellyfin.Server.Migrations.Stages;
 13using Jellyfin.Server.ServerSetupApp;
 14using MediaBrowser.Common.Configuration;
 15using MediaBrowser.Controller.SystemBackupService;
 16using MediaBrowser.Model.Configuration;
 17using Microsoft.EntityFrameworkCore;
 18using Microsoft.EntityFrameworkCore.Infrastructure;
 19using Microsoft.EntityFrameworkCore.Migrations;
 20using Microsoft.EntityFrameworkCore.Storage;
 21using Microsoft.Extensions.Logging;
 22
 23namespace Jellyfin.Server.Migrations;
 24
 25/// <summary>
 26/// Handles Migration of the Jellyfin data structure.
 27/// </summary>
 28internal class JellyfinMigrationService
 29{
 30    private const string DbFilename = "library.db";
 31    private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory;
 32    private readonly ILoggerFactory _loggerFactory;
 33    private readonly IStartupLogger _startupLogger;
 34    private readonly IBackupService? _backupService;
 35    private readonly IJellyfinDatabaseProvider? _jellyfinDatabaseProvider;
 36    private readonly IApplicationPaths _applicationPaths;
 37    private (string? LibraryDb, string? JellyfinDb, BackupManifestDto? FullBackup) _backupKey;
 38
 39    /// <summary>
 40    /// Initializes a new instance of the <see cref="JellyfinMigrationService"/> class.
 41    /// </summary>
 42    /// <param name="dbContextFactory">Provides access to the jellyfin database.</param>
 43    /// <param name="loggerFactory">The logger factory.</param>
 44    /// <param name="startupLogger">The startup logger for Startup UI intigration.</param>
 45    /// <param name="applicationPaths">Application paths for library.db backup.</param>
 46    /// <param name="backupService">The jellyfin backup service.</param>
 47    /// <param name="jellyfinDatabaseProvider">The jellyfin database provider.</param>
 48    public JellyfinMigrationService(
 49        IDbContextFactory<JellyfinDbContext> dbContextFactory,
 50        ILoggerFactory loggerFactory,
 51        IStartupLogger<JellyfinMigrationService> startupLogger,
 52        IApplicationPaths applicationPaths,
 53        IBackupService? backupService = null,
 54        IJellyfinDatabaseProvider? jellyfinDatabaseProvider = null)
 55    {
 9056        _dbContextFactory = dbContextFactory;
 9057        _loggerFactory = loggerFactory;
 9058        _startupLogger = startupLogger;
 9059        _backupService = backupService;
 9060        _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
 9061        _applicationPaths = applicationPaths;
 9062        Migrations = [.. typeof(IAsyncMigrationRoutine).Assembly.GetTypes().Where(e => typeof(IAsyncMigrationRoutine).Is
 9063            .Select(e => (Type: e, Metadata: e.GetCustomAttribute<JellyfinMigrationAttribute>(), Backup: e.GetCustomAttr
 9064            .Where(e => e.Metadata is not null)
 9065            .GroupBy(e => e.Metadata!.Stage)
 9066            .Select(f =>
 9067            {
 9068                var stage = new MigrationStage(f.Key);
 9069                foreach (var item in f)
 9070                {
 9071                    JellyfinMigrationBackupAttribute? backupMetadata = null;
 9072                    if (item.Backup?.Any() == true)
 9073                    {
 9074                        backupMetadata = item.Backup.Aggregate(MergeBackupAttributes);
 9075                    }
 9076
 9077                    stage.Add(new(item.Type, item.Metadata!, backupMetadata));
 9078                }
 9079
 9080                return stage;
 9081            })];
 9082    }
 83
 84    private interface IInternalMigration
 85    {
 86        Task PerformAsync(IStartupLogger logger);
 87    }
 88
 89    private HashSet<MigrationStage> Migrations { get; set; }
 90
 91    public async Task CheckFirstTimeRunOrMigration(IApplicationPaths appPaths, StartupOptions startupOptions)
 92    {
 3693        var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migration
 3694        logger.LogInformation("Initialise Migration service.");
 3695        var xmlSerializer = new MyXmlSerializer();
 3696        var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
 3697            ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigu
 3698            : new ServerConfiguration();
 3699        if (!serverConfig.IsStartupWizardCompleted || startupOptions.StartupMode is Configuration.StartupMode.SeedSystem
 100        {
 29101            logger.LogInformation("System initialization detected. Seed data. Startup mode is: {StartupMode}", startupOp
 29102            var flatApplyMigrations = Migrations.SelectMany(e => e.Where(f => !f.Metadata.RunMigrationOnSetup)).ToArray(
 103
 29104            var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 29105            await using (dbContext.ConfigureAwait(false))
 106            {
 29107                var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator
 29108                    ?? throw new InvalidOperationException("Jellyfin does only support relational databases.");
 29109                if (!await databaseCreator.ExistsAsync().ConfigureAwait(false))
 110                {
 29111                    await databaseCreator.CreateAsync().ConfigureAwait(false);
 112                }
 113
 29114                var historyRepository = dbContext.GetService<IHistoryRepository>();
 115
 29116                await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
 29117                var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false);
 29118                var startupScripts = flatApplyMigrations
 29119                    .Where(e => !appliedMigrations.Any(f => f != e.BuildCodeMigrationId()))
 29120                    .Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.Buil
 29121                    .ToArray();
 2610122                foreach (var item in startupScripts)
 123                {
 1276124                    logger.LogInformation("Seed migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name);
 1276125                    await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
 126                }
 29127            }
 128
 29129            logger.LogInformation("Migration system initialisation completed.");
 29130        }
 131        else
 132        {
 133            // Only a media server start is refused. A MigrateSystem run is left to the migrations, which another databa
 134            // provider may rely on to initialise its database, and a restore replaces the database later, in StartServe
 7135            var startupMode = startupOptions.StartupMode ?? Configuration.StartupMode.MediaServer;
 7136            if (startupMode == Configuration.StartupMode.MediaServer && string.IsNullOrWhiteSpace(startupOptions.Restore
 137            {
 5138                await EnsureExistingDatabaseAsync(appPaths, logger).ConfigureAwait(false);
 139            }
 140
 141            // migrate any existing migration.xml files
 3142            var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, "migrations.xml");
 3143            var migrationOptions = File.Exists(migrationConfigPath)
 3144                 ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
 3145                 : null;
 3146            if (migrationOptions is not null && migrationOptions.Applied.Count > 0)
 147            {
 0148                logger.LogInformation("Old migration style migration.xml detected. Migrate now.");
 149                try
 150                {
 0151                    var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 0152                    await using (dbContext.ConfigureAwait(false))
 153                    {
 0154                        var historyRepository = dbContext.GetService<IHistoryRepository>();
 0155                        var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(fals
 0156                        var lastOldAppliedMigration = Migrations
 0157                            .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that 
 0158                            .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value)))
 0159                            .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId()))
 0160                            .OrderBy(e => e.BuildCodeMigrationId())
 0161                            .Last(); // this is the latest migration applied in the old migration.xml
 162
 0163                        IReadOnlyList<CodeMigration> oldMigrations = [
 0164                            .. Migrations
 0165                            .SelectMany(e => e)
 0166                            .OrderBy(e => e.BuildCodeMigrationId())
 0167                            .TakeWhile(e => e.BuildCodeMigrationId() != lastOldAppliedMigration.BuildCodeMigrationId()),
 0168                            lastOldAppliedMigration
 0169                        ];
 170                        // those are all migrations that had to run in the old migration system, even if not noted in th
 171
 0172                        var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository
 0173                        foreach (var item in startupScripts)
 174                        {
 0175                            logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration.
 0176                            await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
 177                        }
 178
 0179                        logger.LogInformation("Rename old migration.xml to migration.xml.backup");
 0180                        File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true);
 0181                    }
 0182                }
 0183                catch (Exception ex)
 184                {
 0185                    logger.LogCritical(ex, "Failed to apply migrations");
 0186                    throw;
 187                }
 188            }
 3189        }
 32190    }
 191
 192    /// <summary>
 193    /// Stops the startup of a server that has been set up before but whose database is missing or empty. Running the mi
 194    /// against such a database fails part way through, and seeding it would leave a server nobody can log in to.
 195    /// </summary>
 196    private async Task EnsureExistingDatabaseAsync(IApplicationPaths appPaths, ILogger logger)
 197    {
 5198        string? problem = null;
 5199        var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 5200        await using (dbContext.ConfigureAwait(false))
 201        {
 5202            var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator
 5203                ?? throw new InvalidOperationException("Jellyfin does only support relational databases.");
 204
 205            // Check existence first: opening a connection to a missing SQLite database creates an empty file.
 5206            if (!await databaseCreator.ExistsAsync().ConfigureAwait(false))
 207            {
 2208                problem = "the database does not exist";
 209            }
 210            else
 211            {
 3212                var historyRepository = dbContext.GetService<IHistoryRepository>();
 3213                if (!await historyRepository.ExistsAsync().ConfigureAwait(false))
 214                {
 1215                    problem = "the database has no migration history";
 216                }
 2217                else if ((await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false)).Count == 0)
 218                {
 1219                    problem = "the migration history of the database is empty";
 220                }
 3221            }
 222        }
 223
 5224        if (problem is null)
 225        {
 1226            return;
 227        }
 228
 4229        var message = string.Format(
 4230            CultureInfo.InvariantCulture,
 4231            "This server has been set up before (IsStartupWizardCompleted is true in {0}), but {1}. Jellyfin will not st
 4232            + "To continue, either restore the previous database; or start over and keep this server's settings by setti
 4233            + "(users, watch history and everything else stored in the database will not come back); or set up a new ser
 4234            appPaths.SystemConfigurationFilePath,
 4235            problem);
 4236        logger.LogCritical("{Message}", message);
 4237        throw new InvalidOperationException(message);
 1238    }
 239
 240    /// <summary>
 241    /// Runs all pending migrations of the requested stage.
 242    /// </summary>
 243    /// <param name="stage">The stage to migrate.</param>
 244    /// <param name="serviceProvider">The service provider handed to the migrations.</param>
 245    /// <returns>A value indicating whether at least one migration has been applied.</returns>
 246    public async Task<bool> MigrateStepAsync(JellyfinMigrationStageTypes stage, IServiceProvider serviceProvider)
 247    {
 81248        var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migrate s
 81249        ICollection<CodeMigration> migrationStage = (Migrations.FirstOrDefault(e => e.Stage == stage) as ICollection<Cod
 250
 81251        var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 81252        await using (dbContext.ConfigureAwait(false))
 253        {
 81254            var historyRepository = dbContext.GetService<IHistoryRepository>();
 81255            var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
 81256            var completedMigrations = 0;
 81257            string? lastMigrationKey = null;
 258
 1647259            while (true)
 260            {
 261                // A single migration can change which migrations still apply: IMigrator.MigrateAsync treats its argumen
 262                // state to end up in, so it reverts everything applied after it, and a reverted migration can take code
 263                // with it (AddNormalizedUsername.Down drops the UpdateNormalizedUsername history row). Anything compute
 264                // that point is stale, so only ever run the next migration and then work out the pending set again.
 1728265                var appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
 1728266                var pendingCodeMigrations = migrationStage
 1728267                    .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
 1728268                    .Select(e => (Key: e.BuildCodeMigrationId(), Migration: new InternalCodeMigration(e, serviceProvider
 1728269                    .ToArray();
 270
 1728271                (string Key, InternalDatabaseMigration Migration)[] pendingDatabaseMigrations = [];
 1728272                if (stage is JellyfinMigrationStageTypes.CoreInitialisation)
 273                {
 1539274                    pendingDatabaseMigrations = migrationsAssembly.Migrations.Where(f => appliedMigrations.All(e => e.Mi
 1539275                       .Select(e => (Key: e.Key, Migration: new InternalDatabaseMigration(e, dbContext)))
 1539276                       .ToArray();
 277                }
 278
 1728279                (string Key, IInternalMigration Migration)[] pendingMigrations = [.. pendingCodeMigrations, .. pendingDa
 1728280                if (pendingMigrations.Length == 0)
 281                {
 282                    break;
 283                }
 284
 1647285                if (completedMigrations == 0)
 286                {
 54287                    logger.LogInformation("There are {Pending} migrations for stage {Stage}.", pendingMigrations.Length,
 288                }
 289
 1647290                var item = pendingMigrations.OrderBy(e => e.Key, StringComparer.Ordinal).First();
 1647291                if (string.Equals(item.Key, lastMigrationKey, StringComparison.Ordinal))
 292                {
 0293                    throw new InvalidOperationException($"Migration {item.Key} ran but did not record itself as applied 
 294                }
 295
 1647296                lastMigrationKey = item.Key;
 297
 298                // Surface generic "Running migration X of Y" progress in the always-visible startup UI header.
 1647299                SetupServer.ReportActivity(StartupActivity.Migration(completedMigrations + 1, completedMigrations + pend
 1647300                var migrationLogger = logger.With(_loggerFactory.CreateLogger(item.Migration.GetType().Name)).BeginGroup
 301                try
 302                {
 1647303                    migrationLogger.LogInformation("Perform migration {Name}", item.Key);
 1647304                    await item.Migration.PerformAsync(migrationLogger).ConfigureAwait(false);
 1647305                    migrationLogger.LogInformation("Migration {Name} was successfully applied", item.Key);
 1647306                }
 0307                catch (Exception ex)
 308                {
 0309                    migrationLogger.LogCritical("Error: {Error}", ex.Message);
 0310                    migrationLogger.LogError(ex, "Migration {Name} failed", item.Key);
 311
 0312                    if (_backupKey != default && _backupService is not null && _jellyfinDatabaseProvider is not null)
 313                    {
 0314                        if (_backupKey.LibraryDb is not null)
 315                        {
 0316                            migrationLogger.LogInformation("Attempt to rollback librarydb.");
 317                            try
 318                            {
 0319                                var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
 0320                                File.Move(_backupKey.LibraryDb, libraryDbPath, true);
 0321                            }
 0322                            catch (Exception inner)
 323                            {
 0324                                migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interventio
 0325                            }
 326                        }
 327
 0328                        if (_backupKey.JellyfinDb is not null)
 329                        {
 0330                            migrationLogger.LogInformation("Attempt to rollback JellyfinDb.");
 331                            try
 332                            {
 0333                                await _jellyfinDatabaseProvider.RestoreBackupFast(_backupKey.JellyfinDb, CancellationTok
 0334                            }
 0335                            catch (Exception inner)
 336                            {
 0337                                migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interventio
 0338                            }
 339                        }
 340
 0341                        if (_backupKey.FullBackup is not null)
 342                        {
 0343                            migrationLogger.LogInformation("Attempt to rollback from backup.");
 344                            try
 345                            {
 0346                                await _backupService.RestoreBackupAsync(_backupKey.FullBackup.Path).ConfigureAwait(false
 0347                            }
 0348                            catch (Exception inner)
 349                            {
 0350                                migrationLogger.LogCritical(inner, "Could not rollback from backup {Backup}. Manual inte
 0351                            }
 352                        }
 353                    }
 354
 0355                    throw;
 356                }
 357
 1647358                completedMigrations++;
 1647359            }
 360
 81361            return completedMigrations > 0;
 362        }
 81363    }
 364
 365    private static string GetJellyfinVersion()
 366    {
 1411367        return Assembly.GetEntryAssembly()!.GetName().Version!.ToString();
 368    }
 369
 370    public async Task CleanupSystemAfterMigration(ILogger logger)
 371    {
 0372        if (_backupKey != default)
 373        {
 0374            if (_backupKey.LibraryDb is not null)
 375            {
 0376                logger.LogInformation("Attempt to cleanup librarydb backup.");
 377                try
 378                {
 0379                    File.Delete(_backupKey.LibraryDb);
 0380                }
 0381                catch (Exception inner)
 382                {
 0383                    logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.LibraryDb);
 0384                }
 385            }
 386
 0387            if (_backupKey.JellyfinDb is not null && _jellyfinDatabaseProvider is not null)
 388            {
 0389                logger.LogInformation("Attempt to cleanup JellyfinDb backup.");
 390                try
 391                {
 0392                    await _jellyfinDatabaseProvider.DeleteBackup(_backupKey.JellyfinDb).ConfigureAwait(false);
 0393                }
 0394                catch (Exception inner)
 395                {
 0396                    logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.JellyfinDb);
 0397                }
 398            }
 399
 0400            if (_backupKey.FullBackup is not null)
 401            {
 0402                logger.LogInformation("Attempt to cleanup from migration backup.");
 403                try
 404                {
 0405                    File.Delete(_backupKey.FullBackup.Path);
 0406                }
 0407                catch (Exception inner)
 408                {
 0409                    logger.LogCritical(inner, "Could not cleanup backup {Backup}.", _backupKey.FullBackup.Path);
 0410                }
 411            }
 412        }
 0413    }
 414
 415    public async Task PrepareSystemForMigration(ILogger logger)
 416    {
 0417        logger.LogInformation("Prepare system for possible migrations");
 418        JellyfinMigrationBackupAttribute backupInstruction;
 419        IReadOnlyList<HistoryRow> appliedMigrations;
 0420        var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 0421        await using (dbContext.ConfigureAwait(false))
 422        {
 0423            var historyRepository = dbContext.GetService<IHistoryRepository>();
 0424            var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
 0425            appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
 0426            backupInstruction = new JellyfinMigrationBackupAttribute()
 0427            {
 0428                JellyfinDb = migrationsAssembly.Migrations.Any(f => appliedMigrations.All(e => e.MigrationId != f.Key))
 0429            };
 0430        }
 431
 0432        backupInstruction = Migrations.SelectMany(e => e)
 0433           .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
 0434           .Select(e => e.BackupRequirements)
 0435           .Where(e => e is not null)
 0436           .Aggregate(backupInstruction, MergeBackupAttributes!);
 437
 0438        if (backupInstruction.LegacyLibraryDb)
 439        {
 0440            logger.LogInformation("A migration will attempt to modify the library.db, will attempt to backup the file no
 441            // for legacy migrations that still operates on the library.db
 0442            var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
 0443            if (File.Exists(libraryDbPath))
 444            {
 0445                for (int i = 1; ; i++)
 446                {
 0447                    var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", libraryDbPath, i);
 0448                    if (!File.Exists(bakPath))
 449                    {
 450                        try
 451                        {
 0452                            logger.LogInformation("Backing up {Library} to {BackupPath}", DbFilename, bakPath);
 0453                            File.Copy(libraryDbPath, bakPath);
 0454                            _backupKey = (bakPath, _backupKey.JellyfinDb, _backupKey.FullBackup);
 0455                            logger.LogInformation("{Library} backed up to {BackupPath}", DbFilename, bakPath);
 0456                            break;
 457                        }
 0458                        catch (Exception ex)
 459                        {
 0460                            logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, ba
 0461                            throw;
 462                        }
 463                    }
 464                }
 465
 0466                logger.LogInformation("{Library} has been backed up as {BackupPath}", DbFilename, _backupKey.LibraryDb);
 467            }
 468            else
 469            {
 0470                logger.LogError("Cannot make a backup of {Library} at path {BackupPath} because file could not be found 
 471            }
 472        }
 473
 0474        if (backupInstruction.JellyfinDb && _jellyfinDatabaseProvider is not null)
 475        {
 0476            logger.LogInformation("A migration will attempt to modify the jellyfin.db, will attempt to backup the file n
 0477            _backupKey = (_backupKey.LibraryDb, await _jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.No
 0478            logger.LogInformation("Jellyfin database has been backed up as {BackupPath}", _backupKey.JellyfinDb);
 479        }
 480
 0481        if (_backupService is not null && (backupInstruction.Metadata || backupInstruction.Subtitles || backupInstructio
 482        {
 0483            logger.LogInformation("A migration will attempt to modify system resources. Will attempt to create backup no
 0484            _backupKey = (_backupKey.LibraryDb, _backupKey.JellyfinDb, await _backupService.CreateBackupAsync(new Backup
 0485            {
 0486                Metadata = backupInstruction.Metadata,
 0487                Subtitles = backupInstruction.Subtitles,
 0488                Trickplay = backupInstruction.Trickplay,
 0489                Database = false // database backups are explicitly handled by the provider itself as the backup service
 0490            }).ConfigureAwait(false));
 0491            logger.LogInformation("Pre-Migration backup successfully created as {BackupKey}", _backupKey.FullBackup.Path
 492        }
 0493    }
 494
 495    private static JellyfinMigrationBackupAttribute MergeBackupAttributes(JellyfinMigrationBackupAttribute left, Jellyfi
 496    {
 0497        return new JellyfinMigrationBackupAttribute()
 0498        {
 0499            JellyfinDb = left!.JellyfinDb || right!.JellyfinDb,
 0500            LegacyLibraryDb = left.LegacyLibraryDb || right!.LegacyLibraryDb,
 0501            Metadata = left.Metadata || right!.Metadata,
 0502            Subtitles = left.Subtitles || right!.Subtitles,
 0503            Trickplay = left.Trickplay || right!.Trickplay
 0504        };
 505    }
 506
 507    private class InternalCodeMigration : IInternalMigration
 508    {
 509        private readonly CodeMigration _codeMigration;
 510        private readonly IServiceProvider _serviceProvider;
 511        private JellyfinDbContext _dbContext;
 512
 513        public InternalCodeMigration(CodeMigration codeMigration, IServiceProvider serviceProvider, JellyfinDbContext db
 514        {
 405515            _codeMigration = codeMigration;
 405516            _serviceProvider = serviceProvider;
 405517            _dbContext = dbContext;
 405518        }
 519
 520        public async Task PerformAsync(IStartupLogger logger)
 521        {
 135522            await _codeMigration.Perform(_serviceProvider, logger, CancellationToken.None).ConfigureAwait(false);
 523
 135524            var historyRepository = _dbContext.GetService<IHistoryRepository>();
 135525            var createScript = historyRepository.GetInsertScript(new HistoryRow(_codeMigration.BuildCodeMigrationId(), G
 135526            await _dbContext.Database.ExecuteSqlRawAsync(createScript).ConfigureAwait(false);
 135527        }
 528    }
 529
 530    private class InternalDatabaseMigration : IInternalMigration
 531    {
 532        private readonly JellyfinDbContext _jellyfinDbContext;
 533        private KeyValuePair<string, TypeInfo> _databaseMigrationInfo;
 534
 535        public InternalDatabaseMigration(KeyValuePair<string, TypeInfo> databaseMigrationInfo, JellyfinDbContext jellyfi
 536        {
 43092537            _databaseMigrationInfo = databaseMigrationInfo;
 43092538            _jellyfinDbContext = jellyfinDbContext;
 43092539        }
 540
 541        public async Task PerformAsync(IStartupLogger logger)
 542        {
 1512543            var migrator = _jellyfinDbContext.GetService<IMigrator>();
 1512544            await migrator.MigrateAsync(_databaseMigrationInfo.Key).ConfigureAwait(false);
 1512545        }
 546    }
 547}