hermes-server/Store/UserStore.cs

100 lines
3.3 KiB
C#
Raw Normal View History

using HermesSocketLibrary.db;
using HermesSocketServer.Models;
namespace HermesSocketServer.Store
{
public class UserStore : GroupSaveStore<string, User>
{
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<User> _generator;
public UserStore(Database database, Serilog.ILogger logger) : base(logger)
{
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "id", "Id" },
{ "name", "Name" },
{ "email", "Email" },
{ "role", "Role" },
{ "ttsDefaultVoice", "DefaultVoice" }
};
_generator = new GroupSaveSqlGenerator<User>(ctp);
}
public override async Task Load()
{
string sql = "SELECT id, name, email, role, \"ttsDefaultVoice\" FROM \"User\";";
await _database.Execute(sql, new Dictionary<string, object>(), (reader) =>
{
string id = reader.GetString(0);
_store.Add(id, new User()
{
Id = id,
Name = reader.GetString(1),
Email = reader.GetString(2),
Role = reader.GetString(3),
DefaultVoice = reader.GetString(4),
});
});
_logger.Information($"Loaded {_store.Count} users from database.");
}
protected override void OnInitialAdd(string key, User value)
{
}
protected override void OnInitialModify(string key, User value)
{
}
protected override void OnInitialRemove(string key)
{
}
public override async Task<bool> Save()
{
2024-10-20 15:28:16 -04:00
int count = 0;
string sql = string.Empty;
if (_added.Any())
{
lock (_lock)
{
2024-10-20 15:28:16 -04:00
count = _added.Count;
sql = _generator.GenerateInsertSql("User", _added.Select(a => _store[a]), ["id", "name", "email", "role", "ttsDefaultVoice"]);
_added.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"User - Adding {count} rows to database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_modified.Any())
{
lock (_lock)
{
2024-10-20 15:28:16 -04:00
count = _modified.Count;
sql = _generator.GenerateUpdateSql("User", _modified.Select(m => _store[m]), ["id"], ["name", "email", "role", "ttsDefaultVoice"]);
_modified.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"User - Modifying {count} rows in database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_deleted.Any())
{
lock (_lock)
{
2024-10-20 15:28:16 -04:00
count = _deleted.Count;
sql = _generator.GenerateDeleteSql("User", _deleted, ["id"]);
_deleted.Clear();
}
2024-10-20 15:28:16 -04:00
_logger.Debug($"User - Deleting {count} rows from database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
return true;
}
}
}