diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-04-01 19:14:06 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-04-01 19:14:06 -0500 |
| commit | e08b71168e64928f0664eab2b7c070b9d20b6783 (patch) | |
| tree | 881461de46b265cf11706372cfca3571e6f12a5f | |
| parent | eec6e0f098effcb9bfda297a441ca7ffd8d33934 (diff) | |
| download | slskd-e08b71168e64928f0664eab2b7c070b9d20b6783.tar.gz | |
wip
| -rw-r--r-- | src/slskd/Core/Migrations/TransferStateMigration_04012025.cs | 144 | ||||
| -rw-r--r-- | src/slskd/Core/Migrator.cs | 93 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 4 |
3 files changed, 241 insertions, 0 deletions
diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs new file mode 100644 index 00000000..6b03567a --- /dev/null +++ b/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs @@ -0,0 +1,144 @@ +// <copyright file="TransferStateMigration.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Migrations; + +using System; +using System.IO; +using Microsoft.Data.Sqlite; + +public class TransferStateMigration_04012025 : IMigration +{ + public void Apply() + { + + } + + static void AddStateDescriptionColumn(string dbPath) + { + if (!File.Exists(dbPath)) + { + Console.WriteLine("Database file not found."); + return; + } + + string connectionString = $"Data Source={dbPath};Version=3;"; + + using (var connection = new SqliteConnection(connectionString)) + { + connection.Open(); + + // Check if the column exists + bool columnExists = false; + using (var command = new SqliteCommand("PRAGMA table_info(Transfers);", connection)) + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + string columnName = reader["name"].ToString(); + if (columnName.Equals("StateDescription", StringComparison.OrdinalIgnoreCase)) + { + columnExists = true; + break; + } + } + } + + if (columnExists) + { + Console.WriteLine("Column 'StateDescription' already exists."); + return; + } + + Console.WriteLine("Adding 'StateDescription' column..."); + + using (var transaction = connection.BeginTransaction()) + { + try + { + // Rename old table + using (var renameCommand = new SqliteCommand("ALTER TABLE Transfers RENAME TO Transfers_old;", connection)) + { + renameCommand.ExecuteNonQuery(); + } + + // Create new table with StateDescription after State + string createNewTableSQL = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State TEXT 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(createNewTableSQL, connection)) + { + createCommand.ExecuteNonQuery(); + } + + // Copy data into the new table + string copyDataSQL = @" + 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(copyDataSQL, connection)) + { + copyCommand.ExecuteNonQuery(); + } + + // Drop the old table + using (var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection)) + { + dropCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + Console.WriteLine("Column 'StateDescription' added successfully."); + } + catch (Exception ex) + { + transaction.Rollback(); + Console.WriteLine($"Error: {ex.Message}"); + } + } + + connection.Close(); + } + } +} diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Migrator.cs new file mode 100644 index 00000000..a83f4764 --- /dev/null +++ b/src/slskd/Core/Migrator.cs @@ -0,0 +1,93 @@ +// <copyright file="Migrator.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd; + +using System; +using System.Collections.Generic; +using System.IO; +using Serilog; +using slskd.Migrations; + +public interface IMigration +{ + public void Apply(); +} + +public class Migrator +{ + private string HistoryFile { get; } = Path.Combine(Program.DataDirectory, "misc", "migration.history"); + private ILogger Log { get; } = Serilog.Log.ForContext<Migrator>(); + + private Dictionary<string, IMigration> Migrations { get; } = new() + { + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + }; + + public void Migrate() + { + Dictionary<string, DateTime> history = new(); + + try + { + if (File.Exists(HistoryFile)) + { + try + { + var txt = File.ReadAllText(HistoryFile); + history = txt.FromJson<Dictionary<string, DateTime>>(); + + Log.Debug("Loaded migration history from {HistoryFile}: {History}", HistoryFile, history); + } + catch (Exception ex) + { + Log.Warning("Failed to load migration history from {HistoryFile}: {Message}", HistoryFile, ex.Message); + Log.Warning("Migration history will be overwritten and all migrations will be applied"); + } + } + + foreach (var migration in Migrations) + { + if (history.TryGetValue(migration.Key, out var timestamp)) + { + Log.Debug("Migration {Name} was already applied {Date}", migration.Key, timestamp); + continue; + } + + try + { + migration.Value.Apply(); + history[migration.Key] = DateTime.UtcNow; + + Log.Information("Migration {Name} was applied successfully", migration.Key); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migration {Name}: {Message}", migration.Key, ex.Message); + throw; + } + } + + File.WriteAllText(HistoryFile, history.ToJson()); + } + catch (Exception ex) + { + Log.Fatal(ex, "Failed to apply migrations: {Message}", ex.Message); + throw; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b7fa47d2..50ae7a07 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -596,6 +596,10 @@ namespace slskd services.AddDbContext<TransfersDbContext>(DiskConnectionString("transfers")); services.AddDbContext<MessagingDbContext>(DiskConnectionString("messaging")); services.AddDbContext<EventsDbContext>(DiskConnectionString("events")); + + // we're working with non-volatile database files, so register a Migrator to be used later in the + // bootup process. the presence of a Migrator instance in DI determines whether a migration is needed. + services.AddSingleton<Migrator>(_ => new Migrator()); } services.AddSingleton<EventService>(); |
