From 3c70698c39ec1fbe4d522f5c0cdde978d84c1cc0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 May 2025 18:01:19 -0500 Subject: docs, rename migration --- src/slskd/Core/Data/Migrations/README.md | 14 +- .../Migrations/TransferStateMigration_04012025.cs | 203 -------------------- .../Migrations/z04012025_TransferStateMigration.cs | 204 +++++++++++++++++++++ src/slskd/Core/Data/Migrator.cs | 2 +- 4 files changed, 214 insertions(+), 209 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs create mode 100644 src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index 1f603b42..0cafbe6a 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -1,6 +1,6 @@ # Database Migrations -In the hopefully unlikely event that a migration is necessary, a migration must be written. +In the hopefully unlikely event that a non-backwards-compatible schema change to a database migration is necessary, a migration must be written. Migrations are applied by the `Migrator` at startup. @@ -10,17 +10,21 @@ The `Migrator` creates a backup of each database prior to running any migrations ## Creating a Migration -Each migration must be created as a class that implements the `IMigration` interface. +Each migration must be created as a class that implements the `IMigration` interface. The naming convention for migration classes is: + +``` +z_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. -* Log progress, so users can see that the application is performing work while records are updated. -* Use transactions when performing database operations and using/try catch where appropriate to avoid partially applied migrations. * 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. -When the migration is complete, edit the `Migrations` property in the `Migrator` to add the migration to the list in the proper order. +The new `IMigration` implementation must be added to the dictionary in the `Migrations` property of the `Migrator` in the desired order so that it can be run. ### Above all else, each and every migration **MUST** be idempotent. diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs deleted file mode 100644 index 1ea3ca87..00000000 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ /dev/null @@ -1,203 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Migrations; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using Soulseek; - -/// -/// 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 -/// -/// 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 -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class TransferStateMigration_04012025 : IMigration -{ - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string DatabaseName { get; } = "transfers"; - private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - - public void Apply() - { - // first, check the existing database to see if the StatusDescription column exists - // if it does, the migration has already been applied - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var txfers = schema["Transfers"]; - - if (txfers.Any(c => c.Name == "StatusDescription")) - { - Log.Information("Migration {Name} has already been applied", nameof(TransferStateMigration_04012025)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - // get a distinct list of states from the existing data and translate each into the corresponding integer - var stateMapping = GetStateMapping(connection); - - ModifyTableAndMassageData(connection, stateMapping); - } - - private Dictionary GetStateMapping(SqliteConnection connection) - { - Log.Debug("Fetching states and mapping to integers..."); - - using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); - using var reader = command.ExecuteReader(); - - var dict = new Dictionary(); - - while (reader.Read()) - { - var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(TransferStates), state); - } - - Log.Debug("State -> int map: {Map}", dict); - return dict; - } - - private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) - { - using var transaction = connection.BeginTransaction(); - - try - { - /* - rename old table so we can create the new one with the layout we want - while preserving the existing data - */ - var rename = @" - ALTER TABLE Transfers RENAME TO Transfers_old; - "; - - using var renameCommand = new SqliteCommand(rename, connection, transaction); - renameCommand.ExecuteNonQuery(); - - /* - create the new table with StateDescription appearing after State - */ - var create = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - ); - "; - - using var createCommand = new SqliteCommand(create, connection, transaction); - createCommand.ExecuteNonQuery(); - - Log.Information("Schema changes applied, copying data..."); - - /* - copy the existing data into the new table - */ - var copy = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using var copyCommand = new SqliteCommand(copy, connection, transaction); - copyCommand.ExecuteNonQuery(); - - Log.Information("Data copied, adjusting columns..."); - - /* - we no longer need the old table, so drop it - */ - using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); - dropCommand.ExecuteNonQuery(); - - /* - copy the existing (string) State value from State to StateDescription - */ - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - /* - for each of the distinct State values that exist in the data, convert the string - representation into the numeric - - there surely exist better ways to do this, but the reality is that 99% of the records - will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" - sprinkled in. this should run in reasonable time for large collections - */ - var sw = new Stopwatch(); - var step = 1; - - foreach (var state in stateMapping) - { - sw.Reset(); - Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); - - Log.Debug("Setting {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); - mapCommand.ExecuteNonQuery(); - - Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); - } - - Log.Debug("Committing transation..."); - transaction.Commit(); - Log.Debug("Transaction committed!"); - Log.Information("Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs new file mode 100644 index 00000000..2210ba13 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/z04012025_TransferStateMigration.cs @@ -0,0 +1,204 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. + +// + +namespace slskd.Migrations; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using Soulseek; + +/// +/// 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 +/// +/// 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 +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class z04012025_TransferStateMigration : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; + + public void Apply() + { + // first, check the existing database to see if the StatusDescription column exists + // if it does, the migration has already been applied + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var txfers = schema["Transfers"]; + + if (txfers.Any(c => c.Name == "StatusDescription")) + { + Log.Information("Migration {Name} has already been applied", nameof(z04012025_TransferStateMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + ModifyTableAndMassageData(connection, stateMapping); + } + + private Dictionary GetStateMapping(SqliteConnection connection) + { + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) + { + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(TransferStates), state); + } + + Log.Debug("State -> int map: {Map}", dict); + return dict; + } + + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) + { + using var transaction = connection.BeginTransaction(); + + try + { + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + Log.Information("Schema changes applied, copying data..."); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + Log.Information("Data copied, adjusting columns..."); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + */ + var sw = new Stopwatch(); + var step = 1; + + foreach (var state in stateMapping) + { + sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); + } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + Log.Information("Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index ffaae586..14c97272 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -53,7 +53,7 @@ public class Migrator /// private Dictionary Migrations { get; } = new() { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + { nameof(z04012025_TransferStateMigration), new z04012025_TransferStateMigration() }, }; /// -- cgit v1.2.3