namespace Admin.NET.Core;
public static class SqlSugarSetup
{
///
/// Sqlsugar 上下文初始化
///
///
public static void AddSqlSugar(this IServiceCollection services)
{
var dbOptions = App.GetOptions();
dbOptions.ConnectionConfigs.ForEach(config =>
{
SetDbConfig(config);
});
SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt>(), db =>
{
dbOptions.ConnectionConfigs.ForEach(config =>
{
var dbProvider = db.GetConnectionScope(config.ConfigId);
SetDbAop(dbProvider);
SetDbDiffLog(dbProvider, config);
});
});
// 初始化数据库表结构及种子数据
dbOptions.ConnectionConfigs.ForEach(config =>
{
InitDatabase(sqlSugar, config);
});
services.AddSingleton(sqlSugar); // 单例注册
services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
services.AddUnitOfWork(); // 事务与工作单元注册
}
///
/// 配置连接属性
///
///
public static void SetDbConfig(DbConnectionConfig config)
{
if (string.IsNullOrWhiteSpace(config.ConfigId))
config.ConfigId = SqlSugarConst.ConfigId;
var configureExternalServices = new ConfigureExternalServices
{
EntityNameService = (type, entity) => // 处理表
{
if (config.EnableUnderLine && !entity.DbTableName.Contains('_'))
entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); // 驼峰转下划线
},
EntityService = (type, column) => // 处理列
{
if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
column.IsNullable = true;
if (config.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); // 驼峰转下划线
},
DataInfoCacheService = new SqlSugarCache(),
};
config.ConfigureExternalServices = configureExternalServices;
config.InitKeyType = InitKeyType.Attribute;
config.IsAutoCloseConnection = true;
config.MoreSettings = new ConnMoreSettings
{
IsAutoRemoveDataCache = true
};
// PostgreSQL库-时间异常
if (config.DbType == SqlSugar.DbType.PostgreSQL)
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
}
///
/// 配置Aop
///
///
public static void SetDbAop(SqlSugarScopeProvider db)
{
var config = db.CurrentConnectionConfig;
// 设置超时时间
db.Ado.CommandTimeOut = 30;
// 打印SQL语句
db.Aop.OnLogExecuting = (sql, pars) =>
{
if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
Console.ForegroundColor = ConsoleColor.Green;
if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
Console.ForegroundColor = ConsoleColor.White;
if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
db.Aop.OnError = (ex) =>
{
if (ex.Parametres == null) return;
Console.ForegroundColor = ConsoleColor.Red;
var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
};
// 数据审计
db.Aop.DataExecuting = (oldValue, entityInfo) =>
{
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
// 主键(long类型)且没有值的---赋值雪花Id
if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
if (id == null || (long)id == 0)
entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
}
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
if (App.User != null)
{
if (entityInfo.PropertyName == "TenantId")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
}
if (entityInfo.PropertyName == "CreateUserId")
entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
if (entityInfo.PropertyName == "CreateOrgId")
entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
}
}
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateUserId")
entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
}
};
// 超管时排除各种过滤器
if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
return;
// 配置实体假删除过滤器
SetDeletedEntityFilter(db);
// 配置租户过滤器
SetTenantEntityFilter(db);
// 配置用户机构范围过滤器
SetOrgEntityFilter(db);
// 配置自定义过滤器
SetCustomEntityFilter(db);
}
///
/// 开启库表差异化日志
///
///
///
private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
{
if (!config.EnableDiffLog) return;
db.Aop.OnDiffLogEvent = async u =>
{
var logDiff = new SysLogDiff
{
// 操作后记录(字段描述、列名、值、表名、表描述)
AfterData = JsonConvert.SerializeObject(u.AfterData),
// 操作前记录(字段描述、列名、值、表名、表描述)
BeforeData = JsonConvert.SerializeObject(u.BeforeData),
// 传进来的对象
BusinessData = JsonConvert.SerializeObject(u.BusinessData),
// 枚举(insert、update、delete)
DiffType = u.DiffType.ToString(),
Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
Parameters = JsonConvert.SerializeObject(u.Parameters),
Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
};
await db.Insertable(logDiff).ExecuteCommandAsync();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(DateTime.Now + $"\r\n*****差异日志开始*****\r\n{Environment.NewLine}{JsonConvert.SerializeObject(logDiff)}{Environment.NewLine}*****差异日志结束*****\r\n");
};
}
///
/// 初始化数据库
///
///
///
public static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
{
if (!config.EnableInitDb) return;
var dbProvider = db.GetConnectionScope(config.ConfigId);
// 创建数据库
if (config.DbType != SqlSugar.DbType.Oracle)
dbProvider.DbMaintenance.CreateDatabase();
// 获取所有实体表-初始化表结构
var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
&& u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
if (!entityTypes.Any()) return;
foreach (var entityType in entityTypes)
{
var tAtt = entityType.GetCustomAttribute();
if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId) continue;
var splitTable = entityType.GetCustomAttribute();
if (splitTable == null)
dbProvider.CodeFirst.InitTables(entityType);
else
dbProvider.CodeFirst.SplitTables().InitTables(entityType);
}
// 获取所有种子配置-初始化数据
var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
&& u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
if (!seedDataTypes.Any()) return;
foreach (var seedType in seedDataTypes)
{
var instance = Activator.CreateInstance(seedType);
var hasDataMethod = seedType.GetMethod("HasData");
var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast