2024-05-14 11:08:36 +00:00
|
|
|
|
using LinqToDB.Common;
|
|
|
|
|
using LinqToDB.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
|
|
|
|
namespace EllieBot.Db;
|
|
|
|
|
|
2024-06-29 05:50:16 +00:00
|
|
|
|
public sealed class EllieDbService : DbService
|
2024-05-14 11:08:36 +00:00
|
|
|
|
{
|
|
|
|
|
private readonly IBotCredsProvider _creds;
|
|
|
|
|
|
|
|
|
|
// these are props because creds can change at runtime
|
|
|
|
|
private string DbType => _creds.GetCreds().Db.Type.ToLowerInvariant().Trim();
|
|
|
|
|
private string ConnString => _creds.GetCreds().Db.ConnectionString;
|
2024-06-29 05:50:16 +00:00
|
|
|
|
|
2024-05-14 11:08:36 +00:00
|
|
|
|
public EllieDbService(IBotCredsProvider creds)
|
|
|
|
|
{
|
|
|
|
|
LinqToDBForEFTools.Initialize();
|
|
|
|
|
Configuration.Linq.DisableQueryCache = true;
|
|
|
|
|
|
|
|
|
|
_creds = creds;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override async Task SetupAsync()
|
|
|
|
|
{
|
|
|
|
|
var dbType = DbType;
|
|
|
|
|
var connString = ConnString;
|
|
|
|
|
|
|
|
|
|
await using var context = CreateRawDbContext(dbType, connString);
|
2024-06-29 05:50:16 +00:00
|
|
|
|
|
2024-05-14 11:08:36 +00:00
|
|
|
|
// make sure sqlite db is in wal journal mode
|
|
|
|
|
if (context is SqliteContext)
|
|
|
|
|
{
|
|
|
|
|
await context.Database.ExecuteSqlRawAsync("PRAGMA journal_mode=WAL");
|
|
|
|
|
}
|
2024-06-29 05:50:16 +00:00
|
|
|
|
|
2024-05-14 11:08:36 +00:00
|
|
|
|
await context.Database.MigrateAsync();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override EllieContext CreateRawDbContext(string dbType, string connString)
|
|
|
|
|
{
|
|
|
|
|
switch (dbType)
|
|
|
|
|
{
|
|
|
|
|
case "postgresql":
|
|
|
|
|
case "postgres":
|
|
|
|
|
case "pgsql":
|
|
|
|
|
return new PostgreSqlContext(connString);
|
|
|
|
|
case "mysql":
|
|
|
|
|
return new MysqlContext(connString);
|
|
|
|
|
case "sqlite":
|
|
|
|
|
return new SqliteContext(connString);
|
|
|
|
|
default:
|
|
|
|
|
throw new NotSupportedException($"The database provide type of '{dbType}' is not supported.");
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-06-29 05:50:16 +00:00
|
|
|
|
|
2024-05-14 11:08:36 +00:00
|
|
|
|
private EllieContext GetDbContextInternal()
|
|
|
|
|
{
|
|
|
|
|
var dbType = DbType;
|
|
|
|
|
var connString = ConnString;
|
|
|
|
|
|
|
|
|
|
var context = CreateRawDbContext(dbType, connString);
|
|
|
|
|
if (context is SqliteContext)
|
|
|
|
|
{
|
|
|
|
|
var conn = context.Database.GetDbConnection();
|
|
|
|
|
conn.Open();
|
|
|
|
|
using var com = conn.CreateCommand();
|
|
|
|
|
com.CommandText = "PRAGMA synchronous=OFF";
|
|
|
|
|
com.ExecuteNonQuery();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return context;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override EllieContext GetDbContext()
|
|
|
|
|
=> GetDbContextInternal();
|
|
|
|
|
}
|