SqlSugarSetup.cs 33 KB

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