2026-07-02 18:13:56 +08:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
|
|
|
2026-08-13 15:00:39 +08:00
|
|
|
|
namespace Gpulse.WCT.DataAnalyzer.Core.Infrastructure.LocalData;
|
2026-07-02 18:13:56 +08:00
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 数据库上下文工厂实现 - 支持SQLite和PostgreSQL切换
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class DbContextFactory : IDbContextFactory
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly IConfiguration _configuration;
|
|
|
|
|
|
|
|
|
|
|
|
public DbContextFactory(IConfiguration configuration)
|
|
|
|
|
|
{
|
|
|
|
|
|
_configuration = configuration;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public WctMinerDbContext CreateDbContext()
|
|
|
|
|
|
{
|
|
|
|
|
|
var dbType = _configuration["Database:Type"]?.ToLower() ?? "sqlite";
|
|
|
|
|
|
var optionsBuilder = new DbContextOptionsBuilder<WctMinerDbContext>();
|
|
|
|
|
|
|
|
|
|
|
|
switch (dbType)
|
|
|
|
|
|
{
|
|
|
|
|
|
case "postgresql":
|
|
|
|
|
|
case "postgres":
|
|
|
|
|
|
var pgConnStr = BuildPostgreSqlConnectionString();
|
|
|
|
|
|
optionsBuilder.UseNpgsql(pgConnStr);
|
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
|
|
case "sqlite":
|
|
|
|
|
|
default:
|
2026-08-13 15:00:39 +08:00
|
|
|
|
var dbPath = _configuration["Database:LocalPath"]
|
|
|
|
|
|
?? _configuration["Database:Path"]
|
|
|
|
|
|
?? "./data/database/local.db";
|
2026-07-02 18:13:56 +08:00
|
|
|
|
EnsureDirectoryExists(dbPath);
|
|
|
|
|
|
optionsBuilder.UseSqlite($"Data Source={dbPath}");
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#if DEBUG
|
|
|
|
|
|
optionsBuilder.EnableSensitiveDataLogging();
|
|
|
|
|
|
optionsBuilder.EnableDetailedErrors();
|
|
|
|
|
|
#endif
|
|
|
|
|
|
|
2026-07-03 13:17:31 +08:00
|
|
|
|
var context = new WctMinerDbContext(optionsBuilder.Options);
|
|
|
|
|
|
|
2026-08-25 11:29:30 +08:00
|
|
|
|
// 迁移(Migrate)只在启动期由 Program.Main / CliTestHost.CreateAsync 触发,
|
|
|
|
|
|
// 不在每次 scope 解析时执行(避免每条命令都跑迁移)。
|
2026-07-03 13:17:31 +08:00
|
|
|
|
return context;
|
2026-07-02 18:13:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private string BuildPostgreSqlConnectionString()
|
|
|
|
|
|
{
|
|
|
|
|
|
var host = _configuration["Database:Host"] ?? "localhost";
|
|
|
|
|
|
var port = _configuration.GetValue("Database:Port", 5432);
|
|
|
|
|
|
var name = _configuration["Database:Name"] ?? "wctminer";
|
|
|
|
|
|
var user = _configuration["Database:User"] ?? "postgres";
|
|
|
|
|
|
var password = _configuration["Database:Password"] ?? "";
|
|
|
|
|
|
|
|
|
|
|
|
return $"Host={host};Port={port};Database={name};Username={user};Password={password}";
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private static void EnsureDirectoryExists(string dbPath)
|
|
|
|
|
|
{
|
|
|
|
|
|
var directory = Path.GetDirectoryName(dbPath);
|
|
|
|
|
|
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
|
|
|
|
|
{
|
|
|
|
|
|
Directory.CreateDirectory(directory);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|