55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package stardb
|
|
|
|
import (
|
|
"time"
|
|
)
|
|
|
|
// PoolConfig represents database connection pool configuration
|
|
type PoolConfig struct {
|
|
MaxOpenConns int
|
|
MaxIdleConns int
|
|
ConnMaxLifetime time.Duration
|
|
ConnMaxIdleTime time.Duration
|
|
}
|
|
|
|
// DefaultPoolConfig returns default pool configuration
|
|
func DefaultPoolConfig() *PoolConfig {
|
|
return &PoolConfig{
|
|
MaxOpenConns: 25,
|
|
MaxIdleConns: 5,
|
|
ConnMaxLifetime: time.Hour,
|
|
ConnMaxIdleTime: 10 * time.Minute,
|
|
}
|
|
}
|
|
|
|
// SetPoolConfig applies pool configuration to the database
|
|
func (s *StarDB) SetPoolConfig(config *PoolConfig) {
|
|
if config.MaxOpenConns > 0 {
|
|
s.db.SetMaxOpenConns(config.MaxOpenConns)
|
|
}
|
|
if config.MaxIdleConns > 0 {
|
|
s.db.SetMaxIdleConns(config.MaxIdleConns)
|
|
}
|
|
if config.ConnMaxLifetime > 0 {
|
|
s.db.SetConnMaxLifetime(config.ConnMaxLifetime)
|
|
}
|
|
if config.ConnMaxIdleTime > 0 {
|
|
s.db.SetConnMaxIdleTime(config.ConnMaxIdleTime)
|
|
}
|
|
}
|
|
|
|
// OpenWithPool opens a database connection with pool configuration
|
|
func OpenWithPool(driver, connStr string, config *PoolConfig) (*StarDB, error) {
|
|
db := NewStarDB()
|
|
if err := db.Open(driver, connStr); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if config == nil {
|
|
config = DefaultPoolConfig()
|
|
}
|
|
db.SetPoolConfig(config)
|
|
|
|
return db, nil
|
|
}
|