< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.JellyfinMigrationService
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/JellyfinMigrationService.cs
Line coverage
42%
Covered lines: 104
Uncovered lines: 141
Coverable lines: 245
Total lines: 467
Line coverage: 42.4%
Branch coverage
25%
Covered branches: 25
Total branches: 98
Branch coverage: 25.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 3/26/2026 - 12:14:14 AM Line coverage: 81.3% (35/43) Branch coverage: 16.6% (2/12) Total lines: 4594/19/2026 - 12:14:27 AM Line coverage: 41.4% (100/241) Branch coverage: 21.5% (19/88) Total lines: 4595/4/2026 - 12:15:16 AM Line coverage: 41.4% (100/241) Branch coverage: 20.4% (18/88) Total lines: 4595/7/2026 - 12:15:44 AM Line coverage: 41.4% (100/241) Branch coverage: 20.6% (19/92) Total lines: 4595/22/2026 - 12:15:17 AM Line coverage: 41.4% (100/241) Branch coverage: 21.7% (20/92) Total lines: 4595/27/2026 - 12:15:38 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: 467 3/26/2026 - 12:14:14 AM Line coverage: 81.3% (35/43) Branch coverage: 16.6% (2/12) Total lines: 4594/19/2026 - 12:14:27 AM Line coverage: 41.4% (100/241) Branch coverage: 21.5% (19/88) Total lines: 4595/4/2026 - 12:15:16 AM Line coverage: 41.4% (100/241) Branch coverage: 20.4% (18/88) Total lines: 4595/7/2026 - 12:15:44 AM Line coverage: 41.4% (100/241) Branch coverage: 20.6% (19/92) Total lines: 4595/22/2026 - 12:15:17 AM Line coverage: 41.4% (100/241) Branch coverage: 21.7% (20/92) Total lines: 4595/27/2026 - 12:15:38 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: 467

Coverage delta

Coverage delta 40 -40

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%22100%
CheckFirstTimeRunOrMigration()36.36%1012245.31%
MigrateStepAsync()46.87%1303254.23%
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    {
 6656        _dbContextFactory = dbContextFactory;
 6657        _loggerFactory = loggerFactory;
 6658        _startupLogger = startupLogger;
 6659        _backupService = backupService;
 6660        _jellyfinDatabaseProvider = jellyfinDatabaseProvider;
 6661        _applicationPaths = applicationPaths;
 62#pragma warning disable CS0618 // Type or member is obsolete
 6663        Migrations = [.. typeof(IMigrationRoutine).Assembly.GetTypes().Where(e => typeof(IMigrationRoutine).IsAssignable
 6664            .Select(e => (Type: e, Metadata: e.GetCustomAttribute<JellyfinMigrationAttribute>(), Backup: e.GetCustomAttr
 6665            .Where(e => e.Metadata is not null)
 6666            .GroupBy(e => e.Metadata!.Stage)
 6667            .Select(f =>
 6668            {
 6669                var stage = new MigrationStage(f.Key);
 6670                foreach (var item in f)
 6671                {
 6672                    JellyfinMigrationBackupAttribute? backupMetadata = null;
 6673                    if (item.Backup?.Any() == true)
 6674                    {
 6675                        backupMetadata = item.Backup.Aggregate(MergeBackupAttributes);
 6676                    }
 6677
 6678                    stage.Add(new(item.Type, item.Metadata!, backupMetadata));
 6679                }
 6680
 6681                return stage;
 6682            })];
 83#pragma warning restore CS0618 // Type or member is obsolete
 6684    }
 85
 86    private interface IInternalMigration
 87    {
 88        Task PerformAsync(IStartupLogger logger);
 89    }
 90
 91    private HashSet<MigrationStage> Migrations { get; set; }
 92
 93    public async Task CheckFirstTimeRunOrMigration(IApplicationPaths appPaths, StartupOptions startupOptions)
 94    {
 2295        var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migration
 2296        logger.LogInformation("Initialise Migration service.");
 2297        var xmlSerializer = new MyXmlSerializer();
 2298        var serverConfig = File.Exists(appPaths.SystemConfigurationFilePath)
 2299            ? (ServerConfiguration)xmlSerializer.DeserializeFromFile(typeof(ServerConfiguration), appPaths.SystemConfigu
 22100            : new ServerConfiguration();
 22101        if (!serverConfig.IsStartupWizardCompleted || startupOptions.StartupMode is Configuration.StartupMode.SeedSystem
 102        {
 22103            logger.LogInformation("System initialization detected. Seed data. Startup mode is: {StartupMode}", startupOp
 22104            var flatApplyMigrations = Migrations.SelectMany(e => e.Where(f => !f.Metadata.RunMigrationOnSetup)).ToArray(
 105
 22106            var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 22107            await using (dbContext.ConfigureAwait(false))
 108            {
 22109                var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as IRelationalDatabaseCreator
 22110                    ?? throw new InvalidOperationException("Jellyfin does only support relational databases.");
 22111                if (!await databaseCreator.ExistsAsync().ConfigureAwait(false))
 112                {
 22113                    await databaseCreator.CreateAsync().ConfigureAwait(false);
 114                }
 115
 22116                var historyRepository = dbContext.GetService<IHistoryRepository>();
 117
 22118                await historyRepository.CreateIfNotExistsAsync().ConfigureAwait(false);
 22119                var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(false);
 22120                var startupScripts = flatApplyMigrations
 22121                    .Where(e => !appliedMigrations.Any(f => f != e.BuildCodeMigrationId()))
 22122                    .Select(e => (Migration: e.Metadata, Script: historyRepository.GetInsertScript(new HistoryRow(e.Buil
 22123                    .ToArray();
 1628124                foreach (var item in startupScripts)
 125                {
 792126                    logger.LogInformation("Seed migration {Key}-{Name}.", item.Migration.Key, item.Migration.Name);
 792127                    await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
 128                }
 22129            }
 130
 22131            logger.LogInformation("Migration system initialisation completed.");
 22132        }
 133        else
 134        {
 135            // migrate any existing migration.xml files
 0136            var migrationConfigPath = Path.Join(appPaths.ConfigurationDirectoryPath, "migrations.xml");
 0137            var migrationOptions = File.Exists(migrationConfigPath)
 0138                 ? (MigrationOptions)xmlSerializer.DeserializeFromFile(typeof(MigrationOptions), migrationConfigPath)!
 0139                 : null;
 0140            if (migrationOptions is not null && migrationOptions.Applied.Count > 0)
 141            {
 0142                logger.LogInformation("Old migration style migration.xml detected. Migrate now.");
 143                try
 144                {
 0145                    var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 0146                    await using (dbContext.ConfigureAwait(false))
 147                    {
 0148                        var historyRepository = dbContext.GetService<IHistoryRepository>();
 0149                        var appliedMigrations = await dbContext.Database.GetAppliedMigrationsAsync().ConfigureAwait(fals
 0150                        var lastOldAppliedMigration = Migrations
 0151                            .SelectMany(e => e.Where(e => e.Metadata.Key is not null)) // only consider migrations that 
 0152                            .Where(e => migrationOptions.Applied.Any(f => f.Id.Equals(e.Metadata.Key!.Value)))
 0153                            .Where(e => !appliedMigrations.Contains(e.BuildCodeMigrationId()))
 0154                            .OrderBy(e => e.BuildCodeMigrationId())
 0155                            .Last(); // this is the latest migration applied in the old migration.xml
 156
 0157                        IReadOnlyList<CodeMigration> oldMigrations = [
 0158                            .. Migrations
 0159                            .SelectMany(e => e)
 0160                            .OrderBy(e => e.BuildCodeMigrationId())
 0161                            .TakeWhile(e => e.BuildCodeMigrationId() != lastOldAppliedMigration.BuildCodeMigrationId()),
 0162                            lastOldAppliedMigration
 0163                        ];
 164                        // those are all migrations that had to run in the old migration system, even if not noted in th
 165
 0166                        var startupScripts = oldMigrations.Select(e => (Migration: e.Metadata, Script: historyRepository
 0167                        foreach (var item in startupScripts)
 168                        {
 0169                            logger.LogInformation("Migrate migration {Key}-{Name}.", item.Migration.Key, item.Migration.
 0170                            await dbContext.Database.ExecuteSqlRawAsync(item.Script).ConfigureAwait(false);
 171                        }
 172
 0173                        logger.LogInformation("Rename old migration.xml to migration.xml.backup");
 0174                        File.Move(migrationConfigPath, Path.ChangeExtension(migrationConfigPath, ".xml.backup"), true);
 0175                    }
 0176                }
 0177                catch (Exception ex)
 178                {
 0179                    logger.LogCritical(ex, "Failed to apply migrations");
 0180                    throw;
 181                }
 182            }
 0183        }
 22184    }
 185
 186    public async Task MigrateStepAsync(JellyfinMigrationStageTypes stage, IServiceProvider? serviceProvider)
 187    {
 66188        var logger = _startupLogger.With(_loggerFactory.CreateLogger<JellyfinMigrationService>()).BeginGroup($"Migrate s
 66189        ICollection<CodeMigration> migrationStage = (Migrations.FirstOrDefault(e => e.Stage == stage) as ICollection<Cod
 190
 66191        var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 66192        await using (dbContext.ConfigureAwait(false))
 193        {
 66194            var historyRepository = dbContext.GetService<IHistoryRepository>();
 66195            var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
 66196            (string Key, IInternalMigration Migration)[] migrations = [];
 197
 198            do
 199            { // migrations may alter the migration state. Reevaluate the applicable migrations after every stage ran un
 110200                var appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
 110201                var pendingCodeMigrations = migrationStage
 110202                    .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
 110203                    .Select(e => (Key: e.BuildCodeMigrationId(), Migration: new InternalCodeMigration(e, serviceProvider
 110204                    .ToArray();
 205
 110206                (string Key, InternalDatabaseMigration Migration)[] pendingDatabaseMigrations = [];
 110207                if (stage is JellyfinMigrationStageTypes.CoreInitialisation)
 208                {
 44209                    pendingDatabaseMigrations = migrationsAssembly.Migrations.Where(f => appliedMigrations.All(e => e.Mi
 44210                       .Select(e => (Key: e.Key, Migration: new InternalDatabaseMigration(e, dbContext)))
 44211                       .ToArray();
 212                }
 213
 110214                (string Key, IInternalMigration Migration)[] pendingMigrations = [.. pendingCodeMigrations, .. pendingDa
 110215                logger.LogInformation("There are {Pending} migrations for stage {Stage}.", pendingCodeMigrations.Length,
 110216                migrations = pendingMigrations.OrderBy(e => e.Key).ToArray();
 217
 110218                var migrationIndex = 0;
 2596219                foreach (var item in migrations)
 220                {
 221                    // Surface generic "Running migration X of Y" progress in the always-visible startup UI header.
 1188222                    SetupServer.ReportActivity(StartupActivity.Migration(++migrationIndex, migrations.Length));
 1188223                    var migrationLogger = logger.With(_loggerFactory.CreateLogger(item.Migration.GetType().Name)).BeginG
 224                    try
 225                    {
 1188226                        migrationLogger.LogInformation("Perform migration {Name}", item.Key);
 1188227                        await item.Migration.PerformAsync(migrationLogger).ConfigureAwait(false);
 1188228                        migrationLogger.LogInformation("Migration {Name} was successfully applied", item.Key);
 1188229                    }
 0230                    catch (Exception ex)
 231                    {
 0232                        migrationLogger.LogCritical("Error: {Error}", ex.Message);
 0233                        migrationLogger.LogError(ex, "Migration {Name} failed", item.Key);
 234
 0235                        if (_backupKey != default && _backupService is not null && _jellyfinDatabaseProvider is not null
 236                        {
 0237                            if (_backupKey.LibraryDb is not null)
 238                            {
 0239                                migrationLogger.LogInformation("Attempt to rollback librarydb.");
 240                                try
 241                                {
 0242                                    var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
 0243                                    File.Move(_backupKey.LibraryDb, libraryDbPath, true);
 0244                                }
 0245                                catch (Exception inner)
 246                                {
 0247                                    migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interve
 0248                                }
 249                            }
 250
 0251                            if (_backupKey.JellyfinDb is not null)
 252                            {
 0253                                migrationLogger.LogInformation("Attempt to rollback JellyfinDb.");
 254                                try
 255                                {
 0256                                    await _jellyfinDatabaseProvider.RestoreBackupFast(_backupKey.JellyfinDb, Cancellatio
 0257                                }
 0258                                catch (Exception inner)
 259                                {
 0260                                    migrationLogger.LogCritical(inner, "Could not rollback {LibraryPath}. Manual interve
 0261                                }
 262                            }
 263
 0264                            if (_backupKey.FullBackup is not null)
 265                            {
 0266                                migrationLogger.LogInformation("Attempt to rollback from backup.");
 267                                try
 268                                {
 0269                                    await _backupService.RestoreBackupAsync(_backupKey.FullBackup.Path).ConfigureAwait(f
 0270                                }
 0271                                catch (Exception inner)
 272                                {
 0273                                    migrationLogger.LogCritical(inner, "Could not rollback from backup {Backup}. Manual 
 0274                                }
 275                            }
 276                        }
 277
 0278                        throw;
 279                    }
 1188280                }
 220281            } while (migrations.Length != 0);
 66282        }
 66283    }
 284
 285    private static string GetJellyfinVersion()
 286    {
 902287        return Assembly.GetEntryAssembly()!.GetName().Version!.ToString();
 288    }
 289
 290    public async Task CleanupSystemAfterMigration(ILogger logger)
 291    {
 0292        if (_backupKey != default)
 293        {
 0294            if (_backupKey.LibraryDb is not null)
 295            {
 0296                logger.LogInformation("Attempt to cleanup librarydb backup.");
 297                try
 298                {
 0299                    File.Delete(_backupKey.LibraryDb);
 0300                }
 0301                catch (Exception inner)
 302                {
 0303                    logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.LibraryDb);
 0304                }
 305            }
 306
 0307            if (_backupKey.JellyfinDb is not null && _jellyfinDatabaseProvider is not null)
 308            {
 0309                logger.LogInformation("Attempt to cleanup JellyfinDb backup.");
 310                try
 311                {
 0312                    await _jellyfinDatabaseProvider.DeleteBackup(_backupKey.JellyfinDb).ConfigureAwait(false);
 0313                }
 0314                catch (Exception inner)
 315                {
 0316                    logger.LogCritical(inner, "Could not cleanup {LibraryPath}.", _backupKey.JellyfinDb);
 0317                }
 318            }
 319
 0320            if (_backupKey.FullBackup is not null)
 321            {
 0322                logger.LogInformation("Attempt to cleanup from migration backup.");
 323                try
 324                {
 0325                    File.Delete(_backupKey.FullBackup.Path);
 0326                }
 0327                catch (Exception inner)
 328                {
 0329                    logger.LogCritical(inner, "Could not cleanup backup {Backup}.", _backupKey.FullBackup.Path);
 0330                }
 331            }
 332        }
 0333    }
 334
 335    public async Task PrepareSystemForMigration(ILogger logger)
 336    {
 0337        logger.LogInformation("Prepare system for possible migrations");
 338        JellyfinMigrationBackupAttribute backupInstruction;
 339        IReadOnlyList<HistoryRow> appliedMigrations;
 0340        var dbContext = await _dbContextFactory.CreateDbContextAsync().ConfigureAwait(false);
 0341        await using (dbContext.ConfigureAwait(false))
 342        {
 0343            var historyRepository = dbContext.GetService<IHistoryRepository>();
 0344            var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
 0345            appliedMigrations = await historyRepository.GetAppliedMigrationsAsync().ConfigureAwait(false);
 0346            backupInstruction = new JellyfinMigrationBackupAttribute()
 0347            {
 0348                JellyfinDb = migrationsAssembly.Migrations.Any(f => appliedMigrations.All(e => e.MigrationId != f.Key))
 0349            };
 0350        }
 351
 0352        backupInstruction = Migrations.SelectMany(e => e)
 0353           .Where(e => appliedMigrations.All(f => f.MigrationId != e.BuildCodeMigrationId()))
 0354           .Select(e => e.BackupRequirements)
 0355           .Where(e => e is not null)
 0356           .Aggregate(backupInstruction, MergeBackupAttributes!);
 357
 0358        if (backupInstruction.LegacyLibraryDb)
 359        {
 0360            logger.LogInformation("A migration will attempt to modify the library.db, will attempt to backup the file no
 361            // for legacy migrations that still operates on the library.db
 0362            var libraryDbPath = Path.Combine(_applicationPaths.DataPath, DbFilename);
 0363            if (File.Exists(libraryDbPath))
 364            {
 0365                for (int i = 1; ; i++)
 366                {
 0367                    var bakPath = string.Format(CultureInfo.InvariantCulture, "{0}.bak{1}", libraryDbPath, i);
 0368                    if (!File.Exists(bakPath))
 369                    {
 370                        try
 371                        {
 0372                            logger.LogInformation("Backing up {Library} to {BackupPath}", DbFilename, bakPath);
 0373                            File.Copy(libraryDbPath, bakPath);
 0374                            _backupKey = (bakPath, _backupKey.JellyfinDb, _backupKey.FullBackup);
 0375                            logger.LogInformation("{Library} backed up to {BackupPath}", DbFilename, bakPath);
 0376                            break;
 377                        }
 0378                        catch (Exception ex)
 379                        {
 0380                            logger.LogError(ex, "Cannot make a backup of {Library} at path {BackupPath}", DbFilename, ba
 0381                            throw;
 382                        }
 383                    }
 384                }
 385
 0386                logger.LogInformation("{Library} has been backed up as {BackupPath}", DbFilename, _backupKey.LibraryDb);
 387            }
 388            else
 389            {
 0390                logger.LogError("Cannot make a backup of {Library} at path {BackupPath} because file could not be found 
 391            }
 392        }
 393
 0394        if (backupInstruction.JellyfinDb && _jellyfinDatabaseProvider is not null)
 395        {
 0396            logger.LogInformation("A migration will attempt to modify the jellyfin.db, will attempt to backup the file n
 0397            _backupKey = (_backupKey.LibraryDb, await _jellyfinDatabaseProvider.MigrationBackupFast(CancellationToken.No
 0398            logger.LogInformation("Jellyfin database has been backed up as {BackupPath}", _backupKey.JellyfinDb);
 399        }
 400
 0401        if (_backupService is not null && (backupInstruction.Metadata || backupInstruction.Subtitles || backupInstructio
 402        {
 0403            logger.LogInformation("A migration will attempt to modify system resources. Will attempt to create backup no
 0404            _backupKey = (_backupKey.LibraryDb, _backupKey.JellyfinDb, await _backupService.CreateBackupAsync(new Backup
 0405            {
 0406                Metadata = backupInstruction.Metadata,
 0407                Subtitles = backupInstruction.Subtitles,
 0408                Trickplay = backupInstruction.Trickplay,
 0409                Database = false // database backups are explicitly handled by the provider itself as the backup service
 0410            }).ConfigureAwait(false));
 0411            logger.LogInformation("Pre-Migration backup successfully created as {BackupKey}", _backupKey.FullBackup.Path
 412        }
 0413    }
 414
 415    private static JellyfinMigrationBackupAttribute MergeBackupAttributes(JellyfinMigrationBackupAttribute left, Jellyfi
 416    {
 0417        return new JellyfinMigrationBackupAttribute()
 0418        {
 0419            JellyfinDb = left!.JellyfinDb || right!.JellyfinDb,
 0420            LegacyLibraryDb = left.LegacyLibraryDb || right!.LegacyLibraryDb,
 0421            Metadata = left.Metadata || right!.Metadata,
 0422            Subtitles = left.Subtitles || right!.Subtitles,
 0423            Trickplay = left.Trickplay || right!.Trickplay
 0424        };
 425    }
 426
 427    private class InternalCodeMigration : IInternalMigration
 428    {
 429        private readonly CodeMigration _codeMigration;
 430        private readonly IServiceProvider? _serviceProvider;
 431        private JellyfinDbContext _dbContext;
 432
 433        public InternalCodeMigration(CodeMigration codeMigration, IServiceProvider? serviceProvider, JellyfinDbContext d
 434        {
 110435            _codeMigration = codeMigration;
 110436            _serviceProvider = serviceProvider;
 110437            _dbContext = dbContext;
 110438        }
 439
 440        public async Task PerformAsync(IStartupLogger logger)
 441        {
 110442            await _codeMigration.Perform(_serviceProvider, logger, CancellationToken.None).ConfigureAwait(false);
 443
 110444            var historyRepository = _dbContext.GetService<IHistoryRepository>();
 110445            var createScript = historyRepository.GetInsertScript(new HistoryRow(_codeMigration.BuildCodeMigrationId(), G
 110446            await _dbContext.Database.ExecuteSqlRawAsync(createScript).ConfigureAwait(false);
 110447        }
 448    }
 449
 450    private class InternalDatabaseMigration : IInternalMigration
 451    {
 452        private readonly JellyfinDbContext _jellyfinDbContext;
 453        private KeyValuePair<string, TypeInfo> _databaseMigrationInfo;
 454
 455        public InternalDatabaseMigration(KeyValuePair<string, TypeInfo> databaseMigrationInfo, JellyfinDbContext jellyfi
 456        {
 1078457            _databaseMigrationInfo = databaseMigrationInfo;
 1078458            _jellyfinDbContext = jellyfinDbContext;
 1078459        }
 460
 461        public async Task PerformAsync(IStartupLogger logger)
 462        {
 1078463            var migrator = _jellyfinDbContext.GetService<IMigrator>();
 1078464            await migrator.MigrateAsync(_databaseMigrationInfo.Key).ConfigureAwait(false);
 1078465        }
 466    }
 467}