:recycle:代码重构
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
using Infrastructure;
|
||||
using SqlSugar.IOC;
|
||||
using ZR.Model.System;
|
||||
|
||||
namespace ZR.ServiceCore.SqlSugar
|
||||
{
|
||||
public enum DataPermiEnum
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>
|
||||
/// 全部数据权限
|
||||
/// </summary>
|
||||
All = 1,
|
||||
/// <summary>
|
||||
/// 仅本人数据权限
|
||||
/// </summary>
|
||||
SELF = 5,
|
||||
/// <summary>
|
||||
/// 部门数据权限
|
||||
/// </summary>
|
||||
DEPT = 3,
|
||||
/// <summary>
|
||||
/// 自定数据权限
|
||||
/// </summary>
|
||||
CUSTOM = 2,
|
||||
/// <summary>
|
||||
/// 部门及以下数据权限
|
||||
/// </summary>
|
||||
DEPT_CHILD = 4
|
||||
}
|
||||
/// <summary>
|
||||
/// 数据权限
|
||||
/// </summary>
|
||||
public class DataPermi
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据过滤
|
||||
/// </summary>
|
||||
/// <param name="configId">多库id</param>
|
||||
public static void FilterData(int configId)
|
||||
{
|
||||
//获取当前用户的信息
|
||||
var user = JwtUtil.GetLoginUser(App.HttpContext);
|
||||
if (user == null) return;
|
||||
//管理员不过滤
|
||||
if (user.RoleIds.Any(f => f.Equals(GlobalConstant.AdminRole))) return;
|
||||
var db = DbScoped.SugarScope.GetConnectionScope(configId);
|
||||
var expUser = Expressionable.Create<SysUser>();
|
||||
var expRole = Expressionable.Create<SysRole>();
|
||||
var expLoginlog = Expressionable.Create<SysLogininfor>();
|
||||
|
||||
foreach (var role in user.Roles.OrderBy(f => f.DataScope))
|
||||
{
|
||||
var dataScope = (DataPermiEnum)role.DataScope;
|
||||
if (DataPermiEnum.All.Equals(dataScope))//所有权限
|
||||
{
|
||||
break;
|
||||
}
|
||||
else if (DataPermiEnum.CUSTOM.Equals(dataScope))//自定数据权限
|
||||
{
|
||||
//" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
|
||||
|
||||
expUser.Or(it => SqlFunc.Subqueryable<SysRoleDept>().Where(f => f.DeptId == it.DeptId && f.RoleId == role.RoleId).Any());
|
||||
}
|
||||
else if (DataPermiEnum.DEPT.Equals(dataScope))//本部门数据
|
||||
{
|
||||
expUser.Or(it => it.DeptId == user.DeptId);
|
||||
}
|
||||
else if (DataPermiEnum.DEPT_CHILD.Equals(dataScope))//本部门及以下数据
|
||||
{
|
||||
//SQl OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )
|
||||
var allChildDepts = db.Queryable<SysDept>().ToChildList(it => it.ParentId, user.DeptId);
|
||||
|
||||
expUser.Or(it => allChildDepts.Select(f => f.DeptId).ToList().Contains(it.DeptId));
|
||||
}
|
||||
else if (DataPermiEnum.SELF.Equals(dataScope))//仅本人数据
|
||||
{
|
||||
expUser.Or(it => it.UserId == user.UserId);
|
||||
expRole.Or(it => user.RoleIds.Contains(it.RoleKey));
|
||||
expLoginlog.And(it => it.UserName == user.UserName);
|
||||
}
|
||||
}
|
||||
|
||||
db.QueryFilter.AddTableFilter(expUser.ToExpression());
|
||||
db.QueryFilter.AddTableFilter(expRole.ToExpression());
|
||||
db.QueryFilter.AddTableFilter(expLoginlog.ToExpression());
|
||||
}
|
||||
|
||||
public static void FilterData1(int configId)
|
||||
{
|
||||
//获取当前用户的信息
|
||||
var user = JwtUtil.GetLoginUser(App.HttpContext);
|
||||
if (user == null) return;
|
||||
var db = DbScoped.SugarScope.GetConnectionScope(configId);
|
||||
|
||||
foreach (var role in user.Roles.OrderBy(f => f.DataScope))
|
||||
{
|
||||
var dataScope = (DataPermiEnum)role.DataScope;
|
||||
if (DataPermiEnum.All.Equals(dataScope))//所有权限
|
||||
{
|
||||
break;
|
||||
}
|
||||
else if (DataPermiEnum.CUSTOM.Equals(dataScope))//自定数据权限
|
||||
{
|
||||
}
|
||||
else if (DataPermiEnum.DEPT.Equals(dataScope))//本部门数据
|
||||
{
|
||||
}
|
||||
else if (DataPermiEnum.DEPT_CHILD.Equals(dataScope))//本部门及以下数据
|
||||
{
|
||||
|
||||
}
|
||||
else if (DataPermiEnum.SELF.Equals(dataScope))//仅本人数据
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using SqlSugar.IOC;
|
||||
using ZR.Model.Models;
|
||||
using ZR.Model.System;
|
||||
using ZR.Model.System.Generate;
|
||||
|
||||
namespace ZR.ServiceCore.SqlSugar
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化表
|
||||
/// </summary>
|
||||
public class InitTable
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建db、表
|
||||
/// </summary>
|
||||
public static void InitDb()
|
||||
{
|
||||
var db = DbScoped.SugarScope;
|
||||
//建库:如果不存在创建数据库存在不会重复创建
|
||||
db.DbMaintenance.CreateDatabase();// 注意 :Oracle和个别国产库需不支持该方法,需要手动建库
|
||||
|
||||
//var baseType = typeof(SysBase);
|
||||
//var entityes = AssemblyUtils.GetAllTypes().Where(p => !p.IsAbstract && p != baseType && p.GetCustomAttribute<SugarTable>() != null).ToArray();
|
||||
//db.CodeFirst.InitTables(entityes);
|
||||
|
||||
//24个表,建议先使用下面方法初始化表,方便排查问题
|
||||
db.CodeFirst.InitTables(typeof(SysUser));
|
||||
db.CodeFirst.InitTables(typeof(SysRole));
|
||||
db.CodeFirst.InitTables(typeof(SysDept));
|
||||
db.CodeFirst.InitTables(typeof(SysPost));
|
||||
db.CodeFirst.InitTables(typeof(SysFile));
|
||||
db.CodeFirst.InitTables(typeof(SysConfig));
|
||||
db.CodeFirst.InitTables(typeof(SysNotice));
|
||||
db.CodeFirst.InitTables(typeof(SysLogininfor));
|
||||
db.CodeFirst.InitTables(typeof(SysOperLog));
|
||||
db.CodeFirst.InitTables(typeof(SysMenu));
|
||||
db.CodeFirst.InitTables(typeof(SysRoleMenu));
|
||||
db.CodeFirst.InitTables(typeof(SysRoleDept));
|
||||
db.CodeFirst.InitTables(typeof(SysUserRole));
|
||||
db.CodeFirst.InitTables(typeof(SysUserPost));
|
||||
db.CodeFirst.InitTables(typeof(SysTasks));
|
||||
db.CodeFirst.InitTables(typeof(SysTasksLog));
|
||||
db.CodeFirst.InitTables(typeof(CommonLang));
|
||||
db.CodeFirst.InitTables(typeof(GenTable));
|
||||
db.CodeFirst.InitTables(typeof(GenTableColumn));
|
||||
db.CodeFirst.InitTables(typeof(Article));
|
||||
db.CodeFirst.InitTables(typeof(ArticleCategory));
|
||||
db.CodeFirst.InitTables(typeof(SysDictData));
|
||||
db.CodeFirst.InitTables(typeof(SysDictType));
|
||||
db.CodeFirst.InitTables(typeof(SqlDiffLog));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using ZR.Common;
|
||||
|
||||
namespace ZR.ServiceCore.SqlSugar
|
||||
{
|
||||
public class SqlSugarCache : ICacheService
|
||||
{
|
||||
public void Add<V>(string key, V value)
|
||||
{
|
||||
//RedisServer.Cache.Set(key, value, 3600 + RedisHelper.RandomExpired(5, 30));
|
||||
CacheHelper.SetCache(key, value);
|
||||
}
|
||||
|
||||
public void Add<V>(string key, V value, int cacheDurationInSeconds)
|
||||
{
|
||||
//RedisServer.Cache.Set(key, value, cacheDurationInSeconds);
|
||||
CacheHelper.SetCaches(key, value, cacheDurationInSeconds);
|
||||
}
|
||||
|
||||
public bool ContainsKey<V>(string key)
|
||||
{
|
||||
//return RedisServer.Cache.Exists(key);
|
||||
return CacheHelper.Exists(key);
|
||||
}
|
||||
|
||||
public V Get<V>(string key)
|
||||
{
|
||||
//return RedisServer.Cache.Get<V>(key);
|
||||
return (V)CacheHelper.Get(key);
|
||||
}
|
||||
|
||||
public IEnumerable<string> GetAllKey<V>()
|
||||
{
|
||||
//return RedisServer.Cache.Keys("*");
|
||||
return CacheHelper.GetCacheKeys();
|
||||
}
|
||||
|
||||
public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
|
||||
{
|
||||
if (ContainsKey<V>(cacheKey))
|
||||
{
|
||||
var result = Get<V>(cacheKey);
|
||||
if (result == null)
|
||||
{
|
||||
return create();
|
||||
}
|
||||
else
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var restul = create();
|
||||
|
||||
Add(cacheKey, restul, cacheDurationInSeconds);
|
||||
return restul;
|
||||
}
|
||||
}
|
||||
|
||||
public void Remove<V>(string key)
|
||||
{
|
||||
//RedisServer.Cache.Del(key);
|
||||
CacheHelper.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
using Infrastructure;
|
||||
using Infrastructure.Model;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using SqlSugar.IOC;
|
||||
using ZR.Model.System;
|
||||
|
||||
namespace ZR.ServiceCore.SqlSugar
|
||||
{
|
||||
public static class SqlsugarSetup
|
||||
{
|
||||
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
/// <summary>
|
||||
/// 初始化db
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="environment"></param>
|
||||
public static void AddDb(this IServiceCollection services,IWebHostEnvironment environment)
|
||||
{
|
||||
var options = App.OptionsSetting;
|
||||
List<DbConfigs> dbConfigs = options.DbConfigs;
|
||||
|
||||
var iocList = new List<IocConfig>();
|
||||
foreach (var item in dbConfigs)
|
||||
{
|
||||
iocList.Add(new IocConfig()
|
||||
{
|
||||
ConfigId = item.ConfigId,
|
||||
ConnectionString = item.Conn,
|
||||
DbType = (IocDbType)item.DbType,
|
||||
IsAutoCloseConnection = item.IsAutoCloseConnection
|
||||
});
|
||||
}
|
||||
SugarIocServices.AddSqlSugar(iocList);
|
||||
ICacheService cache = new SqlSugarCache();
|
||||
SugarIocServices.ConfigurationSugar(db =>
|
||||
{
|
||||
var u = App.User;
|
||||
if (u != null)
|
||||
{
|
||||
DataPermi.FilterData(0);
|
||||
//ConfigId = 1的数据权限过滤
|
||||
//DataPermi.FilterData1(1);
|
||||
}
|
||||
|
||||
iocList.ForEach(iocConfig =>
|
||||
{
|
||||
SetSugarAop(db, iocConfig, cache);
|
||||
});
|
||||
});
|
||||
|
||||
if (options.InitDb && environment.IsDevelopment())
|
||||
{
|
||||
InitTable.InitDb();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库Aop设置
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
/// <param name="iocConfig"></param>
|
||||
/// <param name="cache"></param>
|
||||
private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache)
|
||||
{
|
||||
var config = db.GetConnectionScope(iocConfig.ConfigId).CurrentConnectionConfig;
|
||||
var showDbLog = AppSettings.Get<bool>("ShowDbLog");
|
||||
string configId = config.ConfigId;
|
||||
db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) =>
|
||||
{
|
||||
if (showDbLog)
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
db.GetConnectionScope(configId).Aop.OnError = (ex) =>
|
||||
{
|
||||
//var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
|
||||
|
||||
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}");
|
||||
};
|
||||
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
|
||||
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()
|
||||
{
|
||||
BeforeData = pars,
|
||||
BusinessData = data?.ToString(),
|
||||
DiffType = diffType.ToString(),
|
||||
Sql = sql,
|
||||
TableName = item.TableName,
|
||||
UserName = name,
|
||||
AddTime = DateTime.Now,
|
||||
ConfigId = configId
|
||||
};
|
||||
if (editAfterData != null)
|
||||
{
|
||||
var afterData = editAfterData?.First(x => x.TableName == item.TableName);
|
||||
var afterPars = db.Utilities.SerializeObject(afterData?.Columns.ToDictionary(it => it.ColumnName, it => it.Value));
|
||||
log.AfterData = afterPars;
|
||||
}
|
||||
//logger.WithProperty("title", data).Info(pars);
|
||||
db.GetConnectionScope(0)
|
||||
.Insertable(log)
|
||||
.ExecuteReturnSnowflakeId();
|
||||
}
|
||||
};
|
||||
db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
|
||||
{
|
||||
IsAutoRemoveDataCache = true
|
||||
};
|
||||
db.GetConnectionScope(configId).CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
|
||||
{
|
||||
DataInfoCacheService = cache,
|
||||
EntityService = (c, p) =>
|
||||
{
|
||||
if (p.IsPrimarykey == true)//主键不能为null
|
||||
{
|
||||
p.IsNullable = false;
|
||||
}
|
||||
else if (p.ExtendedAttribute?.ToString() == ProteryConstant.NOTNULL.ToString())
|
||||
{
|
||||
p.IsNullable = false;
|
||||
}
|
||||
else//则否默认为null
|
||||
{
|
||||
p.IsNullable = true;
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user