using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ORM { public static class DatabaseConfig { /// /// 当前数据库类型 /// public static DbType DbConnectionType { get; private set; } /// /// 数据库连接字符串 /// public static string DbConnectionString { get; private set; } /// /// 默认 SQLite 文件路径(仅记录,不自动启用) /// public static string DefaultDbFilePath { get; private set; } /// /// 租户 Id /// public static int TenantId { get; private set; } public static int SnowFlakeDatacenterId { get; private set; } public static int SnowFlakeWorkId { get; private set; } static DatabaseConfig() { InitDefaultDbPath(); // 只生成路径,不指定 DB 类型/连接 } /// /// 生成默认 DB 路径 EXE目录/SQLDB/Data.db /// private static void InitDefaultDbPath() { string baseDir = AppDomain.CurrentDomain.BaseDirectory; string folder = Path.Combine(baseDir, "SQLDB"); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); DefaultDbFilePath = Path.Combine(folder, "Data.db"); } /// /// 手动设置数据库连接 /// public static void SetConnection(string conn, DbType dbType) { if (string.IsNullOrWhiteSpace(conn)) throw new Exception("数据库连接字符串为空"); DbConnectionString = conn; DbConnectionType = dbType; } /// /// 如果未 SetConnection,默认使用 SQLite + 默认路径 /// public static void EnsureConnection() { if (string.IsNullOrEmpty(DbConnectionString)) { DbConnectionString = $"Data Source={DefaultDbFilePath};"; DbConnectionType = DbType.Sqlite; } } /// /// 设置租户并计算雪花算法节点 /// public static void SetTenant(int tenantId) { if (tenantId <= 10000) throw new Exception("数据租户Id值需大于10000"); TenantId = tenantId; int snowId = (tenantId - 10000) % 1024; if (snowId is < 0 or > 1023) throw new Exception("雪花算法机器码值范围0至1023"); SnowFlakeDatacenterId = snowId >> 5; SnowFlakeWorkId = snowId & 31; } } }