using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using TeamAAS.Database.Models; namespace TeamAAS.Database.Services { /// /// 产品数据库管理器:每个产品一个数据库(跟着产品走)。 /// 配置持久化到「产品目录\db.json」;缺省用 SQLite(产品目录\product.db)。 /// 宿主只需给产品名,路径经 拼取。 /// 后续可扩展为“一个产品分多个 db 文件”(届时把单实例缓存换成 产品→多库 的映射即可)。 /// public static class ProductDatabaseManager { private static readonly Dictionary _cache = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly object _sync = new object(); /// 产品目录(Products\产品名)。 public static string GetProductDir(string productName) => Path.Combine(PathHelper.ProductsDir, productName ?? ""); /// 产品数据库配置文件路径(产品目录\db.json)。 public static string GetConfigPath(string productName) => Path.Combine(GetProductDir(productName), "db.json"); /// 取(或创建)产品的数据库实例(缓存;不自动打开连接)。 public static ProductDatabase GetOrCreate(string productName) { if (string.IsNullOrWhiteSpace(productName)) return null; lock (_sync) { if (_cache.TryGetValue(productName, out var cached) && cached != null) return cached; var db = new ProductDatabase(LoadConfig(productName)); _cache[productName] = db; return db; } } /// 按最新 db.json 重建产品数据库实例(改配置后调用;会释放旧实例)。 public static ProductDatabase Recreate(string productName) { if (string.IsNullOrWhiteSpace(productName)) return null; lock (_sync) { if (_cache.TryGetValue(productName, out var old)) { try { old?.Dispose(); } catch { } _cache.Remove(productName); } var db = new ProductDatabase(LoadConfig(productName)); _cache[productName] = db; return db; } } /// 读产品数据库配置;无 db.json 时回退默认 SQLite(产品目录\product.db)。 public static DatabaseConfig LoadConfig(string productName) { var dir = GetProductDir(productName); try { var path = GetConfigPath(productName); if (File.Exists(path)) { var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); if (cfg != null) { cfg.Name = productName; // 产品名以目录为准 return cfg; } } } catch { } return new DatabaseConfig { Id = Guid.NewGuid(), Name = productName, ProviderType = "sqlite", Server = Path.Combine(dir, "product.db") }; } /// 保存产品数据库配置到 db.json。 public static bool SaveConfig(string productName, DatabaseConfig config) { if (string.IsNullOrWhiteSpace(productName) || config == null) return false; try { var dir = GetProductDir(productName); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); config.Name = productName; File.WriteAllText(GetConfigPath(productName), JsonConvert.SerializeObject(config, Formatting.Indented)); return true; } catch { return false; } } /// 关闭并移除某产品的缓存实例。 public static void Close(string productName) { if (string.IsNullOrWhiteSpace(productName)) return; lock (_sync) { if (_cache.TryGetValue(productName, out var db)) { try { db?.Dispose(); } catch { } _cache.Remove(productName); } } } /// 关闭并移除全部缓存实例(退出 / 切换产品前调用)。 public static void CloseAll() { lock (_sync) { foreach (var kv in _cache) { try { kv.Value?.Dispose(); } catch { } } _cache.Clear(); } } } }