using HermesSocketLibrary.db; using HermesSocketServer.Models; using HermesSocketServer.Validators; namespace HermesSocketServer.Store { public class VoiceStore : GroupSaveStore { private readonly VoiceIdValidator _idValidator; private readonly VoiceNameValidator _nameValidator; private readonly Database _database; private readonly Serilog.ILogger _logger; private readonly GroupSaveSqlGenerator _generator; public VoiceStore(VoiceIdValidator voiceIdValidator, VoiceNameValidator voiceNameValidator, Database database, Serilog.ILogger logger) : base(logger) { _idValidator = voiceIdValidator; _nameValidator = voiceNameValidator; _database = database; _logger = logger; var ctp = new Dictionary { { "id", "Id" }, { "name", "Name" } }; _generator = new GroupSaveSqlGenerator(ctp); } public override async Task Load() { string sql = "SELECT id, name FROM \"TtsVoice\";"; await _database.Execute(sql, new Dictionary(), (reader) => { string id = reader.GetString(0); _store.Add(id, new Voice() { Id = id, Name = reader.GetString(1), }); }); _logger.Information($"Loaded {_store.Count} TTS voices from database."); } protected override void OnInitialAdd(string key, Voice value) { _idValidator.Check(value.Id); _nameValidator.Check(value.Name); } protected override void OnInitialModify(string key, Voice value) { _nameValidator.Check(value.Name); } protected override void OnInitialRemove(string key) { } public override async Task Save() { int count = 0; string sql = string.Empty; if (_added.Any()) { lock (_lock) { count = _added.Count; sql = _generator.GenerateInsertSql("TtsVoice", _added.Select(a => _store[a]), ["id", "name"]); _added.Clear(); } _logger.Debug($"TtsVoice - Adding {count} rows to database: {sql}"); await _database.ExecuteScalarTransaction(sql); } if (_modified.Any()) { lock (_lock) { count = _modified.Count; sql = _generator.GenerateUpdateSql("TtsVoice", _modified.Select(m => _store[m]), ["id"], ["name"]); _modified.Clear(); } _logger.Debug($"TtsVoice - Modifying {count} rows in database: {sql}"); await _database.ExecuteScalarTransaction(sql); } if (_deleted.Any()) { lock (_lock) { count = _deleted.Count; sql = _generator.GenerateDeleteSql("TtsVoice", _deleted, ["id"]); _deleted.Clear(); } _logger.Debug($"TtsVoice - Deleting {count} rows from database: {sql}"); await _database.ExecuteScalarTransaction(sql); } return true; } } }