diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-04-05 16:55:54 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-04-05 16:55:54 -0500 |
| commit | 836934203dc314e08b3e351f60bbf70f14a1d1fc (patch) | |
| tree | 8383f6257ef1fa766753a3b08ab3f7a2cba6c619 /src | |
| parent | a21903811d39a978e2c6acc275bba670abee5574 (diff) | |
| download | slskd-836934203dc314e08b3e351f60bbf70f14a1d1fc.tar.gz | |
more wip
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Core/Data/Migrations/Migration.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs | 56 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Migrator.cs | 64 |
4 files changed, 122 insertions, 95 deletions
diff --git a/src/slskd/Core/Data/Migrations/Migration.cs b/src/slskd/Core/Data/Migrations/Migration.cs deleted file mode 100644 index 02f87a9c..00000000 --- a/src/slskd/Core/Data/Migrations/Migration.cs +++ /dev/null @@ -1,82 +0,0 @@ -// <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/Data/Migrations/TEMP_SeedTransfers.cs b/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs new file mode 100644 index 00000000..9f973023 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/TEMP_SeedTransfers.cs @@ -0,0 +1,56 @@ +// <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 +// 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; +using Serilog; + +public class TEMP_SeedTransfers : IMigration +{ + private ILogger Log { get; } = Serilog.Log.ForContext<TransferStateMigration_04012025>(); + + public void Apply() + { + using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); + connection.Open(); + + Log.Warning("Staring seed"); + + for (long i = 0; i < 10_000; i++) + { + string s(Guid id) => @$" + INSERT INTO Transfers (Id, Username, Direction, Filename, Size, StartOffset, State, RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, AverageSpeed, PlaceInQueue, Removed) + VALUES ('{id}', 'Username', 'Download', 'Foo.mp3', 42, 0, 'Completed, Succeeded', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', '1/1/1970 0:0:0', 42, 0, 0, 1); + "; + + string sql = ""; + + for (int j = 0; j < 5_000; j++) + { + sql += s(Guid.NewGuid()); + } + + using var cmd = new SqliteCommand(sql, connection); + + cmd.ExecuteNonQuery(); + Log.Warning("Completed {i}", i * 5000); + } + } +} diff --git a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs index a3da5435..6d8b4cfc 100644 --- a/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs +++ b/src/slskd/Core/Data/Migrations/TransferStateMigration_04012025.cs @@ -38,20 +38,17 @@ using Soulseek; /// 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 class TransferStateMigration_04012025 : IMigration { - public TransferStateMigration_04012025(string databasName) - : base(databasName) - { - } - private ILogger Log { get; } = Serilog.Log.ForContext<TransferStateMigration_04012025>(); + private string DatabaseName { get; } = "transfers"; + private string ConnectionString => $"Data Source={Path.Combine(Program.DataDirectory, $"{DatabaseName}.db")}"; - public override void Apply() + 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 = GetDatabaseSchema(); + var schema = Migrator.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; if (txfers.Any(c => c.Name == "StatusDescription")) @@ -60,7 +57,7 @@ public class TransferStateMigration_04012025 : Migration return; } - using var connection = new SqliteConnection($"Data Source={Path.Combine(Program.DataDirectory, "transfers.db")}"); + 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 diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index f3543ca9..152624ba 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -22,9 +22,15 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; +using Microsoft.Data.Sqlite; using Serilog; using slskd.Migrations; +public interface IMigration +{ + void Apply(); +} + /// <summary> /// Applies database migrations. /// </summary> @@ -46,9 +52,10 @@ public class Migrator /// <summary> /// A map of all migrations, to be applied in the order they are specified (descending). /// </summary> - private Dictionary<string, Migration> Migrations { get; } = new() + private Dictionary<string, IMigration> Migrations { get; } = new() { - { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025("transfers") }, + // { nameof(TransferStateMigration_04012025), new TransferStateMigration_04012025() }, + { nameof(TEMP_SeedTransfers), new TEMP_SeedTransfers() }, }; /// <summary> @@ -100,6 +107,10 @@ public class Migrator Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsNotYetApplied.Count()); + var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss"); + + Log.Warning("-----> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups. <-----", migrationId); + // take some simple backups before we do anything. this gives users a way to get back to a working configuration // if the migration is interrupted, fails, or if the user wants to revert to the previous version. these files // must be left in place after the migration completes, and they'll be overwritten the next time a migration is applied @@ -111,7 +122,7 @@ public class Migrator { var name = Path.Combine(Program.DataDirectory, database); var src = $"{name}.db"; - var dest = $"{name}.db.pre-migration"; + var dest = $"{name}.pre-migration.{migrationId}.db"; File.Copy(src, dest, overwrite: true); @@ -189,7 +200,7 @@ public class Migrator catch (Exception restoreEx) { 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."); + Log.Fatal($"Restore manually by renaming '<database>.pre-migration.{migrationId}.db' to '<database>.db' prior to starting the application again."); } throw new SlskdException("Failed to apply one or more database migrations. See inner Exception for details.", ex); @@ -201,4 +212,49 @@ public class Migrator Log.Information("Migration(s) complete"); } + + public static Dictionary<string, IEnumerable<ColumnInfo>> GetDatabaseSchema(string connectionString) + { + 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 '{connectionString}'. The database might be corrupt or in use by another application; if the problem persists the backing file may need to be deleted", ex); + } + } + + public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); }
\ No newline at end of file |
