Skip to content

Commit

Permalink
Update auto db initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
EdwinVW committed Jul 13, 2021
1 parent 9383def commit f243358
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 104 deletions.
105 changes: 54 additions & 51 deletions src/InvoiceService/Repositories/SqlServerInvoiceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,60 +25,10 @@ public SqlServerInvoiceRepository(string connectionString)
Policy
.Handle<Exception>()
.WaitAndRetryAsync(10, r => TimeSpan.FromSeconds(10), (ex, ts) => { Log.Error("Error connecting to DB. Retrying in 10 sec."); })
.ExecuteAsync(InitializeDB)
.ExecuteAsync(InitializeDBAsync)
.Wait();
}

private async Task InitializeDB()
{
using (SqlConnection conn = new SqlConnection(_connectionString.Replace("Invoicing", "master")))
{
await conn.OpenAsync();

// create database
string sql =
"IF NOT EXISTS(SELECT * FROM master.sys.databases WHERE name='Invoicing') CREATE DATABASE Invoicing;";

await conn.ExecuteAsync(sql);
}

using (SqlConnection conn = new SqlConnection(_connectionString))
{
string sql = "IF OBJECT_ID('Customer') IS NULL " +
"CREATE TABLE Customer (" +
" CustomerId varchar(50) NOT NULL," +
" Name varchar(50) NOT NULL," +
" Address varchar(50)," +
" PostalCode varchar(50)," +
" City varchar(50)," +
" PRIMARY KEY(CustomerId));" +

"IF OBJECT_ID('MaintenanceJob') IS NULL " +
"CREATE TABLE MaintenanceJob (" +
" JobId varchar(50) NOT NULL," +
" LicenseNumber varchar(50) NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" Description varchar(250) NOT NULL," +
" StartTime datetime2 NULL," +
" EndTime datetime2 NULL," +
" Finished bit NOT NULL," +
" InvoiceSent bit NOT NULL," +
" PRIMARY KEY(JobId));" +

"IF OBJECT_ID('Invoice') IS NULL " +
"CREATE TABLE Invoice (" +
" InvoiceId varchar(50) NOT NULL," +
" InvoiceDate datetime2 NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" Amount decimal(5,2) NOT NULL," +
" Specification text," +
" JobIds varchar(250)," +
" PRIMARY KEY(InvoiceId));";

await conn.ExecuteAsync(sql);
}
}

public async Task<Customer> GetCustomerAsync(string customerId)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
Expand Down Expand Up @@ -155,5 +105,58 @@ public async Task RegisterInvoiceAsync(Invoice invoice)
await conn.ExecuteAsync(sql, jobIds);
}
}

private async Task InitializeDBAsync()
{
using (SqlConnection conn = new SqlConnection(_connectionString.Replace("Invoicing", "master")))
{
await conn.OpenAsync();

// create database
string sql =
"IF NOT EXISTS(SELECT * FROM master.sys.databases WHERE name='Invoicing') CREATE DATABASE Invoicing;";

await conn.ExecuteAsync(sql);
}

using (SqlConnection conn = new SqlConnection(_connectionString))
{
await conn.OpenAsync();

// create tables
string sql = "IF OBJECT_ID('Customer') IS NULL " +
"CREATE TABLE Customer (" +
" CustomerId varchar(50) NOT NULL," +
" Name varchar(50) NOT NULL," +
" Address varchar(50)," +
" PostalCode varchar(50)," +
" City varchar(50)," +
" PRIMARY KEY(CustomerId));" +

"IF OBJECT_ID('MaintenanceJob') IS NULL " +
"CREATE TABLE MaintenanceJob (" +
" JobId varchar(50) NOT NULL," +
" LicenseNumber varchar(50) NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" Description varchar(250) NOT NULL," +
" StartTime datetime2 NULL," +
" EndTime datetime2 NULL," +
" Finished bit NOT NULL," +
" InvoiceSent bit NOT NULL," +
" PRIMARY KEY(JobId));" +

"IF OBJECT_ID('Invoice') IS NULL " +
"CREATE TABLE Invoice (" +
" InvoiceId varchar(50) NOT NULL," +
" InvoiceDate datetime2 NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" Amount decimal(5,2) NOT NULL," +
" Specification text," +
" JobIds varchar(250)," +
" PRIMARY KEY(InvoiceId));";

await conn.ExecuteAsync(sql);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,47 +24,10 @@ public SqlServerNotificationRepository(string connectionString)
Policy
.Handle<Exception>()
.WaitAndRetryAsync(10, r => TimeSpan.FromSeconds(10), (ex, ts) => { Log.Error("Error connecting to DB. Retrying in 10 sec."); })
.ExecuteAsync(InitializeDB)
.ExecuteAsync(InitializeDBAsync)
.Wait();
}

private async Task InitializeDB()
{
using (SqlConnection conn = new SqlConnection(_connectionString.Replace("Notification", "master")))
{
await conn.OpenAsync();

// create database
string sql =
"IF NOT EXISTS(SELECT * FROM master.sys.databases WHERE name='Notification') CREATE DATABASE Notification;";

await conn.ExecuteAsync(sql);
}

// create tables
using (SqlConnection conn = new SqlConnection(_connectionString))
{
string sql = "IF OBJECT_ID('Customer') IS NULL " +
"CREATE TABLE Customer (" +
" CustomerId varchar(50) NOT NULL," +
" Name varchar(50) NOT NULL," +
" TelephoneNumber varchar(50)," +
" EmailAddress varchar(50)," +
" PRIMARY KEY(CustomerId));" +

"IF OBJECT_ID('MaintenanceJob') IS NULL " +
"CREATE TABLE MaintenanceJob (" +
" JobId varchar(50) NOT NULL," +
" LicenseNumber varchar(50) NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" StartTime datetime2 NOT NULL," +
" Description varchar(250) NOT NULL," +
" PRIMARY KEY(JobId));";

await conn.ExecuteAsync(sql);
}
}

public async Task<Customer> GetCustomerAsync(string customerId)
{
using (SqlConnection conn = new SqlConnection(_connectionString))
Expand Down Expand Up @@ -116,5 +79,45 @@ public async Task RemoveMaintenanceJobsAsync(IEnumerable<string> jobIds)
await conn.ExecuteAsync(sql, jobIds.Select(j => new { JobId = j }));
}
}

private async Task InitializeDBAsync()
{
using (SqlConnection conn = new SqlConnection(_connectionString.Replace("Notification", "master")))
{
await conn.OpenAsync();

// create database
string sql =
"IF NOT EXISTS(SELECT * FROM master.sys.databases WHERE name='Notification') CREATE DATABASE Notification;";

await conn.ExecuteAsync(sql);
}

// create tables
using (SqlConnection conn = new SqlConnection(_connectionString))
{
await conn.OpenAsync();

// create tables
string sql = "IF OBJECT_ID('Customer') IS NULL " +
"CREATE TABLE Customer (" +
" CustomerId varchar(50) NOT NULL," +
" Name varchar(50) NOT NULL," +
" TelephoneNumber varchar(50)," +
" EmailAddress varchar(50)," +
" PRIMARY KEY(CustomerId));" +

"IF OBJECT_ID('MaintenanceJob') IS NULL " +
"CREATE TABLE MaintenanceJob (" +
" JobId varchar(50) NOT NULL," +
" LicenseNumber varchar(50) NOT NULL," +
" CustomerId varchar(50) NOT NULL," +
" StartTime datetime2 NOT NULL," +
" Description varchar(250) NOT NULL," +
" PRIMARY KEY(JobId));";

await conn.ExecuteAsync(sql);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using Pitstop.Infrastructure.Messaging;
using Pitstop.WorkshopManagementAPI.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Pitstop.WorkshopManagementAPI.Repositories
{
public interface IEventSourceRepository<T>
{
void EnsureDatabase();
Task<T> GetByIdAsync(string id);
Task SaveAsync(string id, int originalVersion, int newVersion, IEnumerable<Event> newEvents);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Data.SqlClient;
using Pitstop.WorkshopManagementAPI.Domain.Entities;
using System.Globalization;
using Serilog;

namespace Pitstop.WorkshopManagementAPI.Repositories
{
Expand All @@ -34,6 +35,15 @@ static SqlServerWorkshopPlanningEventSourceRepository()
public SqlServerWorkshopPlanningEventSourceRepository(string connectionString)
{
_connectionString = connectionString;

// init db
Log.Information("Initialize Database");

Policy
.Handle<Exception>()
.WaitAndRetryAsync(10, r => TimeSpan.FromSeconds(10), (ex, ts) => { Log.Error("Error connecting to DB. Retrying in 10 sec."); })
.ExecuteAsync(InitializeDatabaseAsync)
.Wait();
}

public async Task<WorkshopPlanning> GetByIdAsync(string aggregateId)
Expand Down Expand Up @@ -149,18 +159,12 @@ await Policy
}
}

public void EnsureDatabase()
private async Task InitializeDatabaseAsync()
{
// init db
using (SqlConnection conn = new SqlConnection(_connectionString.Replace("WorkshopManagementEventStore", "master")))
{
Console.WriteLine("Ensure database exists");

Policy
.Handle<Exception>()
.WaitAndRetry(5, r => TimeSpan.FromSeconds(5), (ex, ts) =>
{ Console.WriteLine("Error connecting to DB. Retrying in 5 sec."); })
.Execute(() => conn.Open());
await conn.OpenAsync();

// create database
string sql = "IF NOT EXISTS(SELECT * FROM master.sys.databases WHERE name='WorkshopManagementEventStore') CREATE DATABASE WorkshopManagementEventStore;";
Expand All @@ -170,6 +174,8 @@ public void EnsureDatabase()
// create tables
using (SqlConnection conn = new SqlConnection(_connectionString))
{
await conn.OpenAsync();

string sql = @"
if OBJECT_ID('WorkshopPlanning') IS NULL
CREATE TABLE WorkshopPlanning (
Expand Down
4 changes: 0 additions & 4 deletions src/WorkshopManagementAPI/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Pitstop.Infrastructure.Messaging;
using Pitstop.WorkshopManagementAPI.Repositories;
using Serilog;
using Microsoft.Extensions.HealthChecks;
Expand Down Expand Up @@ -81,9 +80,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApp
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "WorkshopManagement API - v1");
});

// initialize database
workshopPlanningRepo.EnsureDatabase();
}
}
}

0 comments on commit f243358

Please sign in to comment.