Lidarr/src/NzbDrone.Core/Datastore/Migration/Framework/MigrationController.cs

91 lines
2.9 KiB
C#
Raw Normal View History

using System;
using System.Diagnostics;
using System.Reflection;
2013-03-25 06:13:53 +00:00
using FluentMigrator.Runner;
using FluentMigrator.Runner.Generators;
2013-03-25 06:13:53 +00:00
using FluentMigrator.Runner.Initialization;
2019-10-28 21:12:26 +00:00
using FluentMigrator.Runner.Processors;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
2013-03-25 06:13:53 +00:00
namespace NzbDrone.Core.Datastore.Migration.Framework
{
public interface IMigrationController
{
void Migrate(string connectionString, MigrationContext migrationContext);
2013-03-25 06:13:53 +00:00
}
public class MigrationController : IMigrationController
{
2019-10-28 21:12:26 +00:00
private readonly Logger _logger;
private readonly ILoggerProvider _migrationLoggerProvider;
2013-03-25 06:13:53 +00:00
2019-10-28 21:12:26 +00:00
public MigrationController(Logger logger,
ILoggerProvider migrationLoggerProvider)
2013-03-25 06:13:53 +00:00
{
2019-10-28 21:12:26 +00:00
_logger = logger;
_migrationLoggerProvider = migrationLoggerProvider;
2013-03-25 06:13:53 +00:00
}
public void Migrate(string connectionString, MigrationContext migrationContext)
2013-03-25 06:13:53 +00:00
{
var sw = Stopwatch.StartNew();
2019-10-28 21:12:26 +00:00
_logger.Info("*** Migrating {0} ***", connectionString);
2013-11-30 21:08:53 +00:00
ServiceProvider serviceProvider;
var db = connectionString.Contains(".db") ? "sqlite" : "postgres";
serviceProvider = new ServiceCollection()
.AddLogging(b => b.AddNLog())
2019-10-28 21:12:26 +00:00
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
.AddPostgres()
2019-10-28 21:12:26 +00:00
.AddNzbDroneSQLite()
.WithGlobalConnectionString(connectionString)
.WithMigrationsIn(Assembly.GetExecutingAssembly()))
.Configure<TypeFilterOptions>(opt => opt.Namespace = "NzbDrone.Core.Datastore.Migration")
.Configure<ProcessorOptions>(opt =>
{
opt.PreviewOnly = false;
opt.Timeout = TimeSpan.FromSeconds(60);
})
.Configure<SelectingProcessorAccessorOptions>(cfg =>
{
cfg.ProcessorId = db;
})
.Configure<SelectingGeneratorAccessorOptions>(cfg =>
{
cfg.GeneratorId = db;
})
2019-10-28 21:12:26 +00:00
.BuildServiceProvider();
2013-11-30 21:08:53 +00:00
2019-10-28 21:12:26 +00:00
using (var scope = serviceProvider.CreateScope())
{
2019-10-28 21:12:26 +00:00
var runner = scope.ServiceProvider.GetRequiredService<IMigrationRunner>();
2013-11-30 21:08:53 +00:00
2019-10-28 21:12:26 +00:00
MigrationContext.Current = migrationContext;
if (migrationContext.DesiredVersion.HasValue)
{
2019-10-28 21:12:26 +00:00
runner.MigrateUp(migrationContext.DesiredVersion.Value);
}
else
{
2019-10-28 21:12:26 +00:00
runner.MigrateUp();
}
2019-10-28 21:12:26 +00:00
MigrationContext.Current = null;
}
sw.Stop();
2019-10-28 21:12:26 +00:00
_logger.Debug("Took: {0}", sw.Elapsed);
2013-03-25 06:13:53 +00:00
}
}
}