This commit is contained in:
“xHuPo” 2025-05-27 17:44:24 +08:00
parent 44500afd3f
commit 5d370e1077
13 changed files with 529 additions and 519 deletions

View file

@ -25,11 +25,20 @@ func New(cfg *config.DatabaseConfig) (*DB, error) {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
// Configure connection pool with optimized settings
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(max(1, cfg.MaxOpenConns/2)) // 50% of max open connections
db.SetConnMaxLifetime(30 * time.Minute) // Longer lifetime to reduce connection churn
db.SetConnMaxIdleTime(5 * time.Minute) // Close idle connections after 5 minutes
// Configure connection pool based on database type
if cfg.Driver == "sqlite3" {
// SQLite is a file-based database - simpler connection settings
db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(0) // Connections don't need to be recycled
db.SetConnMaxIdleTime(0)
} else {
// For other databases (MySQL, PostgreSQL etc.)
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(max(1, cfg.MaxOpenConns/2)) // 50% of max open connections
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(5 * time.Minute)
}
// Verify connection with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@ -45,9 +54,16 @@ func New(cfg *config.DatabaseConfig) (*DB, error) {
// WithTx executes a function within a transaction with retry logic
func (db *DB) WithTx(ctx context.Context, fn func(*sqlx.Tx) error) error {
const maxRetries = 3
var maxRetries int
var lastErr error
// Adjust retry settings based on database type
if db.DriverName() == "sqlite3" {
maxRetries = 5 // SQLite needs more retries due to busy timeouts
} else {
maxRetries = 3
}
// Default transaction options
opts := &sql.TxOptions{
Isolation: sql.LevelReadCommitted,