// Package db 提供基于PostgreSQL的数据存储功能 // 使用GORM作为ORM库来操作数据库 // 实现与PostgreSQL数据库的连接和基本操作 package db import ( "fmt" "log" "time" "gorm.io/driver/postgres" "gorm.io/gorm" ) // PostgresStorage 代表基于PostgreSQL的存储实现 // 使用GORM作为ORM库 type PostgresStorage struct { // db GORM数据库实例 db *gorm.DB // connectionString 数据库连接字符串 connectionString string // maxOpenConns 最大开放连接数 maxOpenConns int // maxIdleConns 最大空闲连接数 maxIdleConns int // connMaxLifetime 连接最大生命周期(秒) connMaxLifetime int } // NewPostgresStorage 创建并返回一个新的PostgreSQL存储实例 // 初始化数据库连接和相关配置 func NewPostgresStorage(connectionString string, maxOpenConns, maxIdleConns, connMaxLifetime int) *PostgresStorage { return &PostgresStorage{ connectionString: connectionString, maxOpenConns: maxOpenConns, maxIdleConns: maxIdleConns, connMaxLifetime: connMaxLifetime, } } // Connect 建立与PostgreSQL数据库的连接 // 使用GORM建立数据库连接 func (ps *PostgresStorage) Connect() error { var err error ps.db, err = gorm.Open(postgres.Open(ps.connectionString), &gorm.Config{}) if err != nil { return fmt.Errorf("failed to connect to database: %v", err) } // 测试连接 sqlDB, err := ps.db.DB() if err != nil { return fmt.Errorf("failed to get database instance: %v", err) } if err = sqlDB.Ping(); err != nil { return fmt.Errorf("failed to ping database: %v", err) } // 设置连接池参数 sqlDB.SetMaxOpenConns(ps.maxOpenConns) sqlDB.SetMaxIdleConns(ps.maxIdleConns) sqlDB.SetConnMaxLifetime(time.Duration(ps.connMaxLifetime) * time.Second) log.Println("Successfully connected to PostgreSQL database") return nil } // Disconnect 断开与PostgreSQL数据库的连接 // 安全地关闭所有数据库连接 func (ps *PostgresStorage) Disconnect() error { if ps.db != nil { sqlDB, err := ps.db.DB() if err != nil { return fmt.Errorf("failed to get database instance: %v", err) } if err := sqlDB.Close(); err != nil { return fmt.Errorf("failed to close database connection: %v", err) } log.Println("Successfully disconnected from PostgreSQL database") } return nil } // GetDB 获取GORM数据库实例 // 用于执行具体的数据库操作 func (ps *PostgresStorage) GetDB() *gorm.DB { return ps.db }