public void UpdateExemptsForGuildAsync(ulong gid) { using TheGodfatherDbContext db = this.dbb.CreateContext(); this.guildExempts[gid] = new ConcurrentHashSet <ExemptedEntity>( db.ExemptsMention.Where(ee => ee.GuildIdDb == (long)gid) ); }
public async Task ScheduleAsync(ScheduledTask task) { ScheduledTaskExecutor?texec = null; try { using TheGodfatherDbContext db = this.dbb.CreateContext(); if (task is Reminder rem) { db.Reminders.Add(rem); await db.SaveChangesAsync(); } else if (task is GuildTask gt) { db.GuildTasks.Add(gt); await db.SaveChangesAsync(); } else { throw new ArgumentException("Unknown scheduled task type"); } if (DateTimeOffset.Now + task.TimeUntilExecution <= this.LastReloadTime + this.ReloadSpan) { texec = this.CreateTaskExecutor(task); } } catch (Exception e) { texec?.Dispose(); Log.Warning(e, "Scheduling tasks failed"); throw; } }
public async Task <IReadOnlyList <BankAccount> > GetTopAccountsAsync(ulong?gid = null, int amount = 10) { List <BankAccount> topAccounts; using TheGodfatherDbContext db = this.dbb.CreateContext(); topAccounts = await (gid is { } ? db.BankAccounts.Where(a => a.GuildIdDb == (long)gid) : db.BankAccounts)
public async Task UnregisterGuildAsync(ulong gid) { this.gcfg.TryRemove(gid, out _); using TheGodfatherDbContext db = this.dbb.CreateContext(); GuildConfig gcfg = await db.Configs.FindAsync((long)gid); if (gcfg is { })
public async Task ModifyBankAccountAsync(ulong gid, ulong uid, Func <long, long> balanceModifier) { using TheGodfatherDbContext db = this.dbb.CreateContext(); bool created = false; BankAccount?account = await this.GetAsync(gid, uid); if (account is null) { account = new BankAccount { GuildId = gid, UserId = uid }; created = true; } account.Balance = balanceModifier(account.Balance); if (account.Balance < 0) { account.Balance = 0; } if (created) { db.BankAccounts.Add(account); } else { db.BankAccounts.Update(account); } await db.SaveChangesAsync(); }
private void UpdateEmojiReactionCount(TheGodfatherDbContext db) { this.erCount = this.erCount.ToDictionary( kvp => kvp.Key, kvp => db.EmojiReactions.Count(er => er.GuildIdDb == (long)MockData.Ids[kvp.Key]) ); }
public static async Task <RelationalDataReader> ExecuteSqlQueryAsync(this DatabaseFacade databaseFacade, string sql, TheGodfatherDbContext db, params object[] parameters) { IConcurrencyDetector concurrencyDetector = databaseFacade.GetService <IConcurrencyDetector>(); using (concurrencyDetector.EnterCriticalSection()) { RawSqlCommand rawSqlCommand = databaseFacade .GetService <IRawSqlCommandBuilder>() .Build(sql, parameters); return(await rawSqlCommand .RelationalCommand .ExecuteReaderAsync( new RelationalCommandParameterObject( databaseFacade.GetService <IRelationalConnection>(), parameterValues : rawSqlCommand.ParameterValues, readerColumns : null, context : db, logger : null ) )); } }
private void AssertSingleAndTest(TheGodfatherDbContext db, int index, string regex, bool match, params string[] tests) { if (tests is null || !tests.Any()) { Assert.Fail("No tests provided to assert function."); return; } ForbiddenName filter = this.Service.GetGuildForbiddenNames(MockData.Ids[index]).Single(f => string.Compare(f.RegexString, regex, true) == 0); Assert.IsNotNull(filter); ForbiddenName dbf = db.ForbiddenNames .Where(f => f.GuildIdDb == (long)MockData.Ids[index]) .AsEnumerable() .Single(f => string.Compare(f.RegexString, regex, true) == 0); Assert.IsNotNull(dbf); foreach (string test in tests) { if (match) { Assert.IsTrue(filter.Regex.IsMatch(test)); } else { Assert.IsFalse(filter.Regex.IsMatch(test)); } } }
private static void SeedGuildData() { using TheGodfatherDbContext context = Database.CreateContext(); context.Configs.AddRange(MockData.Ids.Select(id => new GuildConfig { GuildId = id })); context.SaveChanges(); }
public async Task ExemptAsync(ulong gid, ExemptedEntityType type, IEnumerable <ulong> ids) { using TheGodfatherDbContext db = this.dbb.CreateContext(); db.ExemptsMention.AddExemptions(gid, type, ids); await db.SaveChangesAsync(); this.UpdateExemptsForGuildAsync(gid); }
public async Task <GuildConfig> GetConfigAsync(ulong gid) { GuildConfig?gcfg = null; using (TheGodfatherDbContext db = this.dbb.CreateContext()) gcfg = await db.Configs.FindAsync((long)gid); return(gcfg ?? new GuildConfig()); }
private void UpdateFilterCount(TheGodfatherDbContext db) { this.filterCount = this.filterCount.ToDictionary( kvp => kvp.Key, kvp => db.Filters .Count(f => f.GuildIdDb == (long)MockData.Ids[kvp.Key]) ); }
private void SetMockGuildConfig(TheGodfatherDbContext db) { foreach (KeyValuePair <ulong, GuildConfig> kvp in this.gcfg) { db.Attach(kvp.Value); db.Configs.Update(kvp.Value); } }
private void UpdateForbiddenNameCount(TheGodfatherDbContext db) { this.fnamesCount = this.fnamesCount.ToDictionary( kvp => kvp.Key, kvp => db.ForbiddenNames .Count(f => f.GuildIdDb == (long)MockData.Ids[kvp.Key]) ); }
public async Task <IReadOnlyList <Reminder> > GetRemindTasksForChannelAsync(ulong cid) { List <Reminder> reminders; using (TheGodfatherDbContext db = this.dbb.CreateContext()) reminders = await db.Reminders.Where(r => r.ChannelIdDb == (long)cid).ToListAsync(); return(reminders.AsReadOnly()); }
private void AddMockData(TheGodfatherDbContext db) { db.PrivilegedUsers.Add(new PrivilegedUser { UserId = MockData.Ids[0] }); db.PrivilegedUsers.Add(new PrivilegedUser { UserId = MockData.Ids[1] }); }
public async Task <IReadOnlyList <ExemptedBackupEntity> > GetExemptsAsync(ulong gid) { List <ExemptedBackupEntity> exempts; using TheGodfatherDbContext db = this.dbb.CreateContext(); exempts = await db.ExemptsBackup.Where(ex => ex.GuildIdDb == (long)gid).ToListAsync(); return(exempts.AsReadOnly()); }
public override Task <bool> ExecuteCheckAsync(CommandContext ctx, bool help) { if (ctx.Client.IsOwnedBy(ctx.User)) { return(Task.FromResult(true)); } using TheGodfatherDbContext db = ctx.Services.GetRequiredService <DbContextBuilder>().CreateContext(); return(Task.FromResult(db.PrivilegedUsers.Find((long)ctx.User.Id) is { }));
private void AssertGuildForbiddenNameCount(TheGodfatherDbContext db, int index, int count) { Assert.AreEqual(count, db.ForbiddenNames.Count(f => f.GuildIdDb == (long)MockData.Ids[index])); IReadOnlyCollection <ForbiddenName> fs = this.Service.GetGuildForbiddenNames(MockData.Ids[index]); Assert.AreEqual(count, fs.Count); CollectionAssert.AllItemsAreUnique(fs.Select(f => f.Id)); Assert.AreEqual(count, fs.Select(f => f.Regex.ToString()).Distinct().Count()); }
public async Task UnexemptAsync(ulong gid, ExemptedEntityType type, IEnumerable <ulong> ids) { using TheGodfatherDbContext db = this.dbb.CreateContext(); db.ExemptsMention.RemoveRange( db.ExemptsMention.Where(ex => ex.GuildId == gid && ex.Type == type && ids.Any(id => id == ex.Id)) ); await db.SaveChangesAsync(); this.UpdateExemptsForGuildAsync(gid); }
public async Task <RssFeed?> GetByUrlAsync(string url) { url = url.ToLowerInvariant(); RssFeed?feed = null; using TheGodfatherDbContext db = this.dbb.CreateContext(); feed = await db.RssFeeds.SingleOrDefaultAsync(f => f.Url == url); return(feed); }
public void LoadData() { using TheGodfatherDbContext db = this.dbb.CreateContext(); this.xps = new ConcurrentDictionary <ulong, ConcurrentDictionary <ulong, int> >( db.XpCounts .AsEnumerable() .GroupBy(xpc => xpc.GuildId) .ToDictionary(g => g.Key, g => new ConcurrentDictionary <ulong, int>(g.ToDictionary(g1 => g1.UserId, g1 => g1.Xp))) ); }
public bool IsNameForbidden(ulong gid, string name, out ForbiddenName?match) { match = null; using (TheGodfatherDbContext db = this.dbb.CreateContext()) { match = this.InternalGetForbiddenNamesForGuild(db, gid) .AsEnumerable() .FirstOrDefault(fn => fn.Regex.IsMatch(name)) ; } return(match is { });
public async Task DatabaseQuery(CommandContext ctx, [RemainingText, Description("desc-sql")] string query) { if (string.IsNullOrWhiteSpace(query)) { throw new InvalidCommandUsageException(ctx, "cmd-err-dbq-sql-none"); } var res = new List <IReadOnlyDictionary <string, string> >(); using (TheGodfatherDbContext db = ctx.Services.GetRequiredService <DbContextBuilder>().CreateContext()) using (RelationalDataReader dr = await db.Database.ExecuteSqlQueryAsync(query, db)) { DbDataReader reader = dr.DbDataReader; while (await reader.ReadAsync()) { var dict = new Dictionary <string, string>(); for (int i = 0; i < reader.FieldCount; i++) { dict[reader.GetName(i)] = reader[i] is DBNull ? "NULL" : reader[i]?.ToString() ?? "NULL"; } res.Add(new ReadOnlyDictionary <string, string>(dict)); } } if (!res.Any() || !res.First().Any()) { await ctx.ImpInfoAsync(this.ModuleColor, Emojis.Information, "str-dbq-none"); return; } int maxlen = 1 + res .First() .Select(r => r.Key) .OrderByDescending(r => r.Length) .First() .Length; await ctx.PaginateAsync( "str-dbq-res", res.Take(25), row => { var sb = new StringBuilder(); foreach ((string col, string val) in row) { sb.Append(col).Append(new string(' ', maxlen - col.Length)).Append("| ").AppendLine(val); } return(Formatter.BlockCode(sb.ToString())); }, this.ModuleColor, 1 ); }
public async Task UpdateAsync(IEnumerable <Chicken> chickens) { if (!chickens.Any()) { return; } using TheGodfatherDbContext db = this.dbb.CreateContext(); db.UpdateRange(chickens); await db.SaveChangesAsync(); }
private async Task<int> InternalRemoveByPredicateAsync(ulong gid, Func<Filter, bool> predicate) { using TheGodfatherDbContext db = this.dbb.CreateContext(); var filters = this.InternalGetFiltersForGuild(db, gid) .AsEnumerable() .Where(predicate) .ToList(); db.Filters.RemoveRange(filters); await db.SaveChangesAsync(); return this.filters.GetValueOrDefault(gid)?.RemoveWhere(predicate) ?? 0; }
private async Task <IReadOnlyList <GameStats> > GetOrderedInternalAsync <T>(int amount, Func <GameStats, T> orderBy, Func <GameStats, T>?thenBy = null) { // FIXME inefficient - try to use IQueryable with LINQ Expressions ? List <GameStats> top; using (TheGodfatherDbContext db = this.dbb.CreateContext()) { List <GameStats> stats = await db.GameStats.ToListAsync(); IOrderedEnumerable <GameStats> orderedStats = stats .OrderByDescending(orderBy) ; if (thenBy is { })
public async Task <Chicken?> GetCompleteAsync(ulong gid, ulong uid) { Chicken?chicken = null; using (TheGodfatherDbContext db = this.dbb.CreateContext()) { chicken = await db.Chickens .Include(c => c.Upgrades) .ThenInclude(u => u.Upgrade) .FirstOrDefaultAsync(c => c.GuildIdDb == (long)gid && c.UserIdDb == (long)uid); } return(chicken); }
public async Task <IReadOnlyList <PurchasedItem> > GetAllCompleteAsync(ulong uid) { List <PurchasedItem> res; using (TheGodfatherDbContext db = this.dbb.CreateContext()) { DbSet <PurchasedItem> set = this.DbSetSelector(db); res = await this.GroupSelector(set, uid) .Include(i => i.Item) .ToListAsync(); } return(res.AsReadOnly()); }
public void LoadData() { Log.Debug("Loading blocked entities"); try { using TheGodfatherDbContext db = this.dbb.CreateContext(); this.bChannels = new ConcurrentHashSet <ulong>(db.BlockedChannels.Select(c => c.Id)); this.bUsers = new ConcurrentHashSet <ulong>(db.BlockedUsers.Select(u => u.Id)); this.bGuilds = new ConcurrentHashSet <ulong>(db.BlockedGuilds.Select(g => g.Id)); } catch (Exception e) { Log.Error(e, "Loading blocked entities failed"); } }