fix(go): set max open conns;

This commit is contained in:
Vishal Dalwadi 2025-08-14 22:27:33 +05:30
parent a115ad0547
commit 30c44a48df

View file

@ -1,7 +1,6 @@
package db
import (
"database/sql"
"os"
"path/filepath"
"time"
@ -51,37 +50,20 @@ func (s *sqliteConnector) connect() (*gorm.DB, error) {
}
}
// By default, SQLite transactions may keep writes invisible to other readers
// until the transaction commits and the connection closes. This is especially
// noticeable when using multiple connections from a pool.
//
// We configure the DSN to improve visibility and concurrency:
//
// 1. _journal_mode=wal: Use Write-Ahead Logging so committed writes are visible
// to other connections immediately, and readers don't block writers. The default
// journal mode is DELETE, which is not suitable for concurrent access.
//
// 2. _txlock=immediate: Acquire a RESERVED write lock as soon as the transaction
// begins, avoiding mid-transaction "database is locked" errors. The default is
// deferred, which may cause a transaction to rollback if another transaction has
// already acquired a RESERVED lock.
//
// 3. _busy_timeout=5000: Wait up to 5 seconds for a locked database before failing.
//
// See discussion: https://github.com/mattn/go-sqlite3/issues/1022#issuecomment-1067353980
dsn := "file:" + dbFilePath + "?_journal_mode=wal&_txlock=immediate&_busy_timeout=5000"
sqliteDB, err := sql.Open("sqlite3", dsn)
db, err := gorm.Open(sqlite.Open(dbFilePath), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
return nil, err
}
sqliteDB.SetMaxOpenConns(1)
sqliteDB.SetConnMaxLifetime(time.Hour)
sqliteDB.SetMaxIdleConns(1)
sqlDB, err := db.DB()
if err != nil {
return nil, err
}
return gorm.Open(sqlite.Dialector{Conn: sqliteDB}, &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
sqlDB.SetMaxOpenConns(5)
sqlDB.SetConnMaxLifetime(time.Hour)
return db, nil
}