hermes-server/Store/ChatterStore.cs

100 lines
3.5 KiB
C#
Raw Normal View History

using HermesSocketLibrary.db;
using HermesSocketServer.Models;
namespace HermesSocketServer.Store
{
public class ChatterStore : GroupSaveStore<string, ChatterVoice>
{
private readonly string _userId;
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<ChatterVoice> _generator;
public ChatterStore(string userId, Database database, Serilog.ILogger logger) : base(logger)
{
_userId = userId;
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "chatterId", "ChatterId" },
{ "ttsVoiceId", "VoiceId" },
{ "userId", "UserId" },
};
_generator = new GroupSaveSqlGenerator<ChatterVoice>(ctp);
}
public override async Task Load()
{
var data = new Dictionary<string, object>() { { "user", _userId } };
string sql = $"SELECT \"chatterId\", \"ttsVoiceId\" FROM \"TtsChatVoice\" WHERE \"userId\" = @user";
await _database.Execute(sql, data, (reader) =>
{
var chatterId = reader.GetInt64(0);
_store.Add(chatterId.ToString(), new ChatterVoice()
{
UserId = _userId,
ChatterId = chatterId,
VoiceId = reader.GetString(1)
});
});
_logger.Information($"Loaded {_store.Count} TTS chatter voices from database.");
}
protected override void OnInitialAdd(string key, ChatterVoice value)
{
}
protected override void OnInitialModify(string key, ChatterVoice value)
{
}
protected 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("TtsChatVoice", _added.Select(a => _store[a]), ["userId", "chatterId", "ttsVoiceId"]);
_added.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"TtsChatVoice - Adding {count} rows to database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_modified.Any())
{
lock (_lock)
{
count = _modified.Count;
sql = _generator.GenerateUpdateSql("TtsChatVoice", _modified.Select(m => _store[m]), ["userId", "chatterId"], ["ttsVoiceId"]);
_modified.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"TtsChatVoice - Modifying {count} rows in database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_deleted.Any())
{
lock (_lock)
{
count = _deleted.Count;
sql = _generator.GenerateDeleteSql("TtsChatVoice", _deleted, ["userId", "chatterId"]);
_deleted.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"TtsChatVoice - Deleting {count} rows from database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
return true;
}
}
}