diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-05-18 12:21:36 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-05-18 12:21:36 -0500 |
| commit | 85ba3a74f27c753c08af970d4217ed9fc4a85b54 (patch) | |
| tree | 58d3ec4a4a2fbbf7b3ca712c7feebb5a6c66b20d | |
| parent | 5d5a79e06c187cedde3682805d259d50ea0e72c7 (diff) | |
| download | slskd-85ba3a74f27c753c08af970d4217ed9fc4a85b54.tar.gz | |
remove migration history file
| -rw-r--r-- | docs/migrations.md | 5 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/README.md | 11 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs | 69 |
3 files changed, 17 insertions, 68 deletions
diff --git a/docs/migrations.md b/docs/migrations.md index 6f1ec5f5..2b6450ca 100644 --- a/docs/migrations.md +++ b/docs/migrations.md @@ -10,13 +10,8 @@ When the application detects that a migration is required, it performs the follo 2. Apply migrations: The application applies the necessary changes to the database schema and data. -3. Save migration history: After successfully applying migrations, the application updates the migration history file to record the applied changes. - At the start of each migration a unique `migration id` is generated. If anything goes wrong, this ID can be used to locate the backup files created before the error occured (as subsequent migration attempts/retries will generate new backups, which may contain partially applied migrations). -History is stored in the `migrations` directory so that the application can avoid running migrations that have already been applied. If this file is deleted, moved, or becomes corrupted, -all migrations will be applied the next time the application starts. Avoid deleting, moving or modifying this file. - ## What to Do If a Migration Fails If a migration fails, the application will attempt to restore the databases from the backups created before the migration. However, if the automatic restoration process fails, you can manually recover your data by following these steps: diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index cae058b2..e8630265 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -1,11 +1,9 @@ # Database Migrations -In the hopefully unlikely event that a non-backwards-compatible schema change to a database migration is necessary, a migration must be written. +In the hopefully unlikely event that a schema change more complex than the simple addition of a column to a database migration is necessary, a migration must be written. Migrations are applied by the `Migrator` at startup. -The `history` file in the data directory is used to attempt to track whether migrations have already been applied. If a migration appears in the history file it won't be run again. Users can delete or modify the `history` file or use the `force` flag to apply them, meaning migrations **MUST** be idempotent. - The `Migrator` creates a backup of each database prior to running any migrations, and if an exception is thrown at any time during the process the `Migrator` will revert to these backups automatically. The backup files are left in place when the migration is complete so that users can manually revert if the migration left their application in a bad state or destroyed or lost data. ## Creating a Migration @@ -18,11 +16,12 @@ Z<MMDDYYYY>_<ShortDescription>Migration Migrations MUST: -* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable -and the name(s) of the table(s) that need to be migrated. +* Be idempotent. The migration must be able to be run any number of times without corrupting the database or losing data. * Inspect the target database(s) schema to determine whether the migration needs to be applied (if possible) * Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. -* Log progress, so users can see that the application is performing work while records are updated. +* Figure out where on disk the associated database(s) are located. This is accomplished by combining the static `Program.DataDirectory` variable +and the name(s) of the table(s) that need to be migrated. +* Log progress (with logs prefixed by >), so users can see that the application is performing work while records are updated. Review the `IMigration` interface to determine implementation details. diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 02b65c0c..4adc22fb 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -77,62 +77,31 @@ public class Migrator /// <param name="force">Apply all migrations, regardless of whether there's evidence they have been applied already.</param> public void Migrate(bool force = false) { - Dictionary<string, DateTime> history = []; - - 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're going to disregard history and overwrite it. - */ - if (!force) - { - try - { - if (File.Exists(HistoryFileName)) - { - var txt = File.ReadAllText(HistoryFileName); - history = txt.FromJson<Dictionary<string, DateTime>>(); - - Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFileName, history); - } - else - { - Log.Debug("Migration history file {HistoryFile} was not found", HistoryFileName); - } - } - catch (Exception ex) - { - // log a message but don't throw; migrations are (should be!) idempotent, so there's no harm in running them, - // it just takes unnecessary time. - Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFileName, ex.Message); - Log.Warning("Migration history will be overwritten and all migrations will be applied"); - } - } - - Log.Debug("Current history: {History}", history); + List<string> migrationsToApply = []; + List<string> migrationsToSkip = []; /* determine which migrations need to be applied - take the set difference between all registered migrations and the history file, then for each of the migrations - in that set, check to see if it needs to be applied. if it doesn't, add it to the history file with the current - timestamp. if it does, add it to the list of migrations to apply. - */ - List<string> migrationsToApply = []; + for the time being, we'll rely on each of the migrations to determine whether they need to be applied + this will work until: + 1) there's a migration that isn't idempotent (can't tell whether it needs to be applied on its own), or.. + 2) there are > ~20 migrations, making repeated I/O of database files too slow/expensive on low spec hardware + when the time comes, migration history should be stored within the database files themselves. + */ try { - foreach (var migration in Migrations.Keys.Except(history.Keys)) + foreach (var migration in Migrations.Keys) { if (!Migrations[migration].NeedsToBeApplied()) // warning: performs I/O { Log.Debug("Migration {Name} does not need to be applied", migration); - history[migration] = DateTime.UtcNow; + migrationsToSkip.Add(migration); } else { + Log.Debug("Migration {Name} needs to be applied", migration); migrationsToApply.Add(migration); } } @@ -143,15 +112,10 @@ public class Migrator throw; } - Log.Debug("Updated history: {History}", history); - Log.Debug("Migrations to apply: {Migrations}", migrationsToApply); + Log.Debug("Migrations: {Migrations}", new { migrationsToApply, migrationsToSkip }); if (migrationsToApply.Count == 0) { - // write the history file to disk; if there are new migrations that didn't need to be applied, or the user - // used the 'force' flag, the history file on disk and in memory will have diverged. - UpdateHistoryFile(history); - Log.Information("Databases are up to date!"); return; } @@ -216,7 +180,6 @@ public class Migrator try { Migrations[migration].Apply(); - history[migration] = DateTime.UtcNow; Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); } @@ -260,17 +223,9 @@ 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); - } - private string MakeSourceDatabasePath(string database) => Path.Combine(Program.DataDirectory, $"{database}.db"); private string MakeBackupDatabasePath(string database, string timestamp) => Path.Combine(Program.DataMigrationsDirectory, $"{database}.pre-migration-backup.{timestamp}.db"); }
\ No newline at end of file |
