Added our own custom migrations, a lot easier to migrate DB versions now.

pull/609/head
tidusjar 8 years ago
parent 171c64fe8e
commit 6e3339ad3c

@ -0,0 +1,37 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: IMigration.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Data;
namespace PlexRequests.Core.Migration
{
public interface IMigration
{
int Version { get; }
void Start(IDbConnection con);
}
}

@ -0,0 +1,7 @@
namespace PlexRequests.Core.Migration
{
public interface IMigrationRunner
{
void MigrateToLatest();
}
}

@ -0,0 +1,33 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Migrate.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
namespace PlexRequests.Core.Migration
{
public class Migrate
{
}
}

@ -0,0 +1,43 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Migration.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System;
namespace PlexRequests.Core.Migration
{
[AttributeUsage(AttributeTargets.Class)]
public class Migration : Attribute
{
public Migration(int version, string description)
{
Version = version;
Description = description;
}
public int Version { get; private set; }
public string Description { get; private set; }
}
}

@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using Ninject;
using PlexRequests.Store;
namespace PlexRequests.Core.Migration
{
public class MigrationRunner : IMigrationRunner
{
public MigrationRunner(ISqliteConfiguration db, IKernel kernel)
{
Db = db;
Kernel = kernel;
}
private IKernel Kernel { get; }
private ISqliteConfiguration Db { get; }
public void MigrateToLatest()
{
var con = Db.DbConnection();
var versions = GetMigrations().OrderBy(x => x.Key);
var dbVersion = con.GetVersionInfo().OrderByDescending(x => x.Version).FirstOrDefault();
if (dbVersion == null)
{
dbVersion = new TableCreation.VersionInfo { Version = 0 };
}
foreach (var v in versions)
{
if (v.Value.Version > dbVersion.Version)
{
// Assuming only one constructor
var ctor = v.Key.GetConstructors().FirstOrDefault();
var dependencies = new List<object>();
foreach (var param in ctor.GetParameters())
{
Console.WriteLine(string.Format(
"Param {0} is named {1} and is of type {2}",
param.Position, param.Name, param.ParameterType));
var dep = Kernel.Get(param.ParameterType);
dependencies.Add(dep);
}
var method = v.Key.GetMethod("Start");
if (method != null)
{
object result = null;
var classInstance = Activator.CreateInstance(v.Key, dependencies.Any() ? dependencies.ToArray() : null);
var parametersArray = new object[] { Db.DbConnection() };
method.Invoke(classInstance, parametersArray);
}
}
}
}
public static Dictionary<Type, MigrationModel> GetMigrations()
{
var migrationTypes = GetTypesWithHelpAttribute(Assembly.GetAssembly(typeof(MigrationRunner)));
var version = new Dictionary<Type, MigrationModel>();
foreach (var t in migrationTypes)
{
var customAttributes = (Migration[])t.GetCustomAttributes(typeof(Migration), true);
if (customAttributes.Length > 0)
{
var attr = customAttributes[0];
version.Add(t, new MigrationModel { Version = attr.Version, Description = attr.Description });
}
}
return version;
}
private static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly)
{
return assembly.GetTypes().Where(type => type.GetCustomAttributes(typeof(Migration), true).Length > 0);
}
public class MigrationModel
{
public int Version { get; set; }
public string Description { get; set; }
}
}
}

@ -0,0 +1,53 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: BaseMigration.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Collections.Generic;
using System.Data;
using System.Linq;
using PlexRequests.Store;
namespace PlexRequests.Core.Migration.Migrations
{
public abstract class BaseMigration
{
protected void UpdateSchema(IDbConnection con, int version)
{
var migrations = MigrationRunner.GetMigrations();
var model = migrations.Select(x => x.Value).FirstOrDefault(x => x.Version == version);
if (model != null)
{
con.AddVersionInfo(new TableCreation.VersionInfo { Version = model.Version, Description = model.Description });
}
}
protected IEnumerable<TableCreation.VersionInfo> GetVersionInfo(IDbConnection con)
{
return con.GetVersionInfo();
}
}
}

@ -0,0 +1,63 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: Version195.cs
// Created By: Jamie Rees
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ************************************************************************/
#endregion
using System.Data;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.Core.Migration.Migrations
{
[Migration(1950, "v1.9.5.0")]
public class Version195 : BaseMigration, IMigration
{
public Version195(ISettingsService<PlexRequestSettings> plexRequestSettings, ISettingsService<NewletterSettings> news)
{
PlexRequestSettings = plexRequestSettings;
NewsletterSettings = news;
}
public int Version => 1950;
private ISettingsService<PlexRequestSettings> PlexRequestSettings { get; }
private ISettingsService<NewletterSettings> NewsletterSettings { get; }
public void Start(IDbConnection con)
{
var plex = PlexRequestSettings.GetSettings();
var newsLetter = NewsletterSettings.GetSettings();
if (plex.SendRecentlyAddedEmail)
{
newsLetter.SendRecentlyAddedEmail = plex.SendRecentlyAddedEmail;
plex.SendRecentlyAddedEmail = false;
PlexRequestSettings.SaveSettings(plex);
NewsletterSettings.SaveSettings(newsLetter);
}
UpdateSchema(con, Version);
}
}
}

@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8406EE57-D533-47C0-9302-C6B5F8C31E55}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>PlexRequests.Core.Migration</RootNamespace>
<AssemblyName>PlexRequests.Core.Migration</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Data.Sqlite">
<HintPath>..\Assemblies\Mono.Data.Sqlite.dll</HintPath>
</Reference>
<Reference Include="Ninject">
<HintPath>..\packages\Ninject.3.2.0.0\lib\net45-full\Ninject.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="IMigration.cs" />
<Compile Include="IMigrationRunner.cs" />
<Compile Include="Migrate.cs" />
<Compile Include="MigrationAttribute.cs" />
<Compile Include="MigrationRunner.cs" />
<Compile Include="Migrations\BaseMigration.cs" />
<Compile Include="Migrations\Version195.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PlexRequests.Core\PlexRequests.Core.csproj">
<Project>{DD7DC444-D3BF-4027-8AB9-EFC71F5EC581}</Project>
<Name>PlexRequests.Core</Name>
</ProjectReference>
<ProjectReference Include="..\PlexRequests.Store\PlexRequests.Store.csproj">
<Project>{92433867-2B7B-477B-A566-96C382427525}</Project>
<Name>PlexRequests.Store</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PlexRequests.Core.Migration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlexRequests.Core.Migration")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8406ee57-d533-47c0-9302-c6b5f8c31e55")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -60,6 +60,8 @@ namespace PlexRequests.Core
TableCreation.Vacuum(Db.DbConnection());
}
// The below code is obsolete, we should use PlexRequests.Core.Migrations.MigrationRunner
var version = CheckSchema();
if (version > 0)
{
@ -72,10 +74,6 @@ namespace PlexRequests.Core
{
MigrateToVersion1910();
}
if (version > 1943 && version <= 1945)
{
MigrateToVersion1945();
}
}
return Db.DbConnection().ConnectionString;
@ -279,31 +277,5 @@ namespace PlexRequests.Core
Log.Error(e);
}
}
/// <summary>
/// Migrates to version1945
/// </summary>
public void MigrateToVersion1945()
{
try
{
var settings = new SettingsServiceV2<PlexRequestSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var plex = settings.GetSettings();
var newsLetterSettings = new SettingsServiceV2<NewletterSettings>(new SettingsJsonRepository(Db, new MemoryCacheProvider()));
var newsLetter = newsLetterSettings.GetSettings();
if (plex.SendRecentlyAddedEmail)
{
newsLetter.SendRecentlyAddedEmail = plex.SendRecentlyAddedEmail;
plex.SendRecentlyAddedEmail = false;
settings.SaveSettings(plex);
newsLetterSettings.SaveSettings(newsLetter);
}
}
catch (Exception e)
{
Log.Error(e);
}
}
}
}

@ -59,6 +59,12 @@ CREATE TABLE IF NOT EXISTS DBInfo
SchemaVersion INTEGER
);
CREATE TABLE IF NOT EXISTS VersionInfo
(
Version INTEGER NOT NULL,
Description VARCHAR(100) NOT NULL
);
CREATE TABLE IF NOT EXISTS ScheduledJobs
(
Id INTEGER PRIMARY KEY AUTOINCREMENT,

@ -24,6 +24,8 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#endregion
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Dapper;
@ -109,7 +111,29 @@ namespace PlexRequests.Store
con.Close();
}
public static IEnumerable<VersionInfo> GetVersionInfo(this IDbConnection con)
{
con.Open();
var result = con.Query<VersionInfo>("SELECT * FROM VersionInfo");
con.Close();
return result;
}
public static void AddVersionInfo(this IDbConnection con, VersionInfo ver)
{
con.Open();
con.Insert(ver);
con.Close();
}
[Table("VersionInfo")]
public class VersionInfo
{
public int Version { get; set; }
public string Description { get; set; }
}
[Table("DBInfo")]
public class DbInfo

@ -32,6 +32,7 @@ using Nancy.Authentication.Forms;
using Ninject.Modules;
using PlexRequests.Core;
using PlexRequests.Core.Migration;
using PlexRequests.Helpers;
using PlexRequests.Services.Interfaces;
using PlexRequests.Services.Notification;
@ -47,6 +48,7 @@ namespace PlexRequests.UI.NinjectModules
Bind<ISqliteConfiguration>().To<DbConfiguration>().WithConstructorArgument("provider", new SqliteFactory());
Bind<IPlexDatabase>().To<PlexDatabase>().WithConstructorArgument("provider", new SqliteFactory());
Bind<IPlexReadOnlyDatabase>().To<PlexReadOnlyDatabase>();
Bind<IMigrationRunner>().To<MigrationRunner>();
Bind<IUserMapper>().To<UserMapper>();

@ -754,6 +754,10 @@
<Project>{8CB8D235-2674-442D-9C6A-35FCAEEB160D}</Project>
<Name>PlexRequests.Api</Name>
</ProjectReference>
<ProjectReference Include="..\PlexRequests.Core.Migration\PlexRequests.Core.Migration.csproj">
<Project>{8406EE57-D533-47C0-9302-C6B5F8C31E55}</Project>
<Name>PlexRequests.Core.Migration</Name>
</ProjectReference>
<ProjectReference Include="..\PlexRequests.Core\PlexRequests.Core.csproj">
<Project>{DD7DC444-D3BF-4027-8AB9-EFC71F5EC581}</Project>
<Name>PlexRequests.Core</Name>

@ -32,6 +32,7 @@ using Ninject.Planning.Bindings.Resolvers;
using NLog;
using Owin;
using PlexRequests.Core.Migration;
using PlexRequests.Services.Jobs;
using PlexRequests.UI.Helpers;
using PlexRequests.UI.Jobs;
@ -67,6 +68,10 @@ namespace PlexRequests.UI
Debug.WriteLine("Finished bootstrapper");
var scheduler = new Scheduler();
scheduler.StartScheduler();
var runner = kernel.Get<IMigrationRunner>();
runner.MigrateToLatest();
}
catch (Exception exception)
{

@ -45,6 +45,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequests.Automation.Pag
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequestes.Automation.Helpers", "PlexRequestes.Automation.Helpers\PlexRequestes.Automation.Helpers.csproj", "{DC8BACEF-C284-4A8F-A9AA-7F49EFABA288}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PlexRequests.Core.Migration", "PlexRequests.Core.Migration\PlexRequests.Core.Migration.csproj", "{8406EE57-D533-47C0-9302-C6B5F8C31E55}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -108,6 +110,10 @@ Global
{DC8BACEF-C284-4A8F-A9AA-7F49EFABA288}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC8BACEF-C284-4A8F-A9AA-7F49EFABA288}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC8BACEF-C284-4A8F-A9AA-7F49EFABA288}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8406EE57-D533-47C0-9302-C6B5F8C31E55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8406EE57-D533-47C0-9302-C6B5F8C31E55}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8406EE57-D533-47C0-9302-C6B5F8C31E55}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8406EE57-D533-47C0-9302-C6B5F8C31E55}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save