SqlSugarSetup.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using DbType = SqlSugar.DbType;
  7. namespace Admin.NET.Core;
  8. public static class SqlSugarSetup
  9. {
  10. // 多租户实例
  11. public static ITenant ITenant { get; set; }
  12. // 是否正在处理种子数据
  13. private static bool _isHandlingSeedData = false;
  14. /// <summary>
  15. /// SqlSugar 上下文初始化
  16. /// </summary>
  17. /// <param name="services"></param>
  18. public static void AddSqlSugar(this IServiceCollection services)
  19. {
  20. // 注册雪花Id
  21. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  22. YitIdHelper.SetIdGenerator(snowIdOpt);
  23. // 自定义 SqlSugar 雪花ID算法
  24. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  25. StaticConfig.CustomSnowFlakeFunc = () =>
  26. {
  27. return YitIdHelper.NextId();
  28. };
  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="db">SqlSugarScope 实例</param>
  298. /// <param name="config">数据库连接配置</param>
  299. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  300. {
  301. var dbProvider = db.GetConnectionScope(config.ConfigId);
  302. // 初始化数据库
  303. if (config.DbSettings.EnableInitDb)
  304. {
  305. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  306. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  307. }
  308. // 初始化表结构
  309. if (config.TableSettings.EnableInitTable)
  310. {
  311. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  312. var entityTypes = GetEntityTypesForInit(config);
  313. InitializeTables(dbProvider, entityTypes, config);
  314. }
  315. // 初始化种子数据
  316. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  317. }
  318. /// <summary>
  319. /// 获取需要初始化的实体类型
  320. /// </summary>
  321. /// <param name="config">数据库连接配置</param>
  322. /// <returns>实体类型列表</returns>
  323. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  324. {
  325. return App.EffectiveTypes
  326. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  327. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  328. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  329. .Where(u => IsEntityForConfig(u, config))
  330. .ToList();
  331. }
  332. /// <summary>
  333. /// 判断实体是否属于当前配置
  334. /// </summary>
  335. /// <param name="entityType">实体类型</param>
  336. /// <param name="config">数据库连接配置</param>
  337. /// <returns>是否属于当前配置</returns>
  338. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  339. {
  340. switch (config.ConfigId.ToString())
  341. {
  342. case SqlSugarConst.MainConfigId:
  343. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  344. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  345. !entityType.GetCustomAttributes<TenantAttribute>().Any());
  346. case SqlSugarConst.LogConfigId:
  347. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  348. default:
  349. {
  350. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  351. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  352. }
  353. }
  354. }
  355. /// <summary>
  356. /// 初始化表结构
  357. /// </summary>
  358. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  359. /// <param name="entityTypes">实体类型列表</param>
  360. /// <param name="config">数据库连接配置</param>
  361. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  362. {
  363. int count = 0, sum = entityTypes.Count;
  364. var tasks = entityTypes.Select(entityType => Task.Run(() =>
  365. {
  366. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  367. UpdateNullableColumns(dbProvider, entityType);
  368. InitializeTable(dbProvider, entityType);
  369. }));
  370. Task.WhenAll(tasks).GetAwaiter().GetResult();
  371. }
  372. /// <summary>
  373. /// 更新表中不存在于实体的字段为可空
  374. /// </summary>
  375. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  376. /// <param name="entityType">实体类型</param>
  377. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  378. {
  379. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  380. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  381. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  382. {
  383. dbColumn.IsNullable = true;
  384. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  385. }
  386. }
  387. /// <summary>
  388. /// 初始化表
  389. /// </summary>
  390. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  391. /// <param name="entityType">实体类型</param>
  392. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType)
  393. {
  394. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  395. {
  396. dbProvider.CodeFirst.InitTables(entityType);
  397. }
  398. else
  399. {
  400. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  401. }
  402. }
  403. /// <summary>
  404. /// 初始化种子数据
  405. /// </summary>
  406. /// <param name="db">SqlSugarScope 实例</param>
  407. /// <param name="config">数据库连接配置</param>
  408. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  409. {
  410. var dbProvider = db.GetConnectionScope(config.ConfigId);
  411. _isHandlingSeedData = true;
  412. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  413. var seedDataTypes = GetSeedDataTypes(config);
  414. int count = 0, sum = seedDataTypes.Count;
  415. var tasks = seedDataTypes.Select(seedType => Task.Run(() =>
  416. {
  417. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  418. if (!IsEntityForConfig(entityType, config)) return;
  419. var seedData = GetSeedData(seedType);
  420. if (seedData == null) return;
  421. AdjustSeedDataIds(seedData, config);
  422. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  423. }));
  424. Task.WhenAll(tasks).GetAwaiter().GetResult();
  425. _isHandlingSeedData = false;
  426. }
  427. /// <summary>
  428. /// 获取种子数据类型
  429. /// </summary>
  430. /// <param name="config">数据库连接配置</param>
  431. /// <returns>种子数据类型列表</returns>
  432. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  433. {
  434. return App.EffectiveTypes
  435. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  436. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  437. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  438. .ToList();
  439. }
  440. /// <summary>
  441. /// 获取种子数据
  442. /// </summary>
  443. /// <param name="seedType">种子数据类型</param>
  444. /// <returns>种子数据列表</returns>
  445. private static IEnumerable<object> GetSeedData(Type seedType)
  446. {
  447. var instance = Activator.CreateInstance(seedType);
  448. var hasDataMethod = seedType.GetMethod("HasData");
  449. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  450. }
  451. /// <summary>
  452. /// 调整种子数据的 ID
  453. /// </summary>
  454. /// <param name="seedData">种子数据列表</param>
  455. /// <param name="config">数据库连接配置</param>
  456. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  457. {
  458. var seedId = config.ConfigId.ToLong();
  459. foreach (var data in seedData)
  460. {
  461. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  462. if (idProperty == null) continue;
  463. var idValue = idProperty.GetValue(data);
  464. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  465. {
  466. idProperty.SetValue(data, ++seedId);
  467. }
  468. }
  469. }
  470. /// <summary>
  471. /// 插入或更新种子数据
  472. /// </summary>
  473. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  474. /// <param name="seedType">种子数据类型</param>
  475. /// <param name="entityType">实体类型</param>
  476. /// <param name="seedData">种子数据列表</param>
  477. /// <param name="config">数据库连接配置</param>
  478. /// <param name="count">当前处理的数量</param>
  479. /// <param name="sum">总数量</param>
  480. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  481. {
  482. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  483. var dataList = seedData.ToList();
  484. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  485. {
  486. var initMethod = seedType.GetMethod("Init");
  487. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  488. }
  489. else
  490. {
  491. int updateCount = 0, insertCount = 0;
  492. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  493. {
  494. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  495. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  496. {
  497. updateCount = storage.AsUpdateable
  498. .IgnoreColumns(entityInfo.Columns
  499. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  500. .Select(u => u.PropertyName).ToArray())
  501. .ExecuteCommand();
  502. }
  503. insertCount = storage.AsInsertable.ExecuteCommand();
  504. }
  505. else
  506. {
  507. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  508. {
  509. insertCount = dataList.Count;
  510. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  511. }
  512. }
  513. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  514. }
  515. }
  516. /// <summary>
  517. /// 初始化租户业务数据库
  518. /// </summary>
  519. /// <param name="iTenant"></param>
  520. /// <param name="config"></param>
  521. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  522. {
  523. SetDbConfig(config);
  524. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  525. iTenant.AddConnection(config);
  526. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  527. db.DbMaintenance.CreateDatabase();
  528. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  529. var entityTypes = App.EffectiveTypes
  530. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  531. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  532. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  533. if (entityTypes.Count == 0) return;
  534. foreach (var entityType in entityTypes)
  535. {
  536. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  537. if (splitTable == null)
  538. db.CodeFirst.InitTables(entityType);
  539. else
  540. db.CodeFirst.SplitTables().InitTables(entityType);
  541. }
  542. }
  543. }