hermes-server/Store/VoiceStore.cs

103 lines
3.3 KiB
C#
Raw Normal View History

2024-10-17 15:06:22 -04:00
using HermesSocketLibrary.db;
using HermesSocketServer.Models;
2024-10-17 15:06:22 -04:00
using HermesSocketServer.Validators;
namespace HermesSocketServer.Store
{
public class VoiceStore : GroupSaveStore<string, Voice>
2024-10-17 15:06:22 -04:00
{
private readonly VoiceIdValidator _idValidator;
private readonly VoiceNameValidator _nameValidator;
2024-10-17 15:06:22 -04:00
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<Voice> _generator;
2024-10-17 15:06:22 -04:00
public VoiceStore(VoiceIdValidator voiceIdValidator, VoiceNameValidator voiceNameValidator, Database database, Serilog.ILogger logger) : base(logger)
2024-10-17 15:06:22 -04:00
{
_idValidator = voiceIdValidator;
_nameValidator = voiceNameValidator;
2024-10-17 15:06:22 -04:00
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "id", "Id" },
{ "name", "Name" }
};
_generator = new GroupSaveSqlGenerator<Voice>(ctp);
2024-10-17 15:06:22 -04:00
}
public override async Task Load()
2024-10-17 15:06:22 -04:00
{
string sql = "SELECT id, name FROM \"TtsVoice\";";
await _database.Execute(sql, new Dictionary<string, object>(), (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.");
2024-10-17 15:06:22 -04:00
}
protected override void OnInitialAdd(string key, Voice value)
2024-10-17 15:06:22 -04:00
{
_idValidator.Check(value.Id);
_nameValidator.Check(value.Name);
2024-10-17 15:06:22 -04:00
}
protected override void OnInitialModify(string key, Voice value)
2024-10-17 15:06:22 -04:00
{
_nameValidator.Check(value.Name);
2024-10-17 15:06:22 -04:00
}
protected override void OnInitialRemove(string key)
2024-10-17 15:06:22 -04:00
{
}
public override async Task<bool> Save()
2024-10-17 15:06:22 -04:00
{
int count = 0;
string sql = string.Empty;
2024-10-17 15:06:22 -04:00
if (_added.Any())
{
lock (_lock)
{
count = _added.Count;
sql = _generator.GenerateInsertSql("TtsVoice", _added.Select(a => _store[a]), ["id", "name"]);
2024-10-17 15:06:22 -04:00
_added.Clear();
}
_logger.Debug($"ADD {count} " + sql);
await _database.ExecuteScalar(sql);
2024-10-17 15:06:22 -04:00
}
if (_modified.Any())
{
lock (_lock)
{
count = _modified.Count;
sql = _generator.GenerateUpdateSql("TtsVoice", _modified.Select(m => _store[m]), ["id"], ["name"]);
2024-10-17 15:06:22 -04:00
_modified.Clear();
}
_logger.Debug($"MOD {count} " + sql);
await _database.ExecuteScalar(sql);
2024-10-17 15:06:22 -04:00
}
if (_deleted.Any())
{
lock (_lock)
{
count = _deleted.Count;
sql = _generator.GenerateDeleteSql("TtsVoice", _deleted, ["id"]);
2024-10-17 15:06:22 -04:00
_deleted.Clear();
}
_logger.Debug($"DEL {count} " + sql);
await _database.ExecuteScalar(sql);
2024-10-17 15:06:22 -04:00
}
return true;
}
}
}