删除定时任务时用同步方法
This commit is contained in:
parent
fae951dd55
commit
c0d3dda44c
@ -59,10 +59,7 @@ public static class SqlSugarSetup
|
||||
services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
|
||||
|
||||
// 初始化数据库表结构及种子数据
|
||||
dbOptions.ConnectionConfigs.ForEach(config =>
|
||||
{
|
||||
InitDatabase(sqlSugar, config);
|
||||
});
|
||||
dbOptions.ConnectionConfigs.ForEach(config => { InitDatabase(sqlSugar, config); });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -166,7 +163,8 @@ public static class SqlSugarSetup
|
||||
dbProvider.Aop.OnError = ex =>
|
||||
{
|
||||
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);
|
||||
};
|
||||
if (enableConsoleSql)
|
||||
@ -185,7 +183,8 @@ public static class SqlSugarSetup
|
||||
var originColor = Console.ForegroundColor;
|
||||
if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
|
||||
if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) ||
|
||||
sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
@ -193,6 +192,7 @@ public static class SqlSugarSetup
|
||||
Console.ForegroundColor = originColor;
|
||||
};
|
||||
}
|
||||
|
||||
dbProvider.Aop.OnLogExecuted = (sql, pars) =>
|
||||
{
|
||||
//// 若参数值超过100个字符则进行截取
|
||||
@ -209,7 +209,9 @@ public static class SqlSugarSetup
|
||||
var fileName = dbProvider.Ado.SqlStackTrace.FirstFileName; // 文件名
|
||||
var fileLine = dbProvider.Ado.SqlStackTrace.FirstLine; // 行号
|
||||
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);
|
||||
};
|
||||
|
||||
@ -245,6 +247,7 @@ public static class SqlSugarSetup
|
||||
if (createTime == null || createTime.Equals(DateTime.MinValue))
|
||||
entityInfo.SetValue(DateTime.Now);
|
||||
}
|
||||
|
||||
// 若当前用户非空(web线程时)
|
||||
if (App.User == null || userManager.Value == null) return;
|
||||
|
||||
@ -253,12 +256,14 @@ public static class SqlSugarSetup
|
||||
if (entityInfo.PropertyName == nameof(IAppIdFilter.AppId) && entityValue is IAppIdFilter)
|
||||
{
|
||||
var appId = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
|
||||
if (appId == null || appId.Equals(0)) entityInfo.SetValue(userManager.Value?.AppId ?? SqlSugarConst.DefaultAppId);
|
||||
if (appId == null || appId.Equals(0))
|
||||
entityInfo.SetValue(userManager.Value?.AppId ?? SqlSugarConst.DefaultAppId);
|
||||
}
|
||||
else if (entityInfo.PropertyName == nameof(EntityTenantId.TenantId))
|
||||
{
|
||||
if (entityValue.TenantId == null || entityValue.TenantId == 0)
|
||||
entityInfo.SetValue(userManager.Value.TenantId?.ToString() ?? SqlSugarConst.DefaultTenantId.ToString());
|
||||
entityInfo.SetValue(userManager.Value.TenantId?.ToString() ??
|
||||
SqlSugarConst.DefaultTenantId.ToString());
|
||||
}
|
||||
else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
|
||||
{
|
||||
@ -340,17 +345,23 @@ public static class SqlSugarSetup
|
||||
// 操作前记录(字段描述、列名、值、表名、表描述)
|
||||
BeforeData = JSON.Serialize(u.BeforeData),
|
||||
// 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
|
||||
BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
|
||||
BusinessData = u.BusinessData == null
|
||||
? u.AfterData.FirstOrDefault()?.TableName
|
||||
: JSON.Serialize(u.BusinessData),
|
||||
// 枚举(insert、update、delete)
|
||||
DiffType = u.DiffType.ToString().ToUpper(),
|
||||
Sql = u.Sql,
|
||||
Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
|
||||
Parameters = JSON.Serialize(u.Parameters.Select(e => new
|
||||
{ e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
|
||||
Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
|
||||
};
|
||||
var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
|
||||
var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
|
||||
? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
|
||||
: ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
|
||||
await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
|
||||
Console.WriteLine(DateTime.Now +
|
||||
$"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
|
||||
};
|
||||
}
|
||||
|
||||
@ -385,10 +396,11 @@ public static class SqlSugarSetup
|
||||
// 由于修改定时任务后数据库无法更新,暂时先清空内置的定时任务数据
|
||||
if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId)
|
||||
{
|
||||
var jobIds = dbProvider.Queryable<SysJobDetail>().Where(u => u.CreateType == JobCreateTypeEnum.BuiltIn).Select(u => u.JobId).ToList();
|
||||
var jobIds = dbProvider.Queryable<SysJobDetail>().Where(u => u.CreateType == JobCreateTypeEnum.BuiltIn)
|
||||
.Select(u => u.JobId).ToList();
|
||||
dbProvider.Deleteable<SysJobDetail>().Where(u => jobIds.Contains(u.JobId)).ExecuteCommand();
|
||||
dbProvider.Deleteable<SysJobTrigger>().Where(u => jobIds.Contains(u.JobId)).ExecuteCommandAsync();
|
||||
dbProvider.Deleteable<SysJobTriggerRecord>().Where(u => jobIds.Contains(u.JobId)).ExecuteCommandAsync();
|
||||
dbProvider.Deleteable<SysJobTrigger>().Where(u => jobIds.Contains(u.JobId)).ExecuteCommand();
|
||||
dbProvider.Deleteable<SysJobTriggerRecord>().Where(u => jobIds.Contains(u.JobId)).ExecuteCommand();
|
||||
}
|
||||
}
|
||||
|
||||
@ -398,33 +410,44 @@ public static class SqlSugarSetup
|
||||
/// <param name="dbProvider"></param>
|
||||
/// <param name="enableIncreTable"></param>
|
||||
/// <param name="entityNames"></param>
|
||||
public static void InitTable(SqlSugarScopeProvider dbProvider, bool enableIncreTable, List<string> entityNames = null)
|
||||
public static void InitTable(SqlSugarScopeProvider dbProvider, bool enableIncreTable,
|
||||
List<string> entityNames = null)
|
||||
{
|
||||
var config = dbProvider.CurrentConnectionConfig;
|
||||
|
||||
var totalWatch = Stopwatch.StartNew(); // 开始总计时
|
||||
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())
|
||||
.WhereIF(enableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false)).ToList();
|
||||
|
||||
if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId) // 默认库(有系统表特性、没有日志表和租户表特性)
|
||||
entityTypes = entityTypes.Where(u => u.GetCustomAttributes<SysTableAttribute>().Any() || (!u.GetCustomAttributes<LogTableAttribute>().Any() && !u.GetCustomAttributes<TenantAttribute>().Any())).ToList();
|
||||
entityTypes = entityTypes.Where(u =>
|
||||
u.GetCustomAttributes<SysTableAttribute>().Any() ||
|
||||
(!u.GetCustomAttributes<LogTableAttribute>().Any() &&
|
||||
!u.GetCustomAttributes<TenantAttribute>().Any()))
|
||||
.ToList();
|
||||
else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
|
||||
entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
|
||||
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(); // 自定义的库
|
||||
|
||||
// 过滤指定实体
|
||||
if (entityNames is { Count: > 0 })
|
||||
entityTypes = entityTypes.Where(u => entityNames.Contains(u.Name)).ToList();
|
||||
|
||||
// 删除视图再初始化表结构,防止因为视图导致无法同步表结构
|
||||
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();
|
||||
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)))
|
||||
if (dbProvider.DbMaintenance.GetViewInfoList(false)
|
||||
.Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
|
||||
dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
|
||||
}
|
||||
|
||||
@ -436,7 +459,8 @@ public static class SqlSugarSetup
|
||||
stopWatch.Stop(); // 停止计时
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
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());
|
||||
|
||||
@ -451,7 +475,8 @@ public static class SqlSugarSetup
|
||||
/// <param name="dbProvider"></param>
|
||||
/// <param name="enableIncreSeed"></param>
|
||||
/// <param name="seedTypes"></param>
|
||||
public static void InitSeedData(SqlSugarScopeProvider dbProvider, bool enableIncreSeed, List<SeedType> seedTypes = null)
|
||||
public static void InitSeedData(SqlSugarScopeProvider dbProvider, bool enableIncreSeed,
|
||||
List<SeedType> seedTypes = null)
|
||||
{
|
||||
var config = dbProvider.CurrentConnectionConfig;
|
||||
|
||||
@ -466,9 +491,11 @@ public static class SqlSugarSetup
|
||||
var tmpSeedTypes = new List<Type>();
|
||||
foreach (var seedType in seedTypes)
|
||||
{
|
||||
var tmpSeedType = seedDataTypes.FirstOrDefault(u => u.Name == seedType.Name && u.Assembly.ManifestModule.Name == seedType.AssemblyName);
|
||||
var tmpSeedType = seedDataTypes.FirstOrDefault(u =>
|
||||
u.Name == seedType.Name && u.Assembly.ManifestModule.Name == seedType.AssemblyName);
|
||||
if (tmpSeedType != null) tmpSeedTypes.Add(tmpSeedType);
|
||||
}
|
||||
|
||||
if (tmpSeedTypes.Count > 0)
|
||||
seedDataTypes = tmpSeedTypes;
|
||||
}
|
||||
@ -486,7 +513,8 @@ public static class SqlSugarSetup
|
||||
stopWatch.Stop(); // 停止计时
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine($"初始化种子数据 {seedType.FullName,-58} ({config.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} ({config.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(); // 停止总计时
|
||||
@ -504,7 +532,9 @@ public static class SqlSugarSetup
|
||||
|
||||
var totalWatch = Stopwatch.StartNew(); // 开始总计时
|
||||
Log.Information($"初始化视图 {config.DbType} - {config.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();
|
||||
|
||||
int taskIndex = 0, size = viewTypeList.Count;
|
||||
var taskList = viewTypeList.Select(viewType => Task.Run(() =>
|
||||
@ -516,17 +546,20 @@ public static class SqlSugarSetup
|
||||
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(false)
|
||||
.Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
|
||||
dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
|
||||
|
||||
// 获取初始化视图查询SQL
|
||||
var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
|
||||
var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))
|
||||
?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
|
||||
if (string.IsNullOrWhiteSpace(sql)) throw new Exception("视图初始化Sql语句不能为空");
|
||||
|
||||
try
|
||||
{
|
||||
// 创建视图
|
||||
dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " + sql);
|
||||
dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " +
|
||||
sql);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -537,7 +570,8 @@ public static class SqlSugarSetup
|
||||
// 停止计时
|
||||
stopWatch.Stop();
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({config.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
|
||||
Console.WriteLine(
|
||||
$"初始化视图 {viewType.FullName,-58} ({config.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
|
||||
}));
|
||||
Task.WaitAll(taskList.ToArray());
|
||||
|
||||
@ -564,7 +598,9 @@ public static class SqlSugarSetup
|
||||
var entityTypes = App.EffectiveTypes
|
||||
.Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
|
||||
.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
|
||||
!u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
|
||||
!u.IsDefined(typeof(SysTableAttribute), false) &&
|
||||
!u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false))
|
||||
.ToList();
|
||||
if (entityTypes.Count == 0) return;
|
||||
|
||||
foreach (var entityType in entityTypes)
|
||||
@ -610,6 +646,7 @@ public static class SqlSugarSetup
|
||||
sd.GetType().GetProperty(nameof(EntityTenantId.TenantId))!.SetValue(sd, tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
// 若实体包含Pid字段,则设置为当前租户Id
|
||||
if (entityInfo.Columns.Any(u => u.PropertyName == nameof(SysOrg.Pid)))
|
||||
{
|
||||
@ -618,6 +655,7 @@ public static class SqlSugarSetup
|
||||
sd.GetType().GetProperty(nameof(SysOrg.Pid))!.SetValue(sd, tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
// 若实体包含Id字段,则设置为当前租户Id递增1
|
||||
if (entityInfo.Columns.Any(u => u.PropertyName == nameof(EntityBaseId.Id)))
|
||||
{
|
||||
@ -640,7 +678,10 @@ public static class SqlSugarSetup
|
||||
var storage = db.StorageableByObject(seedData).ToStorage();
|
||||
storage.AsInsertable.ExecuteCommand();
|
||||
if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null) // 有忽略更新种子特性时则不更新
|
||||
storage.AsUpdateable.IgnoreColumns(entityInfo.Columns.Where(c => c.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null).Select(c => c.PropertyName).ToArray()).ExecuteCommand();
|
||||
storage.AsUpdateable
|
||||
.IgnoreColumns(entityInfo.Columns
|
||||
.Where(c => c.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
|
||||
.Select(c => c.PropertyName).ToArray()).ExecuteCommand();
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Loading…
Reference in New Issue
Block a user