Skip to content

Commit

Permalink
create db if not exists
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidEggenberger committed Sep 22, 2024
1 parent cfeed4b commit 65dee64
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions Source/Shared/Features/EFCore/DbUp/Registrator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using DbUp;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Shared.Features.EFCore.Configuration;
Expand All @@ -9,20 +10,36 @@ namespace Shared.Features.EFCore.DbUp
{
public static class Registrator
{
public static IServiceCollection AddDbUpMigration(this IServiceCollection services)
public static async Task<IServiceCollection> AddDbUpMigration(this IServiceCollection services)
{
using var serviceProvider = services.BuildServiceProvider();

var isProduction = serviceProvider.GetRequiredService<IExecutionContext>().HostingEnvironment.IsProduction();
var efCoreConfiguration = serviceProvider.GetRequiredService<EFCoreConfiguration>();
var connectionString = isProduction ? efCoreConfiguration.SQLServerConnectionString_Prod : efCoreConfiguration.SQLServerConnectionString_Dev;

var upgrader = DeployChanges.To
.SqlDatabase(isProduction ? efCoreConfiguration.SQLServerConnectionString_Prod : efCoreConfiguration.SQLServerConnectionString_Dev)
.SqlDatabase(connectionString)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
.JournalToSqlTable("dbo", "DbUP_MigrationHistory")
.JournalToSqlTable("dbo", "MigrationHistory_DbUP")
.LogToConsole()
.Build();

if (upgrader.TryConnect(out string _) is false)
{
var sqlConnectionParameters = connectionString.Split(';');
var databaseName = sqlConnectionParameters[1].Split("=")[1];
var serverConnectionString = string.Join(";", sqlConnectionParameters.Where(e => e.StartsWith("Database") is false));

using (var connection = new SqlConnection(string.Join("", serverConnectionString)))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = $"CREATE DATABASE {databaseName}";
await command.ExecuteNonQueryAsync();
}
}

var scripts = upgrader.GetScriptsToExecute();
foreach (var script in scripts)
{
Expand Down

0 comments on commit 65dee64

Please sign in to comment.