2017-09-17 05:28:48 +00:00
|
|
|
|
using Microsoft.Data.Sqlite;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2016-11-15 11:01:02 +00:00
|
|
|
|
using NadekoBot.Services.Database;
|
2017-09-17 05:28:48 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
2017-09-10 01:52:34 +00:00
|
|
|
|
using System.Linq;
|
2016-08-24 01:32:48 +00:00
|
|
|
|
|
|
|
|
|
namespace NadekoBot.Services
|
|
|
|
|
{
|
2017-05-29 04:13:22 +00:00
|
|
|
|
public class DbService
|
2016-08-24 01:32:48 +00:00
|
|
|
|
{
|
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
|
|
|
|
|
2017-05-29 04:13:22 +00:00
|
|
|
|
public DbService(IBotCredentials creds)
|
2017-01-22 20:06:10 +00:00
|
|
|
|
{
|
2017-09-17 05:28:48 +00:00
|
|
|
|
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>();
|
2017-09-17 05:28:48 +00:00
|
|
|
|
optionsBuilder.UseSqlite(builder.ToString());
|
2016-11-15 11:01:02 +00:00
|
|
|
|
options = optionsBuilder.Options;
|
2017-09-10 01:52:34 +00:00
|
|
|
|
|
2017-09-16 00:10:22 +00:00
|
|
|
|
optionsBuilder = new DbContextOptionsBuilder<NadekoContext>();
|
2017-09-17 05:28:48 +00:00
|
|
|
|
optionsBuilder.UseSqlite(builder.ToString(), x => x.SuppressForeignKeyEnforcement());
|
2017-09-10 01:52:34 +00:00
|
|
|
|
migrateOptions = optionsBuilder.Options;
|
2016-08-24 01:32:48 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-01-22 20:06:10 +00:00
|
|
|
|
public NadekoContext GetDbContext()
|
|
|
|
|
{
|
|
|
|
|
var context = new NadekoContext(options);
|
2017-09-10 01:52:34 +00:00
|
|
|
|
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);
|
2017-01-22 20:06:10 +00:00
|
|
|
|
context.EnsureSeedData();
|
2016-08-24 01:32:48 +00:00
|
|
|
|
|
2017-06-22 20:16:58 +00:00
|
|
|
|
//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();
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-22 20:06:10 +00:00
|
|
|
|
return context;
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-22 23:59:31 +00:00
|
|
|
|
public IUnitOfWork UnitOfWork =>
|
2016-08-24 01:32:48 +00:00
|
|
|
|
new UnitOfWork(GetDbContext());
|
|
|
|
|
}
|
2017-01-22 20:06:10 +00:00
|
|
|
|
}
|