package dbs import ( "fmt" "git.x2erp.com/qdy/go-db/factory/database" "git.x2erp.com/qdy/go-svc-mcp/internal/mcp" ) // 数据库配置键名常量(yaml配置键名) const ( // BusinessDBKey 业务数据库键名 BusinessDBKey = "business" // WarehouseDBKey 仓库数据库键名 WarehouseDBKey = "warehouse" ) // GetDBFactory 根据database_key获取数据库工厂 // 如果database_key为空,返回主数据库工厂(deps.DBFactory) // 如果database_key不为空,通过DBSFactory创建对应的数据库工厂 // database_key 必须是 BusinessDBKey 或 WarehouseDBKey 或空字符串 func GetDBFactory(databaseKey string, deps *mcp.ToolDependencies) (*database.DBFactory, error) { if databaseKey == "" { if deps.DBFactory == nil { return nil, fmt.Errorf("主数据库工厂未初始化") } return deps.DBFactory, nil } // 验证database_key是否有效 if !IsValidDatabaseKey(databaseKey) { return nil, fmt.Errorf("无效的数据库键名 '%s',只允许 '%s' 或 '%s'", databaseKey, BusinessDBKey, WarehouseDBKey) } if deps.DBSFactory == nil { return nil, fmt.Errorf("多数据库工厂未初始化,无法使用 database_key 参数") } // 通过DBSFactory创建对应的数据库工厂 factory, err := deps.DBSFactory.CreateDBFactory(databaseKey) if err != nil { return nil, fmt.Errorf("创建数据库工厂 '%s' 失败: %v", databaseKey, err) } return factory, nil } // IsValidDatabaseKey 验证数据库配置键名是否有效 // 有效键名必须是 BusinessDBKey 或 WarehouseDBKey func IsValidDatabaseKey(key string) bool { return key == BusinessDBKey || key == WarehouseDBKey }