diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-04-04 19:01:17 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-04-04 19:01:17 -0500 |
| commit | 534d8824c4a3f1aae0448a17f734b57ea395c59f (patch) | |
| tree | ea7ea00ec0567e605fb141daad81fd48679910e2 /src | |
| parent | 8f4dea8f4fe7708ddc8dd1f15dc8579dfab8b4d5 (diff) | |
| download | slskd-534d8824c4a3f1aae0448a17f734b57ea395c59f.tar.gz | |
wip
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Waiter.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/Migration.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs (renamed from src/slskd/Core/Migrations/TransferStateMigration_04012025.cs) | 68 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs (renamed from src/slskd/Core/Migrator.cs) | 26 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 2 |
5 files changed, 125 insertions, 55 deletions
diff --git a/src/slskd/Common/Waiter.cs b/src/slskd/Common/Waiter.cs index f8b3d305..d32f23b4 100644 --- a/src/slskd/Common/Waiter.cs +++ b/src/slskd/Common/Waiter.cs @@ -450,7 +450,7 @@ namespace slskd if (disposing) { CancellationTokenRegistration.Dispose(); - TimeoutTokenSource.Dispose(); + TimeoutTokenSource?.Dispose(); TimeoutTokenRegistration.Dispose(); } diff --git a/src/slskd/Core/Data/Migrations/Migration.cs b/src/slskd/Core/Data/Migrations/Migration.cs new file mode 100644 index 00000000..02f87a9c --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Migration.cs @@ -0,0 +1,82 @@ +// <copyright file="Migration.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.Collections.Generic; +using System.IO; +using Microsoft.Data.Sqlite; + +public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); + +public abstract class Migration +{ + public Migration(string databaseName) + { + DatabaseName = databaseName; + } + + public string DatabaseName { get; } + public string DatabaseFileName => Path.Combine(Program.DataDirectory, DatabaseName); + public string ConnectionString => $"Data Source={DatabaseFileName}.db"; + + public abstract void Apply(); + + protected Dictionary<string, IEnumerable<ColumnInfo>> GetDatabaseSchema() + { + try + { + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + var dict = new Dictionary<string, IEnumerable<ColumnInfo>>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var columns = new List<ColumnInfo>(); + + using var columnCommand = new SqliteCommand($"PRAGMA table_info({table});", connection); + using var cr = columnCommand.ExecuteReader(); + + while (cr.Read()) + { + columns.Add(new ColumnInfo( + Cid: cr.GetInt64(cr.GetOrdinal("cid")), + Name: cr.GetString(cr.GetOrdinal("name")), + Type: cr.GetString(cr.GetOrdinal("type")), + NotNull: cr.GetInt64(cr.GetOrdinal("notnull")) > 0, + DefaultValue: cr["dflt_value"], + PrimaryKey: cr.GetInt64(cr.GetOrdinal("pk")) > 0)); + } + + dict[table] = columns; + } + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve schema information for database '{DatabaseName}'. The database might be corrupt or in use by another application; if the problem persists the file ({DatabaseFileName}) may need to be deleted", ex); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index ea295851..37171a77 100644 --- a/src/slskd/Core/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -1,4 +1,4 @@ -// <copyright file="TransferStateMigration.cs" company="slskd Team"> +// <copyright file="TransferStateMigration_04012025.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -21,18 +21,46 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text.Json; using Microsoft.Data.Sqlite; - -public class TransferStateMigration_04012025 : IMigration +using Serilog; + +/// <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 +/// +/// 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. +/// </summary> +public class TransferStateMigration_04012025 : Migration { + public TransferStateMigration_04012025(string databasName) + : base(databasName) + { + } + private string DbName => "transfers"; + private ILogger Log { get; } = Serilog.Log.ForContext<TransferStateMigration_04012025>(); - public void Apply(IEnumerable<string> databases) + public override void Apply() { - if (!databases.Contains(DbName)) + // first, check the existing database to see if the StatusDescription column exists + // if it does, the migration has already been applied + var schema = GetDatabaseSchema(); + var txfers = schema["Transfers"]; + + if (txfers.Any(c => c.Name == "StatusDescription")) { - throw new SlskdException($"Attempting to migrate database {DbName} but {DbName} is not in the list of known databases ({string.Join(",", databases)}). This is a precautionary check to ensure databases are properly backed up prior to migration, and the check has failed. Only an application update can fix this; please create an urgent issue: {Program.IssuesUrl}"); + Log.Information("Migration {Name} has already been applied", nameof(TransferStateMigration_04012025)); + return; } + + AddStateDescriptionColumn(Path.Combine(Program.DataDirectory, "transfers.db")); } static void AddStateDescriptionColumn(string dbPath) @@ -43,36 +71,12 @@ public class TransferStateMigration_04012025 : IMigration return; } - string connectionString = $"Data Source={dbPath};Version=3;"; + string connectionString = $"Data Source={dbPath};"; 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 @@ -92,7 +96,7 @@ public class TransferStateMigration_04012025 : IMigration Filename TEXT, Size INTEGER NOT NULL, StartOffset INTEGER NOT NULL, - State TEXT NOT NULL, + State INTEGER NOT NULL, StateDescription TEXT, -- New column RequestedAt TEXT NOT NULL, EnqueuedAt TEXT, diff --git a/src/slskd/Core/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 86056751..f3543ca9 100644 --- a/src/slskd/Core/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -26,23 +26,6 @@ using Serilog; using slskd.Migrations; /// <summary> -/// A database migration. -/// </summary> -public interface IMigration -{ - /// <summary> - /// Apply the database migration. - /// </summary> - /// <remarks> - /// The database list is included to help ensure that we're backing up databases before we start. Migrations - /// must check the supplied list to ensure the database(s) they are attempting to migrate are included; if - /// they are missing they haven't been backed up. - /// </remarks> - /// <param name="databases">A list of known databases.</param> - public void Apply(IEnumerable<string> databases); -} - -/// <summary> /// Applies database migrations. /// </summary> public class Migrator @@ -63,9 +46,9 @@ public class Migrator /// <summary> /// A map of all migrations, to be applied in the order they are specified (descending). /// </summary> - private Dictionary<string, IMigration> Migrations { get; } = new() + private Dictionary<string, Migration> Migrations { get; } = new() { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025("transfers") }, }; /// <summary> @@ -167,7 +150,7 @@ public class Migrator try { - Migrations[migration].Apply(Databases); + Migrations[migration].Apply(); history[migration] = DateTime.UtcNow; Log.Information("Migration {Name} was applied successfully (elapsed: {Duration}ms)", migration, currentSw.ElapsedMilliseconds); @@ -207,10 +190,9 @@ public class Migrator { Log.Fatal(restoreEx, "Failed to restore one or more databases from backup: {Message}", restoreEx.Message); Log.Fatal("Restore manually by renaming '<database>.db.pre-migration' to '<database>.db' prior to starting the application again."); - throw; } - throw; + throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); } var newHistory = history.ToJson(); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 690960a7..763b345a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -500,6 +500,8 @@ namespace slskd app.Services.GetService<Migrator>().Migrate(force: OptionsAtStartup.Flags.ForceMigrations); } + Environment.Exit(1); + // hack: services that exist only to subscribe to the event bus are not referenced by anything else // and are thus never instantiated. force a reference here so they are created. _ = app.Services.GetService<ScriptService>(); |
