RoleAccessPermissionSchemaHelper.cs 1.27 KB
using SqlSugar;

namespace FoodLabeling.Application.Helpers;

/// <summary>
/// 探测 <c>Role.AccessPermissionCodes</c> 列是否已落库(与 <c>RoleAggregateRoot.AccessPermissionCodesJson</c> 映射一致)。
/// </summary>
public static class RoleAccessPermissionSchemaHelper
{
    private static bool? _hasColumn;

    /// <summary>库列名(非 C# 属性名 AccessPermissionCodesJson)。</summary>
    public const string ColumnName = "AccessPermissionCodes";

    public static async Task<bool> HasColumnAsync(ISqlSugarClient db)
    {
        if (_hasColumn is not null)
        {
            return _hasColumn.Value;
        }

        try
        {
            var count = await db.Ado.GetIntAsync(
                """
                SELECT COUNT(*)
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = 'Role'
                  AND COLUMN_NAME = @col
                """,
                new { col = ColumnName });

            _hasColumn = count > 0;
        }
        catch
        {
            _hasColumn = false;
        }

        return _hasColumn.Value;
    }

    /// <summary>单元测试或切换库后调用。</summary>
    public static void ResetCacheForTests() => _hasColumn = null;
}