Blame view

泰额版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling/FoodLabeling.Th.Application/MultiTenancy/TenantDatabaseConnectionStringBuilder.cs 1.59 KB
a1a0369d   李曜臣   5-25代码优化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  using System.Text.RegularExpressions;
  using FoodLabeling.Th.Application.Contracts.Options;
  using SqlSugar;
  
  namespace FoodLabeling.Th.Application.MultiTenancy;
  
  /// <summary>
  /// 根据配置生成 MySQL 租户库连接串
  /// </summary>
  public static class TenantDatabaseConnectionStringBuilder
  {
      private static readonly Regex SafeNameRegex = new(@"[^a-z0-9_]", RegexOptions.Compiled);
  
      public static string NormalizeTenantDatabaseKey(string tenantName)
      {
          var key = tenantName.Trim().ToLowerInvariant();
          key = SafeNameRegex.Replace(key, "_");
          key = Regex.Replace(key, "_+", "_").Trim('_');
          if (string.IsNullOrEmpty(key))
          {
              throw new ArgumentException("租户名称无效,无法生成数据库名");
          }
  
          return key;
      }
  
      public static string BuildDatabaseName(FoodLabelingThTenantDatabaseOptions options, string tenantName)
      {
          var key = NormalizeTenantDatabaseKey(tenantName);
          return options.DatabaseNameTemplate.Replace("{tenant}", key, StringComparison.OrdinalIgnoreCase);
      }
  
      public static string BuildMySqlConnectionString(FoodLabelingThTenantDatabaseOptions options, string tenantName)
      {
          var database = BuildDatabaseName(options, tenantName);
          return
              $"server={options.Server};port={options.Port};database={database};uid={options.UserId};pwd={options.Password};CharSet={options.CharSet};";
      }
  
      public static DbType ResolveDbType(string? configuredDbType)
      {
          return Enum.TryParse<DbType>(configuredDbType, true, out var dbType) ? dbType : DbType.MySql;
      }
  }