72 lines
2.4 KiB
C#
72 lines
2.4 KiB
C#
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.Extensions.Configuration;
|
||
|
||
namespace Gpulse.WCT.DataAnalyzer.Core.Infrastructure.LocalData;
|
||
|
||
/// <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:
|
||
var dbPath = _configuration["Database:LocalPath"]
|
||
?? _configuration["Database:Path"]
|
||
?? "./data/database/local.db";
|
||
EnsureDirectoryExists(dbPath);
|
||
optionsBuilder.UseSqlite($"Data Source={dbPath}");
|
||
break;
|
||
}
|
||
|
||
#if DEBUG
|
||
optionsBuilder.EnableSensitiveDataLogging();
|
||
optionsBuilder.EnableDetailedErrors();
|
||
#endif
|
||
|
||
var context = new WctMinerDbContext(optionsBuilder.Options);
|
||
|
||
// 迁移(Migrate)只在启动期由 Program.Main / CliTestHost.CreateAsync 触发,
|
||
// 不在每次 scope 解析时执行(避免每条命令都跑迁移)。
|
||
return context;
|
||
}
|
||
|
||
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);
|
||
}
|
||
}
|
||
} |