Files
shgx_tz_mes_backend_sync/ZR.Admin.WebApi/Extensions/DbExtension.cs

214 lines
8.7 KiB
C#
Raw Normal View History

2023-06-07 22:28:06 +08:00
using Infrastructure.Extensions;
2021-12-26 18:26:38 +08:00
using SqlSugar;
using SqlSugar.IOC;
2023-06-07 22:28:06 +08:00
using ZR.Model;
2021-12-26 18:26:38 +08:00
using ZR.Model.System;
namespace ZR.Admin.WebApi.Extensions
{
/// <summary>
/// sqlsugar 数据处理
/// </summary>
2021-12-26 18:26:38 +08:00
public static class DbExtension
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 初始化db
/// </summary>
2023-06-07 22:28:06 +08:00
/// <param name="services"></param>
/// <param name="Configuration"></param>
2023-06-09 18:10:38 +08:00
/// <param name="environment"></param>
public static void AddDb(this IServiceCollection services, IConfiguration Configuration, IWebHostEnvironment environment)
2021-12-26 18:26:38 +08:00
{
List<DbConfigs> dbConfigs = Configuration.GetSection("DbConfigs").Get<List<DbConfigs>>();
var iocList = new List<IocConfig>();
2023-06-23 16:36:00 +08:00
foreach (var item in dbConfigs)
{
iocList.Add(new IocConfig()
{
ConfigId = item.ConfigId,
ConnectionString = item.Conn,
DbType = (IocDbType)item.DbType,
IsAutoCloseConnection = item.IsAutoCloseConnection
});
}
2022-12-16 16:08:39 +08:00
SugarIocServices.AddSqlSugar(iocList);
2023-02-15 22:13:01 +08:00
ICacheService cache = new SqlSugarCache();
2022-03-16 21:58:37 +08:00
SugarIocServices.ConfigurationSugar(db =>
2021-12-26 18:26:38 +08:00
{
var u = App.User;
if (u != null)
{
2023-06-29 08:25:49 +08:00
DataPermi.FilterData(0);
//ConfigId = 1的数据权限过滤
2023-06-29 08:25:49 +08:00
//DataPermi.FilterData1(1);
}
2022-10-25 08:12:15 +08:00
2022-12-16 16:08:39 +08:00
iocList.ForEach(iocConfig =>
2022-03-16 21:58:37 +08:00
{
2023-03-05 16:58:32 +08:00
SetSugarAop(db, iocConfig, cache);
2022-12-16 16:08:39 +08:00
});
2022-03-16 21:58:37 +08:00
});
2023-06-09 18:10:38 +08:00
if (Configuration["InitDb"].ParseToBool() == true && environment.IsDevelopment())
2023-06-09 18:10:38 +08:00
{
InitTable.InitDb();
2023-06-09 18:10:38 +08:00
}
2022-12-16 16:08:39 +08:00
}
2022-10-25 08:12:15 +08:00
/// <summary>
/// 数据库Aop设置
/// </summary>
/// <param name="db"></param>
/// <param name="iocConfig"></param>
/// <param name="cache"></param>
2023-03-05 16:58:32 +08:00
private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache)
2022-12-16 16:08:39 +08:00
{
2023-06-09 18:10:38 +08:00
var config = db.GetConnectionScope(iocConfig.ConfigId).CurrentConnectionConfig;
2023-08-14 18:11:03 +08:00
var showDbLog = AppSettings.Get<bool>("ShowDbLog");
2022-12-16 16:08:39 +08:00
string configId = config.ConfigId;
2023-05-12 15:10:45 +08:00
db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) =>
2022-12-16 16:08:39 +08:00
{
2023-08-14 18:11:03 +08:00
if (showDbLog)
2023-04-14 08:46:59 +08:00
{
2023-08-14 18:11:03 +08:00
string log = $"【db{configId} SQL语句】{UtilMethods.GetSqlString(config.DbType, sql, pars)}\n";
if (sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
{
logger.Info(log);
}
else if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
{
logger.Warn(log);
}
else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase))
{
logger.Error(log);
}
else
{
log = $"【db{configId} SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n";
logger.Info(log);
}
2023-04-14 08:46:59 +08:00
}
2022-12-16 16:08:39 +08:00
};
2023-05-12 15:10:45 +08:00
db.GetConnectionScope(configId).Aop.OnError = (ex) =>
2022-12-16 16:08:39 +08:00
{
//var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
2023-05-12 15:10:45 +08:00
string sql = "【错误SQL】" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n";
logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
2022-12-16 16:08:39 +08:00
};
2023-06-09 18:10:38 +08:00
db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) =>
{
};
//差异日志功能
db.GetConnectionScope(configId).Aop.OnDiffLogEvent = it =>
{
//操作前记录 包含: 字段描述 列名 值 表名 表描述
var editBeforeData = it.BeforeData;//插入Before为null之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述
var editAfterData = it.AfterData;
var sql = it.Sql;
var parameter = it.Parameters;
var data = it.BusinessData;//这边会显示你传进来的对象
var time = it.Time;
var diffType = it.DiffType;//enum insert 、update and delete
if (diffType == DiffType.delete)
{
string name = App.UserName;
foreach (var item in editBeforeData)
{
var pars = db.Utilities.SerializeObject(item.Columns.ToDictionary(it => it.ColumnName, it => it.Value));
SqlDiffLog log = new()
{
2023-07-21 18:17:58 +08:00
BeforeData = pars,
2023-08-02 12:25:36 +08:00
BusinessData = data?.ToString(),
DiffType = diffType.ToString(),
Sql = sql,
TableName = item.TableName,
UserName = name,
2023-07-21 18:17:58 +08:00
AddTime = DateTime.Now,
ConfigId = configId
};
//logger.WithProperty("title", data).Info(pars);
2023-07-21 18:17:58 +08:00
db.GetConnectionScope(0).Insertable(log).ExecuteReturnSnowflakeId();
}
}
};
2023-03-05 16:58:32 +08:00
db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
};
db.GetConnectionScope(configId).CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
{
2023-05-12 15:10:45 +08:00
DataInfoCacheService = cache,
EntityService = (c, p) =>
{
2023-06-07 22:28:06 +08:00
if (p.IsPrimarykey == true)//主键不能为null
{
p.IsNullable = false;
}
else if (p.ExtendedAttribute?.ToString() == ProteryConstant.NOTNULL.ToString())
{
p.IsNullable = false;
}
else//则否默认为null
{
p.IsNullable = true;
2023-05-12 15:10:45 +08:00
}
if (config.DbType == DbType.PostgreSQL)
{
if (c.Name == nameof(SysMenu.IsCache) || c.Name == nameof(SysMenu.IsFrame))
{
p.DataType = "char(1)";
}
}
#region Oracle
if (config.DbType == DbType.Oracle)
{
if (p.IsIdentity == true)
{
if (p.EntityName == nameof(SysUser))
{
p.OracleSequenceName = "SEQ_SYS_USER_USERID";
}
else if (p.EntityName == nameof(SysRole))
{
p.OracleSequenceName = "SEQ_SYS_ROLE_ROLEID";
}
else if (p.EntityName == nameof(SysDept))
{
p.OracleSequenceName = "SEQ_SYS_DEPT_DEPTID";
}
else if (p.EntityName == nameof(SysMenu))
{
p.OracleSequenceName = "SEQ_SYS_MENU_MENUID";
}
else
{
p.OracleSequenceName = "SEQ_ID";
}
}
}
#endregion
2023-05-12 15:10:45 +08:00
}
2023-03-05 16:58:32 +08:00
};
}
2023-04-14 08:46:59 +08:00
private static object GetParsValue(SugarParameter x)
{
if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String)
{
return "'" + x.Value + "'";
}
return x.Value;
}
2021-12-26 18:26:38 +08:00
}
}