diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-05-10 16:55:31 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-05-10 16:55:31 -0500 |
| commit | 646446c556524674b2c7b87dfd545cb92447e060 (patch) | |
| tree | 8178442bbb837fa8fa54b166a7e2d7a22d5004a3 /src/slskd/Core/Data | |
| parent | 41725681ffe4164d4acfcfb259eab976541dc00f (diff) | |
| download | slskd-646446c556524674b2c7b87dfd545cb92447e060.tar.gz | |
migrator wip
Diffstat (limited to 'src/slskd/Core/Data')
| -rw-r--r-- | src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs | 94 |
2 files changed, 98 insertions, 21 deletions
diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs index 7df435b6..f18aba55 100644 --- a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs @@ -1,4 +1,4 @@ -// <copyright file="z04012025_TransferStateMigration.cs" company="slskd Team"> +// <copyright file="Z04012025_TransferStateMigration.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -29,10 +29,10 @@ using Soulseek; /// <summary> /// Updates the Transfers table to: /// -/// * Add a new StatusDescription (TEXT) column -/// * Copy the current (string) contents of the Status column to StatusDescription -/// * Change the type of the Status column to INTEGER -/// * Set the contents of the Status column to the numeric representation of the existing Status +/// * Add a new StateDescription (TEXT) column +/// * Copy the current (string) contents of the State column to StateDescription +/// * Change the type of the State column to INTEGER +/// * Set the contents of the State column to the numeric representation of the existing State /// /// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored /// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't @@ -44,16 +44,21 @@ public class Z04012025_TransferStateMigration : IMigration private string DatabaseName { get; } = "transfers"; private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - public void Apply() + public bool NeedsToBeApplied() { - // first, check the existing database to see if the StatusDescription column exists - // if it does, the migration has already been applied + // first, check the existing database to see if the StateDescription column exists + // if it does, the migration has already been applied, or the database has been recreated var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; - if (txfers.Any(c => c.Name == "StatusDescription")) + return !txfers.Any(c => c.Name == "StateDescription"); + } + + public void Apply() + { + if (!NeedsToBeApplied()) { - Log.Information("Migration {Name} has already been applied", nameof(Z04012025_TransferStateMigration)); + Log.Information("Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); return; } diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 1312681c..56f77dd9 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -31,6 +31,12 @@ using slskd.Migrations; public interface IMigration { /// <summary> + /// Determines whether the migration needs to be applied. + /// </summary> + /// <returns>A value indicating whether the migration needs to be applied.</returns> + bool NeedsToBeApplied(); + + /// <summary> /// Applies the migration. /// </summary> void Apply(); @@ -50,6 +56,13 @@ public class Migrator Databases = databases; } + private enum MigrationDisposition + { + AlreadyAppliedPerHistoryFile, + ApplicationNotNeededPerMigration, + ApplicationRequired, + } + private string HistoryFileName { get; } = Path.Combine(Program.DataMigrationsDirectory, "history"); private IEnumerable<string> Databases { get; } private ILogger Log { get; } = Serilog.Log.ForContext<Migrator>(); @@ -72,9 +85,11 @@ public class Migrator Log.Information("Checking for outstanding database migrations..."); - // load migration history from the history file in the root of the data directory. this file contains a key/value - // pair for each migration that's been applied, along with the migration date. - // if force=true, we don't care about the history and there's no reason to look at it. + /* + load migration history from the history file in the root of the data directory. this file contains a key/value + pair for each migration that's been applied, along with the migration date. + if force=true, we're going to disregard history and overwrite it. + */ if (!force) { try @@ -100,16 +115,69 @@ public class Migrator } } - // figure out which migrations need to be applied by taking the set difference of the migration list and the history contents - var migrationsNotYetApplied = Migrations.Keys.Except(history.Keys); + /* + // + disposition each of the registered migrations into one of three dispositions: + - applied (per history file) + - not needed (per migration logic) + - required (does not appear in history and migration logic indicates it needs to be applied)) + */ + var migrationDispositions = new Dictionary<string, MigrationDisposition>(); + + try + { + foreach (var migration in Migrations.Keys) + { + if (history.ContainsKey(migration)) + { + migrationDispositions[migration] = MigrationDisposition.AlreadyAppliedPerHistoryFile; + } + else if (Migrations[migration].NeedsToBeApplied()) // warning: performs I/O + { + migrationDispositions[migration] = MigrationDisposition.ApplicationRequired; + } + else + { + migrationDispositions[migration] = MigrationDisposition.ApplicationNotNeededPerMigration; + } + } + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to disposition migrations: {Message}", ex.Message); + throw; + } + + Log.Debug("Migration dispositions: {Dispositions}", migrationDispositions); + + var migrationsToApply = migrationDispositions + .Where(disposition => disposition.Value == MigrationDisposition.ApplicationRequired) + .Select(disposition => disposition.Key); - if (!migrationsNotYetApplied.Any()) + Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); + + if (!migrationsToApply.Any()) { + // we don't have to migrate anything! however, any migration that 1) isn't in history and 2) reported + // that it didn't need to be applied needs to be added to the history file so we can avoid doing that + // I/O each time the application starts. + foreach (var migration in migrationDispositions.Where(disposition => disposition.Value == MigrationDisposition.ApplicationNotNeededPerMigration)) + { + // note that we might get here if the 'force' option was used. we'll just overwrite the timestamp. + history[migration.Key] = DateTime.UtcNow; + } + + UpdateHistoryFile(history); + Log.Information("Databases are up to date!"); return; } - Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + /* + MIGRATION TIME! + --------------------------------------------------------------------------------------------------------------------------------------------------- + */ + Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsToApply.Count()); var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); @@ -151,11 +219,11 @@ public class Migrator overallSw.Start(); var current = 0; - var total = migrationsNotYetApplied.Count(); + var total = migrationsToApply.Count(); var currentSw = new Stopwatch(); - foreach (var migration in migrationsNotYetApplied) + foreach (var migration in migrationsToApply) { current++; currentSw.Restart(); @@ -209,11 +277,15 @@ public class Migrator throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); } + UpdateHistoryFile(history); + Log.Information("Migration(s) complete!"); + } + + private void UpdateHistoryFile(Dictionary<string, DateTime> history) + { var newHistory = history.ToJson(); File.WriteAllText(HistoryFileName, newHistory); // overwrites existing, if present Log.Debug("Saved history to {Location}: {History}", HistoryFileName, newHistory); - - Log.Information("Migration(s) complete!"); } private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); |
