75 lines
2.3 KiB
C#
75 lines
2.3 KiB
C#
using CalendarNotepad.Models;
|
|
using SqlSugar;
|
|
using System.Text;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace CalendarNotepad.Extends
|
|
{
|
|
/// <summary>
|
|
/// 数据库上下文
|
|
/// </summary>
|
|
public class DbContext:SqlSugar.SqlSugarClient
|
|
{
|
|
public DbContext() : base(GetConfig()) {
|
|
|
|
}
|
|
|
|
public static ConnectionConfig GetConfig() => new() {
|
|
DbType = DbType.Sqlite,
|
|
ConnectionString = AppConfig.SqliteFileName,
|
|
IsAutoCloseConnection = false,
|
|
};
|
|
|
|
/// <summary>
|
|
/// 初始化数据库
|
|
/// </summary>
|
|
public void DbInit() {
|
|
using var db = new DbContext();
|
|
db.CodeFirst.InitTables<WorkUnit>();
|
|
db.CodeFirst.InitTables<PlusFileUnit>();
|
|
db.CodeFirst.InitTables<WorkUnitPlusFile>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 清除数据库垃圾
|
|
/// </summary>
|
|
public string DbClean() {
|
|
StringBuilder sb = new();
|
|
int i;
|
|
i = this.Deleteable<WorkUnitPlusFile>()
|
|
.Where(a => !SqlFunc.Subqueryable<WorkUnit>().Where(b => b.WorkDay == a.WorkDay).Any())
|
|
.ExecuteCommand();
|
|
sb.AppendLine($"WorkUnitPlusFile 清除{i}条数据。");
|
|
|
|
i = this.Deleteable<PlusFileUnit>()
|
|
.Where(a => !SqlFunc.Subqueryable<WorkUnitPlusFile>().Where(b => b.FileKey == a.FileId).Any())
|
|
.ExecuteCommand();
|
|
sb.AppendLine($"PlusFileUnit 清除{i}条数据。");
|
|
return sb.ToString();
|
|
}
|
|
/// <summary>
|
|
/// 压缩数据库文件
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public string DbVacuum() {
|
|
var file = this.SqliteDbfile;
|
|
var oldSize = new FileInfo(file).Length;
|
|
this.Ado.ExecuteCommand("VACUUM;");
|
|
var newSize = new FileInfo(file).Length;
|
|
return $"数据库压缩:原始{oldSize},压缩后{newSize}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// sqllite数据库文件
|
|
/// </summary>
|
|
public string SqliteDbfile {
|
|
get {
|
|
var regex = new Regex(@"DataSource\s*=\s*(?<key>.*?);");
|
|
var mc = regex.Match(AppConfig.SqliteFileName);
|
|
var file = mc.Groups["key"].Value;
|
|
return file;
|
|
}
|
|
}
|
|
}
|
|
}
|