83 lines
2.7 KiB
C#
83 lines
2.7 KiB
C#
using System.Reflection;
|
||
using DispenserCommon.Events;
|
||
using DispenserCommon.Utils;
|
||
using SQLite;
|
||
|
||
namespace DispenserCommon.DB;
|
||
|
||
/// <summary>
|
||
/// 在系统启动的时候记进行数据库初始化校验
|
||
/// </summary>
|
||
public class DatabaseInitializer
|
||
{
|
||
private static readonly SqliteHelper Sqlite = ServiceLocator.GetService<SqliteHelper>();
|
||
|
||
public static void Initialize()
|
||
{
|
||
EventBus<string>.Publish(EventType.SetupNotify, "正在初始化数据库");
|
||
|
||
// 扫描所有带有[Table]特性的类
|
||
var tables = GetAssemblies()
|
||
.SelectMany(a => a.GetTypes()
|
||
.Where(t => t.GetCustomAttributes(typeof(TableAttribute), true).Length > 0))
|
||
.ToList();
|
||
|
||
|
||
tables.ForEach(table =>
|
||
{
|
||
// 判断当前的表是否存在
|
||
var tableName = table.GetCustomAttribute<TableAttribute>()?.Name ?? table.Name;
|
||
|
||
var tableInfo = Sqlite.GetTableInfo(tableName);
|
||
|
||
if (!tableInfo.Any())
|
||
{
|
||
Sqlite.CreateTable(table);
|
||
}
|
||
else
|
||
{
|
||
// 读取当前类的变量是否新增了属性
|
||
var properties = table.GetProperties();
|
||
var colNames = tableInfo.Select(col => col.Name.ToUpper()).ToHashSet();
|
||
|
||
foreach (var property in properties)
|
||
{
|
||
var colName = property.GetCustomAttribute<ColumnAttribute>()?.Name ?? property.Name;
|
||
|
||
// 统一转为大写进行判断
|
||
if (colNames.Contains(colName.ToUpper())) continue;
|
||
// 重新进行DDL时,会自动的判断是否存在新增的列,如果有则自动进行新增
|
||
Sqlite.CreateTable(table);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
|
||
private static IEnumerable<Assembly> GetAssemblies()
|
||
{
|
||
var assemblies = new List<Assembly>();
|
||
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||
{
|
||
var name = assembly.GetName().Name;
|
||
if (name != null && name.ToLower().Contains("dispenser")) GetReferenceAssemblies(assembly, assemblies);
|
||
}
|
||
|
||
return assemblies;
|
||
}
|
||
|
||
private static void GetReferenceAssemblies(Assembly assembly, ICollection<Assembly> assemblies)
|
||
{
|
||
foreach (var assemblyName in assembly.GetReferencedAssemblies())
|
||
{
|
||
var name = assemblyName.Name;
|
||
if (name != null && name.ToLower().Contains("dispenser"))
|
||
{
|
||
var ass = Assembly.Load(assemblyName);
|
||
if (assemblies.Contains(ass)) continue;
|
||
assemblies.Add(ass);
|
||
GetReferenceAssemblies(ass, assemblies);
|
||
}
|
||
}
|
||
}
|
||
} |