Create multiple database contexts instead of one

This commit is contained in:
runebaas 2018-08-29 21:16:01 +02:00
parent d1e9992a8c
commit b0758eb119
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6
5 changed files with 47 additions and 24 deletions

View file

@ -158,10 +158,10 @@ namespace Geekbot.net.Commands.User.Ranking
// .ToDictionary(key => key.UserId.AsUlong(), key => key.MessageCount); // .ToDictionary(key => key.UserId.AsUlong(), key => key.MessageCount);
return _redis.Db return _redis.Db
.HashGetAll($"{Context.Guild.Id}:Messages") .HashGetAll($"{Context.Guild.Id}:Messages")
.Where(user => !user.Key.Equals(0)) .Where(user => !user.Name.Equals(0))
.OrderByDescending(s => s.Value) .OrderByDescending(s => s.Value)
.Take(amount) .Take(amount)
.ToDictionary(user => ulong.Parse(user.Key), user => int.Parse(user.Value)); .ToDictionary(user => ulong.Parse(user.Name), user => int.Parse(user.Value));
} }
private Dictionary<ulong, int> GetKarmaList(int amount) private Dictionary<ulong, int> GetKarmaList(int amount)

View file

@ -39,6 +39,13 @@ namespace Geekbot.net.Commands.User
var age = Math.Floor((DateTime.Now - createdAt).TotalDays); var age = Math.Floor((DateTime.Now - createdAt).TotalDays);
var joinedDayAgo = Math.Floor((DateTime.Now - joinedAt).TotalDays); var joinedDayAgo = Math.Floor((DateTime.Now - joinedAt).TotalDays);
// var messages = _database.Messages
// .First(e => e.GuildId.Equals(Context.Guild.Id.AsLong()) && e.UserId.Equals(Context.User.Id.AsLong()))
// .MessageCount;
// var guildMessages = _database.Messages
// .Where(e => e.GuildId.Equals(Context.Guild.Id.AsLong()))
// .Select(e => e.MessageCount)
// .Sum();
var messages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", userInfo.Id.ToString()); var messages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", userInfo.Id.ToString());
var guildMessages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", 0.ToString()); var guildMessages = (int) _redis.Db.HashGet($"{Context.Guild.Id}:Messages", 0.ToString());
var level = _levelCalc.GetLevel(messages); var level = _levelCalc.GetLevel(messages);

View file

@ -16,9 +16,10 @@ namespace Geekbot.net.Database
{ {
_runParameters = runParameters; _runParameters = runParameters;
_logger = logger; _logger = logger;
NpgsqlLogManager.Provider = new NpgsqlLoggingProviderAdapter(_logger);
} }
public DatabaseContext Initzialize() public DatabaseContext Initialize()
{ {
DatabaseContext database = null; DatabaseContext database = null;
try try
@ -29,7 +30,6 @@ namespace Geekbot.net.Database
} }
else else
{ {
NpgsqlLogManager.Provider = new NpgsqlLoggingProviderAdapter(_logger);
database = new SqlDatabase(new SqlConnectionString database = new SqlDatabase(new SqlConnectionString
{ {
Host = _runParameters.DbHost, Host = _runParameters.DbHost,
@ -39,8 +39,6 @@ namespace Geekbot.net.Database
Password = _runParameters.DbPassword Password = _runParameters.DbPassword
}); });
} }
database.Database.EnsureCreated();
if(!_runParameters.InMemory) database.Database.Migrate();
} }
catch (Exception e) catch (Exception e)
{ {

View file

@ -6,6 +6,7 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.Models;
using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.AlmostRedis;
using Geekbot.net.Lib.Extensions; using Geekbot.net.Lib.Extensions;
using Geekbot.net.Lib.Logger; using Geekbot.net.Lib.Logger;
@ -25,12 +26,14 @@ namespace Geekbot.net
private readonly CommandService _commands; private readonly CommandService _commands;
private readonly IUserRepository _userRepository; private readonly IUserRepository _userRepository;
private readonly IReactionListener _reactionListener; private readonly IReactionListener _reactionListener;
private readonly DatabaseContext _messageCounterDatabaseContext;
public Handlers(DatabaseContext database, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis, public Handlers(DatabaseInitializer databaseInitializer, IDiscordClient client, IGeekbotLogger logger, IAlmostRedis redis,
IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository, IServiceProvider servicesProvider, CommandService commands, IUserRepository userRepository,
IReactionListener reactionListener) IReactionListener reactionListener)
{ {
_database = database; _database = databaseInitializer.Initialize();
_messageCounterDatabaseContext = databaseInitializer.Initialize();
_client = client; _client = client;
_logger = logger; _logger = logger;
_redis = redis; _redis = redis;
@ -52,9 +55,6 @@ namespace Geekbot.net
if (message.Author.IsBot) return Task.CompletedTask; if (message.Author.IsBot) return Task.CompletedTask;
var argPos = 0; var argPos = 0;
// ToDo: remove
// if (!message.Author.Id.Equals(93061333972455424)) return Task.CompletedTask;
var lowCaseMsg = message.ToString().ToLower(); var lowCaseMsg = message.ToString().ToLower();
if (lowCaseMsg.StartsWith("hui")) if (lowCaseMsg.StartsWith("hui"))
{ {
@ -105,11 +105,23 @@ namespace Geekbot.net
var channel = (SocketGuildChannel) message.Channel; var channel = (SocketGuildChannel) message.Channel;
// await _database.Database.ExecuteSqlCommandAsync("UPDATE \"Messages\" " + // var rowId = await _messageCounterDatabaseContext.Database.ExecuteSqlCommandAsync(
// $"SET \"MessageCount\" = \"MessageCount\" + {1} " + // "UPDATE \"Messages\" SET \"MessageCount\" = \"MessageCount\" + 1 WHERE \"GuildId\" = {0} AND \"UserId\" = {1}",
// $"WHERE \"GuildId\" = '{channel.Guild.Id.AsLong()}' " + // channel.Guild.Id.AsLong(),
// $"AND \"UserId\" = '{message.Author.Id.AsLong()}'"); // message.Author.Id.AsLong()
// );
// //
// if (rowId == 0)
// {
// _messageCounterDatabaseContext.Messages.Add(new MessagesModel
// {
// UserId = message.Author.Id.AsLong(),
// GuildId = channel.Guild.Id.AsLong(),
// MessageCount = 1
// });
// _messageCounterDatabaseContext.SaveChanges();
// }
await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString()); await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", message.Author.Id.ToString());
await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString()); await _redis.Db.HashIncrementAsync($"{channel.Guild.Id}:Messages", 0.ToString());

View file

@ -7,6 +7,7 @@ using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Geekbot.net.Database; using Geekbot.net.Database;
using Geekbot.net.Database.LoggingAdapter;
using Geekbot.net.Lib; using Geekbot.net.Lib;
using Geekbot.net.Lib.AlmostRedis; using Geekbot.net.Lib.AlmostRedis;
using Geekbot.net.Lib.Audio; using Geekbot.net.Lib.Audio;
@ -20,6 +21,7 @@ using Geekbot.net.Lib.Logger;
using Geekbot.net.Lib.Media; using Geekbot.net.Lib.Media;
using Geekbot.net.Lib.ReactionListener; using Geekbot.net.Lib.ReactionListener;
using Geekbot.net.Lib.UserRepository; using Geekbot.net.Lib.UserRepository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using WikipediaApi; using WikipediaApi;
@ -29,7 +31,7 @@ namespace Geekbot.net
{ {
private DiscordSocketClient _client; private DiscordSocketClient _client;
private CommandService _commands; private CommandService _commands;
private DatabaseContext _database; private DatabaseInitializer _databaseInitializer;
private IGlobalSettings _globalSettings; private IGlobalSettings _globalSettings;
private IServiceCollection _services; private IServiceCollection _services;
private IServiceProvider _servicesProvider; private IServiceProvider _servicesProvider;
@ -82,8 +84,12 @@ namespace Geekbot.net
_client.Log += discordLogger.Log; _client.Log += discordLogger.Log;
_commands = new CommandService(); _commands = new CommandService();
_database = new DatabaseInitializer(runParameters, logger).Initzialize(); _databaseInitializer = new DatabaseInitializer(runParameters, logger);
_globalSettings = new GlobalSettings(_database); var database = _databaseInitializer.Initialize();
database.Database.EnsureCreated();
if(!_runParameters.InMemory) database.Database.Migrate();
_globalSettings = new GlobalSettings(database);
try try
{ {
@ -108,7 +114,7 @@ namespace Geekbot.net
_services = new ServiceCollection(); _services = new ServiceCollection();
_userRepository = new UserRepository(_database, logger); _userRepository = new UserRepository(_databaseInitializer.Initialize(), logger);
var fortunes = new FortunesProvider(logger); var fortunes = new FortunesProvider(logger);
var mediaProvider = new MediaProvider(logger); var mediaProvider = new MediaProvider(logger);
var malClient = new MalClient(_globalSettings, logger); var malClient = new MalClient(_globalSettings, logger);
@ -129,8 +135,8 @@ namespace Geekbot.net
_services.AddSingleton<IMtgManaConverter>(mtgManaConverter); _services.AddSingleton<IMtgManaConverter>(mtgManaConverter);
_services.AddSingleton<IWikipediaClient>(wikipediaClient); _services.AddSingleton<IWikipediaClient>(wikipediaClient);
_services.AddSingleton<IAudioUtils>(audioUtils); _services.AddSingleton<IAudioUtils>(audioUtils);
_services.AddSingleton<DatabaseContext>(_database);
_services.AddSingleton<IGlobalSettings>(_globalSettings); _services.AddSingleton<IGlobalSettings>(_globalSettings);
_services.AddTransient<DatabaseContext>((e) => _databaseInitializer.Initialize());
logger.Information(LogSource.Geekbot, "Connecting to Discord"); logger.Information(LogSource.Geekbot, "Connecting to Discord");
@ -152,7 +158,7 @@ namespace Geekbot.net
_logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); _logger.Information(LogSource.Geekbot, $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers");
_logger.Information(LogSource.Geekbot, "Registering Stuff"); _logger.Information(LogSource.Geekbot, "Registering Stuff");
var translationHandler = new TranslationHandler(_database, _logger); var translationHandler = new TranslationHandler(_databaseInitializer.Initialize(), _logger);
var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors); var errorHandler = new ErrorHandler(_logger, translationHandler, _runParameters.ExposeErrors);
var reactionListener = new ReactionListener(_redis.Db); var reactionListener = new ReactionListener(_redis.Db);
await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
@ -163,7 +169,7 @@ namespace Geekbot.net
_services.AddSingleton<IReactionListener>(reactionListener); _services.AddSingleton<IReactionListener>(reactionListener);
_servicesProvider = _services.BuildServiceProvider(); _servicesProvider = _services.BuildServiceProvider();
var handlers = new Handlers(_database, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); var handlers = new Handlers(_databaseInitializer, _client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener);
_client.MessageReceived += handlers.RunCommand; _client.MessageReceived += handlers.RunCommand;
_client.MessageReceived += handlers.UpdateStats; _client.MessageReceived += handlers.UpdateStats;
@ -198,7 +204,7 @@ namespace Geekbot.net
private Task StartWebApi() private Task StartWebApi()
{ {
_logger.Information(LogSource.Api, "Starting Webserver"); _logger.Information(LogSource.Api, "Starting Webserver");
WebApi.WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _database); WebApi.WebApiStartup.StartWebApi(_logger, _runParameters, _commands, _databaseInitializer.Initialize());
return Task.CompletedTask; return Task.CompletedTask;
} }
} }