Files
pig-farm-controller/internal/infra/database/storage.go

58 lines
1.5 KiB
Go
Raw Normal View History

2025-09-11 23:10:02 +08:00
// Package database 提供统一的数据存储接口
2025-09-11 20:50:51 +08:00
// 定义存储接口规范,支持多种存储后端实现
// 当前支持PostgreSQL实现
2025-09-11 23:10:02 +08:00
package database
2025-09-11 20:50:51 +08:00
import (
2025-11-05 22:22:46 +08:00
"context"
2025-09-11 20:50:51 +08:00
"fmt"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/config"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
2025-11-05 22:22:46 +08:00
2025-09-11 20:50:51 +08:00
"gorm.io/gorm"
)
// Storage 代表统一的存储接口
// 所有存储实现都需要实现此接口定义的方法
type Storage interface {
// Connect 建立与存储后端的连接
2025-11-05 22:22:46 +08:00
Connect(ctx context.Context) error
2025-09-11 20:50:51 +08:00
// Disconnect 断开与存储后端的连接
2025-11-05 22:22:46 +08:00
Disconnect(ctx context.Context) error
2025-09-11 20:50:51 +08:00
// GetDB 获取数据库实例
2025-11-05 22:22:46 +08:00
GetDB(ctx context.Context) *gorm.DB
2025-09-11 20:50:51 +08:00
// Migrate 执行数据库迁移
// 参数为需要迁移的 GORM 模型
2025-11-05 22:22:46 +08:00
Migrate(ctx context.Context, models ...interface{}) error
2025-09-11 20:50:51 +08:00
}
// NewStorage 创建并返回一个存储实例
// 根据配置返回相应的存储实现
2025-11-05 22:22:46 +08:00
func NewStorage(ctx context.Context, cfg config.DatabaseConfig) Storage {
2025-09-11 20:50:51 +08:00
// 构建数据库连接字符串
connectionString := fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s port=%d sslmode=%s",
cfg.Username,
cfg.Password,
cfg.DBName,
cfg.Host,
cfg.Port,
cfg.SSLMode,
)
// 当前默认返回PostgreSQL存储实现并将 logger 注入
2025-09-11 20:50:51 +08:00
// 当前默认返回PostgreSQL存储实现并将 logger 注入
return NewPostgresStorage(
2025-11-05 22:22:46 +08:00
logs.AddCompName(context.Background(), "PostgresStorage"),
2025-09-11 20:50:51 +08:00
connectionString,
2025-11-05 22:22:46 +08:00
cfg.IsTimescaleDB,
2025-09-11 20:50:51 +08:00
cfg.MaxOpenConns,
cfg.MaxIdleConns,
cfg.ConnMaxLifetime,
)
}