#nullable enable using SqlKata; namespace PluralKit.Core; public partial class ModelRepository { public Task GetGroup(GroupId id) { var query = new Query("groups").Where("id", id); return _db.QueryFirst(query); } public Task GetGroupByName(SystemId system, string name) { var query = new Query("groups").Where("system", system).WhereRaw("lower(name) = lower(?)", name.ToLower()); return _db.QueryFirst(query); } public Task GetGroupByDisplayName(SystemId system, string display_name) { var query = new Query("groups").Where("system", system) .WhereRaw("lower(display_name) = lower(?)", display_name.ToLower()); return _db.QueryFirst(query); } public Task GetGroupByHid(string hid, SystemId? system = null) { var query = new Query("groups").Where("hid", hid.ToLower()); if (system != null) query = query.Where("system", system); return _db.QueryFirst(query); } public Task GetGroupByGuid(Guid uuid) { var query = new Query("groups").Where("uuid", uuid); return _db.QueryFirst(query); } public Task GetGroupMemberCount(GroupId id, PrivacyLevel? privacyFilter = null) { var query = new Query("group_members") .SelectRaw("count(*)") .Where("group_members.group_id", id); if (privacyFilter != null) query = query .Join("members", "group_members.member_id", "members.id") .Where("members.member_visibility", privacyFilter); return _db.QueryFirst(query); } public async Task CreateGroup(SystemId system, string name, IPKConnection? conn = null) { var query = new Query("groups").AsInsert(new { hid = new UnsafeLiteral("find_free_group_hid()"), system, name }); var group = await _db.QueryFirst(conn, query, "returning *"); _logger.Information("Created group {GroupId} in system {SystemId}: {GroupName}", group.Id, system, name); return group; } public async Task UpdateGroup(GroupId id, GroupPatch patch, IPKConnection? conn = null) { _logger.Information("Updated {GroupId}: {@GroupPatch}", id, patch); var query = patch.Apply(new Query("groups").Where("id", id)); var group = await _db.QueryFirst(conn, query, "returning *"); if (conn == null) _ = _dispatch.Dispatch(id, new UpdateDispatchData { Event = DispatchEvent.UPDATE_GROUP, EventData = patch.ToJson() }); return group; } public async Task DeleteGroup(GroupId group) { var oldGroup = await GetGroup(group); _logger.Information("Deleted {GroupId}", group); var query = new Query("groups").AsDelete().Where("id", group); await _db.ExecuteQuery(query); if (oldGroup != null) _ = _dispatch.Dispatch(oldGroup.System, oldGroup.Uuid, DispatchEvent.DELETE_GROUP); } }