NadekoBot/NadekoBot.Core/Services/DbService.cs

59 lines
2.0 KiB
C#
Raw Normal View History

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database;
using System;
using System.IO;
using System.Linq;
namespace NadekoBot.Services
{
public class DbService
{
2017-09-16 00:10:22 +00:00
private readonly DbContextOptions<NadekoContext> options;
private readonly DbContextOptions<NadekoContext> migrateOptions;
2016-11-15 09:54:56 +00:00
public DbService(IBotCredentials creds)
{
var builder = new SqliteConnectionStringBuilder(creds.Db.ConnectionString);
builder.DataSource = Path.Combine(AppContext.BaseDirectory, builder.DataSource);
2017-09-16 00:10:22 +00:00
var optionsBuilder = new DbContextOptionsBuilder<NadekoContext>();
optionsBuilder.UseSqlite(builder.ToString());
options = optionsBuilder.Options;
2017-09-16 00:10:22 +00:00
optionsBuilder = new DbContextOptionsBuilder<NadekoContext>();
optionsBuilder.UseSqlite(builder.ToString(), x => x.SuppressForeignKeyEnforcement());
migrateOptions = optionsBuilder.Options;
}
public NadekoContext GetDbContext()
{
var context = new NadekoContext(options);
if (context.Database.GetPendingMigrations().Any())
{
var mContext = new NadekoContext(migrateOptions);
mContext.Database.Migrate();
mContext.SaveChanges();
mContext.Dispose();
}
2017-06-21 22:22:50 +00:00
context.Database.SetCommandTimeout(60);
context.EnsureSeedData();
//set important sqlite stuffs
var conn = context.Database.GetDbConnection();
conn.Open();
context.Database.ExecuteSqlCommand("PRAGMA journal_mode=WAL");
using (var com = conn.CreateCommand())
{
com.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF";
com.ExecuteNonQuery();
}
return context;
}
2017-05-22 23:59:31 +00:00
public IUnitOfWork UnitOfWork =>
new UnitOfWork(GetDbContext());
}
}