SqlSugarSetup.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Microsoft.Data.Sqlite;
  7. using DbType = SqlSugar.DbType;
  8. namespace Admin.NET.Core;
  9. public static class SqlSugarSetup
  10. {
  11. // 多租户实例
  12. public static ITenant ITenant { get; set; }
  13. // 是否正在处理种子数据
  14. private static bool _isHandlingSeedData = false;
  15. /// <summary>
  16. /// SqlSugar 上下文初始化
  17. /// </summary>
  18. /// <param name="services"></param>
  19. public static void AddSqlSugar(this IServiceCollection services)
  20. {
  21. // 注册雪花Id
  22. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  23. YitIdHelper.SetIdGenerator(snowIdOpt);
  24. // 自定义 SqlSugar 雪花ID算法
  25. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  26. StaticConfig.CustomSnowFlakeFunc = YitIdHelper.NextId;
  27. // 注册 MongoDb
  28. InstanceFactory.CustomAssemblies = [typeof(SqlSugar.MongoDb.MongoDbProvider).Assembly];
  29. // 动态表达式 SqlFunc 支持,https://www.donet5.com/Home/Doc?typeId=2569
  30. StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser);
  31. StaticConfig.DynamicExpressionParsingConfig = new ParsingConfig
  32. {
  33. CustomTypeProvider = new SqlSugarTypeProvider()
  34. };
  35. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  36. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  37. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  38. {
  39. dbOptions.ConnectionConfigs.ForEach(config =>
  40. {
  41. var dbProvider = db.GetConnectionScope(config.ConfigId);
  42. SetDbAop(dbProvider, dbOptions.EnableConsoleSql, dbOptions.SuperAdminIgnoreIDeletedFilter);
  43. SetDbDiffLog(dbProvider, config);
  44. });
  45. });
  46. ITenant = sqlSugar;
  47. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  48. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  49. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  50. // 初始化数据库表结构及种子数据
  51. dbOptions.ConnectionConfigs.ForEach(config =>
  52. {
  53. InitDatabase(sqlSugar, config);
  54. });
  55. }
  56. /// <summary>
  57. /// 配置连接属性
  58. /// </summary>
  59. /// <param name="config"></param>
  60. public static void SetDbConfig(DbConnectionConfig config)
  61. {
  62. if (config.DbSettings.EnableConnStringEncrypt)
  63. config.ConnectionString = CryptogramUtil.Decrypt(config.ConnectionString);
  64. var configureExternalServices = new ConfigureExternalServices
  65. {
  66. EntityNameService = (type, entity) => // 处理表
  67. {
  68. entity.IsDisabledDelete = true; // 禁止删除非 sqlsugar 创建的列
  69. // 只处理贴了特性[SugarTable]表
  70. if (!type.GetCustomAttributes<SugarTable>().Any())
  71. return;
  72. if (config.DbSettings.EnableUnderLine && !entity.DbTableName.Contains('_'))
  73. entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); // 驼峰转下划线
  74. },
  75. EntityService = (type, column) => // 处理列
  76. {
  77. // 只处理贴了特性[SugarColumn]列
  78. if (!type.GetCustomAttributes<SugarColumn>().Any())
  79. return;
  80. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  81. column.IsNullable = true;
  82. if (config.DbSettings.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  83. column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); // 驼峰转下划线
  84. },
  85. DataInfoCacheService = new SqlSugarCache(),
  86. };
  87. config.ConfigureExternalServices = configureExternalServices;
  88. config.InitKeyType = InitKeyType.Attribute;
  89. config.IsAutoCloseConnection = true;
  90. config.MoreSettings = new ConnMoreSettings
  91. {
  92. IsAutoRemoveDataCache = true, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  93. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  94. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  95. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  96. };
  97. // 若库类型是人大金仓则默认设置PG模式
  98. if (config.DbType == DbType.Kdbndp)
  99. config.MoreSettings.DatabaseModel = DbType.PostgreSQL; // 配置PG模式主要是兼容系统表差异
  100. // 若库类型是Oracle则默认主键名字和参数名字最大长度
  101. if (config.DbType == DbType.Oracle)
  102. config.MoreSettings.MaxParameterNameLength = 30;
  103. }
  104. /// <summary>
  105. /// 配置Aop
  106. /// </summary>
  107. /// <param name="db"></param>
  108. /// <param name="enableConsoleSql"></param>
  109. /// <param name="superAdminIgnoreIDeletedFilter"></param>
  110. public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql, bool superAdminIgnoreIDeletedFilter)
  111. {
  112. // 设置超时时间
  113. db.Ado.CommandTimeOut = 30;
  114. // 打印SQL语句
  115. if (enableConsoleSql)
  116. {
  117. db.Aop.OnLogExecuting = (sql, pars) =>
  118. {
  119. //// 若参数值超过100个字符则进行截取
  120. //foreach (var par in pars)
  121. //{
  122. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  123. // if (par.Value.ToString().Length > 100)
  124. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  125. //}
  126. var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
  127. var originColor = Console.ForegroundColor;
  128. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  129. Console.ForegroundColor = ConsoleColor.Green;
  130. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  131. Console.ForegroundColor = ConsoleColor.Yellow;
  132. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  133. Console.ForegroundColor = ConsoleColor.Red;
  134. Console.WriteLine(log);
  135. Console.ForegroundColor = originColor;
  136. };
  137. }
  138. db.Aop.OnError = ex =>
  139. {
  140. if (ex.Parametres == null) return;
  141. var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
  142. Log.Error(log, ex);
  143. };
  144. db.Aop.OnLogExecuted = (sql, pars) =>
  145. {
  146. //// 若参数值超过100个字符则进行截取
  147. //foreach (var par in pars)
  148. //{
  149. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  150. // if (par.Value.ToString().Length > 100)
  151. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  152. //}
  153. // 执行时间超过5秒时
  154. if (!(db.Ado.SqlExecutionTime.TotalSeconds > 5)) return;
  155. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  156. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  157. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  158. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetNativeSql(sql, pars)}";
  159. Log.Warning(log);
  160. };
  161. // 数据审计
  162. db.Aop.DataExecuting = (_, entityInfo) =>
  163. {
  164. // 若正在处理种子数据则直接返回
  165. if (_isHandlingSeedData) return;
  166. // 新增/插入
  167. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  168. {
  169. // 若主键是长整型且空则赋值雪花Id
  170. if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  171. {
  172. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  173. if (id == null || (long)id == 0)
  174. entityInfo.SetValue(YitIdHelper.NextId());
  175. }
  176. // 若创建时间为空则赋值当前时间
  177. else if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  178. {
  179. var createTime = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
  180. if (createTime == null || createTime.Equals(DateTime.MinValue))
  181. entityInfo.SetValue(DateTime.Now);
  182. }
  183. // 若当前用户为空(非web线程时)
  184. if (App.User == null) return;
  185. dynamic entityValue = entityInfo.EntityValue;
  186. if (entityInfo.PropertyName == nameof(EntityBaseTenantId.TenantId))
  187. {
  188. var tenantId = entityValue.TenantId;
  189. if (tenantId == null || tenantId == 0)
  190. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  191. }
  192. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  193. {
  194. var createUserId = entityValue.CreateUserId;
  195. if (createUserId == 0 || createUserId == null)
  196. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  197. }
  198. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  199. {
  200. var createUserName = entityValue.CreateUserName;
  201. if (string.IsNullOrEmpty(createUserName))
  202. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  203. }
  204. else if (entityInfo.PropertyName == "CreateOrgId")
  205. {
  206. var createOrgId = entityValue.CreateOrgId;
  207. if (createOrgId == 0 || createOrgId == null)
  208. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  209. }
  210. else if (entityInfo.PropertyName == "CreateOrgName")
  211. {
  212. var createOrgName = entityValue.CreateOrgName;
  213. if (string.IsNullOrEmpty(createOrgName))
  214. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  215. }
  216. }
  217. // 编辑/更新
  218. else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  219. {
  220. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  221. entityInfo.SetValue(DateTime.Now);
  222. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  223. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  224. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  225. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  226. }
  227. };
  228. // 是否为超级管理员
  229. var isSuperAdmin = App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString();
  230. // 配置假删除过滤器,如果当前用户是超级管理员并且允许忽略软删除过滤器则不会应用
  231. if (!isSuperAdmin || !superAdminIgnoreIDeletedFilter)
  232. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  233. // 超管排除其他过滤器
  234. if (isSuperAdmin) return;
  235. // 配置租户过滤器
  236. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  237. if (!string.IsNullOrWhiteSpace(tenantId))
  238. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  239. // 配置用户机构(数据范围)过滤器
  240. SqlSugarFilter.SetOrgEntityFilter(db);
  241. // 配置自定义过滤器
  242. SqlSugarFilter.SetCustomEntityFilter(db);
  243. }
  244. /// <summary>
  245. /// 开启库表差异化日志
  246. /// </summary>
  247. /// <param name="db"></param>
  248. /// <param name="config"></param>
  249. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  250. {
  251. if (!config.DbSettings.EnableDiffLog) return;
  252. async void AopOnDiffLogEvent(DiffLogModel u)
  253. {
  254. // 记录差异数据
  255. var diffData = new List<dynamic>();
  256. for (int i = 0; i < u.AfterData.Count; i++)
  257. {
  258. var diffColumns = new List<dynamic>();
  259. var afterColumns = u.AfterData[i].Columns;
  260. var beforeColumns = u.BeforeData[i].Columns;
  261. for (int j = 0; j < afterColumns.Count; j++)
  262. {
  263. if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
  264. diffColumns.Add(new
  265. {
  266. afterColumns[j].IsPrimaryKey,
  267. afterColumns[j].ColumnName,
  268. afterColumns[j].ColumnDescription,
  269. BeforeValue = beforeColumns[j].Value,
  270. AfterValue = afterColumns[j].Value,
  271. });
  272. }
  273. diffData.Add(new { u.AfterData[i].TableName, u.AfterData[i].TableDescription, Columns = diffColumns });
  274. }
  275. var logDiff = new SysLogDiff
  276. {
  277. // 差异数据(字段描述、列名、值、表名、表描述)
  278. DiffData = JSON.Serialize(diffData),
  279. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  280. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  281. // 枚举(insert、update、delete)
  282. DiffType = u.DiffType.ToString(),
  283. Sql = u.Sql,
  284. Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
  285. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  286. };
  287. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  288. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  289. Console.ForegroundColor = ConsoleColor.Red;
  290. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  291. }
  292. db.Aop.OnDiffLogEvent = AopOnDiffLogEvent;
  293. }
  294. /// <summary>
  295. /// 初始化视图
  296. /// </summary>
  297. /// <param name="dbProvider"></param>
  298. private static void InitView(SqlSugarScopeProvider dbProvider)
  299. {
  300. var totalWatch = Stopwatch.StartNew(); // 开始总计时
  301. Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
  302. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  303. int taskIndex = 0, size = viewTypeList.Count;
  304. var taskList = viewTypeList.Select(viewType => Task.Run(() =>
  305. {
  306. // 开始计时
  307. var stopWatch = Stopwatch.StartNew();
  308. // 获取视图实体和配置信息
  309. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  310. // 如果视图存在,则删除视图
  311. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  312. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  313. // 获取初始化视图查询SQL
  314. var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
  315. if (string.IsNullOrWhiteSpace(sql)) throw new Exception("视图初始化Sql语句不能为空");
  316. // 创建视图
  317. dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " + sql);
  318. // 停止计时
  319. stopWatch.Stop();
  320. Console.ForegroundColor = ConsoleColor.Green;
  321. Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
  322. }));
  323. Task.WaitAll(taskList.ToArray());
  324. totalWatch.Stop(); // 停止总计时
  325. Console.ForegroundColor = ConsoleColor.Green;
  326. Console.WriteLine($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
  327. }
  328. /// <summary>
  329. /// 等待数据库就绪
  330. /// </summary>
  331. /// <param name="dbProvider"></param>
  332. private static void WaitForDatabaseReady(SqlSugarScopeProvider dbProvider)
  333. {
  334. do
  335. {
  336. try
  337. {
  338. if (dbProvider.Ado.Connection.State != ConnectionState.Open)
  339. dbProvider.Ado.Connection.Open();
  340. // 如果连接成功,直接返回
  341. Log.Information("数据库连接成功。");
  342. return;
  343. }
  344. catch (Exception ex)
  345. {
  346. Log.Warning($"数据库尚未就绪,等待中... 错误:{ex.Message}");
  347. Thread.Sleep(1000);
  348. }
  349. } while (true);
  350. }
  351. /// <summary>
  352. /// 初始化数据库
  353. /// </summary>
  354. /// <param name="db">SqlSugarScope 实例</param>
  355. /// <param name="config">数据库连接配置</param>
  356. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  357. {
  358. var dbProvider = db.GetConnectionScope(config.ConfigId);
  359. // 等待数据库连接就绪
  360. WaitForDatabaseReady(dbProvider);
  361. // 初始化数据库
  362. if (config.DbSettings.EnableInitDb)
  363. {
  364. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  365. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  366. }
  367. // 初始化表结构
  368. if (config.TableSettings.EnableInitTable)
  369. {
  370. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  371. var entityTypes = GetEntityTypesForInit(config);
  372. InitializeTables(dbProvider, entityTypes, config);
  373. }
  374. // 初始化视图
  375. if (config.DbSettings.EnableInitView) InitView(dbProvider);
  376. // 初始化种子数据
  377. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  378. }
  379. /// <summary>
  380. /// 获取需要初始化的实体类型
  381. /// </summary>
  382. /// <param name="config">数据库连接配置</param>
  383. /// <returns>实体类型列表</returns>
  384. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  385. {
  386. return App.EffectiveTypes
  387. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  388. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  389. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  390. .Where(u => IsEntityForConfig(u, config))
  391. .ToList();
  392. }
  393. /// <summary>
  394. /// 判断实体是否属于当前配置
  395. /// </summary>
  396. /// <param name="entityType">实体类型</param>
  397. /// <param name="config">数据库连接配置</param>
  398. /// <returns>是否属于当前配置</returns>
  399. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  400. {
  401. switch (config.ConfigId.ToString())
  402. {
  403. case SqlSugarConst.MainConfigId:
  404. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  405. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  406. !entityType.GetCustomAttributes<TenantAttribute>().Any(o => o.configId.ToString() != config.ConfigId.ToString()));
  407. case SqlSugarConst.LogConfigId:
  408. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  409. default:
  410. {
  411. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  412. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  413. }
  414. }
  415. }
  416. /// <summary>
  417. /// 初始化表结构
  418. /// </summary>
  419. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  420. /// <param name="entityTypes">实体类型列表</param>
  421. /// <param name="config">数据库连接配置</param>
  422. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  423. {
  424. // 删除视图再初始化表结构,防止因为视图导致无法同步表结构
  425. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  426. foreach (var viewType in viewTypeList)
  427. {
  428. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  429. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  430. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  431. }
  432. int count = 0, sum = entityTypes.Count;
  433. var tasks = entityTypes.Select(entityType => Task.Run(() =>
  434. {
  435. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  436. UpdateNullableColumns(dbProvider, entityType);
  437. InitializeTable(dbProvider, entityType);
  438. }));
  439. Task.WhenAll(tasks).GetAwaiter().GetResult();
  440. }
  441. /// <summary>
  442. /// 更新表中不存在于实体的字段为可空
  443. /// </summary>
  444. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  445. /// <param name="entityType">实体类型</param>
  446. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  447. {
  448. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  449. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  450. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  451. {
  452. dbColumn.IsNullable = true;
  453. Retry(() =>
  454. {
  455. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  456. }, maxRetry: 3, retryIntervalMs: 1000);
  457. }
  458. }
  459. /// <summary>
  460. /// 初始化表
  461. /// </summary>
  462. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  463. /// <param name="entityType">实体类型</param>
  464. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType)
  465. {
  466. Retry(() =>
  467. {
  468. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  469. {
  470. dbProvider.CodeFirst.InitTables(entityType);
  471. }
  472. else
  473. {
  474. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  475. }
  476. }, maxRetry: 3, retryIntervalMs: 1000);
  477. }
  478. /// <summary>
  479. /// 初始化种子数据
  480. /// </summary>
  481. /// <param name="db">SqlSugarScope 实例</param>
  482. /// <param name="config">数据库连接配置</param>
  483. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  484. {
  485. var dbProvider = db.GetConnectionScope(config.ConfigId);
  486. _isHandlingSeedData = true;
  487. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  488. var seedDataTypes = GetSeedDataTypes(config);
  489. int count = 0, sum = seedDataTypes.Count;
  490. var tasks = seedDataTypes.Select(seedType => Task.Run(() =>
  491. {
  492. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  493. if (!IsEntityForConfig(entityType, config)) return;
  494. var seedData = GetSeedData(seedType);
  495. if (seedData == null) return;
  496. AdjustSeedDataIds(seedData, config);
  497. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  498. }));
  499. Task.WhenAll(tasks).GetAwaiter().GetResult();
  500. _isHandlingSeedData = false;
  501. }
  502. /// <summary>
  503. /// 获取种子数据类型
  504. /// </summary>
  505. /// <param name="config">数据库连接配置</param>
  506. /// <returns>种子数据类型列表</returns>
  507. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  508. {
  509. return App.EffectiveTypes
  510. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  511. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  512. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  513. .ToList();
  514. }
  515. /// <summary>
  516. /// 获取种子数据
  517. /// </summary>
  518. /// <param name="seedType">种子数据类型</param>
  519. /// <returns>种子数据列表</returns>
  520. private static IEnumerable<object> GetSeedData(Type seedType)
  521. {
  522. var instance = Activator.CreateInstance(seedType);
  523. var hasDataMethod = seedType.GetMethod("HasData");
  524. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  525. }
  526. /// <summary>
  527. /// 调整种子数据的 ID
  528. /// </summary>
  529. /// <param name="seedData">种子数据列表</param>
  530. /// <param name="config">数据库连接配置</param>
  531. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  532. {
  533. var seedId = config.ConfigId.ToLong();
  534. foreach (var data in seedData)
  535. {
  536. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  537. if (idProperty == null || idProperty.PropertyType != typeof(Int64)) continue;
  538. var idValue = idProperty.GetValue(data);
  539. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  540. {
  541. idProperty.SetValue(data, ++seedId);
  542. }
  543. }
  544. }
  545. /// <summary>
  546. /// 插入或更新种子数据
  547. /// </summary>
  548. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  549. /// <param name="seedType">种子数据类型</param>
  550. /// <param name="entityType">实体类型</param>
  551. /// <param name="seedData">种子数据列表</param>
  552. /// <param name="config">数据库连接配置</param>
  553. /// <param name="count">当前处理的数量</param>
  554. /// <param name="sum">总数量</param>
  555. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  556. {
  557. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  558. var dataList = seedData.ToList();
  559. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  560. {
  561. var initMethod = seedType.GetMethod("Init");
  562. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  563. }
  564. else
  565. {
  566. int updateCount = 0, insertCount = 0;
  567. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  568. {
  569. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  570. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  571. {
  572. updateCount = storage.AsUpdateable
  573. .IgnoreColumns(entityInfo.Columns
  574. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  575. .Select(u => u.PropertyName).ToArray())
  576. .ExecuteCommand();
  577. }
  578. insertCount = storage.AsInsertable.ExecuteCommand();
  579. }
  580. else
  581. {
  582. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  583. {
  584. insertCount = dataList.Count;
  585. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  586. }
  587. }
  588. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  589. }
  590. }
  591. /// <summary>
  592. /// 初始化租户业务数据库
  593. /// </summary>
  594. /// <param name="iTenant"></param>
  595. /// <param name="config"></param>
  596. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  597. {
  598. SetDbConfig(config);
  599. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  600. iTenant.AddConnection(config);
  601. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  602. db.DbMaintenance.CreateDatabase();
  603. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  604. var entityTypes = App.EffectiveTypes
  605. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  606. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  607. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  608. if (entityTypes.Count == 0) return;
  609. foreach (var entityType in entityTypes)
  610. {
  611. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  612. if (splitTable == null)
  613. db.CodeFirst.InitTables(entityType);
  614. else
  615. db.CodeFirst.SplitTables().InitTables(entityType);
  616. }
  617. }
  618. /// <summary>
  619. /// 简单的重试机制
  620. /// </summary>
  621. /// <param name="action"></param>
  622. /// <param name="maxRetry"></param>
  623. /// <param name="retryIntervalMs"></param>
  624. private static void Retry(Action action, int maxRetry, int retryIntervalMs)
  625. {
  626. int attempt = 0;
  627. while (true)
  628. {
  629. try
  630. {
  631. action();
  632. return;
  633. }
  634. catch (SqliteException ex) when (ex.SqliteErrorCode == 5) // SQLITE_BUSY
  635. {
  636. if (++attempt >= maxRetry)
  637. {
  638. Log.Error($"简单的重试机制:{ex.Message}"); throw;
  639. }
  640. Log.Information($"数据库忙,正在重试... (尝试 {attempt}/{maxRetry})");
  641. Thread.Sleep(retryIntervalMs);
  642. }
  643. }
  644. }
  645. }