SqlSugarSetup.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 = entity.DbTableName.ToUnderLine(); // 驼峰转下划线
  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 = column.DbColumnName.ToUnderLine(); // 驼峰转下划线
  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. else if (entityInfo.PropertyName == nameof(EntityBaseDel.DeleteTime))
  227. {
  228. dynamic entityValue = entityInfo.EntityValue;
  229. var isDelete = entityValue.IsDelete;
  230. if (isDelete == true)
  231. {
  232. entityInfo.SetValue(DateTime.Now);
  233. }
  234. }
  235. }
  236. };
  237. // 是否为超级管理员
  238. var isSuperAdmin = App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString();
  239. // 配置假删除过滤器,如果当前用户是超级管理员并且允许忽略软删除过滤器则不会应用
  240. if (!isSuperAdmin || !superAdminIgnoreIDeletedFilter)
  241. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  242. // 超管排除其他过滤器
  243. if (isSuperAdmin) return;
  244. // 配置租户过滤器
  245. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  246. if (!string.IsNullOrWhiteSpace(tenantId))
  247. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  248. // 配置用户机构(数据范围)过滤器
  249. SqlSugarFilter.SetOrgEntityFilter(db);
  250. // 配置自定义过滤器
  251. SqlSugarFilter.SetCustomEntityFilter(db);
  252. }
  253. /// <summary>
  254. /// 开启库表差异化日志
  255. /// </summary>
  256. /// <param name="db"></param>
  257. /// <param name="config"></param>
  258. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  259. {
  260. if (!config.DbSettings.EnableDiffLog) return;
  261. async void AopOnDiffLogEvent(DiffLogModel u)
  262. {
  263. // 记录差异数据
  264. var diffData = new List<dynamic>();
  265. for (int i = 0; i < u.AfterData.Count; i++)
  266. {
  267. var diffColumns = new List<dynamic>();
  268. var afterColumns = u.AfterData[i].Columns;
  269. var beforeColumns = u.BeforeData[i].Columns;
  270. for (int j = 0; j < afterColumns.Count; j++)
  271. {
  272. if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
  273. diffColumns.Add(new
  274. {
  275. afterColumns[j].IsPrimaryKey,
  276. afterColumns[j].ColumnName,
  277. afterColumns[j].ColumnDescription,
  278. BeforeValue = beforeColumns[j].Value,
  279. AfterValue = afterColumns[j].Value,
  280. });
  281. }
  282. diffData.Add(new { u.AfterData[i].TableName, u.AfterData[i].TableDescription, Columns = diffColumns });
  283. }
  284. var logDiff = new SysLogDiff
  285. {
  286. // 差异数据(字段描述、列名、值、表名、表描述)
  287. DiffData = JSON.Serialize(diffData),
  288. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  289. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  290. // 枚举(insert、update、delete)
  291. DiffType = u.DiffType.ToString(),
  292. Sql = u.Sql,
  293. Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
  294. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  295. };
  296. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  297. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  298. Console.ForegroundColor = ConsoleColor.Red;
  299. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  300. }
  301. db.Aop.OnDiffLogEvent = AopOnDiffLogEvent;
  302. }
  303. /// <summary>
  304. /// 初始化视图
  305. /// </summary>
  306. /// <param name="dbProvider"></param>
  307. private static void InitView(SqlSugarScopeProvider dbProvider)
  308. {
  309. var totalWatch = Stopwatch.StartNew(); // 开始总计时
  310. Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
  311. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  312. int taskIndex = 0, size = viewTypeList.Count;
  313. var taskList = viewTypeList.Select(viewType => Task.Run(() =>
  314. {
  315. // 开始计时
  316. var stopWatch = Stopwatch.StartNew();
  317. // 获取视图实体和配置信息
  318. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  319. // 如果视图存在,则删除视图
  320. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  321. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  322. // 获取初始化视图查询SQL
  323. var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
  324. if (string.IsNullOrWhiteSpace(sql)) throw new Exception("视图初始化Sql语句不能为空");
  325. // 创建视图
  326. dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " + sql);
  327. // 停止计时
  328. stopWatch.Stop();
  329. Console.ForegroundColor = ConsoleColor.Green;
  330. Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
  331. }));
  332. Task.WaitAll(taskList.ToArray());
  333. totalWatch.Stop(); // 停止总计时
  334. Console.ForegroundColor = ConsoleColor.Green;
  335. Console.WriteLine($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
  336. }
  337. /// <summary>
  338. /// 等待数据库就绪
  339. /// </summary>
  340. /// <param name="dbProvider"></param>
  341. private static void WaitForDatabaseReady(SqlSugarScopeProvider dbProvider)
  342. {
  343. do
  344. {
  345. try
  346. {
  347. if (dbProvider.Ado.Connection.State != ConnectionState.Open)
  348. dbProvider.Ado.Connection.Open();
  349. // 如果连接成功,直接返回
  350. Log.Information("数据库连接成功。");
  351. return;
  352. }
  353. catch (Exception ex)
  354. {
  355. Log.Warning($"数据库尚未就绪,等待中... 错误:{ex.Message}");
  356. Thread.Sleep(1000);
  357. }
  358. } while (true);
  359. }
  360. /// <summary>
  361. /// 初始化数据库
  362. /// </summary>
  363. /// <param name="db">SqlSugarScope 实例</param>
  364. /// <param name="config">数据库连接配置</param>
  365. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  366. {
  367. var dbProvider = db.GetConnectionScope(config.ConfigId);
  368. // 初始化数据库 如果是没有数据库的话,是先初始化数据库再做连接
  369. if (config.DbSettings.EnableInitDb)
  370. {
  371. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  372. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  373. }
  374. // 等待数据库连接就绪
  375. WaitForDatabaseReady(dbProvider);
  376. // 初始化表结构
  377. if (config.TableSettings.EnableInitTable)
  378. {
  379. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  380. var entityTypes = GetEntityTypesForInit(config);
  381. InitializeTables(dbProvider, entityTypes, config);
  382. }
  383. // 初始化视图
  384. if (config.DbSettings.EnableInitView) InitView(dbProvider);
  385. // 初始化种子数据
  386. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  387. }
  388. /// <summary>
  389. /// 获取需要初始化的实体类型
  390. /// </summary>
  391. /// <param name="config">数据库连接配置</param>
  392. /// <returns>实体类型列表</returns>
  393. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  394. {
  395. return App.EffectiveTypes
  396. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  397. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  398. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  399. .Where(u => IsEntityForConfig(u, config))
  400. .ToList();
  401. }
  402. /// <summary>
  403. /// 判断实体是否属于当前配置
  404. /// </summary>
  405. /// <param name="entityType">实体类型</param>
  406. /// <param name="config">数据库连接配置</param>
  407. /// <returns>是否属于当前配置</returns>
  408. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  409. {
  410. switch (config.ConfigId.ToString())
  411. {
  412. case SqlSugarConst.MainConfigId:
  413. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  414. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  415. !entityType.GetCustomAttributes<TenantAttribute>().Any(o => o.configId.ToString() != config.ConfigId.ToString()));
  416. case SqlSugarConst.LogConfigId:
  417. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  418. default:
  419. {
  420. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  421. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  422. }
  423. }
  424. }
  425. /// <summary>
  426. /// 初始化表结构
  427. /// </summary>
  428. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  429. /// <param name="entityTypes">实体类型列表</param>
  430. /// <param name="config">数据库连接配置</param>
  431. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  432. {
  433. // 删除视图再初始化表结构,防止因为视图导致无法同步表结构
  434. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  435. foreach (var viewType in viewTypeList)
  436. {
  437. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  438. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  439. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  440. }
  441. int count = 0, sum = entityTypes.Count;
  442. var tasks = entityTypes.Select(entityType => Task.Run(() =>
  443. {
  444. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  445. UpdateNullableColumns(dbProvider, entityType);
  446. InitializeTable(dbProvider, entityType);
  447. }));
  448. Task.WhenAll(tasks).GetAwaiter().GetResult();
  449. }
  450. /// <summary>
  451. /// 更新表中不存在于实体的字段为可空
  452. /// </summary>
  453. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  454. /// <param name="entityType">实体类型</param>
  455. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  456. {
  457. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  458. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  459. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  460. {
  461. dbColumn.IsNullable = true;
  462. Retry(() =>
  463. {
  464. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  465. }, maxRetry: 3, retryIntervalMs: 1000);
  466. }
  467. }
  468. /// <summary>
  469. /// 初始化表
  470. /// </summary>
  471. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  472. /// <param name="entityType">实体类型</param>
  473. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType)
  474. {
  475. Retry(() =>
  476. {
  477. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  478. {
  479. dbProvider.CodeFirst.InitTables(entityType);
  480. }
  481. else
  482. {
  483. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  484. }
  485. }, maxRetry: 3, retryIntervalMs: 1000);
  486. }
  487. /// <summary>
  488. /// 初始化种子数据
  489. /// </summary>
  490. /// <param name="db">SqlSugarScope 实例</param>
  491. /// <param name="config">数据库连接配置</param>
  492. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  493. {
  494. var dbProvider = db.GetConnectionScope(config.ConfigId);
  495. _isHandlingSeedData = true;
  496. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  497. var seedDataTypes = GetSeedDataTypes(config);
  498. int count = 0, sum = seedDataTypes.Count;
  499. var tasks = seedDataTypes.Select(seedType => Task.Run(() =>
  500. {
  501. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  502. if (!IsEntityForConfig(entityType, config)) return;
  503. var seedData = GetSeedData(seedType)?.ToList();
  504. if (seedData == null) return;
  505. AdjustSeedDataIds(seedData, config);
  506. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  507. }));
  508. Task.WhenAll(tasks).GetAwaiter().GetResult();
  509. _isHandlingSeedData = false;
  510. }
  511. /// <summary>
  512. /// 获取种子数据类型
  513. /// </summary>
  514. /// <param name="config">数据库连接配置</param>
  515. /// <returns>种子数据类型列表</returns>
  516. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  517. {
  518. return App.EffectiveTypes
  519. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  520. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  521. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  522. .ToList();
  523. }
  524. /// <summary>
  525. /// 获取种子数据
  526. /// </summary>
  527. /// <param name="seedType">种子数据类型</param>
  528. /// <returns>种子数据列表</returns>
  529. private static IEnumerable<object> GetSeedData(Type seedType)
  530. {
  531. var instance = Activator.CreateInstance(seedType);
  532. var hasDataMethod = seedType.GetMethod("HasData");
  533. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  534. }
  535. /// <summary>
  536. /// 调整种子数据的 ID
  537. /// </summary>
  538. /// <param name="seedData">种子数据列表</param>
  539. /// <param name="config">数据库连接配置</param>
  540. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  541. {
  542. var seedId = config.ConfigId.ToLong();
  543. foreach (var data in seedData)
  544. {
  545. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  546. if (idProperty == null || idProperty.PropertyType != typeof(Int64)) continue;
  547. var idValue = idProperty.GetValue(data);
  548. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  549. {
  550. idProperty.SetValue(data, ++seedId);
  551. }
  552. }
  553. }
  554. /// <summary>
  555. /// 插入或更新种子数据
  556. /// </summary>
  557. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  558. /// <param name="seedType">种子数据类型</param>
  559. /// <param name="entityType">实体类型</param>
  560. /// <param name="seedData">种子数据列表</param>
  561. /// <param name="config">数据库连接配置</param>
  562. /// <param name="count">当前处理的数量</param>
  563. /// <param name="sum">总数量</param>
  564. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  565. {
  566. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  567. var dataList = seedData.ToList();
  568. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  569. {
  570. var initMethod = seedType.GetMethod("Init");
  571. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  572. }
  573. else
  574. {
  575. int updateCount = 0, insertCount = 0;
  576. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  577. {
  578. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  579. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  580. {
  581. updateCount = storage.AsUpdateable
  582. .IgnoreColumns(entityInfo.Columns
  583. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  584. .Select(u => u.PropertyName).ToArray())
  585. .ExecuteCommand();
  586. }
  587. insertCount = storage.AsInsertable.ExecuteCommand();
  588. }
  589. else
  590. {
  591. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  592. {
  593. insertCount = dataList.Count;
  594. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  595. }
  596. }
  597. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  598. }
  599. }
  600. /// <summary>
  601. /// 初始化租户业务数据库
  602. /// </summary>
  603. /// <param name="iTenant"></param>
  604. /// <param name="config"></param>
  605. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  606. {
  607. SetDbConfig(config);
  608. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  609. iTenant.AddConnection(config);
  610. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  611. db.DbMaintenance.CreateDatabase();
  612. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  613. var entityTypes = App.EffectiveTypes
  614. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  615. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  616. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  617. if (entityTypes.Count == 0) return;
  618. foreach (var entityType in entityTypes)
  619. {
  620. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  621. if (splitTable == null)
  622. db.CodeFirst.InitTables(entityType);
  623. else
  624. db.CodeFirst.SplitTables().InitTables(entityType);
  625. }
  626. }
  627. /// <summary>
  628. /// 简单的重试机制
  629. /// </summary>
  630. /// <param name="action"></param>
  631. /// <param name="maxRetry"></param>
  632. /// <param name="retryIntervalMs"></param>
  633. private static void Retry(Action action, int maxRetry, int retryIntervalMs)
  634. {
  635. int attempt = 0;
  636. while (true)
  637. {
  638. try
  639. {
  640. action();
  641. return;
  642. }
  643. catch (SqliteException ex) when (ex.SqliteErrorCode == 5) // SQLITE_BUSY
  644. {
  645. if (++attempt >= maxRetry)
  646. {
  647. Log.Error($"简单的重试机制:{ex.Message}"); throw;
  648. }
  649. Log.Information($"数据库忙,正在重试... (尝试 {attempt}/{maxRetry})");
  650. Thread.Sleep(retryIntervalMs);
  651. }
  652. }
  653. }
  654. }