98 lines
2.8 KiB
C#
98 lines
2.8 KiB
C#
using SqlSugar;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace ORM
|
||
{
|
||
public static class DatabaseConfig
|
||
{
|
||
/// <summary>
|
||
/// 当前数据库类型
|
||
/// </summary>
|
||
public static DbType DbConnectionType { get; private set; }
|
||
|
||
/// <summary>
|
||
/// 数据库连接字符串
|
||
/// </summary>
|
||
public static string DbConnectionString { get; private set; }
|
||
|
||
/// <summary>
|
||
/// 默认 SQLite 文件路径(仅记录,不自动启用)
|
||
/// </summary>
|
||
public static string DefaultDbFilePath { get; private set; }
|
||
|
||
/// <summary>
|
||
/// 租户 Id
|
||
/// </summary>
|
||
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 类型/连接
|
||
}
|
||
|
||
/// <summary>
|
||
/// 生成默认 DB 路径 EXE目录/SQLDB/Data.db
|
||
/// </summary>
|
||
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");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 手动设置数据库连接
|
||
/// </summary>
|
||
public static void SetConnection(string conn, DbType dbType)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(conn))
|
||
throw new Exception("数据库连接字符串为空");
|
||
|
||
DbConnectionString = conn;
|
||
DbConnectionType = dbType;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 如果未 SetConnection,默认使用 SQLite + 默认路径
|
||
/// </summary>
|
||
public static void EnsureConnection()
|
||
{
|
||
if (string.IsNullOrEmpty(DbConnectionString))
|
||
{
|
||
DbConnectionString = $"Data Source={DefaultDbFilePath};";
|
||
DbConnectionType = DbType.Sqlite;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置租户并计算雪花算法节点
|
||
/// </summary>
|
||
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;
|
||
}
|
||
}
|
||
}
|