TenantDatabaseConnectionStringBuilder.cs 1.59 KB
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;
    }
}