From 4368b3f0474c43c717f9fc96fbae0b3854bac50f Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 25 Dec 2022 14:52:46 +0800 Subject: Add migration. --- .../CrupestApi.Commons/Secrets/SecretService.cs | 30 +++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Secrets/SecretService.cs') diff --git a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Secrets/SecretService.cs b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Secrets/SecretService.cs index 9a0ec95..b8a1bbe 100644 --- a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Secrets/SecretService.cs +++ b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Secrets/SecretService.cs @@ -1,26 +1,32 @@ using System.Data; using CrupestApi.Commons.Crud; +using CrupestApi.Commons.Crud.Migrations; namespace CrupestApi.Commons.Secrets; public class SecretService : CrudService, ISecretService { - public SecretService(ITableInfoFactory tableInfoFactory, IDbConnectionFactory dbConnectionFactory, ILoggerFactory loggerFactory) - : base(tableInfoFactory, dbConnectionFactory, loggerFactory) - { + private readonly ILogger _logger; + public SecretService(ITableInfoFactory tableInfoFactory, IDbConnectionFactory dbConnectionFactory, IDatabaseMigrator migrator, ILoggerFactory loggerFactory) + : base(tableInfoFactory, dbConnectionFactory, migrator, loggerFactory) + { + _logger = loggerFactory.CreateLogger(); } - protected override void DoInitializeDatabase(IDbConnection connection) + protected override void AfterMigrate(IDbConnection connection, TableInfo table, ILoggerFactory loggerFactory) { - base.DoInitializeDatabase(connection); - using var transaction = connection.BeginTransaction(); - var insertClause = InsertClause.Create() - .Add(nameof(SecretInfo.Key), SecretsConstants.SecretManagementKey) - .Add(nameof(SecretInfo.Secret), "crupest") - .Add(nameof(SecretInfo.Description), "This is the init key. Please revoke it immediately after creating a new one."); - _table.Insert(connection, insertClause, out var _); - transaction.Commit(); + if (table.SelectCount(connection) == 0) + { + loggerFactory.CreateLogger().LogInformation("No secrets found, insert default secrets."); + using var transaction = connection.BeginTransaction(); + var insertClause = InsertClause.Create() + .Add(nameof(SecretInfo.Key), SecretsConstants.SecretManagementKey) + .Add(nameof(SecretInfo.Secret), "crupest") + .Add(nameof(SecretInfo.Description), "This is the init key. Please revoke it immediately after creating a new one."); + _table.Insert(connection, insertClause, out var _); + transaction.Commit(); + } } public void CreateTestSecret(string key, string secret) -- cgit v1.2.3