Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

F/226 simple data migrations system #234

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
56f6c20
Add packages to implement migrations system.
DavidPL-coder Jun 6, 2022
8f28102
Remove unnecessary database configuration.
DavidPL-coder Jun 6, 2022
45e74db
Add data migrations system for MongoDB database.
DavidPL-coder Jun 8, 2022
14563f7
Do the MongoDB configuration after the logger configuration.
DavidPL-coder Jun 8, 2022
952b9f3
Add the field with copy of Name field in ConfigurationItems db collec…
DavidPL-coder Jun 8, 2022
9a38bb9
Upgrade database to 1.2.0 version as example of using the migrations …
DavidPL-coder Jun 8, 2022
4211c3f
Upgrade databse to 1.3.0 version as example of using the migrations s…
DavidPL-coder Jun 8, 2022
3302911
Downgrade database to 1.2.0 version as an example of using migrations.
DavidPL-coder Jun 8, 2022
b4aed64
Unapply all migrations as an example of using migrations.
DavidPL-coder Jun 8, 2022
ab82fba
Upgrade database to the latest version as an example of using migrati…
DavidPL-coder Jun 8, 2022
e46eaca
Add validation in M120_CreateBackupOfInitEventsMigration.
DavidPL-coder Jun 9, 2022
5a8b3b7
Add checking existing of database and migrations before using of the …
DavidPL-coder Jun 9, 2022
1fd7898
Remove unnecessary nuget packages.
DavidPL-coder Jun 9, 2022
b32852c
Remove unnecessary fields (which were used as example of using migrat…
DavidPL-coder Jun 9, 2022
e031e24
Remove migrations with 1.2.0 version (which were used as an example c…
DavidPL-coder Jun 9, 2022
6f82b4a
Remove example migration with 1.1.0 version and related things.
DavidPL-coder Jun 9, 2022
db679e0
Add migrations folder for the next migrations.
DavidPL-coder Jun 9, 2022
6e53ff5
Move MongoConventions class to other file.
DavidPL-coder Jun 9, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Watchman.Discord/WatchmanBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public WatchmanBot(DiscordConfiguration configuration, IComponentContext context

public WorkflowBuilder GetWorkflowBuilder(bool useDiscordNetClient = true)
{
MongoConfiguration.Initialize();
ExceptionHandlerService.DiscordConfiguration = this._configuration; //todo ioc

return WorkflowBuilder
Expand Down
2 changes: 2 additions & 0 deletions Watchman.DomainModel/Configuration/ConfigurationItem.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Watchman.Integrations.Database;

namespace Watchman.DomainModel.Configuration
Expand Down
1 change: 1 addition & 0 deletions Watchman.Integrations/Database/MongoDB/Migrations/.gitkeep
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

62 changes: 54 additions & 8 deletions Watchman.Integrations/Database/MongoDB/MongoConfiguration.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
using MongoDB.Bson;
using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDBMigrations;
using Serilog;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;

namespace Watchman.Integrations.Database.MongoDB
{
Expand All @@ -10,13 +16,14 @@ public static class MongoConfiguration
{
private static bool _initialized;

public static void Initialize()
public static void Initialize(IConfigurationRoot configuration)
{
if (_initialized)
{
return;
}
RegisterConventions();
TryToMigrateDatabase(configuration);
_initialized = true;
}

Expand All @@ -25,14 +32,53 @@ private static void RegisterConventions()
ConventionRegistry.Register("DevscordConventions", new MongoConventions(), x => true);
}

private class MongoConventions : IConventionPack
private static void TryToMigrateDatabase(IConfigurationRoot configuration)
{
public IEnumerable<IConvention> Conventions => new List<IConvention>
var connectionString = configuration.GetConnectionString("Mongo");
var databaseName = connectionString.Split('/').Last();
var assemblyForMigrations = Assembly.GetExecutingAssembly();

if (ShouldNotDoMigrations(connectionString, databaseName, assemblyForMigrations))
{
return;
}

var result = new MigrationEngine()
.UseDatabase(connectionString, databaseName)
.UseAssembly(assemblyForMigrations)
.UseSchemeValidation(enabled: false)
.UseProgressHandler(context =>
Log.Information($@"The migration with name ""{context.MigrationName}"" from {context.TargetVersion} version was processed as {context.CurrentNumber} from all {context.TotalCount} migrations."))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Czy takie logi są wystarczające? Podałem taki log jako przykład, ale nie wiem czy trzeba coś zmienić. Inne logi tutaj też są wystarczające?

.Run();

if (!result.Success)
{
new IgnoreExtraElementsConvention(true),
new EnumRepresentationConvention(BsonType.String),
new CamelCaseElementNameConvention()
};
// TODO: Do something when migrations throw exceptions.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Właśnie co zrobić gdy wystąpi wyjątek podczas migracji? Zakończyć aplikacje z odpowiednią informacją?

Poza tym swoją drogą jak teraz patrze w dokumentacje tej paczki to chyba będę musiał użyć try catch aby to obsłużyć zamiast tego if'a.

}

Log.Information($"The current version of the database after data migrations is {result.CurrentVersion}.");
}

private static bool ShouldNotDoMigrations(string connectionString, string databaseName, Assembly assemblyForMigrations)
{
var migrationInterfaceType = typeof(IMigration);
var areNotThereMigrations = assemblyForMigrations.GetTypes()
.All(t => t.GetInterfaces().Contains(migrationInterfaceType) == false);

if (areNotThereMigrations)
{
Log.Warning("The app doesn't see any migration to use.");
}

var mongoClient = new MongoClient(new MongoUrl(connectionString));
var isNotDatabaseExisting = mongoClient.ListDatabaseNames().ToList().All(x => x != databaseName);

if (isNotDatabaseExisting)
{
Log.Warning("The database doesn't exist yet (so data migrations won't be used).");
}

return areNotThereMigrations || isNotDatabaseExisting;
}
}
}
16 changes: 16 additions & 0 deletions Watchman.Integrations/Database/MongoDB/MongoConventions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using System.Collections.Generic;

namespace Watchman.Integrations.Database.MongoDB
{
internal class MongoConventions : IConventionPack
{
public IEnumerable<IConvention> Conventions => new List<IConvention>
{
new IgnoreExtraElementsConvention(true),
new EnumRepresentationConvention(BsonType.String),
new CamelCaseElementNameConvention()
};
}
}
2 changes: 2 additions & 0 deletions Watchman.Integrations/Watchman.Integrations.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
<PackageReference Include="Discord.Net.WebSocket" Version="3.4.1" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.42" />
<PackageReference Include="LiteDB" Version="5.0.11" />
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
<PackageReference Include="MongoDB.Driver" Version="2.15.0" />
<PackageReference Include="MongoDBMigrations" Version="2.2.0" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
Expand Down
2 changes: 1 addition & 1 deletion Watchman.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ public class Program
{
public static void Main(string[] args)
{
MongoConfiguration.Initialize();
var configuration = GetConfiguration();
Log.Logger = SerilogInitializer.Initialize(configuration);
MongoConfiguration.Initialize(configuration);
CreateHostBuilder(args, configuration).Build().Run();
}

Expand Down