You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

406 lines
17 KiB
C#

using DS.Module.Core.Data;
11 months ago
using DS.Module.UserModule;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using NLog;
4 months ago
using DS.Module.Core.Log;
using Newtonsoft.Json;
4 months ago
using DS.Module.Core.Extensions;
using Amazon.Runtime.Internal.Util;
using Logger = NLog.Logger;
using DS.Module.Core;
11 months ago
11 months ago
namespace DS.Module.SqlSugar;
/// <summary>
/// saas数据库服务
/// </summary>
11 months ago
public class SaasDbService : ISaasDbService
11 months ago
{
private readonly IServiceProvider _serviceProvider;
private readonly SqlSugarScope db;
private readonly IUser user;
10 months ago
private readonly ISaasDbService saasService;
11 months ago
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="serviceProvider"></param>
public SaasDbService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
11 months ago
db = (SqlSugarScope)_serviceProvider.GetRequiredService<ISqlSugarClient>();
11 months ago
user = _serviceProvider.GetRequiredService<IUser>();
}
/// <summary>
/// 根据用户租户Id获取业务库
/// </summary>
/// <returns></returns>
public ISqlSugarClient GetBizDb()
{
var tenantId = user.TenantId;
11 months ago
if (!db.IsAnyConnection(tenantId))
11 months ago
{
var connInfo = GetMasterDb().Queryable<SysTenantLink>().First(x => x.TenantId == long.Parse(tenantId));
//用非默认ConfigId进行测试
//添加业务库只在当前上下文有效原理SqlSugarScope模式入门文档去看
11 months ago
db.AddConnection(new ConnectionConfig()
{
ConfigId = tenantId,
ConnectionString = connInfo.Connection,
11 months ago
DbType = connInfo.DbType,
11 months ago
IsAutoCloseConnection = true
});
11 months ago
}
return db.GetConnection(tenantId);
}
/// <summary>
/// 获取主库信息
/// </summary>
/// <returns></returns>
public ISqlSugarClient GetMasterDb()
{
return db.GetConnection("1288018625843826688");
}
11 months ago
/// <summary>
/// 获取日志库信息
/// </summary>
/// <returns></returns>
public SqlSugarScopeProvider GetLogDb()
{
return db.GetConnectionScope("1288018625843826680");
}
11 months ago
/// <summary>
/// 主库根据Id获取业务库Scope
/// </summary>
/// <param name="configId"></param>
/// <returns></returns>
public SqlSugarScopeProvider GetBizDbScopeById(object configId)
{
if (!db.IsAnyConnection(configId))
{
var connInfo = GetMasterDb().Queryable<SysTenantLink>().First(x => x.TenantId == Convert.ToInt64(configId));
//用非默认ConfigId进行测试
//添加业务库只在当前上下文有效原理SqlSugarScope模式入门文档去看
ICacheService myCache = new SqlSugarCsRedisCache(_serviceProvider);
db.AddConnection(new ConnectionConfig()
{
ConfigId = configId,
ConnectionString = connInfo.Connection,
DbType = connInfo.DbType,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = myCache //配置我们创建的缓存类具体用法看标题5
},
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
}
});
var dbProvider = db.GetConnectionScope(configId);
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
//执行前事件
//Logger.Log(LogLevel.Info,
// DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars));
string sqlStr = sql;
foreach (var item in pars)
{
if (item.Value != null && item.Value != DBNull.Value)
{
string? strValue = string.Empty;
if (item.DbType == System.Data.DbType.String)
{
strValue = "'" + (string)item.Value + "'";
}
else if (item.DbType == System.Data.DbType.Boolean)
{
strValue = (bool)item.Value ? "1" : "0";
}
else
{
strValue = item.Value.ToString();
}
sqlStr = sqlStr.Replace(item.ParameterName, strValue);
}
}
Console.WriteLine("执行的SQL" + Environment.NewLine + sqlStr);
};
//数据处理事件
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
SqlsugarHelper.InsertByObjectForSqlsugar(entityInfo, user);
// 更新操作
SqlsugarHelper.UpdateByObjectForSqlsugar(entityInfo, user);
};
4 months ago
dbProvider.Aop.OnDiffLogEvent = it =>
{
//排除日志库操作
if (Convert.ToInt64(configId) != 1288018625843826680)
{
#region 插入日志审计表
//操作前记录 包含: 字段描述 列名 值 表名 表描述
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
var diffData = SqlSugarDiffUtil.GetDiff(editBeforeData, editAfterData);
4 months ago
if (diffData.IsNotNull())
4 months ago
{
4 months ago
var auditData = new SysLogAudit()
{
KeyId = Convert.ToInt64(diffData.Id),
Sql = it.Sql,
Param = JsonConvert.SerializeObject(it.Parameters),
OperateType = diffType.ToString(),
OldValue = JsonConvert.SerializeObject(editBeforeData),
NewValue = JsonConvert.SerializeObject(editAfterData),
DiffData = diffData.DiffData,
AopData = JsonConvert.SerializeObject(it.BusinessData),
};
db.GetConnection(1288018625843826680).Insertable(auditData).ExecuteCommand();
}
4 months ago
#endregion
}
};
//var templist = dbProvider.QueryFilter.GeFilterList;
//Console.WriteLine("当前过滤器:"+ JsonConvert.SerializeObject(templist));
//全局过滤租户Id
dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId ==long.Parse(user.TenantId));
//全局过滤机构Id
dbProvider.QueryFilter.AddTableFilter<IOrgId>(m => m.OrgId == user.OrgId);
//全局过滤共享机构Id
dbProvider.QueryFilter.AddTableFilter<ISharedOrgId>(x => x.OrgId == user.OrgId || x.IsShared);
//全局软删除过滤
dbProvider.QueryFilter.AddTableFilter<IDeleted>(m => m.Deleted == false);
}
11 months ago
return db.GetConnectionScope(configId);
}
public SqlSugarScopeProvider GetBizJobDbScopeById(JobDbInitConfig conf)
{
if (!db.IsAnyConnection(conf.TenantId))
{
var connInfo = GetMasterDb().Queryable<SysTenantLink>().First(x => x.TenantId == conf.TenantId);
//用非默认ConfigId进行测试
//添加业务库只在当前上下文有效原理SqlSugarScope模式入门文档去看
ICacheService myCache = new SqlSugarCsRedisCache(_serviceProvider);
db.AddConnection(new ConnectionConfig()
{
ConfigId = conf.TenantId,
ConnectionString = connInfo.Connection,
DbType = connInfo.DbType,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = myCache //配置我们创建的缓存类具体用法看标题5
},
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
}
});
var dbProvider = db.GetConnectionScope(conf.TenantId);
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
//执行前事件
//Logger.Log(LogLevel.Info,
// DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars));
string sqlStr = sql;
foreach (var item in pars)
{
if (item.Value != null && item.Value != DBNull.Value)
{
string? strValue = string.Empty;
if (item.DbType == System.Data.DbType.String)
{
strValue = "'" + (string)item.Value + "'";
}
else if (item.DbType == System.Data.DbType.Boolean)
{
strValue = (bool)item.Value ? "1" : "0";
}
else
{
strValue = item.Value.ToString();
}
sqlStr = sqlStr.Replace(item.ParameterName, strValue);
}
}
Console.WriteLine("执行的SQL" + Environment.NewLine + sqlStr);
};
//数据处理事件
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
if (entityInfo.PropertyName == "Id")
{
if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
{
entityInfo.SetValue(GuidHelper.GetSnowflakeId());
}
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(SnowFlakeSingle.Instance.NextId());
}
}
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "TenantId")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(conf.TenantId);
}
if (entityInfo.PropertyName == "TenantName")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(conf.TenantName);
}
if (entityInfo.PropertyName == "OrgId")
{
var orgId = ((dynamic)entityInfo.EntityValue).OrgId;
if (orgId == null || orgId == 0)
entityInfo.SetValue(conf.OrgId);
}
if (entityInfo.PropertyName == "CreateBy")
{
if (!user.UserId.IsNullOrEmpty())
{
entityInfo.SetValue(conf.UserId);
}
else
{
entityInfo.SetValue(1288018625843826688);
}
}
if (entityInfo.PropertyName == "CreateUserName")
{
if (!user.UserId.IsNullOrEmpty())
{
entityInfo.SetValue(conf.UserName);
}
else
{
entityInfo.SetValue("超级管理员");
}
}
if (entityInfo.PropertyName == "Deleted")
entityInfo.SetValue(false);
}
// 更新操作
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateBy" && user != null)
entityInfo.SetValue(conf.UserId);
if (entityInfo.PropertyName == "UpdateUserName" && user != null)
entityInfo.SetValue(conf.UserName);
}
};
dbProvider.Aop.OnDiffLogEvent = it =>
{
//排除日志库操作
if (Convert.ToInt64(conf.TenantId) != 1288018625843826680)
{
#region 插入日志审计表
//操作前记录 包含: 字段描述 列名 值 表名 表描述
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
var diffData = SqlSugarDiffUtil.GetDiff(editBeforeData, editAfterData);
if (diffData.IsNotNull())
{
var auditData = new SysLogAudit()
{
KeyId = Convert.ToInt64(diffData.Id),
Sql = it.Sql,
Param = JsonConvert.SerializeObject(it.Parameters),
OperateType = diffType.ToString(),
OldValue = JsonConvert.SerializeObject(editBeforeData),
NewValue = JsonConvert.SerializeObject(editAfterData),
DiffData = diffData.DiffData,
AopData = JsonConvert.SerializeObject(it.BusinessData),
};
db.GetConnection(1288018625843826680).Insertable(auditData).ExecuteCommand();
}
#endregion
}
};
//var templist = dbProvider.QueryFilter.GeFilterList;
//Console.WriteLine("当前过滤器:"+ JsonConvert.SerializeObject(templist));
//全局过滤租户Id
dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == conf.TenantId);
//全局过滤机构Id
dbProvider.QueryFilter.AddTableFilter<IOrgId>(m => m.OrgId == conf.OrgId);
//全局过滤共享机构Id
dbProvider.QueryFilter.AddTableFilter<ISharedOrgId>(x => x.OrgId == conf.OrgId || x.IsShared);
//全局软删除过滤
dbProvider.QueryFilter.AddTableFilter<IDeleted>(m => m.Deleted == false);
}
return db.GetConnectionScope(conf.TenantId);
}
11 months ago
public SqlSugarScopeProvider GetMasterDbScope()
{
return db.GetConnectionScope("1288018625843826688");
}
11 months ago
}