SqlSugarSetup.cs 34 KB

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