using SqlSugar; using System; using EntrustSettle.Common.LogHelper; using EntrustSettle.Model; using Yitter.IdGenerator; using System.Threading.Tasks; namespace EntrustSettle.Common.DB.Aop; public static class SqlSugarAop { public static void OnLogExecuting(string sql, SugarParameter[] p, string user) { if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "Enabled" }).ObjToBool()) { if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "LogToFile", "Enabled" }).ObjToBool()) { Parallel.For(0, 1, e => { // 完整sql语句 LogLock.OutLogAOP("SqlAOPLog", "", [ $"【操作人】:{user}", "【SQL语句】:", GetWholeSql(p, sql), ]); // 参数化sql语句 //LogLock.OutLogAOP("SqlAOPLog", "", new string[] { GetParas(p), "【SQL语句】:" + sql }); }); } if (AppSettings.app(new string[] { "AppSettings", "SqlAOPLog", "LogToConsole", "Enabled" }).ObjToBool()) { ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} :" + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan); } } } public static void DataExecuting(object oldValue, DataFilterModel entityInfo) { if (entityInfo.EntityValue is RootEntityTkey rootEntity) { if (rootEntity.Id == 0) { // SqlSugar自带的雪花算法有javascript精度问题,所以这里用自定义的雪花算法 //rootEntity.Id = SnowFlakeSingle.Instance.NextId(); rootEntity.Id = YitIdHelper.NextId(); } } if (entityInfo.EntityValue is BaseEntity baseEntity) { // 新增操作赋值CreateTime if (entityInfo.OperationType == DataFilterType.InsertByObject) { if (baseEntity.CreateTime == DateTime.MinValue) { baseEntity.CreateTime = DateTime.Now; } } // 更新操作赋值ModifyTime if (entityInfo.OperationType == DataFilterType.UpdateByObject) { baseEntity.ModifyTime = DateTime.Now; } //if (App.User?.ID > 0) if (!string.IsNullOrEmpty(App.User?.ID)) { // 这里不需要用到租户 //if (baseEntity is ITenantEntity tenant && App.User.TenantId > 0) //{ // if (tenant.TenantId == 0) // { // tenant.TenantId = App.User.TenantId; // } //} switch (entityInfo.OperationType) { case DataFilterType.InsertByObject: if (baseEntity.CreateBy.IsNullOrEmpty() || baseEntity.CreateId is null or "") { baseEntity.CreateId = App.User.ID; baseEntity.CreateBy = App.User.Name; } break; case DataFilterType.UpdateByObject: baseEntity.ModifyId = App.User.ID; baseEntity.ModifyBy = App.User.Name; break; } } } } private static string GetWholeSql(SugarParameter[] paramArr, string sql) { foreach (var param in paramArr) { sql.Replace(param.ParameterName, param.Value.ObjToString()); } return sql; } private static string GetParas(SugarParameter[] pars) { string key = "【SQL参数】:"; foreach (var param in pars) { key += $"{param.ParameterName}:{param.Value}\n"; } return key; } }