Files

56 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package database 提供统一的数据存储接口
// 定义存储接口规范,支持多种存储后端实现
// 当前支持PostgreSQL实现
package database
import (
"fmt"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/config"
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
"gorm.io/gorm"
)
// Storage 代表统一的存储接口
// 所有存储实现都需要实现此接口定义的方法
type Storage interface {
// Connect 建立与存储后端的连接
Connect() error
// Disconnect 断开与存储后端的连接
Disconnect() error
// GetDB 获取数据库实例
GetDB() *gorm.DB
// Migrate 执行数据库迁移
// 参数为需要迁移的 GORM 模型
Migrate(models ...interface{}) error
}
// NewStorage 创建并返回一个存储实例
// 根据配置返回相应的存储实现
func NewStorage(cfg config.DatabaseConfig, logger *logs.Logger) Storage {
// 构建数据库连接字符串
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 注入
// 当前默认返回PostgreSQL存储实现并将 logger 注入
return NewPostgresStorage(
connectionString,
cfg.IsTimescaleDB, // <--- 添加 IsTimescaleDB
cfg.MaxOpenConns,
cfg.MaxIdleConns,
cfg.ConnMaxLifetime,
logger,
)
}