SqlsugarSetup.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. using Base;
  2. using Infrastructure;
  3. using Infrastructure.Model;
  4. using SqlSugar.IOC;
  5. namespace SqlSugar
  6. {
  7. public static class SqlsugarSetup
  8. {
  9. private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
  10. /// <summary>
  11. /// 初始化db
  12. /// </summary>
  13. /// <param name="services"></param>
  14. /// <param name="environment"></param>
  15. public static void AddDb(this IServiceCollection services, IWebHostEnvironment environment)
  16. {
  17. var options = App.OptionsSetting;
  18. List<DbConfigs> dbConfigs = options.DbConfigs;
  19. var iocList = new List<IocConfig>();
  20. foreach (var item in dbConfigs)
  21. {
  22. iocList.Add(new IocConfig()
  23. {
  24. ConfigId = item.ConfigId,
  25. ConnectionString = item.Conn,
  26. DbType = (IocDbType)item.DbType,
  27. IsAutoCloseConnection = item.IsAutoCloseConnection
  28. });
  29. }
  30. SugarIocServices.AddSqlSugar(iocList);
  31. ICacheService cache = new SqlSugarCache();
  32. SugarIocServices.ConfigurationSugar(db =>
  33. {
  34. var u = App.User;
  35. if (u != null)
  36. {
  37. DataPermi.FilterData(0);
  38. //ConfigId = 1的数据权限过滤
  39. //DataPermiSevice.FilterData(1);
  40. }
  41. iocList.ForEach(iocConfig =>
  42. {
  43. SetSugarAop(db, iocConfig, cache);
  44. });
  45. });
  46. if (options.InitDb && environment.IsDevelopment())
  47. {
  48. InitTable.InitDb();
  49. }
  50. }
  51. /// <summary>
  52. /// 数据库Aop设置
  53. /// </summary>
  54. /// <param name="db"></param>
  55. /// <param name="iocConfig"></param>
  56. /// <param name="cache"></param>
  57. private static void SetSugarAop(SqlSugarClient db, IocConfig iocConfig, ICacheService cache)
  58. {
  59. var config = db.GetConnectionScope(iocConfig.ConfigId).CurrentConnectionConfig;
  60. var showDbLog = AppSettings.Get<bool>("ShowDbLog");
  61. string configId = config.ConfigId;
  62. db.GetConnectionScope(configId).Aop.OnLogExecuting = (sql, pars) =>
  63. {
  64. if (showDbLog)
  65. {
  66. string log = $"【db{configId} SQL】{UtilMethods.GetSqlString(config.DbType, sql, pars)}\n";
  67. if (sql.TrimStart().StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  68. {
  69. logger.Info(log);
  70. }
  71. else if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  72. {
  73. logger.Warn(log);
  74. }
  75. else if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("TRUNCATE", StringComparison.OrdinalIgnoreCase))
  76. {
  77. logger.Error(log);
  78. }
  79. else
  80. {
  81. log = $"【db{configId} SQL语句】dbo.{sql} {string.Join(", ", pars.Select(x => x.ParameterName + " = " + GetParsValue(x)))};\n";
  82. logger.Info(log);
  83. }
  84. }
  85. };
  86. db.GetConnectionScope(configId).Aop.OnError = (ex) =>
  87. {
  88. //var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  89. string sql = "【错误SQL】" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n";
  90. logger.Error(ex, $"{sql}\r\n{ex.Message}\r\n{ex.StackTrace}");
  91. };
  92. db.GetConnectionScope(configId).Aop.DataExecuting = (oldValue, entiyInfo) =>
  93. {
  94. };
  95. //差异日志功能
  96. db.GetConnectionScope(configId).Aop.OnDiffLogEvent = it =>
  97. {
  98. //操作前记录 包含: 字段描述 列名 值 表名 表描述
  99. var editBeforeData = it.BeforeData;//插入Before为null,之前还没进库
  100. //操作后记录 包含: 字段描述 列名 值 表名 表描述
  101. var editAfterData = it.AfterData;
  102. var sql = it.Sql;
  103. var parameter = it.Parameters;
  104. var data = it.BusinessData;//这边会显示你传进来的对象
  105. var time = it.Time;
  106. var diffType = it.DiffType;//enum insert 、update and delete
  107. string name = App.UserName;
  108. foreach (var item in editBeforeData)
  109. {
  110. var pars = db.Utilities.SerializeObject(item.Columns.ToDictionary(it => it.ColumnName, it => it.Value));
  111. // SqlDiffLog log = new()
  112. // {
  113. // BeforeData = pars,
  114. // BusinessData = data?.ToString(),
  115. // DiffType = diffType.ToString(),
  116. // Sql = sql,
  117. // TableName = item.TableName,
  118. // UserName = name,
  119. // AddTime = DateTime.Now,
  120. // ConfigId = configId
  121. // };
  122. // if (editAfterData != null)
  123. // {
  124. // var afterData = editAfterData?.First(x => x.TableName == item.TableName);
  125. // var afterPars = db.Utilities.SerializeObject(afterData?.Columns.ToDictionary(it => it.ColumnName, it => it.Value));
  126. // log.AfterData = afterPars;
  127. // }
  128. logger.WithProperty("title", data).Info(pars);
  129. // db.GetConnectionScope(0)
  130. // .Insertable(log)
  131. // .ExecuteReturnSnowflakeId();
  132. }
  133. };
  134. db.GetConnectionScope(configId).CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
  135. {
  136. IsAutoRemoveDataCache = true
  137. };
  138. db.GetConnectionScope(configId).CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
  139. {
  140. DataInfoCacheService = cache,
  141. EntityService = (c, p) =>
  142. {
  143. if (p.IsPrimarykey == true)//主键不能为null
  144. {
  145. p.IsNullable = false;
  146. }
  147. else if (p.ExtendedAttribute?.ToString() == "0")
  148. {
  149. p.IsNullable = false;
  150. }
  151. else//则否默认为null
  152. {
  153. p.IsNullable = true;
  154. }
  155. }
  156. };
  157. db.GetConnectionScope(configId).Aop.OnLogExecuted = (sql, pars) =>
  158. {
  159. var sqlExecutionTime = AppSettings.Get<int>("sqlExecutionTime");
  160. if (db.Ado.SqlExecutionTime.TotalSeconds > sqlExecutionTime)
  161. {
  162. //代码CS文件名
  163. var fileName = db.Ado.SqlStackTrace.FirstFileName;
  164. //代码行数
  165. var fileLine = db.Ado.SqlStackTrace.FirstLine;
  166. //方法名
  167. var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
  168. var logInfo = $"Sql执行超时,用时{db.Ado.SqlExecutionTime.TotalSeconds}秒【{sql}】,fileName={fileName},line={fileLine},methodName={FirstMethodName}";
  169. logger.Warn(logInfo);
  170. }
  171. };
  172. }
  173. private static object GetParsValue(SugarParameter x)
  174. {
  175. if (x.DbType == System.Data.DbType.String || x.DbType == System.Data.DbType.DateTime || x.DbType == System.Data.DbType.String)
  176. {
  177. return "'" + x.Value + "'";
  178. }
  179. return x.Value;
  180. }
  181. }
  182. }