2021-08-27 15:03:47 +00:00
|
|
|
using System;
|
2020-06-14 19:37:04 +00:00
|
|
|
using System.Collections.Generic;
|
2020-06-13 17:15:50 +00:00
|
|
|
using System.Data;
|
2020-06-13 17:54:16 +00:00
|
|
|
using System.IO;
|
2021-09-30 01:51:38 +00:00
|
|
|
using System.Runtime.CompilerServices;
|
2020-06-13 16:31:20 +00:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
using App.Metrics;
|
|
|
|
|
2020-06-13 17:15:50 +00:00
|
|
|
using Dapper;
|
|
|
|
|
|
|
|
using NodaTime;
|
|
|
|
|
2020-06-13 16:31:20 +00:00
|
|
|
using Npgsql;
|
|
|
|
|
|
|
|
using Serilog;
|
|
|
|
|
2021-09-30 01:51:38 +00:00
|
|
|
using SqlKata;
|
|
|
|
using SqlKata.Compilers;
|
|
|
|
|
2020-06-13 16:31:20 +00:00
|
|
|
namespace PluralKit.Core
|
|
|
|
{
|
2020-06-13 17:36:43 +00:00
|
|
|
internal class Database: IDatabase
|
2020-06-13 16:31:20 +00:00
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 16:31:20 +00:00
|
|
|
private readonly CoreConfig _config;
|
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly IMetrics _metrics;
|
|
|
|
private readonly DbConnectionCountHolder _countHolder;
|
2021-08-01 15:13:32 +00:00
|
|
|
private readonly DatabaseMigrator _migrator;
|
2020-09-09 20:21:46 +00:00
|
|
|
private readonly string _connectionString;
|
2020-06-13 16:31:20 +00:00
|
|
|
|
|
|
|
public Database(CoreConfig config, DbConnectionCountHolder countHolder, ILogger logger,
|
2021-08-01 15:13:32 +00:00
|
|
|
IMetrics metrics, DatabaseMigrator migrator)
|
2020-06-13 16:31:20 +00:00
|
|
|
{
|
|
|
|
_config = config;
|
|
|
|
_countHolder = countHolder;
|
|
|
|
_metrics = metrics;
|
2021-08-01 15:13:32 +00:00
|
|
|
_migrator = migrator;
|
2021-06-10 12:21:05 +00:00
|
|
|
_logger = logger.ForContext<Database>();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-09-09 20:21:46 +00:00
|
|
|
_connectionString = new NpgsqlConnectionStringBuilder(_config.Database)
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
Pooling = true,
|
|
|
|
Enlist = false,
|
|
|
|
NoResetOnClose = true,
|
|
|
|
|
2020-10-14 21:35:10 +00:00
|
|
|
// Lower timeout than default (15s -> 2s), should ideally fail-fast instead of hanging
|
|
|
|
Timeout = 2
|
2020-09-09 20:21:46 +00:00
|
|
|
}.ConnectionString;
|
2020-06-13 16:31:20 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-09-30 01:51:38 +00:00
|
|
|
private static readonly PostgresCompiler _compiler = new();
|
|
|
|
|
2020-06-13 17:15:50 +00:00
|
|
|
public static void InitStatic()
|
|
|
|
{
|
2020-06-14 19:37:04 +00:00
|
|
|
DefaultTypeMap.MatchNamesWithUnderscores = true;
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 17:15:50 +00:00
|
|
|
// Dapper by default tries to pass ulongs to Npgsql, which rejects them since PostgreSQL technically
|
|
|
|
// doesn't support unsigned types on its own.
|
|
|
|
// Instead we add a custom mapper to encode them as signed integers instead, converting them back and forth.
|
|
|
|
SqlMapper.RemoveTypeMap(typeof(ulong));
|
|
|
|
SqlMapper.AddTypeHandler(new UlongEncodeAsLongHandler());
|
|
|
|
SqlMapper.AddTypeHandler(new UlongArrayHandler());
|
|
|
|
|
|
|
|
NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
|
|
|
|
// With the thing we add above, Npgsql already handles NodaTime integration
|
|
|
|
// This makes Dapper confused since it thinks it has to convert it anyway and doesn't understand the types
|
|
|
|
// So we add a custom type handler that literally just passes the type through to Npgsql
|
|
|
|
SqlMapper.AddTypeHandler(new PassthroughTypeHandler<Instant>());
|
|
|
|
SqlMapper.AddTypeHandler(new PassthroughTypeHandler<LocalDate>());
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-14 19:37:04 +00:00
|
|
|
// Add ID types to Dapper
|
|
|
|
SqlMapper.AddTypeHandler(new NumericIdHandler<SystemId, int>(i => new SystemId(i)));
|
|
|
|
SqlMapper.AddTypeHandler(new NumericIdHandler<MemberId, int>(i => new MemberId(i)));
|
|
|
|
SqlMapper.AddTypeHandler(new NumericIdHandler<SwitchId, int>(i => new SwitchId(i)));
|
2020-06-29 21:51:12 +00:00
|
|
|
SqlMapper.AddTypeHandler(new NumericIdHandler<GroupId, int>(i => new GroupId(i)));
|
2020-06-14 19:37:04 +00:00
|
|
|
SqlMapper.AddTypeHandler(new NumericIdArrayHandler<SystemId, int>(i => new SystemId(i)));
|
|
|
|
SqlMapper.AddTypeHandler(new NumericIdArrayHandler<MemberId, int>(i => new MemberId(i)));
|
|
|
|
SqlMapper.AddTypeHandler(new NumericIdArrayHandler<SwitchId, int>(i => new SwitchId(i)));
|
2020-06-29 21:51:12 +00:00
|
|
|
SqlMapper.AddTypeHandler(new NumericIdArrayHandler<GroupId, int>(i => new GroupId(i)));
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 17:15:50 +00:00
|
|
|
// Register our custom types to Npgsql
|
|
|
|
// Without these it'll still *work* but break at the first launch + probably cause other small issues
|
|
|
|
NpgsqlConnection.GlobalTypeMapper.MapComposite<ProxyTag>("proxy_tag");
|
|
|
|
NpgsqlConnection.GlobalTypeMapper.MapEnum<PrivacyLevel>("privacy_level");
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 16:31:20 +00:00
|
|
|
public async Task<IPKConnection> Obtain()
|
|
|
|
{
|
|
|
|
// Mark the request (for a handle, I guess) in the metrics
|
|
|
|
_metrics.Measure.Meter.Mark(CoreMetrics.DatabaseRequests);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 16:31:20 +00:00
|
|
|
// Create a connection and open it
|
|
|
|
// We wrap it in PKConnection for tracing purposes
|
2020-09-09 20:21:46 +00:00
|
|
|
var conn = new PKConnection(new NpgsqlConnection(_connectionString), _countHolder, _logger, _metrics);
|
2020-06-13 16:31:20 +00:00
|
|
|
await conn.OpenAsync();
|
|
|
|
return conn;
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-06-13 17:54:16 +00:00
|
|
|
public async Task ApplyMigrations()
|
|
|
|
{
|
2021-08-01 15:13:32 +00:00
|
|
|
using var conn = await Obtain();
|
|
|
|
await _migrator.ApplyMigrations(conn);
|
2020-06-13 17:54:16 +00:00
|
|
|
}
|
2020-06-13 17:15:50 +00:00
|
|
|
|
|
|
|
private class PassthroughTypeHandler<T>: SqlMapper.TypeHandler<T>
|
|
|
|
{
|
|
|
|
public override void SetValue(IDbDataParameter parameter, T value) => parameter.Value = value;
|
2021-08-27 15:03:47 +00:00
|
|
|
public override T Parse(object value) => (T)value;
|
2020-06-13 17:15:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private class UlongEncodeAsLongHandler: SqlMapper.TypeHandler<ulong>
|
|
|
|
{
|
|
|
|
public override ulong Parse(object value) =>
|
|
|
|
// Cast to long to unbox, then to ulong (???)
|
2021-08-27 15:03:47 +00:00
|
|
|
(ulong)(long)value;
|
2020-06-13 17:15:50 +00:00
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public override void SetValue(IDbDataParameter parameter, ulong value) => parameter.Value = (long)value;
|
2020-06-13 17:15:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private class UlongArrayHandler: SqlMapper.TypeHandler<ulong[]>
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
public override void SetValue(IDbDataParameter parameter, ulong[] value) => parameter.Value = Array.ConvertAll(value, i => (long)i);
|
2020-06-13 17:15:50 +00:00
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public override ulong[] Parse(object value) => Array.ConvertAll((long[])value, i => (ulong)i);
|
2020-06-13 17:15:50 +00:00
|
|
|
}
|
2020-06-14 19:37:04 +00:00
|
|
|
|
|
|
|
private class NumericIdHandler<T, TInner>: SqlMapper.TypeHandler<T>
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : INumericId<T, TInner>
|
|
|
|
where TInner : IEquatable<TInner>, IComparable<TInner>
|
2020-06-14 19:37:04 +00:00
|
|
|
{
|
|
|
|
private readonly Func<TInner, T> _factory;
|
|
|
|
|
|
|
|
public NumericIdHandler(Func<TInner, T> factory)
|
|
|
|
{
|
|
|
|
_factory = factory;
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void SetValue(IDbDataParameter parameter, T value) => parameter.Value = value.Value;
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public override T Parse(object value) => _factory((TInner)value);
|
2020-06-14 19:37:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private class NumericIdArrayHandler<T, TInner>: SqlMapper.TypeHandler<T[]>
|
2021-08-27 15:03:47 +00:00
|
|
|
where T : INumericId<T, TInner>
|
|
|
|
where TInner : IEquatable<TInner>, IComparable<TInner>
|
2020-06-14 19:37:04 +00:00
|
|
|
{
|
|
|
|
private readonly Func<TInner, T> _factory;
|
|
|
|
|
|
|
|
public NumericIdArrayHandler(Func<TInner, T> factory)
|
|
|
|
{
|
|
|
|
_factory = factory;
|
|
|
|
}
|
|
|
|
|
|
|
|
public override void SetValue(IDbDataParameter parameter, T[] value) => parameter.Value = Array.ConvertAll(value, v => v.Value);
|
|
|
|
|
2021-08-27 15:03:47 +00:00
|
|
|
public override T[] Parse(object value) => Array.ConvertAll((TInner[])value, v => _factory(v));
|
2020-06-14 19:37:04 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-09-30 01:51:38 +00:00
|
|
|
public async Task Execute(Func<IPKConnection, Task> func)
|
2020-08-05 18:24:51 +00:00
|
|
|
{
|
2021-09-30 01:51:38 +00:00
|
|
|
await using var conn = await Obtain();
|
2020-08-05 18:24:51 +00:00
|
|
|
await func(conn);
|
|
|
|
}
|
2020-08-29 11:46:27 +00:00
|
|
|
|
2021-09-30 01:51:38 +00:00
|
|
|
public async Task<T> Execute<T>(Func<IPKConnection, Task<T>> func)
|
2020-08-05 18:24:51 +00:00
|
|
|
{
|
2021-09-30 01:51:38 +00:00
|
|
|
await using var conn = await Obtain();
|
2020-08-05 18:24:51 +00:00
|
|
|
return await func(conn);
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-09-30 01:51:38 +00:00
|
|
|
public async IAsyncEnumerable<T> Execute<T>(Func<IPKConnection, IAsyncEnumerable<T>> func)
|
2020-08-29 11:46:27 +00:00
|
|
|
{
|
2021-09-30 01:51:38 +00:00
|
|
|
await using var conn = await Obtain();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-08-29 11:46:27 +00:00
|
|
|
await foreach (var val in func(conn))
|
|
|
|
yield return val;
|
|
|
|
}
|
2021-09-30 01:51:38 +00:00
|
|
|
|
|
|
|
public async Task<int> ExecuteQuery(Query q, string extraSql = "", [CallerMemberName] string queryName = "")
|
|
|
|
{
|
|
|
|
var query = _compiler.Compile(q);
|
|
|
|
using var conn = await Obtain();
|
|
|
|
using (_metrics.Measure.Timer.Time(CoreMetrics.DatabaseQuery, new MetricTags("Query", queryName)))
|
|
|
|
return await conn.ExecuteAsync(query.Sql + $" {extraSql}", query.NamedBindings);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T> QueryFirst<T>(Query q, string extraSql = "", [CallerMemberName] string queryName = "")
|
|
|
|
{
|
|
|
|
var query = _compiler.Compile(q);
|
|
|
|
using var conn = await Obtain();
|
|
|
|
using (_metrics.Measure.Timer.Time(CoreMetrics.DatabaseQuery, new MetricTags("Query", queryName)))
|
|
|
|
return await conn.QueryFirstOrDefaultAsync<T>(query.Sql + $" {extraSql}", query.NamedBindings);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<T> QueryFirst<T>(IPKConnection? conn, Query q, string extraSql = "", [CallerMemberName] string queryName = "")
|
|
|
|
{
|
|
|
|
if (conn == null)
|
|
|
|
return await QueryFirst<T>(q, extraSql, queryName);
|
|
|
|
|
|
|
|
var query = _compiler.Compile(q);
|
|
|
|
using (_metrics.Measure.Timer.Time(CoreMetrics.DatabaseQuery, new MetricTags("Query", queryName)))
|
|
|
|
return await conn.QueryFirstOrDefaultAsync<T>(query.Sql + $" {extraSql}", query.NamedBindings);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<IEnumerable<T>> Query<T>(Query q, [CallerMemberName] string queryName = "")
|
|
|
|
{
|
|
|
|
var query = _compiler.Compile(q);
|
|
|
|
using var conn = await Obtain();
|
|
|
|
using (_metrics.Measure.Timer.Time(CoreMetrics.DatabaseQuery, new MetricTags("Query", queryName)))
|
|
|
|
return await conn.QueryAsync<T>(query.Sql, query.NamedBindings);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async IAsyncEnumerable<T> QueryStream<T>(Query q, [CallerMemberName] string queryName = "")
|
|
|
|
{
|
|
|
|
var query = _compiler.Compile(q);
|
|
|
|
using var conn = await Obtain();
|
|
|
|
using (_metrics.Measure.Timer.Time(CoreMetrics.DatabaseQuery, new MetricTags("Query", queryName)))
|
|
|
|
await foreach (var val in conn.QueryStreamAsync<T>(query.Sql, query.NamedBindings))
|
|
|
|
yield return val;
|
|
|
|
}
|
|
|
|
|
|
|
|
// the procedures (message_context and proxy_members, as of writing) have their own metrics tracking elsewhere
|
|
|
|
// still, including them here for consistency
|
|
|
|
|
|
|
|
public async Task<T> QuerySingleProcedure<T>(string queryName, object param)
|
|
|
|
{
|
|
|
|
using var conn = await Obtain();
|
|
|
|
return await conn.QueryFirstAsync<T>(queryName, param, commandType: CommandType.StoredProcedure);
|
|
|
|
}
|
|
|
|
|
|
|
|
public async Task<IEnumerable<T>> QueryProcedure<T>(string queryName, object param)
|
|
|
|
{
|
|
|
|
using var conn = await Obtain();
|
|
|
|
return await conn.QueryAsync<T>(queryName, param, commandType: CommandType.StoredProcedure);
|
|
|
|
}
|
2020-08-05 18:24:51 +00:00
|
|
|
}
|
2020-06-13 16:31:20 +00:00
|
|
|
}
|