103 lines
3.3 KiB
C#
103 lines
3.3 KiB
C#
using HermesSocketLibrary.db;
|
|
using HermesSocketServer.Models;
|
|
using HermesSocketServer.Validators;
|
|
|
|
namespace HermesSocketServer.Store
|
|
{
|
|
public class VoiceStore : GroupSaveStore<string, Voice>
|
|
{
|
|
private readonly VoiceIdValidator _idValidator;
|
|
private readonly VoiceNameValidator _nameValidator;
|
|
private readonly Database _database;
|
|
private readonly Serilog.ILogger _logger;
|
|
private readonly GroupSaveSqlGenerator<Voice> _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<string, string>
|
|
{
|
|
{ "id", "Id" },
|
|
{ "name", "Name" }
|
|
};
|
|
_generator = new GroupSaveSqlGenerator<Voice>(ctp);
|
|
}
|
|
|
|
public override async Task Load()
|
|
{
|
|
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.");
|
|
}
|
|
|
|
public override void OnInitialAdd(string key, Voice value)
|
|
{
|
|
_idValidator.Check(value.Id);
|
|
_nameValidator.Check(value.Name);
|
|
}
|
|
|
|
public override void OnInitialModify(string key, Voice value)
|
|
{
|
|
_nameValidator.Check(value.Name);
|
|
}
|
|
|
|
public override void OnInitialRemove(string key)
|
|
{
|
|
}
|
|
|
|
public override async Task<bool> 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($"ADD {count} " + sql);
|
|
await _database.ExecuteScalar(sql);
|
|
}
|
|
if (_modified.Any())
|
|
{
|
|
lock (_lock)
|
|
{
|
|
count = _modified.Count;
|
|
sql = _generator.GenerateUpdateSql("TtsVoice", _modified.Select(m => _store[m]), ["id"], ["name"]);
|
|
_modified.Clear();
|
|
}
|
|
_logger.Debug($"MOD {count} " + sql);
|
|
await _database.ExecuteScalar(sql);
|
|
}
|
|
if (_deleted.Any())
|
|
{
|
|
lock (_lock)
|
|
{
|
|
count = _deleted.Count;
|
|
sql = _generator.GenerateDeleteSql("TtsVoice", _deleted, ["id"]);
|
|
_deleted.Clear();
|
|
}
|
|
_logger.Debug($"DEL {count} " + sql);
|
|
await _database.ExecuteScalar(sql);
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
} |