BUG:种子数据类型如果出现空数据会立即终止后序的所有种子数据生成

This commit is contained in:
yzp 2025-05-28 10:06:23 +08:00
parent 66da7297ca
commit 8b12e6903b
2 changed files with 706 additions and 716 deletions

View File

@ -131,15 +131,15 @@ public static class SqlSugarExtension
Expression binaryExpresioFilter; Expression binaryExpresioFilter;
if (Enum.IsDefined(typeof(FilterLogicEnum), filter.Logic)) if (filter.Logic.HasValue)
{ {
if (filter.Filters is null) throw new ArgumentException("The Filters attribute is required when declaring a logic"); if (filter.Filters is null) throw new ArgumentException("The Filters attribute is required when declaring a logic");
binaryExpresioFilter = CreateFilterExpression(filter.Logic, filter.Filters, parameter); binaryExpresioFilter = CreateFilterExpression(filter.Logic.Value, filter.Filters, parameter);
} }
else else
{ {
var filterValid = GetValidFilter(filter); var filterValid = GetValidFilter(filter);
binaryExpresioFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator, filterValid.Value, parameter); binaryExpresioFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator.Value, filterValid.Value, parameter);
} }
var lambda = Expression.Lambda<Func<T, bool>>(binaryExpresioFilter, parameter); var lambda = Expression.Lambda<Func<T, bool>>(binaryExpresioFilter, parameter);
@ -175,15 +175,15 @@ public static class SqlSugarExtension
{ {
Expression bExpresionFilter; Expression bExpresionFilter;
if (Enum.IsDefined(typeof(FilterLogicEnum), filter.Logic)) if (filter.Logic.HasValue)
{ {
if (filter.Filters is null) throw new ArgumentException("The Filters attribute is required when declaring a logic"); if (filter.Filters is null) throw new ArgumentException("The Filters attribute is required when declaring a logic");
bExpresionFilter = CreateFilterExpression(filter.Logic, filter.Filters, parameter); bExpresionFilter = CreateFilterExpression(filter.Logic.Value, filter.Filters, parameter);
} }
else else
{ {
var filterValid = GetValidFilter(filter); var filterValid = GetValidFilter(filter);
bExpresionFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator, filterValid.Value, parameter); bExpresionFilter = CreateFilterExpression(filterValid.Field!, filterValid.Operator.Value, filterValid.Value, parameter);
} }
filterExpression = filterExpression is null ? bExpresionFilter : CombineFilter(filterLogic, filterExpression, bExpresionFilter); filterExpression = filterExpression is null ? bExpresionFilter : CombineFilter(filterLogic, filterExpression, bExpresionFilter);
@ -385,22 +385,37 @@ public static class SqlSugarExtension
if (entityType.GetCustomAttribute<SysTableAttribute>() == null && if (entityType.GetCustomAttribute<SysTableAttribute>() == null &&
(entityType.GetCustomAttribute<LogTableAttribute>() != null || (entityType.GetCustomAttribute<LogTableAttribute>() != null ||
entityType.GetCustomAttribute<TenantAttribute>() != null)) entityType.GetCustomAttribute<TenantAttribute>() != null))
{
Console.WriteLine($" 忽略 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId}) 原因:非SysTable 与 (LogTable 或 Tenant)");
return default; return default;
} }
}
else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库 else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
{ {
if (entityType.GetCustomAttribute<LogTableAttribute>() == null) return default; if (entityType.GetCustomAttribute<LogTableAttribute>() == null)
{
Console.WriteLine($" 忽略 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId}) 原因:LogTable");
return default;
}
} }
else else
{ {
var att = entityType.GetCustomAttribute<TenantAttribute>(); // 自定义的库 var att = entityType.GetCustomAttribute<TenantAttribute>(); // 自定义的库
if (att == null || att.configId.ToString() != config.ConfigId.ToString()) return default; if (att == null || att.configId.ToString() != config.ConfigId.ToString())
{
Console.WriteLine($" 忽略 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId}) 原因: Tenant 表,但不是这个库:{att.configId} != {config.ConfigId} ");
return default;
}
} }
var instance = Activator.CreateInstance(seedType); var instance = Activator.CreateInstance(seedType);
var hasDataMethod = seedType.GetMethod("HasData"); var hasDataMethod = seedType.GetMethod("HasData");
var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>().ToArray() ?? []; var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>().ToArray() ?? [];
if (!seedData.Any()) return default; if (!seedData.Any())
{
Console.WriteLine($" 忽略 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId}) 原因:没有数据");
return default;
}
// 若实体包含Id字段则设置为当前租户Id递增1 // 若实体包含Id字段则设置为当前租户Id递增1
var idProp = entityType.GetProperty(nameof(EntityBaseId.Id)); var idProp = entityType.GetProperty(nameof(EntityBaseId.Id));

View File

@ -153,6 +153,7 @@ public static class SqlSugarSetup
if (ex.Parametres == null) return; if (ex.Parametres == null) return;
var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n"; var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
Log.Error(log, ex); Log.Error(log, ex);
App.PrintToMiniProfiler("SqlSugar", "Error", log);
}; };
if (enableConsoleSql) if (enableConsoleSql)
{ {
@ -176,6 +177,7 @@ public static class SqlSugarSetup
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(log); Console.WriteLine(log);
Console.ForegroundColor = originColor; Console.ForegroundColor = originColor;
App.PrintToMiniProfiler("SqlSugar", "Info", log);
}; };
} }
dbProvider.Aop.OnLogExecuted = (sql, pars) => dbProvider.Aop.OnLogExecuted = (sql, pars) =>
@ -196,6 +198,7 @@ public static class SqlSugarSetup
var firstMethodName = dbProvider.Ado.SqlStackTrace.FirstMethodName; // 方法名 var firstMethodName = dbProvider.Ado.SqlStackTrace.FirstMethodName; // 方法名
var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】{fileName}\r\n【代码行数】{fileLine}\r\n【方法名】{firstMethodName}\r\n" + $"【SQL语句】{UtilMethods.GetNativeSql(sql, pars)}"; var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】{fileName}\r\n【代码行数】{fileLine}\r\n【方法名】{firstMethodName}\r\n" + $"【SQL语句】{UtilMethods.GetNativeSql(sql, pars)}";
Log.Warning(log); Log.Warning(log);
App.PrintToMiniProfiler("SqlSugar", "Slow", log);
}; };
// 数据审计 // 数据审计
@ -359,14 +362,10 @@ public static class SqlSugarSetup
{ {
var dbProvider = db.GetConnectionScope(config.ConfigId); var dbProvider = db.GetConnectionScope(config.ConfigId);
// 判断是否第一次启动 // 若第一次启动系统则强制初始化数据库表和种子数据
bool isFirstRun = true; bool isFirstRun = false;
try try { isFirstRun = dbProvider.CurrentConnectionConfig.ConfigId.ToString() == SqlSugarConst.MainConfigId && !dbProvider.DbMaintenance.IsAnyTable(dbProvider.EntityMaintenance.GetTableName(typeof(SysConfig))); }
{ catch { isFirstRun = true; }
dbProvider.DbMaintenance.IsAnySystemTablePermissions();
isFirstRun = false;
}
catch { }
// 初始化/创建数据库 // 初始化/创建数据库
if (config.DbSettings.EnableInitDb || isFirstRun) if (config.DbSettings.EnableInitDb || isFirstRun)
@ -381,7 +380,6 @@ public static class SqlSugarSetup
// 初始化表结构 // 初始化表结构
if (config.TableSettings.EnableInitTable || isFirstRun) if (config.TableSettings.EnableInitTable || isFirstRun)
{ {
var totalWatch = Stopwatch.StartNew(); // 开始总计时
Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}"); Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false)) var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
.Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any()) .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
@ -394,15 +392,6 @@ public static class SqlSugarSetup
else else
entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId.ToString()).ToList(); // 自定义的库 entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId.ToString()).ToList(); // 自定义的库
// 删除视图再初始化表结构,防止因为视图导致无法同步表结构
var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
foreach (var viewType in viewTypeList)
{
var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
}
int taskIndex = 0, size = entityTypes.Count; int taskIndex = 0, size = entityTypes.Count;
var taskList = entityTypes.Select(entityType => Task.Run(() => var taskList = entityTypes.Select(entityType => Task.Run(() =>
{ {
@ -416,10 +405,6 @@ public static class SqlSugarSetup
Console.WriteLine($"初始化表 {entityType,-64} ({config.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003}) 耗时:{stopWatch.ElapsedMilliseconds} ms"); Console.WriteLine($"初始化表 {entityType,-64} ({config.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003}) 耗时:{stopWatch.ElapsedMilliseconds} ms");
})); }));
Task.WaitAll(taskList.ToArray()); Task.WaitAll(taskList.ToArray());
totalWatch.Stop(); // 停止总计时
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"初始化表结构 {config.DbType} - {config.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds} ms");
} }
// 初始化视图 // 初始化视图
@ -527,7 +512,6 @@ public static class SqlSugarSetup
/// <param name="enableIncreSeed"></param> /// <param name="enableIncreSeed"></param>
private static void InitSeedData(SqlSugarScopeProvider dbProvider, bool enableIncreSeed) private static void InitSeedData(SqlSugarScopeProvider dbProvider, bool enableIncreSeed)
{ {
var totalWatch = Stopwatch.StartNew(); // 开始总计时
Log.Information($"初始化种子数据 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}"); Log.Information($"初始化种子数据 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>)))) var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
.Where(u => !u.IsDefined(typeof(TenantSeedAttribute), false)) .Where(u => !u.IsDefined(typeof(TenantSeedAttribute), false))
@ -542,17 +526,13 @@ public static class SqlSugarSetup
// 初始化种子数据 // 初始化种子数据
var tuple = dbProvider.InitTableSeedData(seedType); var tuple = dbProvider.InitTableSeedData(seedType);
if (tuple == null) return; if (tuple == null) continue;
stopWatch.Stop(); // 停止计时 stopWatch.Stop(); // 停止计时
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"初始化种子数据 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},数据量:{tuple.Value.Item1:D003},新增 {tuple.Value.Item2:D003} 条记录,更新 {tuple.Value.Item3:D003} 条记录,耗时:{stopWatch.ElapsedMilliseconds:N0} ms)"); Console.WriteLine($"初始化种子数据 {seedType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},数据量:{tuple.Value.Item1:D003},新增 {tuple.Value.Item2:D003} 条记录,更新 {tuple.Value.Item3:D003} 条记录,耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
} }
totalWatch.Stop(); // 停止总计时
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"初始化种子数据 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
} }
/// <summary> /// <summary>
@ -561,7 +541,6 @@ public static class SqlSugarSetup
/// <param name="dbProvider"></param> /// <param name="dbProvider"></param>
private static void InitView(SqlSugarScopeProvider dbProvider) private static void InitView(SqlSugarScopeProvider dbProvider)
{ {
var totalWatch = Stopwatch.StartNew(); // 开始总计时
Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}"); Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList(); var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
@ -575,7 +554,7 @@ public static class SqlSugarSetup
var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误"); var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
// 如果视图存在,则删除视图 // 如果视图存在,则删除视图
if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName))) if (dbProvider.DbMaintenance.GetViewInfoList().Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
dbProvider.DbMaintenance.DropView(entityInfo.DbTableName); dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
// 获取初始化视图查询SQL // 获取初始化视图查询SQL
@ -591,10 +570,6 @@ public static class SqlSugarSetup
Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)"); Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
})); }));
Task.WaitAll(taskList.ToArray()); Task.WaitAll(taskList.ToArray());
totalWatch.Stop(); // 停止总计时
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
} }
/// <summary> /// <summary>