From cca8a2d11aadfb311beaa9c6369791e4dea0cc63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 21:44:14 -0600 Subject: change migration naming scheme to order by year --- src/slskd/Core/Data/Migrations/README.md | 2 +- .../Migrations/Z04012025_TransferStateMigration.cs | 236 --------------------- .../Z07062025_TransferIndexesMigration.cs | 92 -------- ...Z07262025_PrivateMessageWasReplayedMigration.cs | 84 -------- ...Z12282025_AdditionalTransferIndexesMigration.cs | 93 -------- .../Z2025_04_01_TransferStateMigration.cs | 236 +++++++++++++++++++++ .../Z2025_07_06_TransferIndexesMigration.cs | 92 ++++++++ ...025_07_26_PrivateMessageWasReplayedMigration.cs | 83 ++++++++ ...025_12_28_AdditionalTransferIndexesMigration.cs | 93 ++++++++ 9 files changed, 505 insertions(+), 506 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index 2b5fd6f4..46da7ded 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -11,7 +11,7 @@ The `Migrator` creates a backup of each database prior to running any migrations Each migration must be created as a class that implements the `IMigration` interface. The naming convention for migration classes is: ``` -Z_Migration +Z_Migration ``` Migrations MUST: diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs deleted file mode 100644 index c6e3d2f1..00000000 --- a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs +++ /dev/null @@ -1,236 +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.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using slskd.Transfers; - -/// -/// Updates the Transfers table to: -/// -/// * 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 -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class Z04012025_TransferStateMigration : IMigration -{ - public Z04012025_TransferStateMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // 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"]; - - return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or 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(Z04012025_TransferStateMigration_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; - } - } - -#pragma warning disable SA1201 // Elements should appear in the correct order - /// - /// This is a copy of the TransferStates enum as it was at the time this migration was written. This exists to ensure - /// that the migration can be applied to any version of the database, even if the enum changes in the future. - /// - [Flags] - private enum Z04012025_TransferStateMigration_TransferStates - { - None = 0, - Requested = 1, - Queued = 2, - Initializing = 4, - InProgress = 8, - Completed = 16, - Succeeded = 32, - Cancelled = 64, - TimedOut = 128, - Errored = 256, - Rejected = 512, - Aborted = 1024, - Locally = 2048, - Remotely = 4096, - } -#pragma warning restore SA1201 // Elements should appear in the correct order -} diff --git a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs deleted file mode 100644 index 8ae13734..00000000 --- a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs +++ /dev/null @@ -1,92 +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.Linq; -using Microsoft.Data.Sqlite; -using Serilog; - -/// -/// Updates the Transfers table to add indexes on the Direction and State columns. -/// -public class Z07062025_TransferIndexesMigration : IMigration -{ - public Z07062025_TransferIndexesMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); - var txfers = idxes["Transfers"]; - - var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase)); - var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase)); - - if (directionExists && stateExists) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z07062025_TransferIndexesMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - Log.Information("> Adding missing index(es) on the Transfers table..."); - - var directionCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Direction ON Transfers (Direction) - ", connection, transaction); - directionCommand.ExecuteNonQuery(); - - var stateCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_State ON Transfers (State) - ", connection, transaction); - stateCommand.ExecuteNonQuery(); - - Log.Information("> Index(es) created"); - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs b/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs deleted file mode 100644 index a458a756..00000000 --- a/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs +++ /dev/null @@ -1,84 +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.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using slskd.Messaging; - -/// -/// Updates the Transfers table to add indexes on the Direction and State columns. -/// -public class Z07262025_PrivateMessageWasReplayedMigration : IMigration -{ - public Z07262025_PrivateMessageWasReplayedMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Messaging]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var pms = schema["PrivateMessages"]; - - if (pms.Any(r => r.Name == nameof(PrivateMessage.WasReplayed))) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z07262025_PrivateMessageWasReplayedMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - Log.Information("> Adding missing column WasReplayed to PrivateMessages table..."); - - var addColumnCommand = new SqliteCommand(@" - ALTER TABLE PrivateMessages ADD COLUMN WasReplayed INTEGER NOT NULL DEFAULT 0 - ", connection, transaction); - addColumnCommand.ExecuteNonQuery(); - - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs deleted file mode 100644 index 2deffeb3..00000000 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ /dev/null @@ -1,93 +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.Linq; -using Microsoft.Data.Sqlite; -using Serilog; - -/// -/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. -/// -public class Z12282025_AdditionalTransferIndexesMigration : IMigration -{ - public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); - var txfers = idxes["Transfers"]; - - var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); - var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); - var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); - - if (removedExists && usernameFilenameExists && statsExist) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z12282025_AdditionalTransferIndexesMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - void Exec(string sql) - { - using var command = new SqliteCommand(sql, connection, transaction); - command.ExecuteNonQuery(); - } - - Log.Information("> Adding missing index(es) on the Transfers table..."); - - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); - - Log.Information("> Index(es) created"); - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs new file mode 100644 index 00000000..146541dd --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs @@ -0,0 +1,236 @@ +// +// 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.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Transfers; + +/// +/// Updates the Transfers table to: +/// +/// * 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 +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class Z2025_04_01_TransferStateMigration : IMigration +{ + public Z2025_04_01_TransferStateMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // 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"]; + + return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_04_01_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(Z04012025_TransferStateMigration_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; + } + } + +#pragma warning disable SA1201 // Elements should appear in the correct order + /// + /// This is a copy of the TransferStates enum as it was at the time this migration was written. This exists to ensure + /// that the migration can be applied to any version of the database, even if the enum changes in the future. + /// + [Flags] + private enum Z04012025_TransferStateMigration_TransferStates + { + None = 0, + Requested = 1, + Queued = 2, + Initializing = 4, + InProgress = 8, + Completed = 16, + Succeeded = 32, + Cancelled = 64, + TimedOut = 128, + Errored = 256, + Rejected = 512, + Aborted = 1024, + Locally = 2048, + Remotely = 4096, + } +#pragma warning restore SA1201 // Elements should appear in the correct order +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs new file mode 100644 index 00000000..df93f685 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs @@ -0,0 +1,92 @@ +// +// 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.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z2025_07_06_TransferIndexesMigration : IMigration +{ + public Z2025_07_06_TransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase)); + var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase)); + + if (directionExists && stateExists) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_07_06_TransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing index(es) on the Transfers table..."); + + var directionCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Direction ON Transfers (Direction) + ", connection, transaction); + directionCommand.ExecuteNonQuery(); + + var stateCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_State ON Transfers (State) + ", connection, transaction); + stateCommand.ExecuteNonQuery(); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs new file mode 100644 index 00000000..c3f3664b --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs @@ -0,0 +1,83 @@ +// +// 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.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Messaging; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z2025_07_26_PrivateMessageWasReplayedMigration : IMigration +{ + public Z2025_07_26_PrivateMessageWasReplayedMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Messaging]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var pms = schema["PrivateMessages"]; + + if (pms.Any(r => r.Name == nameof(PrivateMessage.WasReplayed))) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_07_26_PrivateMessageWasReplayedMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing column WasReplayed to PrivateMessages table..."); + + var addColumnCommand = new SqliteCommand(@" + ALTER TABLE PrivateMessages ADD COLUMN WasReplayed INTEGER NOT NULL DEFAULT 0 + ", connection, transaction); + addColumnCommand.ExecuteNonQuery(); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs new file mode 100644 index 00000000..e66cc59d --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs @@ -0,0 +1,93 @@ +// +// 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.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. +/// +public class Z2025_12_28_AdditionalTransferIndexesMigration : IMigration +{ + public Z2025_12_28_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); + var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); + + if (removedExists && usernameFilenameExists && statsExist) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_12_28_AdditionalTransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Adding missing index(es) on the Transfers table..."); + + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3